text
stringlengths
8
4.13M
//! Tests auto-converted from "sass-spec/spec/libsass-closed-issues/issue_1210" #[allow(unused)] use super::rsass; // From "sass-spec/spec/libsass-closed-issues/issue_1210/ampersand.hrx" #[test] fn ampersand() { assert_eq!( rsass( "foo {\ \n @at-root {\ \n & {\ \n color: blue;\ \n }\ \n\ \n &--modifier {\ \n color: red;\ \n }\ \n }\ \n}\ \n\ \nfoo {\ \n color: blue;\ \n\ \n @at-root {\ \n & bar {\ \n color: red;\ \n }\ \n }\ \n}\ \n\ \nfoo {\ \n color: blue;\ \n\ \n @at-root {\ \n bar & {\ \n color: red;\ \n }\ \n }\ \n}\ \n\ \nfoo {\ \n color: blue;\ \n\ \n @at-root {\ \n bar {\ \n & baz {\ \n color: red;\ \n }\ \n }\ \n }\ \n}\ \n\ \nfoo {\ \n @at-root bar & {\ \n color: red;\ \n\ \n & baz {\ \n color: blue;\ \n }\ \n }\ \n}\ \n" ) .unwrap(), "foo {\ \n color: blue;\ \n}\ \nfoo--modifier {\ \n color: red;\ \n}\ \nfoo {\ \n color: blue;\ \n}\ \nfoo bar {\ \n color: red;\ \n}\ \nfoo {\ \n color: blue;\ \n}\ \nbar foo {\ \n color: red;\ \n}\ \nfoo {\ \n color: blue;\ \n}\ \nbar baz {\ \n color: red;\ \n}\ \nbar foo {\ \n color: red;\ \n}\ \nbar foo baz {\ \n color: blue;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1210/basic.hrx" #[test] fn basic() { assert_eq!( rsass( "foo {\ \n color: blue;\ \n\ \n @at-root {\ \n bar {\ \n color: red;\ \n }\ \n }\ \n}\ \n\ \nfoo {\ \n color: blue;\ \n\ \n @at-root bar {\ \n color: red;\ \n }\ \n}\ \n\ \nfoo {\ \n color: blue;\ \n\ \n @at-root bar {\ \n baz {\ \n color: red;\ \n }\ \n }\ \n}\ \n\ \nfoo {\ \n color: blue;\ \n\ \n @at-root {\ \n bar {\ \n baz {\ \n color: red;\ \n }\ \n }\ \n }\ \n}\ \n\ \n" ) .unwrap(), "foo {\ \n color: blue;\ \n}\ \nbar {\ \n color: red;\ \n}\ \nfoo {\ \n color: blue;\ \n}\ \nbar {\ \n color: red;\ \n}\ \nfoo {\ \n color: blue;\ \n}\ \nbar baz {\ \n color: red;\ \n}\ \nfoo {\ \n color: blue;\ \n}\ \nbar baz {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1210/extend.hrx" #[test] #[ignore] // wrong result fn extend() { assert_eq!( rsass( "foo {\ \n @at-root {\ \n %placeholder {\ \n color: red;\ \n }\ \n }\ \n\ \n baz {\ \n @at-root {\ \n %other-placeholder {\ \n color: blue;\ \n }\ \n }\ \n }\ \n\ \n %ampersand-placeholder & {\ \n color: green;\ \n }\ \n\ \n @at-root {\ \n qux {\ \n @extend %ampersand-placeholder;\ \n }\ \n }\ \n}\ \n\ \nbar {\ \n @extend %placeholder;\ \n}\ \n\ \nbaz {\ \n @extend %other-placeholder;\ \n}\ \n\ \nbam {\ \n @extend %ampersand-placeholder;\ \n}\ \n" ) .unwrap(), "bar {\ \n color: red;\ \n}\ \nbaz {\ \n color: blue;\ \n}\ \nbam foo, qux foo {\ \n color: green;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1210/keyframes.hrx" #[test] fn keyframes() { assert_eq!( rsass( "foo {\ \n color: red;\ \n\ \n @at-root {\ \n @keyframes animation {\ \n to { color: red; }\ \n }\ \n }\ \n\ \n bar {\ \n color: blue;\ \n\ \n @at-root {\ \n @keyframes other-animation {\ \n to { color: blue; }\ \n }\ \n }\ \n }\ \n}\ \n" ) .unwrap(), "foo {\ \n color: red;\ \n}\ \n@keyframes animation {\ \n to {\ \n color: red;\ \n }\ \n}\ \nfoo bar {\ \n color: blue;\ \n}\ \n@keyframes other-animation {\ \n to {\ \n color: blue;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1210/media.hrx" #[test] fn media() { assert_eq!( rsass( "foo {\ \n @at-root {\ \n @media print {\ \n bar {\ \n color: red;\ \n }\ \n }\ \n\ \n baz {\ \n @media speech {\ \n color: blue;\ \n }\ \n }\ \n }\ \n}\ \n" ) .unwrap(), "@media print {\ \n bar {\ \n color: red;\ \n }\ \n}\ \n@media speech {\ \n baz {\ \n color: blue;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1210/nested.hrx" #[test] fn nested() { assert_eq!( rsass( "foo {\ \n color: blue;\ \n\ \n baz {\ \n color: purple;\ \n\ \n @at-root {\ \n bar {\ \n color: red;\ \n }\ \n }\ \n }\ \n}\ \n\ \nfoo {\ \n color: blue;\ \n\ \n baz {\ \n color: purple;\ \n\ \n @at-root bar {\ \n color: red;\ \n }\ \n }\ \n}\ \n" ) .unwrap(), "foo {\ \n color: blue;\ \n}\ \nfoo baz {\ \n color: purple;\ \n}\ \nbar {\ \n color: red;\ \n}\ \nfoo {\ \n color: blue;\ \n}\ \nfoo baz {\ \n color: purple;\ \n}\ \nbar {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1210/with_without.hrx" #[test] #[ignore] // unexepected error fn with_without() { assert_eq!( rsass( "// Unquoted\ \n\ \n@media (min-width: 1337px) {\ \n .foo {\ \n content: baz;\ \n }\ \n\ \n @at-root (without: media) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n .foo {\ \n content: baz;\ \n }\ \n\ \n @at-root (without: all) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n}\ \n\ \n@supports (color: red) {\ \n .foo {\ \n content: baz;\ \n }\ \n\ \n @at-root (without: supports) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n}\ \n\ \n@supports (color: red) {\ \n .foo {\ \n content: baz;\ \n }\ \n\ \n @at-root (without: all) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (without: all) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (without: media supports) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (without: media) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (without: supports) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (with: all) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (with: media supports) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (with: media) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (with: supports) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n// Quoted\ \n\ \n@media (min-width: 1337px) {\ \n .foo {\ \n content: baz;\ \n }\ \n\ \n @at-root (without: \"media\") {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n .foo {\ \n content: baz;\ \n }\ \n\ \n @at-root (without: \"all\") {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n}\ \n\ \n@supports (color: red) {\ \n .foo {\ \n content: baz;\ \n }\ \n\ \n @at-root (without: \"supports\") {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n}\ \n\ \n@supports (color: red) {\ \n .foo {\ \n content: baz;\ \n }\ \n\ \n @at-root (without: \"all\") {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (without: \"all\") {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (without: \"media\" \"supports\") {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (without: \"media\" supports) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (without: media \"supports\") {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (without: \"media\") {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (without: \"supports\") {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (with: \"all\") {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (with: \"media\" \"supports\") {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (with: \"media\" supports) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (with: media \"supports\") {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (with: \"media\") {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n @at-root (with: \"supports\") {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n }\ \n}\ \n" ) .unwrap(), "@media (min-width: 1337px) {\ \n .foo {\ \n content: baz;\ \n }\ \n}\ \n.foo {\ \n content: bar;\ \n}\ \n@media (min-width: 1337px) {\ \n .foo {\ \n content: baz;\ \n }\ \n}\ \n.foo {\ \n content: bar;\ \n}\ \n@supports (color: red) {\ \n .foo {\ \n content: baz;\ \n }\ \n}\ \n.foo {\ \n content: bar;\ \n}\ \n@supports (color: red) {\ \n .foo {\ \n content: baz;\ \n }\ \n}\ \n.foo {\ \n content: bar;\ \n}\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n}\ \n.foo {\ \n content: bar;\ \n}\ \n.foo {\ \n content: bar;\ \n}\ \n@supports (color: red) {\ \n .foo {\ \n content: bar;\ \n }\ \n}\ \n@media (min-width: 1337px) {\ \n .foo {\ \n content: bar;\ \n }\ \n}\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n}\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n}\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n}\ \n@media (min-width: 1337px) {\ \n .foo {\ \n content: bar;\ \n }\ \n}\ \n@supports (color: red) {\ \n .foo {\ \n content: bar;\ \n }\ \n}\ \n@media (min-width: 1337px) {\ \n .foo {\ \n content: baz;\ \n }\ \n}\ \n.foo {\ \n content: bar;\ \n}\ \n@media (min-width: 1337px) {\ \n .foo {\ \n content: baz;\ \n }\ \n}\ \n.foo {\ \n content: bar;\ \n}\ \n@supports (color: red) {\ \n .foo {\ \n content: baz;\ \n }\ \n}\ \n.foo {\ \n content: bar;\ \n}\ \n@supports (color: red) {\ \n .foo {\ \n content: baz;\ \n }\ \n}\ \n.foo {\ \n content: bar;\ \n}\ \n.foo {\ \n content: bar;\ \n}\ \n.foo {\ \n content: bar;\ \n}\ \n.foo {\ \n content: bar;\ \n}\ \n.foo {\ \n content: bar;\ \n}\ \n@supports (color: red) {\ \n .foo {\ \n content: bar;\ \n }\ \n}\ \n@media (min-width: 1337px) {\ \n .foo {\ \n content: bar;\ \n }\ \n}\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n}\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n}\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n}\ \n@media (min-width: 1337px) {\ \n @supports (color: red) {\ \n .foo {\ \n content: bar;\ \n }\ \n }\ \n}\ \n@media (min-width: 1337px) {\ \n .foo {\ \n content: bar;\ \n }\ \n}\ \n@supports (color: red) {\ \n .foo {\ \n content: bar;\ \n }\ \n}\ \n" ); }
use std::fs::File; use std::io::{Read, Write}; use std::path::Path; use compiler; use parser; use rustc_serialize::json::Json; use rustc_serialize::json::Json::{Boolean, Null, I64, U64, F64, Array, Object}; use rustc_serialize::json::Json::String as JString; use build::{HashBuilder, VecBuilder}; use template::Template; use RustacheResult; use RustacheError::{JsonError, FileError}; /// Defines a `renderable` trait, so that all of our data is renderable pub trait Render { /// `render` function on a `renderable` returns a `reader` fn render<W: Write>(&self, template: &str, writer: &mut W) -> RustacheResult<()>; } /// Implement the `renderable` trait on the HashBuilder type impl<'a> Render for HashBuilder<'a> { fn render<W: Write>(&self, template: &str, writer: &mut W) -> RustacheResult<()> { // Create our nodes let tokens = compiler::create_tokens(template); let nodes = parser::parse_nodes(&tokens); // Render and write out Template::new().render_data(writer, self, &nodes) } } /// Implement the `renderable` trait on the JSON type impl Render for Json { fn render<W: Write>(&self, template: &str, writer: &mut W) -> RustacheResult<()> { parse_json(self).render(template, writer) } } impl Render for Path { fn render<W: Write>(&self, template: &str, writer: &mut W) -> RustacheResult<()> { return match read_file(self) { Ok(text) => { let json = match Json::from_str(&text) { Ok(json) => json, Err(err) => return Err(JsonError(format!("Invalid JSON. {}", err))), }; parse_json(&json).render(template, writer) } Err(err) => Err(FileError(err)), }; } } impl Render for ToString { fn render<W: Write>(&self, template: &str, writer: &mut W) -> RustacheResult<()> { let json = match Json::from_str(&self.to_string()) { Ok(json) => json, Err(err) => return Err(JsonError(format!("Invalid JSON. {}", err))), }; parse_json(&json).render(template, writer) } } // parses a Rust JSON hash and matches all possible types that may be passed in // returning a HashBuilder fn parse_json(json: &Json) -> HashBuilder { let mut data = HashBuilder::new(); for (k, v) in json.as_object().unwrap().iter() { match v { &I64(num) => { data = data.insert(&k[..], num.to_string()); } &U64(num) => { data = data.insert(&k[..], num.to_string()); } &F64(num) => { data = data.insert(&k[..], num.to_string()); } &Boolean(val) => { data = data.insert(&k[..], val); } &Array(ref list) => { let mut builder = VecBuilder::new(); for item in list.iter() { builder = match *item { Object(_) => builder.push(parse_json(item)), Array(_) => builder.push(parse_json_vector(item)), JString(_) => builder.push(item.as_string().unwrap()), Boolean(_) => builder.push(item.as_boolean().unwrap()), _ => builder, } } data = data.insert(&k[..], builder); } &Object(_) => { data = data.insert(&k[..], parse_json(v)); } &Null => {} &JString(ref text) => { data = data.insert(&k[..], &text[..]); } } } data } // parses a Rust JSON vector and matches all possible types that may be passed in // returning a VecBuider fn parse_json_vector(json: &Json) -> VecBuilder { let mut data = VecBuilder::new(); for v in json.as_array().unwrap().iter() { match v { &I64(num) => { data = data.push(num.to_string()); } &U64(num) => { data = data.push(num.to_string()); } &F64(num) => { data = data.push(num.to_string()); } &Boolean(val) => { data = data.push(val); } &Array(ref list) => { let mut builder = VecBuilder::new(); for item in list.iter() { builder = match *item { Object(_) => builder.push(parse_json(item)), Array(_) => builder.push(parse_json_vector(item)), JString(_) => builder.push(item.as_string().unwrap()), Boolean(_) => builder.push(item.as_boolean().unwrap()), _ => builder, } } data = data.push(builder); } &Object(_) => { data = data.push(parse_json(v)); } &Null => {} &JString(ref text) => { data = data.push(&text[..]); } } } data } // Hide from documentation #[doc(hidden)] pub fn read_file(path: &Path) -> Result<String, String> { let display = path.display(); let rv: Result<String, String>; //Err(format!("read file failed: {}", display)); // Open the file path let mut file = match File::open(path) { Err(why) => { rv = Err(format!("{}: \"{}\"", why, display)); return rv; } Ok(file) => file, }; // Read the file contents into a heap allocated string let mut text = String::new(); match file.read_to_string(&mut text) { Err(why) => { return { rv = Err(format!("{}", why)); return rv; } } Ok(_) => { rv = Ok(text); } }; rv }
#[test] fn percent_absolute_position() { let layout = stretch::node::Node::new( stretch::style::Style { flex_direction: stretch::style::FlexDirection::Column, size: stretch::geometry::Size { width: stretch::style::Dimension::Points(60f32), height: stretch::style::Dimension::Points(50f32), ..Default::default() }, ..Default::default() }, vec![&stretch::node::Node::new( stretch::style::Style { position_type: stretch::style::PositionType::Absolute, size: stretch::geometry::Size { width: stretch::style::Dimension::Percent(1f32), height: stretch::style::Dimension::Points(50f32), ..Default::default() }, position: stretch::geometry::Rect { start: stretch::style::Dimension::Percent(0.5f32), ..Default::default() }, ..Default::default() }, vec![ &stretch::node::Node::new( stretch::style::Style { size: stretch::geometry::Size { width: stretch::style::Dimension::Percent(1f32), ..Default::default() }, ..Default::default() }, vec![], ), &stretch::node::Node::new( stretch::style::Style { size: stretch::geometry::Size { width: stretch::style::Dimension::Percent(1f32), ..Default::default() }, ..Default::default() }, vec![], ), ], )], ) .compute_layout(stretch::geometry::Size::undefined()) .unwrap(); assert_eq!(layout.size.width, 60f32); assert_eq!(layout.size.height, 50f32); assert_eq!(layout.location.x, 0f32); assert_eq!(layout.location.y, 0f32); assert_eq!(layout.children[0usize].size.width, 60f32); assert_eq!(layout.children[0usize].size.height, 50f32); assert_eq!(layout.children[0usize].location.x, 30f32); assert_eq!(layout.children[0usize].location.y, 0f32); assert_eq!(layout.children[0usize].children[0usize].size.width, 30f32); assert_eq!(layout.children[0usize].children[0usize].size.height, 50f32); assert_eq!(layout.children[0usize].children[0usize].location.x, 0f32); assert_eq!(layout.children[0usize].children[0usize].location.y, 0f32); assert_eq!(layout.children[0usize].children[1usize].size.width, 30f32); assert_eq!(layout.children[0usize].children[1usize].size.height, 50f32); assert_eq!(layout.children[0usize].children[1usize].location.x, 30f32); assert_eq!(layout.children[0usize].children[1usize].location.y, 0f32); }
/* #[derive(Debug)] struct Weeks { day1 : String, day2 : String, } #[derive(Debug)] enum Days { Sunday(String), Monday(u8,u8), Tuesday, } #[derive(Debug)] enum Option { Some(u8), None } */ //generic enum Option<T> { Some(T), None } fn main() { /* let value1 = Some(5); let name = Some(String::from("Rizwan")); let data1 = Option::Some(10); println!("{:?}",data1); println!("{:?}",value1); println!("{:?}",name); */ let nodata:Option<i32> = None; let coa = String::from("Qamar Javeed Bajwa"); println!("Name length of {:?} is {}",coa,coa.len()); let age =[22,33,44,55]; let temp =100; let data = age.get(temp); println!("{:?}",data); /* let week1 = Weeks{ let day1 : String::from("Friday"), let day2 : String::from("Saturday"), }; let day1 = Days::Sunday(String::from("Holiday")); let day1 = Days::Monday(22,33); println!("{:#?}",week1); println!("{:#?}",day1); println!("{:#?}",day2); */ }
use std::str::FromStr; use problem::{Problem, solve}; struct Answers(u32); impl FromStr for Answers { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Answers(s.chars().fold(0, |acc, c| acc | (1 << (c as usize - 'a' as usize))))) } } struct Day6; impl Problem for Day6 { type Input = Vec<Answers>; type Part1Output = u32; type Part2Output = u32; type Error = (); fn part_1(input: &Self::Input) -> Result<Self::Part1Output, Self::Error> { let mut total = 0; let mut acc = 0u32; for i in input { if i.0 == 0 { total += acc.count_ones(); acc = 0; } else { acc |= i.0; } } total += acc.count_ones(); Ok(total) } fn part_2(input: &Self::Input) -> Result<Self::Part2Output, Self::Error> { let mut total = 0; let mut acc = 0xffffffffu32; for i in input { if i.0 == 0 { total += acc.count_ones(); acc = 0xffffffffu32; } else { acc &= i.0; } } total += acc.count_ones(); Ok(total) } } fn main() { solve::<Day6>("input").unwrap(); }
use std::ops::Add; fn main() { println!( "First solution: {}", part1(include_str!("../../input/18.txt")) ); println!( "Second solution: {}", part2(include_str!("../../input/18.txt")) ); } fn part1(s: &str) -> u32 { s.lines() .map(Number::from) .reduce(|a, b| a + b) .unwrap() .magnitude() } fn part2(s: &str) -> u32 { let numbers: Vec<Number> = s.lines().map(Number::from).collect(); let mut max = 0; for a in &numbers { for b in &numbers { let sum = (a.clone() + b.clone()).magnitude(); max = max.max(sum); } } max } #[derive(Debug, Clone, Eq)] struct Number(Vec<Token>); #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Token { Open, Close, Num(u32), } impl Token { /// assume that this token is a number and return the value or panic. fn num(&self) -> u32 { match self { Token::Num(n) => *n, t => panic!("expected Token::Num, but got {:?}", t), } } fn num_mut(&mut self) -> &mut u32 { match self { Token::Num(n) => n, t => panic!("expected Token::Num, but got {:?}", t), } } } impl Add for Number { type Output = Number; fn add(self, rhs: Self) -> Self::Output { let mut v = vec![Token::Open]; v.extend(self.0); v.extend(rhs.0); v.push(Token::Close); Self(v).reduce() } } impl From<&str> for Number { fn from(s: &str) -> Self { Self( s.chars() .filter_map(|c| match c { '[' => Some(Token::Open), ']' => Some(Token::Close), ',' => None, // commas do not matter after parsing d => match d.to_digit(10) { Some(d) => Some(Token::Num(d)), None => panic!("unknown char '{}'", d), }, }) .collect(), ) } } impl PartialEq for Number { fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } impl Number { fn magnitude(&self) -> u32 { let mut stack: Vec<u32> = Vec::new(); for tok in &self.0 { match tok { Token::Open => continue, Token::Close => { let b = stack.pop().unwrap(); let a = stack.pop().unwrap(); stack.push(3 * a + 2 * b); } Token::Num(n) => stack.push(*n), } } stack.pop().unwrap() } fn reduce(&self) -> Self { let mut result = self.clone(); loop { let (num, exploded) = result.explode(); if exploded { result = num; } else { let (num, split) = num.split(); if split { result = num; } else { return result; } } } } /// Perform the leftmost explosion, if any. Returns true if any explosions happened. fn explode(&self) -> (Self, bool) { let mut explode_happened = false; let mut depth = 0; // Keep track of the last num to move a value backwards. let mut last_num_idx: Option<usize> = None; // Carry a value to the next num let mut carrying: Option<u32> = None; let mut result: Vec<Token> = Vec::new(); let mut tokens = self.0.iter().copied(); while let Some(tok) = tokens.next() { match tok { Token::Open if depth >= 4 && !explode_happened => { // Explode! explode_happened = true; let left = tokens.next().unwrap().num(); let right = tokens.next().unwrap().num(); let _close = tokens.next(); if let Some(i) = last_num_idx { *result[i].num_mut() += left; } carrying = Some(right); result.push(Token::Num(0)); } Token::Open => { depth += 1; result.push(Token::Open); } Token::Close => { depth -= 1; result.push(Token::Close); } Token::Num(n) => { last_num_idx = Some(result.len()); let n = n + carrying.take().unwrap_or(0); result.push(Token::Num(n)); } } } (Self(result), explode_happened) } /// Perform the leftmost split, if any. Returns true if any splits happened. fn split(&self) -> (Self, bool) { let mut split_happened = false; let mut result = Vec::new(); for tok in self.0.iter().copied() { match tok { Token::Num(n) if n > 9 && !split_happened => { // Split! split_happened = true; let (a, b) = split(n); result.extend([Token::Open, Token::Num(a), Token::Num(b), Token::Close]); } tok => result.push(tok), } } (Self(result), split_happened) } } fn split(n: u32) -> (u32, u32) { if n % 2 == 0 { (n / 2, n / 2) } else { (n / 2, n / 2 + 1) } } #[cfg(test)] mod test { use crate::{part1, part2, Number}; #[test] fn magnitude() { assert_eq!(Number::from("[[1,2],[[3,4],5]]").magnitude(), 143); assert_eq!( Number::from("[[[[0,7],4],[[7,8],[6,0]]],[8,1]]").magnitude(), 1384 ); assert_eq!( Number::from("[[[[1,1],[2,2]],[3,3]],[4,4]]").magnitude(), 445 ); assert_eq!( Number::from("[[[[3,0],[5,3]],[4,4]],[5,5]]").magnitude(), 791 ); assert_eq!( Number::from("[[[[5,0],[7,4]],[5,5]],[6,6]]").magnitude(), 1137 ); assert_eq!( Number::from("[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]]").magnitude(), 3488 ); } #[test] fn explode() { let expected = Number::from("[[[[0,9],2],3],4]"); let actual = Number::from("[[[[[9,8],1],2],3],4]").reduce(); assert_eq!(expected, actual) } #[test] fn example_part1() { assert_eq!(part1(include_str!("../../input/18-test.txt")), 4140); } #[test] fn example_part2() { assert_eq!(part2(include_str!("../../input/18-test.txt")), 3993); } }
#![recursion_limit = "256"] extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2::Span; use quote::{quote, ToTokens}; use syn::punctuated::Punctuated; use syn::token::Comma; #[proc_macro_attribute] pub fn rusterlium(args: TokenStream, input: TokenStream) -> TokenStream { let args = syn::parse_macro_input!(args as syn::AttributeArgs); let ast: syn::Item = syn::parse_macro_input!(input as syn::Item); let expanded: proc_macro2::TokenStream = impl_wrapper(&args, &ast); TokenStream::from(expanded) } fn impl_wrapper(args: &syn::AttributeArgs, item: &syn::Item) -> proc_macro2::TokenStream { let fun = if let syn::Item::Fn(fun) = item { fun } else { panic!("`#[rusterlium]` attribute only supported on functions"); }; let name = &fun.ident; let decl = &fun.decl; let inputs = &decl.inputs; let erl_func_name = extract_attr_value(&args, "name") .map(|ref n| syn::Ident::new(n, Span::call_site())) .unwrap_or_else(|| fun.ident.clone()); //let flags = extract_attr_value(&args, "schedule").unwrap_or_else(|| "Normal".to_string()); if decl.variadic.is_some() { panic!("variadic functions are not supported") } // declare the function let function = item.clone().into_token_stream(); let decoded_terms = extract_inputs(inputs); let argument_names = create_function_params(inputs); let arity = inputs.len(); // Return a const ErlNifFunc. // // The name is based on the user function name followed by `_ErlNifFunc`. // For example: Given the user function `add`, the const will be named `add_ErlNifFunc`. let erl_nif_func_const = syn::Ident::new(&format!("{}_ErlNifFunc", name), Span::call_site()); quote! { #function const #erl_nif_func_const: erlang_nif_sys::ErlNifFunc = erlang_nif_sys::ErlNifFunc { name: concat!(stringify!(#erl_func_name), "\x00") as *const str as *const u8, arity: #arity as u32, function: { unsafe extern "C" fn nif(nif_env: *mut ErlNifEnv, argc: c_int, argv: *const ERL_NIF_TERM) -> ERL_NIF_TERM { let lifetime = (); let env = rustler::Env::new(&lifetime, nif_env); let terms = std::slice::from_raw_parts(argv, argc as usize) .iter() .map(|term| rustler::Term::new(env, *term)) .collect::<Vec<rustler::Term>>(); fn wrapper<'a>(env: rustler::Env<'a>, args: &[rustler::Term<'a>]) -> rustler::Term<'a> { let panic_result = std::panic::catch_unwind(|| { #decoded_terms let result = #name(#argument_names); result.encode(env) }); match panic_result { Ok(result) => result.encode(env), Err(err) => std::panic::resume_unwind(err) } } wrapper(env, &terms).as_c_arg() } nif }, flags: 0 as u32, }; } } fn extract_attr_value<'a>(input: &'a syn::AttributeArgs, attr: &str) -> Option<String> { use syn::{Lit, Meta, MetaNameValue, NestedMeta}; for item in input.iter() { if let NestedMeta::Meta(Meta::NameValue(meta_name_value)) = item { let MetaNameValue { ident, lit, .. } = meta_name_value; if ident == attr { if let Lit::Str(lit) = lit { return Some(lit.value()); } } } } None } fn extract_inputs<'a>(inputs: &'a Punctuated<syn::FnArg, Comma>) -> proc_macro2::TokenStream { let mut tokens = proc_macro2::TokenStream::new(); for (i, item) in inputs.iter().enumerate() { let (name, typ) = if let syn::FnArg::Captured(ref captured) = *item { (&captured.pat, &captured.ty) } else { panic!("unsupported input given: {:?}", stringify!(&item)); }; let error = format!( "unsupported function argument type `{}` for `{}`", quote!(#typ), quote!(#name) ); let arg = quote! { let #name: #typ = args[#i] .decode() .map_err(|_| #error) .expect(#error); }; tokens.extend(arg); } tokens } fn create_function_params<'a>( inputs: &'a Punctuated<syn::FnArg, Comma>, ) -> proc_macro2::TokenStream { let mut tokens = proc_macro2::TokenStream::new(); for item in inputs.iter() { let name = if let syn::FnArg::Captured(syn::ArgCaptured { pat: syn::Pat::Ident(syn::PatIdent { ref ident, .. }), .. }) = *item { ident } else { panic!("unsupported input given: {:?}", stringify!(&item)); }; tokens.extend(quote!( #name, )); } tokens }
mod camera; mod engine; mod object; mod printer; mod window; mod raytrace_pipeline; use engine::*; fn main() { raytrace_pipeline::raytracing() }
use bstr::ByteSlice; use anyhow::Result; use super::{ AnnotationCollection, AnnotationColumn, AnnotationRecord, ColumnKey, }; #[derive(Debug, Clone, Default)] pub struct BedRecords { file_name: String, pub records: Vec<BedRecord>, column_keys: Vec<BedColumn>, // TODO add header support // pub column_header: Vec<Vec<u8>>, headers: Vec<Vec<u8>>, } #[derive(Debug, Clone)] pub struct BedRecord { pub chr: Vec<u8>, pub start: usize, pub end: usize, // TODO add header support pub rest: Vec<Vec<u8>>, // headers: FxHashMap<Vec<u8>, usize> } #[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] pub enum BedColumn { Chr, Start, End, Name, Index(usize), Header { index: usize, name: Vec<u8> }, } impl ColumnKey for BedColumn { fn is_column_optional(key: &Self) -> bool { use BedColumn::*; match key { Chr | Start | End => false, _ => true, } } fn seq_id() -> Self { Self::Chr } fn start() -> Self { Self::Start } fn end() -> Self { Self::End } } impl BedRecords { pub fn parse_bed_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self> { use std::fs::File; use std::io::{BufRead, BufReader}; let file_name = path.as_ref().file_name().unwrap(); let file_name = file_name.to_str().unwrap().to_string(); let file = File::open(path)?; let mut reader = BufReader::new(file); let mut buf: Vec<u8> = Vec::new(); let mut records = Vec::new(); let mut column_count = 0; let mut headers = Vec::new(); let mut line_num = 0; loop { buf.clear(); let read = reader.read_until(b'\n', &mut buf)?; if read == 0 { break; } let line = &buf[0..read]; line_num += 1; if line[0] == b'#' { if line_num == 1 && line.len() > 1 { let fields = (&line[1..]).fields(); headers.extend(fields.map(|field| field.trim().to_owned())); } continue; } let fields = line.split_str("\t").map(ByteSlice::trim); if let Some(record) = BedRecord::parse_row(fields) { column_count = record.rest.len().max(column_count); records.push(record); } } let mut column_keys: Vec<BedColumn> = vec![BedColumn::Chr, BedColumn::Start, BedColumn::End]; if headers.is_empty() { column_keys .extend((0..column_count).map(|ix| BedColumn::Index(ix))); } else { column_keys.extend(headers.iter().skip(3).enumerate().map( |(ix, h)| BedColumn::Header { index: ix, name: h.to_owned(), }, )); } Ok(Self { file_name, records, column_keys, headers, }) } pub fn has_headers(&self) -> bool { !self.headers.is_empty() } pub fn headers(&self) -> &[Vec<u8>] { &self.headers } pub fn header_to_column(&self, header: &[u8]) -> Option<BedColumn> { let raw_index = self .headers .iter() .enumerate() .find(|(_, h)| h == &header) .map(|(ix, _)| ix)?; use BedColumn as Bed; let column = match raw_index { 0 => Bed::Chr, 1 => Bed::Start, 2 => Bed::End, // 3 => Bed::Name, ix => Bed::Header { index: ix, name: header.to_owned(), }, // ix => Bed::Index(ix - 3), }; Some(column) } } fn parse_next<'a, T, I>(fields: &mut I) -> Option<T> where T: std::str::FromStr, I: Iterator<Item = &'a [u8]> + 'a, { let field = fields.next()?; let field = field.as_bstr().to_str().ok()?; field.parse().ok() } impl BedRecord { fn parse_row<'a, I>(mut fields: I) -> Option<Self> where I: Iterator<Item = &'a [u8]> + 'a, { let chr = fields.next()?; let start: usize = parse_next(&mut fields)?; let end: usize = parse_next(&mut fields)?; let rest: Vec<Vec<u8>> = fields.map(|field| field.to_owned()).collect(); // let mut rest: Vec<Vec<u8>> = Vec::new(); // let mut count = 0; // while let Some(field) = fields.next() { // count += 1; // rest.push(field.to_owned()); // } // println!("adding {} columns", count); Some(Self { chr: chr.to_owned(), start, end, rest, }) } } impl std::fmt::Display for BedColumn { fn fmt( &self, f: &mut std::fmt::Formatter<'_>, ) -> std::result::Result<(), std::fmt::Error> { match self { BedColumn::Chr => write!(f, "chr"), BedColumn::Start => write!(f, "start"), BedColumn::End => write!(f, "end"), BedColumn::Name => write!(f, "name"), BedColumn::Index(i) => write!(f, "{}", i), BedColumn::Header { name, .. } => write!(f, "{}", name.as_bstr()), } } } impl AnnotationCollection for BedRecords { type ColumnKey = BedColumn; type Record = BedRecord; fn file_name(&self) -> &str { &self.file_name } fn len(&self) -> usize { self.records.len() } fn all_columns(&self) -> Vec<Self::ColumnKey> { self.column_keys.clone() } fn mandatory_columns(&self) -> Vec<Self::ColumnKey> { let slice = &self.column_keys[0..=2]; Vec::from(slice) } fn optional_columns(&self) -> Vec<Self::ColumnKey> { let mut res = Vec::new(); res.extend(self.column_keys.iter().cloned().skip(3)); res } fn records(&self) -> &[Self::Record] { &self.records } fn wrap_column(column: Self::ColumnKey) -> AnnotationColumn { AnnotationColumn::Bed(column) } } impl AnnotationRecord for BedRecord { type ColumnKey = BedColumn; fn columns(&self) -> Vec<Self::ColumnKey> { let mut columns = Vec::with_capacity(3 + self.rest.len()); use BedColumn::*; columns.push(Chr); columns.push(Start); columns.push(End); for i in 0..self.rest.len() { columns.push(Index(i)); } columns } fn seq_id(&self) -> &[u8] { &self.chr } fn start(&self) -> usize { self.start } fn end(&self) -> usize { self.end } // TODO handle this more intelligently... somehow fn score(&self) -> Option<f64> { let field = self.rest.get(1)?; let field_str = field.to_str().ok()?; field_str.parse().ok() } fn get_first(&self, key: &Self::ColumnKey) -> Option<&[u8]> { match key { BedColumn::Chr => Some(&self.chr), BedColumn::Start => None, BedColumn::End => None, BedColumn::Name => self.rest.get(0).map(|v| v.as_bytes()), BedColumn::Index(i) => self.rest.get(*i).map(|v| v.as_bytes()), BedColumn::Header { index, .. } => { self.rest.get(*index).map(|v| v.as_bytes()) } // let index = self.headers.iter().fi // todo!(), // } } } fn get_all(&self, key: &Self::ColumnKey) -> Vec<&[u8]> { match key { BedColumn::Chr => vec![&self.chr], BedColumn::Start => vec![], BedColumn::End => vec![], BedColumn::Name => { self.rest.get(0).map(|v| v.as_bytes()).into_iter().collect() } BedColumn::Index(i) => self .rest .get(*i) .map(|v| v.as_bytes()) .into_iter() .collect(), BedColumn::Header { index, .. } => self .rest .get(*index) .map(|v| v.as_bytes()) .into_iter() .collect(), } } }
mod support; mod ui; use cubik::glium::{glutin, Surface}; use cubik::draw::{ObjDrawInfo, EnvDrawInfo, basic_render, MAX_LIGHTS, Light}; use cubik::camera::perspective_matrix; use cubik::input::{InputListener, process_input_event, center_cursor}; use cubik::skybox::Skybox; use cubik::animation::ObjAnimation; use cubik::player::{Player, PlayerControlType}; use ui::{MainMenu, MainMenuAction}; use support::constants::APP_ID; use cubik::audio::{buffer_sound, get_sound_stream, play_sound_from_file}; use cubik::map::GameMap; use cubik::container::RenderContainer; fn main() { let event_loop = glutin::event_loop::EventLoop::new(); let mut ctr = RenderContainer::new(&event_loop, 1280, 720, "Example", false); let mut map_info: ObjDrawInfo = Default::default(); map_info.generate_matrix(); let mut wolf_info = ObjDrawInfo { position: [0.4, 0.05, 0.0f32], rotation: [0.0, 0.0, 0.0f32], scale: [1., 1., 1.], color: [1., 1., 1.], model_mat: None }; wolf_info.generate_matrix(); let sound_stream = get_sound_stream().unwrap(); let mut player = Player::new([0.0, 1.5, 0.0], PlayerControlType::Singleplayer, [-0.28, 0.275, 0.0], [0.44, 0.275, 0.08]); play_sound_from_file(&sound_stream, "./audio/ding.wav", APP_ID).unwrap(); player.walking_sound = Some(buffer_sound("./audio/running.wav", APP_ID).unwrap()); let map = GameMap::load_map("models/map2", APP_ID, Some(&ctr.display), Some(&mut ctr.textures), true).unwrap(); let wolf_anim = ObjAnimation::load_wavefront("models/wolfrunning", APP_ID, &ctr.display, &mut ctr.textures, 0.041).unwrap(); let skybox = Skybox::new(&ctr.display, "skybox1", APP_ID, 512, 50.).unwrap(); let mut lights_arr: [Light; MAX_LIGHTS] = Default::default(); let mut lights_iter = map.lights.values(); for i in 0..map.lights.len() { lights_arr[i] = *lights_iter.next().unwrap(); } let mut displace = 0.0f32; let mut main_menu = MainMenu::new(&ctr.display).unwrap(); main_menu.enabled = false; let start_time = std::time::Instant::now(); let mut last_frame_time = std::time::Instant::now(); event_loop.run(move |ev, _, control_flow| { let listeners: Vec<&mut dyn InputListener> = vec![&mut main_menu, &mut player]; *control_flow = glutin::event_loop::ControlFlow::Poll; match ev { glutin::event::Event::WindowEvent { event, .. } => match event { glutin::event::WindowEvent::CloseRequested => { *control_flow = glutin::event_loop::ControlFlow::Exit; return; }, glutin::event::WindowEvent::KeyboardInput { input, .. } => { if let Some(glutin::event::VirtualKeyCode::Escape) = input.virtual_keycode { *control_flow = glutin::event_loop::ControlFlow::Exit; return; } process_input_event(event, listeners, &ctr.display); return; }, _ => { process_input_event(event, listeners, &ctr.display); return; } }, glutin::event::Event::NewEvents(cause) => match cause { glutin::event::StartCause::ResumeTimeReached { .. } => (), glutin::event::StartCause::Init => { center_cursor(&ctr.display, false); }, glutin::event::StartCause::Poll => (), _ => return }, _ => return } let new_frame_time = std::time::Instant::now(); let time_delta = new_frame_time.duration_since(last_frame_time).as_secs_f32(); last_frame_time = new_frame_time; displace += time_delta; player.update(time_delta, Some(map.quadoctree.as_ref().unwrap()), Some(&sound_stream), None); let mut target = ctr.display.draw(); let perspective_mat = perspective_matrix(&mut target); let env_info = EnvDrawInfo { perspective_mat: perspective_mat, view_mat: player.camera.view_matrix(), lights: lights_arr, light_count: map.lights.len(), params: &ctr.params, textures: &ctr.textures }; if main_menu.enabled { target.clear_color_and_depth((0., 0., 0., 1.0), 1.0); if let Some(result) = main_menu.draw(&mut target, &ctr.display, &ctr.ui_program).unwrap() { match result { MainMenuAction::Quit => { target.finish().unwrap(); *control_flow = glutin::event_loop::ControlFlow::Exit; return; }, MainMenuAction::Start => main_menu.enabled = false }; } } else { target.clear_color_and_depth((0.85, 0.85, 0.85, 1.0), 1.0); for (key, o) in &map.objects { let text_displace = if key.starts_with("water") { Some([displace.sin() * 0.005, displace.sin() * 0.005]) } else { None }; basic_render(&mut target, &env_info, &map_info, &o, &ctr.main_program, text_displace); } for o in wolf_anim.get_keyframe(start_time.elapsed().as_secs_f32()).values() { basic_render(&mut target, &env_info, &wolf_info, &o, &ctr.main_program, None); } skybox.draw(&mut target, &env_info, &ctr.skybox_program); } target.finish().unwrap(); }); }
/*! BLS signatures */ use ff::Field; use hkdf::Hkdf; use pairing::bls12_381::{Bls12, Fq12, Fr, G1, G2}; use pairing::hash_to_field::BaseFromRO; use pairing::hash_to_curve::HashToCurve; use pairing::{CurveAffine, CurveProjective, Engine}; use sha2::digest::generic_array::typenum::U48; use sha2::digest::generic_array::GenericArray; use sha2::Sha256; /// Hash a secret key sk to the secret exponent x'; then (PK, SK) = (g^{x'}, x'). pub fn xprime_from_sk<B: AsRef<[u8]>>(msg: B) -> Fr { let mut result = GenericArray::<u8, U48>::default(); Hkdf::<Sha256>::new(None, msg.as_ref()) .expand(&[], &mut result) .unwrap(); Fr::from_okm(&result) } /// Alias for the scalar type corresponding to a CurveProjective type type ScalarT<PtT> = <PtT as CurveProjective>::Scalar; /// BLS signature implementation pub trait BLSSignature: CurveProjective { /// The type of the public key type PKType: CurveProjective<Engine = <Self as CurveProjective>::Engine, Scalar = ScalarT<Self>>; /// Generate secret exponent and public key fn keygen<B: AsRef<[u8]>>(sk: B) -> (ScalarT<Self>, Self::PKType); /// Sign a message fn sign<B: AsRef<[u8]>>(x_prime: ScalarT<Self>, msg: B, ciphersuite: u8) -> Self; /// Verify a signature fn verify<B: AsRef<[u8]>>(pk: Self::PKType, sig: Self, msg: B, ciphersuite: u8) -> bool; } impl BLSSignature for G1 { type PKType = G2; fn keygen<B: AsRef<[u8]>>(sk: B) -> (Fr, G2) { let x_prime = xprime_from_sk(sk); let mut pk = G2::one(); pk.mul_assign(x_prime); (x_prime, pk) } fn sign<B: AsRef<[u8]>>(x_prime: Fr, msg: B, ciphersuite: u8) -> G1 { let mut p = G1::hash_to_curve(msg, ciphersuite); p.mul_assign(x_prime); p } fn verify<B: AsRef<[u8]>>(pk: G2, sig: G1, msg: B, ciphersuite: u8) -> bool { let p = G1::hash_to_curve(msg, ciphersuite).into_affine().prepare(); let g2gen = { let mut tmp = G2::one(); tmp.negate(); tmp.into_affine().prepare() }; Fq12::one() == Bls12::final_exponentiation(&Bls12::miller_loop(&[ (&p, &pk.into_affine().prepare()), (&sig.into_affine().prepare(), &g2gen), ])) .unwrap() } } impl BLSSignature for G2 { type PKType = G1; fn keygen<B: AsRef<[u8]>>(sk: B) -> (Fr, G1) { let x_prime = xprime_from_sk(sk); let mut pk = G1::one(); pk.mul_assign(x_prime); (x_prime, pk) } fn sign<B: AsRef<[u8]>>(x_prime: Fr, msg: B, ciphersuite: u8) -> G2 { let mut p = G2::hash_to_curve(msg, ciphersuite); p.mul_assign(x_prime); p } fn verify<B: AsRef<[u8]>>(pk: G1, sig: G2, msg: B, ciphersuite: u8) -> bool { let p = G2::hash_to_curve(msg, ciphersuite).into_affine().prepare(); let g1gen = { let mut tmp = G1::one(); tmp.negate(); tmp.into_affine().prepare() }; Fq12::one() == Bls12::final_exponentiation(&Bls12::miller_loop(&[ (&pk.into_affine().prepare(), &p), (&g1gen, &sig.into_affine().prepare()), ])) .unwrap() } } #[cfg(test)] mod tests { use super::{xprime_from_sk, BLSSignature}; use ff::PrimeField; use pairing::bls12_381::{Fr, FrRepr, G1, G2}; fn test_sig<T: BLSSignature>(ciphersuite: u8) { let msg = "this is the message"; let sk = "this is the key"; let (x_prime, pk) = T::keygen(sk); let sig = T::sign(x_prime, msg, ciphersuite); assert!(T::verify(pk, sig, msg, ciphersuite)); } #[test] fn test_g1() { test_sig::<G1>(1u8); } #[test] fn test_g2() { test_sig::<G2>(2u8); } #[test] fn test_xprime_from_sk() { let fr_val = xprime_from_sk("hello world (it's a secret!)"); let expect = FrRepr([ 0x73f15a42979430a4u64, 0xc26ed5c294f7cbb5u64, 0xa98ec5b569484e7du64, 0x77cf27e14db0de2u64, ]); assert_eq!(fr_val, Fr::from_repr(expect).unwrap()); } }
use kite::schema::FieldRef; use kite::term::TermRef; use kite::Query; use kite::query::term_scorer::TermScorer; use RocksDBIndexReader; #[derive(Debug, Clone)] pub enum CombinatorScorer { Avg, Max, } #[derive(Debug, Clone)] pub enum ScoreFunctionOp { Literal(f64), TermScorer(FieldRef, TermRef, TermScorer), CombinatorScorer(u32, CombinatorScorer), } fn plan_score_function_combinator(index_reader: &RocksDBIndexReader, mut score_function: &mut Vec<ScoreFunctionOp>, queries: &Vec<Query>, scorer: CombinatorScorer) { match queries.len() { 0 => { score_function.push(ScoreFunctionOp::Literal(0.0f64)); } 1 => plan_score_function(index_reader, &mut score_function, &queries[0]), _ => { let mut query_iter = queries.iter(); plan_score_function(index_reader, &mut score_function, query_iter.next().unwrap()); for query in query_iter { plan_score_function(index_reader, &mut score_function, query); } } } score_function.push(ScoreFunctionOp::CombinatorScorer(queries.len() as u32, scorer)); } pub fn plan_score_function(index_reader: &RocksDBIndexReader, mut score_function: &mut Vec<ScoreFunctionOp>, query: &Query) { match *query { Query::All{ref score} => { score_function.push(ScoreFunctionOp::Literal(*score)); } Query::None => { score_function.push(ScoreFunctionOp::Literal(0.0f64)); } Query::Term{field, ref term, ref scorer} => { // Get term let term_ref = match index_reader.store.term_dictionary.get(term) { Some(term_ref) => term_ref, None => { // Term doesn't exist, so will never match score_function.push(ScoreFunctionOp::Literal(0.0f64)); return } }; score_function.push(ScoreFunctionOp::TermScorer(field, term_ref, scorer.clone())); } Query::MultiTerm{field, ref term_selector, ref scorer} => { // Get terms let mut total_terms = 0; for term_ref in index_reader.store.term_dictionary.select(term_selector) { score_function.push(ScoreFunctionOp::TermScorer(field, term_ref, scorer.clone())); total_terms += 1; } // This query must push only one score value onto the stack. // If we haven't pushed any score operations, Push a literal 0.0 // If we have pushed more than one score operations, which will lead to more // than one score value being pushed to the stack, combine the score values // with a combinator operation. match total_terms { 0 => score_function.push(ScoreFunctionOp::Literal(0.0f64)), 1 => {}, _ => score_function.push(ScoreFunctionOp::CombinatorScorer(total_terms, CombinatorScorer::Avg)), } } Query::Conjunction{ref queries} => { plan_score_function_combinator(index_reader, &mut score_function, queries, CombinatorScorer::Avg); } Query::Disjunction{ref queries} => { plan_score_function_combinator(index_reader, &mut score_function, queries, CombinatorScorer::Avg); } Query::DisjunctionMax{ref queries} => { plan_score_function_combinator(index_reader, &mut score_function, queries, CombinatorScorer::Max); } Query::Filter{ref query, ..} => { plan_score_function(index_reader, &mut score_function, query); } Query::Exclude{ref query, ..} => { plan_score_function(index_reader, &mut score_function, query); } } }
use std::io::{Write}; use std::fs::File; use lib::{Node}; use parser_lib as parser; use asm_lib as asm; // $ gcc -m32 -masm=intel main.s -o main pub fn gen(ast: & Vec<Node::Node>, filename: & String) { // println!(""); // println!("----------------"); // println!("[+] Code Generator:"); let mut f = File::create(&filename).expect("Gen: Unable to create the file."); analyze_ast(& ast, 0, 0, &mut f); } fn analyze_ast(ast: & Vec<Node::Node>, me: usize, from: usize, mut f: &mut File) { match ast[me]._level.as_str() { "Program" => program(&ast, me, from, &mut f), "Function" => function(&ast, me, from, &mut f), "Statement" => statement(&ast, me, from, &mut f), _ => panic!("Gen: Unrecoginized AST node.\nAST node: {} {} {} {}", ast[me]._level, ast[me]._type, ast[me]._name, ast[me]._value), } } fn program(ast: & Vec<Node::Node>, me: usize, from: usize, mut f: &mut File) { write!(f, " .intel_syntax noprefix\n").expect("Gen: generator program: Unable to write to the file."); write!(f, " ").expect("Gen: generator program: Unable to write to the file."); write!(f, ".file ").expect("Gen: generator program: Unable to write to the file."); write!(f, "\"{}\"\n", ast[me]._name).expect("Gen: generator program: Unable to write to the file."); for i in ast[me].to.iter() { let to = *i; analyze_ast(& ast, to, me, &mut f); } } fn function(ast: & Vec<Node::Node>, me: usize, from: usize, mut f: &mut File) { write!(f, " ").expect("Gen: generator func: Unable to write to the file."); write!(f, ".globl ").expect("Gen: generator func: Unable to write to the file."); write!(f, "{}\n", ast[me]._name).expect("Gen: generator func: Unable to write to the file."); write!(f, "{}:\n", ast[me]._name).expect("Gen: generator func: Unable to write to the file."); for i in ast[me].to.iter() { let to = *i; analyze_ast(& ast, to, me, &mut f); } } fn statement(ast: & Vec<Node::Node>, me: usize, from: usize, mut f: &mut File) { match ast[me]._type.as_str() { "RETURN_KEYWORD" => Return(&ast, me, from, &mut f), _ => (), } } fn Return(ast: & Vec<Node::Node>, me: usize, from: usize, mut f: &mut File) { expression(&ast, ast[me].to[0], &mut f); asm::ret(&mut f); } fn expression(ast: & Vec<Node::Node>, me: usize, mut f: &mut File){ match ast[me]._type.as_str() { "CONSTANT" => Constant(&ast, me, &mut f), "NEGATION" => Neg(&ast, me, &mut f), "BIT_COMPLE" => BitComple(&ast, me, &mut f), "LOGIC_NEG" => LogicNeg(&ast, me, &mut f), _ => panic!("Gen: Unrecoginized expression type.\nExp type: {} {} {}", ast[me]._level, ast[me]._type, ast[me]._value), } } fn Constant(ast: & Vec<Node::Node>, me: usize, mut f: &mut File) { let ret = ast[me]._value.as_str(); asm::mov("eax", ret, &mut f); } fn Neg(ast: & Vec<Node::Node>, me: usize, mut f: &mut File) { expression(&ast, ast[me].to[0], &mut f); asm::neg("eax", &mut f); } fn BitComple(ast: & Vec<Node::Node>, me: usize, mut f: &mut File) { expression(&ast, ast[me].to[0], &mut f); asm::not("eax", &mut f); } // cmp eax(exp), 0 // return exp==0 ? // sete eax // 1 : 0 fn LogicNeg(ast: & Vec<Node::Node>, me: usize, mut f: &mut File) { expression(&ast, ast[me].to[0], &mut f); asm::cmp("eax", "0", &mut f); asm::mov("eax", "0", &mut f); asm::sete("al", &mut f); }
use ggez::*; use ggez::graphics::{DrawMode, Drawable, Rect, Color, Mesh, DrawParam}; use base::*; use pathfinder::*; use std::time::Instant; use path_example::Point2; /* * AMD Ryzen 5 3600 6-Core Processor * rustc 1.43.0 * Time elapsed : 4.99 sec */ static SIZE_COEFF : i32 = 5; pub struct MainState { pub title: &'static str, from: Vec<ColoredPoint>, to: Vec<Point>, shapes : Vec<RectangleFieldShape>, start: Option<Instant>, ended: bool, first: bool, } struct ColoredPoint { point: Point, color: Color, } impl MainState { pub fn new() -> MainState { let mut from : Vec<ColoredPoint> = Vec::new(); let mut to : Vec<Point> = Vec::new(); let mut shapes : Vec<RectangleFieldShape> = Vec::new(); shapes.push(RectangleFieldShape::new(10, 10, 10, 10)); shapes.push(RectangleFieldShape::new(40, 20, 20, 20)); shapes.push(RectangleFieldShape::new(40, 60, 20, 20)); shapes.push(RectangleFieldShape::new(75, 75, 10, 10)); let green = Color::new(0.0, 1.0, 0.0, 1.0); let blue = Color::new(0.0, 0.0, 1.0, 1.0); for i in 0..49 { from.push(ColoredPoint { point: Point::new(0, 50 - i), color: green }); to.push(Point::new(90, 99 - i)); from.push(ColoredPoint { point: Point::new(90, 99 - i), color: blue }); to.push(Point::new(0, 50 - i)); } MainState { title: "Move example", from, to, shapes, start: None, ended: false, first : true } } } impl MainState { fn to_screen(&self, v: i32) -> f32 { return (v * SIZE_COEFF) as f32; } } impl event::EventHandler<ggez::GameError> for MainState { fn update(&mut self, _ctx: &mut Context) -> GameResult<()> { // the first time, I want only to draw the initial position. if self.first { self.first = false; return Ok(()); } // but I initialize the time on the first real update. if self.start.is_none() { self.start = Some(Instant::now()); } let mut froms : Vec<ColoredPoint> = Vec::new(); let mut tos : Vec<Point> = Vec::new(); let mut ended = true; while !self.from.is_empty() { let from = self.from.pop().unwrap(); let to = self.to.pop().unwrap(); if from.point.eq(&to) { froms.push(from); tos.push(to); continue; } ended = false; let mut shapes : Vec<Box<dyn FieldShape>> = Vec::new(); for shape in &self.shapes { shapes.push(Box::new(shape.clone())); } for point in &self.from { shapes.push(Box::new(PointFieldShape {x: point.point.x, y: point.point.y})); } for point in &froms { shapes.push(Box::new(PointFieldShape {x: point.point.x, y: point.point.y})); } let dim = Dimension {width: 100, height: 100}; let field = PathField::new(shapes, dim); let pf = AStarPathFinder {field, from : from.point.clone(), to : to.clone()}; let mut path = pf.get_path(); if path.is_empty() { froms.push(from); } else { froms.push(ColoredPoint { point: path.pop().unwrap(), color: from.color}); } tos.push(to); } if !self.ended && ended { self.ended = true; let duration = self.start.unwrap().elapsed(); println!("Time elapsed : {:?}", duration); } self.from = froms; self.to = tos; Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult<()> { let black = Color::new(0.0, 0.0, 0.0, 1.0); graphics::clear(ctx, black); // TODO use MeshBuilder? let shapes = &self.shapes; for shape in shapes { let ref s = *shape; let color = Color::new(1.0, 0.0, 0.0, 1.0); let rect = Rect::new( self.to_screen(s.point.x), self.to_screen(s.point.y), self.to_screen(s.width), self.to_screen(s.height) ); let mesh = Mesh::new_rectangle(ctx, DrawMode::fill(), rect, color)?; let param = DrawParam::new().dest(Point2::new(0.0, 0.0)); mesh.draw(ctx, param)?; } for point in &self.from { let rect = Rect::new( self.to_screen(point.point.x), self.to_screen(point.point.y), SIZE_COEFF as f32, SIZE_COEFF as f32 ); let mesh = Mesh::new_rectangle(ctx, DrawMode::fill(), rect, point.color)?; let param = DrawParam::new().dest(Point2::new(0.0, 0.0)); mesh.draw(ctx, param)?; } graphics::present(ctx) } }
//! use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Result as FmtResult; use std::fmt::Write; use super::expression::AlgebraicExpression; #[derive(Clone, Debug, PartialEq)] pub struct Observable { name: String, value: AlgebraicExpression, } impl Observable { pub fn new<N, A>(name: N, value: A) -> Self where N: Into<String>, A: Into<AlgebraicExpression>, { Self { name: name.into(), value: value.into(), } } } impl Display for Observable { fn fmt(&self, f: &mut Formatter) -> FmtResult { f.write_str("%obs: '") .and(f.write_str(&self.name)) .and(f.write_str("' ")) .and(self.value.fmt(f)) .and(f.write_char('\n')) } }
use std::rc::Rc; use cgmath::{self, EuclideanSpace}; use midgar::{KeyCode, Midgar, Surface}; use midgar::graphics::shape::ShapeRenderer; use midgar::graphics::sprite::{DrawTexture, MagnifySamplerFilter, SpriteDrawParams, SpriteRenderer}; use midgar::graphics::text::{self, Font, TextRenderer}; use midgar::graphics::texture::TextureRegion; use specs::{Entities, Join, Read, ReadStorage}; use components::*; use config; use resources::PlayerScore; use world::GameWorld; type RenderData<'a> = ( Read<'a, PlayerScore>, ReadStorage<'a, Bomber>, ReadStorage<'a, Camera>, ReadStorage<'a, Player>, ReadStorage<'a, Renderable>, ReadStorage<'a, Transform>, Entities<'a>, ); pub struct GameRenderer<'a> { sprite: SpriteRenderer, shape: ShapeRenderer, text: TextRenderer<'a>, projection: cgmath::Matrix4<f32>, font: Font<'a>, render_debug: bool, } impl<'a> GameRenderer<'a> { pub fn new(midgar: &Midgar) -> Self { let viewport_width = config::GAME_SIZE.x as f32; let viewport_height = config::GAME_SIZE.y as f32; let projection = cgmath::ortho(-viewport_width / 2.0, viewport_width / 2.0, viewport_height / 2.0, -viewport_height / 2.0, -1.0, 1.0); Self { sprite: SpriteRenderer::new(midgar.graphics().display(), projection), shape: ShapeRenderer::new(midgar.graphics().display(), projection), text: TextRenderer::new(midgar.graphics().display()), projection, font: text::load_font_from_path("assets/fonts/Kenney Pixel.ttf"), render_debug: false, } } pub fn render(&mut self, midgar: &Midgar, _dt: f32, world: &mut GameWorld) { if midgar.input().was_key_pressed(KeyCode::Tab) { self.render_debug = !self.render_debug; } world.world.exec(|(score, bombers, cameras, players, renderables, transforms, entities): RenderData| { let camera_pos = (&transforms, &cameras).join() .next() .expect("Lost the camera when trying to render!").0.position; // Compute the combined projection * view matrix. let camera_pos = cgmath::vec3(camera_pos.x.round(), camera_pos.y.round(), 0.0); let view = cgmath::Matrix4::look_at(cgmath::Point3::from_vec(camera_pos), cgmath::Point3::new(0.0, 0.0, -1.0) + camera_pos, cgmath::vec3(0.0, 1.0, 0.0)); let combined = self.projection * view; self.sprite.set_projection_matrix(combined); self.shape.set_projection_matrix(combined); let mut target = midgar.graphics().display().draw(); // Clear the screen. let color = [0, 0, 0]; target.clear_color(color[0] as f32 / 0.0, color[1] as f32 / 0.0, color[2] as f32 / 0.0, 1.0); // Draw each renderable. for (renderable, transform) in (&renderables, &transforms).join() { match *renderable { Renderable::Shape(ref shape) => { let pos = transform.position; // Round the positions so that shapes are drawn at pixel boundaries. // Also draw with the origin in the center of the shape. self.shape.draw_filled_rect(pos.x.round(), pos.y.round(), shape.width as f32, shape.height as f32, shape.color, &mut target); }, } } // Draw UI. let projection = cgmath::ortho(0.0, config::SCREEN_SIZE.x as f32, config::SCREEN_SIZE.y as f32, 0.0, -1.0, 1.0); // Get the player entity's number of bombs. let bomb_count = if let Some((bomber, _)) = (&bombers, &players).join().next() { bomber.count } else { 0 }; // Draw number of bombs in stock. let bomb_count_text = format!("Bomb: {:02}", bomb_count); self.text.draw_text(&bomb_count_text, self.font.clone(), [1.0, 1.0, 1.0], 40, 40.0, 30.0, 800, &projection, &mut target); // Draw player score. let player_score_text = format!("Score: {}", score.0); self.text.draw_text(&player_score_text, self.font.clone(), [1.0, 1.0, 1.0], 40, 800.0, 30.0, 800, &projection, &mut target); if self.render_debug { // Draw number of entities. let entity_count = entities.join().count(); let entity_count_text = format!("Entities: {}", entity_count); self.text.draw_text(&entity_count_text, self.font.clone(), [1.0, 1.0, 1.0], 30, 800.0, 720.0, 800, &projection, &mut target); } // Finish this frame. target.finish() .unwrap(); }); } }
/// GitTreeResponse returns a git tree #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct GitTreeResponse { pub page: Option<i64>, pub sha: Option<String>, pub total_count: Option<i64>, pub tree: Option<Vec<crate::git_entry::GitEntry>>, pub truncated: Option<bool>, pub url: Option<String>, } impl GitTreeResponse { /// Create a builder for this object. #[inline] pub fn builder() -> GitTreeResponseBuilder { GitTreeResponseBuilder { body: Default::default(), } } #[inline] pub fn get_tree() -> GitTreeResponseGetBuilder<crate::generics::MissingOwner, crate::generics::MissingRepo, crate::generics::MissingSha> { GitTreeResponseGetBuilder { inner: Default::default(), _param_owner: core::marker::PhantomData, _param_repo: core::marker::PhantomData, _param_sha: core::marker::PhantomData, } } } impl Into<GitTreeResponse> for GitTreeResponseBuilder { fn into(self) -> GitTreeResponse { self.body } } /// Builder for [`GitTreeResponse`](./struct.GitTreeResponse.html) object. #[derive(Debug, Clone)] pub struct GitTreeResponseBuilder { body: self::GitTreeResponse, } impl GitTreeResponseBuilder { #[inline] pub fn page(mut self, value: impl Into<i64>) -> Self { self.body.page = Some(value.into()); self } #[inline] pub fn sha(mut self, value: impl Into<String>) -> Self { self.body.sha = Some(value.into()); self } #[inline] pub fn total_count(mut self, value: impl Into<i64>) -> Self { self.body.total_count = Some(value.into()); self } #[inline] pub fn tree(mut self, value: impl Iterator<Item = crate::git_entry::GitEntry>) -> Self { self.body.tree = Some(value.map(|value| value.into()).collect::<Vec<_>>().into()); self } #[inline] pub fn truncated(mut self, value: impl Into<bool>) -> Self { self.body.truncated = Some(value.into()); self } #[inline] pub fn url(mut self, value: impl Into<String>) -> Self { self.body.url = Some(value.into()); self } } /// Builder created by [`GitTreeResponse::get_tree`](./struct.GitTreeResponse.html#method.get_tree) method for a `GET` operation associated with `GitTreeResponse`. #[repr(transparent)] #[derive(Debug, Clone)] pub struct GitTreeResponseGetBuilder<Owner, Repo, Sha> { inner: GitTreeResponseGetBuilderContainer, _param_owner: core::marker::PhantomData<Owner>, _param_repo: core::marker::PhantomData<Repo>, _param_sha: core::marker::PhantomData<Sha>, } #[derive(Debug, Default, Clone)] struct GitTreeResponseGetBuilderContainer { param_owner: Option<String>, param_repo: Option<String>, param_sha: Option<String>, param_recursive: Option<bool>, param_page: Option<i64>, param_per_page: Option<i64>, } impl<Owner, Repo, Sha> GitTreeResponseGetBuilder<Owner, Repo, Sha> { /// owner of the repo #[inline] pub fn owner(mut self, value: impl Into<String>) -> GitTreeResponseGetBuilder<crate::generics::OwnerExists, Repo, Sha> { self.inner.param_owner = Some(value.into()); unsafe { std::mem::transmute(self) } } /// name of the repo #[inline] pub fn repo(mut self, value: impl Into<String>) -> GitTreeResponseGetBuilder<Owner, crate::generics::RepoExists, Sha> { self.inner.param_repo = Some(value.into()); unsafe { std::mem::transmute(self) } } /// sha of the commit #[inline] pub fn sha(mut self, value: impl Into<String>) -> GitTreeResponseGetBuilder<Owner, Repo, crate::generics::ShaExists> { self.inner.param_sha = Some(value.into()); unsafe { std::mem::transmute(self) } } /// show all directories and files #[inline] pub fn recursive(mut self, value: impl Into<bool>) -> Self { self.inner.param_recursive = Some(value.into()); self } /// page number; the 'truncated' field in the response will be true if there are still more items after this page, false if the last page #[inline] pub fn page(mut self, value: impl Into<i64>) -> Self { self.inner.param_page = Some(value.into()); self } /// number of items per page #[inline] pub fn per_page(mut self, value: impl Into<i64>) -> Self { self.inner.param_per_page = Some(value.into()); self } } impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for GitTreeResponseGetBuilder<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::ShaExists> { type Output = GitTreeResponse; const METHOD: http::Method = http::Method::GET; fn rel_path(&self) -> std::borrow::Cow<'static, str> { format!("/repos/{owner}/{repo}/git/trees/{sha}", owner=self.inner.param_owner.as_ref().expect("missing parameter owner?"), repo=self.inner.param_repo.as_ref().expect("missing parameter repo?"), sha=self.inner.param_sha.as_ref().expect("missing parameter sha?")).into() } fn modify(&self, req: Client::Request) -> Result<Client::Request, crate::client::ApiError<Client::Response>> { use crate::client::Request; Ok(req .query(&[ ("recursive", self.inner.param_recursive.as_ref().map(std::string::ToString::to_string)), ("page", self.inner.param_page.as_ref().map(std::string::ToString::to_string)), ("per_page", self.inner.param_per_page.as_ref().map(std::string::ToString::to_string)) ])) } } impl crate::client::ResponseWrapper<GitTreeResponse, GitTreeResponseGetBuilder<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::ShaExists>> { #[inline] pub fn message(&self) -> Option<String> { self.headers.get("message").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok()) } #[inline] pub fn url(&self) -> Option<String> { self.headers.get("url").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok()) } }
use tonic::transport::Server;
#[doc = "Reader of register CTRLR0"] pub type R = crate::R<u32, super::CTRLR0>; #[doc = "Writer for register CTRLR0"] pub type W = crate::W<u32, super::CTRLR0>; #[doc = "Register CTRLR0 `reset()`'s with value 0"] impl crate::ResetValue for super::CTRLR0 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `SSTE`"] pub type SSTE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SSTE`"] pub struct SSTE_W<'a> { w: &'a mut W, } impl<'a> SSTE_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 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "SPI frame format\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum SPI_FRF_A { #[doc = "0: Standard 1-bit SPI frame format; 1 bit per SCK, full-duplex"] STD = 0, #[doc = "1: Dual-SPI frame format; two bits per SCK, half-duplex"] DUAL = 1, #[doc = "2: Quad-SPI frame format; four bits per SCK, half-duplex"] QUAD = 2, } impl From<SPI_FRF_A> for u8 { #[inline(always)] fn from(variant: SPI_FRF_A) -> Self { variant as _ } } #[doc = "Reader of field `SPI_FRF`"] pub type SPI_FRF_R = crate::R<u8, SPI_FRF_A>; impl SPI_FRF_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, SPI_FRF_A> { use crate::Variant::*; match self.bits { 0 => Val(SPI_FRF_A::STD), 1 => Val(SPI_FRF_A::DUAL), 2 => Val(SPI_FRF_A::QUAD), i => Res(i), } } #[doc = "Checks if the value of the field is `STD`"] #[inline(always)] pub fn is_std(&self) -> bool { *self == SPI_FRF_A::STD } #[doc = "Checks if the value of the field is `DUAL`"] #[inline(always)] pub fn is_dual(&self) -> bool { *self == SPI_FRF_A::DUAL } #[doc = "Checks if the value of the field is `QUAD`"] #[inline(always)] pub fn is_quad(&self) -> bool { *self == SPI_FRF_A::QUAD } } #[doc = "Write proxy for field `SPI_FRF`"] pub struct SPI_FRF_W<'a> { w: &'a mut W, } impl<'a> SPI_FRF_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SPI_FRF_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Standard 1-bit SPI frame format; 1 bit per SCK, full-duplex"] #[inline(always)] pub fn std(self) -> &'a mut W { self.variant(SPI_FRF_A::STD) } #[doc = "Dual-SPI frame format; two bits per SCK, half-duplex"] #[inline(always)] pub fn dual(self) -> &'a mut W { self.variant(SPI_FRF_A::DUAL) } #[doc = "Quad-SPI frame format; four bits per SCK, half-duplex"] #[inline(always)] pub fn quad(self) -> &'a mut W { self.variant(SPI_FRF_A::QUAD) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 21)) | (((value as u32) & 0x03) << 21); self.w } } #[doc = "Reader of field `DFS_32`"] pub type DFS_32_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DFS_32`"] pub struct DFS_32_W<'a> { w: &'a mut W, } impl<'a> DFS_32_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x1f << 16)) | (((value as u32) & 0x1f) << 16); self.w } } #[doc = "Reader of field `CFS`"] pub type CFS_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CFS`"] pub struct CFS_W<'a> { w: &'a mut W, } impl<'a> CFS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 12)) | (((value as u32) & 0x0f) << 12); self.w } } #[doc = "Reader of field `SRL`"] pub type SRL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SRL`"] pub struct SRL_W<'a> { w: &'a mut W, } impl<'a> SRL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `SLV_OE`"] pub type SLV_OE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SLV_OE`"] pub struct SLV_OE_W<'a> { w: &'a mut W, } impl<'a> SLV_OE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Transfer mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum TMOD_A { #[doc = "0: Both transmit and receive"] TX_AND_RX = 0, #[doc = "1: Transmit only (not for FRF == 0, standard SPI mode)"] TX_ONLY = 1, #[doc = "2: Receive only (not for FRF == 0, standard SPI mode)"] RX_ONLY = 2, #[doc = "3: EEPROM read mode (TX then RX; RX starts after control data TX'd)"] EEPROM_READ = 3, } impl From<TMOD_A> for u8 { #[inline(always)] fn from(variant: TMOD_A) -> Self { variant as _ } } #[doc = "Reader of field `TMOD`"] pub type TMOD_R = crate::R<u8, TMOD_A>; impl TMOD_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TMOD_A { match self.bits { 0 => TMOD_A::TX_AND_RX, 1 => TMOD_A::TX_ONLY, 2 => TMOD_A::RX_ONLY, 3 => TMOD_A::EEPROM_READ, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `TX_AND_RX`"] #[inline(always)] pub fn is_tx_and_rx(&self) -> bool { *self == TMOD_A::TX_AND_RX } #[doc = "Checks if the value of the field is `TX_ONLY`"] #[inline(always)] pub fn is_tx_only(&self) -> bool { *self == TMOD_A::TX_ONLY } #[doc = "Checks if the value of the field is `RX_ONLY`"] #[inline(always)] pub fn is_rx_only(&self) -> bool { *self == TMOD_A::RX_ONLY } #[doc = "Checks if the value of the field is `EEPROM_READ`"] #[inline(always)] pub fn is_eeprom_read(&self) -> bool { *self == TMOD_A::EEPROM_READ } } #[doc = "Write proxy for field `TMOD`"] pub struct TMOD_W<'a> { w: &'a mut W, } impl<'a> TMOD_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TMOD_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Both transmit and receive"] #[inline(always)] pub fn tx_and_rx(self) -> &'a mut W { self.variant(TMOD_A::TX_AND_RX) } #[doc = "Transmit only (not for FRF == 0, standard SPI mode)"] #[inline(always)] pub fn tx_only(self) -> &'a mut W { self.variant(TMOD_A::TX_ONLY) } #[doc = "Receive only (not for FRF == 0, standard SPI mode)"] #[inline(always)] pub fn rx_only(self) -> &'a mut W { self.variant(TMOD_A::RX_ONLY) } #[doc = "EEPROM read mode (TX then RX; RX starts after control data TX'd)"] #[inline(always)] pub fn eeprom_read(self) -> &'a mut W { self.variant(TMOD_A::EEPROM_READ) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 8)) | (((value as u32) & 0x03) << 8); self.w } } #[doc = "Reader of field `SCPOL`"] pub type SCPOL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SCPOL`"] pub struct SCPOL_W<'a> { w: &'a mut W, } impl<'a> SCPOL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `SCPH`"] pub type SCPH_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SCPH`"] pub struct SCPH_W<'a> { w: &'a mut W, } impl<'a> SCPH_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `FRF`"] pub type FRF_R = crate::R<u8, u8>; #[doc = "Write proxy for field `FRF`"] pub struct FRF_W<'a> { w: &'a mut W, } impl<'a> FRF_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 4)) | (((value as u32) & 0x03) << 4); self.w } } #[doc = "Reader of field `DFS`"] pub type DFS_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DFS`"] pub struct DFS_W<'a> { w: &'a mut W, } impl<'a> DFS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } impl R { #[doc = "Bit 24 - Slave select toggle enable"] #[inline(always)] pub fn sste(&self) -> SSTE_R { SSTE_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bits 21:22 - SPI frame format"] #[inline(always)] pub fn spi_frf(&self) -> SPI_FRF_R { SPI_FRF_R::new(((self.bits >> 21) & 0x03) as u8) } #[doc = "Bits 16:20 - Data frame size in 32b transfer mode\\n Value of n -> n+1 clocks per frame."] #[inline(always)] pub fn dfs_32(&self) -> DFS_32_R { DFS_32_R::new(((self.bits >> 16) & 0x1f) as u8) } #[doc = "Bits 12:15 - Control frame size\\n Value of n -> n+1 clocks per frame."] #[inline(always)] pub fn cfs(&self) -> CFS_R { CFS_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bit 11 - Shift register loop (test mode)"] #[inline(always)] pub fn srl(&self) -> SRL_R { SRL_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 10 - Slave output enable"] #[inline(always)] pub fn slv_oe(&self) -> SLV_OE_R { SLV_OE_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bits 8:9 - Transfer mode"] #[inline(always)] pub fn tmod(&self) -> TMOD_R { TMOD_R::new(((self.bits >> 8) & 0x03) as u8) } #[doc = "Bit 7 - Serial clock polarity"] #[inline(always)] pub fn scpol(&self) -> SCPOL_R { SCPOL_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 6 - Serial clock phase"] #[inline(always)] pub fn scph(&self) -> SCPH_R { SCPH_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bits 4:5 - Frame format"] #[inline(always)] pub fn frf(&self) -> FRF_R { FRF_R::new(((self.bits >> 4) & 0x03) as u8) } #[doc = "Bits 0:3 - Data frame size"] #[inline(always)] pub fn dfs(&self) -> DFS_R { DFS_R::new((self.bits & 0x0f) as u8) } } impl W { #[doc = "Bit 24 - Slave select toggle enable"] #[inline(always)] pub fn sste(&mut self) -> SSTE_W { SSTE_W { w: self } } #[doc = "Bits 21:22 - SPI frame format"] #[inline(always)] pub fn spi_frf(&mut self) -> SPI_FRF_W { SPI_FRF_W { w: self } } #[doc = "Bits 16:20 - Data frame size in 32b transfer mode\\n Value of n -> n+1 clocks per frame."] #[inline(always)] pub fn dfs_32(&mut self) -> DFS_32_W { DFS_32_W { w: self } } #[doc = "Bits 12:15 - Control frame size\\n Value of n -> n+1 clocks per frame."] #[inline(always)] pub fn cfs(&mut self) -> CFS_W { CFS_W { w: self } } #[doc = "Bit 11 - Shift register loop (test mode)"] #[inline(always)] pub fn srl(&mut self) -> SRL_W { SRL_W { w: self } } #[doc = "Bit 10 - Slave output enable"] #[inline(always)] pub fn slv_oe(&mut self) -> SLV_OE_W { SLV_OE_W { w: self } } #[doc = "Bits 8:9 - Transfer mode"] #[inline(always)] pub fn tmod(&mut self) -> TMOD_W { TMOD_W { w: self } } #[doc = "Bit 7 - Serial clock polarity"] #[inline(always)] pub fn scpol(&mut self) -> SCPOL_W { SCPOL_W { w: self } } #[doc = "Bit 6 - Serial clock phase"] #[inline(always)] pub fn scph(&mut self) -> SCPH_W { SCPH_W { w: self } } #[doc = "Bits 4:5 - Frame format"] #[inline(always)] pub fn frf(&mut self) -> FRF_W { FRF_W { w: self } } #[doc = "Bits 0:3 - Data frame size"] #[inline(always)] pub fn dfs(&mut self) -> DFS_W { DFS_W { w: self } } }
mod context; mod gdt; mod ide; mod idt; mod io; mod mmu; mod pci; mod pic; mod timer; mod tss; /* exposed child definitions */ pub use self::context::Context; use self::idt::IDT; use self::timer::Timer; pub const HEAP_VIRT: u64 = mmu::HEAP_VIRT; pub const HEAP_SIZE: u64 = mmu::HEAP_SIZE; /* exported symbols */ pub use self::context::store_context; pub use self::idt::int_handler; /// Put a string of bytes to serial port pub unsafe fn puts(s: &str) { for b in s.bytes() { putb(b); } } /// Put a byte to serial port pub unsafe fn putb(b: u8) { // Wait for the serial port's fifo to not be empty while (io::inb(0x3F8 + 5) & 0x20) == 0 { // Do nothing } // Send the byte out the serial port io::outb(0x3F8, b); } /// Get a byte from serial port pub unsafe fn getb() -> u8 { while (io::inb(0x3F8 + 5) & 0x1) == 0 { // Do nothing } io::inb(0x3F8) } /// Disable interrupt pub unsafe fn disable_int() { idt::cli(); } /// Enable interrupt pub unsafe fn enable_int() { idt::sti(); } /// Check whether interrupt is enabled pub unsafe fn int_enabled() -> bool { idt::check_int() } /// Breakpoint pub unsafe fn breakpoint() { idt::int3(); } /// Register an ISR handler pub fn register_isr(idx: usize, handler: fn(u64, u64)) -> bool { IDT::get().register_isr(idx, handler) } /// Unregister an ISR handler pub fn unregister_isr(idx: usize) -> bool { IDT::get().unregister_isr(idx) } /// Register a timer handler pub fn register_timer(func: fn(u64)) -> Result<usize, ::common::error::Error> { Timer::get().register_timer(func) } /// Unregister a timer handler pub fn unregister_timer(idx: usize) -> Result<(), ::common::error::Error> { Timer::get().unregister_timer(idx) } /// Register a scheduler pub fn register_scheduler(func: fn(u64)) -> Result<(), ::common::error::Error> { Timer::get().register_scheduler(func) } /// Initialize architecture-related configuration pub fn init() { gdt::init(); tss::init(); idt::init(); pic::init(); mmu::init(); timer::init(); pci::init(); } /// Phase 2 initialization pub fn init2() { ide::init(); } #[cfg(test)] pub fn test() { unsafe { ide::test(); } }
extern crate gui; use gui::*; use math::*; struct TextExample { text_input: TextInput, } impl State for TextExample { fn draw(&mut self, frame: &mut Frame, data: &StateData) { frame.rect() .size(Vec2::new(0.7, 0.2)) .color(color::rgb(0.7, 0.3, 0.2)) .anchor(Anchor::MiddleRight) .pivot(Anchor::MiddleRight) .scaling(true) .draw(); frame.text("assets/test_font.ttf") .position(Vec2::new(-0.1, 0.0)) .scale(0.1) .anchor(Anchor::MiddleRight) .pivot(Anchor::MiddleRight) .scaling(true) .color( if data.key_held(KeyCode::A) { color::rgb(1.0, 1.0, 1.0) } else { color::rgb(0.0, 0.0, 1.0) } ) .text(self.text_input.get_text()) .draw(); } } fn main() { Application::new() .with_title("Text Example") .with_window_size(1000, 800) .run(|loader| { let mut text_input = loader.text_input(); text_input.start(); loader.load_font("assets/test_font.ttf", 100); Box::new(TextExample { text_input, }) }); }
extern crate utils; use std::env; use std::collections::HashSet; use std::collections::VecDeque; use std::io::{self, BufReader}; use std::io::prelude::*; use std::fs::File; use utils::*; type Input = Vec<u64>; #[cfg(test)] const PREAMBLE_SIZE: usize = 5; #[cfg(not(test))] const PREAMBLE_SIZE: usize = 25; fn part1(input: &Input) -> u64 { let mut preamble = VecDeque::new(); for i in 0..PREAMBLE_SIZE { let mut sums = HashSet::with_capacity(PREAMBLE_SIZE); for j in 0..PREAMBLE_SIZE { if i == j { continue; } sums.insert(input[i] + input[j]); } preamble.push_back(sums); } for i in PREAMBLE_SIZE..input.len() { let v = input[i]; if !preamble.iter().any(|sums| sums.contains(&v)) { return v; } preamble.pop_front(); let mut sums = HashSet::with_capacity(PREAMBLE_SIZE); for j in (i - PREAMBLE_SIZE)..i { sums.insert(v + input[j]); } preamble.push_back(sums); } 0 } fn part2(input: &Input, p1: u64) -> u64 { for i in 0..input.len() { let mut sum = 0; let mut min = std::u64::MAX; let mut max = std::u64::MIN; for j in i..input.len() { let v = input[j]; sum += v; min = std::cmp::min(v, min); max = std::cmp::max(v, max); if sum == p1 { return min + max; } else if sum > p1 { break; } } } 0 } fn solve(input: &Input) -> (u64, u64) { let p1 = part1(input); (p1, part2(input, p1)) } fn main() { measure(|| { let input = input().expect("Input failed"); let (part1, part2) = solve(&input); println!("Part1: {}", part1); println!("Part2: {}", part2); }); } fn read_input<R: Read>(reader: BufReader<R>) -> io::Result<Input> { Ok(reader.lines().map(|l| l.unwrap().parse::<u64>().unwrap()).collect()) } fn input() -> io::Result<Input> { let f = File::open(env::args().skip(1).next().expect("No input file given"))?; read_input(BufReader::new(f)) } #[cfg(test)] mod tests { use super::*; const INPUT: &'static str = "35 20 15 25 47 40 62 55 65 95 102 117 150 182 127 219 299 277 309 576"; fn as_input(s: &str) -> Input { read_input(BufReader::new(s.split('\n').map(|s| s.trim()).collect::<Vec<_>>().join("\n").as_bytes())).unwrap() } #[test] fn test_part1() { assert_eq!(solve(&as_input(INPUT)).0, 127); } #[test] fn test_part2() { assert_eq!(solve(&as_input(INPUT)).1, 62); } }
use hex; use std::str::from_utf8; pub fn repeating_key_xor(item: String, key: String) -> String { let mut xor_vec = Vec::new(); let mut index = 0; for i in item.into_bytes().iter() { let xored = key.as_bytes()[index] ^ i; if ((index + 1) == key.as_bytes().len()) { index = 0; } else { index += 1; } xor_vec.push(xored); } let result = hex::encode(xor_vec); result }
use std::collections::HashMap; use std::fmt; #[derive(Debug, Hash, Eq, PartialEq, Clone, PartialOrd)] pub enum Pixel { Black = 0, White = 1, Transparent = 2, } impl Default for Pixel { fn default() -> Self { Pixel::Transparent } } impl From<char> for Pixel { fn from(input: char) -> Self { match input { '0' => Pixel::Black, '1' => Pixel::White, '2' => Pixel::Transparent, _ => panic!("unsupported char {}", input), } } } impl Into<char> for Pixel { fn into(self) -> char { match self { Pixel::Black => '0', Pixel::White => '1', Pixel::Transparent => '2', } } } #[derive(Debug, PartialEq)] pub struct Layer { pub pixels: Vec<Pixel>, pixel_count_map: HashMap<Pixel, usize>, width: usize, height: usize, } impl Layer { pub fn count_pixel(&self, pixel: Pixel) -> usize { self.pixel_count_map .get(&pixel) .cloned() .unwrap_or_default() } } impl Layer { fn new(width: usize, height: usize) -> Self { Layer { pixels: vec![Pixel::default(); width * height], pixel_count_map: HashMap::new(), width, height, } } // fn pretty_format(&self) -> String { // let mut tabbed_layer_string = String::new(); // let layer_string = self.to_string(); // for row in 0..self.height { // let low_bound = row * self.width; // let high_bound = (row + 1) * self.width; // let row_string = &layer_string[low_bound..high_bound]; // tabbed_layer_string.push_str(row_string); // tabbed_layer_string.push_str("\n\t"); // } // tabbed_layer_string // } } impl From<RawImage> for Layer { fn from(raw_image: RawImage) -> Self { let mut pixels_vec = vec![]; let mut pixel_count_map = HashMap::new(); for pixel in raw_image.pixels.chars() { let p = Pixel::from(pixel); pixels_vec.push(p.clone()); match pixel_count_map.remove(&p) { Some(count) => pixel_count_map.insert(p, count + 1), None => pixel_count_map.insert(p, 1), }; } Layer { pixels: pixels_vec, pixel_count_map, width: raw_image.width, height: raw_image.height, } } } impl From<Layers> for Layer { fn from(layers: Layers) -> Self { let widths_and_heights = layers.iter().map(|l| (l.width, l.height)); assert_eq!( widths_and_heights.clone().min(), widths_and_heights.clone().max() ); let mut combined_layer = Layer::new(layers[0].width, layers[0].height); for layer in layers { for (i, layer_pixel) in layer.pixels.iter().enumerate() { match combined_layer.pixels.get_mut(i) { Some(combined_pixel) if combined_pixel == &Pixel::Transparent => { combined_layer.pixels[i] = layer_pixel.clone(); } None => combined_layer.pixels[i] = layer_pixel.clone(), _ => continue, } } } combined_layer } } impl fmt::Display for Layer { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", self.pixels .iter() .map(|p| Into::<char>::into(p.clone())) .collect::<String>() ) } } struct RawImage { pixels: String, width: usize, height: usize, } type Layers = Vec<Layer>; impl From<RawImage> for Layers { fn from(raw_image: RawImage) -> Self { assert_eq!( raw_image.pixels.len() % (raw_image.width * raw_image.height), 0 ); let layer_count = raw_image.pixels.len() / (raw_image.width * raw_image.height); let mut layers: Vec<Layer> = Vec::with_capacity(layer_count); for l in 0..layer_count { let low_bound = raw_image.width * raw_image.height * l; let high_bound = raw_image.width * raw_image.height * (l + 1); layers.push(Layer::from(RawImage { pixels: raw_image.pixels[low_bound..high_bound].to_string(), width: raw_image.width, height: raw_image.height, })) } layers } } #[cfg(test)] mod tests { use super::*; use crate::util; #[test] fn test_advent_puzzle() { let layers: Layers = util::load_input_file("day08.txt") .map(|input: String| { Layers::from(RawImage { pixels: input, width: 25, height: 6, }) }) .unwrap(); let combined = Layer::from(layers); assert_eq!(combined.to_string(), "100100110001100111101111010010100101001010000100001111010000100001110011100100101000010110100001000010010100101001010000100001001001100011101000011110"); } #[test] fn smoke_simple_program_1() { let pixels = String::from("0222112222120000"); let layers = Layers::from(RawImage { pixels, width: 2, height: 2, }); let combined = Layer::from(layers); assert_eq!(combined.to_string(), "0110"); } }
use crate::prelude::*; use crate::{headers::from_headers::*, ResourceQuota}; use azure_core::headers::{content_type_from_headers, session_token_from_headers}; use azure_core::{Request as HttpRequest, Response as HttpResponse}; use chrono::{DateTime, Utc}; #[derive(Debug, Clone)] pub struct DeleteCollectionOptions { consistency_level: Option<ConsistencyLevel>, } impl DeleteCollectionOptions { pub fn new() -> Self { Self { consistency_level: None, } } setters! { consistency_level: ConsistencyLevel => Some(consistency_level), } pub(crate) fn decorate_request(&self, request: &mut HttpRequest) -> crate::Result<()> { azure_core::headers::add_optional_header2(&self.consistency_level, request)?; Ok(()) } } #[derive(Debug, Clone)] pub struct DeleteCollectionResponse { pub last_state_change: DateTime<Utc>, pub resource_quota: Vec<ResourceQuota>, pub resource_usage: Vec<ResourceQuota>, pub collection_partition_index: u64, pub collection_service_index: u64, pub schema_version: String, pub alt_content_path: String, pub quorum_acked_lsn: u64, pub current_write_quorum: u64, pub current_replica_set_size: u64, pub charge: f64, pub service_version: String, pub activity_id: uuid::Uuid, pub session_token: String, pub gateway_version: String, pub cosmos_llsn: u64, pub lsn: u64, pub date: DateTime<Utc>, pub transport_request_id: u64, pub xp_role: u32, pub server: String, pub cosmos_quorum_acked_llsn: u64, pub content_location: String, pub content_type: String, } impl DeleteCollectionResponse { pub async fn try_from(response: HttpResponse) -> crate::Result<Self> { let (_status_code, headers, _pinned_stream) = response.deconstruct(); Ok(Self { last_state_change: last_state_change_from_headers(&headers)?, collection_partition_index: collection_partition_index_from_headers(&headers)?, collection_service_index: collection_service_index_from_headers(&headers)?, schema_version: schema_version_from_headers(&headers)?.to_owned(), alt_content_path: alt_content_path_from_headers(&headers)?.to_owned(), charge: request_charge_from_headers(&headers)?, service_version: service_version_from_headers(&headers)?.to_owned(), activity_id: activity_id_from_headers(&headers)?, session_token: session_token_from_headers(&headers)?, gateway_version: gateway_version_from_headers(&headers)?.to_owned(), cosmos_llsn: cosmos_llsn_from_headers(&headers)?, quorum_acked_lsn: quorum_acked_lsn_from_headers(&headers)?, current_write_quorum: current_write_quorum_from_headers(&headers)?, current_replica_set_size: current_replica_set_size_from_headers(&headers)?, lsn: lsn_from_headers(&headers)?, cosmos_quorum_acked_llsn: cosmos_quorum_acked_llsn_from_headers(&headers)?, server: server_from_headers(&headers)?.to_owned(), xp_role: role_from_headers(&headers)?, content_type: content_type_from_headers(&headers)?.to_owned(), content_location: content_location_from_headers(&headers)?.to_owned(), transport_request_id: transport_request_id_from_headers(&headers)?, date: date_from_headers(&headers)?, resource_quota: resource_quota_from_headers(&headers)?, resource_usage: resource_usage_from_headers(&headers)?, }) } }
use crate::schema::games as schema_games; #[derive(serde_derive::Deserialize, serde_derive::Serialize, Queryable)] pub struct Game { pub id: i32, pub match_id: Option<i32>, pub duel_id: Option<i32>, pub score_1: i32, pub score_2: i32, pub timestamp: chrono::NaiveDateTime, } #[derive(serde_derive::Deserialize)] pub struct GameResult { pub score_1: i32, pub score_2: i32, } #[derive(Insertable)] #[table_name = "schema_games"] pub struct NewGame { pub match_id: Option<i32>, pub duel_id: Option<i32>, pub score_1: i32, pub score_2: i32, } impl NewGame { pub fn new( result: GameResult, match_id: Option<i32>, duel_id: Option<i32>, ) -> NewGame { NewGame { match_id, duel_id, score_1: result.score_1, score_2: result.score_2, } } }
use gotham::router::Router; use gotham::router::builder::build_router; use gotham::router::builder::DrawRoutes; use gotham::router::builder::DefineSingleRoute; use gotham::pipeline::set::{finalize_pipeline_set, new_pipeline_set}; use gotham::pipeline::new_pipeline; use gotham::middleware::session::{NewSessionMiddleware, MemoryBackend}; pub fn new() -> Router { let ps_builder = new_pipeline_set(); let (ps_builder, global) = ps_builder.add(new_pipeline() .add(session_middleware()) .add(oauth_config_middleware()) .build()); let (ps_builder, req_authn) = ps_builder.add(new_pipeline() .add(require_auth_middleware()) .build()); let ps = finalize_pipeline_set(ps_builder); let bare_pipeline = (global, ()); let normal_pipeline = (req_authn, (global, ())); build_router(normal_pipeline, ps, |route| { route.get_or_head("/").to(super::inventory::handler); route.with_pipeline_chain(bare_pipeline, |auth| { auth.get_or_head("/oauth").to(super::oauth_receiver::handler); }); }) } fn session_middleware() -> NewSessionMiddleware<MemoryBackend, super::D2Session> { NewSessionMiddleware::default().with_session_type::<super::D2Session>() } fn oauth_config_middleware() -> super::app_config::New { super::app_config::New {} } fn require_auth_middleware() -> super::require_authn::New { super::require_authn::New {} }
#![allow(unused_imports)] #![allow(unused_variables)] #![allow(unused_mut)] #![allow(dead_code)] use std::collections::HashMap; use std::collections::HashSet; use std::collections::BTreeMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::sync::mpsc::{Sender, Receiver}; use std::sync::mpsc; use std::thread; use std::collections::VecDeque; use std::rc::{Rc, Weak}; use std::sync::Arc; use std::cell::RefCell; use std::mem; use glr_grammar; use glr_lex; use glr_grammar::Atom as Atom; use glr_lex::Lex as Lex; use glr_grammar::GrammarItem as GrammarItem; // #[derive(Debug,Clone,Hash,PartialEq,Eq,PartialOrd,Ord)] // pub enum Atom { // Symbol(Arc<String>), // Terminal(Arc<String>) // } // #[derive(Clone,Debug)] // pub struct GrammarItem { // pub symbol: Arc<Atom>, // pub production: Vec<Arc<Atom>> // } #[derive(Clone,Hash,PartialEq,Eq,Ord,PartialOrd,Debug)] pub struct LRItem { pub stacktop: u8, pub terminal: Arc<Atom>, pub symbol: Arc<Atom>, pub production: Vec<Arc<Atom>> } pub fn create_grammars_hashmap(grammars: Vec<Box<GrammarItem>>) -> HashMap<String, Vec<Arc<GrammarItem>>>{ let mut grammars_hashmap: HashMap<String, Vec<Arc<GrammarItem>>> = HashMap::new(); for item in grammars { let symbol_name = glr_grammar::get_atom_string(item.clone().symbol); if !grammars_hashmap.contains_key(&symbol_name) { grammars_hashmap.insert(symbol_name.clone(), vec![]); } match grammars_hashmap.entry(symbol_name) { Occupied(entry) => { entry.into_mut().push(Arc::new(*item)); }, _ => {} } } grammars_hashmap } fn get_first(grammars_hashmap: &HashMap<String, Vec<Arc<GrammarItem>>>, symbol: Arc<Atom>) -> Vec<Arc<Atom>> { let mut ret: Vec<Arc<Atom>> = vec![]; let mut symbols: Vec<Arc<Atom>> = vec![symbol.clone()]; let mut symbols_expanded: HashSet<Arc<Atom>> = HashSet::new(); loop { let current_symbol = match symbols.pop() {Some(x) => x, None => break}; match *current_symbol { Atom::Symbol(ref x) => { if let Some(grammars) = grammars_hashmap.get(&**x) { for each_grammar in grammars { let mut offsets: Vec<u8> = find_solid_indexes(&grammars_hashmap, &each_grammar.production, 0, vec![0u8]); let offsets_len = offsets.len(); offsets.push(offsets_len as u8); for offset in offsets { if let Some(__symbol) = each_grammar.production.get(offset as usize) { let _symbol = __symbol.clone(); if !symbols_expanded.contains(&_symbol) { symbols.push(_symbol.clone()); symbols_expanded.insert(_symbol); } } } } } }, Atom::Terminal(ref x) => { ret.push(current_symbol.clone()); } } } // println!("first {:?}", (symbol, ret.clone())); ret // match *symbol { // Atom::Symbol(ref x) => { // let mut ret: Vec<&Atom> = vec![]; // match grammars_hashmap.get(x) { // Some(grammars) => { // for each_grammar in grammars { // match each_grammar.production.get(0) { // Some(_symbol) => { // ret.push_all(&get_first(grammars_hashmap, _symbol)); // }, // None => {} // } // } // }, // None => {} // } // ret // }, // Atom::Terminal(ref x) => { // vec![symbol] // } // } } // fn contains_lr_item(list: &Vec<LRItem>, x: &LRItem) -> bool { // for item in list.iter() { // if item.stacktop != x.stacktop { continue } // if item.terminal != x.terminal { continue } // if item.symbol != x.symbol { continue } // if !equal_atom_vec(&item.production, &x.production) { continue } // return true; // } // false // } // fn contains_lr_item(list: Vec<Arc<LRItem>>, x: Arc<LRItem>) -> bool { // for item in list.iter() { // if item.stacktop != x.stacktop { continue } // if item.terminal != x.terminal { continue } // if item.symbol != x.symbol { continue } // if !equal_atom_vec(&item.production, &x.production) { continue } // return true; // } // false // } fn get_real_productions(grammars_hashmap: &HashMap<String, Vec<Arc<GrammarItem>>>, production: &Vec<Arc<Atom>>, mut real_prod_cache: &mut HashMap<Vec<Arc<Atom>>, Vec<Vec<Arc<Atom>>>>) -> Vec<Vec<Arc<Atom>>> { match real_prod_cache.entry(production.clone()) { Occupied(entry) => { entry.get().clone() }, Vacant(entry) => { let mut ret: Vec<Vec<Arc<Atom>>> = vec![vec![]]; for item in production.iter() { let mut split = false; match **item { Atom::Symbol(ref x) => { if let Some(atom_str) = x.find('~') { if let Some(grammar_items) = grammars_hashmap.get(&**x) { for item in grammar_items { if item.production.len() == 0 { split = true; break; } } } } }, Atom::Terminal(ref x) => {} } if !split { for each_ret in &mut ret { each_ret.push(item.clone()); } } else { let mut ret_extend: Vec<Vec<Arc<Atom>>> = vec![]; for each_ret in ret.iter() { ret_extend.push(each_ret.clone()); } for each_ret in &mut ret { each_ret.push(item.clone()); } ret.extend(ret_extend); } } entry.insert(ret.clone()); ret } } } fn find_solid_indexes(grammars_hashmap: &HashMap<String, Vec<Arc<GrammarItem>>>, production: &Vec<Arc<Atom>>, start_index: u8, initial_offset: Vec<u8>) -> Vec<u8>{ let initial_len: u8 = match initial_offset.get(0) {Some(x) => *x, None => 0}; let mut offsets: Vec<u8> = initial_offset; loop { let mut break_loop = true; if let Some(atom) = production.get((start_index + offsets.len() as u8) as usize) { match **atom { Atom::Symbol(ref x) => { if let Some(grammar_items) = grammars_hashmap.get(&**x) { for item in grammar_items { if item.production.len() == 0 { let len = offsets.len(); offsets.push(len as u8 + initial_len); break_loop = false; break; } } } }, Atom::Terminal(_) => {} } } if break_loop {break} } return offsets; } fn get_closure(grammars_hashmap: &HashMap<String, Vec<Arc<GrammarItem>>>, initial_items: Vec<Arc<LRItem>>, mut firsts: &mut HashMap<Arc<String>, Vec<Arc<Atom>>>, mut real_prod_cache: &mut HashMap<Vec<Arc<Atom>>, Vec<Vec<Arc<Atom>>>>) -> Vec<Arc<LRItem>> { let mut ret: Vec<Arc<LRItem>> = Vec::new(); let mut ret_cache: HashSet<Arc<LRItem>> = HashSet::new(); // println!("initial_items {:?}", initial_items.clone()); let mut working_items = initial_items; loop { let mut loop_item = match working_items.pop() {Some(x) => x, None => break}; if !ret_cache.contains(&loop_item) { let new_lr_item = Arc::new(LRItem { stacktop: loop_item.stacktop, terminal: loop_item.terminal.clone(), symbol: loop_item.symbol.clone(), production: loop_item.production.clone() }); ret.push(new_lr_item.clone()); ret_cache.insert(new_lr_item); } // watch_lr_item(&loop_item, "loop item"); let mut terminals: Vec<Arc<Atom>> = vec![]; let mut offsets: Vec<u8> = find_solid_indexes(&grammars_hashmap, &loop_item.production, loop_item.stacktop, vec![1u8]); for stacktop_offset in offsets { terminals.extend(match loop_item.production.get((loop_item.stacktop + stacktop_offset) as usize) { Some(atom) => { let atom_string = match **atom {Atom::Symbol(ref x) => x, Atom::Terminal(ref x) => x}; match firsts.entry(atom_string.clone()) { Occupied(entry) => { let mut _ret: Vec<Arc<Atom>> = vec![]; for item in entry.into_mut().iter() { _ret.push(item.clone()); } _ret }, Vacant(entry) => { let new_first = get_first(grammars_hashmap, atom.clone()); let mut atoms: Vec<Arc<Atom>> = Vec::new(); for item in new_first.iter() { atoms.push(item.clone()); } entry.insert(atoms); new_first } } }, None => vec![loop_item.terminal.clone()] }); } let expand_symbol = match loop_item.production.get(loop_item.stacktop as usize) { Some(atom) => { atom }, None => continue }; let symbol_name = glr_grammar::get_atom_string(expand_symbol.clone()); match grammars_hashmap.get(&symbol_name) { Some(grammer_items) => { for each_grammar in grammer_items.iter() { for each_production in get_real_productions(&grammars_hashmap, &each_grammar.production, &mut real_prod_cache).iter() { for terminal_atom in terminals.iter() { let lr_item = Arc::new(LRItem { stacktop: 0, terminal: terminal_atom.clone(), symbol: each_grammar.symbol.clone(), production: each_production.clone() }); if !ret_cache.contains(&lr_item) { working_items.push(lr_item); } } } } }, None => {} } } ret } // fn clone_atom(x: &Atom) -> Atom { // match *x { // Atom::Symbol(ref x) => Atom::Symbol(x.clone()), // Atom::Terminal(ref x) => Atom::Terminal(x.clone()) // } // } // fn equal_atom_vec(iters1: &Vec<Atom>, iters2: &Vec<Atom>) -> bool { // if iters1.len() != iters2.len() { return false; } // for index in 0..iters1.len(){ // if iters1[index] != iters2[index] { // return false; // } // } // true // } // fn equal_cc(cc1: &Vec<LRItem>, cc2: &Vec<LRItem>) -> bool { // if cc1.len() != cc2.len() { return false } // for item in cc2.iter() { // if !contains_lr_item(cc1, item) { // return false; // } // } // true // } fn goto(grammars_hashmap: &HashMap<String, Vec<Arc<GrammarItem>>>, cc: &Vec<Arc<LRItem>>, goto_atom: Arc<Atom>, mut firsts: &mut HashMap<Arc<String>, Vec<Arc<Atom>>>, goto_cache: &mut HashMap<Vec<Arc<LRItem>>, Vec<Arc<LRItem>>>, mut real_prod_cache: &mut HashMap<Vec<Arc<Atom>>, Vec<Vec<Arc<Atom>>>>) -> Vec<Arc<LRItem>>{ let mut ret: Vec<Arc<LRItem>> = Vec::new(); // let goto_pattern = match goto_atom { Atom::Symbol(x) => ("S", x), Atom::Terminal(x) => ("T", x)}; for item in cc.iter() { match item.production.get(item.stacktop as usize) { None => {}, Some(x) => { // let x_pattern = match *x { Atom::Symbol(x) => ("S", x), Atom::Terminal(x) => ("T", x)}; if *x == goto_atom { ret.push(Arc::new(LRItem { stacktop: item.stacktop + 1u8, symbol: item.symbol.clone(), terminal: item.terminal.clone(), production: item.production.clone() })); } } } } // watch_lr_list(&ret, "before closure"); match goto_cache.entry(ret.clone()) { Occupied(entry) => { entry.get().clone() }, Vacant(entry) => { ret = get_closure(&grammars_hashmap, ret, &mut firsts, &mut real_prod_cache); ret.sort_by(|a, b| b.cmp(a)); entry.insert(ret.clone()); ret } } } // fn convert_hashset_to_vec(set: &mut HashSet<Arc<LRItem>>) -> Vec<Arc<LRItem>> { // let mut ret: BTreeMap<Arc<LRItem>, u8> = BTreeMap::new(); // for item in set.drain() { // ret.insert(item, 0); // } // ret.into_iter().map(|(k, v)| k).collect() // } #[derive(Debug,Clone,Hash,PartialEq,Eq,PartialOrd,Ord)] pub enum Action { Reduce, Shift } #[derive(Debug,Clone,Hash,PartialEq,Eq,PartialOrd,Ord)] pub struct TableItem { state: u32, lr_item: Option<Arc<GrammarItem>>, action: Arc<Action> } pub fn create_table(grammars_hashmap: &HashMap<String, Vec<Arc<GrammarItem>>>, initial_item: Arc<LRItem>) -> (Vec<HashMap<String, HashSet<Arc<TableItem>>>>, Vec<HashMap<String, u32>>) { let mut firsts: HashMap<Arc<String>, Vec<Arc<Atom>>> = HashMap::new(); let mut goto_cache: HashMap<Vec<Arc<LRItem>>, Vec<Arc<LRItem>>> = HashMap::new(); let mut real_prod_cache: HashMap<Vec<Arc<Atom>>, Vec<Vec<Arc<Atom>>>> = HashMap::new(); let mut action_table: Vec<HashMap<String, HashSet<Arc<TableItem>>>> = Vec::new(); let mut goto_table: Vec<HashMap<String, u32>> = Vec::new(); let mut cc0 = get_closure(&grammars_hashmap, vec![initial_item], &mut firsts, &mut real_prod_cache); cc0.sort_by(|a, b| b.cmp(a)); let mut working_ccs: Vec<Vec<Arc<LRItem>>> = Vec::new(); let mut working_ccs_hashmap: HashMap<Vec<Arc<LRItem>>, u32> = HashMap::new(); working_ccs.push(cc0.clone()); working_ccs_hashmap.insert(cc0, 0); let mut cc_index = 0u32; let mut cc_to_append: Vec<Vec<Arc<LRItem>>> = Vec::new(); loop { let mut _append_count = 0u32; for item in cc_to_append.iter() { working_ccs.push(item.clone()); working_ccs_hashmap.insert(item.clone(), working_ccs.len() as u32 - 1); } cc_to_append.clear(); let mut loop_cc = match working_ccs.get(cc_index as usize) { Some(x) => x, None => break }; let mut new_action: HashMap<String, HashSet<Arc<TableItem>>> = HashMap::new(); let mut new_goto: HashMap<String, u32> = HashMap::new(); let mut next_cache: HashSet<Arc<Atom>> = HashSet::new(); // println!("{:?}", (loop_cc.len(), working_ccs.len() - cc_index as usize)); for item in loop_cc.iter() { let _state: u32 = working_ccs.len() as u32 + cc_to_append.len() as u32; match item.production.get(item.stacktop as usize) { None => { // Reduce arm match *item.terminal { Atom::Symbol(ref x) => {}, Atom::Terminal(ref x) => { let new_action_item = Arc::new(TableItem {state: 0, action: Arc::new(Action::Reduce), lr_item: Some(Arc::new(GrammarItem { symbol: item.symbol.clone(), production: item.production.clone() }))}); match new_action.entry((&x).to_string()) { Occupied(entry) => { if item.production.len() > 0 { let mut m_entry = entry.into_mut(); if !m_entry.contains(&new_action_item) { m_entry.insert(new_action_item); } } }, Vacant(entry) => { let mut _new_set = HashSet::new(); _new_set.insert(new_action_item); entry.insert(_new_set); } } } } }, Some(x) => { // Shift arm if next_cache.contains(x) { continue } else { next_cache.insert(x.clone()); } // let mut to_new_cc_list: Vec<Arc<Atom>> = vec![x.clone()]; // let mut firsts: Vec<Arc<Atom>> = vec![]; // if let Atom::Symbol(ref x_str) = **x { // match x_str.find('~') { // Some(_) => { // firsts = get_first(&grammars_hashmap, x.clone()); // }, // None => {} // } // } // for x in to_new_cc_list.iter() { // println!("firsts {:?}", (x.clone(), get_first(&grammars_hashmap, x.clone()))); let mut new_cc = goto(&grammars_hashmap, &loop_cc, x.clone(), &mut firsts, &mut goto_cache, &mut real_prod_cache); if let Some(index) = working_ccs_hashmap.get(&new_cc) { match **x { Atom::Symbol(ref x) => { new_goto.insert((&x).to_string(), *index); // for first in firsts.iter(){ // if let Atom::Terminal(ref x_str) = **first { // println!("cached symbol first {:?}", (&x_str).to_string()); // let new_action_item = Arc::new(TableItem {state: *index, action: Arc::new(action_table::Shift), lr_item: None}); // match new_action.entry((&x_str).to_string()) { // Occupied(entry) => { // // entry.into_mut().insert(new_action_item); // }, // Vacant(entry) => { // let mut _new_set = HashSet::new(); // _new_set.insert(new_action_item); // entry.insert(_new_set); // } // } // } // } }, Atom::Terminal(ref x) => { let new_action_item = Arc::new(TableItem {state: *index, action: Arc::new(Action::Shift), lr_item: None}); match new_action.entry((&x).to_string()) { Occupied(entry) => { let mut m_entry = entry.into_mut(); if !m_entry.contains(&new_action_item) { m_entry.insert(new_action_item); } }, Vacant(entry) => { let mut _new_set = HashSet::new(); _new_set.insert(new_action_item); entry.insert(_new_set); } } } } } else { cc_to_append.push(new_cc); match **x { Atom::Symbol(ref x) => { new_goto.insert((&x).to_string(), _state); // for first in firsts.iter(){ // if let Atom::Terminal(ref x_str) = **first { // println!("new symbol first {:?}", (&x_str).to_string()); // let new_action_item = Arc::new(TableItem {state: _state, action: Arc::new(action_table::Shift), lr_item: None}); // match new_action.entry((&x).to_string()) { // Occupied(entry) => { // let mut m_entry = entry.into_mut(); // if !m_entry.contains(&new_action_item) { // m_entry.insert(new_action_item); // } // }, // Vacant(entry) => { // let mut new_cc = goto(&grammars_hashmap, &loop_cc, first.clone(), &mut firsts, &mut goto_cache); // let mut _new_set = HashSet::new(); // _new_set.insert(new_action_item); // entry.insert(_new_set); // if working_ccs_hashmap.get(&new_cc) == None { // cc_to_append.push(new_cc); // } // } // } // } // } }, Atom::Terminal(ref x) => { let new_action_item = Arc::new(TableItem {state: _state, action: Arc::new(Action::Shift), lr_item: None}); match new_action.entry((&x).to_string()) { Occupied(entry) => { let mut m_entry = entry.into_mut(); if !m_entry.contains(&new_action_item) { m_entry.insert(new_action_item); } }, Vacant(entry) => { let mut _new_set = HashSet::new(); _new_set.insert(new_action_item); entry.insert(_new_set); } } } } } // } } } } // println!("action {:?}", new_action); action_table.push(new_action); goto_table.push(new_goto); cc_index += 1; } (action_table, goto_table) } #[derive(Debug,Clone)] pub struct SyntaxTreeNode { pub value: Option<Arc<String>>, pub symbol: Arc<String>, // pub parent: Option<Weak<RefCell<SyntaxTreeNode>>>, pub children: Option<VecDeque<Box<SyntaxTreeNode>>> } impl Drop for SyntaxTreeNode { fn drop(&mut self) { let mut childrens: Vec<Option<VecDeque<Box<SyntaxTreeNode>>>> = vec![mem::replace(&mut self.children, None)]; loop { match childrens.pop() { Some(n) => { match n { Some(mut x) => { for item in x { let mut _item = item; childrens.push(mem::replace(&mut _item.children, None)); } }, None => {} } }, None => break } } } } struct StateStackMark(*mut HashSet<Vec<u32>>); unsafe impl Send for StateStackMark{} pub fn parse(words: Vec<Arc<Lex>>, action: Vec<HashMap<String, HashSet<Arc<TableItem>>>>, goto: Vec<HashMap<String, u32>>) -> Vec<VecDeque<Box<SyntaxTreeNode>>>{ fn _parse(words: Vec<Arc<Lex>>, action: Vec<HashMap<String, HashSet<Arc<TableItem>>>>, goto: Vec<HashMap<String, u32>>, tree_stack: VecDeque<Box<SyntaxTreeNode>>, state_stack: Vec<u32>, word_stack: Vec<Arc<String>>, word_index: u32, curr_lex: Arc<Lex>, curr_word: Arc<String>, curr_value: Option<Arc<String>>, state: u32, cut_count: Vec<u32>, _table_items: Option<HashSet<Arc<TableItem>>>, state_stack_mark: HashSet<Vec<u32>>) -> Vec<VecDeque<Box<SyntaxTreeNode>>>{ let mut tree_stack = tree_stack; let mut state_stack = state_stack; let mut word_stack = word_stack; let mut word_index = word_index; let mut curr_lex = curr_lex; let mut curr_word = curr_word; let mut curr_value =curr_value; let mut state = state; let mut cut_count = cut_count; let mut _table_items = _table_items; let mut state_stack_mark = state_stack_mark; let mut paralle_trees: Vec<VecDeque<Box<SyntaxTreeNode>>> = Vec::new(); // if state_stack_mark.contains(&state_stack) { // println!("contains {:?}", state_stack_mark); // return paralle_trees; // } else { // state_stack_mark.insert(state_stack.clone()); // } let (tx, rx): (Sender<Vec<VecDeque<Box<SyntaxTreeNode>>>>, Receiver<Vec<VecDeque<Box<SyntaxTreeNode>>>>) = mpsc::channel(); let mut spawn_count = 0u32; loop { if let Some(ref table_items) = _table_items { if table_items.len() > 1 { // println!("split talbe items {:?}", table_items); // println!("stack {:?}", (state_stack.clone(), word_stack.clone())); for table_item in table_items.iter() { let __words = words.clone(); let __action = action.clone(); let __goto = goto.clone(); let __tree_stack = tree_stack.clone(); let __state_stack = state_stack.clone(); let __word_stack = word_stack.clone(); let __word_index = word_index.clone(); let __curr_lex = curr_lex.clone(); let __curr_word = curr_word.clone(); let __curr_value =curr_value.clone(); let __state = state.clone(); let __cut_count = cut_count.clone(); let mut __table_item = HashSet::new(); __table_item.insert(table_item.clone()); let __state_stack_mark = state_stack_mark.clone(); let thread_tx = tx.clone(); spawn_count += 1; thread::spawn(move || { thread_tx.send(_parse( __words, __action, __goto, __tree_stack, __state_stack, __word_stack, __word_index, __curr_lex, __curr_word, __curr_value, __state, __cut_count, Some(__table_item), __state_stack_mark )).unwrap(); }); } break; } else { // println!(">>>>>>>>{:?}", word_stack); // println!("<<<<<<<<<{:?}", state_stack); // println!(">>>>>>>>current {:?}", curr_word); let mut table_item = Arc::new(TableItem {state: 0u32, lr_item: None, action: Arc::new(Action::Reduce)}); for item in table_items.iter() { table_item = item.clone(); break; } let _state = table_item.state; let op_lr_item = table_item.lr_item.clone(); let _action = table_item.action.clone(); match *_action { Action::Reduce => { match op_lr_item { Some(_lr_item) =>{ let symbol = glr_grammar::get_atom_string(_lr_item.symbol.clone()); let mut _cut_count = 0u32; for item in _lr_item.production.iter() { state_stack.pop(); word_stack.pop(); let _symbol = match **item {Atom::Symbol(ref x) => &***x, Atom::Terminal(ref x) => ""}; match _symbol.find('~') { None => { _cut_count += 1; }, _ => { if let Some(x) = cut_count.pop() { _cut_count += x; } } } } match symbol.find('~') { Some(_) => { cut_count.push(_cut_count); }, None => { let mut new_tree_node = Box::new(SyntaxTreeNode {value: None, symbol: match *_lr_item.symbol {Atom::Symbol(ref x) => x.clone(), Atom::Terminal(ref x) => x.clone()}, children: None}); let mut tree_node_children: VecDeque<Box<SyntaxTreeNode>> = VecDeque::new(); for i in 0.._cut_count as usize { match tree_stack.pop_back() {Some(mut x) => { // x.parent = Some(new_tree_node.downgrade()); tree_node_children.push_front(x); }, None => {}} } new_tree_node.children = Some(tree_node_children); tree_stack.push_back(new_tree_node); } } state = match state_stack.get(state_stack.len() - 1) {Some(x) => *x, None => break}; word_stack.push(match *_lr_item.symbol {Atom::Symbol(ref x) => x.clone(), Atom::Terminal(ref x) => x.clone()}); state_stack.push(match goto.get(state as usize) {Some(x) => match x.get(&symbol) {Some(x) => *x, None => 0}, None => 0}); }, None => {} } }, Action::Shift => { tree_stack.push_back(Box::new(SyntaxTreeNode {value: curr_value, symbol: curr_word.clone(), children: None})); word_stack.push(curr_word); state_stack.push(_state); curr_lex = match words.get(word_index as usize) {Some(x) => x.clone(), None => break}; curr_word = match *curr_lex.atom {Atom::Symbol(ref x) => x.clone(), Atom::Terminal(ref x) => x.clone()}; curr_value = curr_lex.value.clone(); word_index += 1; } } } } state = match state_stack.get(state_stack.len() - 1) {Some(x) => *x, None => break}; _table_items = match action.get(state as usize) { Some(x) => { match x.get(&**curr_word) {Some(x) => Some(x.clone()), None => { // println!("break action inner word {:?}", (state, &**curr_word, x.clone())); break } } }, None => break }; } // paralle_trees.push(if tree_stack.len() > 1 {VecDeque::new()} else {tree_stack}); paralle_trees.push(tree_stack); for _ in 0..spawn_count { paralle_trees.extend(rx.recv().unwrap()); } paralle_trees } let mut tree_stack: VecDeque<Box<SyntaxTreeNode>> = VecDeque::new(); let mut state_stack: Vec<u32> = Vec::new(); let mut word_stack: Vec<Arc<String>> = Vec::new(); state_stack.push(0); let mut word_index = 1u32; let mut curr_lex = match words.get(0) {Some(x) => x.clone(), None => Arc::new(Lex {value: None, atom: Arc::new(Atom::Terminal(Arc::new("".to_string())))})}; let mut curr_word = match *curr_lex.atom {Atom::Symbol(ref x) => x.clone(), Atom::Terminal(ref x) => x.clone()}; let mut curr_value = curr_lex.value.clone(); let mut cut_count: Vec<u32> = Vec::new(); let mut _table_items = None; let mut state = 0u32; // let mut state_stack_mark: StateStackMark = StateStackMark(&mut HashSet::new()); let mut state_stack_mark: HashSet<Vec<u32>> = HashSet::new(); _parse( words, action, goto, tree_stack, state_stack, word_stack, word_index, curr_lex, curr_word, curr_value, state, cut_count, _table_items, state_stack_mark ) } // fn main(){ // }
#[allow(unused_variables)] fn main() { println!("Hello, world!"); another_function(); parameter_function(5); two_parameters(10, 20); // error - let is a statement, not an expression, so it does not return anything //let x = (let y = 6); // A scope IS an expression let x = 5; let y = { let x = 3; x + 1 }; println!("The value of y is {}", y); let x = five(); println!("The value of x is: {}", x); } fn five() -> i32 { 5 } fn another_function() { println!("Another function!"); } fn parameter_function(x: i32) { println!("The value of x is {}", x); } fn two_parameters(x: i32, y: i32) { println!("The value of x is {}", x); println!("The value of y is {}", y); }
use middle::middle::*; use mangle::Mangle; use ast::name::Symbol; use code::{emit_expression, sizeof_ty, size_name, short_size_name, eax_lo}; use context::Context; use descriptors::{emit_descriptor, emit_primitive_descriptors}; use method::emit_method; use ref_alloc::emit_class_allocator; use stack::Stack; use strings::output_string_constants; fn emit_static_field_initializer<'a, 'ast>(ctx: &Context<'a, 'ast>, stack: &Stack, field: FieldRef<'a, 'ast>) { assert!(field.is_static()); if let Some(ref initializer) = *field.initializer { let target = field.mangle(); let field_size = sizeof_ty(&field.ty); emit!("" ; "emit field initializer {}", field.fq_name); emit_expression(ctx, stack, initializer); emit!("mov {} [{}], {}", size_name(field_size), target, eax_lo(field_size)); } } fn emit_entry_point<'a, 'ast>(ctx: &Context<'a, 'ast>, universe: &Universe<'a, 'ast>, method: MethodImplRef<'a, 'ast>) { emit!("section .text" ; "begin entry point"); emit!("global _start"); emit!("_start:"); emit!("; emit static field initializers"); let stack = Stack::new(&[], false); universe.each_type(|tydef| { for field in tydef.static_fields().iter() { emit_static_field_initializer(ctx, &stack, *field); } }); emit!("; end emit static field initializers\n"); emit!("call {}", method.mangle() ; "begin program"); emit!("mov ebx, eax" ; "exit code in eax"); emit!("mov eax, 1" ; "sys_exit"); emit!("int 80h" ; "syscall"); emit!(""); } fn emit_type<'a, 'ast>(ctx: &Context<'a, 'ast>, tydef: TypeDefinitionRef<'a, 'ast>) { // Emit type descriptors. emit_descriptor(ctx, tydef); if tydef.kind == TypeKind::Class { emit_class_allocator(ctx, tydef); } // Emit slots for static fields. emit!("section .data" ; "begin static field slots"); for field in tydef.static_fields().iter() { let field_size = sizeof_ty(&field.ty); emit!("{}: d{} 0", field.mangle(), short_size_name(field_size)); } emit!("; end static field slots\n"); for method in tydef.method_impls.iter() { emit_method(ctx, *method); } } pub fn emit(universe: &Universe) { let entry_fn = if let Some(&method) = universe.main.methods.get(&MethodSignature { name: Symbol::from_str("test"), args: vec![], }) { let span = if let Some(ast) = method.ast { ast.span } else { universe.main.ast.span }; if !method.is_static { span_fatal!(span, "method `test()` must be static"); } if let Type::SimpleType(SimpleType::Int) = method.ret_ty { } else { span_fatal!(span, "method `test()` must return `int`"); } if let Concrete(method_impl) = method.impled { method_impl } else { panic!("abstract static method?") } } else { span_fatal!(universe.main.ast.span, "missing `static int test()`"); }; let emit_ctx = Context::create(universe); emit!("; vim: ft=nasm"); emit!("extern __exception"); emit!("extern __malloc"); emit!(""); emit!(r"section .text __true: mov eax, 1 ret __false: mov eax, 0 ret ; expression in `eax`, type descriptor in `ebx` ; returns a bool in `eax` __instanceof: test eax, eax jz __false ; null is never instanceof anything mov eax, [eax+VPTR] ; look up type descriptor ; fall into __instanceof_tydesc... ; tydesc in `eax` and `ebx`. ; is `eax` a subtype of `ebx`? __instanceof_tydesc: test ebx, 04h ; is it actually an interface descriptor? jnz __instanceof_tydesc_interface .loop: test eax, eax jz __false cmp eax, ebx je __true mov eax, [eax+TYDESC.parent] ; parent tydesc jmp .loop ; array expression in `eax`, type descriptor in `ebx` __instanceof_array: test eax, eax jz __false ; null is never instanceof anything cmp dword [eax+VPTR], ARRAYDESC ; check array type descriptor jne __false mov eax, [eax+ARRAYLAYOUT.tydesc] ; look up element type descriptor jmp __instanceof_tydesc ; array expression in `eax`, interface type descriptor in `ebx` __instanceof_array_interface: test eax, eax jz __false ; null is never instanceof anything cmp dword [eax+VPTR], ARRAYDESC ; check array type descriptor jne __false mov eax, [eax+ARRAYLAYOUT.tydesc] ; look up element type descriptor jmp __instanceof_tydesc_interface ; object in `eax`, interface descriptor in `ebx` __instanceof_interface: test eax, eax jz __false ; null is never instanceof anything mov eax, [eax+VPTR] ; look up type descriptor ; fall into __instanceof_tydesc_interface __instanceof_tydesc_interface: mov eax, [eax+TYDESC.intfs] ; look up interface list test eax, eax ; list might be null (in the case of a primitive type) jz __false .loop: cmp [eax], dword 0 jz __false cmp [eax], ebx je __true add eax, 4 jmp .loop "); emit_primitive_descriptors(&emit_ctx); universe.each_type(|tydef| { emit_type(&emit_ctx, tydef); }); emit_entry_point(&emit_ctx, universe, entry_fn); output_string_constants(&emit_ctx.string_constants); }
use crate::math::vector::Vector2; #[derive(Copy, Clone)] pub struct Wall { pub a: Vector2, pub b: Vector2, pub normal: Vector2, pub texture: i32, pub floor: f32, pub ceiling: f32, pub u: f32, pub v: f32, pub s: f32, pub t: f32, } impl Wall { pub fn new(a: Vector2, b: Vector2, texture: i32) -> Self { Wall { a, b, normal: a.normal(b), texture, floor: 0.0, ceiling: 0.0, u: 0.0, v: 0.0, s: 0.0, t: 0.0, } } pub fn update(&mut self, floor: f32, ceiling: f32, u: f32, v: f32, s: f32, t: f32) { self.floor = floor; self.ceiling = ceiling; self.u = u; self.v = v; self.s = s; self.t = t; } }
use crate::prelude::*; use std::marker::PhantomData; use syntax::source_map::FileName; use gimli::write::{ Address, AttributeValue, DwarfUnit, EndianVec, FileId, LineProgram, LineString, LineStringTable, Range, RangeList, Result, Sections, UnitEntryId, Writer, }; use gimli::{Encoding, Format, LineEncoding, RunTimeEndian, SectionId}; use faerie::*; fn target_endian(tcx: TyCtxt) -> RunTimeEndian { use rustc::ty::layout::Endian; match tcx.data_layout.endian { Endian::Big => RunTimeEndian::Big, Endian::Little => RunTimeEndian::Little, } } fn line_program_add_file( line_program: &mut LineProgram, line_strings: &mut LineStringTable, file: &FileName, ) -> FileId { match file { FileName::Real(path) => { let dir_name = path.parent().unwrap().to_str().unwrap().as_bytes(); let dir_id = if !dir_name.is_empty() { let dir_name = LineString::new(dir_name, line_program.encoding(), line_strings); line_program.add_directory(dir_name) } else { line_program.default_directory() }; let file_name = LineString::new( path.file_name().unwrap().to_str().unwrap().as_bytes(), line_program.encoding(), line_strings, ); line_program.add_file(file_name, dir_id, None) } // FIXME give more appropriate file names _ => { let dir_id = line_program.default_directory(); let dummy_file_name = LineString::new( file.to_string().into_bytes(), line_program.encoding(), line_strings, ); line_program.add_file(dummy_file_name, dir_id, None) } } } #[derive(Clone)] struct DebugReloc { offset: u32, size: u8, name: DebugRelocName, addend: i64, } #[derive(Clone)] enum DebugRelocName { Section(SectionId), Symbol(usize), } impl DebugReloc { fn name<'a>(&self, ctx: &'a DebugContext) -> &'a str { match self.name { DebugRelocName::Section(id) => id.name(), DebugRelocName::Symbol(index) => ctx.symbols.get_index(index).unwrap(), } } } pub struct DebugContext<'tcx> { endian: RunTimeEndian, symbols: indexmap::IndexSet<String>, dwarf: DwarfUnit, unit_range_list: RangeList, _dummy: PhantomData<&'tcx ()>, } impl<'tcx> DebugContext<'tcx> { pub fn new(tcx: TyCtxt<'tcx>, address_size: u8) -> Self { let encoding = Encoding { format: Format::Dwarf32, // TODO: this should be configurable // macOS doesn't seem to support DWARF > 3 version: 3, address_size, }; let mut dwarf = DwarfUnit::new(encoding); // FIXME: how to get version when building out of tree? // Normally this would use option_env!("CFG_VERSION"). let producer = format!("cranelift fn (rustc version {})", "unknown version"); let comp_dir = tcx.sess.working_dir.0.to_string_lossy().into_owned(); let name = match tcx.sess.local_crate_source_file { Some(ref path) => path.to_string_lossy().into_owned(), None => tcx.crate_name(LOCAL_CRATE).to_string(), }; let line_program = LineProgram::new( encoding, LineEncoding::default(), LineString::new(comp_dir.as_bytes(), encoding, &mut dwarf.line_strings), LineString::new(name.as_bytes(), encoding, &mut dwarf.line_strings), None, ); dwarf.unit.line_program = line_program; { let name = dwarf.strings.add(&*name); let comp_dir = dwarf.strings.add(&*comp_dir); let root = dwarf.unit.root(); let root = dwarf.unit.get_mut(root); root.set( gimli::DW_AT_producer, AttributeValue::StringRef(dwarf.strings.add(producer)), ); root.set( gimli::DW_AT_language, AttributeValue::Language(gimli::DW_LANG_Rust), ); root.set(gimli::DW_AT_name, AttributeValue::StringRef(name)); root.set(gimli::DW_AT_comp_dir, AttributeValue::StringRef(comp_dir)); root.set( gimli::DW_AT_low_pc, AttributeValue::Address(Address::Constant(0)), ); } DebugContext { endian: target_endian(tcx), symbols: indexmap::IndexSet::new(), dwarf, unit_range_list: RangeList(Vec::new()), _dummy: PhantomData, } } fn emit_location(&mut self, tcx: TyCtxt<'tcx>, entry_id: UnitEntryId, span: Span) { let loc = tcx.sess.source_map().lookup_char_pos(span.lo()); let file_id = line_program_add_file( &mut self.dwarf.unit.line_program, &mut self.dwarf.line_strings, &loc.file.name, ); let entry = self.dwarf.unit.get_mut(entry_id); entry.set( gimli::DW_AT_decl_file, AttributeValue::FileIndex(Some(file_id)), ); entry.set( gimli::DW_AT_decl_line, AttributeValue::Udata(loc.line as u64), ); // FIXME: probably omit this entry.set( gimli::DW_AT_decl_column, AttributeValue::Udata(loc.col.to_usize() as u64), ); } pub fn emit(&mut self, artifact: &mut Artifact) { let unit_range_list_id = self.dwarf.unit.ranges.add(self.unit_range_list.clone()); let root = self.dwarf.unit.root(); let root = self.dwarf.unit.get_mut(root); root.set( gimli::DW_AT_ranges, AttributeValue::RangeListRef(unit_range_list_id), ); let mut sections = Sections::new(WriterRelocate::new(self)); self.dwarf.write(&mut sections).unwrap(); let _: Result<()> = sections.for_each_mut(|id, section| { if !section.writer.slice().is_empty() { artifact .declare_with( id.name(), Decl::section(SectionKind::Debug), section.writer.take(), ) .unwrap(); } Ok(()) }); let _: Result<()> = sections.for_each(|id, section| { for reloc in &section.relocs { artifact .link_with( faerie::Link { from: id.name(), to: reloc.name(self), at: u64::from(reloc.offset), }, faerie::Reloc::Debug { size: reloc.size, addend: reloc.addend as i32, }, ) .expect("faerie relocation error"); } Ok(()) }); } } pub struct FunctionDebugContext<'a, 'tcx> { debug_context: &'a mut DebugContext<'tcx>, entry_id: UnitEntryId, symbol: usize, mir_span: Span, } impl<'a, 'tcx> FunctionDebugContext<'a, 'tcx> { pub fn new( tcx: TyCtxt<'tcx>, debug_context: &'a mut DebugContext<'tcx>, mir: &Body, name: &str, _sig: &Signature, ) -> Self { let (symbol, _) = debug_context.symbols.insert_full(name.to_string()); // FIXME: add to appropriate scope intead of root let scope = debug_context.dwarf.unit.root(); let entry_id = debug_context .dwarf .unit .add(scope, gimli::DW_TAG_subprogram); let entry = debug_context.dwarf.unit.get_mut(entry_id); let name_id = debug_context.dwarf.strings.add(name); entry.set( gimli::DW_AT_linkage_name, AttributeValue::StringRef(name_id), ); entry.set( gimli::DW_AT_low_pc, AttributeValue::Address(Address::Symbol { symbol, addend: 0 }), ); debug_context.emit_location(tcx, entry_id, mir.span); FunctionDebugContext { debug_context, entry_id, symbol, mir_span: mir.span, } } pub fn define( &mut self, tcx: TyCtxt, context: &Context, isa: &dyn cranelift::codegen::isa::TargetIsa, source_info_set: &indexmap::IndexSet<SourceInfo>, ) { let line_program = &mut self.debug_context.dwarf.unit.line_program; line_program.begin_sequence(Some(Address::Symbol { symbol: self.symbol, addend: 0, })); let encinfo = isa.encoding_info(); let func = &context.func; let mut ebbs = func.layout.ebbs().collect::<Vec<_>>(); ebbs.sort_by_key(|ebb| func.offsets[*ebb]); // Ensure inst offsets always increase let line_strings = &mut self.debug_context.dwarf.line_strings; let mut create_row_for_span = |line_program: &mut LineProgram, span: Span| { let loc = tcx.sess.source_map().lookup_char_pos(span.lo()); let file_id = line_program_add_file(line_program, line_strings, &loc.file.name); /*println!( "srcloc {:>04X} {}:{}:{}", line_program.row().address_offset, file.display(), loc.line, loc.col.to_u32() );*/ line_program.row().file = file_id; line_program.row().line = loc.line as u64; line_program.row().column = loc.col.to_u32() as u64 + 1; line_program.generate_row(); }; let mut end = 0; for ebb in ebbs { for (offset, inst, size) in func.inst_offsets(ebb, &encinfo) { let srcloc = func.srclocs[inst]; line_program.row().address_offset = offset as u64; if !srcloc.is_default() { let source_info = *source_info_set.get_index(srcloc.bits() as usize).unwrap(); create_row_for_span(line_program, source_info.span); } else { create_row_for_span(line_program, self.mir_span); } end = offset + size; } } line_program.end_sequence(end as u64); let entry = self.debug_context.dwarf.unit.get_mut(self.entry_id); entry.set(gimli::DW_AT_high_pc, AttributeValue::Udata(end as u64)); self.debug_context .unit_range_list .0 .push(Range::StartLength { begin: Address::Symbol { symbol: self.symbol, addend: 0, }, length: end as u64, }); } } #[derive(Clone)] struct WriterRelocate { relocs: Vec<DebugReloc>, writer: EndianVec<RunTimeEndian>, } impl WriterRelocate { fn new(ctx: &DebugContext) -> Self { WriterRelocate { relocs: Vec::new(), writer: EndianVec::new(ctx.endian), } } } impl Writer for WriterRelocate { type Endian = RunTimeEndian; fn endian(&self) -> Self::Endian { self.writer.endian() } fn len(&self) -> usize { self.writer.len() } fn write(&mut self, bytes: &[u8]) -> Result<()> { self.writer.write(bytes) } fn write_at(&mut self, offset: usize, bytes: &[u8]) -> Result<()> { self.writer.write_at(offset, bytes) } fn write_address(&mut self, address: Address, size: u8) -> Result<()> { match address { Address::Constant(val) => self.write_udata(val, size), Address::Symbol { symbol, addend } => { let offset = self.len() as u64; self.relocs.push(DebugReloc { offset: offset as u32, size, name: DebugRelocName::Symbol(symbol), addend: addend as i64, }); self.write_udata(0, size) } } } // TODO: implement write_eh_pointer fn write_offset(&mut self, val: usize, section: SectionId, size: u8) -> Result<()> { let offset = self.len() as u32; self.relocs.push(DebugReloc { offset, size, name: DebugRelocName::Section(section), addend: val as i64, }); self.write_udata(0, size) } fn write_offset_at( &mut self, offset: usize, val: usize, section: SectionId, size: u8, ) -> Result<()> { self.relocs.push(DebugReloc { offset: offset as u32, size, name: DebugRelocName::Section(section), addend: val as i64, }); self.write_udata_at(offset, 0, size) } }
extern crate terminal; extern crate serde_json; use terminal::Source; use std::net::{TcpListener, TcpStream}; // use std::net::Shutdown; // need to implement shutdown later use std::thread; use std::sync::mpsc::channel; use std::str; use std::io::{Read, Write}; pub struct Transport { pub listener_addr: std::net::SocketAddr, pub other_listeners: Vec<std::net::SocketAddr>, pub tx_ch: std::sync::mpsc::Sender< String >, pub net_txs: Vec< std::net::TcpStream >, pub listener_receiver: std::sync::mpsc::Receiver< std::net::TcpStream > } impl Transport { pub fn new(ip:String, port:String, tx_ch:std::sync::mpsc::Sender< String >) -> Transport { let listener = TcpListener::bind( ip + ":" + &port ) .expect("Transport::new() Could not bind to the given ip"); let listener_addr = listener.local_addr().unwrap(); let (listener_sender, listener_receiver) = channel(); let tx_ch_clone = tx_ch.clone(); thread::spawn(move || { for stream in listener.incoming() { match stream { Err(e) => { eprintln!("Transport::new() - Stream failed: {}", e) } Ok(stream) => { let tx_ch_clone_2 = tx_ch_clone.clone(); listener_sender.send( stream.try_clone() .expect("Transport::new() - clone failed") ).unwrap(); tx_ch_clone.send( serde_json::to_string(&Source::Stream) .unwrap()).unwrap(); thread::spawn(move || { incoming_conn(stream,tx_ch_clone_2); }); } } } }); Transport { listener_addr: listener_addr, other_listeners: vec![], tx_ch: tx_ch, net_txs: vec![], listener_receiver: listener_receiver } } pub fn join(&mut self, addr:std::net::SocketAddr, tx_ch:std::sync::mpsc::Sender< String >, listener_package: String) { let mut stream = TcpStream::connect(addr) .expect("Transport::join() - Could not connect to server"); stream.write(listener_package.as_bytes()) .expect("transport::distribute - Failed to write to server"); self.net_txs.push( stream.try_clone() .expect("Transport::join - stream clone failed") ); tx_ch.send( serde_json::to_string(&Source::Join).unwrap()).unwrap(); thread::spawn(move || { let mut buf = [0; 512]; loop { let bytes_read = stream.read(&mut buf) .expect("Transport::join() Failed to read stream"); if bytes_read != 0 { let s = str::from_utf8(&buf[..bytes_read]).unwrap().to_string(); let st = serde_json::to_string( &(Source::Net(s)) ).unwrap(); tx_ch.send(st).unwrap(); } } }); } pub fn distribute(&mut self, op:String) { for mut stream in &self.net_txs { stream.write(op.as_bytes()) .expect("transport::distribute - Failed to write to server"); } } pub fn connected(&self) -> Vec<std::net::SocketAddr> { let mut ip_list = Vec::new(); for t in &self.net_txs { ip_list.push( t.peer_addr().unwrap()); } ip_list } } fn incoming_conn(mut stream: TcpStream, tx_ch:std::sync::mpsc::Sender<String>) { let mut buf = [0; 512]; loop { let bytes_read = stream.read(&mut buf) .expect("Transport::new() Failed to read stream"); if bytes_read != 0 { let s = str::from_utf8(&buf[..bytes_read]).unwrap().to_string(); let st = serde_json::to_string( &(Source::Net(s)) ).unwrap(); tx_ch.send(st).unwrap(); } } } #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } }
fn main() { proconio::input! { n: usize, s: String, } let mut cs: Vec<char> = s.chars().collect(); // println!("{:?}", cs); for i in (0..n).rev() { let mut pre = cs[0]; for j in 1..(i+1) { // println!("{} {}", i, j); if cs[j] == pre { cs[j-1] = pre; pre = cs[j]; } else { let tmp = cs[j]; cs[j-1] = se(pre, cs[j]); pre = tmp; } } // println!("{:?}", cs); } println!("{}", cs[0]); } fn se(a: char, b: char)->char{ if a == 'B' { if b == 'W' { return 'R'; }else { return 'W'; } } else if a == 'W' { if b == 'B' { return 'R'; }else { return 'B'; } } else { if b == 'B' { return 'W'; }else { return 'B'; } } }
#[doc = "Reader of register CONN_UPDATE_NEW_INTERVAL"] pub type R = crate::R<u32, super::CONN_UPDATE_NEW_INTERVAL>; #[doc = "Writer for register CONN_UPDATE_NEW_INTERVAL"] pub type W = crate::W<u32, super::CONN_UPDATE_NEW_INTERVAL>; #[doc = "Register CONN_UPDATE_NEW_INTERVAL `reset()`'s with value 0"] impl crate::ResetValue for super::CONN_UPDATE_NEW_INTERVAL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `CONN_UPDT_INTERVAL`"] pub type CONN_UPDT_INTERVAL_R = crate::R<u16, u16>; #[doc = "Write proxy for field `CONN_UPDT_INTERVAL`"] pub struct CONN_UPDT_INTERVAL_W<'a> { w: &'a mut W, } impl<'a> CONN_UPDT_INTERVAL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff); self.w } } impl R { #[doc = "Bits 0:15 - This register will have the new connection interval that the hardware will use after the connection update instant. Before the instant, the connection interval in the register CONN_INTERVAL will be used by hardware."] #[inline(always)] pub fn conn_updt_interval(&self) -> CONN_UPDT_INTERVAL_R { CONN_UPDT_INTERVAL_R::new((self.bits & 0xffff) as u16) } } impl W { #[doc = "Bits 0:15 - This register will have the new connection interval that the hardware will use after the connection update instant. Before the instant, the connection interval in the register CONN_INTERVAL will be used by hardware."] #[inline(always)] pub fn conn_updt_interval(&mut self) -> CONN_UPDT_INTERVAL_W { CONN_UPDT_INTERVAL_W { w: self } } }
use std::env; use std::vec::Vec; mod graphreader; mod graph; mod dfs; mod bfs; mod mark; mod constructiongraph; fn main() { let args: Vec<String> = env::args().collect(); let arg = args.get(1); if arg.is_some() { let g = graphreader::new_from_file(&(arg.unwrap())).unwrap(); let mut marker = mark::TMarker::new(g.len()); //dfs::dfs(&g, 0, &(Box::new(|x: usize| print!("{} ", x))), &mut marker); println!("doint a full dfs:"); dfs::full_dfs(&g, &mut (Box::new(|x: usize| print!("{} ->", x))), &mut marker); marker.reset(); println!("doint a full bfs:"); bfs::full_bfs(&g, &mut (Box::new(|x: usize| print!("{} ->", x))), &mut marker); println!("done!"); let cg = constructiongraph::ConstructionGraph::new_cg_from_file(&(arg.unwrap())); } }
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. use crate::itest; use test_util as util; itest!(globals { args: "run --compat --unstable --allow-read --allow-env compat/globals.ts", output: "compat/globals.out", }); itest!(fs_promises { args: "run --compat --unstable -A compat/fs_promises.js", output: "compat/fs_promises.out", }); itest!(node_prefix_fs_promises { args: "run --compat --unstable -A compat/node_fs_promises.js", output: "compat/fs_promises.out", }); itest!(existing_import_map { args: "run --compat --unstable --import-map compat/existing_import_map.json compat/fs_promises.js", output: "compat/existing_import_map.out", exit_code: 1, }); #[test] fn globals_in_repl() { let (out, err) = util::run_and_collect_output_with_args( true, vec!["repl", "--compat", "--unstable", "--quiet"], Some(vec!["global == window"]), None, false, ); assert!(out.contains("true")); assert!(err.contains("Implicitly using latest version")); }
use std::io::{Write, Seek, SeekFrom, Read, self}; use regex::Regex; use ::{format_u64, format_usize, NumberStyle, parse_as_u64, extract_section}; use sections::Section; #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] pub enum SegmentType { Text, Data } impl SegmentType { pub fn to_string(self, seg_num: u64) -> String { use self::SegmentType::*; match self { Text => format!(".text{}", seg_num), Data => format!(".data{}", seg_num), } } } #[derive(Copy, Clone, Debug)] pub struct Segment { // NOTE: `offset` is not the offset stored on the ROM. // The ROM provides the offset relative to the start of the DOL header, // whereas this is relative to the beginning of the ROM. This offset // is essentially the offset relative to the DOL (which is the value // given in the ROM), plus the offset of the DOL itself. pub offset: u64, pub size: usize, pub loading_address: u64, pub seg_type: SegmentType, pub seg_num: u64, } impl Segment { pub fn text() -> Segment { Segment { offset: 0, size: 0, loading_address: 0, seg_type: SegmentType::Text, seg_num: 0, } } pub fn data() -> Segment { Segment { offset: 0, size: 0, loading_address: 0, seg_type: SegmentType::Data, seg_num: 0, } } pub fn to_string(self) -> String { self.seg_type.to_string(self.seg_num) } pub fn parse_segment_name(name: &str) -> Option<(SegmentType, u64)> { use self::SegmentType::*; lazy_static! { static ref SEG_NAME_REGEX: Regex = Regex::new(r"^\.?(text|data)(\d+)$").unwrap(); } SEG_NAME_REGEX.captures(name).and_then(|c| { parse_as_u64(c.get(2).unwrap().as_str()).map(|n| { let t = match c.get(1).unwrap().as_str() { "text" => Text, "data" => Data, _ => unreachable!(), }; (t, n) }).ok() }) } // TODO: put in a trait pub fn extract<R, W>(&self, mut iso: R, output: W) -> io::Result<()> where Self: Sized, R: Read + Seek, W: Write, { iso.seek(SeekFrom::Start(self.offset))?; extract_section(iso, self.size, output) } } impl Section for Segment { fn print_info(&self, style: NumberStyle) { println!("Segment name: {}", self.seg_type.to_string(self.seg_num)); println!("Offset: {}", format_u64(self.offset, style)); println!("Size: {}", format_usize(self.size, style)); println!("Loading address: {}", format_u64(self.loading_address, style)); } fn start(&self) -> u64 { self.offset } fn size(&self) -> usize { self.size } }
use aoc::*; use std::collections::BTreeSet; fn main() -> Result<()> { let asteroids: Vec<_> = input("10.txt")? .lines() .enumerate() .flat_map(|(y, line)| { line.chars() .enumerate() .filter(|(_, ch)| *ch == '#') .map(move |(x, _)| (x as i8, y as i8)) }) .collect(); let best = asteroids.iter().map(|&p| angles(p, &asteroids).len()).max(); Ok(println!("{:?}", best)) } type Point = (i8, i8); fn angles(from: Point, asteroids: &[Point]) -> BTreeSet<i16> { asteroids .iter() .filter(|&&to| from != to) .map(|&to| (angle(from, to) * 10.0) as i16) .collect() } fn angle(from: Point, to: Point) -> f64 { let relative = (from.0 - to.0, from.1 - to.1); (relative.1 as f64).atan2(relative.0 as f64).to_degrees() }
#[doc = "Register `NSEPOCHR_CUR` reader"] pub type R = crate::R<NSEPOCHR_CUR_SPEC>; #[doc = "Field `NS_EPOCH` reader - Non-volatile non-secure EPOCH counter"] pub type NS_EPOCH_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:23 - Non-volatile non-secure EPOCH counter"] #[inline(always)] pub fn ns_epoch(&self) -> NS_EPOCH_R { NS_EPOCH_R::new(self.bits & 0x00ff_ffff) } } #[doc = "FLASH non-secure EPOCH register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`nsepochr_cur::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct NSEPOCHR_CUR_SPEC; impl crate::RegisterSpec for NSEPOCHR_CUR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`nsepochr_cur::R`](R) reader structure"] impl crate::Readable for NSEPOCHR_CUR_SPEC {} #[doc = "`reset()` method sets NSEPOCHR_CUR to value 0"] impl crate::Resettable for NSEPOCHR_CUR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::any::Any; use std::cell::{RefCell, RefMut}; use std::rc::Rc; use super::{CanReceive, Handoff, HandoffMeta, Iter}; /// A [Vec]-based FIFO handoff. pub struct VecHandoff<T> where T: 'static, { pub(crate) input: Rc<RefCell<Vec<T>>>, pub(crate) output: Rc<RefCell<Vec<T>>>, } impl<T> Default for VecHandoff<T> where T: 'static, { fn default() -> Self { Self { input: Default::default(), output: Default::default(), } } } impl<T> Handoff for VecHandoff<T> { type Inner = Vec<T>; fn take_inner(&self) -> Self::Inner { self.input.take() } fn borrow_mut_swap(&self) -> RefMut<Self::Inner> { let mut input = self.input.borrow_mut(); let mut output = self.output.borrow_mut(); std::mem::swap(&mut *input, &mut *output); output } } impl<T> CanReceive<Option<T>> for VecHandoff<T> { fn give(&self, mut item: Option<T>) -> Option<T> { if let Some(item) = item.take() { (*self.input).borrow_mut().push(item) } None } } impl<T, I> CanReceive<Iter<I>> for VecHandoff<T> where I: Iterator<Item = T>, { fn give(&self, mut iter: Iter<I>) -> Iter<I> { (*self.input).borrow_mut().extend(&mut iter.0); iter } } impl<T> CanReceive<Vec<T>> for VecHandoff<T> { fn give(&self, mut vec: Vec<T>) -> Vec<T> { (*self.input).borrow_mut().extend(vec.drain(..)); vec } } impl<T> HandoffMeta for VecHandoff<T> { fn any_ref(&self) -> &dyn Any { self } fn is_bottom(&self) -> bool { (*self.input).borrow_mut().is_empty() } } impl<H> HandoffMeta for Rc<RefCell<H>> where H: HandoffMeta, { fn any_ref(&self) -> &dyn Any { self } fn is_bottom(&self) -> bool { self.borrow().is_bottom() } }
use lazy_static::lazy_static; use regex::Regex; const INPUT: &str = include_str!("../input"); const MAX_STEPS: u32 = 1_000_000; type Result<T> = ::std::result::Result<T, Box<dyn ::std::error::Error>>; lazy_static! { static ref INPUT_REGEX: Regex = Regex::new(r"position=<\s*(-?\d+),\s*(-?\d+)> velocity=<\s*(-?\d+),\s*(-?\d+)>").unwrap(); } fn main() -> Result<()> { let points = parse_input(INPUT)?; let solution = solve(&points); println!("{}{}", solution.0, solution.1); Ok(()) } #[derive(Debug, PartialEq, Clone)] struct Point { position: (i32, i32), velocity: (i32, i32), } impl Point { fn step(&mut self) { let (x, y) = self.position; let (vx, vy) = self.velocity; self.position = (x + vx, y + vy); } fn has_neighbor_in(&self, other_points: &[Point]) -> bool { let (x, y) = self.position; let neighboring_positions = [ (x + 1, y + 1), (x + 1, y), (x + 1, y - 1), (x, y + 1), (x, y - 1), (x - 1, y + 1), (x - 1, y), (x - 1, y - 1), ]; other_points .iter() .any(|p| neighboring_positions.contains(&p.position)) } } fn parse_input(input: &str) -> Result<Vec<Point>> { input .trim() .split('\n') .map(|line| { let captures = INPUT_REGEX .captures(line) .ok_or_else(|| format!("Line did not match input regex: {}", line))?; let position = (captures[1].parse()?, captures[2].parse()?); let velocity = (captures[3].parse()?, captures[4].parse()?); Ok(Point { position, velocity }) }) .collect() } fn solve(points: &[Point]) -> (String, u32) { let mut points = points.to_vec(); for step in 0..=MAX_STEPS { if points.iter().all(|p| p.has_neighbor_in(&points)) { return (points_to_str(&points), step); } points.iter_mut().for_each(|p| p.step()); } panic!("hit max steps"); } fn points_to_str(points: &[Point]) -> String { let x_values = points.iter().map(|p| p.position.0); let min_x = x_values.clone().min().unwrap(); let max_x = x_values.clone().max().unwrap(); let y_values = points.iter().map(|p| p.position.1); let min_y = y_values.clone().min().unwrap(); let max_y = y_values.clone().max().unwrap(); let mut result = String::new(); for y in min_y..=max_y { for x in min_x..=max_x { let c = if points.iter().any(|p| p.position == (x, y)) { '#' } else { '.' }; result.push(c); } result.push('\n'); } result } #[cfg(test)] mod tests { use super::*; const SAMPLE_INPUT: &str = include_str!("../sample-input"); const SAMPLE_OUTPUT: &str = include_str!("../sample-output"); #[test] fn it_parses_input_correctly() { assert_eq!(parse_input(SAMPLE_INPUT).unwrap(), get_sample_input()); } #[test] fn it_solves_part_one_correctly() { assert_eq!(solve(&get_sample_input()).0, SAMPLE_OUTPUT); } #[test] fn it_solves_part_two_correctly() { assert_eq!(solve(&get_sample_input()).1, 3); } fn get_sample_input() -> [Point; 31] { [ Point { position: (9, 1), velocity: (0, 2), }, Point { position: (7, 0), velocity: (-1, 0), }, Point { position: (3, -2), velocity: (-1, 1), }, Point { position: (6, 10), velocity: (-2, -1), }, Point { position: (2, -4), velocity: (2, 2), }, Point { position: (-6, 10), velocity: (2, -2), }, Point { position: (1, 8), velocity: (1, -1), }, Point { position: (1, 7), velocity: (1, 0), }, Point { position: (-3, 11), velocity: (1, -2), }, Point { position: (7, 6), velocity: (-1, -1), }, Point { position: (-2, 3), velocity: (1, 0), }, Point { position: (-4, 3), velocity: (2, 0), }, Point { position: (10, -3), velocity: (-1, 1), }, Point { position: (5, 11), velocity: (1, -2), }, Point { position: (4, 7), velocity: (0, -1), }, Point { position: (8, -2), velocity: (0, 1), }, Point { position: (15, 0), velocity: (-2, 0), }, Point { position: (1, 6), velocity: (1, 0), }, Point { position: (8, 9), velocity: (0, -1), }, Point { position: (3, 3), velocity: (-1, 1), }, Point { position: (0, 5), velocity: (0, -1), }, Point { position: (-2, 2), velocity: (2, 0), }, Point { position: (5, -2), velocity: (1, 2), }, Point { position: (1, 4), velocity: (2, 1), }, Point { position: (-2, 7), velocity: (2, -2), }, Point { position: (3, 6), velocity: (-1, -1), }, Point { position: (5, 0), velocity: (1, 0), }, Point { position: (-6, 0), velocity: (2, 0), }, Point { position: (5, 9), velocity: (1, -2), }, Point { position: (14, 7), velocity: (-2, 0), }, Point { position: (-3, 6), velocity: (2, -1), }, ] } }
pub mod cli_tests;
use std::io::{stdin, Read, StdinLock}; use std::str::FromStr; #[allow(dead_code)] struct Scanner<'a> { cin: StdinLock<'a>, } #[allow(dead_code)] impl<'a> Scanner<'a> { fn new(cin: StdinLock<'a>) -> Scanner<'a> { Scanner { cin: cin } } fn read<T: FromStr>(&mut self) -> Option<T> { let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char) .skip_while(|c| c.is_whitespace()) .take_while(|c| !c.is_whitespace()) .collect::<String>(); token.parse::<T>().ok() } fn input<T: FromStr>(&mut self) -> T { self.read().unwrap() } } fn main() { let cin = stdin(); let cin = cin.lock(); let mut sc = Scanner::new(cin); let n: isize = sc.input(); let ts: Vec<isize> = (0..n) .map(|_| sc.input()) .collect(); let m: isize = sc.input(); let drinks: Vec<(isize, isize)> = (0..m) .map(|_| (sc.input(), sc.input())) .collect(); let sum: isize = ts.iter().sum(); for (p, x) in drinks { let index = p - 1; println!("{}", sum - ts[index as usize] + x); } }
use core::fmt::Write; use core::panic::PanicInfo; use cortexm4; use kernel::debug; use kernel::debug::IoWrite; use kernel::hil::led; use kernel::hil::uart; use kernel::hil::uart::Configure; use stm32f407vg; use stm32f407vg::gpio::PinId; use crate::CHIP; use crate::PROCESSES; /// Writer is used by kernel::debug to panic message to the serial port. pub struct Writer { initialized: bool, } /// Global static for debug writer pub static mut WRITER: Writer = Writer { initialized: false }; impl Writer { /// Indicate that USART has already been initialized. Trying to double /// initialize USART2 causes STM32F407VG to go into in in-deterministic state. pub fn set_initialized(&mut self) { self.initialized = true; } } impl Write for Writer { fn write_str(&mut self, s: &str) -> ::core::fmt::Result { self.write(s.as_bytes()); Ok(()) } } impl IoWrite for Writer { fn write(&mut self, buf: &[u8]) { let uart = unsafe { &mut stm32f407vg::usart::USART2 }; if !self.initialized { self.initialized = true; uart.configure(uart::Parameters { baud_rate: 115200, stop_bits: uart::StopBits::One, parity: uart::Parity::None, hw_flow_control: false, width: uart::Width::Eight, }); } for &c in buf { uart.send_byte(c); } } } /// Panic handler. #[no_mangle] #[panic_handler] pub unsafe extern "C" fn panic_fmt(info: &PanicInfo) -> ! { // User LD5 (RED) is connected to PD14 let led = &mut led::LedHigh::new(PinId::PD14.get_pin_mut().as_mut().unwrap()); let writer = &mut WRITER; debug::panic( &mut [led], writer, info, &cortexm4::support::nop, &PROCESSES, &CHIP, ) }
use super::*; use common_failures::prelude::*; #[derive(Default)] pub struct MemDataStore { blocks: BTreeMap<BlockHeight, Block>, block_hashes: BTreeMap<BlockHeight, BlockHash>, } impl DataStore for MemDataStore { fn get_hash_by_height(&mut self, height: BlockHeight) -> Result<Option<BlockHash>> { Ok(self.block_hashes.get(&height).cloned()) } fn reorg_at_height(&mut self, height: BlockHeight) -> Result<()> { for height in height.. { if self.blocks.remove(&height).is_none() { break; } self.block_hashes .remove(&height) .expect("block_hashes out of sync"); } Ok(()) } fn insert(&mut self, info: BlockInfo) -> Result<()> { let parsed = super::parse_node_block(&info)?; self.blocks.insert(info.height, parsed.block); Ok(()) } fn flush(&mut self) -> Result<()> { Ok(()) } fn get_max_height(&mut self) -> Result<Option<BlockHeight>> { Ok(self.blocks.keys().next_back().cloned()) } }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::batch::WriteBatch; use crate::storage::{CodecStorage, ValueCodec}; use crate::TRANSACTION_INFO_PREFIX_NAME; use crate::{define_storage, TransactionInfoStore}; use anyhow::{Error, Result}; use crypto::HashValue; use scs::SCSCodec; use starcoin_types::transaction::TransactionInfo; use std::sync::Arc; define_storage!( TransactionInfoStorage, HashValue, TransactionInfo, TRANSACTION_INFO_PREFIX_NAME ); impl ValueCodec for TransactionInfo { fn encode_value(&self) -> Result<Vec<u8>> { self.encode() } fn decode_value(data: &[u8]) -> Result<Self> { Self::decode(data) } } impl TransactionInfoStore for TransactionInfoStorage { fn get_transaction_info( &self, txn_info_hash: HashValue, ) -> Result<Option<TransactionInfo>, Error> { self.store.get(txn_info_hash) } fn save_transaction_infos(&self, vec_txn_info: Vec<TransactionInfo>) -> Result<(), Error> { let mut batch = WriteBatch::new(); for txn_info in vec_txn_info { batch.put(txn_info.id(), txn_info)?; } self.store.write_batch(batch) } }
//! Contains baked-in assets. use phf; macro_rules! include_files_as_assets { ( $field_name:ident, $file_base:expr, $( $file_name:expr ),* ) => { pub static $field_name: phf::Map<&'static str, &'static [u8]> = phf_map!( $( $file_name => include_bytes!(concat!($file_base, $file_name)), )* ); } } include_files_as_assets!( FILES, "../static/", "css/agate.css", "css/bulma.min.css", "css/main.css", "js/highlight.pack.js", "js/manage.js", "js/vue.min.js" ); include_files_as_assets!( TEMPLATES, "../templates/", "footer.hbs", "header.hbs", "index.hbs", "manage.hbs", "text.hbs" ); /// Returns the contents of a file from the given list. pub fn get_file( table: &phf::Map<&'static str, &'static [u8]>, name: &str, ) -> Option<&'static [u8]> { table.get(name).map(|x| *x) } /// Returns the contents of a file from the given list. pub fn list_files(table: &phf::Map<&'static str, &'static [u8]>) -> Vec<&'static str> { table.keys().map(|x| *x).collect() }
//! This example demonstrates an alternative method for creating a [`Table`]. //! [`Builder`] is an efficient implementation of the [builder design pattern](https://en.wikipedia.org/wiki/Builder_pattern). //! //! > The intent of the Builder design pattern is to separate the construction of a complex object from its representation. //! > -- <cite>Wikipedia</cite> //! //! * Note how [Builder] can be used to define a table's shape manually //! and can be populated through iteration if it is mutable. This flexibility //! is useful when you don't have direct control over the datasets you intend to [table](tabled). use tabled::{ builder::Builder, settings::{object::Rows, Modify, Panel, Style, Width}, }; fn main() { let message = r#"The terms "the ocean" or "the sea" used without specification refer to the interconnected body of salt water covering the majority of the Earth's surface"#; let link = r#"https://en.wikipedia.org/wiki/Ocean"#; let oceans = ["Atlantic", "Pacific", "Indian", "Southern", "Arctic"]; let mut builder = Builder::default(); builder.set_header(["#", "Ocean"]); for (i, ocean) in oceans.iter().enumerate() { builder.push_record([i.to_string(), ocean.to_string()]); } let table = builder .build() .with(Panel::header(message)) .with(Panel::header(link)) .with(Panel::horizontal(2, "=".repeat(link.len()))) .with(Modify::new(Rows::single(1)).with(Width::wrap(link.len()))) .with(Style::markdown()) .to_string(); println!("{table}"); }
use crate::grammar::model::WrightInput; use crate::grammar::tracing::input::OptionallyTraceable; use crate::grammar::tracing::trace_result; use nom::error::ErrorKind; use nom::Err; use nom::IResult; /// A trait used to replace /// [nom's trait of the same name](https://docs.rs/nom/5.1.1/nom/branch/trait.Alt.html). pub trait Alt<I, O, E> { /// Choose the appropriate parser, in this case /// the first one that succeeds. fn choice(&self, input: I) -> IResult<I, O, E>; } macro_rules! impl_alt { ($first:ident $second:ident $($rest:ident)*) => { impl_alt!(inner1 $first $second; $($rest)*); }; (inner1 $($current:ident)+; $head:ident $($rest:ident)+) => { impl_alt_inner!( $($current)+ ); impl_alt!(inner1 $($current)+ $head; $($rest)+); }; (inner1 $($current:ident)+; $head:ident) => { impl_alt_inner!( $($current)+ ); impl_alt_inner!( $($current)+ $head); }; } macro_rules! impl_alt_inner { ($($id:ident)+) => { #[allow(bad_style)] impl<Input: WrightInput, Output, $($id: Fn(Input) -> IResult<Input, Output>),+ > Alt<Input, Output, (Input, ErrorKind)> for ( $($id),+ ) { fn choice(&self, input: Input) -> IResult<Input, Output> { let mut source = input; let ( $($id),+ ) = self; $( match ($id)(source.clone()) { Result::Err(Err::Error((s, _))) => source.set_trace(s.get_trace()), other => return other, } )+ IResult::Err(Err::Error((source, ErrorKind::Alt))) } } }; } impl_alt!(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z); /// A traced version of nom's /// [`alt`](https://docs.rs/nom/5.1.1/nom/branch/fn.alt.html) /// combinator. pub fn alt<I, O, List>(l: List) -> impl Fn(I) -> IResult<I, O, (I, ErrorKind)> where I: OptionallyTraceable, List: Alt<I, O, (I, ErrorKind)>, { let trace = "alt"; move |input: I| { let input = input.trace_start_clone(trace); let res = l.choice(input); trace_result(trace, res) } }
#[doc = "Reader of register TEMP_ICIFR"] pub type R = crate::R<u32, super::TEMP_ICIFR>; #[doc = "Writer for register TEMP_ICIFR"] pub type W = crate::W<u32, super::TEMP_ICIFR>; #[doc = "Register TEMP_ICIFR `reset()`'s with value 0"] impl crate::ResetValue for super::TEMP_ICIFR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TS1_CITEF`"] pub type TS1_CITEF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TS1_CITEF`"] pub struct TS1_CITEF_W<'a> { w: &'a mut W, } impl<'a> TS1_CITEF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `TS1_CITLF`"] pub type TS1_CITLF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TS1_CITLF`"] pub struct TS1_CITLF_W<'a> { w: &'a mut W, } impl<'a> TS1_CITLF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `TS1_CITHF`"] pub type TS1_CITHF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TS1_CITHF`"] pub struct TS1_CITHF_W<'a> { w: &'a mut W, } impl<'a> TS1_CITHF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `TS1_CAITEF`"] pub type TS1_CAITEF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TS1_CAITEF`"] pub struct TS1_CAITEF_W<'a> { w: &'a mut W, } impl<'a> TS1_CAITEF_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 `TS1_CAITLF`"] pub type TS1_CAITLF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TS1_CAITLF`"] pub struct TS1_CAITLF_W<'a> { w: &'a mut W, } impl<'a> TS1_CAITLF_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 `TS1_CAITHF`"] pub type TS1_CAITHF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TS1_CAITHF`"] pub struct TS1_CAITHF_W<'a> { w: &'a mut W, } impl<'a> TS1_CAITHF_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 0 - TS1_CITEF"] #[inline(always)] pub fn ts1_citef(&self) -> TS1_CITEF_R { TS1_CITEF_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - TS1_CITLF"] #[inline(always)] pub fn ts1_citlf(&self) -> TS1_CITLF_R { TS1_CITLF_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - TS1_CITHF"] #[inline(always)] pub fn ts1_cithf(&self) -> TS1_CITHF_R { TS1_CITHF_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 4 - TS1_CAITEF"] #[inline(always)] pub fn ts1_caitef(&self) -> TS1_CAITEF_R { TS1_CAITEF_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - TS1_CAITLF"] #[inline(always)] pub fn ts1_caitlf(&self) -> TS1_CAITLF_R { TS1_CAITLF_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - TS1_CAITHF"] #[inline(always)] pub fn ts1_caithf(&self) -> TS1_CAITHF_R { TS1_CAITHF_R::new(((self.bits >> 6) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - TS1_CITEF"] #[inline(always)] pub fn ts1_citef(&mut self) -> TS1_CITEF_W { TS1_CITEF_W { w: self } } #[doc = "Bit 1 - TS1_CITLF"] #[inline(always)] pub fn ts1_citlf(&mut self) -> TS1_CITLF_W { TS1_CITLF_W { w: self } } #[doc = "Bit 2 - TS1_CITHF"] #[inline(always)] pub fn ts1_cithf(&mut self) -> TS1_CITHF_W { TS1_CITHF_W { w: self } } #[doc = "Bit 4 - TS1_CAITEF"] #[inline(always)] pub fn ts1_caitef(&mut self) -> TS1_CAITEF_W { TS1_CAITEF_W { w: self } } #[doc = "Bit 5 - TS1_CAITLF"] #[inline(always)] pub fn ts1_caitlf(&mut self) -> TS1_CAITLF_W { TS1_CAITLF_W { w: self } } #[doc = "Bit 6 - TS1_CAITHF"] #[inline(always)] pub fn ts1_caithf(&mut self) -> TS1_CAITHF_W { TS1_CAITHF_W { w: self } } }
// Copyright (c) 2017-present PyO3 Project and Contributors use crate::{ exceptions::{PyAttributeError, PyNotImplementedError}, ffi, impl_::freelist::FreeList, pycell::PyCellLayout, pyclass_init::PyObjectInit, type_object::{PyLayout, PyTypeObject}, PyClass, PyMethodDefType, PyNativeType, PyResult, PyTypeInfo, Python, }; use std::{marker::PhantomData, os::raw::c_void, ptr::NonNull, thread}; /// This type is used as a "dummy" type on which dtolnay specializations are /// applied to apply implementations from `#[pymethods]` & `#[pyproto]` pub struct PyClassImplCollector<T>(PhantomData<T>); impl<T> PyClassImplCollector<T> { pub fn new() -> Self { Self(PhantomData) } } impl<T> Default for PyClassImplCollector<T> { fn default() -> Self { Self::new() } } impl<T> Clone for PyClassImplCollector<T> { fn clone(&self) -> Self { Self::new() } } impl<T> Copy for PyClassImplCollector<T> {} /// Implements the underlying functionality of `#[pyclass]`, assembled by various proc macros. /// /// Users are discouraged from implementing this trait manually; it is a PyO3 implementation detail /// and may be changed at any time. pub trait PyClassImpl: Sized { /// Class doc string const DOC: &'static str = "\0"; /// #[pyclass(gc)] const IS_GC: bool = false; /// #[pyclass(subclass)] const IS_BASETYPE: bool = false; /// #[pyclass(extends=...)] const IS_SUBCLASS: bool = false; /// Layout type Layout: PyLayout<Self>; /// Base class type BaseType: PyTypeInfo + PyTypeObject + PyClassBaseType; /// This handles following two situations: /// 1. In case `T` is `Send`, stub `ThreadChecker` is used and does nothing. /// This implementation is used by default. Compile fails if `T: !Send`. /// 2. In case `T` is `!Send`, `ThreadChecker` panics when `T` is accessed by another thread. /// This implementation is used when `#[pyclass(unsendable)]` is given. /// Panicking makes it safe to expose `T: !Send` to the Python interpreter, where all objects /// can be accessed by multiple threads by `threading` module. type ThreadChecker: PyClassThreadChecker<Self>; fn for_each_method_def(_visitor: &mut dyn FnMut(&[PyMethodDefType])) {} fn get_new() -> Option<ffi::newfunc> { None } fn get_alloc() -> Option<ffi::allocfunc> { None } fn get_free() -> Option<ffi::freefunc> { None } fn for_each_proto_slot(_visitor: &mut dyn FnMut(&[ffi::PyType_Slot])) {} fn get_buffer() -> Option<&'static PyBufferProcs> { None } } // Traits describing known special methods. pub trait PyClassNewImpl<T> { fn new_impl(self) -> Option<ffi::newfunc>; } impl<T> PyClassNewImpl<T> for &'_ PyClassImplCollector<T> { fn new_impl(self) -> Option<ffi::newfunc> { None } } macro_rules! slot_fragment_trait { ($trait_name:ident, $($default_method:tt)*) => { #[allow(non_camel_case_types)] pub trait $trait_name<T>: Sized { $($default_method)* } impl<T> $trait_name<T> for &'_ PyClassImplCollector<T> {} } } /// Macro which expands to three items /// - Trait for a __setitem__ dunder /// - Trait for the corresponding __delitem__ dunder /// - A macro which will use dtolnay specialisation to generate the shared slot for the two dunders macro_rules! define_pyclass_setattr_slot { ( $set_trait:ident, $del_trait:ident, $set:ident, $del:ident, $set_error:expr, $del_error:expr, $generate_macro:ident, $slot:ident, $func_ty:ident, ) => { slot_fragment_trait! { $set_trait, /// # Safety: _slf and _attr must be valid non-null Python objects #[inline] unsafe fn $set( self, _py: Python, _slf: *mut ffi::PyObject, _attr: *mut ffi::PyObject, _value: NonNull<ffi::PyObject>, ) -> PyResult<()> { $set_error } } slot_fragment_trait! { $del_trait, /// # Safety: _slf and _attr must be valid non-null Python objects #[inline] unsafe fn $del( self, _py: Python, _slf: *mut ffi::PyObject, _attr: *mut ffi::PyObject, ) -> PyResult<()> { $del_error } } #[doc(hidden)] #[macro_export] macro_rules! $generate_macro { ($cls:ty) => {{ unsafe extern "C" fn __wrap( _slf: *mut $crate::ffi::PyObject, attr: *mut $crate::ffi::PyObject, value: *mut $crate::ffi::PyObject, ) -> ::std::os::raw::c_int { use ::std::option::Option::*; use $crate::callback::IntoPyCallbackOutput; use $crate::class::impl_::*; $crate::callback::handle_panic(|py| { let collector = PyClassImplCollector::<$cls>::new(); if let Some(value) = ::std::ptr::NonNull::new(value) { collector.$set(py, _slf, attr, value).convert(py) } else { collector.$del(py, _slf, attr).convert(py) } }) } $crate::ffi::PyType_Slot { slot: $crate::ffi::$slot, pfunc: __wrap as $crate::ffi::$func_ty as _, } }}; } }; } define_pyclass_setattr_slot! { PyClass__setattr__SlotFragment, PyClass__delattr__SlotFragment, __setattr__, __delattr__, Err(PyAttributeError::new_err("can't set attribute")), Err(PyAttributeError::new_err("can't delete attribute")), generate_pyclass_setattr_slot, Py_tp_setattro, setattrofunc, } define_pyclass_setattr_slot! { PyClass__set__SlotFragment, PyClass__delete__SlotFragment, __set__, __delete__, Err(PyNotImplementedError::new_err("can't set descriptor")), Err(PyNotImplementedError::new_err("can't delete descriptor")), generate_pyclass_setdescr_slot, Py_tp_descr_set, descrsetfunc, } define_pyclass_setattr_slot! { PyClass__setitem__SlotFragment, PyClass__delitem__SlotFragment, __setitem__, __delitem__, Err(PyNotImplementedError::new_err("can't set item")), Err(PyNotImplementedError::new_err("can't delete item")), generate_pyclass_setitem_slot, Py_mp_ass_subscript, objobjargproc, } /// Macro which expands to three items /// - Trait for a lhs dunder e.g. __add__ /// - Trait for the corresponding rhs e.g. __radd__ /// - A macro which will use dtolnay specialisation to generate the shared slot for the two dunders macro_rules! define_pyclass_binary_operator_slot { ( $lhs_trait:ident, $rhs_trait:ident, $lhs:ident, $rhs:ident, $generate_macro:ident, $slot:ident, $func_ty:ident, ) => { slot_fragment_trait! { $lhs_trait, /// # Safety: _slf and _other must be valid non-null Python objects #[inline] unsafe fn $lhs( self, _py: Python, _slf: *mut ffi::PyObject, _other: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { Ok(ffi::_Py_NewRef(ffi::Py_NotImplemented())) } } slot_fragment_trait! { $rhs_trait, /// # Safety: _slf and _other must be valid non-null Python objects #[inline] unsafe fn $rhs( self, _py: Python, _slf: *mut ffi::PyObject, _other: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { Ok(ffi::_Py_NewRef(ffi::Py_NotImplemented())) } } #[doc(hidden)] #[macro_export] macro_rules! $generate_macro { ($cls:ty) => {{ unsafe extern "C" fn __wrap( _slf: *mut $crate::ffi::PyObject, _other: *mut $crate::ffi::PyObject, ) -> *mut $crate::ffi::PyObject { $crate::callback::handle_panic(|py| { use ::pyo3::class::impl_::*; let collector = PyClassImplCollector::<$cls>::new(); let lhs_result = collector.$lhs(py, _slf, _other)?; if lhs_result == $crate::ffi::Py_NotImplemented() { $crate::ffi::Py_DECREF(lhs_result); collector.$rhs(py, _other, _slf) } else { ::std::result::Result::Ok(lhs_result) } }) } $crate::ffi::PyType_Slot { slot: $crate::ffi::$slot, pfunc: __wrap as $crate::ffi::$func_ty as _, } }}; } }; } define_pyclass_binary_operator_slot! { PyClass__add__SlotFragment, PyClass__radd__SlotFragment, __add__, __radd__, generate_pyclass_add_slot, Py_nb_add, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__sub__SlotFragment, PyClass__rsub__SlotFragment, __sub__, __rsub__, generate_pyclass_sub_slot, Py_nb_subtract, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__mul__SlotFragment, PyClass__rmul__SlotFragment, __mul__, __rmul__, generate_pyclass_mul_slot, Py_nb_multiply, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__mod__SlotFragment, PyClass__rmod__SlotFragment, __mod__, __rmod__, generate_pyclass_mod_slot, Py_nb_remainder, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__divmod__SlotFragment, PyClass__rdivmod__SlotFragment, __divmod__, __rdivmod__, generate_pyclass_divmod_slot, Py_nb_divmod, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__lshift__SlotFragment, PyClass__rlshift__SlotFragment, __lshift__, __rlshift__, generate_pyclass_lshift_slot, Py_nb_lshift, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__rshift__SlotFragment, PyClass__rrshift__SlotFragment, __rshift__, __rrshift__, generate_pyclass_rshift_slot, Py_nb_rshift, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__and__SlotFragment, PyClass__rand__SlotFragment, __and__, __rand__, generate_pyclass_and_slot, Py_nb_and, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__or__SlotFragment, PyClass__ror__SlotFragment, __or__, __ror__, generate_pyclass_or_slot, Py_nb_or, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__xor__SlotFragment, PyClass__rxor__SlotFragment, __xor__, __rxor__, generate_pyclass_xor_slot, Py_nb_xor, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__matmul__SlotFragment, PyClass__rmatmul__SlotFragment, __matmul__, __rmatmul__, generate_pyclass_matmul_slot, Py_nb_matrix_multiply, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__truediv__SlotFragment, PyClass__rtruediv__SlotFragment, __truediv__, __rtruediv__, generate_pyclass_truediv_slot, Py_nb_true_divide, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__floordiv__SlotFragment, PyClass__rfloordiv__SlotFragment, __floordiv__, __rfloordiv__, generate_pyclass_floordiv_slot, Py_nb_floor_divide, binaryfunc, } slot_fragment_trait! { PyClass__pow__SlotFragment, /// # Safety: _slf and _other must be valid non-null Python objects #[inline] unsafe fn __pow__( self, _py: Python, _slf: *mut ffi::PyObject, _other: *mut ffi::PyObject, _mod: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { Ok(ffi::_Py_NewRef(ffi::Py_NotImplemented())) } } slot_fragment_trait! { PyClass__rpow__SlotFragment, /// # Safety: _slf and _other must be valid non-null Python objects #[inline] unsafe fn __rpow__( self, _py: Python, _slf: *mut ffi::PyObject, _other: *mut ffi::PyObject, _mod: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { Ok(ffi::_Py_NewRef(ffi::Py_NotImplemented())) } } #[doc(hidden)] #[macro_export] macro_rules! generate_pyclass_pow_slot { ($cls:ty) => {{ unsafe extern "C" fn __wrap( _slf: *mut $crate::ffi::PyObject, _other: *mut $crate::ffi::PyObject, _mod: *mut $crate::ffi::PyObject, ) -> *mut $crate::ffi::PyObject { $crate::callback::handle_panic(|py| { use ::pyo3::class::impl_::*; let collector = PyClassImplCollector::<$cls>::new(); let lhs_result = collector.__pow__(py, _slf, _other, _mod)?; if lhs_result == $crate::ffi::Py_NotImplemented() { $crate::ffi::Py_DECREF(lhs_result); collector.__rpow__(py, _other, _slf, _mod) } else { ::std::result::Result::Ok(lhs_result) } }) } $crate::ffi::PyType_Slot { slot: $crate::ffi::Py_nb_power, pfunc: __wrap as $crate::ffi::ternaryfunc as _, } }}; } pub trait PyClassAllocImpl<T> { fn alloc_impl(self) -> Option<ffi::allocfunc>; } impl<T> PyClassAllocImpl<T> for &'_ PyClassImplCollector<T> { fn alloc_impl(self) -> Option<ffi::allocfunc> { None } } pub trait PyClassFreeImpl<T> { fn free_impl(self) -> Option<ffi::freefunc>; } impl<T> PyClassFreeImpl<T> for &'_ PyClassImplCollector<T> { fn free_impl(self) -> Option<ffi::freefunc> { None } } /// Implements a freelist. /// /// Do not implement this trait manually. Instead, use `#[pyclass(freelist = N)]` /// on a Rust struct to implement it. pub trait PyClassWithFreeList: PyClass { fn get_free_list(py: Python) -> &mut FreeList<*mut ffi::PyObject>; } /// Implementation of tp_alloc for `freelist` classes. /// /// # Safety /// - `subtype` must be a valid pointer to the type object of T or a subclass. /// - The GIL must be held. pub unsafe extern "C" fn alloc_with_freelist<T: PyClassWithFreeList>( subtype: *mut ffi::PyTypeObject, nitems: ffi::Py_ssize_t, ) -> *mut ffi::PyObject { let py = Python::assume_gil_acquired(); #[cfg(not(Py_3_8))] bpo_35810_workaround(py, subtype); let self_type = T::type_object_raw(py); // If this type is a variable type or the subtype is not equal to this type, we cannot use the // freelist if nitems == 0 && subtype == self_type { if let Some(obj) = T::get_free_list(py).pop() { ffi::PyObject_Init(obj, subtype); return obj as _; } } ffi::PyType_GenericAlloc(subtype, nitems) } /// Implementation of tp_free for `freelist` classes. /// /// # Safety /// - `obj` must be a valid pointer to an instance of T (not a subclass). /// - The GIL must be held. #[allow(clippy::collapsible_if)] // for if cfg! pub unsafe extern "C" fn free_with_freelist<T: PyClassWithFreeList>(obj: *mut c_void) { let obj = obj as *mut ffi::PyObject; debug_assert_eq!( T::type_object_raw(Python::assume_gil_acquired()), ffi::Py_TYPE(obj) ); if let Some(obj) = T::get_free_list(Python::assume_gil_acquired()).insert(obj) { let ty = ffi::Py_TYPE(obj); // Deduce appropriate inverse of PyType_GenericAlloc let free = if ffi::PyType_IS_GC(ty) != 0 { ffi::PyObject_GC_Del } else { ffi::PyObject_Free }; free(obj as *mut c_void); if cfg!(Py_3_8) { if ffi::PyType_HasFeature(ty, ffi::Py_TPFLAGS_HEAPTYPE) != 0 { ffi::Py_DECREF(ty as *mut ffi::PyObject); } } } } /// Workaround for Python issue 35810; no longer necessary in Python 3.8 #[inline] #[cfg(not(Py_3_8))] unsafe fn bpo_35810_workaround(_py: Python, ty: *mut ffi::PyTypeObject) { #[cfg(Py_LIMITED_API)] { // Must check version at runtime for abi3 wheels - they could run against a higher version // than the build config suggests. use crate::once_cell::GILOnceCell; static IS_PYTHON_3_8: GILOnceCell<bool> = GILOnceCell::new(); if *IS_PYTHON_3_8.get_or_init(_py, || _py.version_info() >= (3, 8)) { // No fix needed - the wheel is running on a sufficiently new interpreter. return; } } ffi::Py_INCREF(ty as *mut ffi::PyObject); } // General methods implementation: either dtolnay specialization trait or inventory if // multiple-pymethods feature is enabled. macro_rules! methods_trait { ($name:ident, $function_name: ident) => { pub trait $name<T> { fn $function_name(self) -> &'static [PyMethodDefType]; } impl<T> $name<T> for &'_ PyClassImplCollector<T> { fn $function_name(self) -> &'static [PyMethodDefType] { &[] } } }; } /// Implementation detail. Only to be used through our proc macro code. /// Method storage for `#[pyclass]`. /// Allows arbitrary `#[pymethod]` blocks to submit their methods, /// which are eventually collected by `#[pyclass]`. #[cfg(all(feature = "macros", feature = "multiple-pymethods"))] pub trait PyMethodsInventory: inventory::Collect { /// Create a new instance fn new(methods: Vec<PyMethodDefType>, slots: Vec<ffi::PyType_Slot>) -> Self; /// Returns the methods for a single `#[pymethods] impl` block fn methods(&'static self) -> &'static [PyMethodDefType]; /// Returns the slots for a single `#[pymethods] impl` block fn slots(&'static self) -> &'static [ffi::PyType_Slot]; } /// Implemented for `#[pyclass]` in our proc macro code. /// Indicates that the pyclass has its own method storage. #[cfg(all(feature = "macros", feature = "multiple-pymethods"))] pub trait HasMethodsInventory { type Methods: PyMethodsInventory; } // Methods from #[pyo3(get, set)] on struct fields. methods_trait!(PyClassDescriptors, py_class_descriptors); // Methods from #[pymethods] if not using inventory. #[cfg(not(feature = "multiple-pymethods"))] methods_trait!(PyMethods, py_methods); // All traits describing slots, as well as the fallback implementations for unimplemented protos // // Protos which are implemented use dtolnay specialization to implement for PyClassImplCollector<T>. // // See https://github.com/dtolnay/case-studies/blob/master/autoref-specialization/README.md macro_rules! slots_trait { ($name:ident, $function_name: ident) => { #[allow(clippy::upper_case_acronyms)] pub trait $name<T> { fn $function_name(self) -> &'static [ffi::PyType_Slot]; } impl<T> $name<T> for &'_ PyClassImplCollector<T> { fn $function_name(self) -> &'static [ffi::PyType_Slot] { &[] } } }; } slots_trait!(PyObjectProtocolSlots, object_protocol_slots); slots_trait!(PyDescrProtocolSlots, descr_protocol_slots); slots_trait!(PyGCProtocolSlots, gc_protocol_slots); slots_trait!(PyIterProtocolSlots, iter_protocol_slots); slots_trait!(PyMappingProtocolSlots, mapping_protocol_slots); slots_trait!(PyNumberProtocolSlots, number_protocol_slots); slots_trait!(PyAsyncProtocolSlots, async_protocol_slots); slots_trait!(PySequenceProtocolSlots, sequence_protocol_slots); slots_trait!(PyBufferProtocolSlots, buffer_protocol_slots); // Protocol slots from #[pymethods] if not using inventory. #[cfg(not(feature = "multiple-pymethods"))] slots_trait!(PyMethodsProtocolSlots, methods_protocol_slots); methods_trait!(PyObjectProtocolMethods, object_protocol_methods); methods_trait!(PyAsyncProtocolMethods, async_protocol_methods); methods_trait!(PyContextProtocolMethods, context_protocol_methods); methods_trait!(PyDescrProtocolMethods, descr_protocol_methods); methods_trait!(PyMappingProtocolMethods, mapping_protocol_methods); methods_trait!(PyNumberProtocolMethods, number_protocol_methods); // On Python < 3.9 setting the buffer protocol using slots doesn't work, so these procs are used // on those versions to set the slots manually (on the limited API). #[cfg(not(Py_LIMITED_API))] pub use ffi::PyBufferProcs; #[cfg(Py_LIMITED_API)] pub struct PyBufferProcs; pub trait PyBufferProtocolProcs<T> { fn buffer_procs(self) -> Option<&'static PyBufferProcs>; } impl<T> PyBufferProtocolProcs<T> for &'_ PyClassImplCollector<T> { fn buffer_procs(self) -> Option<&'static PyBufferProcs> { None } } // Thread checkers #[doc(hidden)] pub trait PyClassThreadChecker<T>: Sized { fn ensure(&self); fn new() -> Self; private_decl! {} } /// Stub checker for `Send` types. #[doc(hidden)] pub struct ThreadCheckerStub<T: Send>(PhantomData<T>); impl<T: Send> PyClassThreadChecker<T> for ThreadCheckerStub<T> { fn ensure(&self) {} #[inline] fn new() -> Self { ThreadCheckerStub(PhantomData) } private_impl! {} } impl<T: PyNativeType> PyClassThreadChecker<T> for ThreadCheckerStub<crate::PyObject> { fn ensure(&self) {} #[inline] fn new() -> Self { ThreadCheckerStub(PhantomData) } private_impl! {} } /// Thread checker for unsendable types. /// Panics when the value is accessed by another thread. #[doc(hidden)] pub struct ThreadCheckerImpl<T>(thread::ThreadId, PhantomData<T>); impl<T> PyClassThreadChecker<T> for ThreadCheckerImpl<T> { fn ensure(&self) { if thread::current().id() != self.0 { panic!( "{} is unsendable, but sent to another thread!", std::any::type_name::<T>() ); } } fn new() -> Self { ThreadCheckerImpl(thread::current().id(), PhantomData) } private_impl! {} } /// Thread checker for types that have `Send` and `extends=...`. /// Ensures that `T: Send` and the parent is not accessed by another thread. #[doc(hidden)] pub struct ThreadCheckerInherited<T: Send, U: PyClassBaseType>(PhantomData<T>, U::ThreadChecker); impl<T: Send, U: PyClassBaseType> PyClassThreadChecker<T> for ThreadCheckerInherited<T, U> { fn ensure(&self) { self.1.ensure(); } fn new() -> Self { ThreadCheckerInherited(PhantomData, U::ThreadChecker::new()) } private_impl! {} } /// Trait denoting that this class is suitable to be used as a base type for PyClass. pub trait PyClassBaseType: Sized { type Dict; type WeakRef; type LayoutAsBase: PyCellLayout<Self>; type BaseNativeType; type ThreadChecker: PyClassThreadChecker<Self>; type Initializer: PyObjectInit<Self>; } /// All PyClasses can be used as a base type. impl<T: PyClass> PyClassBaseType for T { type Dict = T::Dict; type WeakRef = T::WeakRef; type LayoutAsBase = crate::pycell::PyCell<T>; type BaseNativeType = T::BaseNativeType; type ThreadChecker = T::ThreadChecker; type Initializer = crate::pyclass_init::PyClassInitializer<Self>; } /// Default new implementation pub(crate) unsafe extern "C" fn fallback_new( _subtype: *mut ffi::PyTypeObject, _args: *mut ffi::PyObject, _kwds: *mut ffi::PyObject, ) -> *mut ffi::PyObject { crate::callback_body!(py, { Err::<(), _>(crate::exceptions::PyTypeError::new_err( "No constructor defined", )) }) } /// Implementation of tp_dealloc for all pyclasses pub(crate) unsafe extern "C" fn tp_dealloc<T: PyClass>(obj: *mut ffi::PyObject) { crate::callback_body!(py, T::Layout::tp_dealloc(obj, py)) }
use super::constants::RICH_SCHEMA; use super::RequestType; use crate::ledger::constants::{GET_RICH_SCHEMA_BY_ID, GET_RICH_SCHEMA_BY_METADATA}; use crate::ledger::identifiers::rich_schema::RichSchemaId; use crate::utils::validation::{Validatable, ValidationError}; pub const MAX_ATTRIBUTES_COUNT: usize = 125; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct RSContent(pub String); // impl RSContent { // // ToDo: Should it be json-ld validated object or something like that? For now, String object using is enough // pub fn new(jsld_string: String) -> Self { // Self { jsld_string } // } // // pub fn loads(jsld: String) -> Self { // // ToDo: Add JSON-LD object creation from string // Self { jsld_string: jsld } // } // } impl Validatable for RSContent { fn validate(&self) -> Result<(), ValidationError> { // ToDo: Add JSON-LD validation if needed return Ok(()); } } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct RichSchema { pub id: RichSchemaId, pub content: RSContent, pub rs_name: String, pub rs_version: String, pub rs_type: String, pub ver: String, } impl RichSchema { pub fn new( id: RichSchemaId, content: RSContent, rs_name: String, rs_version: String, rs_type: String, ver: String, ) -> Self { Self { id, content, rs_name, rs_version, rs_type, ver, } } } impl Validatable for RichSchema { fn validate(&self) -> Result<(), ValidationError> { // ToDo: add specific validation return self.id.validate(); // Ok(()) => { // match self.content.validate(){ // Ok(()) => return Ok(()), // Err(_) => return Err(_), // }; // }, // Err(_) => return Err(_), // } } } #[derive(Serialize, Debug)] pub struct RichSchemaOperation { #[serde(rename = "type")] pub _type: String, pub id: RichSchemaId, pub content: RSContent, #[serde(rename = "rsName")] pub rs_name: String, #[serde(rename = "rsVersion")] pub rs_version: String, #[serde(rename = "rsType")] pub rs_type: String, pub ver: String, } impl RichSchemaOperation { pub fn new(rs_schema: RichSchema) -> RichSchemaOperation { RichSchemaOperation { _type: Self::get_txn_type().to_string(), id: rs_schema.id, content: rs_schema.content, rs_name: rs_schema.rs_name, rs_version: rs_schema.rs_version, rs_type: rs_schema.rs_type, ver: rs_schema.ver, } } } impl RequestType for RichSchemaOperation { fn get_txn_type<'a>() -> &'a str { RICH_SCHEMA } } // Get RichSchema object from ledger using RichSchema's ID. #[derive(Debug, Serialize, Deserialize, Clone)] pub struct GetRichSchemaById { #[serde(rename = "type")] pub id: RichSchemaId, } impl GetRichSchemaById { pub fn new(id: RichSchemaId) -> Self { Self { id } } } impl Validatable for GetRichSchemaById { fn validate(&self) -> Result<(), ValidationError> { // ToDo: add specific validation if needed return self.id.validate(); } } #[derive(Serialize, Debug)] pub struct GetRichSchemaByIdOperation { #[serde(rename = "type")] pub _type: String, pub id: RichSchemaId, } impl GetRichSchemaByIdOperation { pub fn new(get_rs: GetRichSchemaById) -> Self { Self { _type: Self::get_txn_type().to_string(), id: get_rs.id, } } } impl Validatable for GetRichSchemaByIdOperation { fn validate(&self) -> Result<(), ValidationError> { // ToDo: add specific validation return self.id.validate(); } } impl RequestType for GetRichSchemaByIdOperation { fn get_txn_type<'a>() -> &'a str { GET_RICH_SCHEMA_BY_ID } } // Get RichSchema object from ledger using metadata: // rs_type: Rich Schema object's type enum // rs_name: Rich Schema object's name, // rs_version: Rich Schema object's version, #[derive(Debug, Serialize, Deserialize, Clone)] pub struct GetRichSchemaByMetadata { pub rs_type: String, pub rs_name: String, pub rs_version: String, } impl GetRichSchemaByMetadata { pub fn new(rs_type: String, rs_name: String, rs_version: String) -> Self { Self { rs_type, rs_name, rs_version, } } } #[derive(Serialize, Debug)] pub struct GetRichSchemaByMetadataOperation { #[serde(rename = "type")] pub _type: String, #[serde(rename = "rsType")] pub rs_type: String, #[serde(rename = "rsName")] pub rs_name: String, #[serde(rename = "rsVersion")] pub rs_version: String, } impl GetRichSchemaByMetadataOperation { pub fn new(get_rs: GetRichSchemaByMetadata) -> Self { Self { _type: Self::get_txn_type().to_string(), rs_type: get_rs.rs_type, rs_name: get_rs.rs_name, rs_version: get_rs.rs_version, } } } impl RequestType for GetRichSchemaByMetadataOperation { fn get_txn_type<'a>() -> &'a str { GET_RICH_SCHEMA_BY_METADATA } } #[cfg(test)] mod tests { use super::*; use crate::ledger::constants::RS_SCHEMA_TYPE_VALUE; fn _rich_schema_id() -> RichSchemaId { RichSchemaId::new("did:sov:some_hash_value".to_string()) } fn _get_rs_by_id() -> GetRichSchemaById { GetRichSchemaById::new(_rich_schema_id()) } fn _get_rs_by_metadata() -> GetRichSchemaByMetadata { GetRichSchemaByMetadata::new( RS_SCHEMA_TYPE_VALUE.to_string(), "test_rich_schema".to_string(), "first_version".to_string(), ) } fn _get_rs_by_metadata_op() -> GetRichSchemaByMetadataOperation { GetRichSchemaByMetadataOperation::new(_get_rs_by_metadata()) } fn _rs_schema() -> RichSchema { RichSchema::new( _rich_schema_id(), RSContent(r#"{"json": "ld"; "valid": "object"}"#.to_string()), "test_rich_schema".to_string(), "first_version".to_string(), RS_SCHEMA_TYPE_VALUE.to_string(), "1".to_string(), ) } fn _rs_operation() -> RichSchemaOperation { RichSchemaOperation::new(_rs_schema()) } fn _get_rs_op_by_id() -> GetRichSchemaByIdOperation { GetRichSchemaByIdOperation::new(_get_rs_by_id()) } #[test] fn test_check_type_rs_op() { assert_eq!(_rs_operation()._type, RICH_SCHEMA) } #[test] fn test_check_type_get_rs_by_id_op() { assert_eq!(_get_rs_op_by_id()._type, GET_RICH_SCHEMA_BY_ID) } #[test] fn test_check_type_get_rs_by_metadata_op() { assert_eq!(_get_rs_by_metadata_op()._type, GET_RICH_SCHEMA_BY_METADATA) } }
extern crate sdl2; extern crate ted_interface; extern crate time; extern crate rand; use self::rand::Rng; use std::io; mod terrain; use terrain::*; mod effects; use effects::*; mod flag_selection; mod spell_selection; mod building_selection; use spell_selection::*; mod windows; use windows::{WindowState,WindowArgs}; mod selection_window; mod color_selection_window; use ted_interface::*; use std::cmp::Ordering; use sdl2::keyboard::Keycode; use sdl2::render::*; use sdl2::image::*; use sdl2::rect::Rect; use sdl2::pixels::Color; use std::collections::VecDeque; use std::sync::mpsc; use std::convert::From; use std::path::Path; use std::collections::hash_map::HashMap; use std::thread; use std::f64::consts::PI; const LEFT_CLICK_SPELL: u8=0; const RIGHT_CLICK_SPELL: u8=1; const Q_SPELL: u8=2; const E_SPELL: u8=3; const R_SPELL: u8=4; const SPACE_SPELL: u8=5; type SCanvas=Canvas<sdl2::video::Window>; const VIEW_DISTANCE: f64=3000.0; const MAX_SPELLS: usize=8; const RESOURCE_FONT_SIZE: u16=40; const RESOURCE_OVERLAY_X: i32=670; const RESOURCE_OVERLAY_Y: i32=800; const FOOD_X: i32=RESOURCE_OVERLAY_X+420; const FOOD_Y: i32=RESOURCE_OVERLAY_Y+20; const WOOD_X: i32=RESOURCE_OVERLAY_X+190; const WOOD_Y: i32=RESOURCE_OVERLAY_Y+20; const SMALL_SPRITES: u32=512; const BIG_SPRITES: u32=512; const EXTRA_SPRITES: u32=1024; struct InterpolatedFrame{ pub view_x: f64, pub view_y: f64, pub entities: Vec<(i8, EntitySprite)>, //depth pub trail_sprites: Vec<(f64, TrailSprite)>, pub overlay_info: OverlayInfo, } enum Drawable{ Entity((i8, EntitySprite)), //depth } impl Drawable{ fn get_coords(&self)->(f64, f64){ match self{ &Drawable::Entity((_,ref e))=>{ e.get_coords() }, } } fn get_depth(&self)->i8{ match self{ &Drawable::Entity((depth,_))=>{ depth }, } } } #[derive(Debug)] struct ZippedFrame{ overlay_info: (OverlayInfo, OverlayInfo), view_x: (f64, f64), view_y: (f64, f64), entities: Vec<(i8, EntitySprite, EntitySprite)>, //sprite_id, depth trail_sprites: Vec<(f64, TrailSprite, TrailSprite)>, //last percentage interpolated at length: u64, //time for frame to play out, lagged: bool //Time to play at double speed } pub struct SpellState{ spell_sprites: [Option<u32>; MAX_SPELLS] } impl SpellState{ fn new()->Self{ SpellState{spell_sprites: [None; MAX_SPELLS]} } } pub struct FrameState<'a>{ last: EntityFrame, current: ZippedFrame, zipped: VecDeque<ZippedFrame>, stationary_entities: HashMap<u32,IDEntitySprite>, temporary_entities: Vec<(u8, i8, EntitySprite)>, //lifetime, depth started_frame_time: u64, last_time: u64, percent: f64, chunks: HashMap<(i64, i64), Chunk<'a>>, current_effects: Effects } impl<'a> FrameState<'a>{ fn new()->Self{ let now=time::precise_time_ns(); FrameState{ percent: 0.0, stationary_entities: HashMap::new(), temporary_entities: Vec::new(), last: EntityFrame{ overlay_info: OverlayInfo::default(), entities: Vec::new(), new_stationary_entities: vec![], removed_stationary_entities: vec![], spell_changes: Vec::new(), view_x: 0.0, view_y:0.0, effects: Vec::new() }, current: ZippedFrame{ overlay_info: (OverlayInfo::default(), OverlayInfo::default()), entities: Vec::new(), trail_sprites: Vec::new(), view_x: (0.0,0.0), view_y:(0.0,0.0), length: 1, lagged: false }, started_frame_time: 0, zipped: VecDeque::new(), last_time: now, chunks: HashMap::new(), current_effects: Effects::load() } } } enum Placements{ Flag, Building } pub struct EventState{ quit: bool, up: bool, //if up is currently pressed down: bool, left: bool, right: bool, mouse_left: u8, //0: unpressed, 1: repeat, 2: just pressed mouse_right: u8, //0: unpressed, 1: repeat, 2: just pressed delete_spell: bool, mouse_x: i32, //relative to center of screen mouse_y: i32, flag_colour: u8, building: u8, placement: Placements, } impl EventState{ fn new()->Self{ EventState{ quit: false, delete_spell: false, up: false, down: false, left: false, right: false, mouse_left: 0, mouse_right: 0, mouse_x: 0, mouse_y: 0, flag_colour: 0, building: 0, placement: Placements::Building, } } } struct ExtraImage<'a>{ image: Texture<'a>, width: u32, height: u32 } const BIG_BASIC_IMAGE_SIZE: u32=80; const BIG_BASIC_IMAGE_ROWS: u32=10; const BASIC_IMAGE_SIZE: u32=40; const BASIC_IMAGE_ROWS: u32=10; pub struct ImageLoader<'a>{ basic_images: Texture<'a>, big_basic_images: Texture<'a>, extra_images: Vec<ExtraImage<'a>>, gui_images: Vec<ExtraImage<'a>>, flags: Vec<ExtraImage<'a>>, terrain_images: Texture<'a>, resource_overlay: Texture<'a>, font: sdl2::ttf::Font<'a, 'static> } fn get_basic_image_rect_size(rows: u32, size: u32, i: u32)->Rect{ let x=i%rows; let x=x*size; let y=i/rows; let y=y*size; Rect::new(x as i32, y as i32, size, size) } fn get_basic_image_rect(i: u32)->Rect{ get_basic_image_rect_size(BASIC_IMAGE_ROWS, BASIC_IMAGE_SIZE, i) } fn get_big_basic_image_rect(i: u32)->Rect{ get_basic_image_rect_size(BIG_BASIC_IMAGE_ROWS, BIG_BASIC_IMAGE_SIZE, i) } const SCREEN_WIDTH: i64=1920; const SCREEN_HEIGHT: i64=1080; pub fn gui_thread( mut frame_stream: mpsc::Receiver<Frame>, mut command_stream: mpsc::Sender<Command>, handshake: ServerHandshake ){ let sdl_context=sdl2::init().expect("Could not initialise SDL2"); let mut sdl_event_pump=sdl_context. event_pump().expect("Could not initialise sdl event pump"); let sdl_video_context=sdl_context. video().expect("Could not initialise sdl video context"); let _sdl_image_context=sdl2::image::init(sdl2::image::INIT_PNG). expect("Could not initialise sdl image context"); let _sdl_mixer_context=sdl2::mixer::init( sdl2::mixer::INIT_MP3). expect("Could not initialise mixer"); sdl2::mixer::open_audio( 22050, sdl2::mixer::DEFAULT_FORMAT, 1, 256).expect("Could not open audio device"); let ttf_context=sdl2::ttf::init(). expect("Could not initialise sdl ttf context"); let window=sdl_video_context.window("Ted's world", SCREEN_WIDTH as u32, SCREEN_HEIGHT as u32). build(). expect("Could not create window"); let mut canvas=window.into_canvas().accelerated().present_vsync(). build().expect("Could not create canvas"); let texture_creator=canvas.texture_creator(); let mut window_state=WindowState::new(&handshake); let mut event_state=EventState::new(); let mut spell_state=SpellState::new(); let mut frame_state=FrameState::new(); let mut image_loader=load_images(&texture_creator, &ttf_context); let mut frame_timer_timer=time::precise_time_ns(); while !event_state.quit { parse_events( &mut sdl_event_pump, &mut command_stream, &mut event_state, &mut window_state, ); draw( &mut canvas, &mut image_loader, &texture_creator, &mut frame_state, &spell_state, &mut window_state ); step_effects(&mut frame_state.current_effects); update_frames(&mut canvas, &texture_creator, &mut image_loader, &mut frame_stream, &mut frame_state, &mut spell_state); let mut sleep_time=time::precise_time_ns()-frame_timer_timer; sleep_time=sleep_time/1000000000; let sleep_time=if sleep_time>10 {0} else {10-sleep_time}; frame_timer_timer=time::precise_time_ns(); thread::sleep(std::time::Duration::from_millis(sleep_time)); } //TODO-QUITTING SHOULD KILL NETWORK THREAD } fn zip_frames( a: &EntityFrame, b: &EntityFrame, stationary_entities: &mut HashMap<u32, IDEntitySprite> )->ZippedFrame{ let mut entities=Vec::new(); let mut trail_sprites=Vec::new(); 'b_loop: for b_sprite in b.entities.iter(){ //TODO: currently O(n^2), replace with hashset to make O(n log n) let mut other=None; let mut preexisting=false; for a_sprite in a.entities.iter(){ if a_sprite.id!=b_sprite.id {continue;} other=Some(a_sprite.clone()); preexisting=true; break; } let a_sprite=other.unwrap_or(b_sprite.clone()); match a_sprite.sprite{ EntitySprite::TrailSprite(ref e)=>{ if let EntitySprite::TrailSprite(ref e2)=b_sprite.sprite{ let mut e1=e.clone(); let mut e2=e2.clone(); if preexisting{ e1.adjust_view(a.view_x,a.view_y); } else{ e1.adjust_view(b.view_x,b.view_y); } e2.adjust_view(b.view_x,b.view_y); trail_sprites.push((0.0,e1,e2)) } else{ panic!("Trail and non-trail shared an ID"); } }, _=>{ entities.push( ( b_sprite.depth, a_sprite.sprite.clone(), b_sprite.sprite.clone() ) ); } } }; for id in b.removed_stationary_entities.iter(){ stationary_entities.remove(id); } for entity in b.new_stationary_entities.iter(){ let mut sprite=entity.clone(); sprite.sprite.adjust_view(b.view_x,b.view_y); stationary_entities.insert(entity.id, sprite); } ZippedFrame{ entities, trail_sprites, overlay_info: (a.overlay_info.clone(), b.overlay_info.clone()), view_x: (a.view_x, b.view_x), view_y: (a.view_y,b.view_y), length: 0, //set later, lagged: false } } fn update_frames<'a>( canvas: &mut Canvas<sdl2::video::Window>, texture_creator: &'a TextureCreator<sdl2::video::WindowContext>, image_loader: &mut ImageLoader, frame_stream: &mut mpsc::Receiver<Frame>, frame_state: &mut FrameState<'a>, spell_state: &mut SpellState){ let time_before=frame_state.last_time; let now=time::precise_time_ns(); while let Ok(frame)=frame_stream.try_recv(){ match frame{ Frame::EntityFrameF(entity_frame)=>{ for &(slot, new_value) in entity_frame.spell_changes.iter(){ spell_state.spell_sprites[slot as usize]=new_value; } frame_state.update_percent(); let mut zipped=zip_frames( &frame_state.last, &entity_frame, &mut frame_state.stationary_entities ); for effect in entity_frame.effects.iter(){ draw_effects_sprite(&mut frame_state.current_effects, effect, entity_frame.view_x, entity_frame.view_y); } frame_state.last=entity_frame; frame_state.last_time=now; zipped.length=(now-time_before).min(100*1000000); frame_state.zipped.push_back(zipped); }, Frame::TerrainUpdateFrameF(terrain_update_frame)=>{ terrain::process_update_frame(canvas, frame_state, image_loader, terrain_update_frame); }, Frame::TerrainFrameF(terrain_frame)=>{ terrain::process_terrain_frame(canvas, texture_creator, frame_state, image_loader, terrain_frame) }, Frame::ChunkRemovedFrame(ChunkRemovedFrame {x,y})=>{ frame_state.chunks.remove(&(x,y)); } } } } fn load_extra_image_maybe( texture_loader: &TextureCreator<sdl2::video::WindowContext>, image_name: String )->io::Result<ExtraImage>{ let image=texture_loader.load_texture(Path::new(&("images/extra_images/".to_string()+&image_name))); match image{ Ok(image)=>{ let query=image.query(); Ok(ExtraImage{image: image, width: query.width, height: query.height}) }, Err(string)=>{ Err(io::Error::new(io::ErrorKind::Other, string)) } } } fn load_extra_image( texture_loader: &TextureCreator<sdl2::video::WindowContext>, image_name: String )->ExtraImage{ load_extra_image_maybe(texture_loader, image_name).expect("Could not load extra image {}") } fn load_gui_images(texture_loader: &TextureCreator<sdl2::video::WindowContext>)->Vec<ExtraImage>{ let mut ret=Vec::new(); ret.push(load_extra_image(texture_loader,"window_background.png".to_string())); ret.push(load_extra_image(texture_loader,"color_selection_slider.png".to_string())); ret.push(load_extra_image(texture_loader,"selector.png".to_string())); //2 ret.push(load_extra_image(texture_loader,"selection_box.png".to_string())); //3 ret.push(load_extra_image(texture_loader,"selection_box_big.png".to_string())); //4 ret.push(load_extra_image(texture_loader,"spell_keys.png".to_string())); //5 ret } fn load_extra_images(texture_loader: &TextureCreator<sdl2::video::WindowContext>)->Vec<ExtraImage>{ let mut ret=Vec::new(); ret.push(load_extra_image(texture_loader,"time_sword.png".to_string())); //1024 ret.push(load_extra_image(texture_loader,"time_sword_windup.png".to_string())); ret.push(load_extra_image(texture_loader,"pheobe_arena.png".to_string())); //1026 ret.push(load_extra_image(texture_loader,"fire_field.png".to_string())); //1027 ret.push(load_extra_image(texture_loader,"tree.png".to_string())); ret.push(load_extra_image(texture_loader,"lodestone.png".to_string())); //1029 ret.push(load_extra_image(texture_loader,"wolf_right.png".to_string())); ret.push(load_extra_image(texture_loader,"wolf_left.png".to_string())); ret.push(load_extra_image(texture_loader,"spitter.png".to_string())); //1032 ret.push(load_extra_image(texture_loader,"crack.png".to_string())); ret.push(load_extra_image(texture_loader,"zombie_giant.png".to_string())); ret.push(load_extra_image(texture_loader,"volcano.png".to_string())); //1035 ret.push(load_extra_image(texture_loader,"volcano_rune.png".to_string())); ret.push(load_extra_image(texture_loader,"spell_selector.png".to_string())); ret.push(load_extra_image(texture_loader,"archer_building.png".to_string())); //1038 ret.push(load_extra_image(texture_loader,"barrage.png".to_string())); ret.push(load_extra_image(texture_loader,"player_left.png".to_string())); ret.push(load_extra_image(texture_loader,"player_right.png".to_string())); //1041 ret.push(load_extra_image(texture_loader,"player_up.png".to_string())); ret.push(load_extra_image(texture_loader,"player_down.png".to_string())); ret.push(load_extra_image(texture_loader,"blade_dash.png".to_string())); //1044 ret.push(load_extra_image(texture_loader,"dash_trail.png".to_string())); //1045 ret.push(load_extra_image(texture_loader,"arcane.png".to_string())); //1046 ret.push(load_extra_image(texture_loader,"pentagram.png".to_string())); //1047 ret.push(load_extra_image(texture_loader,"pentagram_icon.png".to_string())); //1048 ret.push(load_extra_image(texture_loader,"archer_icon.png".to_string())); //1049 ret.push(load_extra_image(texture_loader,"lodestone_icon.png".to_string())); //1050 ret.push(load_extra_image(texture_loader,"worker_icon.png".to_string())); //1051 ret.push(load_extra_image(texture_loader,"fireball_icon.png".to_string())); //1052 ret.push(load_extra_image(texture_loader,"blink_icon.png".to_string())); //1053 ret.push(load_extra_image(texture_loader,"blink_icon.png".to_string())); //1054 ret.push(load_extra_image(texture_loader,"snake_icon.png".to_string())); //1055 ret.push(load_extra_image(texture_loader,"volcano_icon.png".to_string())); //1056 ret.push(load_extra_image(texture_loader,"orbiting_fireball_icon.png".to_string())); //1057 ret } fn load_flags<'a>( texture_loader: &'a TextureCreator<sdl2::video::WindowContext>, )->Vec<ExtraImage<'a>>{ let mut ret=Vec::new(); let mut i=0; loop{ let flag_path=format!("flags/{}.png", i); let flag=load_extra_image_maybe( texture_loader, flag_path ); match flag{ Ok(flag)=>{ ret.push(flag) }, Err(_str)=>{ break; } } i+=1; } ret } fn load_images<'a>( texture_loader: &'a TextureCreator<sdl2::video::WindowContext>, ttf_context: &'a sdl2::ttf::Sdl2TtfContext )->ImageLoader<'a>{ let basic_images=texture_loader. load_texture(Path::new("images/basic_images.png")).expect("Unable to load basic images"); let big_basic_images=texture_loader. load_texture(Path::new("images/big_basic_images.png")).expect("Unable to load big basic images"); let terrain_images=texture_loader. load_texture(Path::new("images/terrain_images.png")).expect("Unable to load terrain images"); let resource_overlay=texture_loader. load_texture(Path::new("images/resource_overlay.png")).expect("Unable to load resource overlay"); let extra_images=load_extra_images(texture_loader); let gui_images=load_gui_images(texture_loader); let flags=load_flags(texture_loader); let font=ttf_context.load_font("fonts/digit_font.ttf",RESOURCE_FONT_SIZE).expect("Unable to load digit font"); ImageLoader{ basic_images, big_basic_images, resource_overlay, extra_images, gui_images, flags, terrain_images, font, } } fn send_spell_command(event_state: &mut EventState, command_stream: &mut mpsc::Sender<Command>, slot: u8){ let command=Command::from(SpellCommand{ slot: slot, x: event_state.mouse_x as i16, y: event_state.mouse_y as i16 }); command_stream.send(command).expect("Could not send spell command"); } fn send_spell_command_or_delete(event_state: &mut EventState, command_stream: &mut mpsc::Sender<Command>, slot: u8){ if event_state.delete_spell { let command=Command::from(WipeSlotCommand{slot: slot}); command_stream.send(command).expect("Could not send spell command"); } else {send_spell_command(event_state, command_stream, slot);}; event_state.delete_spell=false; } fn parse_events( event_pump: &mut sdl2::EventPump, command_stream: &mut mpsc::Sender<Command>, event_state: &mut EventState, window_state: &mut WindowState, ){ //check for key repeats { if event_state.mouse_right==2{ event_state.mouse_right=1;//ready to fire } else if event_state.mouse_right==1{ send_spell_command(event_state, command_stream, RIGHT_CLICK_SPELL); } if event_state.mouse_left==2{ event_state.mouse_left=1;//ready to fire } else if event_state.mouse_left==1{ send_spell_command(event_state, command_stream, LEFT_CLICK_SPELL); } } for event in event_pump.poll_iter(){ match event{ sdl2::event::Event::Quit{..}=>event_state.quit=true, sdl2::event::Event::MouseMotion{x,y, ..}=>{ event_state.mouse_x=x-(SCREEN_WIDTH/2) as i32; event_state.mouse_y=y-(SCREEN_HEIGHT/2) as i32; } sdl2::event::Event::KeyDown{keycode: Some(key), ..}=>{ match key { Keycode::Num1=>{ match event_state.placement{ Placements::Flag=>{ command_stream.send(Command::from(FlagCommand{ x: event_state.mouse_x as i16, y: event_state.mouse_y as i16, colour: event_state.flag_colour, })).unwrap(); }, Placements::Building=>{ command_stream.send(Command::from(BuildCommand{ x: event_state.mouse_x as i16, y: event_state.mouse_y as i16, building_type: event_state.building.into(), })).unwrap(); } } } Keycode::Delete=>{ event_state.delete_spell=!event_state.delete_spell; }, Keycode::Semicolon=>{ window_state.spell_selection.toggle_draw(); }, Keycode::C=>{ window_state.color_selection.draw=!window_state.color_selection.draw }, Keycode::M=>{ window_state.flag_selection.toggle_draw(); }, Keycode::B=>{ window_state.building_selection.toggle_draw(); }, Keycode::W=>{ if event_state.up {continue;} event_state.up=true; command_stream.send(Command::from(MoveCommand{ x:SignType::Unchanged, y:SignType::MinusSign })).unwrap(); }, Keycode::A=>{ if event_state.left {continue;} event_state.left=true; command_stream.send(Command::from(MoveCommand{ y:SignType::Unchanged, x:SignType::MinusSign })).unwrap(); } Keycode::S=>{ if event_state.down {continue;} event_state.down=true; command_stream.send(Command::from(MoveCommand{ x:SignType::Unchanged, y:SignType::PlusSign })).unwrap(); } Keycode::D=>{ if event_state.right {continue;} event_state.right=true; command_stream.send(Command::from(MoveCommand{ y:SignType::Unchanged, x:SignType::PlusSign })).unwrap(); }, Keycode::E=>{ send_spell_command_or_delete(event_state, command_stream, E_SPELL); event_state.delete_spell=false; }, Keycode::Q=>{ send_spell_command_or_delete(event_state, command_stream, Q_SPELL); }, Keycode::R=>{ send_spell_command_or_delete(event_state, command_stream, R_SPELL); }, Keycode::Space=>{ send_spell_command_or_delete(event_state, command_stream, SPACE_SPELL); }, Keycode::G=>{ command_stream.send(Command::Grab).expect("Could not send grab command"); }, _=>{} } } sdl2::event::Event::MouseButtonDown{mouse_btn,..}=>{ match mouse_btn{ sdl2::mouse::MouseButton::Left=>{ let mut captured=false; { let mx=event_state.mouse_x; let my=event_state.mouse_y; let mut window_args=WindowArgs{ command_stream, event_state }; for window in window_state.iter_mut(){ if window.handle_click( mx, my, &mut window_args ){ captured=true; break; } } } if !captured{ send_spell_command_or_delete(event_state, command_stream, LEFT_CLICK_SPELL); event_state.mouse_left=2; } } sdl2::mouse::MouseButton::Right=>{ send_spell_command_or_delete(event_state, command_stream, RIGHT_CLICK_SPELL); event_state.mouse_right=2; } _=>{} } } sdl2::event::Event::MouseButtonUp{mouse_btn,..}=>{ match mouse_btn{ sdl2::mouse::MouseButton::Left=>{ event_state.mouse_left=0; } sdl2::mouse::MouseButton::Right=>{ event_state.mouse_right=0; } _=>{} } } sdl2::event::Event::KeyUp{keycode: Some(key), ..}=>{ match key{ Keycode::W=>{ event_state.up=false; command_stream.send(Command::from(MoveCommand{x:SignType::Unchanged, y:if event_state.down {SignType::PlusSign} else {SignType::ZeroSign}})).unwrap(); } Keycode::A=>{ event_state.left=false; command_stream.send(Command::from(MoveCommand{y:SignType::Unchanged, x:if event_state.right {SignType::PlusSign} else {SignType::ZeroSign}})).unwrap(); } Keycode::S=>{ event_state.down=false; command_stream.send(Command::from(MoveCommand{x:SignType::Unchanged, y:if event_state.up {SignType::MinusSign} else {SignType::ZeroSign}})).unwrap(); } Keycode::D=>{ event_state.right=false; command_stream.send(Command::from(MoveCommand{y:SignType::Unchanged, x:if event_state.left {SignType::MinusSign} else {SignType::ZeroSign}})).unwrap(); } _=>{} } } _=>{} } }; } //without the first clause, the game would jolt a pixel whenever it managed to have a //percent>0.5, but this was rare enough to be jerky. fn interpolate_float(v1: f64, v2: f64, percent: f64)->f64{ if (v1-v2).abs()<=1.0 {v2} else {(v1*(1.0-percent)+v2*percent)} } fn interpolate(v1: i64, v2: i64, percent: f64)->i64{ interpolate_float(v1 as f64, v2 as f64, percent).round() as i64 } fn interpolate_u32(v1: u32, v2: u32, percent: f64)->u32{ interpolate_float(v1 as f64, v2 as f64, percent).round() as u32 } pub fn interpolate_direction(start: f64, finish: f64, percent: f64)->f64{ let mut ret; if start>finish{ let diff=start-finish; if start-finish<PI{ ret=start-diff*percent; } else{ let diff=PI*2.0-diff; ret=start-diff*percent; } } else{ let diff=finish-start; if finish-start<PI{ ret=start+diff*percent } else{ let diff=std::f64::consts::PI*2.0-diff; ret=start-diff*percent } } while ret>PI*2.0{ ret-=PI*2.0; } while ret<0.0{ ret+=PI*2.0; } ret } fn interpolate_overlay_info(o1: &OverlayInfo, o2: &OverlayInfo, percent: f64)->OverlayInfo{ OverlayInfo{ resource_info: ResourceInfo{ wood: interpolate_u32(o1.resource_info.wood, o2.resource_info.wood, percent), food: interpolate_u32(o1.resource_info.food, o2.resource_info.food, percent) } } } fn interpolate_sprites(s1: &EntitySprite, s2: &EntitySprite, percent: f64)->EntitySprite{ match (s1,s2){ (&EntitySprite::BasicEntitySprite(ref s1),&EntitySprite::BasicEntitySprite(ref s2))=>{ EntitySprite::BasicEntitySprite(interpolate_basic_sprites(s1,s2,percent)) }, (&EntitySprite::BarSprite(ref s1),&EntitySprite::BarSprite(ref s2))=>{ EntitySprite::BarSprite(interpolate_bar_sprites(s1,s2,percent)) }, (&EntitySprite::ScaleSprite(ref s1), &EntitySprite::ScaleSprite(ref s2))=>{ EntitySprite::ScaleSprite(interpolate_scale_sprites(s1,s2,percent)) }, (s1, &EntitySprite::ScaleSprite(ref s2))=>{ EntitySprite::ScaleSprite(interpolate_scale_sprites( &ScaleSprite{ lower_sprite: Box::new(s1.clone()), scale_factor: 1.0, }, s2, percent )) }, (&EntitySprite::ScaleSprite(ref s1), s2)=>{ EntitySprite::ScaleSprite(interpolate_scale_sprites( s1, &ScaleSprite{ lower_sprite: Box::new(s2.clone()), scale_factor: 1.0, }, percent )) }, (&EntitySprite::HeightSprite(ref s1), &EntitySprite::HeightSprite(ref s2))=>{ EntitySprite::HeightSprite(interpolate_height_sprites(s1,s2,percent)) }, (s1, &EntitySprite::HeightSprite(ref s2))=>{ EntitySprite::HeightSprite(interpolate_height_sprites( &HeightSprite{ lower_sprite: Box::new(s1.clone()), height: 0.0, }, s2, percent )) }, (&EntitySprite::HeightSprite(ref s1), s2)=>{ EntitySprite::HeightSprite(interpolate_height_sprites( s1, &HeightSprite{ lower_sprite: Box::new(s2.clone()), height: 1.0, }, percent )) }, (&EntitySprite::OrbitingSprite(ref s1), &EntitySprite::OrbitingSprite(ref s2))=>{ EntitySprite::OrbitingSprite(interpolate_orbiting_sprites(s1,s2,percent)) }, (ref s1, &EntitySprite::ColorModSprite(ref s2))=>{ EntitySprite::ColorModSprite(ColorModSprite{ r: s2.r, g: s2.g, b: s2.b, lower_sprite: Box::new(interpolate_sprites(s1, &s2.lower_sprite, percent)), }) }, (&EntitySprite::ColorModSprite(ref s1),ref s2)=>{ interpolate_sprites(&s1.lower_sprite, s2, percent) }, _=>panic!(format!("Attempted to interpolate incompatible sprites {:?} and {:?}", s1, s2)) } } fn interpolate_trail_sprites(s1: &TrailSprite, s2: &TrailSprite)->TrailSprite{ let mut combined=Vec::new(); combined.push(s1.lower_sprites[s1.lower_sprites.len()-1].clone()); combined.append(&mut s2.lower_sprites.clone()); TrailSprite{ lower_sprites: combined, lifetime: s1.lifetime, trail_depth: s1.trail_depth, fidelity: s2.fidelity, } } fn interpolate_basic_sprites( s1: &BasicEntitySprite, s2: &BasicEntitySprite, percent: f64 )->BasicEntitySprite{ let x=interpolate_float(s1.x,s2.x,percent); let y=interpolate_float(s1.y,s2.y,percent); let direction=interpolate_direction(s1.direction, s2.direction, percent); BasicEntitySprite{x:x,y:y,direction: direction, sprite:s2.sprite} } fn interpolate_bar_sprites(s1: &BarSprite, s2: &BarSprite,percent: f64)->BarSprite{ let bar_percent=interpolate(s1.bar_percent as i64,s2.bar_percent as i64, percent); let x=interpolate_float(s1.x,s2.x,percent); let y=interpolate_float(s1.y,s2.y,percent); BarSprite{ bar_percent:bar_percent as u8, bar_width: s2.bar_width, bar_height: s2.bar_height, x: x, y: y } } fn interpolate_scale_sprites(s1: &ScaleSprite, s2: &ScaleSprite, percent: f64)->ScaleSprite{ let scale_factor=interpolate_float(s1.scale_factor, s2.scale_factor, percent); let lower_sprite=Box::new(interpolate_sprites(&s1.lower_sprite,&s2.lower_sprite, percent)); ScaleSprite{scale_factor, lower_sprite} } fn interpolate_height_sprites(s1: &HeightSprite, s2: &HeightSprite, percent: f64)->HeightSprite{ let height=interpolate_float(s1.height, s2.height, percent); let lower_sprite=Box::new(interpolate_sprites(&s1.lower_sprite,&s2.lower_sprite, percent)); HeightSprite{height, lower_sprite} } fn interpolate_orbiting_sprites(s1: &OrbitingSprite, s2: &OrbitingSprite, percent: f64)->OrbitingSprite{ let mut finish_angle=s2.angle; if s1.clockwise{ if s2.angle<s1.angle{ finish_angle+=2.0*std::f64::consts::PI; } } else{ if s2.angle>s1.angle{ finish_angle-=2.0*std::f64::consts::PI; } } let radius=interpolate_float(s1.radius, s2.radius, percent); let angle=interpolate_float(s1.angle, finish_angle, percent); let lower_sprite=interpolate_sprites(&s1.lower_sprite, &s2.lower_sprite, percent); OrbitingSprite{radius: radius, angle: angle, lower_sprite: Box::new(lower_sprite), clockwise: s2.clockwise} } fn interpolate_frames(zipped: &ZippedFrame, percent: f64)->InterpolatedFrame{ let mut entities=Vec::new(); let mut trail_sprites=Vec::new(); for &(depth, ref e1,ref e2) in zipped.entities.iter(){ let ei=interpolate_sprites(e1,e2,percent); entities.push((depth, ei)) }; for &(last_progress, ref e1, ref e2) in zipped.trail_sprites.iter(){ let ei=interpolate_trail_sprites(e1,e2); trail_sprites.push((last_progress, ei)); } let view_x=interpolate_float(zipped.view_x.0,zipped.view_x.1,percent); let view_y=interpolate_float(zipped.view_y.0,zipped.view_y.1,percent); let overlay_info=interpolate_overlay_info(&zipped.overlay_info.0, &zipped.overlay_info.1,percent); InterpolatedFrame{ entities, overlay_info, view_x, view_y, trail_sprites, } } impl<'a> FrameState<'a>{ fn update_percent(&mut self){ let time_passed=(time::precise_time_ns()-self.started_frame_time) as f64; let percent: f64=time_passed/(self.current.length as f64); self.percent=percent; if self.current.lagged{ self.percent*=4.0; } } } fn draw( canvas: &mut Canvas<sdl2::video::Window>, image_loader: &mut ImageLoader, texture_creator: &TextureCreator<sdl2::video::WindowContext>, frame_state: &mut FrameState, spell_state: &SpellState, window_state: &mut WindowState ){ canvas.clear(); frame_state.update_percent(); let mut to_draw=interpolate_frames(&frame_state.current, frame_state.percent); { let progress=frame_state.percent.min(1.0); for trail_sprite in to_draw.trail_sprites.iter(){ let &(last_progress, ref sprite)=trail_sprite; draw_trail_sprite( frame_state, &sprite, last_progress, progress, ); } for &mut (ref mut last_progress, _, _) in frame_state.current.trail_sprites.iter_mut(){ *last_progress=progress; } } if frame_state.percent>=1.0{ if frame_state.zipped.is_empty(){ frame_state.percent=1.0; } else{ frame_state.percent=frame_state.percent%1.0; frame_state.current=frame_state.zipped.pop_front().unwrap(); frame_state.started_frame_time= time::precise_time_ns()- ((frame_state.current.length as f64)*frame_state.percent) as u64; let mut i=0; while i<frame_state.temporary_entities.len(){ let mut remove=false; { let (ref mut lifetime, _, _)=frame_state.temporary_entities[i]; if *lifetime==0{ remove=true; } else{ *lifetime-=1; } } if remove{ frame_state.temporary_entities.swap_remove(i); } else{ i+=1 } } to_draw=interpolate_frames(&frame_state.current, frame_state.percent); } } let len=frame_state.zipped.len(); if len>1{ if len>2{ println!("Unusually high frame state count of {}", frame_state.zipped.len()); } frame_state.current.lagged=true; } let (shake_x, shake_y)=if frame_state.current_effects.shake>0{ let shake=frame_state.current_effects.shake as i16; let mut rng=rand::thread_rng(); let x=rng.gen_range(-shake, shake); let y=rng.gen_range(-shake, shake); (x as f64,y as f64) } else{ (0.0,0.0) }; let entity_view_x=-(SCREEN_WIDTH/2) as f64+shake_x; let entity_view_y=-(SCREEN_HEIGHT/2) as f64+shake_y; let view_x=to_draw.view_x as i64-SCREEN_WIDTH/2+shake_x as i64; let view_y=to_draw.view_y as i64-SCREEN_HEIGHT/2+shake_y as i64; terrain::animate(canvas, image_loader, frame_state); for (&(x,y),chunk) in frame_state.chunks.iter(){ let dst_rect=Rect::new((x*400-view_x) as i32, (y*400-view_y) as i32, 400, 400); canvas.copy(&chunk.image, None, Some(dst_rect)).expect("Cannot draw chunk image to canvas"); } let mut entities: Vec<Drawable>=Vec::new(); for entity in to_draw.entities.iter().map(|x|{ Drawable::Entity(x.clone()) }) .chain(frame_state.stationary_entities.values().map(|x|{ let mut x=x.clone(); x.sprite.adjust_view(-to_draw.view_x,-to_draw.view_y); Drawable::Entity((x.depth, x.sprite.clone())) })) .chain(frame_state.temporary_entities.iter().map(|&(_,depth, ref sprite)|{ let mut x=sprite.clone(); x.adjust_view(-to_draw.view_x,-to_draw.view_y); Drawable::Entity((depth, x)) })) { let insert_pos=entities.binary_search_by( |sprite|{ match sprite.get_depth().cmp(&entity.get_depth()){ Ordering::Equal=>{ let y=&entity.get_coords().1; let other_y=sprite.get_coords().1; other_y.partial_cmp(y).unwrap_or(Ordering::Greater) }, x=>x } } ).unwrap_or_else(|e|e); entities.insert(insert_pos, entity); }; for entity in entities.iter(){ match entity{ &Drawable::Entity((_, ref entity))=>{ draw_entity_sprite( canvas, image_loader, frame_state, &entity, entity_view_x, entity_view_y, DrawEffects::default() ); }, } } draw_spells(canvas, image_loader, spell_state); draw_overlay(canvas, image_loader, texture_creator, &to_draw.overlay_info); for window in window_state.iter_mut(){ window.draw(canvas, image_loader); } canvas.present(); } fn draw_overlay( canvas: &mut Canvas<sdl2::video::Window>, image_loader: &mut ImageLoader, texture_loader: &TextureCreator<sdl2::video::WindowContext>, overlay_info: &OverlayInfo ){ { let query=image_loader.resource_overlay.query(); let dst_rect=Rect::new( RESOURCE_OVERLAY_X, RESOURCE_OVERLAY_Y, query.width, query.height ); canvas.copy(&image_loader.resource_overlay, None, Some(dst_rect)).expect("Unable to draw resource overlay"); } let resource_info=&overlay_info.resource_info; draw_resource_number( canvas, image_loader, texture_loader, resource_info.food, FOOD_X, FOOD_Y ); draw_resource_number( canvas, image_loader, texture_loader, resource_info.wood, WOOD_X, WOOD_Y ); } fn draw_resource_number( canvas: &mut Canvas<sdl2::video::Window>, image_loader: &mut ImageLoader, texture_loader: &TextureCreator<sdl2::video::WindowContext>, val: u32, x: i32, y: i32 ){ let res_str=val.to_string(); let surface=image_loader.font.render(&res_str).solid(Color::RGBA(0,0,0,255)).expect("unable to draw digit"); let texture=texture_loader.create_texture_from_surface(&surface). expect("Unable to create resource string texture"); let dst_rect=Rect::new(x, y, surface.width(), surface.height()); canvas.copy(&texture, None, Some(dst_rect)).expect("Cannot draw resource string to canvas"); } #[derive(Clone)] struct DrawEffects{ scale_factor: Option<f64>, orbit: Option<(f64,f64)>, //angle, radius color_mod: Option<(u8,u8,u8)>, client_side: bool, //draw images from gui_images } impl DrawEffects{ fn default()->Self{ DrawEffects{ scale_factor: None, orbit: None, color_mod: None, client_side: false, } } fn client_side()->Self{ let mut ret=Self::default(); ret.client_side=true; ret } fn scale_by(mut self, fac: f64)->Self{ self.scale_factor=Some(self.scale_factor.unwrap_or(1.0)*fac); self } fn orbit(mut self, angle: f64, radius: f64)->Self{ self.orbit=Some((angle,radius)); self } fn color(mut self, r: u8, g: u8, b: u8)->Self{ self.color_mod=Some((r,g,b)); self } } fn draw_entity_sprite( canvas: &mut Canvas<sdl2::video::Window>, image_loader: &mut ImageLoader, frame_state: &mut FrameState, sprite: &EntitySprite, view_x: f64, view_y: f64, draw_effects: DrawEffects ){ match sprite{ &EntitySprite::BarSprite(ref e)=>draw_bar_sprite(canvas, &e, view_x, view_y, draw_effects), &EntitySprite::BasicEntitySprite(ref e)=>draw_basic_entity_sprite(canvas, image_loader, &e, view_x, view_y, draw_effects), &EntitySprite::TrailSprite(_)=>{panic!("Trail sprite in generic list")}, &EntitySprite::ScaleSprite(ref e)=>draw_entity_sprite(canvas, image_loader, frame_state, &e.lower_sprite, view_x, view_y, draw_effects.scale_by(e.scale_factor)), &EntitySprite::ColorModSprite(ref e)=>{ draw_entity_sprite(canvas, image_loader, frame_state, &e.lower_sprite, view_x, view_y, draw_effects.color(e.r,e.g,e.b)); }, &EntitySprite::HeightSprite(ref e)=>{ let distance=VIEW_DISTANCE-e.height; let scale_factor=(VIEW_DISTANCE*VIEW_DISTANCE)/(distance*distance); draw_entity_sprite( canvas, image_loader, frame_state, &e.lower_sprite, view_x, view_y, draw_effects.scale_by(scale_factor) ); }, &EntitySprite::OrbitingSprite(ref e)=>draw_entity_sprite(canvas, image_loader, frame_state, &e.lower_sprite, view_x, view_y, draw_effects.orbit(e.angle, e.radius)), } } fn draw_trail_sprite( frame_state: &mut FrameState, sprite: &TrailSprite, last_progress: f64, progress: f64, ){ let range=(sprite.lower_sprites.len()-1) as f64; let progress_diff=progress-last_progress; for i in 0..sprite.fidelity{ let percent=last_progress+i as f64*progress_diff/(sprite.fidelity as f64); let through=percent*range; let first=through.floor() as usize; let first_sprite=&sprite.lower_sprites[first]; let second=through.ceil() as usize; let second_sprite=&sprite.lower_sprites[second]; let drawn_sprite=interpolate_sprites( first_sprite, second_sprite, percent-(first as f64/range) ); frame_state.temporary_entities.push((sprite.lifetime, sprite.trail_depth, drawn_sprite)); } } fn draw_bar_sprite(canvas: &mut Canvas<sdl2::video::Window>, sprite: &BarSprite, view_x: f64, view_y: f64, draw_effects: DrawEffects){ let x=(sprite.x-view_x).round() as i64; let y=(sprite.y-view_y).round() as i64; let scale_factor=draw_effects.scale_factor.unwrap_or(1.0); let bar_width=((sprite.bar_width as f64)*scale_factor) as u32; let bar_height=((sprite.bar_height as f64)*scale_factor) as u32; let full_rect=Rect::new(x as i32, y as i32, bar_width as u32, bar_height as u32); let health_pixels=((bar_width as f64)*(sprite.bar_percent as f64)/100.0) as u32; let health_rect=Rect::new(x as i32, y as i32, health_pixels, bar_height as u32); canvas.set_draw_color(Color::RGB(255,0,0)); canvas.fill_rect(full_rect).expect("Could not fill base bar for sprite"); canvas.set_draw_color(Color::RGB(0,255,0)); if health_pixels>0 {canvas.fill_rect(health_rect).expect("could not fill health bar for sprite");}; } fn draw_basic_entity_sprite( canvas: &mut Canvas<sdl2::video::Window>, image_loader: &mut ImageLoader, sprite: &BasicEntitySprite, view_x: f64, view_y: f64, draw_effects: DrawEffects, ){ let mut sprite=sprite.clone(); match draw_effects.orbit{ Some((angle,radius))=>{ sprite.x+=radius*angle.cos(); sprite.y+=radius*angle.sin(); }, None=>{} }; let get_dst_rect=|mut x: f64, mut y: f64,width: u32, height: u32|{ x-=view_x; y-=view_y; Rect::new( ((x.round() as i64)-(width as i64)/2) as i32, ((y.round() as i64)-(height as i64)/2) as i32, width, height ) }; let angle_degrees=sprite.direction*180.0/std::f64::consts::PI; let scale_factor=draw_effects.scale_factor.unwrap_or(1.0); let src_image; let src_rect; let dst_rect; if draw_effects.client_side{ let sprite_number=sprite.sprite; if sprite_number>=image_loader.gui_images.len() as u32{ panic!(format!("Unsupported gui image {}",sprite_number))}; let extra_image=&mut image_loader.gui_images[sprite_number as usize]; src_image=&mut extra_image.image; src_rect=None; dst_rect=get_dst_rect( sprite.x, sprite.y, (extra_image.width as f64*scale_factor) as u32, (extra_image.height as f64*scale_factor) as u32, ); } else{ let sprite_number=sprite.sprite; if sprite_number<SMALL_SPRITES{ let im_size=((BASIC_IMAGE_SIZE as f64)*scale_factor) as u32; src_rect=Some(get_basic_image_rect(sprite_number)); dst_rect=get_dst_rect(sprite.x, sprite.y, im_size, im_size); src_image=&mut image_loader.basic_images; } else{ let sprite_number=sprite_number-SMALL_SPRITES; if sprite_number<BIG_SPRITES{ let im_size=((BIG_BASIC_IMAGE_SIZE as f64)*scale_factor) as u32; src_rect=Some(get_big_basic_image_rect(sprite_number)); dst_rect=get_dst_rect(sprite.x, sprite.y, im_size, im_size); src_image=&mut image_loader.big_basic_images; } else{ let sprite_number=sprite_number-BIG_SPRITES; if sprite_number<EXTRA_SPRITES{ if sprite_number>=image_loader.extra_images.len() as u32{ panic!(format!("Unsupported exceptional sprite {}",sprite_number))}; let extra_image=&mut image_loader.extra_images[sprite_number as usize]; src_image=&mut extra_image.image; src_rect=None; dst_rect=get_dst_rect( sprite.x, sprite.y, (extra_image.width as f64*scale_factor) as u32, (extra_image.height as f64*scale_factor) as u32, ); } else{ let sprite_number=sprite_number-EXTRA_SPRITES; if sprite_number>=image_loader.flags.len() as u32{ panic!(format!("Unsupported flag sprite {}",sprite_number))}; let extra_image=&mut image_loader.flags[sprite_number as usize]; src_image=&mut extra_image.image; src_rect=None; dst_rect=get_dst_rect( sprite.x, sprite.y, extra_image.width, extra_image.height, ); } } } } let mut reset_color_mod=false; if let Some((r,g,b))=draw_effects.color_mod{ src_image.set_color_mod(r,g,b); reset_color_mod=true; } canvas.copy_ex( src_image, src_rect, Some(dst_rect), angle_degrees, None, false, false ).expect("Failed to render extra sprite"); if reset_color_mod{ src_image.set_color_mod(255,255,255); } }
mod parser; pub mod tokenizer; use parser::create::{CreateQuery}; use sqlparser::ast::{Statement}; use sqlparser::dialect::SQLiteDialect; use sqlparser::parser::{Parser, ParserError}; use crate::error::{SQLRiteError, Result}; #[derive(Debug,PartialEq)] pub enum SQLCommand { Insert(String), Delete(String), Update(String), CreateTable(String), Select(String), Unknown(String), } impl SQLCommand { pub fn new(command: String) -> SQLCommand { let v = command.split(" ").collect::<Vec<&str>>(); match v[0] { "insert" => SQLCommand::Insert(command), "update" => SQLCommand::Update(command), "delete" => SQLCommand::Delete(command), "create" => SQLCommand::CreateTable(command), "select" => SQLCommand::Select(command), _ => SQLCommand::Unknown(command), } } } /// Performs initial parsing of SQL Statement using sqlparser-rs pub fn process_command(query: &str) -> Result<String> { let dialect = SQLiteDialect{}; let message: String; let mut ast = Parser::parse_sql(&dialect, &query).map_err(SQLRiteError::from)?; if ast.len() > 1 { return Err(SQLRiteError::SqlError(ParserError::ParserError(format!( "Expected a single query statement, but there are {}", ast.len() )))); } let query = ast.pop().unwrap(); // Initialy only implementing some basic SQL Statements match query { Statement::CreateTable{..} => { let result = CreateQuery::new(&query); match result { Ok(payload) => { println!("Table name: {}", payload.table_name); for col in payload.columns { println!("Column Name: {}, Column Type: {}", col.name, col.datatype); } }, Err(err) => return Err(err), } message = String::from("CREATE TABLE Statement executed."); // TODO: Push table to DB }, Statement::Query(_query) => message = String::from("SELECT Statement executed."), Statement::Insert {..} => message = String::from("INSERT Statement executed."), Statement::Delete{..} => message = String::from("DELETE Statement executed."), _ => { return Err(SQLRiteError::NotImplemented( "SQL Statement not supported yet.".to_string())) } }; Ok(message) } #[cfg(test)] mod tests { use super::*; #[test] fn process_command_select_test() { let inputed_query = String::from("SELECT * from users;"); let _ = match process_command(&inputed_query) { Ok(response) => assert_eq!(response, "SELECT Statement executed."), Err(_) => assert!(false), }; } #[test] fn process_command_insert_test() { let inputed_query = String::from("INSERT INTO users (name) Values ('josh');"); let _ = match process_command(&inputed_query) { Ok(response) => assert_eq!(response, "INSERT Statement executed."), Err(_) => assert!(false), }; } #[test] fn process_command_delete_test() { let inputed_query = String::from("DELETE FROM users WHERE id=1;"); let _ = match process_command(&inputed_query) { Ok(response) => assert_eq!(response, "DELETE Statement executed."), Err(_) => assert!(false), }; } #[test] fn process_command_not_implemented_test() { let inputed_query = String::from("UPDATE users SET name='josh' where id=1;"); let expected = Err(SQLRiteError::NotImplemented("SQL Statement not supported yet.".to_string())); let result = process_command(&inputed_query).map_err(|e| e); assert_eq!(result, expected); } }
use std::str::CharIndices; pub type Spanned<Tok, Loc, Error> = Result<(Loc, Tok, Loc), Error>; #[derive(Copy, Clone, Debug)] pub enum Tok<'input> { Comment(&'input str), Str(&'input str), SectionKey(&'input str), SectionValue(&'input str), Guid(&'input str), Id(&'input str), DigitsAndDots(&'input str), OpenElement(&'input str), CloseElement(&'input str), Comma, Eq, Skip, } enum LexerContext { None, SectionDefinition, InsideSection, InsideString, } pub struct Lexer<'input> { chars: std::iter::Peekable<CharIndices<'input>>, input: &'input str, context: LexerContext, } impl<'input> Lexer<'input> { pub fn new(input: &'input str) -> Self { Lexer { chars: input.char_indices().peekable(), input, context: LexerContext::None, } } fn identifier(&mut self, i: usize) -> (Tok<'input>, usize) { let finish; loop { if let Some((j, c)) = self.chars.peek() { match *c { 'a'..='z' | 'A'..='Z' => { self.chars.next(); } '(' => { finish = *j; break; } _ => { if Lexer::is_close_element(&self.input[i..]) { self.context = LexerContext::None; return (Tok::CloseElement(&self.input[i..*j]), *j); } return (Tok::Id(&self.input[i..*j]), *j); } } } else { if Lexer::is_close_element(&self.input[i..]) { return (Tok::CloseElement(&self.input[i..]), self.input.len()); } return (Tok::Id(&self.input[i..]), self.input.len()); } } // Skip ( self.chars.next(); let section_suffix = "Section"; let sub: String = self.input[i..finish] .chars() .rev() .take(section_suffix.len()) .collect(); let sub: String = sub.chars().rev().collect(); if sub == section_suffix { self.context = LexerContext::SectionDefinition; }; (Tok::OpenElement(&self.input[i..finish]), finish) } fn comment(&mut self, i: usize) -> Option<Spanned<Tok<'input>, usize, ()>> { loop { match self.chars.peek() { Some((j, '\n' | '\r')) => { return Some(Ok((i, Tok::Comment(&self.input[i..*j]), *j))); } None => { return Some(Ok((i, Tok::Comment(&self.input[i..]), self.input.len()))); } _ => { self.chars.next(); } } } } fn guid(&mut self, i: usize) -> (usize, Tok<'input>, usize) { let finish; loop { match self.chars.peek() { Some((j, '}')) => { finish = *j + 1; break; } None => { return (i, Tok::Guid(&self.input[i..]), self.input.len()); } _ => { self.chars.next(); } } } // Skip { self.chars.next(); (i, Tok::Guid(&self.input[i..finish]), finish) } fn digits_with_dots(&mut self, i: usize) -> Option<Spanned<Tok<'input>, usize, ()>> { loop { match self.chars.peek() { Some((j, c)) => match *c { '0'..='9' | '.' => { self.chars.next(); } _ => return Some(Ok((i, Tok::DigitsAndDots(&self.input[i..*j]), *j))), }, None => { return Some(Ok(( i, Tok::DigitsAndDots(&self.input[i..]), self.input.len(), ))); } } } } fn string(&mut self, i: usize) -> Option<Spanned<Tok<'input>, usize, ()>> { match self.context { LexerContext::InsideString => { self.context = LexerContext::None; return Some(Ok((i, Tok::Skip, i + 1))); } _ => { self.context = LexerContext::InsideString; } } let mut guid = false; loop { match self.chars.peek() { // Guid start Some((_, '{')) => { guid = true; self.chars.next(); } Some((j, '"')) => { let start = i + 1; let val = &self.input[start..*j]; return if guid { Some(Ok((start, Tok::Guid(val), *j - 1))) } else { Some(Ok((start, Tok::Str(val), *j))) }; } None => return Some(Ok((i, Tok::Str(&self.input[i..]), self.input.len()))), _ => { self.chars.next(); } } } } fn section_key(&mut self, i: usize) -> Option<Spanned<Tok<'input>, usize, ()>> { let mut start = i; while let Some((j, '\r' | '\n' | '\t' | ' ')) = self.chars.peek() { start = *j + 1; self.chars.next(); } if Lexer::is_close_element(&self.input[start..]) { self.context = LexerContext::None; return Some(Ok((start, Tok::Skip, start))); } match self.context { LexerContext::InsideSection => {} LexerContext::SectionDefinition => self.context = LexerContext::InsideSection, _ => return Some(Ok((start, Tok::Skip, start))), } loop { match self.chars.peek() { Some((j, '=')) => { let finish = Lexer::trim_end(self.input, *j); let val = if finish < start { "" } else { &self.input[start..finish] }; return Some(Ok((start, Tok::SectionKey(val), finish))); } None => { let val = &self.input[start..]; if Lexer::is_close_element(val) { return Some(Ok((start, Tok::CloseElement(val), self.input.len()))); } return Some(Ok((start, Tok::SectionKey(val), self.input.len()))); } _ => { self.chars.next(); } } } } fn section_value(&mut self, i: usize) -> Option<Spanned<Tok<'input>, usize, ()>> { match self.context { LexerContext::InsideSection => { // i + 1 skips equal sign (=) let start = Lexer::trim_start(self.input, i + 1); loop { match self.chars.peek() { Some((j, '\r' | '\n')) => { let finish = *j; return Some(Ok(( start, Tok::SectionValue(&self.input[start..finish]), finish, ))); } None => { return Some(Ok(( start, Tok::SectionValue(&self.input[start..]), self.input.len(), ))); } _ => { self.chars.next(); } } } } _ => Some(Ok((i, Tok::Eq, i + 1))), } } fn is_close_element(val: &str) -> bool { // This implementation is ugly equivalent of: // let substr: String = val.chars().take("End".len()).collect(); // substr == "End" // but without allocations let mut it = val.chars(); let mut next_is = |c: char| -> bool { it.next().map(|x| x == c).unwrap_or_default() }; next_is('E') && next_is('n') && next_is('d') } fn trim_start(s: &str, mut i: usize) -> usize { i += Lexer::count_whitespaces(s[i..].chars()); i } fn trim_end(s: &str, mut i: usize) -> usize { i -= Lexer::count_whitespaces(s[..i].chars().rev()); i } fn count_whitespaces<I: Iterator<Item = char>>(it: I) -> usize { it.take_while(|c| ' ' == *c || '\t' == *c).count() } fn current(&mut self, i: usize, ch: char) -> Option<Spanned<Tok<'input>, usize, ()>> { match ch { '\r' | '\n' => return self.section_key(i), '=' => return self.section_value(i), ',' => return Some(Ok((i, Tok::Comma, i + 1))), ')' => return Some(Ok((i, Tok::Skip, i + 1))), '0'..='9' => return self.digits_with_dots(i), '{' => return Some(Ok(self.guid(i))), '"' => return self.string(i), '#' => return self.comment(i), 'a'..='z' | 'A'..='Z' => { let (tok, loc) = self.identifier(i); return Some(Ok((i, tok, loc))); } _ => {} } None } } impl<'input> Iterator for Lexer<'input> { type Item = Spanned<Tok<'input>, usize, ()>; fn next(&mut self) -> Option<Self::Item> { loop { let (i, c) = self.chars.next()?; if let ' ' | '\t' = c { continue; } let tok = self.current(i, c)?; match tok { Ok(_x @ (_, Tok::Skip, _)) => continue, Ok(_) | Err(_) => {} } return Some(tok); } } } #[cfg(test)] mod tests { use super::*; use rstest::rstest; #[test] fn lexer() { let input = r#"# comment 12.00 ({405827CB-84E1-46F3-82C9-D889892645AC}) . | "{CFBAE2FB-6E3F-44CF-9FC9-372D6EA8DD3D}" "str" x = y "#; let lexer = Lexer::new(input); for tok in lexer { println!("{tok:#?}"); } } #[test] fn lex_solution() { let lexer = Lexer::new(REAL_SOLUTION); for tok in lexer { println!("{tok:#?}"); } } #[test] fn lex_solution_no_last_line_break() { let lexer = Lexer::new(REAL_SOLUTION.trim_end()); for tok in lexer { println!("{tok:#?}"); } } #[rstest] #[case("1 ", 1)] #[case("1", 1)] #[case(" 1", 3)] #[case(" ", 0)] #[case(" ", 0)] #[case(" \t", 0)] #[case("", 0)] #[case(" ", 0)] #[trace] fn trim_end_tests(#[case] content: &str, #[case] expected: usize) { // Arrange let i: usize = content.len(); // Act let actual = Lexer::trim_end(content, i); // Assert assert_eq!(actual, expected); } const REAL_SOLUTION: &str = r#" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26403.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{930C7802-8A8C-48F9-8165-68863BCCD9DD}") = "logviewer.install", "logviewer.install\logviewer.install.wixproj", "{27060CA7-FB29-42BC-BA66-7FC80D498354}" ProjectSection(ProjectDependencies) = postProject {405827CB-84E1-46F3-82C9-D889892645AC} = {405827CB-84E1-46F3-82C9-D889892645AC} {CFBAE2FB-6E3F-44CF-9FC9-372D6EA8DD3D} = {CFBAE2FB-6E3F-44CF-9FC9-372D6EA8DD3D} EndProjectSection EndProject Project("{930C7802-8A8C-48F9-8165-68863BCCD9DD}") = "logviewer.install.bootstrap", "logviewer.install.bootstrap\logviewer.install.bootstrap.wixproj", "{1C0ED62B-D506-4E72-BBC2-A50D3926466E}" ProjectSection(ProjectDependencies) = postProject {27060CA7-FB29-42BC-BA66-7FC80D498354} = {27060CA7-FB29-42BC-BA66-7FC80D498354} EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "solution items", "solution items", "{3B960F8F-AD5D-45E7-92C0-05B65E200AC4}" ProjectSection(SolutionItems) = preProject .editorconfig = .editorconfig appveyor.yml = appveyor.yml logviewer.xml = logviewer.xml WiX.msbuild = WiX.msbuild EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "logviewer.tests", "logviewer.tests\logviewer.tests.csproj", "{939DD379-CDC8-47EF-8D37-0E5E71D99D30}" ProjectSection(ProjectDependencies) = postProject {383C08FC-9CAC-42E5-9B02-471561479A74} = {383C08FC-9CAC-42E5-9B02-471561479A74} EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "logviewer.logic", "logviewer.logic\logviewer.logic.csproj", "{383C08FC-9CAC-42E5-9B02-471561479A74}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{B720ED85-58CF-4840-B1AE-55B0049212CC}" ProjectSection(SolutionItems) = preProject .nuget\NuGet.Config = .nuget\NuGet.Config EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "logviewer.engine", "logviewer.engine\logviewer.engine.csproj", "{90E3A68D-C96D-4764-A1D0-F73D9F474BE4}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "logviewer.install.mca", "logviewer.install.mca\logviewer.install.mca.csproj", "{405827CB-84E1-46F3-82C9-D889892645AC}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "logviewer.ui", "logviewer.ui\logviewer.ui.csproj", "{CFBAE2FB-6E3F-44CF-9FC9-372D6EA8DD3D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "logviewer.bench", "logviewer.bench\logviewer.bench.csproj", "{75E0C034-44C8-461B-A677-9A19566FE393}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|Mixed Platforms = Debug|Mixed Platforms Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|Mixed Platforms = Release|Mixed Platforms Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {27060CA7-FB29-42BC-BA66-7FC80D498354}.Debug|Any CPU.ActiveCfg = Debug|x86 {27060CA7-FB29-42BC-BA66-7FC80D498354}.Debug|Any CPU.Build.0 = Debug|x86 {27060CA7-FB29-42BC-BA66-7FC80D498354}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 {27060CA7-FB29-42BC-BA66-7FC80D498354}.Debug|Mixed Platforms.Build.0 = Debug|x86 {27060CA7-FB29-42BC-BA66-7FC80D498354}.Debug|x86.ActiveCfg = Debug|x86 {27060CA7-FB29-42BC-BA66-7FC80D498354}.Debug|x86.Build.0 = Debug|x86 {27060CA7-FB29-42BC-BA66-7FC80D498354}.Release|Any CPU.ActiveCfg = Release|x86 {27060CA7-FB29-42BC-BA66-7FC80D498354}.Release|Any CPU.Build.0 = Release|x86 {27060CA7-FB29-42BC-BA66-7FC80D498354}.Release|Mixed Platforms.ActiveCfg = Release|x86 {27060CA7-FB29-42BC-BA66-7FC80D498354}.Release|Mixed Platforms.Build.0 = Release|x86 {27060CA7-FB29-42BC-BA66-7FC80D498354}.Release|x86.ActiveCfg = Release|x86 {27060CA7-FB29-42BC-BA66-7FC80D498354}.Release|x86.Build.0 = Release|x86 {1C0ED62B-D506-4E72-BBC2-A50D3926466E}.Debug|Any CPU.ActiveCfg = Debug|x86 {1C0ED62B-D506-4E72-BBC2-A50D3926466E}.Debug|Any CPU.Build.0 = Debug|x86 {1C0ED62B-D506-4E72-BBC2-A50D3926466E}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 {1C0ED62B-D506-4E72-BBC2-A50D3926466E}.Debug|Mixed Platforms.Build.0 = Debug|x86 {1C0ED62B-D506-4E72-BBC2-A50D3926466E}.Debug|x86.ActiveCfg = Debug|x86 {1C0ED62B-D506-4E72-BBC2-A50D3926466E}.Debug|x86.Build.0 = Debug|x86 {1C0ED62B-D506-4E72-BBC2-A50D3926466E}.Release|Any CPU.ActiveCfg = Release|x86 {1C0ED62B-D506-4E72-BBC2-A50D3926466E}.Release|Any CPU.Build.0 = Release|x86 {1C0ED62B-D506-4E72-BBC2-A50D3926466E}.Release|Mixed Platforms.ActiveCfg = Release|x86 {1C0ED62B-D506-4E72-BBC2-A50D3926466E}.Release|Mixed Platforms.Build.0 = Release|x86 {1C0ED62B-D506-4E72-BBC2-A50D3926466E}.Release|x86.ActiveCfg = Release|x86 {1C0ED62B-D506-4E72-BBC2-A50D3926466E}.Release|x86.Build.0 = Release|x86 {939DD379-CDC8-47EF-8D37-0E5E71D99D30}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {939DD379-CDC8-47EF-8D37-0E5E71D99D30}.Debug|Any CPU.Build.0 = Debug|Any CPU {939DD379-CDC8-47EF-8D37-0E5E71D99D30}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {939DD379-CDC8-47EF-8D37-0E5E71D99D30}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {939DD379-CDC8-47EF-8D37-0E5E71D99D30}.Debug|x86.ActiveCfg = Debug|Any CPU {939DD379-CDC8-47EF-8D37-0E5E71D99D30}.Release|Any CPU.ActiveCfg = Release|Any CPU {939DD379-CDC8-47EF-8D37-0E5E71D99D30}.Release|Any CPU.Build.0 = Release|Any CPU {939DD379-CDC8-47EF-8D37-0E5E71D99D30}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {939DD379-CDC8-47EF-8D37-0E5E71D99D30}.Release|Mixed Platforms.Build.0 = Release|Any CPU {939DD379-CDC8-47EF-8D37-0E5E71D99D30}.Release|x86.ActiveCfg = Release|Any CPU {383C08FC-9CAC-42E5-9B02-471561479A74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {383C08FC-9CAC-42E5-9B02-471561479A74}.Debug|Any CPU.Build.0 = Debug|Any CPU {383C08FC-9CAC-42E5-9B02-471561479A74}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {383C08FC-9CAC-42E5-9B02-471561479A74}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {383C08FC-9CAC-42E5-9B02-471561479A74}.Debug|x86.ActiveCfg = Debug|Any CPU {383C08FC-9CAC-42E5-9B02-471561479A74}.Release|Any CPU.ActiveCfg = Release|Any CPU {383C08FC-9CAC-42E5-9B02-471561479A74}.Release|Any CPU.Build.0 = Release|Any CPU {383C08FC-9CAC-42E5-9B02-471561479A74}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {383C08FC-9CAC-42E5-9B02-471561479A74}.Release|Mixed Platforms.Build.0 = Release|Any CPU {383C08FC-9CAC-42E5-9B02-471561479A74}.Release|x86.ActiveCfg = Release|Any CPU {90E3A68D-C96D-4764-A1D0-F73D9F474BE4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {90E3A68D-C96D-4764-A1D0-F73D9F474BE4}.Debug|Any CPU.Build.0 = Debug|Any CPU {90E3A68D-C96D-4764-A1D0-F73D9F474BE4}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {90E3A68D-C96D-4764-A1D0-F73D9F474BE4}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {90E3A68D-C96D-4764-A1D0-F73D9F474BE4}.Debug|x86.ActiveCfg = Debug|Any CPU {90E3A68D-C96D-4764-A1D0-F73D9F474BE4}.Release|Any CPU.ActiveCfg = Release|Any CPU {90E3A68D-C96D-4764-A1D0-F73D9F474BE4}.Release|Any CPU.Build.0 = Release|Any CPU {90E3A68D-C96D-4764-A1D0-F73D9F474BE4}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {90E3A68D-C96D-4764-A1D0-F73D9F474BE4}.Release|Mixed Platforms.Build.0 = Release|Any CPU {90E3A68D-C96D-4764-A1D0-F73D9F474BE4}.Release|x86.ActiveCfg = Release|Any CPU {405827CB-84E1-46F3-82C9-D889892645AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {405827CB-84E1-46F3-82C9-D889892645AC}.Debug|Any CPU.Build.0 = Debug|Any CPU {405827CB-84E1-46F3-82C9-D889892645AC}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {405827CB-84E1-46F3-82C9-D889892645AC}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {405827CB-84E1-46F3-82C9-D889892645AC}.Debug|x86.ActiveCfg = Debug|Any CPU {405827CB-84E1-46F3-82C9-D889892645AC}.Release|Any CPU.ActiveCfg = Release|Any CPU {405827CB-84E1-46F3-82C9-D889892645AC}.Release|Any CPU.Build.0 = Release|Any CPU {405827CB-84E1-46F3-82C9-D889892645AC}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {405827CB-84E1-46F3-82C9-D889892645AC}.Release|Mixed Platforms.Build.0 = Release|Any CPU {405827CB-84E1-46F3-82C9-D889892645AC}.Release|x86.ActiveCfg = Release|Any CPU {CFBAE2FB-6E3F-44CF-9FC9-372D6EA8DD3D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CFBAE2FB-6E3F-44CF-9FC9-372D6EA8DD3D}.Debug|Any CPU.Build.0 = Debug|Any CPU {CFBAE2FB-6E3F-44CF-9FC9-372D6EA8DD3D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {CFBAE2FB-6E3F-44CF-9FC9-372D6EA8DD3D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {CFBAE2FB-6E3F-44CF-9FC9-372D6EA8DD3D}.Debug|x86.ActiveCfg = Debug|Any CPU {CFBAE2FB-6E3F-44CF-9FC9-372D6EA8DD3D}.Release|Any CPU.ActiveCfg = Release|Any CPU {CFBAE2FB-6E3F-44CF-9FC9-372D6EA8DD3D}.Release|Any CPU.Build.0 = Release|Any CPU {CFBAE2FB-6E3F-44CF-9FC9-372D6EA8DD3D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {CFBAE2FB-6E3F-44CF-9FC9-372D6EA8DD3D}.Release|Mixed Platforms.Build.0 = Release|Any CPU {CFBAE2FB-6E3F-44CF-9FC9-372D6EA8DD3D}.Release|x86.ActiveCfg = Release|Any CPU {75E0C034-44C8-461B-A677-9A19566FE393}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {75E0C034-44C8-461B-A677-9A19566FE393}.Debug|Any CPU.Build.0 = Debug|Any CPU {75E0C034-44C8-461B-A677-9A19566FE393}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {75E0C034-44C8-461B-A677-9A19566FE393}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {75E0C034-44C8-461B-A677-9A19566FE393}.Debug|x86.ActiveCfg = Debug|Any CPU {75E0C034-44C8-461B-A677-9A19566FE393}.Debug|x86.Build.0 = Debug|Any CPU {75E0C034-44C8-461B-A677-9A19566FE393}.Release|Any CPU.ActiveCfg = Release|Any CPU {75E0C034-44C8-461B-A677-9A19566FE393}.Release|Any CPU.Build.0 = Release|Any CPU {75E0C034-44C8-461B-A677-9A19566FE393}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {75E0C034-44C8-461B-A677-9A19566FE393}.Release|Mixed Platforms.Build.0 = Release|Any CPU {75E0C034-44C8-461B-A677-9A19566FE393}.Release|x86.ActiveCfg = Release|Any CPU {75E0C034-44C8-461B-A677-9A19566FE393}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal "#; }
use core::cmp::min; use crate::error::ExpectedString; use crate::parser::Parser; use crate::span::Span; impl<'s> Parser for &'s str { type Value = Self; type Error = ExpectedString<'s>; fn parse(&self, input: &'_ str) -> Result<Span<Self::Value>, Span<Self::Error>> { if input.starts_with(*self) { Ok(Span::new(0..self.len(), *self)) } else if input.is_empty() { Err(Span::new(0..0, ExpectedString(*self))) } else { let mut len = min(input.len(), self.len()); while input.get(0..len).is_none() { len += 1; } Err(Span::new(0..len, ExpectedString(*self))) } } } #[cfg(test)] mod tests { use core::cmp::min; use quickcheck_macros::quickcheck; use crate::error::ExpectedString; use crate::parser::Parser; use crate::span::Span; #[test] fn match_ascii() { assert_eq!( Parser::parse(&"hello", "hello"), Ok(Span::new(0..5, "hello")) ); } #[test] fn match_utf8() { assert_eq!(Parser::parse(&"💩", "💩"), Ok(Span::new(0..4, "💩"))); } #[test] fn match_grapheme() { assert_eq!(Parser::parse(&"नि", "नि"), Ok(Span::new(0..6, "नि"))); } #[test] fn error_if_empty() { assert_eq!( Parser::parse(&"hello", ""), Err(Span::new(0..0, ExpectedString("hello"))) ); } #[test] fn error_if_wrong_char_ascii() { assert_eq!( Parser::parse(&"hello", "world"), Err(Span::new(0..5, ExpectedString("hello"))) ); } #[test] fn error_if_wrong_char_grapheme() { assert_eq!( Parser::parse(&"hello", "नि"), Err(Span::new(0..6, ExpectedString("hello"))) ); } #[quickcheck] fn parse(string: String, input: std::string::String) { let result = Parser::parse(&&string[..], &input); if input.starts_with(&string) { assert_eq!(result, Ok(Span::new(0..string.len(), &string[..]))); } else if input.is_empty() { assert_eq!(result, Err(Span::new(0..0, ExpectedString(&string)))); } else { let mut len = min(input.len(), string.len()); while input.get(0..len).is_none() { len += 1; } assert_eq!(result, Err(Span::new(0..len, ExpectedString(&string)))); } } }
use std::io::Error; use std::os::unix::io::RawFd; #[derive(Debug)] pub struct Prog; #[macro_export] macro_rules! bpfprog { ($count:expr, $($code:tt $jt:tt $jf:tt $k:tt),*) => { bpf::Prog }; } #[allow(unused_variables)] pub fn attach_filter(fd: RawFd, prog: Prog) -> Result<(), Error> { Ok(()) } #[allow(unused_variables)] pub fn detach_filter(fd: RawFd) -> Result<(), Error> { Ok(()) } #[allow(unused_variables)] pub fn lock_filter(fd: RawFd) -> Result<(), Error> { Ok(()) }
#[doc = "Register `MACTXTSSNR` reader"] pub type R = crate::R<MACTXTSSNR_SPEC>; #[doc = "Register `MACTXTSSNR` writer"] pub type W = crate::W<MACTXTSSNR_SPEC>; #[doc = "Field `TXTSSLO` reader - Transmit Timestamp Status Low This field contains the 31 bits of the Nanoseconds field of the Transmit packet's captured timestamp.\n\nThe field is **cleared** (set to zero) following a read operation."] pub type TXTSSLO_R = crate::FieldReader<u32>; #[doc = "Field `TXTSSLO` writer - Transmit Timestamp Status Low This field contains the 31 bits of the Nanoseconds field of the Transmit packet's captured timestamp."] pub type TXTSSLO_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 31, O, u32>; #[doc = "Field `TXTSSMIS` reader - Transmit Timestamp Status Missed When this bit is set, it indicates one of the following: The timestamp of the current packet is ignored if TXTSSTSM bit of the Timestamp control Register (ETH_MACTSCR) is reset The timestamp of the previous packet is overwritten with timestamp of the current packet if TXTSSTSM bit of the Timestamp control Register (ETH_MACTSCR) is set."] pub type TXTSSMIS_R = crate::BitReader; impl R { #[doc = "Bits 0:30 - Transmit Timestamp Status Low This field contains the 31 bits of the Nanoseconds field of the Transmit packet's captured timestamp."] #[inline(always)] pub fn txtsslo(&self) -> TXTSSLO_R { TXTSSLO_R::new(self.bits & 0x7fff_ffff) } #[doc = "Bit 31 - Transmit Timestamp Status Missed When this bit is set, it indicates one of the following: The timestamp of the current packet is ignored if TXTSSTSM bit of the Timestamp control Register (ETH_MACTSCR) is reset The timestamp of the previous packet is overwritten with timestamp of the current packet if TXTSSTSM bit of the Timestamp control Register (ETH_MACTSCR) is set."] #[inline(always)] pub fn txtssmis(&self) -> TXTSSMIS_R { TXTSSMIS_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bits 0:30 - Transmit Timestamp Status Low This field contains the 31 bits of the Nanoseconds field of the Transmit packet's captured timestamp."] #[inline(always)] #[must_use] pub fn txtsslo(&mut self) -> TXTSSLO_W<MACTXTSSNR_SPEC, 0> { TXTSSLO_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "Tx timestamp status nanoseconds register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mactxtssnr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`mactxtssnr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct MACTXTSSNR_SPEC; impl crate::RegisterSpec for MACTXTSSNR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`mactxtssnr::R`](R) reader structure"] impl crate::Readable for MACTXTSSNR_SPEC {} #[doc = "`write(|w| ..)` method takes [`mactxtssnr::W`](W) writer structure"] impl crate::Writable for MACTXTSSNR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets MACTXTSSNR to value 0"] impl crate::Resettable for MACTXTSSNR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use crate::schema::page; #[derive( juniper::GraphQLObject, Debug, Queryable, Identifiable, Serialize, Deserialize, PartialEq, Associations, )] #[table_name = "page"] pub struct Page { pub id: i32, pub name: String, pub icon: Option<String>, pub content: Option<String>, } #[derive(juniper::GraphQLInputObject, AsChangeset, Debug, Serialize, Deserialize, Insertable)] #[table_name = "page"] pub struct PageInput { pub name: String, pub icon: Option<String>, pub content: Option<String>, }
use handlegraph::packedgraph::paths::StepPtr; #[allow(unused_imports)] use handlegraph::{ handle::{Direction, Handle, NodeId}, handlegraph::*, mutablehandlegraph::*, packed::*, packedgraph::index::OneBasedIndex, packedgraph::*, path_position::*, pathhandlegraph::*, }; use crossbeam::{atomic::AtomicCell, channel::Sender}; use rustc_hash::FxHashSet; use std::sync::Arc; use bstr::ByteSlice; use crate::{ app::AppMsg, context::ContextMgr, geometry::*, gui::util::ColumnWidths, }; use crate::gui::util as gui_util; use crate::{graph_query::GraphQuery, gui::util::grid_row_label}; pub struct NodeDetails { node_id: Arc<AtomicCell<Option<NodeId>>>, fetched_node: Option<NodeId>, sequence: Vec<u8>, degree: (usize, usize), paths: Vec<(PathId, StepPtr, usize)>, unique_paths: Vec<PathId>, col_widths: ColumnWidths<3>, } impl std::default::Default for NodeDetails { fn default() -> Self { Self { node_id: Arc::new(None.into()), fetched_node: None, sequence: Vec::new(), degree: (0, 0), paths: Vec::new(), unique_paths: Vec::new(), col_widths: Default::default(), } } } pub enum NodeDetailsMsg { SetNode(NodeId), NoNode, } impl NodeDetails { const ID: &'static str = "node_details_window"; pub fn node_id_cell(&self) -> &Arc<AtomicCell<Option<NodeId>>> { &self.node_id } pub fn apply_msg(&mut self, msg: NodeDetailsMsg) { match msg { NodeDetailsMsg::SetNode(node_id) => { self.node_id.store(Some(node_id)); } NodeDetailsMsg::NoNode => { self.node_id.store(None); self.sequence.clear(); self.degree = (0, 0); self.paths.clear(); } } } pub fn need_fetch(&self) -> bool { let to_show = self.node_id.load(); to_show != self.fetched_node } pub fn fetch(&mut self, graph_query: &GraphQuery) -> Option<()> { if !self.need_fetch() { return None; } let node_id = self.node_id.load()?; self.sequence.clear(); self.degree = (0, 0); self.paths.clear(); self.unique_paths.clear(); let graph = graph_query.graph(); let handle = Handle::pack(node_id, false); self.sequence.extend(graph.sequence(handle)); let degree_l = graph.neighbors(handle, Direction::Left).count(); let degree_r = graph.neighbors(handle, Direction::Right).count(); self.degree = (degree_l, degree_r); let paths_fwd = graph_query.handle_positions(Handle::pack(node_id, false)); if let Some(p) = paths_fwd { self.paths.extend_from_slice(&p); self.unique_paths .extend(self.paths.iter().map(|(path, _, _)| path)); self.unique_paths.sort(); self.unique_paths.dedup(); } self.fetched_node = Some(node_id); Some(()) } pub fn ui( &mut self, open_node_details: &mut bool, graph_query: &GraphQuery, ctx: &egui::CtxRef, path_details_id_cell: &AtomicCell<Option<PathId>>, open_path_details: &mut bool, ctx_mgr: &ContextMgr, ) -> Option<egui::InnerResponse<Option<()>>> { if self.need_fetch() { self.fetch(graph_query); } egui::Window::new("Node details") .id(egui::Id::new(Self::ID)) .default_pos(egui::Pos2::new(450.0, 200.0)) .open(open_node_details) .show(ctx, |ui| { if let Some(node_id) = self.node_id.load() { ui.set_min_height(200.0); ui.set_max_width(200.0); let node_label = ui.add( egui::Label::new(format!("Node {}", node_id)) .sense(egui::Sense::click()), ); if node_label.hovered() { ctx_mgr.produce_context(|| node_id); } // if node_label.clicked_by(egui::PointerButton::Secondary) { // ctx_tx.send(ContextEntry::Node(node_id)).unwrap(); // } ui.separator(); if self.sequence.len() < 50 { ui.label(format!("Seq: {}", self.sequence.as_bstr())); } else { ui.label(format!("Seq len: {}", self.sequence.len())); } ui.label(format!( "Degree ({}, {})", self.degree.0, self.degree.1 )); ui.separator(); let scroll_align = gui_util::add_scroll_buttons(ui); let num_rows = self.paths.len(); let text_style = egui::TextStyle::Body; let row_height = ui.fonts()[text_style].row_height(); let [w0, w1, w2] = self.col_widths.get(); let header = egui::Grid::new( "node_details_path_list_header", ) .show(ui, |ui| { let inner = grid_row_label( ui, egui::Id::new("node_details_path_list_header__"), &["Path", "Step", "Base pos"], false, Some(&[w0, w1, w2]), ); self.col_widths.set_hdr(&inner.inner); }); gui_util::scrolled_area(ui, num_rows, scroll_align) .show_rows(ui, row_height, num_rows, |ui, range| { ui.set_min_width(header.response.rect.width()); egui::Grid::new("node_details_path_list") .spacing(Point { x: 10.0, y: 5.0 }) .striped(true) .show(ui, |ui| { let take_n = range.start.max(range.end) - range.start; for (path_id, step_ptr, pos) in self .paths .iter() .skip(range.start) .take(take_n) { let path_name = graph_query .graph() .get_path_name_vec(*path_id); let name = if let Some(name) = path_name { format!("{}", name.as_bstr()) } else { format!("Path ID {}", path_id.0) }; let step_str = format!( "{}", step_ptr.to_vector_value() ); let pos_str = format!("{}", pos); let fields: [&str; 3] = [&name, &step_str, &pos_str]; let inner = grid_row_label( ui, egui::Id::new(ui.id().with( format!( "path_{}_{}", path_id.0, step_ptr.to_vector_value() ), )), &fields, false, Some(&[w0, w1, w2]), ); self.col_widths.set(&inner.inner); let row = inner.response; if row.clicked() { path_details_id_cell .store(Some(*path_id)); *open_path_details = true; } if row.hovered() { ctx_mgr .produce_context(|| *path_id); } /* if row.clicked_by( egui::PointerButton::Secondary, ) { ctx_tx .send(ContextEntry::Path( *path_id, )) .unwrap(); } */ } }); }); ui.shrink_width_to_current(); } else { ui.label("Examine a node by picking it from the node list"); } }) } } pub struct NodeList { // probably not needed as I can assume compact node IDs all_nodes: Vec<NodeId>, filtered_nodes: Vec<NodeId>, apply_filter: AtomicCell<bool>, node_details_id: Arc<AtomicCell<Option<NodeId>>>, range: AtomicCell<(usize, usize)>, col_widths: ColumnWidths<5>, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum NodeListMsg { ApplyFilter(Option<bool>), SetFiltered(Vec<NodeId>), } impl NodeList { const ID: &'static str = "node_list_window"; pub fn apply_msg(&mut self, msg: NodeListMsg) { match msg { NodeListMsg::ApplyFilter(apply) => { if let Some(apply) = apply { self.apply_filter.store(apply); } else { self.apply_filter.fetch_xor(true); } } NodeListMsg::SetFiltered(nodes) => { self.set_filtered(&nodes); } } } pub fn new( graph_query: &GraphQuery, node_details_id: Arc<AtomicCell<Option<NodeId>>>, ) -> Self { let graph = graph_query.graph(); let mut all_nodes = graph.handles().map(|h| h.id()).collect::<Vec<_>>(); all_nodes.sort(); let filtered_nodes: Vec<NodeId> = Vec::new(); Self { all_nodes, filtered_nodes, apply_filter: true.into(), node_details_id, range: (0, 0).into(), col_widths: Default::default(), } } pub fn set_filtered(&mut self, nodes: &[NodeId]) { self.filtered_nodes.clear(); self.filtered_nodes.extend(nodes.iter().copied()); } pub fn ui( &mut self, ctx: &egui::CtxRef, app_msg_tx: &Sender<AppMsg>, open_node_details: &mut bool, graph_query: &GraphQuery, ctx_mgr: &ContextMgr, ) -> Option<egui::InnerResponse<Option<()>>> { let filter = self.apply_filter.load(); let nodes = if !filter || self.filtered_nodes.is_empty() { &self.all_nodes } else { &self.filtered_nodes }; egui::Window::new("Nodes") .id(egui::Id::new(Self::ID)) .default_pos(egui::Pos2::new(200.0, 200.0)) .show(ctx, |ui| { ui.set_min_height(300.0); ui.set_max_width(200.0); ui.horizontal(|ui| { let clear_selection_btn = ui .button("Clear selection") .on_hover_text("Hotkey: <Escape>"); if clear_selection_btn.clicked() { use crate::app::Select; app_msg_tx .send(AppMsg::Selection(Select::Clear)) .unwrap(); } if ui .selectable_label(*open_node_details, "Node Details") .clicked() { *open_node_details = !*open_node_details; } }); let apply_filter = &self.apply_filter; if ui.selectable_label(filter, "Show only selected").clicked() { apply_filter.store(!filter); } let scroll_align = gui_util::add_scroll_buttons(ui); let node_id_cell = &self.node_details_id; let text_style = egui::TextStyle::Body; let row_height = ui.fonts()[text_style].row_height(); let spacing = ui.style().spacing.item_spacing.y; let num_rows = nodes.len(); let (start, end) = self.range.load(); ui.label(format!( "Showing {}-{} out of {} nodes", start, end, nodes.len() )); let widths = self.col_widths.get(); egui::Grid::new("node_list_grid_header").show(ui, |ui| { let inner = grid_row_label( ui, egui::Id::new("node_list_grid_header__"), &[ "Node", "Degree", "Seq. len", "Unique paths", "Total paths", ], false, Some(&widths), ); let ws = inner.inner; self.col_widths.set_hdr(&ws); }); gui_util::scrolled_area(ui, num_rows, scroll_align).show_rows( ui, row_height, num_rows, |ui, range| { egui::Grid::new("node_list_grid").striped(true).show( ui, |ui| { self.range.store((range.start, range.end)); let n = range.start.max(range.end) - range.start; let graph = graph_query.graph(); for (ix, node_id) in nodes .iter() .copied() .enumerate() .skip(range.start) .take(n) { let node_id_lb = format!("{}", node_id); let handle = Handle::pack(node_id, false); let deg_l = graph.degree(handle, Direction::Left); let deg_r = graph.degree(handle, Direction::Right); let degree = format!("({}, {})", deg_l, deg_r); let seq_len = format!("{}", graph.node_len(handle)); let mut path_count = 0; let mut uniq_count = 0; let mut seen_paths: FxHashSet<PathId> = FxHashSet::default(); if let Some(steps) = graph.steps_on_handle(handle) { for (path, _) in steps { if seen_paths.insert(path) { uniq_count += 1; } path_count += 1; } } let uniq_paths = format!("{}", uniq_count); let step_count = format!("{}", path_count); let fields: [&str; 5] = [ &node_id_lb, &degree, &seq_len, &uniq_paths, &step_count, ]; let inner = grid_row_label( ui, egui::Id::new(ui.id().with(ix)), &fields, false, Some(&widths), ); self.col_widths.set(&inner.inner); let row = inner.response; if row.clicked() { node_id_cell.store(Some(node_id)); *open_node_details = true; } if row.hovered() { ctx_mgr.produce_context(|| node_id); } /* if row.clicked_by( egui::PointerButton::Secondary, ) { ctx_tx .send(ContextEntry::Node(node_id)) .unwrap(); } */ } }, ); /* if let Some(align) = scroll_align { // ui.scroll_to_cursor(align) ui.scroll_to_cursor(align); } */ }, ); ui.shrink_width_to_current(); }) } }
use core::cellbuffer::{CellAccessor, Cell}; use ui::core::attributes::{HorizontalAlign, VerticalAlign}; #[derive(Clone, Copy)] pub enum Orientation { Horizontal, Vertical, } pub trait Painter: CellAccessor { /// Prints a string at the specified position. /// /// This is a shorthand for setting each cell individually. `cell`'s style is going to be /// copied to each destination cell. /// /// # Examples /// /// ``` /// use rustty::{Terminal, Cell, Color, Attr}; /// use rustty::ui::core::Painter; /// /// let mut term = Terminal::new().unwrap(); /// let cell = Cell::with_style(Color::Default, Color::Red, Attr::Default); /// term.printline_with_cell(0, 0, "foobar", cell); /// ``` fn printline_with_cell(&mut self, x: usize, y: usize, line: &str, cell: Cell) { let (cols, _) = self.size(); for (index, ch) in line.chars().enumerate() { let current_x = x + index; if current_x >= cols { break; } match self.get_mut(current_x, y) { Some(c) => { c.set_fg(cell.fg()); c.set_bg(cell.bg()); c.set_attrs(cell.attrs()); c.set_ch(ch); }, None => {}, } } } /// Prints a string at the specified position. /// /// Shorthand for `printline_with_cell(x, y, line, Cell::default())`. fn printline(&mut self, x: usize, y: usize, line: &str) { self.printline_with_cell(x, y, line, Cell::default()); } /// Returns the proper x coord to align `line` in the specified `halign` alignment. /// /// `margin` is the number of characters we want to leave near the borders. fn halign_line(&self, line: &str, halign: HorizontalAlign, margin: usize) -> usize { let (cols, _) = self.size(); match halign { HorizontalAlign::Left => margin, HorizontalAlign::Right => cols - line.chars().count() - margin - 1, HorizontalAlign::Middle => (cols - line.chars().count()) / 2, } } /// Returns the proper y coord to align `line` in the specified `valign` alignment. /// /// `margin` is the number of characters we want to leave near the borders. /// /// For now, the contents of line has no incidence whatsoever on the result, but when we /// support multi-line strings, it will, so we might as well stay consistent with /// `halign_line()`. #[allow(unused_variables)] fn valign_line(&self, line: &str, valign: VerticalAlign, margin: usize) -> usize { let (_, rows) = self.size(); match valign { VerticalAlign::Top => margin, VerticalAlign::Bottom => rows - margin - 1, VerticalAlign::Middle => rows / 2, } } fn repeat_cell(&mut self, x: usize, y: usize, orientation: Orientation, count: usize, cell: Cell) { for i in 0..count { let (ix, iy) = match orientation { Orientation::Horizontal => (x + i, y), Orientation::Vertical => (x, y + i), }; match self.get_mut(ix, iy) { Some(c) => { *c = cell; }, None => (), }; } } fn draw_box(&mut self) { let (cols, rows) = self.size(); if cols <= 1 || rows <= 1 { panic!("draw_box attempted on widget that does not meet \ minimum size requirements. Must be greater than (1x1)"); } let corners = [ (0, 0, '┌'), (cols-1, 0, '┐'), (cols-1, rows-1, '┘'), (0, rows-1, '└'), ]; for &(x, y, ch) in corners.iter() { self.get_mut(x, y).unwrap().set_ch(ch); } let lines = [ (1, 0, cols-2, Orientation::Horizontal, '─'), (1, rows-1, cols-2, Orientation::Horizontal, '─'), (0, 1, rows-2, Orientation::Vertical, '│'), (cols-1, 1, rows-2, Orientation::Vertical, '│'), ]; for &(x, y, count, orientation, ch) in lines.iter() { let cell = Cell::with_char(ch); self.repeat_cell(x, y, orientation, count, cell); } } } impl<T: CellAccessor> Painter for T {}
// Copyright (c) 2018 Alexander Færøy. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. extern crate image; extern crate rand; use image::{Rgb, RgbImage}; /// Expression types and helpers. mod expression; use self::expression::{Evaluate, Generator}; /// Various math helpers. mod math; fn to_u8(x: f64) -> u8 { (x * 127.5 + 127.5) as u8 } pub struct ImageGenerator { r: Box<dyn Evaluate>, g: Box<dyn Evaluate>, b: Box<dyn Evaluate>, random_data_used: usize, } impl ImageGenerator { pub fn new(seed: &[u8]) -> ImageGenerator { let mut generator = Generator::new(seed); ImageGenerator { r: generator.generate(), g: generator.generate(), b: generator.generate(), random_data_used: generator.random_data_used(), } } pub fn generate(&self, filename: String, size: u32, factor: f64) { let unit_size: f64 = (size as f64) / 2.0; assert!(size % 2 == 0); println!("R: f(x, y) = {}", self.r); println!("G: f(x, y) = {}", self.g); println!("B: f(x, y) = {}", self.b); println!("Random data used = {}", self.random_data_used); let image = RgbImage::from_fn(size, size, |i_x, i_y| { let x = (((i_x as f64) - unit_size) / unit_size) * factor; let y = (((i_y as f64) - unit_size) / unit_size) * factor; let r = self.r.evaluate(x, y); let g = self.g.evaluate(x, y); let b = self.b.evaluate(x, y); Rgb([to_u8(r), to_u8(g), to_u8(b)]) }); image.save(filename).unwrap(); } }
use crate::{ default_resource, diffable, error::ServiceError, generation, models::{ sql::{slice_iter, SelectBuilder}, Lock, TypedAlias, }, update_aliases, Client, }; use async_trait::async_trait; use chrono::{DateTime, Utc}; use drogue_client::{meta, registry}; use drogue_cloud_service_api::labels::LabelSelector; use futures::{future, Stream, TryStreamExt}; use serde_json::Value; use std::collections::{hash_map::RandomState, HashMap, HashSet}; use std::pin::Pin; use tokio_postgres::types::{ToSql, Type}; use tokio_postgres::{types::Json, Row}; use uuid::Uuid; /// A device entity record. pub struct Device { pub application: String, pub uid: Uuid, pub name: String, pub labels: HashMap<String, String>, pub annotations: HashMap<String, String>, pub creation_timestamp: DateTime<Utc>, pub resource_version: Uuid, pub generation: u64, pub deletion_timestamp: Option<DateTime<Utc>>, pub finalizers: Vec<String>, pub data: Value, } diffable!(Device); generation!(Device => generation); default_resource!(Device); impl From<Device> for registry::v1::Device { fn from(device: Device) -> Self { registry::v1::Device { metadata: meta::v1::ScopedMetadata { uid: device.uid.to_string(), name: device.name, application: device.application, labels: device.labels, annotations: device.annotations, creation_timestamp: device.creation_timestamp, generation: device.generation, resource_version: device.resource_version.to_string(), deletion_timestamp: device.deletion_timestamp, finalizers: device.finalizers, }, spec: device.data["spec"].as_object().cloned().unwrap_or_default(), status: device.data["status"] .as_object() .cloned() .unwrap_or_default(), } } } #[async_trait] pub trait DeviceAccessor { /// Lookup a device by alias. async fn lookup(&self, app: &str, alias: &str) -> Result<Option<Device>, ServiceError>; /// Delete a device. async fn delete(&self, app: &str, device: &str) -> Result<(), ServiceError>; /// Get a device. async fn get( &self, app: &str, device: &str, lock: Lock, ) -> Result<Option<Device>, ServiceError> { Ok(self .list( app, Some(device), LabelSelector::default(), Some(1), None, lock, ) .await? .try_next() .await?) } /// Create a new device. async fn create( &self, device: Device, aliases: HashSet<TypedAlias>, ) -> Result<(), ServiceError>; /// Update an existing device. async fn update( &self, device: Device, aliases: Option<HashSet<TypedAlias>>, ) -> Result<u64, ServiceError>; /// Delete all devices that belong to an application. async fn delete_app(&self, app: &str) -> Result<u64, ServiceError>; /// Count devices remaining for an application. async fn count_devices(&self, app: &str) -> Result<u64, ServiceError>; /// Get a list of applications async fn list( &self, app: &str, name: Option<&str>, labels: LabelSelector, limit: Option<usize>, offset: Option<usize>, lock: Lock, ) -> Result<Pin<Box<dyn Stream<Item = Result<Device, ServiceError>> + Send>>, ServiceError>; } pub struct PostgresDeviceAccessor<'c, C: Client> { client: &'c C, } impl<'c, C: Client> PostgresDeviceAccessor<'c, C> { pub fn new(client: &'c C) -> Self { Self { client } } pub fn from_row(row: Row) -> Result<Device, tokio_postgres::Error> { Ok(Device { application: row.try_get("APP")?, uid: row.try_get("UID")?, name: row.try_get("NAME")?, creation_timestamp: row.try_get("CREATION_TIMESTAMP")?, generation: row.try_get::<_, i64>("GENERATION")? as u64, resource_version: row.try_get("RESOURCE_VERSION")?, labels: super::row_to_map(&row, "LABELS")?, annotations: super::row_to_map(&row, "ANNOTATIONS")?, deletion_timestamp: row.try_get("DELETION_TIMESTAMP")?, finalizers: super::row_to_vec(&row, "FINALIZERS")?, data: row.try_get::<_, Json<_>>("DATA")?.0, }) } async fn insert_aliases( &self, app: &str, device: &str, aliases: &HashSet<TypedAlias>, ) -> Result<(), tokio_postgres::Error> { if aliases.is_empty() { return Ok(()); } let stmt = self .client .prepare_typed( "INSERT INTO DEVICE_ALIASES (APP, DEVICE, TYPE, ALIAS) VALUES ($1, $2, $3, $4)", &[Type::VARCHAR, Type::VARCHAR, Type::VARCHAR, Type::VARCHAR], ) .await?; for alias in aliases { self.client .execute(&stmt, &[&app, &device, &alias.0, &alias.1]) .await?; } Ok(()) } } #[async_trait] impl<'c, C: Client> DeviceAccessor for PostgresDeviceAccessor<'c, C> { async fn lookup(&self, app: &str, alias: &str) -> Result<Option<Device>, ServiceError> { let sql = r#" SELECT D.NAME, D.UID, D.APP, D.LABELS, D.CREATION_TIMESTAMP, D.GENERATION, D.RESOURCE_VERSION, D.ANNOTATIONS, D.DELETION_TIMESTAMP, D.FINALIZERS, D.DATA FROM DEVICE_ALIASES A INNER JOIN DEVICES D ON (A.DEVICE=D.NAME AND A.APP=D.APP) WHERE A.APP = $1 AND A.ALIAS = $2 "#; let stmt = self .client .prepare_typed(sql, &[Type::VARCHAR, Type::VARCHAR]) .await?; let result = self .client .query_opt(&stmt, &[&app, &alias]) .await? .map(Self::from_row) .transpose()?; Ok(result) } async fn delete(&self, app: &str, device: &str) -> Result<(), ServiceError> { let sql = "DELETE FROM DEVICES WHERE APP = $1 AND NAME = $2"; let stmt = self .client .prepare_typed(sql, &[Type::VARCHAR, Type::VARCHAR]) .await?; let count = self.client.execute(&stmt, &[&app, &device]).await?; if count > 0 { Ok(()) } else { Err(ServiceError::NotFound) } } async fn list( &self, app: &str, name: Option<&str>, labels: LabelSelector, limit: Option<usize>, offset: Option<usize>, lock: Lock, ) -> Result<Pin<Box<dyn Stream<Item = Result<Device, ServiceError>> + Send>>, ServiceError> { let select = r#" SELECT UID, NAME, APP, LABELS, ANNOTATIONS, CREATION_TIMESTAMP, GENERATION, RESOURCE_VERSION, DELETION_TIMESTAMP, FINALIZERS, DATA FROM DEVICES WHERE APP=$1 "# .to_string(); let mut types: Vec<Type> = Vec::new(); types.push(Type::VARCHAR); let mut params: Vec<&(dyn ToSql + Sync)> = Vec::new(); params.push(&app); let builder = SelectBuilder::new(select, params, types) .has_where() .name(&name) .labels(&labels.0) .lock(lock) .sort(&["NAME"]) .limit(limit) .offset(offset); let (select, params, types) = builder.build(); let stmt = self.client.prepare_typed(&select, &types).await?; let stream = self .client .query_raw(&stmt, slice_iter(&params[..])) .await .map_err(|err| { log::debug!("Failed to get: {}", err); err })? .and_then(|row| future::ready(Self::from_row(row))) .map_err(ServiceError::Database); Ok(Box::pin(stream)) } async fn create( &self, device: Device, aliases: HashSet<TypedAlias>, ) -> Result<(), ServiceError> { self.client .execute( r#" INSERT INTO DEVICES ( APP, NAME, LABELS, ANNOTATIONS, CREATION_TIMESTAMP, GENERATION, RESOURCE_VERSION, FINALIZERS, DATA ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9 )"#, &[ &device.application, &device.name, &Json(&device.labels), &Json(&device.annotations), &Utc::now(), &(device.generation as i64), &Uuid::new_v4(), &device.finalizers, &Json(&device.data), ], ) .await?; self.insert_aliases(&device.application, &device.name, &aliases) .await?; Ok(()) } async fn update( &self, device: Device, aliases: Option<HashSet<TypedAlias>>, ) -> Result<u64, ServiceError> { // update device let count = self .client .execute( r#" UPDATE DEVICES SET LABELS = $3, ANNOTATIONS = $4, GENERATION = $5, RESOURCE_VERSION = $6, DELETION_TIMESTAMP = $7, FINALIZERS = $8, DATA = $9 WHERE APP = $1 AND NAME = $2 "#, &[ &device.application, &device.name, &Json(device.labels), &Json(device.annotations), &(device.generation as i64), &Uuid::new_v4(), &device.deletion_timestamp, &device.finalizers, &Json(device.data), ], ) .await .map_err(|err| { log::info!("Failed: {}", err); err })?; update_aliases!(count, aliases, |aliases| { // clear existing aliases let sql = "DELETE FROM DEVICE_ALIASES WHERE APP=$1 AND DEVICE=$2"; let stmt = self .client .prepare_typed(sql, &[Type::VARCHAR, Type::VARCHAR]) .await?; self.client .execute(&stmt, &[&device.application, &device.name]) .await?; // insert new alias set self.insert_aliases(&device.application, &device.name, &aliases) .await?; Ok(count) }) } async fn delete_app(&self, app_id: &str) -> Result<u64, ServiceError> { // delete all devices without finalizers directly let sql = r#" DELETE FROM DEVICES WHERE APP = $1 AND cardinality ( FINALIZERS ) = 0 "#; let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?; let count = self.client.execute(&stmt, &[&app_id]).await?; log::debug!("Deleted {} devices without a finalizer", count); // count all remaining devices let count = self.count_devices(&app_id).await?; log::debug!("{} devices remain for deletion", count); // done Ok(count) } async fn count_devices(&self, app_id: &str) -> Result<u64, ServiceError> { let sql = r#"SELECT COUNT(NAME) AS COUNT FROM DEVICES WHERE APP = $1"#; let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?; let count = self .client .query_opt(&stmt, &[&app_id]) .await? .ok_or_else(|| { ServiceError::Internal("Unable to retrieve number of devices with finalizer".into()) })?; Ok(count.try_get::<_, i64>("COUNT")? as u64) } }
use crate::components::{EnergyComponent, EnergyRegenComponent}; use crate::indices::EntityId; use crate::join; use crate::profile; use crate::storage::views::{UnsafeView, View}; use crate::tables::JoinIterator; pub fn energy_update( mut energy: UnsafeView<EntityId, EnergyComponent>, energy_regen: View<EntityId, EnergyRegenComponent>, ) { profile!("EnergySystem update"); let energy_it = energy.iter_mut(); let energy_regen_it = energy_regen.iter(); join!([energy_it, energy_regen_it]).for_each(|(_id, (e, er))| { e.energy = (e.energy + er.amount).min(e.energy_max); }); }
use crate::AddAsHeader; use http::request::Builder; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ContentType<'a>(&'a str); impl<'a> ContentType<'a> { pub fn new(s: &'a str) -> Self { Self(s) } pub fn as_str(&self) -> &str { self.0 } } impl<'a, S> From<S> for ContentType<'a> where S: Into<&'a str>, { fn from(s: S) -> Self { Self(s.into()) } } impl<'a> AddAsHeader for ContentType<'a> { fn add_as_header(&self, builder: Builder) -> Builder { builder.header(http::header::CONTENT_TYPE, self.0) } fn add_as_header2( &self, request: &mut crate::Request, ) -> Result<(), crate::errors::HTTPHeaderError> { request.headers_mut().append( http::header::CONTENT_TYPE, http::HeaderValue::from_str(self.0)?, ); Ok(()) } }
extern crate earthinator; use earthinator::field::Map; fn main(){ let mut map = Map::new(200,150); map.generate(); //map.print(); map.export(); }
#[doc = "Register `C0CR` reader"] pub type R = crate::R<C0CR_SPEC>; #[doc = "Register `C0CR` writer"] pub type W = crate::W<C0CR_SPEC>; #[doc = "Field `DMAREQ_ID` reader - DMA request identification"] pub type DMAREQ_ID_R = crate::FieldReader<DMAREQ_ID_A>; #[doc = "DMA request identification\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum DMAREQ_ID_A { #[doc = "0: No signal selected as request input"] None = 0, #[doc = "1: Signal `dmamux1_req_gen0` selected as request input"] Dmamux1ReqGen0 = 1, #[doc = "2: Signal `dmamux1_req_gen1` selected as request input"] Dmamux1ReqGen1 = 2, #[doc = "3: Signal `dmamux1_req_gen2` selected as request input"] Dmamux1ReqGen2 = 3, #[doc = "4: Signal `dmamux1_req_gen3` selected as request input"] Dmamux1ReqGen3 = 4, #[doc = "5: Signal `adc1_dma` selected as request input"] Adc = 5, #[doc = "6: Signal `dac_out1_dma` selected as request input"] DatOut1 = 6, #[doc = "7: Signal `spi1_rx_dma` selected as request input"] Spi1RxDma = 7, #[doc = "8: Signal `spi1_tx_dma` selected as request input"] Spi1TxDma = 8, #[doc = "9: Signal `spi2_rx_dma` selected as request input"] Spi2RxDma = 9, #[doc = "10: Signal `spi2_tx_dma` selected as request input"] Spi2TxDma = 10, #[doc = "11: Signal `i2c1_rx_dma` selected as request input"] I2c1RxDma = 11, #[doc = "12: Signal `i2c1_tx_dma` selected as request input"] I2c1TxDma = 12, #[doc = "13: Signal `i2c2_rx_dma` selected as request input"] I2c2RxDma = 13, #[doc = "14: Signal `i2c2_tx_dma` selected as request input"] I2c2TxDma = 14, #[doc = "15: Signal `i2c3_rx_dma` selected as request input"] I2c3RxDma = 15, #[doc = "16: Signal `i2c3_tx_dma` selected as request input"] I2c3TxDma = 16, #[doc = "17: Signal `usart1_rx_dma` selected as request input"] Usart1RxDma = 17, #[doc = "18: Signal `usart1_tx_dma` selected as request input"] Usart1TxDma = 18, #[doc = "19: Signal `usart2_rx_dma` selected as request input"] Usart2RxDma = 19, #[doc = "20: Signal `usart2_tx_dma` selected as request input"] Usart2TxDma = 20, #[doc = "21: Signal `lpuart1_rx_dma` selected as request input"] Lpuart1RxDma = 21, #[doc = "22: Signal `lpuart1_tx_dma` selected as request input"] Lpuart1TxDma = 22, #[doc = "23: Signal `tim1_ch1` selected as request input"] Tim1Ch1 = 23, #[doc = "24: Signal `tim1_ch2` selected as request input"] Tim1Ch2 = 24, #[doc = "25: Signal `tim1_ch3` selected as request input"] Tim1Ch3 = 25, #[doc = "26: Signal `tim1_ch4` selected as request input"] Tim1Ch4 = 26, #[doc = "27: Signal `tim1_up` selected as request input"] Tim1Up = 27, #[doc = "28: Signal `tim1_trig` selected as request input"] Tim1Trig = 28, #[doc = "29: Signal `tim1_com` selected as request input"] Tim1Com = 29, #[doc = "30: Signal `tim2_ch1` selected as request input"] Tim2Ch1 = 30, #[doc = "31: Signal `tim2_ch2` selected as request input"] Tim2Ch2 = 31, #[doc = "32: Signal `tim2_ch3` selected as request input"] Tim2Ch3 = 32, #[doc = "33: Signal `tim2_ch4` selected as request input"] Tim2Ch4 = 33, #[doc = "34: Signal `tim2_up` selected as request input"] Tim2Up = 34, #[doc = "35: Signal `tim16_ch1` selected as request input"] Tim16Ch1 = 35, #[doc = "36: Signal `tim16_up` selected as request input"] Tim16Up = 36, #[doc = "37: Signal `tim17_ch1` selected as request input"] Tim17Ch1 = 37, #[doc = "38: Signal `tim17_up` selected as request input"] Tim17Up = 38, #[doc = "39: Signal `aes_in` selected as request input"] AesIn = 39, #[doc = "40: Signal `aes_out` selected as request input"] AesOut = 40, #[doc = "41: Signal `subghzspi_rx` selected as request input"] SubghzspiRx = 41, #[doc = "42: Signal `subghzspi_tx` selected as request input"] SubghzspiTx = 42, } impl From<DMAREQ_ID_A> for u8 { #[inline(always)] fn from(variant: DMAREQ_ID_A) -> Self { variant as _ } } impl crate::FieldSpec for DMAREQ_ID_A { type Ux = u8; } impl DMAREQ_ID_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<DMAREQ_ID_A> { match self.bits { 0 => Some(DMAREQ_ID_A::None), 1 => Some(DMAREQ_ID_A::Dmamux1ReqGen0), 2 => Some(DMAREQ_ID_A::Dmamux1ReqGen1), 3 => Some(DMAREQ_ID_A::Dmamux1ReqGen2), 4 => Some(DMAREQ_ID_A::Dmamux1ReqGen3), 5 => Some(DMAREQ_ID_A::Adc), 6 => Some(DMAREQ_ID_A::DatOut1), 7 => Some(DMAREQ_ID_A::Spi1RxDma), 8 => Some(DMAREQ_ID_A::Spi1TxDma), 9 => Some(DMAREQ_ID_A::Spi2RxDma), 10 => Some(DMAREQ_ID_A::Spi2TxDma), 11 => Some(DMAREQ_ID_A::I2c1RxDma), 12 => Some(DMAREQ_ID_A::I2c1TxDma), 13 => Some(DMAREQ_ID_A::I2c2RxDma), 14 => Some(DMAREQ_ID_A::I2c2TxDma), 15 => Some(DMAREQ_ID_A::I2c3RxDma), 16 => Some(DMAREQ_ID_A::I2c3TxDma), 17 => Some(DMAREQ_ID_A::Usart1RxDma), 18 => Some(DMAREQ_ID_A::Usart1TxDma), 19 => Some(DMAREQ_ID_A::Usart2RxDma), 20 => Some(DMAREQ_ID_A::Usart2TxDma), 21 => Some(DMAREQ_ID_A::Lpuart1RxDma), 22 => Some(DMAREQ_ID_A::Lpuart1TxDma), 23 => Some(DMAREQ_ID_A::Tim1Ch1), 24 => Some(DMAREQ_ID_A::Tim1Ch2), 25 => Some(DMAREQ_ID_A::Tim1Ch3), 26 => Some(DMAREQ_ID_A::Tim1Ch4), 27 => Some(DMAREQ_ID_A::Tim1Up), 28 => Some(DMAREQ_ID_A::Tim1Trig), 29 => Some(DMAREQ_ID_A::Tim1Com), 30 => Some(DMAREQ_ID_A::Tim2Ch1), 31 => Some(DMAREQ_ID_A::Tim2Ch2), 32 => Some(DMAREQ_ID_A::Tim2Ch3), 33 => Some(DMAREQ_ID_A::Tim2Ch4), 34 => Some(DMAREQ_ID_A::Tim2Up), 35 => Some(DMAREQ_ID_A::Tim16Ch1), 36 => Some(DMAREQ_ID_A::Tim16Up), 37 => Some(DMAREQ_ID_A::Tim17Ch1), 38 => Some(DMAREQ_ID_A::Tim17Up), 39 => Some(DMAREQ_ID_A::AesIn), 40 => Some(DMAREQ_ID_A::AesOut), 41 => Some(DMAREQ_ID_A::SubghzspiRx), 42 => Some(DMAREQ_ID_A::SubghzspiTx), _ => None, } } #[doc = "No signal selected as request input"] #[inline(always)] pub fn is_none(&self) -> bool { *self == DMAREQ_ID_A::None } #[doc = "Signal `dmamux1_req_gen0` selected as request input"] #[inline(always)] pub fn is_dmamux1_req_gen0(&self) -> bool { *self == DMAREQ_ID_A::Dmamux1ReqGen0 } #[doc = "Signal `dmamux1_req_gen1` selected as request input"] #[inline(always)] pub fn is_dmamux1_req_gen1(&self) -> bool { *self == DMAREQ_ID_A::Dmamux1ReqGen1 } #[doc = "Signal `dmamux1_req_gen2` selected as request input"] #[inline(always)] pub fn is_dmamux1_req_gen2(&self) -> bool { *self == DMAREQ_ID_A::Dmamux1ReqGen2 } #[doc = "Signal `dmamux1_req_gen3` selected as request input"] #[inline(always)] pub fn is_dmamux1_req_gen3(&self) -> bool { *self == DMAREQ_ID_A::Dmamux1ReqGen3 } #[doc = "Signal `adc1_dma` selected as request input"] #[inline(always)] pub fn is_adc(&self) -> bool { *self == DMAREQ_ID_A::Adc } #[doc = "Signal `dac_out1_dma` selected as request input"] #[inline(always)] pub fn is_dat_out1(&self) -> bool { *self == DMAREQ_ID_A::DatOut1 } #[doc = "Signal `spi1_rx_dma` selected as request input"] #[inline(always)] pub fn is_spi1_rx_dma(&self) -> bool { *self == DMAREQ_ID_A::Spi1RxDma } #[doc = "Signal `spi1_tx_dma` selected as request input"] #[inline(always)] pub fn is_spi1_tx_dma(&self) -> bool { *self == DMAREQ_ID_A::Spi1TxDma } #[doc = "Signal `spi2_rx_dma` selected as request input"] #[inline(always)] pub fn is_spi2_rx_dma(&self) -> bool { *self == DMAREQ_ID_A::Spi2RxDma } #[doc = "Signal `spi2_tx_dma` selected as request input"] #[inline(always)] pub fn is_spi2_tx_dma(&self) -> bool { *self == DMAREQ_ID_A::Spi2TxDma } #[doc = "Signal `i2c1_rx_dma` selected as request input"] #[inline(always)] pub fn is_i2c1_rx_dma(&self) -> bool { *self == DMAREQ_ID_A::I2c1RxDma } #[doc = "Signal `i2c1_tx_dma` selected as request input"] #[inline(always)] pub fn is_i2c1_tx_dma(&self) -> bool { *self == DMAREQ_ID_A::I2c1TxDma } #[doc = "Signal `i2c2_rx_dma` selected as request input"] #[inline(always)] pub fn is_i2c2_rx_dma(&self) -> bool { *self == DMAREQ_ID_A::I2c2RxDma } #[doc = "Signal `i2c2_tx_dma` selected as request input"] #[inline(always)] pub fn is_i2c2_tx_dma(&self) -> bool { *self == DMAREQ_ID_A::I2c2TxDma } #[doc = "Signal `i2c3_rx_dma` selected as request input"] #[inline(always)] pub fn is_i2c3_rx_dma(&self) -> bool { *self == DMAREQ_ID_A::I2c3RxDma } #[doc = "Signal `i2c3_tx_dma` selected as request input"] #[inline(always)] pub fn is_i2c3_tx_dma(&self) -> bool { *self == DMAREQ_ID_A::I2c3TxDma } #[doc = "Signal `usart1_rx_dma` selected as request input"] #[inline(always)] pub fn is_usart1_rx_dma(&self) -> bool { *self == DMAREQ_ID_A::Usart1RxDma } #[doc = "Signal `usart1_tx_dma` selected as request input"] #[inline(always)] pub fn is_usart1_tx_dma(&self) -> bool { *self == DMAREQ_ID_A::Usart1TxDma } #[doc = "Signal `usart2_rx_dma` selected as request input"] #[inline(always)] pub fn is_usart2_rx_dma(&self) -> bool { *self == DMAREQ_ID_A::Usart2RxDma } #[doc = "Signal `usart2_tx_dma` selected as request input"] #[inline(always)] pub fn is_usart2_tx_dma(&self) -> bool { *self == DMAREQ_ID_A::Usart2TxDma } #[doc = "Signal `lpuart1_rx_dma` selected as request input"] #[inline(always)] pub fn is_lpuart1_rx_dma(&self) -> bool { *self == DMAREQ_ID_A::Lpuart1RxDma } #[doc = "Signal `lpuart1_tx_dma` selected as request input"] #[inline(always)] pub fn is_lpuart1_tx_dma(&self) -> bool { *self == DMAREQ_ID_A::Lpuart1TxDma } #[doc = "Signal `tim1_ch1` selected as request input"] #[inline(always)] pub fn is_tim1_ch1(&self) -> bool { *self == DMAREQ_ID_A::Tim1Ch1 } #[doc = "Signal `tim1_ch2` selected as request input"] #[inline(always)] pub fn is_tim1_ch2(&self) -> bool { *self == DMAREQ_ID_A::Tim1Ch2 } #[doc = "Signal `tim1_ch3` selected as request input"] #[inline(always)] pub fn is_tim1_ch3(&self) -> bool { *self == DMAREQ_ID_A::Tim1Ch3 } #[doc = "Signal `tim1_ch4` selected as request input"] #[inline(always)] pub fn is_tim1_ch4(&self) -> bool { *self == DMAREQ_ID_A::Tim1Ch4 } #[doc = "Signal `tim1_up` selected as request input"] #[inline(always)] pub fn is_tim1_up(&self) -> bool { *self == DMAREQ_ID_A::Tim1Up } #[doc = "Signal `tim1_trig` selected as request input"] #[inline(always)] pub fn is_tim1_trig(&self) -> bool { *self == DMAREQ_ID_A::Tim1Trig } #[doc = "Signal `tim1_com` selected as request input"] #[inline(always)] pub fn is_tim1_com(&self) -> bool { *self == DMAREQ_ID_A::Tim1Com } #[doc = "Signal `tim2_ch1` selected as request input"] #[inline(always)] pub fn is_tim2_ch1(&self) -> bool { *self == DMAREQ_ID_A::Tim2Ch1 } #[doc = "Signal `tim2_ch2` selected as request input"] #[inline(always)] pub fn is_tim2_ch2(&self) -> bool { *self == DMAREQ_ID_A::Tim2Ch2 } #[doc = "Signal `tim2_ch3` selected as request input"] #[inline(always)] pub fn is_tim2_ch3(&self) -> bool { *self == DMAREQ_ID_A::Tim2Ch3 } #[doc = "Signal `tim2_ch4` selected as request input"] #[inline(always)] pub fn is_tim2_ch4(&self) -> bool { *self == DMAREQ_ID_A::Tim2Ch4 } #[doc = "Signal `tim2_up` selected as request input"] #[inline(always)] pub fn is_tim2_up(&self) -> bool { *self == DMAREQ_ID_A::Tim2Up } #[doc = "Signal `tim16_ch1` selected as request input"] #[inline(always)] pub fn is_tim16_ch1(&self) -> bool { *self == DMAREQ_ID_A::Tim16Ch1 } #[doc = "Signal `tim16_up` selected as request input"] #[inline(always)] pub fn is_tim16_up(&self) -> bool { *self == DMAREQ_ID_A::Tim16Up } #[doc = "Signal `tim17_ch1` selected as request input"] #[inline(always)] pub fn is_tim17_ch1(&self) -> bool { *self == DMAREQ_ID_A::Tim17Ch1 } #[doc = "Signal `tim17_up` selected as request input"] #[inline(always)] pub fn is_tim17_up(&self) -> bool { *self == DMAREQ_ID_A::Tim17Up } #[doc = "Signal `aes_in` selected as request input"] #[inline(always)] pub fn is_aes_in(&self) -> bool { *self == DMAREQ_ID_A::AesIn } #[doc = "Signal `aes_out` selected as request input"] #[inline(always)] pub fn is_aes_out(&self) -> bool { *self == DMAREQ_ID_A::AesOut } #[doc = "Signal `subghzspi_rx` selected as request input"] #[inline(always)] pub fn is_subghzspi_rx(&self) -> bool { *self == DMAREQ_ID_A::SubghzspiRx } #[doc = "Signal `subghzspi_tx` selected as request input"] #[inline(always)] pub fn is_subghzspi_tx(&self) -> bool { *self == DMAREQ_ID_A::SubghzspiTx } } #[doc = "Field `DMAREQ_ID` writer - DMA request identification"] pub type DMAREQ_ID_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 7, O, DMAREQ_ID_A>; impl<'a, REG, const O: u8> DMAREQ_ID_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u8>, { #[doc = "No signal selected as request input"] #[inline(always)] pub fn none(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::None) } #[doc = "Signal `dmamux1_req_gen0` selected as request input"] #[inline(always)] pub fn dmamux1_req_gen0(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Dmamux1ReqGen0) } #[doc = "Signal `dmamux1_req_gen1` selected as request input"] #[inline(always)] pub fn dmamux1_req_gen1(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Dmamux1ReqGen1) } #[doc = "Signal `dmamux1_req_gen2` selected as request input"] #[inline(always)] pub fn dmamux1_req_gen2(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Dmamux1ReqGen2) } #[doc = "Signal `dmamux1_req_gen3` selected as request input"] #[inline(always)] pub fn dmamux1_req_gen3(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Dmamux1ReqGen3) } #[doc = "Signal `adc1_dma` selected as request input"] #[inline(always)] pub fn adc(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Adc) } #[doc = "Signal `dac_out1_dma` selected as request input"] #[inline(always)] pub fn dat_out1(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::DatOut1) } #[doc = "Signal `spi1_rx_dma` selected as request input"] #[inline(always)] pub fn spi1_rx_dma(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Spi1RxDma) } #[doc = "Signal `spi1_tx_dma` selected as request input"] #[inline(always)] pub fn spi1_tx_dma(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Spi1TxDma) } #[doc = "Signal `spi2_rx_dma` selected as request input"] #[inline(always)] pub fn spi2_rx_dma(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Spi2RxDma) } #[doc = "Signal `spi2_tx_dma` selected as request input"] #[inline(always)] pub fn spi2_tx_dma(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Spi2TxDma) } #[doc = "Signal `i2c1_rx_dma` selected as request input"] #[inline(always)] pub fn i2c1_rx_dma(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::I2c1RxDma) } #[doc = "Signal `i2c1_tx_dma` selected as request input"] #[inline(always)] pub fn i2c1_tx_dma(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::I2c1TxDma) } #[doc = "Signal `i2c2_rx_dma` selected as request input"] #[inline(always)] pub fn i2c2_rx_dma(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::I2c2RxDma) } #[doc = "Signal `i2c2_tx_dma` selected as request input"] #[inline(always)] pub fn i2c2_tx_dma(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::I2c2TxDma) } #[doc = "Signal `i2c3_rx_dma` selected as request input"] #[inline(always)] pub fn i2c3_rx_dma(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::I2c3RxDma) } #[doc = "Signal `i2c3_tx_dma` selected as request input"] #[inline(always)] pub fn i2c3_tx_dma(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::I2c3TxDma) } #[doc = "Signal `usart1_rx_dma` selected as request input"] #[inline(always)] pub fn usart1_rx_dma(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Usart1RxDma) } #[doc = "Signal `usart1_tx_dma` selected as request input"] #[inline(always)] pub fn usart1_tx_dma(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Usart1TxDma) } #[doc = "Signal `usart2_rx_dma` selected as request input"] #[inline(always)] pub fn usart2_rx_dma(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Usart2RxDma) } #[doc = "Signal `usart2_tx_dma` selected as request input"] #[inline(always)] pub fn usart2_tx_dma(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Usart2TxDma) } #[doc = "Signal `lpuart1_rx_dma` selected as request input"] #[inline(always)] pub fn lpuart1_rx_dma(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Lpuart1RxDma) } #[doc = "Signal `lpuart1_tx_dma` selected as request input"] #[inline(always)] pub fn lpuart1_tx_dma(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Lpuart1TxDma) } #[doc = "Signal `tim1_ch1` selected as request input"] #[inline(always)] pub fn tim1_ch1(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Tim1Ch1) } #[doc = "Signal `tim1_ch2` selected as request input"] #[inline(always)] pub fn tim1_ch2(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Tim1Ch2) } #[doc = "Signal `tim1_ch3` selected as request input"] #[inline(always)] pub fn tim1_ch3(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Tim1Ch3) } #[doc = "Signal `tim1_ch4` selected as request input"] #[inline(always)] pub fn tim1_ch4(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Tim1Ch4) } #[doc = "Signal `tim1_up` selected as request input"] #[inline(always)] pub fn tim1_up(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Tim1Up) } #[doc = "Signal `tim1_trig` selected as request input"] #[inline(always)] pub fn tim1_trig(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Tim1Trig) } #[doc = "Signal `tim1_com` selected as request input"] #[inline(always)] pub fn tim1_com(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Tim1Com) } #[doc = "Signal `tim2_ch1` selected as request input"] #[inline(always)] pub fn tim2_ch1(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Tim2Ch1) } #[doc = "Signal `tim2_ch2` selected as request input"] #[inline(always)] pub fn tim2_ch2(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Tim2Ch2) } #[doc = "Signal `tim2_ch3` selected as request input"] #[inline(always)] pub fn tim2_ch3(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Tim2Ch3) } #[doc = "Signal `tim2_ch4` selected as request input"] #[inline(always)] pub fn tim2_ch4(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Tim2Ch4) } #[doc = "Signal `tim2_up` selected as request input"] #[inline(always)] pub fn tim2_up(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Tim2Up) } #[doc = "Signal `tim16_ch1` selected as request input"] #[inline(always)] pub fn tim16_ch1(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Tim16Ch1) } #[doc = "Signal `tim16_up` selected as request input"] #[inline(always)] pub fn tim16_up(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Tim16Up) } #[doc = "Signal `tim17_ch1` selected as request input"] #[inline(always)] pub fn tim17_ch1(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Tim17Ch1) } #[doc = "Signal `tim17_up` selected as request input"] #[inline(always)] pub fn tim17_up(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::Tim17Up) } #[doc = "Signal `aes_in` selected as request input"] #[inline(always)] pub fn aes_in(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::AesIn) } #[doc = "Signal `aes_out` selected as request input"] #[inline(always)] pub fn aes_out(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::AesOut) } #[doc = "Signal `subghzspi_rx` selected as request input"] #[inline(always)] pub fn subghzspi_rx(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::SubghzspiRx) } #[doc = "Signal `subghzspi_tx` selected as request input"] #[inline(always)] pub fn subghzspi_tx(self) -> &'a mut crate::W<REG> { self.variant(DMAREQ_ID_A::SubghzspiTx) } } #[doc = "Field `SOIE` reader - Synchronization overrun interrupt enable"] pub type SOIE_R = crate::BitReader<SOIE_A>; #[doc = "Synchronization overrun interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SOIE_A { #[doc = "0: Synchronization overrun interrupt disabled"] Disabled = 0, #[doc = "1: Synchronization overrun interrupt enabled"] Enabled = 1, } impl From<SOIE_A> for bool { #[inline(always)] fn from(variant: SOIE_A) -> Self { variant as u8 != 0 } } impl SOIE_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SOIE_A { match self.bits { false => SOIE_A::Disabled, true => SOIE_A::Enabled, } } #[doc = "Synchronization overrun interrupt disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == SOIE_A::Disabled } #[doc = "Synchronization overrun interrupt enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == SOIE_A::Enabled } } #[doc = "Field `SOIE` writer - Synchronization overrun interrupt enable"] pub type SOIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SOIE_A>; impl<'a, REG, const O: u8> SOIE_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Synchronization overrun interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(SOIE_A::Disabled) } #[doc = "Synchronization overrun interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(SOIE_A::Enabled) } } #[doc = "Field `EGE` reader - Event generation enable"] pub type EGE_R = crate::BitReader<EGE_A>; #[doc = "Event generation enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum EGE_A { #[doc = "0: Event generation disabled"] Disabled = 0, #[doc = "1: Event generation enabled"] Enabled = 1, } impl From<EGE_A> for bool { #[inline(always)] fn from(variant: EGE_A) -> Self { variant as u8 != 0 } } impl EGE_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EGE_A { match self.bits { false => EGE_A::Disabled, true => EGE_A::Enabled, } } #[doc = "Event generation disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == EGE_A::Disabled } #[doc = "Event generation enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == EGE_A::Enabled } } #[doc = "Field `EGE` writer - Event generation enable"] pub type EGE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, EGE_A>; impl<'a, REG, const O: u8> EGE_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Event generation disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(EGE_A::Disabled) } #[doc = "Event generation enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(EGE_A::Enabled) } } #[doc = "Field `SE` reader - Synchronization enable"] pub type SE_R = crate::BitReader<SE_A>; #[doc = "Synchronization enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SE_A { #[doc = "0: Synchronization disabled"] Disabled = 0, #[doc = "1: Synchronization enabled"] Enabled = 1, } impl From<SE_A> for bool { #[inline(always)] fn from(variant: SE_A) -> Self { variant as u8 != 0 } } impl SE_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SE_A { match self.bits { false => SE_A::Disabled, true => SE_A::Enabled, } } #[doc = "Synchronization disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == SE_A::Disabled } #[doc = "Synchronization enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == SE_A::Enabled } } #[doc = "Field `SE` writer - Synchronization enable"] pub type SE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SE_A>; impl<'a, REG, const O: u8> SE_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Synchronization disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(SE_A::Disabled) } #[doc = "Synchronization enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(SE_A::Enabled) } } #[doc = "Field `SPOL` reader - Synchronization polarity"] pub type SPOL_R = crate::FieldReader<SPOL_A>; #[doc = "Synchronization polarity\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum SPOL_A { #[doc = "0: No event, i.e. no synchronization nor detection"] NoEdge = 0, #[doc = "1: Rising edge"] RisingEdge = 1, #[doc = "2: Falling edge"] FallingEdge = 2, #[doc = "3: Rising and falling edges"] BothEdges = 3, } impl From<SPOL_A> for u8 { #[inline(always)] fn from(variant: SPOL_A) -> Self { variant as _ } } impl crate::FieldSpec for SPOL_A { type Ux = u8; } impl SPOL_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SPOL_A { match self.bits { 0 => SPOL_A::NoEdge, 1 => SPOL_A::RisingEdge, 2 => SPOL_A::FallingEdge, 3 => SPOL_A::BothEdges, _ => unreachable!(), } } #[doc = "No event, i.e. no synchronization nor detection"] #[inline(always)] pub fn is_no_edge(&self) -> bool { *self == SPOL_A::NoEdge } #[doc = "Rising edge"] #[inline(always)] pub fn is_rising_edge(&self) -> bool { *self == SPOL_A::RisingEdge } #[doc = "Falling edge"] #[inline(always)] pub fn is_falling_edge(&self) -> bool { *self == SPOL_A::FallingEdge } #[doc = "Rising and falling edges"] #[inline(always)] pub fn is_both_edges(&self) -> bool { *self == SPOL_A::BothEdges } } #[doc = "Field `SPOL` writer - Synchronization polarity"] pub type SPOL_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, SPOL_A>; impl<'a, REG, const O: u8> SPOL_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u8>, { #[doc = "No event, i.e. no synchronization nor detection"] #[inline(always)] pub fn no_edge(self) -> &'a mut crate::W<REG> { self.variant(SPOL_A::NoEdge) } #[doc = "Rising edge"] #[inline(always)] pub fn rising_edge(self) -> &'a mut crate::W<REG> { self.variant(SPOL_A::RisingEdge) } #[doc = "Falling edge"] #[inline(always)] pub fn falling_edge(self) -> &'a mut crate::W<REG> { self.variant(SPOL_A::FallingEdge) } #[doc = "Rising and falling edges"] #[inline(always)] pub fn both_edges(self) -> &'a mut crate::W<REG> { self.variant(SPOL_A::BothEdges) } } #[doc = "Field `NBREQ` reader - Number of DMA requests minus 1 to forward"] pub type NBREQ_R = crate::FieldReader; #[doc = "Field `NBREQ` writer - Number of DMA requests minus 1 to forward"] pub type NBREQ_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 5, O>; #[doc = "Field `SYNC_ID` reader - Synchronization identification"] pub type SYNC_ID_R = crate::FieldReader<SYNC_ID_A>; #[doc = "Synchronization identification\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum SYNC_ID_A { #[doc = "0: Signal `EXTIx` selected as synchronization input"] Exti0 = 0, #[doc = "1: Signal `EXTIx` selected as synchronization input"] Exti1 = 1, #[doc = "2: Signal `EXTIx` selected as synchronization input"] Exti2 = 2, #[doc = "3: Signal `EXTIx` selected as synchronization input"] Exti3 = 3, #[doc = "4: Signal `EXTIx` selected as synchronization input"] Exti4 = 4, #[doc = "5: Signal `EXTIx` selected as synchronization input"] Exti5 = 5, #[doc = "6: Signal `EXTIx` selected as synchronization input"] Exti6 = 6, #[doc = "7: Signal `EXTIx` selected as synchronization input"] Exti7 = 7, #[doc = "8: Signal `EXTIx` selected as synchronization input"] Exti8 = 8, #[doc = "9: Signal `EXTIx` selected as synchronization input"] Exti9 = 9, #[doc = "10: Signal `EXTIx` selected as synchronization input"] Exti10 = 10, #[doc = "11: Signal `EXTIx` selected as synchronization input"] Exti11 = 11, #[doc = "12: Signal `EXTIx` selected as synchronization input"] Exti12 = 12, #[doc = "13: Signal `EXTIx` selected as synchronization input"] Exti13 = 13, #[doc = "14: Signal `EXTIx` selected as synchronization input"] Exti14 = 14, #[doc = "15: Signal `EXTIx` selected as synchronization input"] Exti15 = 15, #[doc = "16: Signal `dmamux1_evt0` selected as synchronization input"] Dmamux1Evt0 = 16, #[doc = "17: Signal `dmamux1_evt1` selected as synchronization input"] Dmamux1Evt1 = 17, #[doc = "18: Signal `lptim1_out` selected as synchronization input"] Lptim1Out = 18, #[doc = "19: Signal `lptim2_out` selected as synchronization input"] Lptim2Out = 19, #[doc = "20: Signal `lptim3_out` selected as synchronization input"] Lptim3Out = 20, } impl From<SYNC_ID_A> for u8 { #[inline(always)] fn from(variant: SYNC_ID_A) -> Self { variant as _ } } impl crate::FieldSpec for SYNC_ID_A { type Ux = u8; } impl SYNC_ID_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<SYNC_ID_A> { match self.bits { 0 => Some(SYNC_ID_A::Exti0), 1 => Some(SYNC_ID_A::Exti1), 2 => Some(SYNC_ID_A::Exti2), 3 => Some(SYNC_ID_A::Exti3), 4 => Some(SYNC_ID_A::Exti4), 5 => Some(SYNC_ID_A::Exti5), 6 => Some(SYNC_ID_A::Exti6), 7 => Some(SYNC_ID_A::Exti7), 8 => Some(SYNC_ID_A::Exti8), 9 => Some(SYNC_ID_A::Exti9), 10 => Some(SYNC_ID_A::Exti10), 11 => Some(SYNC_ID_A::Exti11), 12 => Some(SYNC_ID_A::Exti12), 13 => Some(SYNC_ID_A::Exti13), 14 => Some(SYNC_ID_A::Exti14), 15 => Some(SYNC_ID_A::Exti15), 16 => Some(SYNC_ID_A::Dmamux1Evt0), 17 => Some(SYNC_ID_A::Dmamux1Evt1), 18 => Some(SYNC_ID_A::Lptim1Out), 19 => Some(SYNC_ID_A::Lptim2Out), 20 => Some(SYNC_ID_A::Lptim3Out), _ => None, } } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn is_exti0(&self) -> bool { *self == SYNC_ID_A::Exti0 } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn is_exti1(&self) -> bool { *self == SYNC_ID_A::Exti1 } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn is_exti2(&self) -> bool { *self == SYNC_ID_A::Exti2 } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn is_exti3(&self) -> bool { *self == SYNC_ID_A::Exti3 } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn is_exti4(&self) -> bool { *self == SYNC_ID_A::Exti4 } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn is_exti5(&self) -> bool { *self == SYNC_ID_A::Exti5 } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn is_exti6(&self) -> bool { *self == SYNC_ID_A::Exti6 } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn is_exti7(&self) -> bool { *self == SYNC_ID_A::Exti7 } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn is_exti8(&self) -> bool { *self == SYNC_ID_A::Exti8 } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn is_exti9(&self) -> bool { *self == SYNC_ID_A::Exti9 } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn is_exti10(&self) -> bool { *self == SYNC_ID_A::Exti10 } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn is_exti11(&self) -> bool { *self == SYNC_ID_A::Exti11 } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn is_exti12(&self) -> bool { *self == SYNC_ID_A::Exti12 } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn is_exti13(&self) -> bool { *self == SYNC_ID_A::Exti13 } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn is_exti14(&self) -> bool { *self == SYNC_ID_A::Exti14 } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn is_exti15(&self) -> bool { *self == SYNC_ID_A::Exti15 } #[doc = "Signal `dmamux1_evt0` selected as synchronization input"] #[inline(always)] pub fn is_dmamux1_evt0(&self) -> bool { *self == SYNC_ID_A::Dmamux1Evt0 } #[doc = "Signal `dmamux1_evt1` selected as synchronization input"] #[inline(always)] pub fn is_dmamux1_evt1(&self) -> bool { *self == SYNC_ID_A::Dmamux1Evt1 } #[doc = "Signal `lptim1_out` selected as synchronization input"] #[inline(always)] pub fn is_lptim1_out(&self) -> bool { *self == SYNC_ID_A::Lptim1Out } #[doc = "Signal `lptim2_out` selected as synchronization input"] #[inline(always)] pub fn is_lptim2_out(&self) -> bool { *self == SYNC_ID_A::Lptim2Out } #[doc = "Signal `lptim3_out` selected as synchronization input"] #[inline(always)] pub fn is_lptim3_out(&self) -> bool { *self == SYNC_ID_A::Lptim3Out } } #[doc = "Field `SYNC_ID` writer - Synchronization identification"] pub type SYNC_ID_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O, SYNC_ID_A>; impl<'a, REG, const O: u8> SYNC_ID_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u8>, { #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn exti0(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Exti0) } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn exti1(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Exti1) } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn exti2(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Exti2) } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn exti3(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Exti3) } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn exti4(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Exti4) } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn exti5(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Exti5) } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn exti6(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Exti6) } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn exti7(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Exti7) } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn exti8(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Exti8) } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn exti9(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Exti9) } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn exti10(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Exti10) } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn exti11(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Exti11) } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn exti12(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Exti12) } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn exti13(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Exti13) } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn exti14(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Exti14) } #[doc = "Signal `EXTIx` selected as synchronization input"] #[inline(always)] pub fn exti15(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Exti15) } #[doc = "Signal `dmamux1_evt0` selected as synchronization input"] #[inline(always)] pub fn dmamux1_evt0(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Dmamux1Evt0) } #[doc = "Signal `dmamux1_evt1` selected as synchronization input"] #[inline(always)] pub fn dmamux1_evt1(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Dmamux1Evt1) } #[doc = "Signal `lptim1_out` selected as synchronization input"] #[inline(always)] pub fn lptim1_out(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Lptim1Out) } #[doc = "Signal `lptim2_out` selected as synchronization input"] #[inline(always)] pub fn lptim2_out(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Lptim2Out) } #[doc = "Signal `lptim3_out` selected as synchronization input"] #[inline(always)] pub fn lptim3_out(self) -> &'a mut crate::W<REG> { self.variant(SYNC_ID_A::Lptim3Out) } } impl R { #[doc = "Bits 0:6 - DMA request identification"] #[inline(always)] pub fn dmareq_id(&self) -> DMAREQ_ID_R { DMAREQ_ID_R::new((self.bits & 0x7f) as u8) } #[doc = "Bit 8 - Synchronization overrun interrupt enable"] #[inline(always)] pub fn soie(&self) -> SOIE_R { SOIE_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - Event generation enable"] #[inline(always)] pub fn ege(&self) -> EGE_R { EGE_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 16 - Synchronization enable"] #[inline(always)] pub fn se(&self) -> SE_R { SE_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bits 17:18 - Synchronization polarity"] #[inline(always)] pub fn spol(&self) -> SPOL_R { SPOL_R::new(((self.bits >> 17) & 3) as u8) } #[doc = "Bits 19:23 - Number of DMA requests minus 1 to forward"] #[inline(always)] pub fn nbreq(&self) -> NBREQ_R { NBREQ_R::new(((self.bits >> 19) & 0x1f) as u8) } #[doc = "Bits 24:28 - Synchronization identification"] #[inline(always)] pub fn sync_id(&self) -> SYNC_ID_R { SYNC_ID_R::new(((self.bits >> 24) & 0x1f) as u8) } } impl W { #[doc = "Bits 0:6 - DMA request identification"] #[inline(always)] #[must_use] pub fn dmareq_id(&mut self) -> DMAREQ_ID_W<C0CR_SPEC, 0> { DMAREQ_ID_W::new(self) } #[doc = "Bit 8 - Synchronization overrun interrupt enable"] #[inline(always)] #[must_use] pub fn soie(&mut self) -> SOIE_W<C0CR_SPEC, 8> { SOIE_W::new(self) } #[doc = "Bit 9 - Event generation enable"] #[inline(always)] #[must_use] pub fn ege(&mut self) -> EGE_W<C0CR_SPEC, 9> { EGE_W::new(self) } #[doc = "Bit 16 - Synchronization enable"] #[inline(always)] #[must_use] pub fn se(&mut self) -> SE_W<C0CR_SPEC, 16> { SE_W::new(self) } #[doc = "Bits 17:18 - Synchronization polarity"] #[inline(always)] #[must_use] pub fn spol(&mut self) -> SPOL_W<C0CR_SPEC, 17> { SPOL_W::new(self) } #[doc = "Bits 19:23 - Number of DMA requests minus 1 to forward"] #[inline(always)] #[must_use] pub fn nbreq(&mut self) -> NBREQ_W<C0CR_SPEC, 19> { NBREQ_W::new(self) } #[doc = "Bits 24:28 - Synchronization identification"] #[inline(always)] #[must_use] pub fn sync_id(&mut self) -> SYNC_ID_W<C0CR_SPEC, 24> { SYNC_ID_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "channel 0 configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`c0cr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`c0cr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct C0CR_SPEC; impl crate::RegisterSpec for C0CR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`c0cr::R`](R) reader structure"] impl crate::Readable for C0CR_SPEC {} #[doc = "`write(|w| ..)` method takes [`c0cr::W`](W) writer structure"] impl crate::Writable for C0CR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets C0CR to value 0"] impl crate::Resettable for C0CR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::cmp; fn main() { let input: &str = include_str!("input.txt"); let mut p = Picture::from(input); p.enhance(2); p.enhance(48); } struct Picture { grid: Grid, template: Vec<bool>, } impl Picture { fn from(str: &str) -> Picture { let mut sections = str.split("\n\n"); let template_string = sections.next().unwrap(); let template = parse_template_to_bools(template_string); let mut grid = Grid::new(); parse_grid(sections.next().unwrap(), &mut grid); Picture { grid, template } } fn run_enhancement(&mut self) { let min_max = self.grid.min_max(); let mut new_grid = Grid::new(); // This intentionally goes too far each way - that's what is required for y in min_max.min_y-2..=min_max.max_y+2 { for x in min_max.min_x-2..=min_max.max_x+2 { let mut str = String::from(""); for i in -1..=1 { for j in -1..=1 { let v = self.grid.get(x + j, y + i); if v { str.push_str("1"); } else { str.push_str("0"); } } } let num = usize::from_str_radix(&str, 2).unwrap(); let new_b = self.template[num]; new_grid.set(new_b, x, y); } } self.grid = new_grid; } fn enhance(&mut self, max: u8) { for _i in 0..max { self.run_enhancement(); } println!("{:?}", self.grid.count_trues()); } } fn parse_template_to_bools(str: &str) -> Vec<bool> { let mut v = Vec::new(); for char in str.chars() { if char == '#' { v.push(true); } else { v.push(false); } } v } fn parse_grid(str: &str, grid: &mut Grid) { let mut y = 0; let mut max_x = 0; for line in str.lines() { let mut x = 0; for char in line.chars() { let mut b = false; if char == '#' { b = true; } grid.set(b, x, y); x += 1; max_x = x; } grid.set(false, x, y); y += 1; } for x in 0..max_x { grid.set(false, x, y); } } struct Grid { top_left: Vec<Vec<bool>>, top_right: Vec<Vec<bool>>, bottom_left: Vec<Vec<bool>>, bottom_right: Vec<Vec<bool>>, } impl Grid { fn new() -> Grid { Grid { top_left: vec![vec![false; 1]; 1], top_right: vec![vec![false; 1]; 1], bottom_left: vec![vec![false; 1]; 1], bottom_right: vec![vec![false; 1]; 1], } } fn set(&mut self, b: bool, x: i64, y: i64) { let yy = y.abs() as usize; let xx = x.abs() as usize; if x >= 0 && y >= 0 { // bottom right resize_grid_vec(&mut self.bottom_right, xx, yy ); self.bottom_right[yy][xx] = b; } else if x >= 0 { // top right resize_grid_vec(&mut self.top_right, xx, yy); self.top_right[yy][xx] = b; } else if y < 0 { // top left resize_grid_vec(&mut self.top_left, xx, yy); self.top_left[yy][xx] = b; } else { // bottom left resize_grid_vec(&mut self.bottom_left, xx, yy); self.bottom_left[yy][xx] = b; } } fn get(&mut self, x: i64, y: i64) -> bool { let mut yy = y.abs() as usize; let mut xx = x.abs() as usize; if x >= 0 && y >= 0 { // bottom right let i = alternative_x_y(&mut self.bottom_right, xx, yy); xx = i.0; yy = i.1; return self.bottom_right[yy][xx]; } else if x >= 0 { // top right let i = alternative_x_y(&mut self.top_right, xx, yy); xx = i.0; yy = i.1; return self.top_right[yy][xx]; } else if y < 0 { // top left let i = alternative_x_y(&mut self.top_left, xx, yy); xx = i.0; yy = i.1; return self.top_left[yy][xx]; } else { // bottom left let i = alternative_x_y(&mut self.bottom_left, xx, yy); xx = i.0; yy = i.1; return self.bottom_left[yy][xx]; } } fn min_max(&self) -> MinMax { // min x let min_x = -(cmp::max( self.top_left.iter().fold(0, |iter, item| cmp::max(item.len(), iter)), self.bottom_left.iter().fold(0, |iter, item| cmp::max(item.len(), iter))) as i64); let max_x = cmp::max( self.top_right.iter().fold(0, |iter, item| cmp::max(item.len(), iter)), self.bottom_right.iter().fold(0, |iter, item| cmp::max(item.len(), iter))) as i64; let min_y = -(cmp::max(self.top_left.len(), self.bottom_left.len()) as i64); let max_y = cmp::max(self.top_right.len(), self.bottom_right.len()) as i64; MinMax { min_x, min_y, max_x, max_y } } fn count_trues(&self) -> u64 { count_trues(&self.bottom_left) + count_trues(&self.bottom_right) + count_trues(&self.top_left) + count_trues(&self.top_right) } } fn resize_grid_vec(arr: &mut Vec<Vec<bool>>, xx: usize, yy: usize) { if arr.len() <= yy { arr.resize(yy + 1, Vec::new()); } if arr[yy].len() <= xx { arr[yy].resize(xx + 1, false); } } fn alternative_x_y(arr: &mut Vec<Vec<bool>>, xx: usize, yy: usize) -> (usize, usize) { let mut xxx = xx; let mut yyy = yy; if arr.len() <= yyy { yyy = arr.len() - 1; } if arr[yyy].len() <= xxx { xxx = arr[yyy].len() - 1; } (xxx, yyy) } fn count_trues(list: &Vec<Vec<bool>>) -> u64 { let mut count = 0; for y in 0..list.len() { for x in 0..list[y].len() { if list[y][x] { count += 1; } } } count } #[derive(Debug)] struct MinMax { min_x: i64, min_y: i64, max_x: i64, max_y: i64 } fn print_grid(grid: &mut Grid) { let min_max = grid.min_max(); for y in min_max.min_y..min_max.max_y { for x in min_max.min_x..min_max.max_x { if grid.get(x, y) { print!("#"); } else { print!(" "); } } println!(); } }
use std::io; fn main() { // practice of convert between Fahrenheit and Celsius println!("Please input the Fahrenheit"); let mut input_f = String::new(); io::stdin().read_line(&mut input_f) .expect("Can not read line"); let input_f: f64 = input_f.trim().parse() .expect("please type a number"); let c = convert_f_to_c(input_f); println!("The Celsius of {}F° is {}C° ", input_f, c); println!("Please input the Celsius"); let mut input_c = String::new(); io::stdin().read_line(&mut input_c) .expect("Can not read line"); let input_c: f64 = input_c.trim().parse() .expect("Please type a number"); let f = convert_c_to_f(input_c); println!("The Fahrenheit of {}C° is {}F°", input_c, f); // pracitce of generate the nth Fibonacci number for idx in 1..10{ println!("The {}st fibonacci number is {}", idx, compute_nth_fabonacci_number(idx)); } } // convert Fahrenheit to Celsius. fn convert_f_to_c (f:f64) -> f64 { 5.0 / 9.0 * (f - 32.0) } // convert Celsius to Fahrenheit fn convert_c_to_f (c:f64) -> f64 { 9.0 / 5.0 * c + 32.0 } // calculate the nth fabonacci number fn compute_nth_fabonacci_number (n: u32) -> u64 { let mut a:u64 = 0; let mut b:u64 = 1; for _ in 1..n{ let c = b; b = a + b; a = c; } b }
//! Validating References with [Lifetimes] //! //! [lifetimes]: https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html //! //! # Examples //! //! Generic lifetimes in functions. //! //! ``` //! use the_book::ch10::longest; //! //! let a = "this is a sentence."; //! let b = "This is also a sentence."; //! //! assert_eq!("This is also a sentence.", longest(&a, &b)); //! ``` //! //! Different lifetime input case //! //! ``` //! use the_book::ch10::longest; //! //! let s1 = String::from("long string is long"); //! { //! let s2 = String::from("xyz"); //! assert_eq!( //! &String::from("long string is long"), //! longest(&s1, &s2), //! ); //! } //! ``` //! //! Lifetime annotations in struct. //! //! ``` //! use the_book::ch10::ImportantExcerpt; //! //! let novel = String::from("Call me Ishmael. Some years ago..."); // 'a -+ //! let first_sentence = novel.split('.').next().unwrap(); // | //! assert_eq!("Call me Ishmael", first_sentence); // | //! let i = ImportantExcerpt::new(first_sentence); // | //! assert_eq!("Call me Ishmael", i.part()); // <--+ //! ``` //! //! Lifetime elision //! //! ``` //! use the_book::ch10::first_word; //! //! let sentence = String::from("This is a sentence."); // 'a -+ //! assert_eq!("This", first_word(sentence.as_str())); // <--+ //! ``` //! //! Lifetime elision examples in methods. //! //! ``` //! use the_book::ch10::ImportantExcerpt; //! //! let novel = String::from("Call me Keith. Some years ago..."); //! let mut lines = novel.split('.'); //! let first_sentence = lines.next().unwrap(); //! let i = ImportantExcerpt::new(first_sentence); //! assert_eq!("Call me Keith", i.part()); //! let announcement = lines.next().unwrap().trim(); //! assert_eq!("Call me Keith", i.announce_and_return_part(announcement)); //! assert_eq!("Some years ago", i.announce_and_return_announcement(announcement)); //! ``` /// It returns the longest strings. pub fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } /// Lifetime annotations example in structures. pub struct ImportantExcerpt<'a> { part: &'a str, } impl<'a> ImportantExcerpt<'a> { /// `'a` lifetime parameter to `sentence` is required so that /// it will be linked to the `ImportantExcerpt` type itself. pub fn new(sentence: &'a str) -> Self { Self { part: sentence } } /// We don't need to provide the lifetime annotation for the /// return value, as it will get the &self lifetime annotation /// through the lifetime annotation rule #3. pub fn part(&self) -> &str { self.part } /// We don't need any lifetime annotations here, as `annoucement` /// will get its own lifetime annotation, e.g. `'b` through the /// first rule of the lifetime annotation elision rule and the /// return value will get the `'a` lifetime annotation, same lifetime /// with the `Self` type itself, through the third time lifetime /// annotation elision rule. pub fn announce_and_return_part(&self, announcement: &str) -> &str { println!("Attention please: {}", announcement); self.part } /// This time, we need to give the explicit lifetime annotation to both /// the second argument, `announcement` as well as the return value, /// as the return value lifetime is not associated with the `Self` itself. pub fn announce_and_return_announcement<'b>(&self, announcement: &'b str) -> &'b str { println!("Attention please: {}", announcement); announcement } } /// `first_word` doesn't need the lifetime annotation because /// the lifetime elision rule will put `'a` to both the argument /// and the return value through the lifetime elision rule #1 and #2. pub fn first_word(s: &str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] }
#![warn(rust_2018_idioms)] use std::path::{Path, PathBuf}; use winapi::shared::minwindef::{MAX_PATH, TRUE, UINT}; use winapi::um::winnt::{HRESULT, PVOID, WCHAR}; use winapi::um::winuser::{ SystemParametersInfoW, SPIF_SENDCHANGE, SPIF_UPDATEINIFILE, SPI_GETDESKWALLPAPER, SPI_SETDESKWALLPAPER, }; use widestring::{U16CStr, U16CString}; mod error; pub use error::Error; pub type Result<T> = std::result::Result<T, Error>; /// Set desktop image. /// /// ```no_run /// use wallpaper_windows_user32::set; /// use std::path::{Path, PathBuf}; /// /// let path = Path::new(r#"C:\Users\User\AppData\Local\Temp\qwerty.jpg"#); /// let result = set(path); /// assert!(result.is_ok()) /// ``` pub fn set<T: AsRef<Path>>(full_path: T) -> Result<()> { let full_path: U16CString = U16CString::from_os_str(full_path.as_ref())?; let ret = unsafe { SystemParametersInfoW( SPI_SETDESKWALLPAPER, 0, full_path.as_ptr() as PVOID, SPIF_SENDCHANGE | SPIF_UPDATEINIFILE, ) }; check_result(ret)?; Ok(()) } /// Get desktop image. /// /// ```no_run /// use wallpaper_windows_user32::get; /// use std::path::{Path, PathBuf}; /// /// let wallpaper_path: PathBuf = get().unwrap(); /// assert_eq!(Path::new(r#"C:\Users\User\AppData\Local\Temp\qwerty.jpg"#), wallpaper_path) /// ``` pub fn get() -> Result<PathBuf> { let mut full_path_buf = [0 as WCHAR; MAX_PATH]; let ret = unsafe { SystemParametersInfoW( SPI_GETDESKWALLPAPER, full_path_buf.len() as UINT, full_path_buf.as_mut_ptr() as PVOID, 0, ) }; check_result(ret)?; let full_path: &U16CStr = U16CStr::from_slice_with_nul(&full_path_buf)?; Ok(full_path.to_os_string().into()) } fn check_result(result: HRESULT) -> Result<()> { match result { TRUE => Ok(()), _ => Err(std::io::Error::from_raw_os_error(result))?, } }
use crate::block::{Block, Content}; use crate::blockchain::BlockChain; use crate::blockdb::BlockDatabase; use crate::crypto::hash::Hashable; use crate::experiment::performance_counter::PERFORMANCE_COUNTER; use crate::miner::memory_pool::MemoryPool; use crate::network::server::Handle as ServerHandle; use std::sync::Mutex; pub fn new_validated_block( block: &Block, mempool: &Mutex<MemoryPool>, _blockdb: &BlockDatabase, chain: &BlockChain, _server: &ServerHandle, ) { PERFORMANCE_COUNTER.record_process_block(&block); // if this block is a transaction, remove transactions from mempool if let Content::Transaction(content) = &block.content { let mut mempool = mempool.lock().unwrap(); for tx in &content.transactions { mempool.remove_by_hash(&tx.hash()); // the inputs have been used here, so remove all transactions in the mempool that // tries to use the input again. for input in tx.input.iter() { mempool.remove_by_input(input); } } drop(mempool); } // insert the new block into the blockchain chain.insert_block(&block).unwrap(); }
use crate::{app, config, eww_state::*, ipc_server, script_var_handler, try_logging_errors, util, EwwPaths}; use anyhow::*; use futures_util::StreamExt; use std::{collections::HashMap, os::unix::io::AsRawFd, path::Path}; use tokio::sync::mpsc::*; pub fn initialize_server(paths: EwwPaths) -> Result<()> { do_detach(&paths.get_log_file())?; println!( r#" ┏━━━━━━━━━━━━━━━━━━━━━━━┓ ┃Initializing eww daemon┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┛ "# ); simple_signal::set_handler(&[simple_signal::Signal::Int, simple_signal::Signal::Term], move |_| { println!("Shutting down eww daemon..."); if let Err(e) = crate::application_lifecycle::send_exit() { eprintln!("Failed to send application shutdown event to workers: {:?}", e); std::process::exit(1); } }); let (ui_send, mut ui_recv) = tokio::sync::mpsc::unbounded_channel(); std::env::set_current_dir(&paths.get_config_dir()) .with_context(|| format!("Failed to change working directory to {}", paths.get_config_dir().display()))?; log::info!("Loading paths: {}", &paths); let eww_config = config::EwwConfig::read_from_file(&paths.get_eww_xml_path())?; gtk::init()?; log::info!("Initializing script var handler"); let script_var_handler = script_var_handler::init(ui_send.clone()); let mut app = app::App { eww_state: EwwState::from_default_vars(eww_config.generate_initial_state()?), eww_config, open_windows: HashMap::new(), css_provider: gtk::CssProvider::new(), script_var_handler, app_evt_send: ui_send.clone(), paths, }; if let Some(screen) = gdk::Screen::get_default() { gtk::StyleContext::add_provider_for_screen(&screen, &app.css_provider, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION); } if let Ok(eww_css) = util::parse_scss_from_file(&app.paths.get_eww_scss_path()) { app.load_css(&eww_css)?; } // initialize all the handlers and tasks running asyncronously init_async_part(app.paths.clone(), ui_send); glib::MainContext::default().spawn_local(async move { while let Some(event) = ui_recv.recv().await { app.handle_command(event); } }); gtk::main(); log::info!("main application thread finished"); Ok(()) } fn init_async_part(paths: EwwPaths, ui_send: UnboundedSender<app::DaemonCommand>) { std::thread::spawn(move || { let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().expect("Failed to initialize tokio runtime"); rt.block_on(async { let filewatch_join_handle = { let ui_send = ui_send.clone(); let paths = paths.clone(); tokio::spawn(async move { run_filewatch(paths.get_eww_xml_path(), paths.get_eww_scss_path(), ui_send).await }) }; let ipc_server_join_handle = { let ui_send = ui_send.clone(); tokio::spawn(async move { ipc_server::run_server(ui_send, paths.get_ipc_socket_file()).await }) }; let forward_exit_to_app_handle = { let ui_send = ui_send.clone(); tokio::spawn(async move { // Wait for application exit event let _ = crate::application_lifecycle::recv_exit().await; log::info!("Forward task received exit event"); // Then forward that to the application let _ = ui_send.send(app::DaemonCommand::KillServer); }) }; let result = tokio::try_join!(filewatch_join_handle, ipc_server_join_handle, forward_exit_to_app_handle); if let Err(e) = result { eprintln!("Eww exiting with error: {:?}", e); } }) }); } #[cfg(not(target_os = "linux"))] async fn run_filewatch<P: AsRef<Path>>( config_file_path: P, scss_file_path: P, evt_send: UnboundedSender<app::DaemonCommand>, ) -> Result<()> { Ok(()) } /// Watch configuration files for changes, sending reload events to the eww app when the files change. #[cfg(target_os = "linux")] async fn run_filewatch<P: AsRef<Path>>( config_file_path: P, scss_file_path: P, evt_send: UnboundedSender<app::DaemonCommand>, ) -> Result<()> { let mut inotify = inotify::Inotify::init().context("Failed to initialize inotify")?; let config_file_descriptor = inotify .add_watch(config_file_path.as_ref(), inotify::WatchMask::MODIFY) .context("Failed to add inotify watch for config file")?; let scss_file_descriptor = inotify .add_watch(scss_file_path.as_ref(), inotify::WatchMask::MODIFY) .context("Failed to add inotify watch for scss file")?; let mut buffer = [0; 1024]; let mut event_stream = inotify.event_stream(&mut buffer)?; crate::loop_select_exiting! { Some(Ok(event)) = event_stream.next() => { try_logging_errors!("handling change of config file" => { if event.wd == config_file_descriptor { log::info!("Reloading eww configuration"); let new_eww_config = config::EwwConfig::read_from_file(config_file_path.as_ref())?; evt_send.send(app::DaemonCommand::UpdateConfig(new_eww_config))?; } else if event.wd == scss_file_descriptor { log::info!("reloading eww css file"); let eww_css = crate::util::parse_scss_from_file(scss_file_path.as_ref())?; evt_send.send(app::DaemonCommand::UpdateCss(eww_css))?; } else { eprintln!("Got inotify event for unknown thing: {:?}", event); } }); } else => break, } Ok(()) } /// detach the process from the terminal, also redirecting stdout and stderr to LOG_FILE fn do_detach(log_file_path: impl AsRef<Path>) -> Result<()> { // detach from terminal match unsafe { nix::unistd::fork()? } { nix::unistd::ForkResult::Parent { .. } => { std::process::exit(0); } nix::unistd::ForkResult::Child => {} } let file = std::fs::OpenOptions::new() .create(true) .append(true) .open(&log_file_path) .expect(&format!("Error opening log file ({}), for writing", log_file_path.as_ref().to_string_lossy())); let fd = file.as_raw_fd(); if nix::unistd::isatty(1)? { nix::unistd::dup2(fd, std::io::stdout().as_raw_fd())?; } if nix::unistd::isatty(2)? { nix::unistd::dup2(fd, std::io::stderr().as_raw_fd())?; } Ok(()) }
use super::super::super::super::super::{awesome, btn, color_picker, modeless, text}; use super::super::state::{Modal, Modeless}; use super::Msg; use crate::{ block::{self, BlockId}, model::{self}, resource::Data, Color, Resource, }; use kagura::prelude::*; use wasm_bindgen::JsCast; pub fn render( block_field: &block::Field, resource: &Resource, is_grabbed: bool, tablemask: &block::table_object::Tablemask, tablemask_id: &BlockId, ) -> Html { let [xw, yw, _] = tablemask.size().clone(); let color = tablemask.color(); let is_inved = tablemask.is_inved(); modeless::body( Attributes::new().class("scroll-v"), Events::new().on_mousemove(move |e| { if !is_grabbed { e.stop_propagation(); } Msg::NoOp }), vec![Html::div( Attributes::new() .class("editormodeless") .class("pure-form") .class("linear-v"), Events::new(), vec![Html::div( Attributes::new().class("container-a").class("keyvalue"), Events::new(), vec![ text::span("形状"), Html::div( Attributes::new().class("linear-h"), Events::new(), vec![ set_type_btn(tablemask_id, "矩形", false, !tablemask.is_rounded()), set_type_btn(tablemask_id, "円形", true, tablemask.is_rounded()), ], ), text::span("反転"), btn::toggle( is_inved, Attributes::new(), Events::new().on_click({ let tablemask_id = tablemask_id.clone(); move |_| Msg::SetTablemaskIsInved(tablemask_id, !is_inved) }), ), text::span("X幅"), set_size_input(tablemask_id, xw, move |xw| [xw, yw]), text::span("Y幅"), set_size_input(tablemask_id, yw, move |yw| [xw, yw]), text::span("選択色"), Html::div( Attributes::new() .class("cell") .class("cell-medium") .style("background-color", color.to_string()), Events::new(), vec![], ), Html::div( Attributes::new().class("keyvalue-banner").class("linear-v"), Events::new(), vec![ table_color(tablemask_id, color.alpha, 3), table_color(tablemask_id, color.alpha, 5), table_color(tablemask_id, color.alpha, 7), ], ), text::span("不透明度"), Html::input( Attributes::new() .type_("number") .string("step", "1") .value((color.alpha as f32 * 100.0 / 255.0).round().to_string()), Events::new().on_input({ let tablemask_id = tablemask_id.clone(); let mut color = color.clone(); move |a| { a.parse() .map(|a: f32| { let a = (a * 255.0 / 100.0).min(255.0).max(0.0) as u8; color.alpha = a; Msg::SetTablemaskColor(tablemask_id, color) }) .unwrap_or(Msg::NoOp) } }), vec![], ), ], )], )], ) } fn set_type_btn( tablemask_id: &BlockId, text: impl Into<String>, is_rounded: bool, selected: bool, ) -> Html { btn::selectable( selected, Attributes::new(), Events::new().on_click({ let tablemask_id = tablemask_id.clone(); move |_| { if selected { Msg::NoOp } else { Msg::SetTablemaskIsRounded(tablemask_id, is_rounded) } } }), vec![Html::text(text)], ) } fn set_size_input( tablemask_id: &BlockId, s: f32, on_input: impl FnOnce(f32) -> [f32; 2] + 'static, ) -> Html { Html::input( Attributes::new() .type_("number") .value(s.to_string()) .string("step", "0.1"), Events::new().on_input({ let tablemask_id = tablemask_id.clone(); move |s| { s.parse() .map(|s| Msg::SetTablemaskSize(tablemask_id, on_input(s))) .unwrap_or(Msg::NoOp) } }), vec![], ) } fn table_color(tablemask_id: &BlockId, alpha: u8, idx: usize) -> Html { color_picker::idx(idx, Msg::NoOp, { let tablemask_id = tablemask_id.clone(); move |mut color| { color.alpha = alpha; Msg::SetTablemaskColor(tablemask_id, color) } }) }
//! A port of request parameter *Optionals from apimachinery/types.go use crate::request::Error; use serde::Serialize; /// Controls how the resource version parameter is applied for list calls /// /// Not specifying a `VersionMatch` strategy will give you different semantics /// depending on what `resource_version`, `limit`, `continue_token` you include with the list request. /// /// See <https://kubernetes.io/docs/reference/using-api/api-concepts/#semantics-for-get-and-list> for details. #[derive(Clone, Debug, PartialEq)] pub enum VersionMatch { /// Returns data at least as new as the provided resource version. /// /// The newest available data is preferred, but any data not older than the provided resource version may be served. /// This guarantees that the collection's resource version is not older than the requested resource version, /// but does not make any guarantee about the resource version of any of the items in that collection. /// /// ### Any Version /// A degenerate, but common sub-case of `NotOlderThan` is when used together with `resource_version` "0". /// /// It is possible for a "0" resource version request to return data at a much older resource version /// than the client has previously observed, particularly in HA configurations, due to partitions or stale caches. /// Clients that cannot tolerate this should not use this semantic. NotOlderThan, /// Return data at the exact resource version provided. /// /// If the provided resource version is unavailable, the server responds with HTTP 410 "Gone". /// For list requests to servers that honor the resource version Match parameter, this guarantees that the collection's /// resource version is the same as the resource version you requested in the query string. /// That guarantee does not apply to the resource version of any items within that collection. /// /// Note that `Exact` cannot be used with resource version "0". For the most up-to-date list; use `Unset`. Exact, } /// Common query parameters used in list/delete calls on collections #[derive(Clone, Debug, Default)] pub struct ListParams { /// A selector to restrict the list of returned objects by their labels. /// /// Defaults to everything if `None`. pub label_selector: Option<String>, /// A selector to restrict the list of returned objects by their fields. /// /// Defaults to everything if `None`. pub field_selector: Option<String>, /// Timeout for the list/watch call. /// /// This limits the duration of the call, regardless of any activity or inactivity. pub timeout: Option<u32>, /// Limit the number of results. /// /// If there are more results, the server will respond with a continue token which can be used to fetch another page /// of results. See the [Kubernetes API docs](https://kubernetes.io/docs/reference/using-api/api-concepts/#retrieving-large-results-sets-in-chunks) /// for pagination details. pub limit: Option<u32>, /// Fetch a second page of results. /// /// After listing results with a limit, a continue token can be used to fetch another page of results. pub continue_token: Option<String>, /// Determines how resourceVersion is matched applied to list calls. pub version_match: Option<VersionMatch>, /// An explicit resourceVersion using the given `VersionMatch` strategy /// /// See <https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions> for details. pub resource_version: Option<String>, } impl ListParams { pub(crate) fn validate(&self) -> Result<(), Error> { if let Some(rv) = &self.resource_version { if self.version_match == Some(VersionMatch::Exact) && rv == "0" { return Err(Error::Validation( "A non-zero resource_version is required when using an Exact match".into(), )); } } else if self.version_match.is_some() { return Err(Error::Validation( "A resource_version is required when using an explicit match".into(), )); } Ok(()) } // Partially populate query parameters (needs resourceVersion out of band) pub(crate) fn populate_qp(&self, qp: &mut form_urlencoded::Serializer<String>) { if let Some(fields) = &self.field_selector { qp.append_pair("fieldSelector", fields); } if let Some(labels) = &self.label_selector { qp.append_pair("labelSelector", labels); } if let Some(limit) = &self.limit { qp.append_pair("limit", &limit.to_string()); } if let Some(continue_token) = &self.continue_token { qp.append_pair("continue", continue_token); } if let Some(rv) = &self.resource_version { qp.append_pair("resourceVersion", rv.as_str()); } match &self.version_match { None => {} Some(VersionMatch::NotOlderThan) => { qp.append_pair("resourceVersionMatch", "NotOlderThan"); } Some(VersionMatch::Exact) => { qp.append_pair("resourceVersionMatch", "Exact"); } } } } /// Builder interface to ListParams /// /// Usage: /// ``` /// use kube::api::ListParams; /// let lp = ListParams::default() /// .match_any() /// .timeout(60) /// .labels("kubernetes.io/lifecycle=spot"); /// ``` impl ListParams { /// Configure the timeout for list/watch calls /// /// This limits the duration of the call, regardless of any activity or inactivity. /// Defaults to 290s #[must_use] pub fn timeout(mut self, timeout_secs: u32) -> Self { self.timeout = Some(timeout_secs); self } /// Configure the selector to restrict the list of returned objects by their fields. /// /// Defaults to everything. /// Supports `=`, `==`, `!=`, and can be comma separated: `key1=value1,key2=value2`. /// The server only supports a limited number of field queries per type. #[must_use] pub fn fields(mut self, field_selector: &str) -> Self { self.field_selector = Some(field_selector.to_string()); self } /// Configure the selector to restrict the list of returned objects by their labels. /// /// Defaults to everything. /// Supports `=`, `==`, `!=`, and can be comma separated: `key1=value1,key2=value2`. #[must_use] pub fn labels(mut self, label_selector: &str) -> Self { self.label_selector = Some(label_selector.to_string()); self } /// Sets a result limit. #[must_use] pub fn limit(mut self, limit: u32) -> Self { self.limit = Some(limit); self } /// Sets a continue token. #[must_use] pub fn continue_token(mut self, token: &str) -> Self { self.continue_token = Some(token.to_string()); self } /// Sets the resource version #[must_use] pub fn at(mut self, resource_version: &str) -> Self { self.resource_version = Some(resource_version.into()); self } /// Sets an arbitary resource version match strategy /// /// A non-default strategy such as `VersionMatch::Exact` or `VersionMatch::NotGreaterThan` /// requires an explicit `resource_version` set to pass request validation. #[must_use] pub fn matching(mut self, version_match: VersionMatch) -> Self { self.version_match = Some(version_match); self } /// Use the semantic "any" resource version strategy /// /// This is a less taxing variant of the default list, returning data at any resource version. /// It will prefer the newest avialable resource version, but strong consistency is not required; /// data at any resource version may be served. /// It is possible for the request to return data at a much older resource version than the client /// has previously observed, particularly in high availability configurations, due to partitions or stale caches. /// Clients that cannot tolerate this should not use this semantic. #[must_use] pub fn match_any(self) -> Self { self.matching(VersionMatch::NotOlderThan).at("0") } } /// Common query parameters used in get calls #[derive(Clone, Debug, Default)] pub struct GetParams { /// An explicit resourceVersion with implicit version matching strategies /// /// Default (unset) gives the most recent version. "0" gives a less /// consistent, but more performant "Any" version. Specifing a version is /// like providing a `VersionMatch::NotOlderThan`. /// See <https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions> for details. pub resource_version: Option<String>, } /// Helper interface to GetParams /// /// Usage: /// ``` /// use kube::api::GetParams; /// let gp = GetParams::at("6664"); /// ``` impl GetParams { /// Sets the resource version, implicitly applying a 'NotOlderThan' match #[must_use] pub fn at(resource_version: &str) -> Self { Self { resource_version: Some(resource_version.into()), } } /// Sets the resource version to "0" #[must_use] pub fn any() -> Self { Self::at("0") } } /// The validation directive to use for `fieldValidation` when using server-side apply. #[derive(Clone, Debug)] pub enum ValidationDirective { /// Strict mode will fail any invalid manifests. /// /// This will fail the request with a BadRequest error if any unknown fields would be dropped from the /// object, or if any duplicate fields are present. The error returned from the server will contain /// all unknown and duplicate fields encountered. Strict, /// Warn mode will return a warning for invalid manifests. /// /// This will send a warning via the standard warning response header for each unknown field that /// is dropped from the object, and for each duplicate field that is encountered. The request will /// still succeed if there are no other errors, and will only persist the last of any duplicate fields. Warn, /// Ignore mode will silently ignore any problems. /// /// This will ignore any unknown fields that are silently dropped from the object, and will ignore /// all but the last duplicate field that the decoder encounters. Ignore, } impl ValidationDirective { /// Returns the string format of the directive pub fn as_str(&self) -> &str { match self { Self::Strict => "Strict", Self::Warn => "Warn", Self::Ignore => "Ignore", } } } /// Common query parameters used in watch calls on collections #[derive(Clone, Debug)] pub struct WatchParams { /// A selector to restrict returned objects by their labels. /// /// Defaults to everything if `None`. pub label_selector: Option<String>, /// A selector to restrict returned objects by their fields. /// /// Defaults to everything if `None`. pub field_selector: Option<String>, /// Timeout for the watch call. /// /// This limits the duration of the call, regardless of any activity or inactivity. /// If unset for a watch call, we will use 290s. /// We limit this to 295s due to [inherent watch limitations](https://github.com/kubernetes/kubernetes/issues/6513). pub timeout: Option<u32>, /// Enables watch events with type "BOOKMARK". /// /// Servers that do not implement bookmarks ignore this flag and /// bookmarks are sent at the server's discretion. Clients should not /// assume bookmarks are returned at any specific interval, nor may they /// assume the server will send any BOOKMARK event during a session. /// If this is not a watch, this field is ignored. /// If the feature gate WatchBookmarks is not enabled in apiserver, /// this field is ignored. pub bookmarks: bool, } impl WatchParams { pub(crate) fn validate(&self) -> Result<(), Error> { if let Some(to) = &self.timeout { // https://github.com/kubernetes/kubernetes/issues/6513 if *to >= 295 { return Err(Error::Validation("WatchParams::timeout must be < 295s".into())); } } Ok(()) } // Partially populate query parameters (needs resourceVersion out of band) pub(crate) fn populate_qp(&self, qp: &mut form_urlencoded::Serializer<String>) { qp.append_pair("watch", "true"); // https://github.com/kubernetes/kubernetes/issues/6513 qp.append_pair("timeoutSeconds", &self.timeout.unwrap_or(290).to_string()); if let Some(fields) = &self.field_selector { qp.append_pair("fieldSelector", fields); } if let Some(labels) = &self.label_selector { qp.append_pair("labelSelector", labels); } if self.bookmarks { qp.append_pair("allowWatchBookmarks", "true"); } } } impl Default for WatchParams { /// Default `WatchParams` without any constricting selectors fn default() -> Self { Self { // bookmarks stable since 1.17, and backwards compatible bookmarks: true, label_selector: None, field_selector: None, timeout: None, } } } /// Builder interface to WatchParams /// /// Usage: /// ``` /// use kube::api::WatchParams; /// let lp = WatchParams::default() /// .timeout(60) /// .labels("kubernetes.io/lifecycle=spot"); /// ``` impl WatchParams { /// Configure the timeout for watch calls /// /// This limits the duration of the call, regardless of any activity or inactivity. /// Defaults to 290s #[must_use] pub fn timeout(mut self, timeout_secs: u32) -> Self { self.timeout = Some(timeout_secs); self } /// Configure the selector to restrict the list of returned objects by their fields. /// /// Defaults to everything. /// Supports `=`, `==`, `!=`, and can be comma separated: `key1=value1,key2=value2`. /// The server only supports a limited number of field queries per type. #[must_use] pub fn fields(mut self, field_selector: &str) -> Self { self.field_selector = Some(field_selector.to_string()); self } /// Configure the selector to restrict the list of returned objects by their labels. /// /// Defaults to everything. /// Supports `=`, `==`, `!=`, and can be comma separated: `key1=value1,key2=value2`. #[must_use] pub fn labels(mut self, label_selector: &str) -> Self { self.label_selector = Some(label_selector.to_string()); self } /// Disables watch bookmarks to simplify watch handling /// /// This is not recommended to use with production watchers as it can cause desyncs. /// See [#219](https://github.com/kube-rs/kube/issues/219) for details. #[must_use] pub fn disable_bookmarks(mut self) -> Self { self.bookmarks = false; self } } /// Common query parameters for put/post calls #[derive(Default, Clone, Debug)] pub struct PostParams { /// Whether to run this as a dry run pub dry_run: bool, /// fieldManager is a name of the actor that is making changes pub field_manager: Option<String>, } impl PostParams { pub(crate) fn populate_qp(&self, qp: &mut form_urlencoded::Serializer<String>) { if self.dry_run { qp.append_pair("dryRun", "All"); } if let Some(ref fm) = self.field_manager { qp.append_pair("fieldManager", fm); } } pub(crate) fn validate(&self) -> Result<(), Error> { if let Some(field_manager) = &self.field_manager { // Implement the easy part of validation, in future this may be extended to provide validation as in go code // For now it's fine, because k8s API server will return an error if field_manager.len() > 128 { return Err(Error::Validation( "Failed to validate PostParams::field_manager!".into(), )); } } Ok(()) } } /// Describes changes that should be applied to a resource /// /// Takes arbitrary serializable data for all strategies except `Json`. /// /// We recommend using ([server-side](https://kubernetes.io/blog/2020/04/01/kubernetes-1.18-feature-server-side-apply-beta-2)) `Apply` patches on new kubernetes releases. /// /// See [kubernetes patch docs](https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment) for the older patch types. /// /// Note that patches have different effects on different fields depending on their merge strategies. /// These strategies are configurable when deriving your [`CustomResource`](https://docs.rs/kube-derive/*/kube_derive/derive.CustomResource.html#customizing-schemas). /// /// # Creating a patch via serde_json /// ``` /// use kube::api::Patch; /// let patch = serde_json::json!({ /// "apiVersion": "v1", /// "kind": "Pod", /// "metadata": { /// "name": "blog" /// }, /// "spec": { /// "activeDeadlineSeconds": 5 /// } /// }); /// let patch = Patch::Apply(&patch); /// ``` /// # Creating a patch from a type /// ``` /// use kube::api::Patch; /// use k8s_openapi::api::rbac::v1::Role; /// use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta; /// let r = Role { /// metadata: ObjectMeta { name: Some("user".into()), ..ObjectMeta::default() }, /// rules: Some(vec![]) /// }; /// let patch = Patch::Apply(&r); /// ``` #[non_exhaustive] #[derive(Debug, PartialEq, Clone)] pub enum Patch<T: Serialize> { /// [Server side apply](https://kubernetes.io/docs/reference/using-api/api-concepts/#server-side-apply) /// /// Requires kubernetes >= 1.16 Apply(T), /// [JSON patch](https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment) /// /// Using this variant will require you to explicitly provide a type for `T` at the moment. /// /// # Example /// /// ``` /// use kube::api::Patch; /// let json_patch = json_patch::Patch(vec![]); /// let patch = Patch::Json::<()>(json_patch); /// ``` #[cfg(feature = "jsonpatch")] #[cfg_attr(docsrs, doc(cfg(feature = "jsonpatch")))] Json(json_patch::Patch), /// [JSON Merge patch](https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment) Merge(T), /// [Strategic JSON Merge patch](https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-strategic-merge-patch-to-update-a-deployment) Strategic(T), } impl<T: Serialize> Patch<T> { pub(crate) fn is_apply(&self) -> bool { matches!(self, Patch::Apply(_)) } pub(crate) fn content_type(&self) -> &'static str { match &self { Self::Apply(_) => "application/apply-patch+yaml", #[cfg(feature = "jsonpatch")] #[cfg_attr(docsrs, doc(cfg(feature = "jsonpatch")))] Self::Json(_) => "application/json-patch+json", Self::Merge(_) => "application/merge-patch+json", Self::Strategic(_) => "application/strategic-merge-patch+json", } } } impl<T: Serialize> Patch<T> { pub(crate) fn serialize(&self) -> Result<Vec<u8>, serde_json::Error> { match self { Self::Apply(p) => serde_json::to_vec(p), #[cfg(feature = "jsonpatch")] #[cfg_attr(docsrs, doc(cfg(feature = "jsonpatch")))] Self::Json(p) => serde_json::to_vec(p), Self::Strategic(p) => serde_json::to_vec(p), Self::Merge(p) => serde_json::to_vec(p), } } } /// Common query parameters for patch calls #[derive(Default, Clone, Debug)] pub struct PatchParams { /// Whether to run this as a dry run pub dry_run: bool, /// force Apply requests. Applicable only to [`Patch::Apply`]. pub force: bool, /// fieldManager is a name of the actor that is making changes. Required for [`Patch::Apply`] /// optional for everything else. pub field_manager: Option<String>, /// The server-side validation directive to use. Applicable only to [`Patch::Apply`]. pub field_validation: Option<ValidationDirective>, } impl PatchParams { pub(crate) fn validate<P: Serialize>(&self, patch: &Patch<P>) -> Result<(), Error> { if let Some(field_manager) = &self.field_manager { // Implement the easy part of validation, in future this may be extended to provide validation as in go code // For now it's fine, because k8s API server will return an error if field_manager.len() > 128 { return Err(Error::Validation( "Failed to validate PatchParams::field_manager!".into(), )); } } if self.force && !patch.is_apply() { return Err(Error::Validation( "PatchParams::force only works with Patch::Apply".into(), )); } Ok(()) } pub(crate) fn populate_qp(&self, qp: &mut form_urlencoded::Serializer<String>) { if self.dry_run { qp.append_pair("dryRun", "All"); } if self.force { qp.append_pair("force", "true"); } if let Some(ref fm) = self.field_manager { qp.append_pair("fieldManager", fm); } if let Some(sv) = &self.field_validation { qp.append_pair("fieldValidation", sv.as_str()); } } /// Construct `PatchParams` for server-side apply #[must_use] pub fn apply(manager: &str) -> Self { Self { field_manager: Some(manager.into()), ..Self::default() } } /// Force the result through on conflicts /// /// NB: Force is a concept restricted to the server-side [`Patch::Apply`]. #[must_use] pub fn force(mut self) -> Self { self.force = true; self } /// Perform a dryRun only #[must_use] pub fn dry_run(mut self) -> Self { self.dry_run = true; self } /// Set the validation directive for `fieldValidation` during server-side apply. pub fn validation(mut self, vd: ValidationDirective) -> Self { self.field_validation = Some(vd); self } /// Set the validation directive to `Ignore` #[must_use] pub fn validation_ignore(self) -> Self { self.validation(ValidationDirective::Ignore) } /// Set the validation directive to `Warn` #[must_use] pub fn validation_warn(self) -> Self { self.validation(ValidationDirective::Warn) } /// Set the validation directive to `Strict` #[must_use] pub fn validation_strict(self) -> Self { self.validation(ValidationDirective::Strict) } } /// Common query parameters for delete calls #[derive(Default, Clone, Serialize, Debug)] #[serde(rename_all = "camelCase")] pub struct DeleteParams { /// When present, indicates that modifications should not be persisted. #[serde( serialize_with = "dry_run_all_ser", skip_serializing_if = "std::ops::Not::not" )] pub dry_run: bool, /// The duration in seconds before the object should be deleted. /// /// Value must be non-negative integer. The value zero indicates delete immediately. /// If this value is `None`, the default grace period for the specified type will be used. /// Defaults to a per object value if not specified. Zero means delete immediately. #[serde(skip_serializing_if = "Option::is_none")] pub grace_period_seconds: Option<u32>, /// Whether or how garbage collection is performed. /// /// The default policy is decided by the existing finalizer set in /// `metadata.finalizers`, and the resource-specific default policy. #[serde(skip_serializing_if = "Option::is_none")] pub propagation_policy: Option<PropagationPolicy>, /// Condtions that must be fulfilled before a deletion is carried out /// /// If not possible, a `409 Conflict` status will be returned. #[serde(skip_serializing_if = "Option::is_none")] pub preconditions: Option<Preconditions>, } impl DeleteParams { /// Construct `DeleteParams` with `PropagationPolicy::Background`. /// /// This allows the garbage collector to delete the dependents in the background. pub fn background() -> Self { Self { propagation_policy: Some(PropagationPolicy::Background), ..Self::default() } } /// Construct `DeleteParams` with `PropagationPolicy::Foreground`. /// /// This is a cascading policy that deletes all dependents in the foreground. pub fn foreground() -> Self { Self { propagation_policy: Some(PropagationPolicy::Foreground), ..Self::default() } } /// Construct `DeleteParams` with `PropagationPolicy::Orphan`. /// /// /// This orpans the dependents. pub fn orphan() -> Self { Self { propagation_policy: Some(PropagationPolicy::Orphan), ..Self::default() } } /// Perform a dryRun only #[must_use] pub fn dry_run(mut self) -> Self { self.dry_run = true; self } /// Set the duration in seconds before the object should be deleted. #[must_use] pub fn grace_period(mut self, secs: u32) -> Self { self.grace_period_seconds = Some(secs); self } /// Set the condtions that must be fulfilled before a deletion is carried out. #[must_use] pub fn preconditions(mut self, preconditions: Preconditions) -> Self { self.preconditions = Some(preconditions); self } pub(crate) fn is_default(&self) -> bool { !self.dry_run && self.grace_period_seconds.is_none() && self.propagation_policy.is_none() && self.preconditions.is_none() } } // dryRun serialization differ when used as body parameters and query strings: // query strings are either true/false // body params allow only: missing field, or ["All"] // The latter is a very awkward API causing users to do to // dp.dry_run = vec!["All".into()]; // just to turn on dry_run.. // so we hide this detail for now. fn dry_run_all_ser<S>(t: &bool, s: S) -> std::result::Result<S::Ok, S::Error> where S: serde::ser::Serializer, { use serde::ser::SerializeTuple; match t { true => { let mut map = s.serialize_tuple(1)?; map.serialize_element("All")?; map.end() } false => s.serialize_none(), } } #[cfg(test)] mod test { use super::{DeleteParams, PatchParams}; #[test] fn delete_param_serialize() { let mut dp = DeleteParams::default(); let emptyser = serde_json::to_string(&dp).unwrap(); //println!("emptyser is: {}", emptyser); assert_eq!(emptyser, "{}"); dp.dry_run = true; let ser = serde_json::to_string(&dp).unwrap(); //println!("ser is: {}", ser); assert_eq!(ser, "{\"dryRun\":[\"All\"]}"); } #[test] fn delete_param_constructors() { let dp_background = DeleteParams::background(); let ser = serde_json::to_value(dp_background).unwrap(); assert_eq!(ser, serde_json::json!({"propagationPolicy": "Background"})); let dp_foreground = DeleteParams::foreground(); let ser = serde_json::to_value(dp_foreground).unwrap(); assert_eq!(ser, serde_json::json!({"propagationPolicy": "Foreground"})); let dp_orphan = DeleteParams::orphan(); let ser = serde_json::to_value(dp_orphan).unwrap(); assert_eq!(ser, serde_json::json!({"propagationPolicy": "Orphan"})); } #[test] fn patch_param_serializes_field_validation() { let pp = PatchParams::default().validation_ignore(); let mut qp = form_urlencoded::Serializer::new(String::from("some/resource?")); pp.populate_qp(&mut qp); let urlstr = qp.finish(); assert_eq!(String::from("some/resource?&fieldValidation=Ignore"), urlstr); let pp = PatchParams::default().validation_warn(); let mut qp = form_urlencoded::Serializer::new(String::from("some/resource?")); pp.populate_qp(&mut qp); let urlstr = qp.finish(); assert_eq!(String::from("some/resource?&fieldValidation=Warn"), urlstr); let pp = PatchParams::default().validation_strict(); let mut qp = form_urlencoded::Serializer::new(String::from("some/resource?")); pp.populate_qp(&mut qp); let urlstr = qp.finish(); assert_eq!(String::from("some/resource?&fieldValidation=Strict"), urlstr); } } /// Preconditions must be fulfilled before an operation (update, delete, etc.) is carried out. #[derive(Default, Clone, Serialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Preconditions { /// Specifies the target ResourceVersion #[serde(skip_serializing_if = "Option::is_none")] pub resource_version: Option<String>, /// Specifies the target UID #[serde(skip_serializing_if = "Option::is_none")] pub uid: Option<String>, } /// Propagation policy when deleting single objects #[derive(Clone, Debug, Serialize)] pub enum PropagationPolicy { /// Orphan dependents Orphan, /// Allow the garbage collector to delete the dependents in the background Background, /// A cascading policy that deletes all dependents in the foreground Foreground, }
use std::collections::HashSet; pub struct Solution {} /// LeetCode Monthly Challenge problem for March 1st, 2021. impl Solution { /// Given a vector of i32 integers, returns the minimum of unique integers, /// or half the vector length. /// /// # Arguments /// /// * candy_type - A vector of i32 integers, each representing a type of /// candy. /// /// # Examples /// /// ``` /// # use crate::distribute_candies::Solution; /// let ex_one = Solution::distribute_candies(vec![1,1,2,2,3,3]); /// let ex_two = Solution::distribute_candies(vec![1,1,2,3]); /// let ex_three = Solution::distribute_candies(vec![6,6,6,6]); /// /// assert_eq!(ex_one, 3); /// assert_eq!(ex_two, 2); /// assert_eq!(ex_three, 1); /// ``` /// /// # Constraints /// /// * n == candy_type.len() /// * 2 <= n <= 10^4 /// * n is even /// * -10^5 <= candy_type[i] <= 10^5 /// pub fn distribute_candies(candy_type: Vec<i32>) -> i32 { let unique: HashSet<&i32> = candy_type.iter().collect(); unique.len().min(candy_type.len()/2) as i32 } } #[cfg(test)] mod tests { use super::*; #[test] fn candy_unique_equals_half_length() { assert_eq!( Solution::distribute_candies(vec![1,1,2,2,3,3]), 3, ); } #[test] fn candy_half_length_greather_than_unique() { assert_eq!( Solution::distribute_candies(vec![1,1,2,3]), 2 ); } #[test] fn candy_unique_less_than_half_length() { assert_eq!( Solution::distribute_candies(vec![6,6,6,6]), 1, ); } }
use std::collections::{HashMap, HashSet}; use hydroflow::util::collect_ready; use hydroflow::{assert_graphvis_snapshots, hydroflow_syntax}; use multiplatform_test::multiplatform_test; #[multiplatform_test] pub fn test_fold_tick() { let (items_send, items_recv) = hydroflow::util::unbounded_channel::<Vec<u32>>(); let (result_send, mut result_recv) = hydroflow::util::unbounded_channel::<Vec<u32>>(); let mut df = hydroflow::hydroflow_syntax! { source_stream(items_recv) -> fold::<'tick>(Vec::new(), |old: &mut Vec<u32>, mut x: Vec<u32>| { old.append(&mut x); }) -> for_each(|v| result_send.send(v).unwrap()); }; assert_graphvis_snapshots!(df); assert_eq!((0, 0), (df.current_tick(), df.current_stratum())); items_send.send(vec![1, 2]).unwrap(); items_send.send(vec![3, 4]).unwrap(); df.run_tick(); assert_eq!((1, 0), (df.current_tick(), df.current_stratum())); assert_eq!( &[vec![1, 2, 3, 4]], &*collect_ready::<Vec<_>, _>(&mut result_recv) ); items_send.send(vec![5, 6]).unwrap(); items_send.send(vec![7, 8]).unwrap(); df.run_tick(); assert_eq!((2, 0), (df.current_tick(), df.current_stratum())); assert_eq!( &[vec![5, 6, 7, 8]], &*collect_ready::<Vec<_>, _>(&mut result_recv) ); df.run_available(); // Should return quickly and not hang } #[multiplatform_test] pub fn test_fold_static() { let (items_send, items_recv) = hydroflow::util::unbounded_channel::<Vec<u32>>(); let (result_send, mut result_recv) = hydroflow::util::unbounded_channel::<Vec<u32>>(); let mut df = hydroflow::hydroflow_syntax! { source_stream(items_recv) -> fold::<'static>(Vec::new(), |old: &mut Vec<u32>, mut x: Vec<u32>| { old.append(&mut x); }) -> for_each(|v| result_send.send(v).unwrap()); }; assert_graphvis_snapshots!(df); assert_eq!((0, 0), (df.current_tick(), df.current_stratum())); items_send.send(vec![1, 2]).unwrap(); items_send.send(vec![3, 4]).unwrap(); df.run_tick(); assert_eq!((1, 0), (df.current_tick(), df.current_stratum())); assert_eq!( &[vec![1, 2, 3, 4]], &*collect_ready::<Vec<_>, _>(&mut result_recv) ); items_send.send(vec![5, 6]).unwrap(); items_send.send(vec![7, 8]).unwrap(); df.run_tick(); assert_eq!((2, 0), (df.current_tick(), df.current_stratum())); assert_eq!( &[vec![1, 2, 3, 4, 5, 6, 7, 8]], &*collect_ready::<Vec<_>, _>(&mut result_recv) ); df.run_available(); // Should return quickly and not hang } #[multiplatform_test] pub fn test_fold_flatten() { // test pull let (out_send, mut out_recv) = hydroflow::util::unbounded_channel::<(u8, u8)>(); let mut df_pull = hydroflow_syntax! { source_iter([(1,1), (1,2), (2,3), (2,4)]) -> fold::<'tick>(HashMap::<u8, u8>::new(), |ht: &mut HashMap<u8, u8>, t: (u8,u8)| { let e = ht.entry(t.0).or_insert(0); *e += t.1; }) -> flatten() -> for_each(|(k,v)| out_send.send((k,v)).unwrap()); }; assert_eq!((0, 0), (df_pull.current_tick(), df_pull.current_stratum())); df_pull.run_tick(); assert_eq!((1, 0), (df_pull.current_tick(), df_pull.current_stratum())); let out: HashSet<_> = collect_ready(&mut out_recv); for pair in [(1, 3), (2, 7)] { assert!(out.contains(&pair)); } // test push let (out_send, mut out_recv) = hydroflow::util::unbounded_channel::<(u8, u8)>(); let mut df_push = hydroflow_syntax! { datagen = source_iter([(1,2), (1,2), (2,4), (2,4)]) -> tee(); datagen[0] -> fold::<'tick>(HashMap::<u8, u8>::new(), |ht: &mut HashMap<u8, u8>, t:(u8,u8)| { let e = ht.entry(t.0).or_insert(0); *e += t.1; }) -> flatten() -> for_each(|(k,v)| out_send.send((k,v)).unwrap()); datagen[1] -> null(); }; assert_eq!((0, 0), (df_push.current_tick(), df_push.current_stratum())); df_push.run_tick(); assert_eq!((1, 0), (df_push.current_tick(), df_push.current_stratum())); let out: HashSet<_> = collect_ready(&mut out_recv); for pair in [(1, 4), (2, 8)] { assert!(out.contains(&pair)); } df_push.run_available(); // Should return quickly and not hang df_pull.run_available(); // Should return quickly and not hang } #[multiplatform_test] pub fn test_fold_sort() { let (items_send, items_recv) = hydroflow::util::unbounded_channel::<usize>(); let mut df = hydroflow_syntax! { source_stream(items_recv) -> fold::<'tick>(Vec::new(), Vec::push) -> flat_map(|mut vec| { vec.sort(); vec }) -> for_each(|v| print!("{:?}, ", v)); }; assert_graphvis_snapshots!(df); assert_eq!((0, 0), (df.current_tick(), df.current_stratum())); df.run_tick(); assert_eq!((1, 0), (df.current_tick(), df.current_stratum())); print!("\nA: "); items_send.send(9).unwrap(); items_send.send(2).unwrap(); items_send.send(5).unwrap(); df.run_tick(); assert_eq!((2, 0), (df.current_tick(), df.current_stratum())); print!("\nB: "); items_send.send(9).unwrap(); items_send.send(5).unwrap(); items_send.send(2).unwrap(); items_send.send(0).unwrap(); items_send.send(3).unwrap(); df.run_tick(); assert_eq!((3, 0), (df.current_tick(), df.current_stratum())); println!(); df.run_available(); // Should return quickly and not hang }
mod libc_wrapper; mod tagfs; use chrono::Local; use std::ffi::OsStr; use std::{env, io}; use crate::tagfs::TagFS; #[macro_use] extern crate log; struct ConsoleLogger; impl log::Log for ConsoleLogger { fn enabled(&self, _metadata: &log::Metadata) -> bool { true } fn log(&self, record: &log::Record) { println!( "{} {} {} - {}", Local::now().format("%Y-%m-%dT%H:%M:%S%z"), record.level(), record.target(), record.args() ); } fn flush(&self) {} } static LOGGER: ConsoleLogger = ConsoleLogger; fn main() -> io::Result<()> { log::set_logger(&LOGGER).unwrap(); log::set_max_level(log::LevelFilter::Debug); let args: Vec<String> = env::args().collect(); let tag_fs = TagFS::new(&args[1]); debug!("Hi"); trace!("Hello, world!"); info!("bye"); let fuse_args: Vec<&OsStr> = vec![OsStr::new("-o"), OsStr::new("auto_unmount")]; fuse_mt::mount(fuse_mt::FuseMT::new(tag_fs, 1), &args[2], &fuse_args).unwrap(); Ok(()) }
mod cd_args; mod ls_args; mod cat_args; pub use cd_args::CdArgs; pub use ls_args::LsArgs; pub use cat_args::CatArgs;
#[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum Network { Mainnet, Devnet, Testnet, } impl Network { pub fn epoch(&self) -> &'static str { match *self { Network::Mainnet => "2017-03-21T13:00:00.000Z", Network::Devnet => "2017-03-21T13:00:00.000Z", Network::Testnet => "2017-03-21T13:00:00.000Z", } } pub fn version(&self) -> u8 { match *self { Network::Mainnet => 0x17, Network::Devnet => 0x1e, Network::Testnet => 0x17, } } pub fn wif(&self) -> u8 { match *self { Network::Mainnet => 170, Network::Devnet => 170, Network::Testnet => 186, } } }
pub fn question2() { let number = 0; if number < 0 { println!("value {} is Nagitive",number); } else { println!("value {} is Positive",number); } }
pub fn xor_byte_slices(raw_bytes_1: &[u8], raw_bytes_2: &[u8]) -> Vec<u8> { let mut raw_bytes_xor = Vec::with_capacity(raw_bytes_1.len()); if raw_bytes_1.len() != raw_bytes_2.len() { panic!("bytes to xor must have equal length") } let mut i = 0; while i < raw_bytes_1.len() { raw_bytes_xor.push(raw_bytes_1[i] ^ raw_bytes_2[i]); i += 1; } return raw_bytes_xor; } pub fn xor_byte_slice_fixed(raw_bytes: &[u8], key: u8) -> Vec<u8> { let mut raw_bytes_xor = Vec::with_capacity(raw_bytes.len()); let mut i = 0; while i < raw_bytes.len() { raw_bytes_xor.push(raw_bytes[i] ^ key); i += 1; } return raw_bytes_xor; } pub fn xor_bytes_repeating_key(bytes: &[u8], key: &[u8]) -> Vec<u8> { if key.len() == 0 { panic!("Key length must be >= 0"); } let mut ciphertext = Vec::with_capacity(bytes.len()); let mut i = 0; let mut j = 0; while i < bytes.len() { ciphertext.push(bytes[i] ^ key[j]); i += 1; j = (j + 1) % key.len(); } return ciphertext; }
use bevy::prelude::*; pub struct Plate; pub struct PlateMaterial(Handle<ColorMaterial>); pub const PLATE_WIDTH: f32 = 80.; pub const PLATE_HEIGHT: f32 = 10.; pub fn init( commands: &mut Commands, asset_server: &AssetServer, materials: &mut ResMut<Assets<ColorMaterial>>, ) { let plate_sprite = asset_server.load("sprites/plate.png"); commands.insert_resource(PlateMaterial(materials.add(plate_sprite.into()))); } pub fn spawn(commands: &mut Commands, materials: &Res<PlateMaterial>, pos: &(f32, f32)) { commands .insert_resource(Plate) .spawn(SpriteBundle { material: materials.0.clone(), sprite: Sprite::new(Vec2::new(PLATE_WIDTH, PLATE_HEIGHT)), transform: Transform::from_translation(Vec3::new(pos.0, pos.1, 0.)), ..Default::default() }) .with(Plate); }
fn main(){ let x = String::from("Hello"); let y = &x; println!("{}", y); //this line fails. comment out to fix println!("{}", x); //this line fails. comment out to fix // so what happens here? // x is the owner of some data, and x holds a reference to // a string. // y then is given a pointer to this string, as copies are // by reference if the data is on the heap. // y is now the owner of the the data "Hello". X looses // ownership and looses acces to the value. This to help // avoid a double free. }
// SPDX-License-Identifier: Apache-2.0 use crate::evp; use cipher_bench::{BlockCipher, BlockCipherBuilder}; use std::os::raw::c_int; use std::ptr; pub struct Aes128CbcCtxBuilder { iv: Option<Vec<u8>>, } impl Aes128CbcCtxBuilder { pub fn new() -> Self { Self { iv: None } } fn build(&mut self, key: &[u8], for_encryption: bool) -> Box<dyn BlockCipher> { let ctx = unsafe { let ctx: *mut evp::EVP_CIPHER_CTX = evp::EVP_CIPHER_CTX_new(); let cipher = evp::EVP_aes_128_cbc(); let iv = self.iv.take().unwrap(); let _ = evp::EVP_CipherInit_ex( ctx, cipher, ptr::null_mut::<evp::ENGINE>(), key.as_ptr() as _, iv.as_ptr() as _, for_encryption as _, ); ctx }; Box::new(Aes128CbcCtx { ctx }) } } impl BlockCipherBuilder for Aes128CbcCtxBuilder { fn nonce(&mut self, iv: &[u8]) -> &mut Self { self.iv.replace(iv.to_vec()); self } fn for_encryption(&mut self, key: &[u8]) -> Box<dyn BlockCipher> { self.build(&key, true) } fn for_decryption(&mut self, key: &[u8]) -> Box<dyn BlockCipher> { self.build(&key, false) } } pub struct Aes128CbcCtx { ctx: *mut evp::EVP_CIPHER_CTX, } impl BlockCipher for Aes128CbcCtx { fn encrypt(&mut self, ptext: &[u8], ctext: &mut [u8]) { let mut outl = ctext.len() as c_int; unsafe { evp::EVP_EncryptUpdate( self.ctx, ctext.as_mut_ptr() as *mut _, &mut outl, ptext.as_ptr() as _, ptext.len() as _, ); } } fn decrypt(&mut self, ctext: &[u8], ptext: &mut [u8]) { let mut outl = ptext.len() as c_int; unsafe { evp::EVP_DecryptUpdate( self.ctx, ptext.as_mut_ptr() as *mut _, &mut outl, ctext.as_ptr() as _, ctext.len() as _, ); } } } #[cfg(test)] mod tests { use super::*; use cipher_bench::BlockCipherAlgorithm; use rand::prelude::*; use std::convert::TryInto; #[test] fn roundtrip() { let mut rng = rand::thread_rng(); let mut key_bytes = vec![0u8; BlockCipherAlgorithm::Aes128Cbc.key_len()]; rng.fill(key_bytes.as_mut_slice()); let mut nonce_bytes = vec![0u8; BlockCipherAlgorithm::Aes128Cbc.nonce_len()]; rng.fill(nonce_bytes.as_mut_slice()); let mut data_bytes = vec![0u8; 1024]; rng.fill(data_bytes.as_mut_slice()); let mut ptext = vec![0u8; 1024]; ptext.copy_from_slice(data_bytes.as_slice()); let mut ctext = vec![0u8; 1024]; let mut builder = Aes128CbcCtxBuilder::new(); let mut ctx = builder.nonce(&nonce_bytes).for_encryption(&key_bytes); ctx.encrypt(&ptext, &mut ctext); let mut ctx = builder.nonce(&nonce_bytes).for_decryption(&key_bytes); ctx.decrypt(&ctext, &mut ptext); assert_eq!(ptext, data_bytes); } }
use std::sync::Arc; use eyre::Report; use hashbrown::HashMap; use rosu_v2::{ prelude::{GameMode, OsuError, Username}, OsuResult, }; use twilight_model::id::{marker::ChannelMarker, Id}; use crate::{ embeds::{EmbedData, TrackListEmbed}, util::{constants::OSU_API_ISSUE, MessageExt}, BotResult, CommandData, Context, MessageBuilder, }; pub struct TracklistUserEntry { pub name: Username, pub mode: GameMode, pub limit: usize, } #[command] #[authority()] #[short_desc("Display tracked users of a channel")] #[aliases("tl")] pub async fn tracklist(ctx: Arc<Context>, data: CommandData) -> BotResult<()> { let channel_id = data.channel_id(); let tracked = ctx.tracking().list(channel_id); let mut users = match get_users(&ctx, data.channel_id(), tracked).await { Ok(entries) => entries, Err(err) => { let _ = data.error(&ctx, OSU_API_ISSUE).await; return Err(err.into()); } }; users.sort_unstable_by(|a, b| { (a.mode as u8) .cmp(&(b.mode as u8)) .then(a.name.cmp(&b.name)) }); let embeds = TrackListEmbed::new(users); if embeds.is_empty() { let content = "No tracked users in this channel"; let builder = MessageBuilder::new().content(content); data.create_message(&ctx, builder).await?; } else { for embed_data in embeds { let embed = embed_data.into_builder().build(); let builder = MessageBuilder::new().embed(embed); data.create_message(&ctx, builder).await?; } } Ok(()) } async fn get_users( ctx: &Context, channel: Id<ChannelMarker>, tracked: Vec<(u32, GameMode, usize)>, ) -> OsuResult<Vec<TracklistUserEntry>> { let user_ids: Vec<_> = tracked.iter().map(|(id, ..)| *id as i32).collect(); let stored_names = match ctx.psql().get_names_by_ids(&user_ids).await { Ok(map) => map, Err(err) => { let report = Report::new(err).wrap_err("failed to get names by ids"); warn!("{report:?}",); HashMap::new() } }; let mut users = Vec::with_capacity(tracked.len()); for (user_id, mode, limit) in tracked { let entry = match stored_names.get(&user_id) { Some(name) => TracklistUserEntry { name: name.to_owned(), mode, limit, }, None => match ctx.osu().user(user_id).mode(mode).await { Ok(user) => { if let Err(err) = ctx.psql().upsert_osu_user(&user, mode).await { let report = Report::new(err).wrap_err("failed to upsert user"); warn!("{report:?}"); } TracklistUserEntry { name: user.username, mode, limit, } } Err(OsuError::NotFound) => { let remove_fut = ctx .tracking() .remove_user(user_id, None, channel, ctx.psql()); if let Err(err) = remove_fut.await { warn!("Error while removing unknown user {user_id} from tracking: {err}"); } continue; } Err(err) => return Err(err), }, }; users.push(entry); } Ok(users) }
use std::fmt::{Display, Formatter}; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Term { Var(Var), Const(Const), Atom(Atom), } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Var(pub String, pub usize); #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Const(pub String); #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Atom { pub name: Const, pub arity: Arity, pub args: Vec<Term>, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct Assertion { pub head: Atom, pub clause: Clause, } pub type Arity = usize; pub type Clause = Vec<Atom>; impl Assertion { pub fn new(head: Atom, clause: Clause) -> Self { Assertion { head, clause } } } impl Atom { pub fn new(name: &str, args: Vec<Term>) -> Self { Atom { name: Const::new(name), arity: args.len(), args, } } } impl Var { pub fn new(name: &str, n: usize) -> Self { Var(String::from(name), n) } } impl Const { pub fn new(name: &str) -> Self { Const(String::from(name)) } } impl Display for Term { fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> { match self { Term::Var(Var(name, n)) if *n == 0 => Ok(write!(f, "{}", name)?), Term::Var(Var(name, n)) => Ok(write!(f, "{}{}", name, n)?), Term::Const(Const(a)) => Ok(write!(f, "{}", a)?), Term::Atom(Atom { name: Const(name), args, .. }) => match args.last() { None => Ok(write!(f, "{}", &name)?), Some(last) => { let init = &args[..args.len() - 1]; let mut args = String::new(); for arg in init { args.push_str(&format!("{}, ", arg)); } args.push_str(&format!("{})", last)); Ok(write!(f, "{}({}", &name, args)?) } }, } } } impl Display for Var { fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> { Ok(write!(f, "{}", Term::Var(self.clone()))?) } } impl Display for Const { fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> { Ok(write!(f, "{}", Term::Const(self.clone()))?) } } impl Display for Atom { fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> { Ok(write!(f, "{}", Term::Atom(self.clone()))?) } }
macro_rules! test_op { ($ty:ty => $lhs:literal $op:tt $rhs:literal = $result:literal) => {{ let program = format!( r#"const A = {lhs}; const B = {rhs}; const VALUE = A {op} B; fn main() {{ VALUE }}"#, lhs = $lhs, rhs = $rhs, op = stringify!($op), ); assert_eq!( $result, rune!($ty => &program), concat!("expected ", stringify!($result), " out of program `{}`"), program ); }} } #[test] fn test_const_values() { assert_eq!( true, rune!(bool => r#"const VALUE = true; fn main() { VALUE }"#) ); assert_eq!( "Hello World", rune!(String => r#"const VALUE = "Hello World"; fn main() { VALUE }"#) ); assert_eq!( "Hello World 1 1.0 true", rune!(String => r#" const VALUE = `Hello {WORLD} {A} {B} {C}`; const WORLD = "World"; const A = 1; const B = 1.0; const C = true; fn main() { VALUE } "#) ); } #[test] fn test_integer_ops() { test_op!(i64 => 1 + 2 = 3); test_op!(i64 => 2 - 1 = 1); test_op!(i64 => 8 / 2 = 4); test_op!(i64 => 8 * 2 = 16); test_op!(i64 => 0b1010 << 2 = 0b101000); test_op!(i64 => 0b1010 >> 2 = 0b10); test_op!(bool => 1 < 2 = true); test_op!(bool => 2 < 2 = false); test_op!(bool => 1 <= 1 = true); test_op!(bool => 2 <= 1 = false); test_op!(bool => 3 > 2 = true); test_op!(bool => 2 > 2 = false); test_op!(bool => 1 >= 1 = true); test_op!(bool => 0 >= 2 = false); } macro_rules! test_float_op { ($ty:ty => $lhs:literal $op:tt $rhs:literal = $result:literal) => {{ let program = format!( r#"const A = {lhs}.0; const B = {rhs}.0; const VALUE = A {op} B; fn main() {{ VALUE }}"#, lhs = $lhs, rhs = $rhs, op = stringify!($op), ); assert_eq!( $result, rune!($ty => &program), concat!("expected ", stringify!($result), " out of program `{}`"), program ); }} } #[test] fn test_float_ops() { test_float_op!(f64 => 1 + 2 = 3f64); test_float_op!(f64 => 2 - 1 = 1f64); test_float_op!(f64 => 8 / 2 = 4f64); test_float_op!(f64 => 8 * 2 = 16f64); test_float_op!(bool => 1 < 2 = true); test_float_op!(bool => 2 < 2 = false); test_float_op!(bool => 1 <= 1 = true); test_float_op!(bool => 2 <= 1 = false); test_float_op!(bool => 3 > 2 = true); test_float_op!(bool => 2 > 2 = false); test_float_op!(bool => 1 >= 1 = true); test_float_op!(bool => 0 >= 2 = false); }
/*! Totsu ([凸](http://www.decodeunicode.org/en/u+51F8) in Japanese) means convex. <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script> <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script> This crate for Rust provides **convex optimization problems LP/QP/QCQP/SOCP/SDP** that can be solved by [`totsu_core`]. # General usage 1. An optimization problem you want to solve is assumed to be expressed in the standard form of LP, QP, QCQP, SOCP or SDP. Refer to [`ProbLP`], [`ProbQP`], [`ProbQCQP`], [`ProbSOCP`] and [`ProbSDP`] about their mathematical formulations. 1. Choose a [`totsu_core::LinAlgEx`] implementation to use: * [`prelude::FloatGeneric`] - `num::Float`-generic, pure Rust but slow, fewer environment-dependent problems. * [`totsu_f64lapack` crate](https://crates.io/crates/totsu_f64lapack) - `f64`-specific, using BLAS/LAPACK which requires an installed environment. * [`totsu_f32cuda` crate](https://crates.io/crates/totsu_f32cuda) - `f32`-specific, using CUDA/cuBLAS/cuSOLVER which requires an installed environment. 1. Construct your problem with matrices using [`MatBuild`]. 1. Create a [`prelude::Solver`] instance and optionally set its parameters. 1. Feed the problem to the solver and invoke [`prelude::Solver::solve`] to get a resulted solution. # Examples A simple QP problem: \\[ \begin{array}{ll} {\rm minimize} & {(x_0 - (-1))^2 + (x_1 - (-2))^2 \over 2} \\\\ {\rm subject \ to} & 1 - {x_0 \over 2} - {x_1 \over 3} <= 0 \end{array} \\] You will notice that a perpendicular drawn from \\((-1, -2)\\) to the line \\(1 - {x_0 \over 2} - {x_1 \over 3} = 0\\) intersects at point \\((2, 0)\\) which is the optimal solution of the problem. ``` use float_eq::assert_float_eq; use totsu::prelude::*; use totsu::*; //env_logger::init(); // Use any logger crate as `totsu` uses `log` crate. type La = FloatGeneric<f64>; type AMatBuild = MatBuild<La>; type AProbQP = ProbQP<La>; type ASolver = Solver<La>; let n = 2; // x0, x1 let m = 1; let p = 0; // (1/2)(x - a)^2 + const let mut sym_p = AMatBuild::new(MatType::SymPack(n)); sym_p[(0, 0)] = 1.; sym_p[(1, 1)] = 1.; let mut vec_q = AMatBuild::new(MatType::General(n, 1)); vec_q[(0, 0)] = -(-1.); // -a0 vec_q[(1, 0)] = -(-2.); // -a1 // 1 - x0/b0 - x1/b1 <= 0 let mut mat_g = AMatBuild::new(MatType::General(m, n)); mat_g[(0, 0)] = -1. / 2.; // -1/b0 mat_g[(0, 1)] = -1. / 3.; // -1/b1 let mut vec_h = AMatBuild::new(MatType::General(m, 1)); vec_h[(0, 0)] = -1.; let mat_a = AMatBuild::new(MatType::General(p, n)); let vec_b = AMatBuild::new(MatType::General(p, 1)); let s = ASolver::new().par(|p| { p.max_iter = Some(100_000); }); let mut qp = AProbQP::new(sym_p, vec_q, mat_g, vec_h, mat_a, vec_b, s.par.eps_zero); let rslt = s.solve(qp.problem()).unwrap(); assert_float_eq!(rslt.0[0..2], [2., 0.].as_ref(), abs_all <= 1e-3); ``` ## Other examples You can find other [tests](https://github.com/convexbrain/Totsu/tree/master/solver_rust_conic/totsu/tests) of the problems. More practical [examples](https://github.com/convexbrain/Totsu/tree/master/examples) are also available. */ mod matbuild; pub use matbuild::*; // mod problem; pub use problem::*; // pub use totsu_core; /// Prelude pub mod prelude { pub use totsu_core::solver::{Solver, SolverError, SolverParam}; pub use totsu_core::{FloatGeneric, MatType}; }
use core::cell::UnsafeCell; use core::ops::{Deref, DerefMut, Drop}; use crate::bindings; //use crate::println; extern "C" { pub fn spin_lock_init_wrapper(lock: *mut bindings::spinlock_t); pub fn spin_lock_wrapper(lock: *mut bindings::spinlock_t); pub fn spin_unlock_wrapper(lock: *mut bindings::spinlock_t); pub fn mutex_init_wrapper(lock: *mut bindings::mutex); pub fn mutex_lock_wrapper(lock: *mut bindings::mutex); pub fn mutex_unlock_wrapper(lock: *mut bindings::mutex); } pub struct Spinlock<T: ?Sized> { lock: UnsafeCell<bindings::spinlock_t>, data: UnsafeCell<T>, } pub struct SpinlockGuard<'a, T: ?Sized + 'a> { lock: &'a mut bindings::spinlock_t, data: &'a mut T, } unsafe impl<T: ?Sized + Send> Sync for Spinlock<T> {} unsafe impl<T: ?Sized + Send> Send for Spinlock<T> {} impl<T> Spinlock<T> { pub fn new(user_data: T) -> Spinlock<T> { let mut lock = bindings::spinlock_t::default(); unsafe { spin_lock_init_wrapper(&mut lock); } Spinlock { lock: UnsafeCell::new(lock), data: UnsafeCell::new(user_data), } } pub fn lock(&self) -> SpinlockGuard<T> { unsafe { spin_lock_wrapper(self.lock.get()); //println!("Spinlock is locked!"); } SpinlockGuard { lock: unsafe { &mut *self.lock.get() }, data: unsafe { &mut *self.data.get() }, } } } impl<'a, T: ?Sized> Deref for SpinlockGuard<'a, T> { type Target = T; fn deref<'b>(&'b self) -> &'b T { &*self.data } } impl<'a, T: ?Sized> DerefMut for SpinlockGuard<'a, T> { fn deref_mut<'b>(&'b mut self) -> &'b mut T { &mut *self.data } } impl<'a, T: ?Sized> Drop for SpinlockGuard<'a, T> { fn drop(&mut self) { unsafe { spin_unlock_wrapper(self.lock) } //println!("Spinlock is dropped!"); } } pub struct Mutex<T: ?Sized> { lock: UnsafeCell<bindings::mutex>, data: UnsafeCell<T>, } pub struct MutexGuard<'a, T: ?Sized + 'a> { lock: &'a mut bindings::mutex, data: &'a mut T, } unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {} unsafe impl<T: ?Sized + Send> Send for Mutex<T> {} impl<T> Mutex<T> { pub fn new(user_data: T) -> Mutex<T> { let mut lock = bindings::mutex::default(); unsafe { mutex_init_wrapper(&mut lock); } Mutex { lock: UnsafeCell::new(lock), data: UnsafeCell::new(user_data), } } pub fn lock(&self) -> MutexGuard<T> { unsafe { mutex_lock_wrapper(self.lock.get()); //println!("Mutex is locked!"); } MutexGuard { lock: unsafe { &mut *self.lock.get() }, data: unsafe { &mut *self.data.get() }, } } } impl<'a, T: ?Sized> Deref for MutexGuard<'a, T> { type Target = T; fn deref<'b>(&'b self) -> &'b T { &*self.data } } impl<'a, T: ?Sized> DerefMut for MutexGuard<'a, T> { fn deref_mut<'b>(&'b mut self) -> &'b mut T { &mut *self.data } } impl<'a, T: ?Sized> Drop for MutexGuard<'a, T> { fn drop(&mut self) { unsafe { mutex_unlock_wrapper(self.lock) } //println!("Mutex is dropped!"); } } pub fn drop<T>(_x: T) { }
fn main() { // Rust has a lot of neat things you can do with functions: let's go over the basics first fn no_args() {} // Run function with no arguments no_args(); // Calling a function with fixed number of arguments. // adds_one takes a 32-bit signed integer and returns a 32-bit signed integer fn adds_one(num: i32) -> i32 { // the final expression is used as the return value, though `return` may be used for early returns num + 1 } adds_one(1); // Optional arguments // The language itself does not support optional arguments, however, you can take advantage of // Rust's algebraic types for this purpose fn prints_argument(maybe: Option<i32>) { match maybe { Some(num) => println!("{}", num), None => println!("No value given"), }; } prints_argument(Some(3)); prints_argument(None); // You could make this a bit more ergonomic by using Rust's Into trait fn prints_argument_into<I>(maybe: I) where I: Into<Option<i32>> { match maybe.into() { Some(num) => println!("{}", num), None => println!("No value given"), }; } prints_argument_into(3); prints_argument_into(None); // Rust does not support functions with variable numbers of arguments. Macros fill this niche // (println! as used above is a macro for example) // Rust does not support named arguments // We used the no_args function above in a no-statement context // Using a function in an expression context adds_one(1) + adds_one(5); // evaluates to eight // Obtain the return value of a function. let two = adds_one(1); // In Rust there are no real built-in functions (save compiler intrinsics but these must be // manually imported) // In rust there are no such thing as subroutines // In Rust, there are three ways to pass an object to a function each of which have very important // distinctions when it comes to Rust's ownership model and move semantics. We may pass by // value, by immutable reference, or mutable reference. let mut v = vec![1, 2, 3, 4, 5, 6]; // By mutable reference fn add_one_to_first_element(vector: &mut Vec<i32>) { vector[0] += 1; } add_one_to_first_element(&mut v); // By immutable reference fn print_first_element(vector: &Vec<i32>) { println!("{}", vector[0]); } print_first_element(&v); // By value fn consume_vector(vector: Vec<i32>) { // We can do whatever we want to vector here } consume_vector(v); // Due to Rust's move semantics, v is now inaccessible because it was moved into consume_vector // and was then dropped when it went out of scope // Partial application is not possible in rust without wrapping the function in another // function/closure e.g.: fn average(x: f64, y: f64) -> f64 { (x + y) / 2.0 } let average_with_four = |y| average(4.0, y); average_with_four(2.0); }
use crate::be::MinBigEndian; use crate::error::Error; use crate::error::UnsupportedType; use serde::ser::{ SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, }; use serde::{Serialize, Serializer}; use std::fmt::Display; pub fn to_bytes<T: Serialize>(value: &T) -> Result<Vec<u8>, Error> { let mut serializer = RLPSerializer::new(); value.serialize(&mut serializer)?; Ok(serializer.output) } pub struct RLPSerializer { pub output: Vec<u8>, } impl RLPSerializer { fn new() -> RLPSerializer { RLPSerializer { output: vec![] } } } struct RLPSequenceSerializer<'a> { source_serializer: &'a mut RLPSerializer, sequence: Vec<Vec<u8>>, } impl<'a> RLPSequenceSerializer<'a> { fn new(serializer: &'a mut RLPSerializer) -> RLPSequenceSerializer { RLPSequenceSerializer { source_serializer: serializer, sequence: vec![], } } } impl<'a> SerializeSeq for &'a mut RLPSequenceSerializer<'a> { type Ok = (); type Error = crate::error::Error; fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> { self.sequence.push(to_bytes(value)?); Ok(()) } fn end(self) -> Result<Self::Ok, Self::Error> { let total_length = self.sequence.iter().map(|element| element.len()).sum(); if total_length < 56 { self.source_serializer .output .push((192 + total_length) as u8); } else { let mut total_length_be = total_length.to_min_be(); self.source_serializer .output .push((247 + total_length_be.len()) as u8); self.source_serializer.output.append(total_length_be); } self.sequence .iter_mut() .for_each(|element| self.source_serializer.output.append(element)); Ok(()) } } impl<'a> SerializeTuple for &'a mut RLPSequenceSerializer<'a> { type Ok = (); type Error = crate::error::Error; fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> { // TODO ????? (self as dyn SerializeSeq).serialize_element(value) } fn end(self) -> Result<Self::Ok, Self::Error> { // TODO ???? (self as dyn SerializeSeq).end() } } impl<'a> Serializer for &'a mut RLPSerializer { type Ok = (); type Error = crate::error::Error; type SerializeSeq = Self; type SerializeTuple = Self; type SerializeTupleStruct = Self; type SerializeTupleVariant = Self; type SerializeMap = Self; type SerializeStruct = Self; type SerializeStructVariant = Self; fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> { self.serialize_u8(v as u8) } fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> { Err(Error::UnsupportedDataType(UnsupportedType::I8)) } fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> { Err(Error::UnsupportedDataType(UnsupportedType::I16)) } fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> { Err(Error::UnsupportedDataType(UnsupportedType::I32)) } fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> { Err(Error::UnsupportedDataType(UnsupportedType::I64)) } fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> { self.serialize_bytes(v.to_min_be().as_slice()) } fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> { self.serialize_bytes(v.to_min_be().as_slice()) } fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> { self.serialize_bytes(v.to_min_be().as_slice()) } fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> { self.serialize_bytes(v.to_min_be().as_slice()) } fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> { Err(Error::UnsupportedDataType(UnsupportedType::F32)) } fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> { Err(Error::UnsupportedDataType(UnsupportedType::F64)) } fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> { let mut utf8_encoded = [0u8; 4]; self.serialize_str(v.encode_utf8(&mut utf8_encoded)) } fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> { self.serialize_bytes(v.as_bytes()) } fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> { if (v.len() == 1) && (v[0] < 128) { self.output.extend(v); } else if v.len() < 56 { self.output.push((128 + v.len()) as u8); self.output.extend(v); } else { let mut len_be_bytes = v.len().to_min_be(); self.output.push((183 + len_be_bytes.len()) as u8); self.output.append(&mut len_be_bytes); self.output.extend(v); } Ok(()) } fn serialize_none(self) -> Result<Self::Ok, Self::Error> { Err(Error::UnsupportedDataType(UnsupportedType::Option)) } fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<Self::Ok, Self::Error> { Err(Error::UnsupportedDataType(UnsupportedType::Option)) } fn serialize_unit(self) -> Result<Self::Ok, Self::Error> { Err(Error::UnsupportedDataType(UnsupportedType::Unit)) } fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> { Err(Error::UnsupportedDataType(UnsupportedType::UnitStruct)) } fn serialize_unit_variant( self, name: &'static str, variant_index: u32, variant: &'static str, ) -> Result<Self::Ok, Self::Error> { Err(Error::UnsupportedDataType(UnsupportedType::UnitVariant)) } fn serialize_newtype_struct<T: ?Sized + Serialize>( self, name: &'static str, value: &T, ) -> Result<Self::Ok, Self::Error> { Err(Error::UnsupportedDataType(UnsupportedType::NewTypeStruct)) } fn serialize_newtype_variant<T: ?Sized + Serialize>( self, name: &'static str, variant_index: u32, variant: &'static str, value: &T, ) -> Result<Self::Ok, Self::Error> { Err(Error::UnsupportedDataType(UnsupportedType::NewTypeVariant)) } fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> { self.items = Some(vec![]); Ok(self) } fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> { self.items = Some(vec![]); Ok(self) } fn serialize_tuple_struct( self, name: &'static str, len: usize, ) -> Result<Self::SerializeTupleStruct, Self::Error> { Err(Error::UnsupportedDataType(UnsupportedType::TupleStruct)) } fn serialize_tuple_variant( self, name: &'static str, variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeTupleVariant, Self::Error> { Err(Error::UnsupportedDataType(UnsupportedType::TupleVariant)) } fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> { Ok(self) } fn serialize_struct( self, _name: &'static str, _len: usize, ) -> Result<Self::SerializeStruct, Self::Error> { Ok(self) } fn serialize_struct_variant( self, name: &'static str, variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeStructVariant, Self::Error> { Err(Error::UnsupportedDataType(UnsupportedType::StructVariant)) } fn collect_str<T: ?Sized + Display>(self, value: &T) -> Result<Self::Ok, Self::Error> { // TODO unimplemented!() } } impl<'a> SerializeSeq for &'a mut RLPSerializer { type Ok = (); type Error = crate::error::Error; fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> { // TODO: is this optimized? let mut serialized = to_bytes(value)?; self.output.append(&mut serialized); Ok(()) } fn end(self) -> Result<Self::Ok, Self::Error> { // TODO: empty list? if self.output.len() < 56 { self.output.insert(0, (192 + self.output.len()) as u8); } else { // TODO: need to shorten this. let output_len_be = self.output.len().to_be_bytes(); self.output.insert(0, (247 + output_len_be.len()) as u8); // TODO: insert output_len_be at top. } Ok(()) } } impl<'a> SerializeTuple for &'a mut RLPSerializer { type Ok = (); type Error = crate::error::Error; fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> { // TODO: is this optimized? let mut serialized = to_bytes(value)?; self.output.append(&mut serialized); Ok(()) } fn end(self) -> Result<Self::Ok, Self::Error> { // TODO: empty list? if self.output.len() < 56 { self.output.insert(0, (192 + self.output.len()) as u8); } else { // TODO: need to shorten this. let output_len_be = self.output.len().to_be_bytes(); self.output.insert(0, (247 + output_len_be.len()) as u8); // TODO: insert output_len_be at top. } Ok(()) } } impl<'a> SerializeMap for &'a mut RLPSerializer { type Ok = (); type Error = Error; fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<(), Self::Error> { match self.key { None => { self.key = Some(to_bytes(key)?); Ok(()) } Some(_) => Err(Error::CallingSerializeKeyTwice), } } fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> { match self.key { None => Err(Error::CallingSerializeValueWithoutKey), Some(&key) => self.items.push(to_bytes([key, to_bytes(value)])), // TODO: ???? _ => {} } } fn end(self) -> Result<Self::Ok, Self::Error> { // TODO: end here. unimplemented!() } } impl<'a> SerializeStruct for &'a mut RLPSerializer { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>( &mut self, key: &'static str, value: &T, ) -> Result<(), Self::Error> { unimplemented!() } fn end(self) -> Result<Self::Ok, Self::Error> { unimplemented!() } } impl<'a> SerializeTupleStruct for &'a mut RLPSerializer { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> { unimplemented!() } fn end(self) -> Result<Self::Ok, Self::Error> { unimplemented!() } } impl<'a> SerializeTupleVariant for &'a mut RLPSerializer { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> { unimplemented!() } fn end(self) -> Result<Self::Ok, Self::Error> { unimplemented!() } } impl<'a> SerializeStructVariant for &'a mut RLPSerializer { type Ok = (); type Error = Error; fn serialize_field<T: ?Sized + Serialize>( &mut self, key: &'static str, value: &T, ) -> Result<(), Self::Error> { unimplemented!() } fn end(self) -> Result<Self::Ok, Self::Error> { unimplemented!() } }
#[doc = "Register `RCC_MC_APB5ENSETR` reader"] pub type R = crate::R<RCC_MC_APB5ENSETR_SPEC>; #[doc = "Register `RCC_MC_APB5ENSETR` writer"] pub type W = crate::W<RCC_MC_APB5ENSETR_SPEC>; #[doc = "Field `SPI6EN` reader - SPI6EN"] pub type SPI6EN_R = crate::BitReader; #[doc = "Field `SPI6EN` writer - SPI6EN"] pub type SPI6EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `I2C4EN` reader - I2C4EN"] pub type I2C4EN_R = crate::BitReader; #[doc = "Field `I2C4EN` writer - I2C4EN"] pub type I2C4EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `I2C6EN` reader - I2C6EN"] pub type I2C6EN_R = crate::BitReader; #[doc = "Field `I2C6EN` writer - I2C6EN"] pub type I2C6EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `USART1EN` reader - USART1EN"] pub type USART1EN_R = crate::BitReader; #[doc = "Field `USART1EN` writer - USART1EN"] pub type USART1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RTCAPBEN` reader - RTCAPBEN"] pub type RTCAPBEN_R = crate::BitReader; #[doc = "Field `RTCAPBEN` writer - RTCAPBEN"] pub type RTCAPBEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TZC1EN` reader - TZC1EN"] pub type TZC1EN_R = crate::BitReader; #[doc = "Field `TZC1EN` writer - TZC1EN"] pub type TZC1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TZC2EN` reader - TZC2EN"] pub type TZC2EN_R = crate::BitReader; #[doc = "Field `TZC2EN` writer - TZC2EN"] pub type TZC2EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TZPCEN` reader - TZPCEN"] pub type TZPCEN_R = crate::BitReader; #[doc = "Field `TZPCEN` writer - TZPCEN"] pub type TZPCEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `BSECEN` reader - BSECEN"] pub type BSECEN_R = crate::BitReader; #[doc = "Field `BSECEN` writer - BSECEN"] pub type BSECEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `STGENEN` reader - STGENEN"] pub type STGENEN_R = crate::BitReader; #[doc = "Field `STGENEN` writer - STGENEN"] pub type STGENEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - SPI6EN"] #[inline(always)] pub fn spi6en(&self) -> SPI6EN_R { SPI6EN_R::new((self.bits & 1) != 0) } #[doc = "Bit 2 - I2C4EN"] #[inline(always)] pub fn i2c4en(&self) -> I2C4EN_R { I2C4EN_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - I2C6EN"] #[inline(always)] pub fn i2c6en(&self) -> I2C6EN_R { I2C6EN_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - USART1EN"] #[inline(always)] pub fn usart1en(&self) -> USART1EN_R { USART1EN_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 8 - RTCAPBEN"] #[inline(always)] pub fn rtcapben(&self) -> RTCAPBEN_R { RTCAPBEN_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 11 - TZC1EN"] #[inline(always)] pub fn tzc1en(&self) -> TZC1EN_R { TZC1EN_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - TZC2EN"] #[inline(always)] pub fn tzc2en(&self) -> TZC2EN_R { TZC2EN_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - TZPCEN"] #[inline(always)] pub fn tzpcen(&self) -> TZPCEN_R { TZPCEN_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 16 - BSECEN"] #[inline(always)] pub fn bsecen(&self) -> BSECEN_R { BSECEN_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 20 - STGENEN"] #[inline(always)] pub fn stgenen(&self) -> STGENEN_R { STGENEN_R::new(((self.bits >> 20) & 1) != 0) } } impl W { #[doc = "Bit 0 - SPI6EN"] #[inline(always)] #[must_use] pub fn spi6en(&mut self) -> SPI6EN_W<RCC_MC_APB5ENSETR_SPEC, 0> { SPI6EN_W::new(self) } #[doc = "Bit 2 - I2C4EN"] #[inline(always)] #[must_use] pub fn i2c4en(&mut self) -> I2C4EN_W<RCC_MC_APB5ENSETR_SPEC, 2> { I2C4EN_W::new(self) } #[doc = "Bit 3 - I2C6EN"] #[inline(always)] #[must_use] pub fn i2c6en(&mut self) -> I2C6EN_W<RCC_MC_APB5ENSETR_SPEC, 3> { I2C6EN_W::new(self) } #[doc = "Bit 4 - USART1EN"] #[inline(always)] #[must_use] pub fn usart1en(&mut self) -> USART1EN_W<RCC_MC_APB5ENSETR_SPEC, 4> { USART1EN_W::new(self) } #[doc = "Bit 8 - RTCAPBEN"] #[inline(always)] #[must_use] pub fn rtcapben(&mut self) -> RTCAPBEN_W<RCC_MC_APB5ENSETR_SPEC, 8> { RTCAPBEN_W::new(self) } #[doc = "Bit 11 - TZC1EN"] #[inline(always)] #[must_use] pub fn tzc1en(&mut self) -> TZC1EN_W<RCC_MC_APB5ENSETR_SPEC, 11> { TZC1EN_W::new(self) } #[doc = "Bit 12 - TZC2EN"] #[inline(always)] #[must_use] pub fn tzc2en(&mut self) -> TZC2EN_W<RCC_MC_APB5ENSETR_SPEC, 12> { TZC2EN_W::new(self) } #[doc = "Bit 13 - TZPCEN"] #[inline(always)] #[must_use] pub fn tzpcen(&mut self) -> TZPCEN_W<RCC_MC_APB5ENSETR_SPEC, 13> { TZPCEN_W::new(self) } #[doc = "Bit 16 - BSECEN"] #[inline(always)] #[must_use] pub fn bsecen(&mut self) -> BSECEN_W<RCC_MC_APB5ENSETR_SPEC, 16> { BSECEN_W::new(self) } #[doc = "Bit 20 - STGENEN"] #[inline(always)] #[must_use] pub fn stgenen(&mut self) -> STGENEN_W<RCC_MC_APB5ENSETR_SPEC, 20> { STGENEN_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "This register is used to set the peripheral clock enable bit\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rcc_mc_apb5ensetr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rcc_mc_apb5ensetr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct RCC_MC_APB5ENSETR_SPEC; impl crate::RegisterSpec for RCC_MC_APB5ENSETR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`rcc_mc_apb5ensetr::R`](R) reader structure"] impl crate::Readable for RCC_MC_APB5ENSETR_SPEC {} #[doc = "`write(|w| ..)` method takes [`rcc_mc_apb5ensetr::W`](W) writer structure"] impl crate::Writable for RCC_MC_APB5ENSETR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets RCC_MC_APB5ENSETR to value 0"] impl crate::Resettable for RCC_MC_APB5ENSETR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::fmt::Debug; use aoc_lib::Solver; #[derive(Debug, Default)] pub struct Day10 { cycles: Vec<(i32, i32, i32)>, } #[derive(Clone, Default)] struct Crt { rows: Vec<PixelType>, current_sprite_pos: usize, } #[derive(Clone, Copy)] enum PixelType { Lit, Dark, } impl Solver for Day10 { fn day() -> u8 { 10 } fn solution_part1(input: aoc_lib::Input) -> Option<Self::OutputPart1> { let mut d = Day10::default(); d.load_instructions(input.lines.iter().map(Instruction::from), |_, _| {}); let s = [20, 60, 100, 140, 180, 220] .map(|i| (i, d.cycles[i - 1])) .iter() .map(|(n, (_, during, _))| *n as i32 * during) .sum::<i32>(); Some(s) } fn solution_part2(input: aoc_lib::Input) -> Option<Self::OutputPart2> { let mut crt = Crt::default(); let mut d = Day10::default(); d.load_instructions(input.lines.iter().map(Instruction::from), |x, y| { crt.handle_cyle(x, y); }); println!("{:?}", crt.clone()); Some(()) } type OutputPart1 = i32; type OutputPart2 = (); } impl From<PixelType> for usize { fn from(val: PixelType) -> Self { match val { PixelType::Lit => 1, PixelType::Dark => 0, } } } impl From<PixelType> for String { fn from(p: PixelType) -> Self { match p { PixelType::Lit => "#".to_string(), PixelType::Dark => ".".to_string(), } } } impl Crt { fn handle_cyle(&mut self, register_val_after: i32, register_val_during: i32) { let crt_draw_pos = self.rows.iter().enumerate().last().map(|(index, _)| index); let sprite_pos = [ (register_val_during as usize % 40).saturating_sub(1), register_val_during as usize % 40, register_val_during as usize % 40 + 1, ]; let next_crt_pos = crt_draw_pos.map(|p| p % 40 + 1).unwrap_or(0); let should_lit = sprite_pos.contains(&next_crt_pos); if should_lit { self.rows.push(PixelType::Lit); } else { self.rows.push(PixelType::Dark) } self.current_sprite_pos = register_val_after as usize; } } impl Debug for Crt { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.rows .chunks(40) .map(|r| r.iter().map(|x| String::from(*x))) .for_each(|x| { f.write_str(&x.collect::<Vec<_>>().join(" ")).expect(""); f.write_str("\n").expect("") }); Ok(()) } } impl Day10 { fn load_instructions<F, G>(&mut self, instructions: F, mut cycle_callback: G) -> &mut Self where F: Iterator<Item = Instruction>, G: FnMut(i32, i32), { instructions.for_each(|instr| match instr { Instruction::Noop => { if self.cycles.is_empty() { self.cycles.push((0, 1, 1)); cycle_callback(1, 0); } else { let (_, _, after) = self .cycles .last() .expect("expected some value in the register"); let after = *after; self.cycles.push((after, after, after)); cycle_callback(after, after); } } Instruction::AddX(a) => { if self.cycles.is_empty() { self.cycles.push((0, 1, 1)); cycle_callback(1, 0); self.cycles.push((1, 1, 1 + a)); cycle_callback(1 + a, 1); } else { let cycles_1 = self.cycles.clone(); let (_, _, after) = cycles_1 .last() .expect("expected some value in the register"); self.cycles.push((*after, *after, *after)); cycle_callback(*after, *after); self.cycles.push((*after, *after, after + a)); cycle_callback(*after + a, *after); } } }); self } } #[derive(Debug)] enum Instruction { AddX(i32), Noop, } impl From<&String> for Instruction { fn from(s: &String) -> Self { let xs = s.split(' ').collect::<Vec<_>>(); match *xs.first().expect("expecting a string") { "addx" => Self::AddX( xs.get(1) .map(|x| x.parse::<i32>().expect("expecting a number")) .expect("not possible"), ), "noop" => Self::Noop, _ => panic!("not possible"), } } }
#[derive(Debug, PartialEq, Clone, Copy)] pub enum Token { String, Number, Name, /// default token None, Eof, /// used for errors SC(char), LeftParen, RightParen, LeftSquare, RightSquare, LeftBrace, RightBrace, Colon, Line, Dot, And, Or, Equal, Eq, Neq, Gt, Lt, Ge, Le, Plus, Dash, Star, Slash, Percent, Bang, Semi, Comma, Let, If, Else, Fn, For, Return, While, True, False, Nil }
use async_executor::Executor; use async_std::sync::Mutex; use log::*; use std::net::SocketAddr; use std::sync::{Arc, Weak}; use crate::net::error::{NetError, NetResult}; use crate::net::protocols::{ProtocolAddress, ProtocolPing}; use crate::net::sessions::Session; use crate::net::{ChannelPtr, Connector, P2p}; use crate::system::{StoppableTask, StoppableTaskPtr}; /// Defines outbound connections session. pub struct OutboundSession { p2p: Weak<P2p>, connect_slots: Mutex<Vec<StoppableTaskPtr>>, } impl OutboundSession { /// Create a new outbound session. pub fn new(p2p: Weak<P2p>) -> Arc<Self> { Arc::new(Self { p2p, connect_slots: Mutex::new(Vec::new()), }) } /// Start the outbound session. Runs the channel connect loop. pub async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> NetResult<()> { let slots_count = self.p2p().settings().outbound_connections; info!("Starting {} outbound connection slots.", slots_count); // Activate mutex lock on connection slots. let mut connect_slots = self.connect_slots.lock().await; for i in 0..slots_count { let task = StoppableTask::new(); task.clone().start( self.clone().channel_connect_loop(i, executor.clone()), // Ignore stop handler |_| async {}, NetError::ServiceStopped, executor.clone(), ); connect_slots.push(task); } Ok(()) } /// Stop the outbound session. pub async fn stop(&self) { let connect_slots = &*self.connect_slots.lock().await; for slot in connect_slots { slot.stop().await; } } /// Start making outbound connections. Creates a connector object, then /// starts a connect loop. Loads a valid address then tries to connect. /// Once connected, registers the channel, removes it from the list of /// pending channels, and starts sending messages across the channel. /// Otherwise returns a network error. pub async fn channel_connect_loop( self: Arc<Self>, slot_number: u32, executor: Arc<Executor<'_>>, ) -> NetResult<()> { let connector = Connector::new(self.p2p().settings().clone()); loop { let addr = self.load_address(slot_number).await?; info!("#{} connecting to outbound [{}]", slot_number, addr); match connector.connect(addr).await { Ok(channel) => { // Blacklist goes here info!("#{} connected to outbound [{}]", slot_number, addr); let stop_sub = channel.subscribe_stop().await; self.clone() .register_channel(channel.clone(), executor.clone()) .await?; // Channel is now connected but not yet setup // Remove pending lock since register_channel will add the channel to p2p self.p2p().remove_pending(&addr).await; self.clone() .attach_protocols(channel, executor.clone()) .await?; // Wait for channel to close stop_sub.receive().await; } Err(err) => { info!("Unable to connect to outbound [{}]: {}", addr, err); } } } } /// Loops through host addresses to find a outbound address that we can /// connect to. Checks whether address is valid by making sure it isn't /// our own inbound address, then checks whether it is already connected /// (exists) or connecting (pending). Keeps looping until address is /// found that passes all checks. async fn load_address(&self, slot_number: u32) -> NetResult<SocketAddr> { let p2p = self.p2p(); let hosts = p2p.hosts(); let inbound_addr = p2p.settings().inbound; loop { let addr = hosts.load_single().await; if addr.is_none() { error!( "Hosts address pool is empty. Closing connect slot #{}", slot_number ); return Err(NetError::ServiceStopped); } let addr = addr.unwrap(); if Self::is_self_inbound(&addr, &inbound_addr) { continue; } if p2p.exists(&addr).await { continue; } // Obtain a lock on this address to prevent duplicate connections if !p2p.add_pending(addr).await { continue; } return Ok(addr); } } /// Checks whether an address is our own inbound address to avoid connecting /// to ourselves. fn is_self_inbound(addr: &SocketAddr, inbound_addr: &Option<SocketAddr>) -> bool { match inbound_addr { Some(inbound_addr) => inbound_addr == addr, // No inbound listening address configured None => false, } } /// Starts sending keep-alive and address messages across the channels. async fn attach_protocols( self: Arc<Self>, channel: ChannelPtr, executor: Arc<Executor<'_>>, ) -> NetResult<()> { let settings = self.p2p().settings().clone(); let hosts = self.p2p().hosts().clone(); let protocol_ping = ProtocolPing::new(channel.clone(), settings.clone()); let protocol_addr = ProtocolAddress::new(channel, hosts).await; protocol_ping.start(executor.clone()).await; protocol_addr.start(executor).await; Ok(()) } } impl Session for OutboundSession { fn p2p(&self) -> Arc<P2p> { self.p2p.upgrade().unwrap() } }
extern crate aoc2017; use aoc2017::days::day12; fn main() { let input = aoc2017::read_trim("input/day12.txt").unwrap(); let value1 = day12::part1::parse(&input); let value2 = day12::part2::parse(&input); println!("Day 12 part 1 value: {}", value1); println!("Day 12 part 2 value: {}", value2); }
extern crate std; extern crate term; enum Color { Green, Red, Yellow, Blue, Blank } fn _ask(question: &str, col: Color) -> String { _say(question, col); let mut s = std::io::stdio::stdin().read_line().unwrap(); s.pop(); // XXX terrible terrible s } pub fn ask(question: &str) -> String { _ask(question, Blank) } pub fn ask_red(question: &str) -> String { _ask(question, Red) } fn _say (s: &str, col: Color) { let mut t = term::stdout().unwrap(); match col { Green => { t.fg(term::color::GREEN).unwrap(); } Red => { t.fg(term::color::RED).unwrap(); } Yellow => { t.fg(term::color::BRIGHT_YELLOW).unwrap(); } Blue => { t.fg(term::color::BRIGHT_BLUE).unwrap(); } Blank => {} } (writeln!(t, "{}", s)).unwrap(); t.reset().unwrap(); } pub fn say (s: &str) { _say(s, Blank) } pub fn say_red (s: &str) { _say(s, Red) } pub fn say_green (s: &str) { _say(s, Green) } pub fn say_yellow (s: &str) { _say(s, Yellow) } pub fn say_blue (s: &str) { _say(s, Blue) }
use super::{Pages, Pagination}; use crate::{embeds::MostPlayedCommonEmbed, BotResult}; use hashbrown::HashMap; use rosu_v2::prelude::{MostPlayedMap, Username}; use smallvec::SmallVec; use twilight_model::channel::Message; pub struct MostPlayedCommonPagination { msg: Message, pages: Pages, names: Vec<Username>, users_count: SmallVec<[HashMap<u32, usize>; 3]>, maps: Vec<MostPlayedMap>, } impl MostPlayedCommonPagination { pub fn new( msg: Message, names: Vec<Username>, users_count: SmallVec<[HashMap<u32, usize>; 3]>, maps: Vec<MostPlayedMap>, ) -> Self { Self { pages: Pages::new(10, maps.len()), msg, names, users_count, maps, } } } #[async_trait] impl Pagination for MostPlayedCommonPagination { type PageData = MostPlayedCommonEmbed; fn msg(&self) -> &Message { &self.msg } fn pages(&self) -> Pages { self.pages } fn pages_mut(&mut self) -> &mut Pages { &mut self.pages } fn single_step(&self) -> usize { self.pages.per_page } async fn build_page(&mut self) -> BotResult<Self::PageData> { Ok(MostPlayedCommonEmbed::new( &self.names, &self.maps[self.pages.index..(self.pages.index + 10).min(self.maps.len())], &self.users_count, self.pages.index, )) } }