text
stringlengths
8
4.13M
mods! { pub boxblock::Boxblock; pub canvas_texture::CanvasTexture; pub character::Character; pub chat_channel::ChatChannel; pub chat_message::ChatMessage; pub chat::Chat; pub craftboard::Craftboard; pub layer_group::LayerGroup; pub property::Property; pub scene::Scene; pub table::Table; pub terran::Terran; pub terran_texture::TerranTexture; pub textboard::Textboard; pub world::World; }
fn test_val(input: i32) -> bool { let get_digit = |place: u32| -> i32 { (input / 10i32.pow(place)) % 10 }; let mut highest = 0i32; let mut counts = [0; 10]; for n in (0..6).rev() { let digit = get_digit(n); if digit < highest { return false; } highest = digit; counts[digit as usize] += 1; } counts.iter().any(|&n| n == 2) } fn main() { let total = (240920..=789857).filter(|&n| test_val(n)).count(); println!("Found {} in range that meet criteria.", total); }
mod facts; use datafrog::{Iteration, Relation, RelationLeaper, Variable}; use facts::{Definition, Point}; fn main() { let mut iteration = Iteration::new(); let edge: Relation<(Point, Point)> = vec![ (Point::from(1), Point::from(2)), (Point::from(2), Point::from(3)), (Point::from(6), Point::from(3)), (Point::from(3), Point::from(4)), (Point::from(4), Point::from(5)), (Point::from(4), Point::from(7)), (Point::from(5), Point::from(6)), (Point::from(6), Point::from(8)), (Point::from(7), Point::from(8)), ] .iter() .collect(); // definition at Point let def: Relation<(Point, Definition)> = vec![ (Point::from(1), Definition::from(1)), (Point::from(2), Definition::from(2)), (Point::from(3), Definition::from(3)), (Point::from(4), Definition::from(4)), (Point::from(5), Definition::from(5)), (Point::from(6), Definition::from(6)), (Point::from(7), Definition::from(7)), (Point::from(8), Definition::from(8)), ] .iter() .collect(); let mut v = vec![ // x (Definition::from(1), Definition::from(5)), (Definition::from(1), Definition::from(7)), (Definition::from(5), Definition::from(7)), // y (Definition::from(2), Definition::from(4)), // z (Definition::from(6), Definition::from(8)), ]; let mut v_rev = v.iter().map(|&(u, v)| (v, u)).collect(); v.append(&mut v_rev); let conflict: Relation<(Definition, Definition)> = v.iter().collect(); let reach = iteration.variable::<(Point, Definition)>("reach"); reach.insert(def.clone()); // kill(d2,p):- // def(p,d1), // conflict(d1,d2). let kill: Relation<(Definition, Point)> = Relation::from_leapjoin( &def, conflict.extend_with(|&(_p, d1)| d1), |&(p, _d1), &d2| (d2, p), ); while iteration.changed() { // reach(point2, definition) :- // reach(point1, definition), // edge(point1, point2), // not kill(definition, point2). // reach.from_leapjoin( &reach, ( edge.extend_with(|&(point1, definition)| point1), kill.extend_anti(|&(point1, definition)| definition), ), |&(point1, definition), &point2| (point2, definition), ); } let x = reach.complete(); assert_eq!(x.elements.len(),31); println!("{:?}", x.elements); }
use std::rc::Rc; #[derive(Clone, Debug, Eq, PartialEq)] pub enum List<Value> { Nil, Cons(Value, Rc<List<Value>>), } impl<Value: Clone> List<Value> { pub fn empty() -> List<Value> { List::Nil } pub fn is_empty(&self) -> bool { match self { List::Nil => true, _ => false, } } pub fn cons(&self, x: Value) -> List<Value> { List::Cons(x, Rc::new(self.clone())) } pub fn head(&self) -> Option<Value> { match self { List::Cons(h, _) => Some(h.clone()), List::Nil => None, } } pub fn tail(&self) -> List<Value> { match self { List::Nil => List::Nil, List::Cons(_, t) => (**t).clone(), } } } #[test] fn list() { // let l1: List<usize> = Stack::new(); // let l2 = l1.cons(3).cons(2).cons(1); // let l3 = l1.cons(5).cons(4); // // assert!(l1.is_empty()); // assert!(!l2.is_empty()); // assert_eq!( // l2, // Cons(1, Rc::new(Cons(2, Rc::new(Cons(3, Rc::new(Nil)))))) // ); // assert_eq!(l2.head(), 1); // assert_eq!(l2.tail(), Cons(2, Rc::new(Cons(3, Rc::new(Nil))))); // // assert_eq!(l1.append(&l2), l2); // assert_eq!(l2.append(&l1), l2); // // assert_eq!( // l2.append(&l3), // Cons( // 1, // Rc::new(Cons( // 2, // Rc::new(Cons(3, Rc::new(Cons(4, Rc::new(Cons(5, Rc::new(Nil))))))) // )) // ) // ); // // assert_eq!( // l3.append(&l2), // Cons( // 4, // Rc::new(Cons( // 5, // Rc::new(Cons(1, Rc::new(Cons(2, Rc::new(Cons(3, Rc::new(Nil))))))) // )) // ) // ); // // assert_eq!(l3.update(0, 0), Cons(0, Rc::new(Cons(5, Rc::new(Nil))))); // // assert_eq!(l3.update(1, 0), Cons(4, Rc::new(Cons(0, Rc::new(Nil))))); }
use crate::microvm::memory::address::AddressType; pub mod settings; pub mod flags; pub mod regs; pub mod core; pub mod alu; pub mod address; pub mod counter; pub mod port; pub mod decoder; pub mod instructions; pub mod pipeline;
#[doc = "Register `GICD_ISPENDR2` reader"] pub type R = crate::R<GICD_ISPENDR2_SPEC>; #[doc = "Register `GICD_ISPENDR2` writer"] pub type W = crate::W<GICD_ISPENDR2_SPEC>; #[doc = "Field `ISPENDR2` reader - ISPENDR2"] pub type ISPENDR2_R = crate::FieldReader<u32>; #[doc = "Field `ISPENDR2` writer - ISPENDR2"] pub type ISPENDR2_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 32, O, u32>; impl R { #[doc = "Bits 0:31 - ISPENDR2"] #[inline(always)] pub fn ispendr2(&self) -> ISPENDR2_R { ISPENDR2_R::new(self.bits) } } impl W { #[doc = "Bits 0:31 - ISPENDR2"] #[inline(always)] #[must_use] pub fn ispendr2(&mut self) -> ISPENDR2_W<GICD_ISPENDR2_SPEC, 0> { ISPENDR2_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 = "For interrupts ID\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicd_ispendr2::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 [`gicd_ispendr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct GICD_ISPENDR2_SPEC; impl crate::RegisterSpec for GICD_ISPENDR2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`gicd_ispendr2::R`](R) reader structure"] impl crate::Readable for GICD_ISPENDR2_SPEC {} #[doc = "`write(|w| ..)` method takes [`gicd_ispendr2::W`](W) writer structure"] impl crate::Writable for GICD_ISPENDR2_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets GICD_ISPENDR2 to value 0"] impl crate::Resettable for GICD_ISPENDR2_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::io::Read; use std::fs::File; use std::io::{BufReader, Result}; fn difference(puzzle_input:String) -> u32 { let mut total = 0; puzzle_input.lines().fold(0, |acc, line| { let mut values:Vec<u32> = line.split_whitespace().map(|number_string|{ number_string.parse::<u32>().expect("Unable to parse")}).collect(); values.sort(); let largest_value = values.last().unwrap(); let smallest_value = values.first().unwrap(); let diff = largest_value - smallest_value; acc + diff }) } fn main(){ let mut file = File::open("inputday2.txt") .expect("Unable to open file."); let mut puzzle_input = String::new(); file.read_to_string(&mut puzzle_input) .expect("Unable to read the file"); println!("{}", difference(puzzle_input)); }
pub mod macros; pub mod builder; pub mod factory;
use std::collections::HashMap; use serde::Deserialize; pub type JsonValue = serde_json::Value; pub type JsonObject = serde_json::Map<String, JsonValue>; #[derive(Clone, Debug, Deserialize)] pub struct Payload { pub message_id: i32, pub sent_by_device_id: String, pub command: JsonObject, } #[derive(Clone, Debug, Deserialize)] pub struct Request { #[serde(default)] pub headers: HashMap<String, String>, pub message_ident: String, pub key: String, pub payload: Payload, } #[derive(Clone, Debug, Deserialize)] pub struct Message { #[serde(default)] pub headers: HashMap<String, String>, pub method: Option<String>, #[serde(default)] pub payloads: Vec<JsonValue>, pub uri: String, } #[derive(Clone, Debug, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub(super) enum MessageOrRequest { Message(Message), Request(Request), }
use std::cmp::{min, max}; use std::collections::HashMap; use super::types::SiteId; #[derive(Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Map { pub sites: Vec<SiteId>, pub rivers: Vec<River>, pub mines: Vec<SiteId>, } #[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)] pub struct River { pub source: SiteId, pub target: SiteId, } impl River { pub fn new(source: SiteId, target: SiteId) -> River { River { source: min(source, target), target: max(source, target), } } } #[derive(Default)] pub struct RiversIndex<T>(HashMap<River, T>); impl<T> RiversIndex<T> { pub fn from_hash_map(map: HashMap<River, T>) -> RiversIndex<T> { RiversIndex(map) } } use std::ops::{Deref, DerefMut}; impl<T> Deref for RiversIndex<T> { type Target = HashMap<River, T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> DerefMut for RiversIndex<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } use serde::{ser, de}; impl<T> ser::Serialize for RiversIndex<T> where T: ser::Serialize { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer { let vec: Vec<_> = self.iter().collect(); vec.serialize(serializer) } } impl<'de, T> de::Deserialize<'de> for RiversIndex<T> where T: de::Deserialize<'de> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: de::Deserializer<'de> { let vec: Vec<(River, T)> = de::Deserialize::deserialize(deserializer)?; Ok(RiversIndex(vec.into_iter().collect())) } }
use serde::{Serialize, Deserialize}; use cubik::player::PlayerControlMessage; #[derive(Serialize, Deserialize)] pub enum AppMessage { Chat { text: String, sender: Option<u8> }, PlayerChange { player_id: u8, msg: PlayerControlMessage } }
#![allow(dead_code)] use Stmt::*; use Expr::*; #[derive(Debug, Clone)] struct Ast(Vec<Stmt>); #[derive(Debug, Clone)] enum Stmt { SubStmt(String, Expr), Print(Vec<Expr>), Block(Vec<Stmt>), } #[derive(Debug, Clone)] enum Expr { Str(String), Num(isize), Var(String), } use std::ops::Drop; struct Scope<'a>(&'a mut Interpreter); impl <'a> Scope<'a> { fn new(interpreter: &'a mut Interpreter) -> Self { interpreter.in_scope(); Scope(interpreter) } } impl <'a> Drop for Scope<'a> { fn drop(&mut self) { self.0.out_scope(); } } use std::ops::{Deref, DerefMut}; impl <'a> Deref for Scope<'a> { type Target = Interpreter; fn deref(&self) -> &Interpreter { self.0 } } impl <'a> DerefMut for Scope<'a> { fn deref_mut(&mut self) -> &mut Interpreter { self.0 } } use std::collections::HashMap; struct Interpreter { symbol_tables: Vec<HashMap<String, Expr>>, pos: usize, } impl Interpreter { pub fn new() -> Self { Interpreter { symbol_tables: Vec::new(), pos: 0 } } fn in_scope(&mut self) { let pos = self.pos; if self.symbol_tables.len() <= pos { self.symbol_tables.push(HashMap::new()); } else { self.symbol_tables[pos-1].clear(); } self.pos += 1; } fn out_scope(&mut self) { self.pos -= 1; } fn add_symbol(&mut self, name: String, expr: Expr) { let pos = self.pos - 1; self.symbol_tables[pos].insert(name, expr); } fn find_symbol(&self, name: &str) -> Expr { let pos = self.pos; for table in self.symbol_tables[0..pos].iter().rev() { if let Some(e) = table.get(name) { return e.clone() } } panic!("reference to unknown variable") } fn run(&mut self, ast: Ast) { let mut scope = Scope::new(self); // self.in_scope(); for stmt in ast.0 { // self.run_stmt(stmt); scope.run_stmt(stmt); } // self.out_scope(); // scope will be dropped and out_scope() will be called. } fn run_stmt(&mut self, stmt: Stmt) { // TODO match stmt { SubStmt(name, expr) => { let evaled_expr = self.eval(expr); self.add_symbol(name, evaled_expr); }, Print(exprs) => { for expr in exprs { self.print_expr(expr); } println!(""); }, Block(stmts) => { let mut scope = Scope::new(self); // self.in_scope(); for s in stmts { // self.run_stmt(s); scope.run_stmt(s); } // self.out_scope(); }, } } fn eval(&self, expr: Expr) -> Expr { match expr { Var(name) => self.find_symbol(&name), e @ Str(_) => e, e @ Num(_) => e, } } fn print_expr(&self, expr: Expr) { match self.eval(expr) { Str(ref s) => print!("{}", s), Num(ref n) => print!("{}", n), Var(_) => panic!("reference to unknown variable"), } } } fn main() { // input code // x = 1 // y = 2 // println("x = ", x) // println("y = ", y) // println("--") // { // x = 3 // println("x = ", x) // println("y = ", y) // } // println("--") // println("x = ", x) // println("y = ", y) let line1 = SubStmt("x".to_string(), Num(1)); let line2 = SubStmt("y".to_string(), Num(2)); let line3 = Print(vec![Str("x = ".to_string()), Var("x".to_string())]); let line4 = Print(vec![Str("y = ".to_string()), Var("y".to_string())]); let line5 = Print(vec![Str("--".to_string())]); let line6 = Block(vec![ SubStmt("x".to_string(), Num(3)), Print(vec![Str("x = ".to_string()), Var("x".to_string())]), Print(vec![Str("y = ".to_string()), Var("y".to_string())]), ]); let line7 = Print(vec![Str("--".to_string())]); let line8 = Print(vec![Str("x = ".to_string()), Var("x".to_string())]); let line9 = Print(vec![Str("y = ".to_string()), Var("y".to_string())]); let ast = Ast(vec![line1, line2, line3, line4, line5, line6, line7, line8, line9]); let mut interpreter = Interpreter::new(); interpreter.run(ast); }
use serde::de; /// Serializes a vector of bytes as a base64 encoded string. pub fn serialize_base64_str<S>(val: &[u8], serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.serialize_str(&base64::encode(val)) } /// Deserializes a base64 encoded string as a vector of bytes. pub fn deserialize_base64_str<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error> where D: serde::Deserializer<'de>, { struct Base64Visitor; impl<'de> de::Visitor<'de> for Base64Visitor { type Value = Vec<u8>; fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(formatter, "base64 ASCII text") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: de::Error, { base64::decode(v).map_err(de::Error::custom) } } deserializer.deserialize_str(Base64Visitor) }
mod physics; mod drone; mod beam; mod settings; mod info_panel; use rapier3d; use dotrix::prelude::*; use dotrix::{ Assets, Camera, CubeMap, Color, Input, World, Pipeline, State, egui, overlay, sky::{ skybox, SkyBox, }, pbr::{ self, Light, }, input::{ ActionMapper, Button, KeyCode, Mapper, }, camera, math::{ Point3, Vec3 }, ecs::{ Entity, }, }; // States struct Pause { handled: bool, } struct Main {} struct Initialization {} // Services pub struct ToExile { pub entity_list: Vec<Entity>, } impl Default for ToExile { fn default() -> Self { Self { entity_list: Vec::new(), } } } fn main() { Dotrix::application("drone-target") .with(System::from(startup)) .with(System::from(settings::startup)) .with(System::from(settings::init).with(State::on::<Initialization>())) // init_level should be called the last as it pops init state .with(System::from(init_level).with(State::on::<Initialization>())) .with(System::from(settings::ui_update).with(State::off::<Pause>())) .with(System::from(settings::pause_menu).with(State::on::<Pause>())) .with(System::from(camera::control).with(State::on::<Main>())) .with(System::from(physics::step).with(State::on::<Main>())) .with(System::from(drone::control).with(State::on::<Main>())) .with(System::from(beam::gravity).with(State::on::<Main>())) .with(System::from(drone::exile)) .with(System::from(exile)) .with(System::from(info_panel::update)) .with(Service::from(rapier3d::dynamics::RigidBodySet::new())) .with(Service::from(rapier3d::geometry::ColliderSet::new())) .with(Service::from(rapier3d::dynamics::JointSet::new())) .with(Service::from(rapier3d::geometry::BroadPhase::new())) .with(Service::from(rapier3d::geometry::NarrowPhase::new())) .with(Service::from(rapier3d::dynamics::CCDSolver::new())) .with(Service::from(settings::Settings::default())) .with(Service::from(ToExile::default())) .with(skybox::extension) .with(pbr::extension) .with(overlay::extension) .with(egui::extension) .run(); } fn startup( mut state: Mut<State>, mut world: Mut<World>, mut assets: Mut<Assets>, mut bodies: Mut<rapier3d::dynamics::RigidBodySet>, mut colliders: Mut<rapier3d::geometry::ColliderSet>, mut input: Mut<Input>, ) { input.set_mapper(Box::new(Mapper::<Action>::new())); load_assets(&mut assets); init_controls(&mut input); // Spawn skybox world.spawn(Some(( SkyBox { view_range: 500.0, ..Default::default() }, CubeMap { right: assets.register("skybox_right"), left: assets.register("skybox_left"), top: assets.register("skybox_top"), bottom: assets.register("skybox_bottom"), back: assets.register("skybox_back"), front: assets.register("skybox_front"), ..Default::default() }, Pipeline::default() ))); beam::spawn( &mut world, &mut assets, &mut bodies, &mut colliders, Point3::new(0.0, 0.0, 0.0), ); init_light(&mut world); state.push(Initialization {}); } fn init_level( mut state: Mut<State>, mut world: Mut<World>, mut assets: Mut<Assets>, mut camera: Mut<Camera>, mut bodies: Mut<rapier3d::dynamics::RigidBodySet>, mut colliders: Mut<rapier3d::geometry::ColliderSet>, mut to_exile: Mut<ToExile>, ) { // despawn all drones let query = world.query::<( &Entity, &drone::Stats )>(); for (entity, _) in query { to_exile.entity_list.push(*entity); } init_camera(&mut camera); init_drones(&mut world, &mut assets, &mut bodies, &mut colliders); //Clear all states while state.pop_any().is_some() {}; state.push(Main {}); } fn init_camera(camera: &mut Camera) { camera.y_angle = 0.0; camera.xz_angle = 0.0; camera.target = Point3::new(0.0, 2.0, 0.0); camera.distance = 10.0; } fn load_assets( assets: &mut Assets, ) { // The skybox cubemap was downloaded from https://opengameart.org/content/elyvisions-skyboxes // These files were licensed as CC-BY 3.0 Unported on 2012/11/7 assets.import("assets/skybox/skybox_right.png"); assets.import("assets/skybox/skybox_left.png"); assets.import("assets/skybox/skybox_top.png"); assets.import("assets/skybox/skybox_bottom.png"); assets.import("assets/skybox/skybox_front.png"); assets.import("assets/skybox/skybox_back.png"); assets.import("assets/energy_beam/energy_beam.gltf"); assets.import("assets/drone/drone.gltf"); } fn init_drones( world: &mut World, assets: &mut Assets, bodies: &mut rapier3d::dynamics::RigidBodySet, colliders: &mut rapier3d::geometry::ColliderSet, ) { drone::spawn( world, assets, bodies, colliders, Point3::new(10.0, 0.0, 0.0), true, ); let positions: [[f32; 3]; 20] = [ [ 80.0, 10.0, -90.0], [-50.0, 20.0, 30.0], [100.0, -50.0, -40.0], [ 0.0, -25.0, 20.0], [ 15.0, 35.0, -2.0], [-90.0, -85.0, 10.0], [-45.0, 25.0, -95.0], [-80.0, -10.0, 90.0], [ 50.0, -20.0, -30.0], [-95.0, 50.0, 40.0], [ 10.0, 25.0, -20.0], [-15.0, -35.0, 2.0], [ 90.0, 85.0, -10.0], [ 45.0, -25.0, 95.0], [ 80.0, -10.0, -90.0], [ 50.0, 20.0, -30.0], [100.0, 50.0, -40.0], [ 0.0, -25.0, -20.0], [-15.0, 35.0, 2.0], [-90.0, 85.0, 10.0], ]; for i in 0..positions.len() { println!("{}", i); drone::spawn( world, assets, bodies, colliders, Point3::new(positions[i][0], positions[i][1], positions[i][2]), false, ); } } fn init_light(world: &mut World) { world.spawn(Some(( Light::Simple { position: Vec3::new(200.0, 0.0, 200.0), color: Color::white(), intensity: 0.8, enabled: true, }, ))); world.spawn(Some(( Light::Simple { position: Vec3::new(-200.0, 50.0, 100.0), color: Color::white(), intensity: 0.8, enabled: true, }, ))); world.spawn(Some(( Light::Simple { position: Vec3::new(100.0, -50.0, -200.0), color: Color::white(), intensity: 0.8, enabled: true, }, ))); } fn exile(mut world: Mut<World>, mut to_exile: Mut<ToExile>) { for i in 0..to_exile.entity_list.len() { world.exile(to_exile.entity_list[i]); } to_exile.entity_list = Vec::new(); } fn init_controls(input: &mut Input) { // Map W key to Run Action input.mapper_mut::<Mapper<Action>>() .set(vec![ (Action::MoveForward, Button::Key(KeyCode::W)), (Action::MoveBackward, Button::Key(KeyCode::S)), (Action::MoveLeft, Button::Key(KeyCode::A)), (Action::MoveRight, Button::Key(KeyCode::D)), (Action::Accelerate, Button::Key(KeyCode::LShift)), (Action::Strike, Button::MouseLeft), (Action::Menu, Button::Key(KeyCode::Escape)), ]); } #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] // All bindable actions pub enum Action { MoveForward, MoveBackward, MoveLeft, MoveRight, Accelerate, Strike, Menu, } // Bind Inputs and Actions impl ActionMapper<Action> for Input { fn action_mapped(&self, action: Action) -> Option<&Button> { let mapper = self.mapper::<Mapper<Action>>(); mapper.get_button(action) } }
pub mod entity; pub mod service; pub mod repository;
use crate::order::{ filter_input::FilterInput, filter_output::FilterOutput, parameters::ParameterValue, }; use std::collections::HashMap; #[derive(Debug, Deserialize, PartialEq)] pub struct Filter { pub name: String, pub label: Option<String>, pub parameters: HashMap<String, ParameterValue>, pub inputs: Option<Vec<FilterInput>>, pub outputs: Option<Vec<FilterOutput>>, }
use crate::libs::js_object::Object; use wasm_bindgen::prelude::*; use super::{Color, EventDispatcher, Texture}; #[wasm_bindgen(module = "three")] extern "C" { #[wasm_bindgen(extends = Material)] pub type LineBasicMaterial; #[wasm_bindgen(constructor)] pub fn new(parameters: &Object) -> LineBasicMaterial; #[wasm_bindgen(method, getter)] pub fn color(this: &LineBasicMaterial) -> Color; } #[wasm_bindgen(module = "three")] extern "C" { #[wasm_bindgen(extends = LineBasicMaterial)] pub type LineDashedMaterial; #[wasm_bindgen(constructor)] pub fn new(parameters: &Object) -> LineDashedMaterial; } #[wasm_bindgen(module = "three")] extern "C" { #[wasm_bindgen(extends = EventDispatcher)] pub type Material; #[wasm_bindgen(method, setter, js_name = "needsUpdate")] pub fn set_needs_update(this: &Material, needs_update: bool); #[wasm_bindgen(method, setter, js_name = "opacity")] pub fn set_opacity(this: &Material, opacity: f64); #[wasm_bindgen(method, setter, js_name = "stencilWrite")] pub fn set_stencil_write(this: &Material, stencil_write: bool); #[wasm_bindgen(method, setter, js_name = "stencilFunc")] pub fn set_stencil_func(this: &Material, stencil_func: u32); #[wasm_bindgen(method, setter, js_name = "stencilRef")] pub fn set_stencil_ref(this: &Material, stencil_func: u32); #[wasm_bindgen(method, setter, js_name = "stencilFail")] pub fn set_stencil_fail(this: &Material, stencil_func: u32); #[wasm_bindgen(method, setter, js_name = "stencilZFail")] pub fn set_stencil_z_fail(this: &Material, stencil_func: u32); #[wasm_bindgen(method, setter, js_name = "stencilZPass")] pub fn set_stencil_z_pass(this: &Material, stencil_func: u32); #[wasm_bindgen(method, setter, js_name = "side")] pub fn set_side(this: &Material, side: i32); #[wasm_bindgen(method, setter, js_name = "transparent")] pub fn set_transparent(this: &Material, transparent: bool); } #[wasm_bindgen(module = "three")] extern "C" { #[wasm_bindgen(extends = Material)] pub type MeshBasicMaterial; #[wasm_bindgen(constructor)] pub fn new(parameters: &Object) -> MeshBasicMaterial; #[wasm_bindgen(method, getter)] pub fn color(this: &MeshBasicMaterial) -> Color; #[wasm_bindgen(method, setter, js_name = "alphaMap")] pub fn set_alpha_map(this: &MeshBasicMaterial, map: Option<&Texture>); #[wasm_bindgen(method, setter, js_name = "map")] pub fn set_map(this: &MeshBasicMaterial, map: Option<&Texture>); } #[wasm_bindgen(module = "three")] extern "C" { #[wasm_bindgen(extends = Material)] pub type MeshStandardMaterial; #[wasm_bindgen(constructor)] pub fn new(parameters: &Object) -> MeshStandardMaterial; #[wasm_bindgen(method, getter)] pub fn color(this: &MeshStandardMaterial) -> Color; #[wasm_bindgen(method, setter, js_name = "map")] pub fn set_map(this: &MeshStandardMaterial, map: Option<&Texture>); }
use std::collections::HashMap; /// Rust中创建HashMap pub fn new_hashmap() { let mut new_map = HashMap::new(); new_map.insert("k", 1); new_map.insert("k1", 2); let s = String::from("kk"); new_map.insert(&s, 4); println!("{:?}", new_map); } /// 通过解引符号,能修改变量值 pub fn get_from_map() { let text = "hello world wonderful world"; let mut map = HashMap::new(); for word in text.split_whitespace() { let count = map.entry(word).or_insert(0); // sleep(Duration::from_secs(3)); *count += 1; } println!("{:?}", map.get_mut("world")); println!("{:?}", map); }
use { crate::{misc::OffsetSeeker, result::Result}, std::{ fs::File, io::{Read, Seek, SeekFrom}, }, }; const DATA_OFFSET_LENGTH: usize = 8; const SIGNATURE: &str = "ONEX"; pub struct OnexFile { f: File, } impl OnexFile { pub fn new(mut f: File) -> Result<Self> { Self::validate(&mut f)?; Ok(OnexFile { f }) } pub fn generate_bytes(loader_bytes: Vec<u8>, data_bytes: Vec<u8>) -> Vec<u8> { let data_offset = loader_bytes.len() as u64; let mut bytes = Vec::with_capacity( loader_bytes.len() + data_bytes.len() + DATA_OFFSET_LENGTH + SIGNATURE.len(), ); bytes.extend(loader_bytes); bytes.extend(data_bytes); let data_offset_bytes = data_offset.to_le_bytes(); bytes.extend(&data_offset_bytes); bytes.extend(SIGNATURE.bytes()); debug_assert_eq!(bytes.len(), bytes.capacity()); bytes } pub fn data_offset(&mut self) -> Result<u64> { self.f.seek(SeekFrom::End( -((SIGNATURE.len() + DATA_OFFSET_LENGTH) as i64), ))?; let mut data_offset = [0; DATA_OFFSET_LENGTH]; self.f.read_exact(&mut data_offset)?; Ok(u64::from_le_bytes(data_offset)) } pub fn data(&mut self) -> Result<Vec<u8>> { let mut accessor = self.data_accessor()?; let mut data_bytes = Vec::new(); accessor.read_to_end(&mut data_bytes)?; Ok(data_bytes) } pub fn data_accessor(&mut self) -> Result<OffsetSeeker> { self.f.seek(SeekFrom::Start(0))?; Ok(OffsetSeeker::new( self.f.try_clone()?, self.data_offset()?, self.data_length()?, )?) } pub fn validate(f: &mut File) -> Result<()> { f.seek(SeekFrom::End(-(SIGNATURE.len() as i64)))?; let mut signature = String::new(); f.read_to_string(&mut signature)?; if signature != SIGNATURE { Err("Signature not found for executable file.".into()) } else { Ok(()) } } fn file_length(&self) -> Result<u64> { Ok(self.f.metadata()?.len()) } fn data_length(&mut self) -> Result<u64> { Ok(self.file_length()? - self.data_offset()? - SIGNATURE.len() as u64 - DATA_OFFSET_LENGTH as u64) } }
use std::collections::HashMap; #[derive(Eq, Hash, Ord, PartialEq, PartialOrd)] struct Team<'a> { name: &'a str, } impl<'a> Team<'a> { fn new(name: &'a str) -> Self { Team { name } } } enum MatchResult<'a> { NonDraw { winner: Team<'a>, loser: Team<'a> }, Draw(Team<'a>, Team<'a>), } #[derive(Eq, Ord, PartialEq, PartialOrd)] struct Stats { // This field order is needed for Ord to be derived correctly. Stats will be ordered by // their point value (wins = 3, draws = 1, and losses = 0). wins: usize, draws: usize, losses: usize, } impl Stats { fn new() -> Self { Stats { wins: 0, draws: 0, losses: 0, } } fn matches_played(&self) -> usize { self.wins + self.losses + self.draws } fn points(&self) -> usize { (self.wins * 3) + self.draws } } struct Tally<'a> { data: HashMap<Team<'a>, Stats>, } impl<'a> Tally<'a> { fn new() -> Self { Tally { data: HashMap::new() } } fn add(&mut self, match_result: MatchResult<'a>) { match match_result { MatchResult::NonDraw { winner, loser } => { self.stats(winner).wins += 1; self.stats(loser).losses += 1; } MatchResult::Draw(team_1, team_2) => { self.stats(team_1).draws += 1; self.stats(team_2).draws += 1; } } } fn stats(&mut self, team: Team<'a>) -> &mut Stats { self.data.entry(team).or_insert(Stats::new()) } } impl<'a> IntoIterator for &'a Tally<'a> { type Item = (&'a Team<'a>, &'a Stats); type IntoIter = ::std::vec::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { let mut values = self.data.iter().collect::<Vec<_>>(); // Order by points, descending. In case of a tie, teams are ordered alphabetically. values.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0))); values.into_iter() } } #[derive(Debug)] enum ParseError { NotEnoughFields, InvalidMatchOutcome, } // TODO: Use std::convert::TryFrom once it's stabilized. trait TryFrom<T>: Sized { type Error; fn try_from(value: T) -> Result<Self, Self::Error>; } impl<'a> TryFrom<&'a str> for MatchResult<'a> { type Error = ParseError; fn try_from(input: &'a str) -> Result<Self, Self::Error> { let mut input_fields = input.split(';'); match (input_fields.next(), input_fields.next(), input_fields.next()) { (Some(winner_name), Some(loser_name), Some("win")) | (Some(loser_name), Some(winner_name), Some("loss")) => { Ok(MatchResult::NonDraw { winner: Team::new(winner_name), loser: Team::new(loser_name), }) } (Some(name_1), Some(name_2), Some("draw")) => { Ok(MatchResult::Draw(Team::new(name_1), Team::new(name_2))) } (Some(_), Some(_), Some(_)) => Err(ParseError::InvalidMatchOutcome), _ => Err(ParseError::NotEnoughFields), } } } macro_rules! row { ($a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr) => ( format!("{:30} | {:>2} | {:>2} | {:>2} | {:>2} | {:>2}", $a, $b, $c, $d, $e, $f) ) } fn tally_safe(input: &str) -> Result<String, ParseError> { let mut tally = Tally::new(); for line in input.lines() { tally.add(MatchResult::try_from(line)?); } let mut output = row!("Team", "MP", "W", "D", "L", "P"); for (team, stats) in &tally { output.push('\n'); output.push_str(&row!(team.name, stats.matches_played(), stats.wins, stats.draws, stats.losses, stats.points())); } Ok(output) } pub fn tally(input: &str) -> String { tally_safe(input).unwrap() }
use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn greet(greeting: String) -> String { let host_name = greeting.split_whitespace().last().unwrap_or(""); let mut return_greeting = "Hello, ".to_string(); return_greeting.push_str(host_name); return_greeting.push_str(" I am Rust"); return_greeting }
#[doc = "Register `FDCAN_ILS` reader"] pub type R = crate::R<FDCAN_ILS_SPEC>; #[doc = "Register `FDCAN_ILS` writer"] pub type W = crate::W<FDCAN_ILS_SPEC>; #[doc = "Field `RF0NL` reader - RF0NL"] pub type RF0NL_R = crate::BitReader; #[doc = "Field `RF0NL` writer - RF0NL"] pub type RF0NL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RF0WL` reader - RF0WL"] pub type RF0WL_R = crate::BitReader; #[doc = "Field `RF0WL` writer - RF0WL"] pub type RF0WL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RF0FL` reader - RF0FL"] pub type RF0FL_R = crate::BitReader; #[doc = "Field `RF0FL` writer - RF0FL"] pub type RF0FL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RF0LL` reader - RF0LL"] pub type RF0LL_R = crate::BitReader; #[doc = "Field `RF0LL` writer - RF0LL"] pub type RF0LL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RF1NL` reader - RF1NL"] pub type RF1NL_R = crate::BitReader; #[doc = "Field `RF1NL` writer - RF1NL"] pub type RF1NL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RF1WL` reader - RF1WL"] pub type RF1WL_R = crate::BitReader; #[doc = "Field `RF1WL` writer - RF1WL"] pub type RF1WL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RF1FL` reader - RF1FL"] pub type RF1FL_R = crate::BitReader; #[doc = "Field `RF1FL` writer - RF1FL"] pub type RF1FL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RF1LL` reader - RF1LL"] pub type RF1LL_R = crate::BitReader; #[doc = "Field `RF1LL` writer - RF1LL"] pub type RF1LL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HPML` reader - HPML"] pub type HPML_R = crate::BitReader; #[doc = "Field `HPML` writer - HPML"] pub type HPML_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TCL` reader - TCL"] pub type TCL_R = crate::BitReader; #[doc = "Field `TCL` writer - TCL"] pub type TCL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TCFL` reader - TCFL"] pub type TCFL_R = crate::BitReader; #[doc = "Field `TCFL` writer - TCFL"] pub type TCFL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TFEL` reader - TFEL"] pub type TFEL_R = crate::BitReader; #[doc = "Field `TFEL` writer - TFEL"] pub type TFEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TEFNL` reader - TEFNL"] pub type TEFNL_R = crate::BitReader; #[doc = "Field `TEFNL` writer - TEFNL"] pub type TEFNL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TEFWL` reader - TEFWL"] pub type TEFWL_R = crate::BitReader; #[doc = "Field `TEFWL` writer - TEFWL"] pub type TEFWL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TEFFL` reader - TEFFL"] pub type TEFFL_R = crate::BitReader; #[doc = "Field `TEFFL` writer - TEFFL"] pub type TEFFL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TEFLL` reader - TEFLL"] pub type TEFLL_R = crate::BitReader; #[doc = "Field `TEFLL` writer - TEFLL"] pub type TEFLL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TSWL` reader - TSWL"] pub type TSWL_R = crate::BitReader; #[doc = "Field `TSWL` writer - TSWL"] pub type TSWL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `MRAFL` reader - MRAFL"] pub type MRAFL_R = crate::BitReader; #[doc = "Field `MRAFL` writer - MRAFL"] pub type MRAFL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TOOL` reader - TOOL"] pub type TOOL_R = crate::BitReader; #[doc = "Field `TOOL` writer - TOOL"] pub type TOOL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DRXL` reader - DRXL"] pub type DRXL_R = crate::BitReader; #[doc = "Field `DRXL` writer - DRXL"] pub type DRXL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `BECL` reader - BECL"] pub type BECL_R = crate::BitReader; #[doc = "Field `BECL` writer - BECL"] pub type BECL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `BEUL` reader - BEUL"] pub type BEUL_R = crate::BitReader; #[doc = "Field `BEUL` writer - BEUL"] pub type BEUL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ELOL` reader - ELOL"] pub type ELOL_R = crate::BitReader; #[doc = "Field `ELOL` writer - ELOL"] pub type ELOL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `EPL` reader - EPL"] pub type EPL_R = crate::BitReader; #[doc = "Field `EPL` writer - EPL"] pub type EPL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `EWL` reader - EWL"] pub type EWL_R = crate::BitReader; #[doc = "Field `EWL` writer - EWL"] pub type EWL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `BOL` reader - BOL"] pub type BOL_R = crate::BitReader; #[doc = "Field `BOL` writer - BOL"] pub type BOL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WDIL` reader - WDIL"] pub type WDIL_R = crate::BitReader; #[doc = "Field `WDIL` writer - WDIL"] pub type WDIL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PEAL` reader - PEAL"] pub type PEAL_R = crate::BitReader; #[doc = "Field `PEAL` writer - PEAL"] pub type PEAL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PEDL` reader - PEDL"] pub type PEDL_R = crate::BitReader; #[doc = "Field `PEDL` writer - PEDL"] pub type PEDL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ARAL` reader - ARAL"] pub type ARAL_R = crate::BitReader; #[doc = "Field `ARAL` writer - ARAL"] pub type ARAL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - RF0NL"] #[inline(always)] pub fn rf0nl(&self) -> RF0NL_R { RF0NL_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - RF0WL"] #[inline(always)] pub fn rf0wl(&self) -> RF0WL_R { RF0WL_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - RF0FL"] #[inline(always)] pub fn rf0fl(&self) -> RF0FL_R { RF0FL_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - RF0LL"] #[inline(always)] pub fn rf0ll(&self) -> RF0LL_R { RF0LL_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - RF1NL"] #[inline(always)] pub fn rf1nl(&self) -> RF1NL_R { RF1NL_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - RF1WL"] #[inline(always)] pub fn rf1wl(&self) -> RF1WL_R { RF1WL_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - RF1FL"] #[inline(always)] pub fn rf1fl(&self) -> RF1FL_R { RF1FL_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - RF1LL"] #[inline(always)] pub fn rf1ll(&self) -> RF1LL_R { RF1LL_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - HPML"] #[inline(always)] pub fn hpml(&self) -> HPML_R { HPML_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - TCL"] #[inline(always)] pub fn tcl(&self) -> TCL_R { TCL_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - TCFL"] #[inline(always)] pub fn tcfl(&self) -> TCFL_R { TCFL_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - TFEL"] #[inline(always)] pub fn tfel(&self) -> TFEL_R { TFEL_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - TEFNL"] #[inline(always)] pub fn tefnl(&self) -> TEFNL_R { TEFNL_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - TEFWL"] #[inline(always)] pub fn tefwl(&self) -> TEFWL_R { TEFWL_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 14 - TEFFL"] #[inline(always)] pub fn teffl(&self) -> TEFFL_R { TEFFL_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 15 - TEFLL"] #[inline(always)] pub fn tefll(&self) -> TEFLL_R { TEFLL_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bit 16 - TSWL"] #[inline(always)] pub fn tswl(&self) -> TSWL_R { TSWL_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - MRAFL"] #[inline(always)] pub fn mrafl(&self) -> MRAFL_R { MRAFL_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - TOOL"] #[inline(always)] pub fn tool(&self) -> TOOL_R { TOOL_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - DRXL"] #[inline(always)] pub fn drxl(&self) -> DRXL_R { DRXL_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - BECL"] #[inline(always)] pub fn becl(&self) -> BECL_R { BECL_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - BEUL"] #[inline(always)] pub fn beul(&self) -> BEUL_R { BEUL_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - ELOL"] #[inline(always)] pub fn elol(&self) -> ELOL_R { ELOL_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 23 - EPL"] #[inline(always)] pub fn epl(&self) -> EPL_R { EPL_R::new(((self.bits >> 23) & 1) != 0) } #[doc = "Bit 24 - EWL"] #[inline(always)] pub fn ewl(&self) -> EWL_R { EWL_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 25 - BOL"] #[inline(always)] pub fn bol(&self) -> BOL_R { BOL_R::new(((self.bits >> 25) & 1) != 0) } #[doc = "Bit 26 - WDIL"] #[inline(always)] pub fn wdil(&self) -> WDIL_R { WDIL_R::new(((self.bits >> 26) & 1) != 0) } #[doc = "Bit 27 - PEAL"] #[inline(always)] pub fn peal(&self) -> PEAL_R { PEAL_R::new(((self.bits >> 27) & 1) != 0) } #[doc = "Bit 28 - PEDL"] #[inline(always)] pub fn pedl(&self) -> PEDL_R { PEDL_R::new(((self.bits >> 28) & 1) != 0) } #[doc = "Bit 29 - ARAL"] #[inline(always)] pub fn aral(&self) -> ARAL_R { ARAL_R::new(((self.bits >> 29) & 1) != 0) } } impl W { #[doc = "Bit 0 - RF0NL"] #[inline(always)] #[must_use] pub fn rf0nl(&mut self) -> RF0NL_W<FDCAN_ILS_SPEC, 0> { RF0NL_W::new(self) } #[doc = "Bit 1 - RF0WL"] #[inline(always)] #[must_use] pub fn rf0wl(&mut self) -> RF0WL_W<FDCAN_ILS_SPEC, 1> { RF0WL_W::new(self) } #[doc = "Bit 2 - RF0FL"] #[inline(always)] #[must_use] pub fn rf0fl(&mut self) -> RF0FL_W<FDCAN_ILS_SPEC, 2> { RF0FL_W::new(self) } #[doc = "Bit 3 - RF0LL"] #[inline(always)] #[must_use] pub fn rf0ll(&mut self) -> RF0LL_W<FDCAN_ILS_SPEC, 3> { RF0LL_W::new(self) } #[doc = "Bit 4 - RF1NL"] #[inline(always)] #[must_use] pub fn rf1nl(&mut self) -> RF1NL_W<FDCAN_ILS_SPEC, 4> { RF1NL_W::new(self) } #[doc = "Bit 5 - RF1WL"] #[inline(always)] #[must_use] pub fn rf1wl(&mut self) -> RF1WL_W<FDCAN_ILS_SPEC, 5> { RF1WL_W::new(self) } #[doc = "Bit 6 - RF1FL"] #[inline(always)] #[must_use] pub fn rf1fl(&mut self) -> RF1FL_W<FDCAN_ILS_SPEC, 6> { RF1FL_W::new(self) } #[doc = "Bit 7 - RF1LL"] #[inline(always)] #[must_use] pub fn rf1ll(&mut self) -> RF1LL_W<FDCAN_ILS_SPEC, 7> { RF1LL_W::new(self) } #[doc = "Bit 8 - HPML"] #[inline(always)] #[must_use] pub fn hpml(&mut self) -> HPML_W<FDCAN_ILS_SPEC, 8> { HPML_W::new(self) } #[doc = "Bit 9 - TCL"] #[inline(always)] #[must_use] pub fn tcl(&mut self) -> TCL_W<FDCAN_ILS_SPEC, 9> { TCL_W::new(self) } #[doc = "Bit 10 - TCFL"] #[inline(always)] #[must_use] pub fn tcfl(&mut self) -> TCFL_W<FDCAN_ILS_SPEC, 10> { TCFL_W::new(self) } #[doc = "Bit 11 - TFEL"] #[inline(always)] #[must_use] pub fn tfel(&mut self) -> TFEL_W<FDCAN_ILS_SPEC, 11> { TFEL_W::new(self) } #[doc = "Bit 12 - TEFNL"] #[inline(always)] #[must_use] pub fn tefnl(&mut self) -> TEFNL_W<FDCAN_ILS_SPEC, 12> { TEFNL_W::new(self) } #[doc = "Bit 13 - TEFWL"] #[inline(always)] #[must_use] pub fn tefwl(&mut self) -> TEFWL_W<FDCAN_ILS_SPEC, 13> { TEFWL_W::new(self) } #[doc = "Bit 14 - TEFFL"] #[inline(always)] #[must_use] pub fn teffl(&mut self) -> TEFFL_W<FDCAN_ILS_SPEC, 14> { TEFFL_W::new(self) } #[doc = "Bit 15 - TEFLL"] #[inline(always)] #[must_use] pub fn tefll(&mut self) -> TEFLL_W<FDCAN_ILS_SPEC, 15> { TEFLL_W::new(self) } #[doc = "Bit 16 - TSWL"] #[inline(always)] #[must_use] pub fn tswl(&mut self) -> TSWL_W<FDCAN_ILS_SPEC, 16> { TSWL_W::new(self) } #[doc = "Bit 17 - MRAFL"] #[inline(always)] #[must_use] pub fn mrafl(&mut self) -> MRAFL_W<FDCAN_ILS_SPEC, 17> { MRAFL_W::new(self) } #[doc = "Bit 18 - TOOL"] #[inline(always)] #[must_use] pub fn tool(&mut self) -> TOOL_W<FDCAN_ILS_SPEC, 18> { TOOL_W::new(self) } #[doc = "Bit 19 - DRXL"] #[inline(always)] #[must_use] pub fn drxl(&mut self) -> DRXL_W<FDCAN_ILS_SPEC, 19> { DRXL_W::new(self) } #[doc = "Bit 20 - BECL"] #[inline(always)] #[must_use] pub fn becl(&mut self) -> BECL_W<FDCAN_ILS_SPEC, 20> { BECL_W::new(self) } #[doc = "Bit 21 - BEUL"] #[inline(always)] #[must_use] pub fn beul(&mut self) -> BEUL_W<FDCAN_ILS_SPEC, 21> { BEUL_W::new(self) } #[doc = "Bit 22 - ELOL"] #[inline(always)] #[must_use] pub fn elol(&mut self) -> ELOL_W<FDCAN_ILS_SPEC, 22> { ELOL_W::new(self) } #[doc = "Bit 23 - EPL"] #[inline(always)] #[must_use] pub fn epl(&mut self) -> EPL_W<FDCAN_ILS_SPEC, 23> { EPL_W::new(self) } #[doc = "Bit 24 - EWL"] #[inline(always)] #[must_use] pub fn ewl(&mut self) -> EWL_W<FDCAN_ILS_SPEC, 24> { EWL_W::new(self) } #[doc = "Bit 25 - BOL"] #[inline(always)] #[must_use] pub fn bol(&mut self) -> BOL_W<FDCAN_ILS_SPEC, 25> { BOL_W::new(self) } #[doc = "Bit 26 - WDIL"] #[inline(always)] #[must_use] pub fn wdil(&mut self) -> WDIL_W<FDCAN_ILS_SPEC, 26> { WDIL_W::new(self) } #[doc = "Bit 27 - PEAL"] #[inline(always)] #[must_use] pub fn peal(&mut self) -> PEAL_W<FDCAN_ILS_SPEC, 27> { PEAL_W::new(self) } #[doc = "Bit 28 - PEDL"] #[inline(always)] #[must_use] pub fn pedl(&mut self) -> PEDL_W<FDCAN_ILS_SPEC, 28> { PEDL_W::new(self) } #[doc = "Bit 29 - ARAL"] #[inline(always)] #[must_use] pub fn aral(&mut self) -> ARAL_W<FDCAN_ILS_SPEC, 29> { ARAL_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 assigns an interrupt generated by a specific interrupt flag from the interrupt register to one of the two module interrupt lines. For interrupt generation the respective interrupt line has to be enabled via FDCAN_ILE.EINT0 and FDCAN_ILE.EINT1.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fdcan_ils::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 [`fdcan_ils::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct FDCAN_ILS_SPEC; impl crate::RegisterSpec for FDCAN_ILS_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`fdcan_ils::R`](R) reader structure"] impl crate::Readable for FDCAN_ILS_SPEC {} #[doc = "`write(|w| ..)` method takes [`fdcan_ils::W`](W) writer structure"] impl crate::Writable for FDCAN_ILS_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets FDCAN_ILS to value 0"] impl crate::Resettable for FDCAN_ILS_SPEC { const RESET_VALUE: Self::Ux = 0; }
//! [dma_gpio](index.html) is a library for pi's GPIO that uses DMA ([Direct Memory Access](https://en.wikipedia.org/wiki/Direct_memory_access)) and [PWM via DMA](https://stackoverflow.com/questions/50427275/raspberry-how-does-the-pwm-via-dma-work). //! By using DMA and interacting directly with hardware memory, it manages to be fast (Max Raw Speed ≈ 1.6 MHz on Pi3) while having almost no CPU usage ( ~2%). //! This project was inspired by its predecessor projects in C, such as [PiBits](https://github.com/richardghirst/PiBits), [pi-blaster](https://github.com/sarfata/pi-blaster) and [RPIO](https://github.com/metachris/RPIO/tree/master/source); however, this project bypasses L1 cache which the DMA Controller does not recognize, resulting in a slightly faster GPIO Speed. //! //! Be sure to run your binary file in sudo. //! //! ## Cross-Compilation //! Note that this library will only compile on a 32-bit machine a.k.a. a raspberry pi. So, if you try to compile this on your personal computer, it will most likely fail. //! So, if you want to test and compile your project with this library on your PC, you should do so by cross-compiling using a specific target such as armv7-unknown-linux-gnueabihf. //! //! Great resource for cross-compilations to Pi that I found helpful is [rust-cross](https://github.com/japaric/rust-cross). For pi 2 and 3, use armv7-unknown-linux-gnueabihf, and, for pi 1 and zero, use armv6-unknown-linux-gnueabihf. //! # Getting Started //! First, add the crate to the dependencies. //! ```no_run //! Cargo.toml //! //! ... //! [dependencies] //! dma_gpio = "0.1.8" //! ``` //! [pi](pi/index.html) module will have everything you need. //! //! The easiest way to get started using this library is initializing a [Board](pi/struct.Board.html) using [BoardBuilder](pi/struct.BoardBuilder.html). //! BoardBuilder will configure the default setting for the DMA, but manual configuration is also available (read more on this in [BoardBuiler](pi/struct.BoardBuilder.html#building-with-custom-settings)). //! When the Board is initialized, it recognizes which Pi-version it is running on, and interacts with the hardware memory accordingly. //! //! ## Example //! Below example initializes the board using BoardBuilder with default configurations, set the PWM of gpio pins 21 and 22 to 25%, 50%, 75%, then 100% for 1 second each. //! //! Make sure to run the binary file in sudo. //! //! ```no_run //! use std::thread::sleep; //! use std::time::Duration; //! use dma_gpio::pi::BoardBuilder; //! //! fn main() { //! let mut board = BoardBuilder::new().build_with_pins(vec![21, 22]).unwrap(); //! board.print_info(); //! //! board.set_all_pwm(0.25).unwrap(); //! let sec = Duration::from_millis(1000); //! sleep(millis); //! //! board.set_all_pwm(0.5).unwrap(); //! sleep(millis); //! //! board.set_all_pwm(0.75).unwrap(); //! sleep(millis); //! //! board.set_all_pwm(1.0).unwrap(); //! sleep(millis); //! } //! //! ``` //! //! # Features //! There are two features you can enable in this crate: 'debug' and 'bind_process'. To enable these features, write the dependency for this crate as shown below. //! ```no_run //! Cargo.toml //! //! ... //! [dependencies] //! ... //! //! [dependencies.dma_gpio] //! version = "0.1.8" //! features = ["debug", "bind_process"] //! ``` //! //! ## 'debug' feature //! By enabling this feature, the library will print out the process every step of the way. This feature will be useful when debugging. //! Also, after enabling this feature in Cargo.toml, you have to call [enable_logger](fn.enable_logger.html) function to see the logs in the terminal. //! ```no_run //! use std::thread::sleep; //! use std::time::Duration; //! use dma_gpio::pi::BoardBuilder; //! //! fn main() { //! dma_gpio::enable_logger(); //! let mut board = BoardBuilder::new().build_with_pins(vec![21, 22]).unwrap(); //! //! board.set_all_pwm(0.5).unwrap(); //! let sec = Duration::from_millis(2000); //! sleep(millis); //! } //! //! ``` //! ## 'bind_process' feature //! This feature lets you access the [pi_core](pi_core/index.html) module which only has one function [bind_process_to_last](pi_core/fn.bind_process_to_last.html). This function binds the process to the last core of the Pi. However, to use this function, you have to first install a C library called [hwloc](https://github.com/daschl/hwloc-rs#install-hwloc-on-os-x). Also, enabling debug feature will print out if you have correctly bound process to the last core. //! ```no_run //! use std::thread::sleep; //! use std::time::Duration; //! use dma_gpio::{pi::BoardBuilder, pi_core}; //! //! fn main() { //! pi_core::bind_process_to_last(); //! let mut board = BoardBuilder::new().build_with_pins(vec![21, 22]).unwrap(); //! //! board.set_all_pwm(0.5).unwrap(); //! let sec = Duration::from_millis(2000); //! sleep(millis); //! } //! ``` //! # Contact //! If you have any questions or recommendations for the betterment of this project, please email me at Jack.Y.L.Dev@gmail.com #[macro_use] extern crate log; #[cfg(feature = "debug")] use env_logger; pub mod mailbox; pub mod pi; // if you wanna bind the process to core for better performance? #[cfg(feature = "bind_process")] pub mod pi_core; /// Only accessable with "debug" feature. Use it to see traces when running #[cfg(feature = "debug")] pub fn enable_logger(){ env_logger::Builder::new() .default_format() .default_format_module_path(false) .default_format_timestamp(false) .filter_level(log::LevelFilter::Warn) .filter_module("dma_gpio", log::LevelFilter::Trace) .init(); }
//! The abstraction layer before actually rendering glyphs. The world is "captured" into a scene //! here and then can be rendered independent of world state. Until a turn is made, the world state //! does not need to be recaptured. All non-stateful graphical elements (animations, etc.) are //! captured by the types in this module. use crate::gfx::prelude::*; pub struct GfxGlyph { pub glyph: &'static str, pub render_offset: [f32; 2], } impl GfxGlyph { pub fn new(glyph: &'static str) -> GfxGlyph { GfxGlyph { glyph, render_offset: [0.0, 0.0], } } } pub struct GfxTile { pub glyph: GfxGlyph, pub fg: [f32; 4], pub bg: [f32; 4], } pub struct GfxRegion { pub tiles: Vec<GfxTile>, } impl GfxRegion { /// Useful when using non-blocking (i.e. cache-only) world state retrieval functions. pub fn empty() -> Self { Self { tiles: Vec::new(), } } }
use reqwest::Client; use scraper::Html; use std::error::Error; pub async fn fetch(http_client: &Client) -> Result<Html, Box<dyn Error>> { const URL: &str = "https://www.jobkorea.co.kr/Recruit/Home/_GI_List/"; #[rustfmt::skip] let body = [ ("isDefault", "true"), ("condition[duty]", "1000100,1000101,1000102,1000109,1000094,1000097",), ("condition[jobtype]", "1,3,9"), ("condition[menucode]", ""), ("page", "1"), ("direct", "0"), ("order", "2"), ("pagesize", "20"), ("tabindex", "0"), ("fulltime", "0"), ("confirm", "0"), ]; #[rustfmt::skip] let res = http_client .post(URL) .header("Accept", "text/html, */*; q=0.01") .header("Referer", "https://www.jobkorea.co.kr/recruit/joblist?menucode=duty&dutyCtgr=10016",) .header("X-Requested-With", "XMLHttpRequest") .header("DNT", "1") .form(&body) .send() .await?; let document = Html::parse_document(res.text().await?.as_str()); Ok(document) } #[cfg(test)] mod tests { use super::*; use reqwest::Client; #[tokio::test] async fn fetch_test() { let http_client = Client::new(); fetch(&http_client).await.unwrap(); } }
pub use self::test_mod::*; mod test_mod; mod row;
// Copyright (c) 2019 Alain Brenzikofer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // initialise with: // post({sender: runtime.indices.ss58Decode('F7Gh'), call: calls.demo.setPayment(1000)}).tie(console.log) use parity_codec::Encode; use support::{decl_module, decl_storage, decl_event, StorageValue, Parameter, dispatch::Result}; use runtime_primitives::traits::{Hash, Zero, SimpleArithmetic, As, StaticLookup, Member, CheckedAdd, CheckedSub}; use balances; use system::{self, IsDeadAccount, OnNewAccount, ensure_signed}; use rstd::prelude::*; use runtime_io; pub trait Trait: balances::Trait {} decl_module! { pub struct Module<T: Trait> for enum Call where origin: T::Origin { /// Transfer some liquid free balance to another staker. pub fn transfer( origin, dest: <T::Lookup as StaticLookup>::Source, //#[compact] value: T::Balance value: T::Balance ) { runtime_io::print("nctr_token::transfer() was called!"); let transactor = ensure_signed(origin)?; let dest = T::Lookup::lookup(dest)?; let from_balance = <balances::Module<T>>::free_balance(&transactor); let to_balance = <balances::Module<T>>::free_balance(&dest); let would_create = to_balance.is_zero(); let fee = if would_create { Self::creation_fee(value) } else { Self::transfer_fee(value) }; let liability = match value.checked_add(&fee) { Some(l) => l, None => return Err("got overflow after adding a fee to value"), }; let new_from_balance = match from_balance.checked_sub(&liability) { Some(b) => b, None => return Err("balance too low to send value"), }; if would_create && value < <balances::Module<T>>::existential_deposit() { return Err("value too low to create account"); } T::EnsureAccountLiquid::ensure_account_liquid(&transactor)?; // NOTE: total stake being stored in the same type means that this could never overflow // but better to be safe than sorry. let new_to_balance = match to_balance.checked_add(&value) { Some(b) => b, None => return Err("destination balance too high to receive value"), }; if transactor != dest { <balances::Module<T>>::set_free_balance(&transactor, new_from_balance); <balances::Module<T>>::decrease_total_stake_by(fee); <balances::Module<T>>::set_free_balance_creating(&dest, new_to_balance); //TODO <balances::Module<T>>::deposit_event(RawEvent::Transfer(transactor, dest, value, fee)); } } } } decl_storage! { trait Store for Module<T: Trait> as NctrToken { pub TransactionPropFee get(transaction_prop_fee) config(): T::Balance; } } impl<T: Trait> Module<T> { fn transfer_fee(value: T::Balance) -> T::Balance{ value / Self::transaction_prop_fee() } fn creation_fee(value: T::Balance) -> T::Balance{ Self::transfer_fee(value) } }
//! //! Support for Slack Webhooks methods //! use rsb_derive::Builder; use serde::{Deserialize, Serialize}; use serde_with::skip_serializing_none; use crate::ClientResult; use crate::SlackClient; use slack_morphism_models::*; impl SlackClient { /// /// Post a webhook message using webhook url /// pub async fn post_webhook_message( &self, hook_url: &str, req: &SlackApiPostWebhookMessageRequest, ) -> ClientResult<SlackApiPostWebhookMessageResponse> { self.http_api .http_post_uri(hook_url.parse()?, req, None) .await } } #[skip_serializing_none] #[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)] pub struct SlackApiPostWebhookMessageRequest { #[serde(flatten)] pub content: SlackMessageContent, pub thread_ts: Option<SlackTs>, } #[skip_serializing_none] #[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)] pub struct SlackApiPostWebhookMessageResponse {}
struct Solution; impl Solution { pub fn maximum_gap(mut nums: Vec<i32>) -> i32 { let n = nums.len(); if n < 2 { return 0; } let max = *(nums.iter().max().unwrap()); // for i:=1; i<=max; i*=10 let mut buf = vec![0; n]; for exp in (0..).map(|i| 10_i32.pow(i)).take_while(|i| i <= &max) { let mut cnt = vec![0; 10]; for num in nums.iter() { let digit = num / exp % 10; cnt[digit as usize] += 1; } for i in 1..10 { cnt[i] += cnt[i - 1]; } for i in (0..n).rev() { let digit = (nums[i] / exp % 10) as usize; buf[cnt[digit] - 1] = nums[i]; cnt[digit] -= 1; } nums.copy_from_slice(&buf); } let mut ans = 0; for i in 1..n { ans = ans.max(nums[i] - nums[i - 1]); } ans } } #[cfg(test)] mod tests { use super::*; #[test] fn test_maximum_gap() { assert_eq!(Solution::maximum_gap(vec![3, 6, 9, 1]), 3); assert_eq!(Solution::maximum_gap(vec![10]), 0); assert_eq!(Solution::maximum_gap(vec![100, 3, 2, 1]), 97); } }
// Copyright 2021 The Matrix.org Foundation C.I.C. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::{cmp::Reverse, future::Future, pin::Pin}; use mime::{Mime, STAR}; use serde::Serialize; use tera::Context; use tide::{ http::headers::{ACCEPT, LOCATION}, Body, Request, StatusCode, }; use tracing::debug; use crate::{state::State, templates::common_context}; /// Get the weight parameter for a mime type from 0 to 1000 #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)] fn get_weight(mime: &Mime) -> usize { let q = mime .get_param("q") .map_or(1.0_f64, |q| q.as_str().parse().unwrap_or(0.0)) .min(1.0) .max(0.0); // Weight have a 3 digit precision so we can multiply by 1000 and cast to // int. Sign loss should not happen here because of the min/max up there and // truncation does not matter here. (q * 1000.0) as _ } /// Find what content type should be used for a given request fn preferred_mime_type<'a>( request: &Request<State>, supported_types: &'a [Mime], ) -> Option<&'a Mime> { let accept = request.header(ACCEPT)?; // Parse the Accept header as a list of mime types with their associated // weight let accepted_types: Vec<(Mime, usize)> = { let v: Option<Vec<_>> = accept .into_iter() .flat_map(|value| value.as_str().split(',')) .map(|mime| { mime.trim().parse().ok().map(|mime| { let q = get_weight(&mime); (mime, q) }) }) .collect(); let mut v = v?; v.sort_by_key(|(_, weight)| Reverse(*weight)); v }; // For each supported content type, find out if it is accepted with what // weight and specificity let mut types: Vec<_> = supported_types .iter() .enumerate() .filter_map(|(index, supported)| { accepted_types.iter().find_map(|(accepted, weight)| { if accepted.type_() == supported.type_() && accepted.subtype() == supported.subtype() { // Accept: text/html Some((supported, *weight, 2_usize, index)) } else if accepted.type_() == supported.type_() && accepted.subtype() == STAR { // Accept: text/* Some((supported, *weight, 1, index)) } else if accepted.type_() == STAR && accepted.subtype() == STAR { // Accept: */* Some((supported, *weight, 0, index)) } else { None } }) }) .collect(); types.sort_by_key(|(_, weight, specificity, index)| { (Reverse(*weight), Reverse(*specificity), *index) }); types.first().map(|(mime, _, _, _)| *mime) } #[derive(Serialize)] struct ErrorContext { #[serde(skip_serializing_if = "Option::is_none")] code: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] description: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] details: Option<String>, } impl ErrorContext { fn should_render(&self) -> bool { self.code.is_some() || self.description.is_some() || self.details.is_some() } } pub fn middleware<'a>( request: tide::Request<State>, next: tide::Next<'a, State>, ) -> Pin<Box<dyn Future<Output = tide::Result> + Send + 'a>> { Box::pin(async { let content_type = preferred_mime_type( &request, &[mime::TEXT_PLAIN, mime::TEXT_HTML, mime::APPLICATION_JSON], ); debug!("Content-Type from Accept: {:?}", content_type); // TODO: We should not clone here let templates = request.state().templates().clone(); // TODO: This context should probably be comptuted somewhere else let pctx = common_context(&request).await?.clone(); let mut response = next.run(request).await; // Find out what message should be displayed from the response status // code let (code, description) = match response.status() { StatusCode::NotFound => (Some("Not found".to_string()), None), StatusCode::MethodNotAllowed => (Some("Method not allowed".to_string()), None), StatusCode::Found | StatusCode::PermanentRedirect | StatusCode::TemporaryRedirect | StatusCode::SeeOther => { let description = response.header(LOCATION).map(|loc| format!("To {}", loc)); (Some("Redirecting".to_string()), description) } StatusCode::InternalServerError => (Some("Internal server error".to_string()), None), _ => (None, None), }; // If there is an error associated to the response, format it in a nice // way with a backtrace if we have one let details = response.take_error().map(|err| { format!( "{:?}{}", err, err.backtrace() .map(|bt| format!("\nBacktrace:\n{}", bt.to_string())) .unwrap_or_default() ) }); let error_context = ErrorContext { code, description, details, }; // This is the case if one of the code, description or details is not // None if error_context.should_render() { match content_type { Some(c) if c == &mime::APPLICATION_JSON => { response.set_body(Body::from_json(&error_context)?); response.set_content_type("application/json"); } Some(c) if c == &mime::TEXT_HTML => { let mut ctx = Context::from_serialize(&error_context)?; ctx.extend(pctx); response.set_body(templates.render("error.html", &ctx)?); response.set_content_type("text/html"); } Some(c) if c == &mime::TEXT_PLAIN => { let mut ctx = Context::from_serialize(&error_context)?; ctx.extend(pctx); response.set_body(templates.render("error.txt", &ctx)?); response.set_content_type("text/plain"); } _ => { response.set_body("Unsupported Content-Type in Accept header"); response.set_content_type("text/plain"); response.set_status(StatusCode::NotAcceptable); } } } Ok(response) }) }
#[doc = "Register `PR2` reader"] pub type R = crate::R<PR2_SPEC>; #[doc = "Register `PR2` writer"] pub type W = crate::W<PR2_SPEC>; #[doc = "Field `PIF32` reader - Pending bit 32"] pub type PIF32_R = crate::BitReader<PIF32R_A>; #[doc = "Pending bit 32\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PIF32R_A { #[doc = "0: No trigger request occurred"] NotPending = 0, #[doc = "1: Selected trigger request occurred"] Pending = 1, } impl From<PIF32R_A> for bool { #[inline(always)] fn from(variant: PIF32R_A) -> Self { variant as u8 != 0 } } impl PIF32_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PIF32R_A { match self.bits { false => PIF32R_A::NotPending, true => PIF32R_A::Pending, } } #[doc = "No trigger request occurred"] #[inline(always)] pub fn is_not_pending(&self) -> bool { *self == PIF32R_A::NotPending } #[doc = "Selected trigger request occurred"] #[inline(always)] pub fn is_pending(&self) -> bool { *self == PIF32R_A::Pending } } #[doc = "Pending bit 32\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PIF32W_AW { #[doc = "1: Clears pending bit"] Clear = 1, } impl From<PIF32W_AW> for bool { #[inline(always)] fn from(variant: PIF32W_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `PIF32` writer - Pending bit 32"] pub type PIF32_W<'a, REG, const O: u8> = crate::BitWriter1C<'a, REG, O, PIF32W_AW>; impl<'a, REG, const O: u8> PIF32_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(PIF32W_AW::Clear) } } #[doc = "Field `PIF33` reader - Pending bit 33"] pub use PIF32_R as PIF33_R; #[doc = "Field `PIF40` reader - Pending bit 40"] pub use PIF32_R as PIF40_R; #[doc = "Field `PIF41` reader - Pending bit 41"] pub use PIF32_R as PIF41_R; #[doc = "Field `PIF33` writer - Pending bit 33"] pub use PIF32_W as PIF33_W; #[doc = "Field `PIF40` writer - Pending bit 40"] pub use PIF32_W as PIF40_W; #[doc = "Field `PIF41` writer - Pending bit 41"] pub use PIF32_W as PIF41_W; impl R { #[doc = "Bit 0 - Pending bit 32"] #[inline(always)] pub fn pif32(&self) -> PIF32_R { PIF32_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Pending bit 33"] #[inline(always)] pub fn pif33(&self) -> PIF33_R { PIF33_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 8 - Pending bit 40"] #[inline(always)] pub fn pif40(&self) -> PIF40_R { PIF40_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - Pending bit 41"] #[inline(always)] pub fn pif41(&self) -> PIF41_R { PIF41_R::new(((self.bits >> 9) & 1) != 0) } } impl W { #[doc = "Bit 0 - Pending bit 32"] #[inline(always)] #[must_use] pub fn pif32(&mut self) -> PIF32_W<PR2_SPEC, 0> { PIF32_W::new(self) } #[doc = "Bit 1 - Pending bit 33"] #[inline(always)] #[must_use] pub fn pif33(&mut self) -> PIF33_W<PR2_SPEC, 1> { PIF33_W::new(self) } #[doc = "Bit 8 - Pending bit 40"] #[inline(always)] #[must_use] pub fn pif40(&mut self) -> PIF40_W<PR2_SPEC, 8> { PIF40_W::new(self) } #[doc = "Bit 9 - Pending bit 41"] #[inline(always)] #[must_use] pub fn pif41(&mut self) -> PIF41_W<PR2_SPEC, 9> { PIF41_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 = "Pending register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pr2::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 [`pr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct PR2_SPEC; impl crate::RegisterSpec for PR2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`pr2::R`](R) reader structure"] impl crate::Readable for PR2_SPEC {} #[doc = "`write(|w| ..)` method takes [`pr2::W`](W) writer structure"] impl crate::Writable for PR2_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0x0303; } #[doc = "`reset()` method sets PR2 to value 0"] impl crate::Resettable for PR2_SPEC { const RESET_VALUE: Self::Ux = 0; }
//! System calls related to files and resource management. use arch::context::ContextFile; use core::str; use fs::ResourceSeek; use schemes::pipe::{PipeRead, PipeWrite}; use syscall::{Stat, SEEK_CUR, SEEK_END, SEEK_SET}; use system::error::{Error, Result, EBADF, EFAULT, EINVAL}; /** <!-- @MANSTART{sys_chdir} --> NAME sys_chdir - change working directory SYNOPSIS sys_chdir(path: *const u8) -> Result<usize>; DESCRIPTION sys_chdir changes the current working directory of the calling process to the directory specified in path RETURN VALUE On success, Ok(0) is returned. On error, Err(err) is returned where err is one of the following errors ERRORS EACCESS TODO Access permissions denied to one of the path components EFAULT TODO path points outside the accessible address space of the process EIO TODO An I/O error occured ENOENT TODO path references a directory that does not exist ENOMEM TODO Insufficient kernel memory was available ENOTDIR TODO A component of path is not a directory ESRCH Currently not running in a process context (rare, would only happen during kernel init) <!-- @MANEND --> */ pub fn chdir(path_ptr: *const u8, path_len: usize) -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = try!(contexts.current()); let path_safe = current.get_slice(path_ptr, path_len)?; unsafe { *current.cwd.get() = current.canonicalize(str::from_utf8_unchecked(path_safe)); } Ok(0) } /** <!-- @MANSTART{sys_close} --> NAME sys_close - close a file descriptor SYNOPSIS sys_close(fd: usize) -> Result<usize>; DESCRIPTION sys_close closes a file descriptor, so that it no longer refers to any file and may be reused. RETURN VALUE On success, Ok(0) is returned. On error, Err(err) is returned where err is one of the following errors ERRORS EBADF fd is not a valid open file decriptor EIO TODO An I/O error occured ESRCH Currently not running in a process context (rare, would only happen during kernel init) <!-- @MANEND --> */ pub fn close(fd: usize) -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = try!(contexts.current()); for i in 0..unsafe { (*current.files.get()).len() } { let mut remove = false; if let Some(file) = unsafe { (*current.files.get()).get(i) } { if file.fd == fd { remove = true; } } if remove { if i < unsafe { (*current.files.get()).len() } { drop(unsafe { (*current.files.get()).remove(i) }); return Ok(0); } } } Err(Error::new(EBADF)) } /** <!-- @MANSTART{sys_dup} --> NAME sys_dup - duplicate a file descriptor SYNOPSIS sys_dup(fd: usize) -> Result<usize>; DESCRIPTION sys_dup creates a copy of fd, using the lowest unused descriptor for the new descriptor RETURN VALUE On success, Ok(new_fd) is returned, where new_fd is the new file descriptor. On error, Err(err) is returned where err is one of the following errors ERRORS EBADF fd is not a valid open file decriptor ESRCH Currently not running in a process context (rare, would only happen during kernel init) <!-- @MANEND --> */ pub fn dup(fd: usize) -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = try!(contexts.current()); let resource = try!(current.get_file(fd)); let new_resource = try!(resource.dup()); let new_fd = current.next_fd(); unsafe { (*current.files.get()).push(ContextFile { fd: new_fd, resource: new_resource, }); } Ok(new_fd) } pub fn fpath(fd: usize, buf: *mut u8, count: usize) -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = contexts.current()?; let resource = current.get_file(fd)?; if count > 0 { let buf_safe = current.get_slice_mut(buf, count)?; resource.path(buf_safe) } else { Ok(0) } } pub fn fstat(fd: usize, stat: *mut Stat) -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = contexts.current()?; let resource = current.get_file(fd)?; let stat_safe = current.get_ref_mut(stat)?; resource.stat(stat_safe).and(Ok(0)) } /** <!-- @MANSTART{sys_fsync} --> NAME sys_fsync - synchronize a file's in-core state with storage device SYNOPSIS sys_fsync(fd: usize) -> Result<usize>; DESCRIPTION sys_fsync transfers all modified in-core data of the file refered to by the file descriptor fd to the underlying device RETURN VALUE On success, Ok(0) is returned. On error, Err(err) is returned where err is one of the following errors ERRORS EBADF fd is not a valid open file decriptor EIO TODO An I/O error occured EINVAL TODO fd does not support synchronization ESRCH Currently not running in a process context (rare, would only happen during kernel init) <!-- @MANEND --> */ pub fn fsync(fd: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); let mut resource = try!(current.get_file_mut(fd)); resource.sync().and(Ok(0)) } /** <!-- @MANSTART{sys_ftruncate} --> NAME sys_ftruncate - truncate a file to a specified length SYNOPSIS sys_ftruncate(fd: usize, length: usize) -> Result<usize>; DESCRIPTION sys_ftruncate causes the file referenced by fd to be truncated to a size of precisely length bytes RETURN VALUE On success, Ok(0) is returned. On error, Err(err) is returned where err is one of the following errors ERRORS EBADF fd is not a valid open file decriptor EIO TODO An I/O error occured EINVAL TODO fd does not support truncation ESRCH Currently not running in a process context (rare, would only happen during kernel init) <!-- @MANEND --> */ pub fn ftruncate(fd: usize, length: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); let mut resource = try!(current.get_file_mut(fd)); resource.truncate(length).and(Ok(0)) } //TODO: Link /** <!-- @MANSTART{sys_lseek} --> NAME sys_lseek - reposition read/write file offset SYNOPSIS sys_lseek(fd: usize, offset: isize, whence: usize) -> Result<usize>; DESCRIPTION sys_lseek repositions the offset of the file referenced by fd to the offset according to whence SEEK_SET: 0 The offset is set to offset bytes SEEK_CUR: 1 The offset is set to its current location plus offset bytes SEEK_END: 2 The offset is set to the size of the file plus offset bytes RETURN VALUE On success, Ok(new_offset) is returned, where new_offset is the resulting offset location. On error, Err(err) is returned where err is one of the following errors ERRORS EBADF fd is not a valid open file decriptor EINVAL whence or the offset is not valid ESPIPE fd does not support seeking ESRCH Currently not running in a process context (rare, would only happen during kernel init) <!-- @MANEND --> */ pub fn lseek(fd: usize, offset: isize, whence: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); let mut resource = try!(current.get_file_mut(fd)); match whence { SEEK_SET => resource.seek(ResourceSeek::Start(offset as usize)), SEEK_CUR => resource.seek(ResourceSeek::Current(offset)), SEEK_END => resource.seek(ResourceSeek::End(offset)), _ => Err(Error::new(EINVAL)), } } /** <!-- @MANSTART{sys_mkdir} --> NAME sys_mkdir - create a directory SYNOPSIS sys_mkdir(path: *const u8, flags: usize) -> Result<usize>; DESCRIPTION sys_mkdir attempts to create a directory named path RETURN VALUE On success, Ok(0) is returned. On error, Err(err) is returned where err is one of the following errors ERRORS EACCES This process does not have write permissions to the parent directory or search permissions to other components in path EEXIST path already exists EFAULT path points outside of the accessible address space of the process ENOENT A directory component in path does not exist EPERM The filesystem containing path does not support the creation of directories EROFS The filesystem containing path is read-only ESRCH Currently not running in a process context (rare, would only happen during kernel init) <!-- @MANEND --> */ pub fn mkdir(path_ptr: *const u8, path_len: usize, flags: usize) -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = try!(contexts.current()); let path_safe = current.get_slice(path_ptr, path_len)?; let path_string = current.canonicalize(unsafe { str::from_utf8_unchecked(path_safe) }); ::env().mkdir(&path_string, flags).and(Ok(0)) } /** <!-- @MANSTART{sys_open} --> NAME sys_open - open and possibly create a file SYNOPSIS sys_open(path: *const u8, flags: usize) -> Result<usize>; DESCRIPTION sys_open returns a file descriptor referencing path, creating path if O_CREAT is provided TODO: Open is very complicated, and has a lot of flags RETURN VALUE On success, Ok(fd) is returned, where fd is a file descriptor referencing path. On error, Err(err) is returned where err is one of the following errors ERRORS EACCES The requested access to the file is not allowed, or search permissions are denied for one of the components of path, or the file did not exist and write access to the parent directory is not allowed EEXIST path already exists EFAULT path points outside of the accessible address space of the process EISDIR path refers to a directory and O_DIRECTORY was not provided ENOENT A directory component in path does not exist ENOMEM insufficient kernel memory was available ENOSPC There was insufficient space to create path ENOTDIR path does not refer to a directory and O_DIRECTORY was passed EPERM The filesystem containing path does not support the creation of files EROFS The filesystem containing path is read-only and write access was requested ESRCH Currently not running in a process context (rare, would only happen during kernel init) <!-- @MANEND --> */ pub fn open(path_ptr: *const u8, path_len: usize, flags: usize) -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = try!(contexts.current()); let path_safe = current.get_slice(path_ptr, path_len)?; let path = current.canonicalize(unsafe { str::from_utf8_unchecked(path_safe) }); let resource = try!(::env().open(&path, flags)); let fd = current.next_fd(); unsafe { (*current.files.get()).push(ContextFile { fd: fd, resource: resource, }); } Ok(fd) } pub fn pipe2(fds: *mut usize, _flags: usize) -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = try!(contexts.current()); if fds as usize > 0 { let read = box PipeRead::new(); let write = box PipeWrite::new(&read); unsafe { *fds.offset(0) = current.next_fd(); (*current.files.get()).push(ContextFile { fd: *fds.offset(0), resource: read, }); *fds.offset(1) = current.next_fd(); (*current.files.get()).push(ContextFile { fd: *fds.offset(1), resource: write, }); } Ok(0) } else { Err(Error::new(EFAULT)) } } /** <!-- @MANSTART{sys_read} --> NAME sys_read - read from a file descriptor SYNOPSIS sys_read(fd: usize, buf: *mut u8, count: usize) -> Result<usize>; DESCRIPTION sys_read attempts to read up to count bytes from file descriptor fd into the buffer starting at buf RETURN VALUE On success, Ok(count) is returned, where count is the number of bytes read into buf. On error, Err(err) is returned where err is one of the following errors ERRORS EBADF fd is not a valid open file decriptor EFAULT buf is outside of the accessible address space of the process EINVAL fd refers to a ifle that does not support reading EIO I/O error ESRCH Currently not running in a process context (rare, would only happen during kernel init) <!-- @MANEND --> */ pub fn read(fd: usize, buf: *mut u8, count: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = contexts.current_mut()?; let mut resource = current.get_file_mut(fd)?; if count > 0 { let buf_safe = current.get_slice_mut(buf, count)?; resource.read(buf_safe) } else { Ok(0) } } pub fn rmdir(path_ptr: *const u8, path_len: usize) -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = try!(contexts.current()); let path_safe = current.get_slice(path_ptr, path_len)?; let path_string = current.canonicalize(unsafe { str::from_utf8_unchecked(path_safe) }); ::env().rmdir(&path_string).and(Ok(0)) } pub fn unlink(path_ptr: *const u8, path_len: usize) -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = try!(contexts.current()); let path_safe = current.get_slice(path_ptr, path_len)?; let path_string = current.canonicalize(unsafe { str::from_utf8_unchecked(path_safe) }); ::env().unlink(&path_string).and(Ok(0)) } /** <!-- @MANSTART{sys_write} --> NAME sys_write - read from a file descriptor SYNOPSIS sys_write(fd: usize, buf: *mut u8, count: usize) -> Result<usize>; DESCRIPTION sys_write attempts to read up to count bytes from file descriptor fd into the buffer starting at buf RETURN VALUE On success, Ok(count) is returned, where count is the number of bytes read into buf. On error, Err(err) is returned where err is one of the following errors ERRORS EBADF fd is not a valid open file decriptor EFAULT buf is outside of the accessible address space of the process EINVAL fd refers to a ifle that does not support writing EIO I/O error ENOSPC The filesystem containing fd has no more space EPIPE fd is connected to a pipe or socket whose reading end is closed ESRCH Currently not running in a process context (rare, would only happen during kernel init) <!-- @MANEND --> */ pub fn write(fd: usize, buf: *const u8, count: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = contexts.current_mut()?; let mut resource = current.get_file_mut(fd)?; if count > 0 { let buf_safe = current.get_slice(buf, count)?; resource.write(buf_safe) } else { Ok(0) } }
use super::{Hex, Delta, Direction, Rotation, ORIGIN}; use std::collections::HashMap; use std::ops::Div; /// The delta from the center of one group to the next at the given zoom level. /// /// Zoom levels: /// 0 => single hex /// 1 => seven hex group (six sides plus center) /// 2 => seven groups of zoom 1 /// ... pub fn offset(level: u32) -> Delta { let increment = level.div(2); let scale = (7 as i32).pow(increment); let delta = if level % 2 == 0 { Direction::XY.delta() } else { Delta {dx: 2, dy: -3} }; delta * scale } /// A Gosper island with a given center and zoom level. #[derive(PartialEq, Eq, Copy, Clone, Default, Debug, Hash)] pub struct Island { pub center: Hex, pub level: u32 } impl Island { pub fn split(&self) -> Option<(Island, Vec<(Direction, Island)>)> { if self.level == 0 { return None; } let middle = Island {center: self.center, level: self.level-1}; let split_offset = offset(self.level-1); let side = |n| { let mut center = self.center + split_offset; for _ in 0..n { center = center.rotate_around(self.center, Rotation::CW); } center }; let side_dirs = vec![Direction::XY, Direction::XZ, Direction::YZ, Direction::YX, Direction::ZX, Direction::ZY]; let sides = (0..6).map(|n| Island {center: side(n), level: self.level-1}); Some((middle, side_dirs.into_iter().zip(sides).collect())) } pub fn hexes(&self) -> Box<dyn Iterator<Item=Hex>> { if self.level == 0 { return Box::new(Some(self.center).into_iter()); } let (middle, sides) = self.split().unwrap(); Box::new(middle.hexes().chain(sides.into_iter().flat_map(|(_, s)| s.hexes()))) } } /// Gosper Space Partition: coordinate addressing for nested Gosper islands. #[derive(PartialEq, Eq, Copy, Clone, Default, Debug, Hash)] pub struct GSP { pub coord: Hex, pub level: u32 } fn fold_path(xy: Delta, h: Hex) -> Delta { // TODO: use std::iter::iterate when it's stable let mut delta = xy; let mut deltas: HashMap<Direction, Delta> = HashMap::new(); for dir in [Direction::XY, Direction::XZ, Direction::YZ, Direction::YX, Direction::ZX, Direction::ZY].iter() { deltas.insert(*dir, delta.clone()); delta = delta.rotate(Rotation::CW); } let dir_delta = |dir| *deltas.get(&dir).unwrap(); let steps = h.path(); let trans = steps.into_iter() .map(|(d, m)| dir_delta(d) * (m as i32)); // TODO: use sum() when std::num::Zero is stable let mut ret = Delta {dx: 0, dy: 0}; for d in trans { ret = ret + d; } ret } impl GSP { pub fn map<F>(&self, f: F) -> GSP where F: Fn(&Hex) -> Hex { GSP {coord: f(&self.coord), level: self.level} } pub fn apply<F>(&mut self, f: F) where F: Fn(&mut Hex) { f(&mut self.coord) } pub fn absolute(&self) -> Island { if self.level == 0 { return Island {center: self.coord, level: 0}; } Island {center: ORIGIN + fold_path(offset(self.level), self.coord), level: self.level} } fn delta(&self) -> Delta { if self.level % 2 == 0 { Delta {dx: 3, dy: -2} } else { Delta {dx: 2, dy: -3} } } fn path_delta(&self) -> Delta { fold_path(self.delta(), self.coord) } pub fn smaller(&self) -> Option<GSP> { if self.level == 0 { return None; } Some(GSP {coord: ORIGIN + self.path_delta(), level: self.level-1}) } pub fn larger(&self) -> (GSP, Option<Direction>) { let Delta {dx, dy} = self.path_delta(); let ix = ((dx as f32) / 7.0).round() as i32; let iy = ((dy as f32) / 7.0).round() as i32; let d = Delta {dx: dx - (ix*7), dy: dy - (iy*7)}; let mut ret_dir = None; if d != (Delta {dx: 0, dy: 0}) { let mut ref_d = self.delta(); for dir in [Direction::XY, Direction::XZ, Direction::YZ, Direction::YX, Direction::ZX, Direction::ZY].iter() { if d == ref_d { ret_dir = Some(*dir); break; } ref_d = ref_d.rotate(Rotation::CW); } if ret_dir.is_none() { panic!("Invalid delta {:?}", d); } } (GSP {coord: Hex {x: ix, y: iy}, level: self.level+1}, ret_dir) } } #[cfg(test)] mod tests { use crate::Direction; use crate::test_util::check_eq; use super::{Island, GSP}; use std::collections::HashSet; use quickcheck::quickcheck; use rand::Rng; impl quickcheck::Arbitrary for Island { fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> Self { let center = quickcheck::Arbitrary::arbitrary(g); let level = g.gen_range(0, 5); Island {center: center, level: level} } fn shrink(&self) -> Box<dyn Iterator<Item=Island>> { let level = self.level; let shrink_center = self.center.shrink().map(move |h| Island {center: h, level: level}); if level == 0 { Box::new(shrink_center) } else { Box::new(Some(Island {center: self.center, level: self.level-1}).into_iter().chain(shrink_center)) } } } // Number of hexes in a Gosper island is 7^level #[test] fn island_size() { fn prop(i: Island) -> bool { i.hexes().count() == (7 as usize).pow(i.level) } quickcheck(prop as fn(Island) -> bool); } // All hexes in a Gosper island are unique #[test] fn island_unique() { fn prop(i: Island) -> bool { let hs: HashSet<_> = i.hexes().collect(); hs.len() == (7 as usize).pow(i.level) } quickcheck(prop as fn(Island) -> bool); } impl quickcheck::Arbitrary for GSP { fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> Self { let coord = quickcheck::Arbitrary::arbitrary(g); let level = g.gen_range(0, 5); GSP { coord: coord, level: level } } fn shrink(&self) -> Box<dyn Iterator<Item=GSP>> { let level = self.level; let shrink_coord = self.coord.shrink().map(move |h| GSP {coord: h, level: level}); if level == 0 { Box::new(shrink_coord) } else { Box::new(Some(GSP {coord: self.coord, level: self.level-1}).into_iter().chain(shrink_coord)) } } } fn to_zero(g: GSP) -> GSP { if g.level == 0 { g } else { to_zero(g.smaller().unwrap()) } } // The center of the island from absolute() is the same as the coord when shrunk to zero. #[test] fn gsp_minimal() { fn prop(g: GSP) -> Result<bool, String> { check_eq(g.absolute().center, to_zero(g).coord) } quickcheck(prop as fn(GSP) -> Result<bool, String>); } // Smaller followed by larger is identity. #[test] fn gsp_smaller_larger() { fn prop(g: GSP) -> bool { if g.level == 0 { return true; } let s = g.smaller().unwrap(); let (l, d) = s.larger(); d.is_none() && (l == g) } quickcheck(prop as fn(GSP) -> bool); } // Smaller followed by a single move followed by larger is identity. #[test] fn gsp_smaller_move_larger() { fn prop(g: GSP, d: Direction) -> bool { if g.level == 0 { return true; } let g0 = g.smaller().unwrap(); let g1 = g0.map(|&h| h + d.delta()); let (g2, d2) = g1.larger(); (d2.unwrap() == d) && g2 == g } quickcheck(prop as fn(GSP, Direction) -> bool); } } // mod tests
#![allow(clippy::format_push_string)] use std::io; use std::path::{Component, Path, PathBuf}; use std::time::SystemTime; use actix_web::{dev::ServiceResponse, web::Query, HttpMessage, HttpRequest, HttpResponse}; use bytesize::ByteSize; use comrak::{markdown_to_html, ComrakOptions}; use percent_encoding::{percent_decode_str, utf8_percent_encode}; use regex::Regex; use serde::Deserialize; use strum::{Display, EnumString}; use crate::archive::ArchiveMethod; use crate::auth::CurrentUser; use crate::errors::{self, ContextualError}; use crate::renderer; use self::percent_encode_sets::PATH_SEGMENT; /// "percent-encode sets" as defined by WHATWG specs: /// https://url.spec.whatwg.org/#percent-encoded-bytes mod percent_encode_sets { use percent_encoding::{AsciiSet, CONTROLS}; const BASE: &AsciiSet = &CONTROLS.add(b'%'); pub const QUERY: &AsciiSet = &BASE.add(b' ').add(b'"').add(b'#').add(b'<').add(b'>'); pub const PATH: &AsciiSet = &QUERY.add(b'?').add(b'`').add(b'{').add(b'}'); pub const PATH_SEGMENT: &AsciiSet = &PATH.add(b'/').add(b'\\'); } /// Query parameters #[derive(Deserialize, Default)] pub struct QueryParameters { pub path: Option<PathBuf>, pub sort: Option<SortingMethod>, pub order: Option<SortingOrder>, pub raw: Option<bool>, pub mkdir_name: Option<String>, download: Option<ArchiveMethod>, } /// Available sorting methods #[derive(Deserialize, Clone, EnumString, Display, Copy)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum SortingMethod { /// Sort by name Name, /// Sort by size Size, /// Sort by last modification date (natural sort: follows alphanumerical order) Date, } /// Available sorting orders #[derive(Deserialize, Clone, EnumString, Display, Copy)] pub enum SortingOrder { /// Ascending order #[serde(alias = "asc")] #[strum(serialize = "asc")] Ascending, /// Descending order #[serde(alias = "desc")] #[strum(serialize = "desc")] Descending, } #[derive(PartialEq, Eq)] /// Possible entry types pub enum EntryType { /// Entry is a directory Directory, /// Entry is a file File, } /// Entry pub struct Entry { /// Name of the entry pub name: String, /// Type of the entry pub entry_type: EntryType, /// URL of the entry pub link: String, /// Size in byte of the entry. Only available for EntryType::File pub size: Option<bytesize::ByteSize>, /// Last modification date pub last_modification_date: Option<SystemTime>, /// Path of symlink pointed to pub symlink_info: Option<String>, } impl Entry { fn new( name: String, entry_type: EntryType, link: String, size: Option<bytesize::ByteSize>, last_modification_date: Option<SystemTime>, symlink_info: Option<String>, ) -> Self { Entry { name, entry_type, link, size, last_modification_date, symlink_info, } } /// Returns whether the entry is a directory pub fn is_dir(&self) -> bool { self.entry_type == EntryType::Directory } /// Returns whether the entry is a file pub fn is_file(&self) -> bool { self.entry_type == EntryType::File } } /// One entry in the path to the listed directory pub struct Breadcrumb { /// Name of directory pub name: String, /// Link to get to directory, relative to listed directory pub link: String, } impl Breadcrumb { fn new(name: String, link: String) -> Self { Breadcrumb { name, link } } } pub async fn file_handler(req: HttpRequest) -> actix_web::Result<actix_files::NamedFile> { let path = &req.app_data::<crate::MiniserveConfig>().unwrap().path; actix_files::NamedFile::open(path).map_err(Into::into) } /// List a directory and renders a HTML file accordingly /// Adapted from https://docs.rs/actix-web/0.7.13/src/actix_web/fs.rs.html#564 pub fn directory_listing( dir: &actix_files::Directory, req: &HttpRequest, ) -> io::Result<ServiceResponse> { let extensions = req.extensions(); let current_user: Option<&CurrentUser> = extensions.get::<CurrentUser>(); let conf = req.app_data::<crate::MiniserveConfig>().unwrap(); let serve_path = req.path(); let base = Path::new(serve_path); let random_route_abs = format!("/{}", conf.route_prefix); let abs_uri = http::Uri::builder() .scheme(req.connection_info().scheme()) .authority(req.connection_info().host()) .path_and_query(req.uri().to_string()) .build() .unwrap(); let is_root = base.parent().is_none() || Path::new(&req.path()) == Path::new(&random_route_abs); let encoded_dir = match base.strip_prefix(random_route_abs) { Ok(c_d) => Path::new("/").join(c_d), Err(_) => base.to_path_buf(), } .display() .to_string(); let breadcrumbs = { let title = conf .title .clone() .unwrap_or_else(|| req.connection_info().host().into()); let decoded = percent_decode_str(&encoded_dir).decode_utf8_lossy(); let mut res: Vec<Breadcrumb> = Vec::new(); let mut link_accumulator = format!("{}/", &conf.route_prefix); let mut components = Path::new(&*decoded).components().peekable(); while let Some(c) = components.next() { let name; match c { Component::RootDir => { name = title.clone(); } Component::Normal(s) => { name = s.to_string_lossy().to_string(); link_accumulator .push_str(&(utf8_percent_encode(&name, PATH_SEGMENT).to_string() + "/")); } _ => name = "".to_string(), }; res.push(Breadcrumb::new( name, if components.peek().is_some() { link_accumulator.clone() } else { ".".to_string() }, )); } res }; let query_params = extract_query_parameters(req); let mut entries: Vec<Entry> = Vec::new(); let mut readme: Option<(String, String)> = None; let readme_rx: Regex = Regex::new("^readme([.](md|txt))?$").unwrap(); for entry in dir.path.read_dir()? { if dir.is_visible(&entry) || conf.show_hidden { let entry = entry?; // show file url as relative to static path let file_name = entry.file_name().to_string_lossy().to_string(); let (is_symlink, metadata) = match entry.metadata() { Ok(metadata) if metadata.file_type().is_symlink() => { // for symlinks, get the metadata of the original file (true, std::fs::metadata(entry.path())) } res => (false, res), }; let symlink_dest = (is_symlink && conf.show_symlink_info) .then(|| entry.path()) .and_then(|path| std::fs::read_link(path).ok()) .map(|path| path.to_string_lossy().into_owned()); let file_url = base .join(utf8_percent_encode(&file_name, PATH_SEGMENT).to_string()) .to_string_lossy() .to_string(); // if file is a directory, add '/' to the end of the name if let Ok(metadata) = metadata { if conf.no_symlinks && is_symlink { continue; } let last_modification_date = match metadata.modified() { Ok(date) => Some(date), Err(_) => None, }; if metadata.is_dir() { entries.push(Entry::new( file_name, EntryType::Directory, file_url, None, last_modification_date, symlink_dest, )); } else if metadata.is_file() { entries.push(Entry::new( file_name.clone(), EntryType::File, file_url, Some(ByteSize::b(metadata.len())), last_modification_date, symlink_dest, )); if conf.readme && readme_rx.is_match(&file_name.to_lowercase()) { let ext = file_name.split('.').last().unwrap().to_lowercase(); readme = Some(( file_name.to_string(), if ext == "md" { markdown_to_html( &std::fs::read_to_string(entry.path())?, &ComrakOptions::default(), ) } else { format!("<pre>{}</pre>", &std::fs::read_to_string(entry.path())?) }, )); } } } else { continue; } } } match query_params.sort.unwrap_or(SortingMethod::Name) { SortingMethod::Name => entries.sort_by(|e1, e2| { alphanumeric_sort::compare_str(e1.name.to_lowercase(), e2.name.to_lowercase()) }), SortingMethod::Size => entries.sort_by(|e1, e2| { // If we can't get the size of the entry (directory for instance) // let's consider it's 0b e2.size .unwrap_or_else(|| ByteSize::b(0)) .cmp(&e1.size.unwrap_or_else(|| ByteSize::b(0))) }), SortingMethod::Date => entries.sort_by(|e1, e2| { // If, for some reason, we can't get the last modification date of an entry // let's consider it was modified on UNIX_EPOCH (01/01/19270 00:00:00) e2.last_modification_date .unwrap_or(SystemTime::UNIX_EPOCH) .cmp(&e1.last_modification_date.unwrap_or(SystemTime::UNIX_EPOCH)) }), }; if let Some(SortingOrder::Descending) = query_params.order { entries.reverse() } // List directories first if conf.dirs_first { entries.sort_by_key(|e| !e.is_dir()); } if let Some(archive_method) = query_params.download { if !archive_method.is_enabled(conf.tar_enabled, conf.tar_gz_enabled, conf.zip_enabled) { return Ok(ServiceResponse::new( req.clone(), HttpResponse::Forbidden() .content_type(mime::TEXT_PLAIN_UTF_8) .body("Archive creation is disabled."), )); } log::info!( "Creating an archive ({extension}) of {path}...", extension = archive_method.extension(), path = &dir.path.display().to_string() ); let file_name = format!( "{}.{}", dir.path.file_name().unwrap().to_str().unwrap(), archive_method.extension() ); // We will create the archive in a separate thread, and stream the content using a pipe. // The pipe is made of a futures channel, and an adapter to implement the `Write` trait. // Include 10 messages of buffer for erratic connection speeds. let (tx, rx) = futures::channel::mpsc::channel::<io::Result<actix_web::web::Bytes>>(10); let pipe = crate::pipe::Pipe::new(tx); // Start the actual archive creation in a separate thread. let dir = dir.path.to_path_buf(); let skip_symlinks = conf.no_symlinks; std::thread::spawn(move || { if let Err(err) = archive_method.create_archive(dir, skip_symlinks, pipe) { log::error!("Error during archive creation: {:?}", err); } }); Ok(ServiceResponse::new( req.clone(), HttpResponse::Ok() .content_type(archive_method.content_type()) .append_header(archive_method.content_encoding()) .append_header(("Content-Transfer-Encoding", "binary")) .append_header(( "Content-Disposition", format!("attachment; filename={file_name:?}"), )) .body(actix_web::body::BodyStream::new(rx)), )) } else { Ok(ServiceResponse::new( req.clone(), HttpResponse::Ok().content_type(mime::TEXT_HTML_UTF_8).body( renderer::page( entries, readme, &abs_uri, is_root, query_params, &breadcrumbs, &encoded_dir, conf, current_user, ) .into_string(), ), )) } } pub fn extract_query_parameters(req: &HttpRequest) -> QueryParameters { match Query::<QueryParameters>::from_query(req.query_string()) { Ok(Query(query_params)) => query_params, Err(e) => { let err = ContextualError::ParseError("query parameters".to_string(), e.to_string()); errors::log_error_chain(err.to_string()); QueryParameters::default() } } }
fn main() { let world_dir: &str = "World"; let world_src: &str = &format!("{}/{}", world_dir, "src"); let _world_header: &str = &format!("{}/{}", world_src, "world"); let file_names = [ "cheaptrick", "codec", "common", "d4c", "dio", "fft", "harvest", "matlabfunctions", "stonemask", "synthesis", "synthesisrealtime" ]; for file_name in &file_names { cc::Build::new() .cpp(true) // .warnings(true) .flag("-O1") .flag("-w") .file(&format!("{}/{}.cpp", world_src, file_name)) .include(world_src) .compile(&format!("{}", file_name)); } }
extern crate rand; use std::io; use rand::Rng; fn main() { println!("Rust Acid Metal"); // rock(rust), paper(acid), scissors(metal) println!("1 - Rust, 2 - Acid, 3 - Metal"); println!("Rust beats metal, acid beats rust, and metal beats acid"); println!(""); println!("First to 5 points wins the battle"); println!(""); let mut p_points = 0; let mut c_points = 0; loop { println!("Please input your throw."); // get player's throw let mut p_throw = String::new(); io::stdin().read_line(&mut p_throw) .ok() .expect("Failed to read line"); let p_throw: u32 = match p_throw.trim().parse() { Ok(num) => num, Err(_) => continue, }; // throw is out of range, so ignore if p_throw < 1 || p_throw > 3 { continue; } // get computer's throw let c_throw = rand::thread_rng().gen_range(1, 3); println!("Plyr threw: {}", p_throw); println!("Comp threw: {}", c_throw); // parse moves if p_throw == c_throw { println!("Player and Computer throw the same thing; TIE!"); } else if p_throw == 1 && c_throw == 2 { println!("Player's rust is dissolved by Computer's acid; LOSE!"); c_points += 1; } else if p_throw == 1 && c_throw == 3 { println!("Player rust takes over Computer's metal: WIN!"); p_points += 1; } else if p_throw == 2 && c_throw == 1 { println!("Player's acid dissolves Computer's acid; WIN!"); p_points += 1; } else if p_throw == 2 && c_throw == 3 { println!("Player's acid is beaten by Computer's metal; LOSE!"); c_points += 1; } else if p_throw == 3 && c_throw == 1 { println!("Player's metal is taken over by Computer's rust; LOSE!"); c_points += 1; } else if p_throw == 3 && c_throw == 2 { println!("Player's metal beats Computer's acid; WIN!"); p_points += 1; } println!("Player {}, Computer {}", p_points, c_points); if p_points >= 5 { println!("Player wins the whole thing! WOO!"); break; } if c_points >= 5 { println!("Player loses to a random number generator! :-("); break; } } println!("Thank you for playing Rust Acid Metal!"); } #[test] fn it_works() { assert!(true); }
// 定期更新discovery. // 基于left-right实现无锁并发更新 // use super::Discover; use left_right::{Absorb, WriteHandle}; use std::io::{Error, ErrorKind, Result}; use std::path::PathBuf; use std::time::Duration; use tokio::fs::File; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::time::{interval, Interval}; use super::ServiceName; unsafe impl<D, T> Send for AsyncServiceUpdate<D, T> where T: Absorb<(String, String)> {} unsafe impl<D, T> Sync for AsyncServiceUpdate<D, T> where T: Absorb<(String, String)> {} pub(crate) struct AsyncServiceUpdate<D, T> where T: Absorb<(String, String)>, { service: ServiceName, discovery: D, w: WriteHandle<T, (String, String)>, cfg: String, sign: String, interval: Interval, snapshot: PathBuf, // 本地快照存储的文件名称 } impl<D, T> AsyncServiceUpdate<D, T> where T: Absorb<(String, String)>, { pub fn new( service: String, discovery: D, writer: WriteHandle<T, (String, String)>, tick: Duration, snapshot: String, ) -> Self { let snapshot = if snapshot.len() == 0 { "/tmp/breeze/services/snapshot".to_owned() } else { snapshot }; let mut path = PathBuf::from(snapshot); path.push(&service); Self { service: ServiceName::from(service), discovery: discovery, w: writer, cfg: Default::default(), sign: Default::default(), interval: interval(tick), snapshot: path, } } fn path(&self) -> PathBuf { let mut pb = PathBuf::new(); pb.push(&self.snapshot); pb.push(self.service.name()); pb } // 如果当前配置为空,则从snapshot加载 async fn load_from_snapshot(&mut self) -> Result<()> where D: Discover + Send + Unpin, { if self.cfg.len() != 0 { return Ok(()); } let mut contents = vec![]; File::open(&self.path()) .await? .read_to_end(&mut contents) .await?; let mut contents = String::from_utf8(contents) .map_err(|_e| Error::new(ErrorKind::Other, "not a valid utfi file"))?; // 内容的第一行是签名,第二行是往后是配置 let idx = contents.find('\n').unwrap_or(0); let cfg = contents.split_off(idx); self.cfg = cfg; self.sign = contents; self.w.append((self.cfg.clone(), self.service.to_owned())); self.w.publish(); Ok(()) } async fn dump_to_snapshot(&mut self) -> Result<()> { let path = self.snapshot.as_path(); if let Some(parent) = path.parent() { if !parent.exists() { tokio::fs::create_dir_all(parent).await?; } } let mut file = File::create(path).await?; file.write_all(self.sign.as_bytes()).await?; file.write_all(self.cfg.as_bytes()).await?; Ok(()) } async fn load_from_discovery(&mut self) -> Result<()> where D: Discover + Send + Unpin, { use super::Config; match self .discovery .get_service(&self.service, &self.sign) .await? { Config::NotChanged => Ok(()), Config::NotFound => Err(Error::new( ErrorKind::NotFound, format!("service not found. name:{}", self.service.name()), )), Config::Config(cfg, sig) => { if self.cfg != cfg || self.sign != sig { self.cfg = cfg; self.sign = sig; self.w.append((self.cfg.clone(), self.service.to_owned())); self.w.publish(); if let Err(e) = self.dump_to_snapshot().await { log::warn!( "failed to dump to snapshot. path:{:?} {:?}", self.snapshot, e ); }; } Ok(()) } } } pub async fn start_watch(&mut self) where D: Discover + Send + Unpin, { let _r = self.load_from_snapshot().await; if self.cfg.len() == 0 { let r = self.load_from_discovery().await; self.check(r); } loop { self.interval.tick().await; let r = self.load_from_discovery().await; self.check(r); } } fn check(&self, r: Result<()>) { match r { Ok(_) => {} Err(e) => { log::warn!( "load service config error. service:{} error:{:?}", self.service.name(), e ); } } } }
// Copyright 2023 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::os::raw::{c_void, c_char}; use base::{CFAllocatorRef, CFTypeID, Boolean, CFIndex, CFOptionFlags, CFRange}; use locale::{CFCalendarIdentifier, CFLocaleRef}; use timezone::CFTimeZoneRef; use date::{CFAbsoluteTime, CFTimeInterval}; #[repr(C)] pub struct __CFCalendar(c_void); pub type CFCalendarRef = *mut __CFCalendar; pub type CFCalendarUnit = CFOptionFlags; pub const kCFCalendarUnitEra: CFCalendarUnit = 1 << 1; pub const kCFCalendarUnitYear: CFCalendarUnit = 1 << 2; pub const kCFCalendarUnitMonth: CFCalendarUnit = 1 << 3; pub const kCFCalendarUnitDay: CFCalendarUnit = 1 << 4; pub const kCFCalendarUnitHour: CFCalendarUnit = 1 << 5; pub const kCFCalendarUnitMinute: CFCalendarUnit = 1 << 6; pub const kCFCalendarUnitSecond: CFCalendarUnit = 1 << 7; pub const kCFCalendarUnitWeek: CFCalendarUnit = 1 << 8; // deprecated since macos 10.10 pub const kCFCalendarUnitWeekday: CFCalendarUnit = 1 << 9; pub const kCFCalendarUnitWeekdayOrdinal: CFCalendarUnit = 1 << 10; pub const kCFCalendarUnitQuarter: CFCalendarUnit = 1 << 11; pub const kCFCalendarUnitWeekOfMonth: CFCalendarUnit = 1 << 12; pub const kCFCalendarUnitWeekOfYear: CFCalendarUnit = 1 << 13; pub const kCFCalendarUnitYearForWeekOfYear: CFCalendarUnit = 1 << 14; pub const kCFCalendarComponentsWrap: CFOptionFlags = 1 << 0; extern { /* * CFCalendar.h */ /* Creating a Calendar */ pub fn CFCalendarCopyCurrent() -> CFCalendarRef; pub fn CFCalendarCreateWithIdentifier(allocator: CFAllocatorRef, identifier: CFCalendarIdentifier) -> CFCalendarRef; /* Calendrical Calculations */ pub fn CFCalendarAddComponents(identifier: CFCalendarIdentifier, /* inout */ at: *mut CFAbsoluteTime, options: CFOptionFlags, componentDesc: *const char, ...) -> Boolean; pub fn CFCalendarComposeAbsoluteTime(identifier: CFCalendarIdentifier, /* out */ at: *mut CFAbsoluteTime, componentDesc: *const c_char, ...) -> Boolean; pub fn CFCalendarDecomposeAbsoluteTime(identifier: CFCalendarIdentifier, at: CFAbsoluteTime, componentDesc: *const c_char, ...) -> Boolean; pub fn CFCalendarGetComponentDifference(identifier: CFCalendarIdentifier, startingAT: CFAbsoluteTime, resultAT: CFAbsoluteTime, options: CFOptionFlags, componentDesc: *const c_char, ...) -> Boolean; /* Getting Ranges of Units */ pub fn CFCalendarGetRangeOfUnit(identifier: CFCalendarIdentifier, smallerUnit: CFCalendarUnit, biggerUnit: CFCalendarUnit, at: CFAbsoluteTime) -> CFRange; pub fn CFCalendarGetOrdinalityOfUnit(identifier: CFCalendarIdentifier, smallerUnit: CFCalendarUnit, biggerUnit: CFCalendarUnit, at: CFAbsoluteTime) -> CFIndex; pub fn CFCalendarGetTimeRangeOfUnit(identifier: CFCalendarIdentifier, unit: CFCalendarUnit, at: CFAbsoluteTime, startp: *mut CFAbsoluteTime, tip: *mut CFTimeInterval) -> Boolean; pub fn CFCalendarGetMaximumRangeOfUnit(identifier: CFCalendarIdentifier, unit: CFCalendarUnit) -> CFRange; pub fn CFCalendarGetMinimumRangeOfUnit(identifier: CFCalendarIdentifier, unit: CFCalendarUnit) -> CFRange; /* Getting and Setting the Time Zone */ pub fn CFCalendarCopyTimeZone(identifier: CFCalendarIdentifier) -> CFTimeZoneRef; pub fn CFCalendarSetTimeZone(identifier: CFCalendarIdentifier, tz: CFTimeZoneRef); /* Getting the Identifier */ pub fn CFCalendarGetIdentifier(identifier: CFCalendarIdentifier) -> CFCalendarIdentifier; /* Getting and Setting the Locale */ pub fn CFCalendarCopyLocale(identifier: CFCalendarIdentifier) -> CFLocaleRef; pub fn CFCalendarSetLocale(identifier: CFCalendarIdentifier, locale: CFLocaleRef); /* Getting and Setting Day Information */ pub fn CFCalendarGetFirstWeekday(identifier: CFCalendarIdentifier) -> CFIndex; pub fn CFCalendarSetFirstWeekday(identifier: CFCalendarIdentifier, wkdy: CFIndex); pub fn CFCalendarGetMinimumDaysInFirstWeek(identifier: CFCalendarIdentifier) -> CFIndex; pub fn CFCalendarSetMinimumDaysInFirstWeek(identifier: CFCalendarIdentifier, mwd: CFIndex); /* Getting the Type ID */ pub fn CFCalendarGetTypeID() -> CFTypeID; }
//! Tide-fs contains extensions for the Tide web-framework to serve files //! or whole directories from your file-system. Tide-fs provides a `ServeDir` //! and a `ServeFile` endpoint. //! //! `ServeFile` serves a single file on a single route; //! ```rust //! # use tide::{Request, Result}; //! # pub async fn endpoint(_: Request<()>) -> Result { //! # todo!() //! # } //! use tide_fs::prelude::*; //! //! # fn main() -> std::io::Result<()> { //! let mut app = tide::new(); //! app.at("index.html").get(ServeFile::init("files/index.html")?); //! # Ok(()) //! # } //! ``` //! //! //! `ServeDir` maps a section of a route to files in a directory //! ```rust //! # use tide::{Request, Result}; //! # pub async fn endpoint(_: Request<()>) -> Result { //! # todo!() //! # } //! use tide_fs::prelude::*; //! //! # fn main() -> std::io::Result<()> { //! let mut app = tide::new(); //! app.at("static/css/*path").get(ServeDir::init("static_content/css/", "path")?); //! # Ok(()) //! # } //! ``` //! The ServeDir endpoint requires you to define a route with a parameter //! the value of which is then mapped to files inside the directory that is served. use std::{io, path::Path}; use prelude::{ServeDir, ServeFile}; use tide::Route; pub mod serve_dir; pub mod serve_file; pub mod prelude { pub use crate::serve_dir::ServeDir; pub use crate::serve_file::ServeFile; pub use crate::TideFsExt; } pub trait TideFsExt { fn serve_file(&mut self, file: impl AsRef<Path>) -> io::Result<()>; fn serve_dir(&mut self, dir: impl AsRef<Path>) -> io::Result<()>; } impl<'a, State: Clone + Send + Sync + 'static> TideFsExt for Route<'a, State> { fn serve_file(&mut self, file: impl AsRef<Path>) -> io::Result<()> { self.get(ServeFile::init(file)?); Ok(()) } fn serve_dir(&mut self, dir: impl AsRef<Path>) -> io::Result<()> { self.at("*path").get(ServeDir::init(dir, "path")?); Ok(()) } }
use ggez::{ Context, GameResult, graphics::{ Mesh, Rect, Color }, nalgebra::Point2, }; use crate::text::Text; pub struct Button { text: Text, border: Mesh, hitbox: Rect, colors: (Color, Color), border_thickness: f32, hovered: bool } impl Button { pub fn new(ctx: &mut Context, width: f32, height: f32, x: f32, y: f32, color_when_not_hovered: Color, color_when_hovered: Color, thickness: f32, text: String) -> GameResult<Button> { let hitbox = Rect::new(x, y, width, height); let border = Mesh::new_rectangle( ctx, ggez::graphics::DrawMode::stroke(thickness), Rect::new(0.0, 0.0, hitbox.w, hitbox.h), color_when_not_hovered )?; let mut inside_text = Text::new( ctx, text, "/Fonts/arial_narrow_7.ttf".to_string(), (width + height) / 10.0, color_when_not_hovered, )?; inside_text.set_pos(Point2::new( (hitbox.x + (hitbox.w / 2.0)) - (inside_text.width(ctx) / 2.0), (hitbox.y + (hitbox.h / 2.0)) - (inside_text.height(ctx) / 2.0) )); let button = Button { text: inside_text, border: border, hitbox: hitbox, colors: (color_when_not_hovered, color_when_hovered), border_thickness: thickness, hovered: false }; Ok(button) } pub fn draw(&self, ctx: &mut Context) -> GameResult { ggez::graphics::draw(ctx, &self.border, (Point2::new(self.hitbox.x, self.hitbox.y),))?; self.text.draw(ctx)?; Ok(()) } pub fn mouse_motion_event(&mut self, ctx: &mut Context, x: f32, y: f32) { if self.contains(x, y) && !self.hovered { self.hovered = true; self.text.change_color(self.colors.1); self.border = Mesh::new_rectangle( ctx, ggez::graphics::DrawMode::stroke(self.border_thickness), Rect::new(0.0, 0.0, self.hitbox.w, self.hitbox.h), self.colors.1 ).unwrap(); } else if !self.contains(x, y) && self.hovered { self.hovered = false; self.text.change_color(self.colors.0); self.border = Mesh::new_rectangle( ctx, ggez::graphics::DrawMode::stroke(self.border_thickness), Rect::new(0.0, 0.0, self.hitbox.w, self.hitbox.h), self.colors.0 ).unwrap(); } } pub fn contains(&self, x: f32, y: f32) -> bool { self.hitbox.contains(ggez::mint::Point2 { x: x, y: y }) } pub fn width(&self) -> f32 { self.hitbox.w } pub fn height(&self) -> f32 { self.hitbox.h } pub fn set_pos(&mut self, ctx: &mut Context, x: f32, y: f32) { self.hitbox.x = x; self.hitbox.y = y; self.text.set_pos(Point2::new( (self.hitbox.x + (self.hitbox.w / 2.0)) - (self.text.width(ctx) / 2.0), (self.hitbox.y + (self.hitbox.h / 2.0)) - (self.text.height(ctx) / 2.0) )); } pub fn set_text_scale(&mut self, scale: f32) { self.text.change_scale(scale); } pub fn get_text_pos(&self) -> Point2<f32> { self.text.get_pos() } pub fn get_border(&self) -> &Mesh { &self.border } pub fn get_pos(&self) -> Point2<f32> { Point2::new(self.hitbox.x, self.hitbox.y) } pub fn get_hitbox(&self) -> Rect { self.hitbox } pub fn get_text(&self) -> &Text { &self.text } }
//compile: "rustc libworld.rs" #[link(name = "libworld", vers = "1.0")]; #[crate_type = "lib"]; pub mod libearth{ //now we are in the world::earth namespace. pub fn libexplore() -> &str { "libworld" } }
//Receives calls from routes, decides on what service needs to do use crate::database::DbConn; use rocket_contrib::json::Json; use rocket_contrib::uuid::Uuid; use crate::api::components::consumer::model::Consumer; use crate::api::components::consumer::service; // Generates a new uuid, assings it to the consumer and passes it to service pub fn construct_consumer(mut consumer : Consumer, connection : DbConn) -> Consumer { let new_uuid = uuid::Uuid::new_v4(); consumer.set_id(new_uuid); service::insert_new_consumer(consumer, connection) } pub fn get_all_consumers(connection : DbConn) -> Vec<Consumer> { service::get_all_consumers(connection) } pub fn get_consumer_by_id(uuid : Uuid, connection : DbConn) -> Consumer { //This UUID type is from the crate rocket_contrib::uuid and uses the general uuid crate v0.7.4 let bytes = uuid.as_bytes(); //This UUID type is from the general uuid crate and is on v0.6.5 because of a diesel dependency let other_uuid = uuid::Uuid::from_bytes(bytes).expect("Could not convert uuid v0.7.4 to v0.6.5"); service::get_consumer_by_id(other_uuid, connection) } pub fn update_consumer(body : Json<Consumer>, connection : DbConn) -> Json<Consumer> { Json(service::update_consumer(body.into_inner(), connection)) } pub fn delete_consumer(uuid : Uuid, connection : DbConn) -> Json<String> { let bytes = uuid.as_bytes(); let other_uuid = uuid::Uuid::from_bytes(bytes).expect("Could not convert uuid v0.7.4 to v0.6.5"); let num_deleted = service::delete_consumer(other_uuid, connection); let response = format!("num_deleted: {}", num_deleted); Json(response) }
use crate::prelude::*; trait FacilityBounds = Clone + Eq + Ord + std::hash::Hash; fn solve<const N: usize>(input: Vec<Vec<Module>>) -> Result<usize> where [Element; N]: Default, [bool; N]: Default, { use std::{collections::VecDeque, rc::Rc}; let facility: Facility<[Element; N]> = Facility::from_input(input)?; struct TrackedFacility<E: FacilityBounds> { parent: Option<Rc<Self>>, current: Facility<E>, } impl<const N: usize> TrackedFacility<[Element; N]> where [Element; N]: Default, [bool; N]: Default, { pub fn depth(&self) -> usize { match self.parent.as_ref() { Some(parent) => parent.depth() + 1, None => 0, } } } let mut visited = HashSet::new(); visited.insert(facility.clone()); let mut bfs = VecDeque::new(); bfs.push_back(Rc::new(TrackedFacility { parent: None, current: facility, })); while let Some(tracked) = bfs.pop_front() { for facility in tracked.current.next_configurations() { if !visited.insert(facility.clone()) { continue; } let child = Rc::new(TrackedFacility { parent: Some(Rc::clone(&tracked)), current: facility, }); if child.current.is_solved() { let depth = child.depth(); // let mut current = Some(&child); // let mut current_depth = depth as isize; // while let Some(tracked) = current { // println!("depth {}\n{:#?}\n", current_depth, tracked.current); // current_depth -= 1; // current = tracked.parent.as_ref(); // } return Ok(depth); } bfs.push_back(child); } } Err(anyhow!("no solution found")) } pub fn pt1(input: Vec<Vec<Module>>) -> Result<usize> { solve::<5>(input) } pub fn pt2(mut input: Vec<Vec<Module>>) -> Result<usize> { input[0].push(Module::Generator("elerium")); input[0].push(Module::Microchip("elerium")); input[0].push(Module::Generator("dilithium")); input[0].push(Module::Microchip("dilithium")); solve::<7>(input) } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash)] #[repr(packed)] struct Element(u8); impl Element { #[inline(always)] fn generator(&self) -> u8 { self.0 >> 4 } #[inline(always)] fn microchip(&self) -> u8 { self.0 & 0x0f } #[inline(always)] fn move_generator(&mut self, new_floor: u8) { debug_assert!(new_floor & 0xf0 == 0); self.0 = (self.0 & 0x0f) | (new_floor << 4); } #[inline(always)] fn move_microchip(&mut self, new_floor: u8) { debug_assert!(new_floor & 0xf0 == 0); self.0 = (self.0 & 0xf0) | new_floor; } } const FLOOR_COUNT: u8 = 4; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] struct Facility<E: FacilityBounds> { elements: E, elevator_position: u8, } impl<const N: usize> Facility<[Element; N]> where [Element; N]: Default, [bool; N]: Default, { fn from_input(input: Vec<Vec<Module>>) -> Result<Self> { assert!(N <= 8); if input.len() != FLOOR_COUNT as usize { return Err(anyhow!("invalid floor count")); } let mut element_map = HashMap::new(); for (floor_idx, floor) in input.into_iter().rev().enumerate() { for module in floor { let elem_map_len = element_map.len(); let value = element_map .entry(module.name()) .or_insert((elem_map_len, None, None)); let opt = match module { Module::Generator(_) => &mut value.1, Module::Microchip(_) => &mut value.2, }; if let Some(previous_floor) = opt { return Err(anyhow!( "duplicate module {:?} (floors {} and {})", module, FLOOR_COUNT as usize - floor_idx, FLOOR_COUNT as usize - *previous_floor )); } *opt = Some(floor_idx); } } if element_map.len() != N { return Err(anyhow!( "expected {} elements, got {}", N, element_map.len() )); } if !element_map .values() .all(|(_, a, b)| a.is_some() && b.is_some()) { return Err(anyhow!( "modules must be matching generator & microchip pairs" )); } let mut elements: [Element; N] = Default::default(); for (_, (elem_idx, generator_floor, microchip_floor)) in element_map { elements[elem_idx].move_generator(generator_floor.unwrap() as u8); elements[elem_idx].move_microchip(microchip_floor.unwrap() as u8); } let mut facility = Facility { elements, elevator_position: FLOOR_COUNT - 1, }; facility.normalize(); if !facility.is_safe_configuration() { return Err(anyhow!("unsafe starting conditions")); } Ok(facility) } fn normalize(&mut self) { self.elements.sort_unstable() } fn is_solved(&self) -> bool { self.elements.iter().all(|e| e.0 == 0) } fn is_safe_configuration(&self) -> bool { let mut has_generator: [bool; FLOOR_COUNT as usize] = Default::default(); let mut has_unpaired_microchip: [bool; FLOOR_COUNT as usize] = Default::default(); for elem in &self.elements { let generator_floor = elem.generator(); let microchip_floor = elem.microchip(); has_generator[elem.generator() as usize] = true; if generator_floor != microchip_floor { has_unpaired_microchip[microchip_floor as usize] = true; } } (0..FLOOR_COUNT as usize).all(|i| !has_generator[i] || !has_unpaired_microchip[i]) } fn next_configurations<'s>(&'s self) -> impl Iterator<Item = Facility<[Element; N]>> + 's { use std::iter::ExactSizeIterator; #[derive(Clone, Copy)] struct NextFloors { a: u8, b: u8, l: u8, c: u8, } impl Iterator for NextFloors { type Item = u8; fn next(&mut self) -> Option<Self::Item> { if self.c >= self.l { return None; } self.c += 1; Some(if self.c == 1 { self.a } else { self.b }) } fn size_hint(&self) -> (usize, Option<usize>) { let l = self.len(); (l, Some(l)) } } impl ExactSizeIterator for NextFloors { fn len(&self) -> usize { (self.l - self.c) as usize } } #[rustfmt::skip] let next_floors = // if we cannot or shouldn't move down if self.elevator_position == FLOOR_COUNT - 1 { if self.elevator_position == 0 { NextFloors { a: 0, b: 0, l: 0, c: 0 } } else { NextFloors { a: self.elevator_position - 1, b: 0, l: 1, c: 0 } } } else { if self.elevator_position == 0 { NextFloors { a: self.elevator_position + 1, b: 0, l: 1, c: 0 } } else { NextFloors { a: self.elevator_position - 1, b: self.elevator_position + 1, l: 2, c: 0 } } }; #[derive(Clone, Copy, PartialEq, Eq)] enum Moveable { Microchip(u8), Generator(u8), } let elevator_position = self.elevator_position; let moveable_items = self .elements .iter() .enumerate() .flat_map(move |(idx, elem)| { let idx = idx as u8; let mut array: ArrayVec<Moveable, 2> = ArrayVec::new(); unsafe { if elem.generator() == elevator_position { array.push_unchecked(Moveable::Generator(idx)); } if elem.microchip() == elevator_position { array.push_unchecked(Moveable::Microchip(idx)); } } array.into_iter() }); let moveable_pairs = moveable_items .clone() .enumerate() .flat_map(move |(count, a)| { repeat(None) .take(1) .chain(moveable_items.clone().skip(count + 1).map(Option::Some)) .map(move |b| (a, b)) }); moveable_pairs .flat_map(move |(a, b)| next_floors.map(move |f| (a, b, f))) .filter_map(move |(a, b, next_floor)| { let mut new = self.clone(); new.elevator_position = next_floor; #[rustfmt::skip] match a { Moveable::Generator(idx) => new.elements[idx as usize].move_generator(next_floor), Moveable::Microchip(idx) => new.elements[idx as usize].move_microchip(next_floor), } if let Some(b) = b { #[rustfmt::skip] match b { Moveable::Generator(idx) => new.elements[idx as usize].move_generator(next_floor), Moveable::Microchip(idx) => new.elements[idx as usize].move_microchip(next_floor), } } if new.is_safe_configuration() { new.normalize(); Some(new) } else { None } }) } } impl Debug for Element { fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { write!(fmt, "G({})xM({})", self.generator(), self.microchip()) } } pub fn parse(s: &str) -> IResult<&str, Vec<Vec<Module>>> { use parsers::*; map_res( fold_many1( delimited( tag("The "), pair( terminated( map_res(alpha1, |s: &str| { Ok(match s { "first" => 1, "second" => 2, "third" => 3, "fourth" => 4, _ => return Err(()), }) }), tag(" floor contains "), ), alt(( map(tag("nothing relevant"), |_| Vec::new()), separated_list1( alt((tag(", and "), tag(" and "), tag(", "))), alt(( map( delimited(tag("a "), alpha1, tag("-compatible microchip")), Module::Microchip, ), map( delimited(tag("a "), alpha1, tag(" generator")), Module::Generator, ), )), ), )), ), terminated(char('.'), opt(line_ending)), ), || HashMap::new(), |mut acc, (floor, modules)| { acc.insert(floor, modules); acc }, ), |mut layout| { if layout.len() != FLOOR_COUNT as usize { return Err(anyhow!("expected {} floors", FLOOR_COUNT)); } let mut res = Vec::with_capacity(FLOOR_COUNT as usize); for i in 1..=FLOOR_COUNT as usize { let v = layout .get_mut(&i) .ok_or_else(|| anyhow!("expected floors 1 through {}", FLOOR_COUNT))?; res.push(Vec::new()); std::mem::swap(&mut res[i - 1], v); } Ok(res) }, )(s) } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)] pub enum Module<'s> { Generator(&'s str), Microchip(&'s str), } impl<'s> Module<'s> { fn name(&self) -> &'s str { match self { Module::Generator(s) => s, Module::Microchip(s) => s, } } } #[test] fn day11() -> Result<()> { fn solve_2(input: Vec<Vec<Module>>) -> Result<usize> { solve::<2>(input) } test_part!(parse, solve_2, "\ The first floor contains a hydrogen-compatible microchip and a lithium-compatible microchip. The second floor contains a hydrogen generator. The third floor contains a lithium generator. The fourth floor contains nothing relevant." => 11); Ok(()) }
pub mod traits; use std::fmt; use std::iter; #[derive(Clone, Hash, Eq, PartialEq)] pub struct BitSet { inner: Box<[u64]> } impl BitSet { #[inline] pub fn new(n: usize) -> BitSet { BitSet { inner: iter::repeat(0).take(BitSet::calc_inner_len(n)).collect() } } #[inline] pub fn from_slice(v: &[bool]) -> BitSet { let n = v.len(); let mut ret = BitSet::new(n); unsafe { for i in 0..n { if *v.get_unchecked(i) { ret.set_unchecked(i); } } } ret } #[inline] pub fn clear_all(&mut self) { for x in self.inner.iter_mut() { *x = 0; } } #[inline] pub fn or(&mut self, other: &BitSet) -> bool { let mut changed = false; for (x, y) in self.inner.iter_mut().zip(other.inner.iter()) { let ox = *x; *x |= *y; changed |= *x != ox; } changed } // it is possible that the n is out of range that `new` specified // no check, for my convenience #[inline] pub fn test(&self, n: usize) -> bool { ((self.inner[n >> 6] >> (n & 63)) & 1) != 0 } #[inline] pub fn any(&self) -> bool { self.inner.iter().any(|&x| x != 0) } #[inline] pub fn set(&mut self, n: usize) { self.inner[n >> 6] |= (1 as u64) << (n & 63); } #[inline] pub fn clear(&mut self, n: usize) { self.inner[n >> 6] &= !((1 as u64) << (n & 63)); } #[inline] pub fn inner_len(&self) -> usize { self.inner.len() } #[inline] pub const fn calc_inner_len(n: usize) -> usize { (n + 63) >> 6 } #[inline] pub fn as_ptr(&self) -> *const u64 { self.inner.as_ptr() } #[inline] pub fn as_mut_ptr(&mut self) -> *mut u64 { self.inner.as_mut_ptr() } #[inline] pub unsafe fn test_unchecked(&self, n: usize) -> bool { BitSet::test_raw(self.inner.as_ptr(), n) } #[inline] pub unsafe fn test_raw(x: *const u64, n: usize) -> bool { ((*x.add(n >> 6) >> (n & 63)) & 1) != 0 } #[inline] pub unsafe fn set_unchecked(&mut self, n: usize) { BitSet::set_raw(self.inner.as_mut_ptr(), n) } #[inline] pub unsafe fn set_raw(x: *mut u64, n: usize) { *x.add(n >> 6) |= (1 as u64) << (n & 63); } #[inline] pub unsafe fn clear_unchecked(&mut self, n: usize) { BitSet::clear_raw(self.inner.as_mut_ptr(), n); } #[inline] pub unsafe fn clear_raw(x: *mut u64, n: usize) { *x.add(n >> 6) &= !((1 as u64) << (n & 63)); } #[inline] pub unsafe fn or_raw(mut x: *mut u64, mut y: *const u64, len: usize) -> bool { let mut changed = false; for _ in 0..len { let ox = *x; *x |= *y; changed |= *x != ox; x = x.add(1); y = y.add(1); } changed } } impl fmt::Debug for BitSet { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { let mut l = f.debug_list(); for i in 0..self.inner.len() * 64 { if self.test(i) { l.entry(&i); } } l.finish()?; Ok(()) } }
use ::ast::{StringlyTyped, StringlyTypedInner, RustComponent}; /// A StringlyTyped tree that uses Rust's semantics for its components. #[allow(dead_code)] // False positive: https://github.com/rust-lang/rust/issues/47131 type StringlyTypedRust<'s> = StringlyTyped<'s, RustComponent>; type Attributes<'s> = Option<StringlyTypedInner<'s, RustComponent>>; impl<'s> StringlyTypedRust<'s> { /// Convert a StringlyTypedRust tree into a string of Rust code. /// /// Panics if the tree does not match the grammar of the language. pub(crate) fn to_rust_string(&self) -> String { self.to_mod_item_string() } } /// Helper functions for `to_rust_string`. impl<'s> StringlyTypedRust<'s> { fn to_mod_item_string(&self) -> String { match self.component { RustComponent::Const => self.to_const_string(), RustComponent::Mod => self.to_mod_string(), RustComponent::Static => self.to_static_string(), _ => unimplemented!("Non-item at top level. Only items are supported due to procedural macro limitations.") } } // Precondition: self.component == Mod fn to_mod_string(&self) -> String { let inners = self.unwrap_inners(); match inners.len() { 0 => panic!("Module must either take an ident or an ident followed by items"), 1 => format!("mod {};", inners[0].to_ident_string()), _ => { let mut inners_iter = inners.iter(); let mod_name = inners_iter.next().unwrap().to_ident_string(); let items = inners_iter.map(|item| item.to_mod_item_string()).collect::<Vec<_>>().join(""); format!("mod {} {{ {} }}", mod_name, items) } } } fn to_const_string(&self) -> String { let mut inner_iter = self.unwrap_inners().iter(); let ident = inner_iter.next().unwrap(); let ty = inner_iter.next().unwrap(); let expr = inner_iter.next().unwrap(); format!("{} const {}: {} = {};", to_attributes_string(&self.quasi), ident.unwrap_str(), ty.to_ty_string(), expr.to_expr_string()) } fn to_static_string(&self) -> String { let mut inner_iter = self.unwrap_inners().iter(); let ident = inner_iter.next().unwrap(); let ty = inner_iter.next().unwrap(); let expr = inner_iter.next().unwrap(); assert_eq!(inner_iter.next(), None); format!("{} static {}: {} = {};", to_attributes_string(&self.quasi), ident.unwrap_str(), ty.to_ty_string(), expr.to_expr_string()) } fn to_ty_string(&self) -> String { match self.component { RustComponent::Type => self.to_type_path_string(), rc => { panic!("Exprected type. Got {:?}.", rc); } } } // Precondition on Self: Component == Type fn to_type_path_string(&self) -> String { // TODO(Havvy, 2019-09-08): Validate. Either inner is Str(ident) or Inners is [Ident, ...]. self.unwrap_str().to_string() } // Precondition on Self: Component = Id fn to_ident_string(&self) -> String { self.unwrap_str().to_string() } /// There's no `expr` component. Instead, a bunch of other components are themselves expression components. fn to_expr_string(&self) -> String { match self.component { // Literals RustComponent::Int => self.to_int_literal_string(), // Binary operators RustComponent::Plus => self.to_plus_string(), // Call expr RustComponent::Call => self.to_call_string(), // Otherwise, it's not an expression. Error in this case. rc => { panic!("Expected expression. Got {:?}.", rc); } } } // Precondition on Self: Component == Int fn to_int_literal_string(&self) -> String { // TODO(Havvy, 2019-09-08): Validate numeric only. self.unwrap_str().to_string() } fn to_plus_string(&self) -> String { let mut inner_iter = self.unwrap_inners().iter(); let lhs = inner_iter.next().unwrap(); let rhs = inner_iter.next().unwrap(); assert_eq!(inner_iter.next(), None); format!("({} + {})", lhs.to_expr_string(), rhs.to_expr_string()) } fn to_call_string(&self) -> String { let mut inner_iter = self.unwrap_inners().iter(); let fnname = inner_iter.next().unwrap().to_ident_string(); // TODO(Havvy, 2018-09-09): Generics let args = inner_iter.map(|arg| arg.to_expr_string()).collect::<Vec<_>>().join(", "); format!("{}({})", fnname, args) } } fn to_attributes_string(sti: &Attributes<'_>) -> String { match sti { None => "".to_string(), Some(StringlyTypedInner::Str(ref name)) => format!("#[{}]", name), Some(StringlyTypedInner::Inners(_inners)) => unimplemented!("Attributes with metaitems are unimplemented.") } } #[cfg(test)] mod test { #[test] fn const_attr() { let st_rust = "\"`no_mangle`'answer'id'i32'ty'42'int\"static"; let rust_st = ::parse::parse(st_rust).map_components(|s| s.parse::<::ast::RustComponent>().unwrap()).to_rust_string(); assert_eq!(rust_st, "#[no_mangle] static answer: i32 = 42;") } }
use js_sys::{Date as JsDate, Error as JsError}; use std::{ convert::TryInto, io::{Cursor, Write}, }; use wasm_bindgen::prelude::*; use zip::write::FileOptions as ZipFileOptions; type ZipWriterImpl = zip::ZipWriter<Cursor<Vec<u8>>>; #[wasm_bindgen] pub struct ZipWriter { inner: ZipWriterImpl, } #[wasm_bindgen] extern "C" { pub type FileOptions; #[wasm_bindgen(method, getter)] pub fn last_modified(this: &FileOptions) -> Option<JsDate>; } #[wasm_bindgen] impl ZipWriter { #[wasm_bindgen(constructor)] pub fn new() -> Self { ZipWriter { inner: ZipWriterImpl::new(Default::default()), } } /// Creates a new file in the archive. /// /// Subsequent calls to `write` will write to this file. pub fn start_file(&mut self, name: &str, options: Option<FileOptions>) -> Result<(), JsValue> { let options = if let Some(options) = options { let mut zip_options = ZipFileOptions::default(); if let Some(date) = options.last_modified() { let year: u16 = date.get_full_year().try_into().expect_throw("Invalid year"); let month: u8 = (date.get_month() + 1) .try_into() .expect_throw("Invalid month"); let day: u8 = date.get_date().try_into().expect_throw("Invalid day"); let hours: u8 = date.get_hours().try_into().expect_throw("Invalid hours"); let minutes: u8 = date .get_minutes() .try_into() .expect_throw("Invalid minutes"); let seconds: u8 = date .get_seconds() .try_into() .expect_throw("Invalid seconds"); zip_options = zip_options.last_modified_time( zip::DateTime::from_date_and_time(year, month, day, hours, minutes, seconds) .expect_throw("Invalid date"), ); } zip_options } else { ZipFileOptions::default() }; self.inner .start_file(name, options) .map_err(|e| JsError::new(&e.to_string()).into()) } /// Writes some data to the current file. pub fn write(&mut self, data: &[u8]) -> Result<(), JsValue> { self.inner .write_all(data) .map_err(|e| JsError::new(&e.to_string()).into()) } /// Sets the ZIP file comment. pub fn set_comment(&mut self, comment: String) { self.inner.set_comment(comment) } /// Closes the ZipWriter and returns the generated binary data (the zip file) as a `Uint8Array`. pub fn finish(mut self) -> Result<Vec<u8>, JsValue> { self.inner .finish() .map(Cursor::into_inner) .map_err(|e| JsError::new(&e.to_string()).into()) } }
use serde_json::Value; use crate::validator::{ scope::ScopedSchema, state::ValidationState, types::{validate_as_ipv4, validate_as_ipv6}, }; // // https://github.com/balena-os/meta-balena/blob/v2.29.2/meta-resin-common/recipes-connectivity/resin-proxy-config/resin-proxy-config/resin-proxy-config#L66-L73 // // -d, --destination address[/mask][,...] // Destination specification. See the description of the -s (source) flag for a detailed description // of the syntax. The flag --dst is an alias for this option. // // ip tables address is (ipv4|ipv6)[/mask] // // -d also accepts "ipv4/mask,ipv4/mask,...", but then, it should be stringlist of iptables-address pub fn validate_as_iptables_address(scope: &ScopedSchema, data: &Value) -> ValidationState { let state = validate_as_ipv4(scope, data); if state.is_valid() { return state; } validate_as_ipv6(scope, data) }
#[doc = "Register `HASH_CSR3` reader"] pub type R = crate::R<HASH_CSR3_SPEC>; #[doc = "Register `HASH_CSR3` writer"] pub type W = crate::W<HASH_CSR3_SPEC>; #[doc = "Field `CS3` reader - CS3"] pub type CS3_R = crate::FieldReader<u32>; #[doc = "Field `CS3` writer - CS3"] pub type CS3_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 32, O, u32>; impl R { #[doc = "Bits 0:31 - CS3"] #[inline(always)] pub fn cs3(&self) -> CS3_R { CS3_R::new(self.bits) } } impl W { #[doc = "Bits 0:31 - CS3"] #[inline(always)] #[must_use] pub fn cs3(&mut self) -> CS3_W<HASH_CSR3_SPEC, 0> { CS3_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 = "HASH context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hash_csr3::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 [`hash_csr3::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct HASH_CSR3_SPEC; impl crate::RegisterSpec for HASH_CSR3_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`hash_csr3::R`](R) reader structure"] impl crate::Readable for HASH_CSR3_SPEC {} #[doc = "`write(|w| ..)` method takes [`hash_csr3::W`](W) writer structure"] impl crate::Writable for HASH_CSR3_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets HASH_CSR3 to value 0"] impl crate::Resettable for HASH_CSR3_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[doc = "Register `IPCC_C2TOC1SR` reader"] pub type R = crate::R<IPCC_C2TOC1SR_SPEC>; #[doc = "Field `CHxF` reader - CHxF"] pub type CHX_F_R = crate::FieldReader; impl R { #[doc = "Bits 0:5 - CHxF"] #[inline(always)] pub fn chx_f(&self) -> CHX_F_R { CHX_F_R::new((self.bits & 0x3f) as u8) } } #[doc = "IPCC processor 2 to processor 1 status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipcc_c2toc1sr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct IPCC_C2TOC1SR_SPEC; impl crate::RegisterSpec for IPCC_C2TOC1SR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ipcc_c2toc1sr::R`](R) reader structure"] impl crate::Readable for IPCC_C2TOC1SR_SPEC {} #[doc = "`reset()` method sets IPCC_C2TOC1SR to value 0"] impl crate::Resettable for IPCC_C2TOC1SR_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[derive(Debug, Copy, Clone)] struct Point { x: i32, y: i32, } fn main() { let mut p1 = Point::new(24, 42); println!("{:#?}", p1); let p2 = p1; println!("{}", p1.x); inc_x(&mut p1); println!("{}", p1.x); println!("{}", p1.distance_from_origin()); let p3 = Point { x: 1, y: 2 }; } fn inc_x(point: &mut Point) { point.x += 1; } impl Point { fn distance_from_origin(&self) -> f64 { ((self.x.pow(2) + self.y.pow(2)) as f64).sqrt() } fn origin() -> Self { Point { x: 0, y: 0 } } fn new(x: i32, y: i32) -> Self { Self(x, y) } }
// This is always necessary to get the `TokenStream` typedef. extern crate proc_macro; #[macro_use] extern crate serde_derive; extern crate serde; use proc_macro::{Ident, Literal, TokenStream, TokenTree}; use quote::quote; use reqwest; use semver::Version; use std::net::SocketAddr; #[derive(Default)] struct ServiceDefinitionBuilder { pub name: Option<String>, pub version: Option<Version>, } #[derive(Debug)] struct ServiceDefinition { pub name: String, pub version: Version, } #[derive(Debug, Serialize, Deserialize, Eq, Hash, PartialEq, Clone)] struct ServiceName { pub name: String, pub version: Version, } #[derive(Debug, Serialize, Deserialize, Clone)] struct Service { pub name: ServiceName, pub address: SocketAddr, pub methods: Vec<ServiceMethod>, } #[derive(Debug, Serialize, Deserialize, Clone)] struct ServiceMethod { pub name: String, pub args: Vec<ServiceMethodArgument>, pub returning: Type, } #[derive(Debug, Serialize, Deserialize, Clone)] struct ServiceMethodArgument { pub name: String, pub r#type: Type, } #[derive(Debug, Serialize, Deserialize, Clone)] struct Type(pub String); impl From<ServiceDefinitionBuilder> for ServiceDefinition { fn from(d: ServiceDefinitionBuilder) -> ServiceDefinition { ServiceDefinition { name: d.name.expect("Missing field: \"name\""), version: d.version.expect("Missing field: \"version\""), } } } #[proc_macro_attribute] pub fn mock_service(args: TokenStream, _input: TokenStream) -> TokenStream { let mut iter = args.into_iter().peekable(); let mut definition = ServiceDefinitionBuilder::default(); while iter.peek().is_some() { let name = get_ident(&mut iter).to_string(); consume_punct(&mut iter, '='); match name.as_str() { "name" => { let lit = get_lit(&mut iter).to_string(); let name = lit.trim_matches('"'); definition.name = Some(name.to_string()); } "version" => { let lit = get_lit(&mut iter).to_string(); let version = lit.trim_matches('"'); definition.version = Some(version.parse().expect("Could not parse version string")); } x => panic!("Unknown tag: {:?}", x), } if let Some(next) = iter.peek() { if let TokenTree::Punct(p) = next { if p.as_char() == ',' { iter.next(); } } } } let definition: ServiceDefinition = definition.into(); let data: Service = reqwest::get(&format!( "http://localhost:8000/api/service/{0}/{1}", definition.name, definition.version )) .expect("Could not query index service") .json() .expect("Could not deserialize service definition"); let methods = data.methods.iter().map(|m| { let name = syn::Ident::new(m.name.as_str(), proc_macro2::Span::call_site()); let returning = syn::Ident::new(m.returning.0.as_str(), proc_macro2::Span::call_site()); quote! { pub fn #name() -> #returning { unimplemented!() } } }); let name = syn::Ident::new(data.name.name.as_str(), proc_macro2::Span::call_site()); let result = quote! { pub mod #name { #(#methods)* } }; println!("{}", result); result.into() } fn consume_punct(iter: &mut Iterator<Item = TokenTree>, c: char) { match iter.next() { Some(TokenTree::Punct(p)) => { if p.as_char() != c { panic!("Expected token '{}', got '{}'", c, p.as_char()); } } x => { panic!("Expected token '{}', got {:?}", c, x); } } } fn get_lit(iter: &mut Iterator<Item = TokenTree>) -> Literal { match iter.next() { Some(TokenTree::Literal(literal)) => literal, x => panic!("Expected literal, got {:?}", x), } } fn get_ident(iter: &mut Iterator<Item = TokenTree>) -> Ident { match iter.next() { Some(TokenTree::Ident(ident)) => ident, x => panic!("Expected ident, got {:?}", x), } }
use http::Request; use std::io::Read; pub fn cmp_strings(expected: &str, actual: &str) { if expected != actual { let cs = difference::Changeset::new(expected, actual, "\n"); panic!("{}", cs); } } pub fn requests_eq<AB: std::fmt::Debug, EB: std::fmt::Debug>( actual: &Request<AB>, expected: &Request<EB>, ) { let expected = format!("{:#?}", expected); let actual = format!("{:#?}", actual); cmp_strings(&expected, &actual); } #[allow(dead_code)] pub fn requests_read_eq<AB: Read, EB: Read>(actual: Request<AB>, expected: Request<EB>) { let (ap, mut ab) = actual.into_parts(); let (ep, mut eb) = expected.into_parts(); let expected = format!("{:#?}", ep); let actual = format!("{:#?}", ap); cmp_strings(&expected, &actual); let mut act_bod = Vec::with_capacity(2 * 1024); ab.read_to_end(&mut act_bod).unwrap(); let mut exp_bod = Vec::with_capacity(2 * 1024); eb.read_to_end(&mut exp_bod).unwrap(); let act_body = String::from_utf8_lossy(&act_bod); let exp_body = String::from_utf8_lossy(&exp_bod); cmp_strings(&exp_body, &act_body); }
use crate::intcode::*; use itertools::*; use std::thread; fn run_01(mem: &[isize], initial: &[isize]) -> isize { let mut vm_01 = VM::new(mem); let mut vm_02 = VM::new(mem); let mut vm_03 = VM::new(mem); let mut vm_04 = VM::new(mem); let mut vm_05 = VM::new(mem); vm_01.pipe(&mut vm_02); vm_02.pipe(&mut vm_03); vm_03.pipe(&mut vm_04); vm_04.pipe(&mut vm_05); vm_01.input.send(initial[0]).unwrap(); vm_01.input.send(0).unwrap(); vm_02.input.send(initial[1]).unwrap(); vm_03.input.send(initial[2]).unwrap(); vm_04.input.send(initial[3]).unwrap(); vm_05.input.send(initial[4]).unwrap(); thread::spawn(move || vm_01.run()); thread::spawn(move || vm_02.run()); thread::spawn(move || vm_03.run()); thread::spawn(move || vm_04.run()); thread::spawn(move || vm_05.run()).join().unwrap() } fn solve_01(mem: &[isize]) -> isize { (0..5) .permutations(5) .map(|permutation| run_01(mem, &permutation)) .max() .expect("has a max") } fn run_02(mem: &[isize], initial: &[isize]) -> isize { let mut vm_01 = VM::new(mem); let mut vm_02 = VM::new(mem); let mut vm_03 = VM::new(mem); let mut vm_04 = VM::new(mem); let mut vm_05 = VM::new(mem); vm_01.pipe(&mut vm_02); vm_02.pipe(&mut vm_03); vm_03.pipe(&mut vm_04); vm_04.pipe(&mut vm_05); vm_05.pipe(&mut vm_01); vm_01.input.send(initial[0]).unwrap(); vm_01.input.send(0).unwrap(); vm_02.input.send(initial[1]).unwrap(); vm_03.input.send(initial[2]).unwrap(); vm_04.input.send(initial[3]).unwrap(); vm_05.input.send(initial[4]).unwrap(); thread::spawn(move || vm_01.run()); thread::spawn(move || vm_02.run()); thread::spawn(move || vm_03.run()); thread::spawn(move || vm_04.run()); thread::spawn(move || vm_05.run()).join().unwrap() } fn solve_02(mem: &[isize]) -> isize { (5..10) .permutations(5) .map(|permutation| run_02(mem, &permutation)) .max() .expect("has a max") } fn load_initial_memory(input: &str) -> Vec<isize> { input.split(',').flat_map(|c| c.trim().parse()).collect() } pub fn solve(input: &str) { let mem = load_initial_memory(input); dbg!(solve_01(&mem)); dbg!(solve_02(&mem)); } #[cfg(test)] mod tests { use super::*; #[test] fn part_one() { let mem = load_initial_memory("3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0"); let inputs = vec![4, 3, 2, 1, 0]; let last = run_01(&mem, &inputs); assert_eq!(last, 43_210); let mem = load_initial_memory( "3,23,3,24,1002,24,10,24,1002,23, -1,23,101,5,23,23,1,24,23,23,4,23,99,0,0", ); let inputs = vec![0, 1, 2, 3, 4]; let last = run_01(&mem, &inputs); assert_eq!(last, 54_321); let mem = load_initial_memory( "3,31,3,32,1002,32,10,32,1001,31,-2,31,1007, 31,0,33,1002,33,7,33,1,33,31,31,1,32,31,31,4,31,99,0,0,0", ); let inputs = vec![1, 0, 4, 3, 2]; let last = run_01(&mem, &inputs); assert_eq!(last, 65_210); } #[test] fn part_two() { let mem = load_initial_memory( "3,52,1001,52,-5,52,3,53,1,52,56,54,1007,54,5,55,1005,55,26,1001,54, -5,54,1105,1,12,1,53,54,53,1008,54,0,55,1001,55,1,55,2,53,55,53,4, 53,1001,56,-1,56,1005,56,6,99,0,0,0,0,10", ); let inputs = vec![9, 7, 8, 5, 6]; let res = run_02(&mem, &inputs); assert_eq!(res, 18_216); let mem = load_initial_memory( "3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26, 27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5", ); let inputs = vec![9, 8, 7, 6, 5]; let res = run_02(&mem, &inputs); assert_eq!(res, 139_629_729); } }
use game::board::pieces::points::Points; use game::board::pieces::placement::Placement; pub struct PlacementMap { maps: [Placement; 400], } type BitfieldIter<'a> = ::std::iter::Take<::std::slice::Iter<'a, (u8, u64)>>; impl PlacementMap { pub fn new() -> Self { PlacementMap { maps: [Placement::new(); 400], } } pub fn from_points(points: &Points) -> Self { let mut maps = [Placement::new(); 400]; for (i, map) in maps.iter_mut().enumerate() { *map = Placement::from_points(points, i); } PlacementMap { maps: maps, } } #[inline] pub fn intersection_bitfields(&self, index: usize) -> BitfieldIter { let map = &self.maps[index]; map.bits.iter().take(map.len as usize) } }
#[doc = "Register `MPCBB1_VCTR50` reader"] pub type R = crate::R<MPCBB1_VCTR50_SPEC>; #[doc = "Register `MPCBB1_VCTR50` writer"] pub type W = crate::W<MPCBB1_VCTR50_SPEC>; #[doc = "Field `B1600` reader - B1600"] pub type B1600_R = crate::BitReader; #[doc = "Field `B1600` writer - B1600"] pub type B1600_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1601` reader - B1601"] pub type B1601_R = crate::BitReader; #[doc = "Field `B1601` writer - B1601"] pub type B1601_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1602` reader - B1602"] pub type B1602_R = crate::BitReader; #[doc = "Field `B1602` writer - B1602"] pub type B1602_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1603` reader - B1603"] pub type B1603_R = crate::BitReader; #[doc = "Field `B1603` writer - B1603"] pub type B1603_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1604` reader - B1604"] pub type B1604_R = crate::BitReader; #[doc = "Field `B1604` writer - B1604"] pub type B1604_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1605` reader - B1605"] pub type B1605_R = crate::BitReader; #[doc = "Field `B1605` writer - B1605"] pub type B1605_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1606` reader - B1606"] pub type B1606_R = crate::BitReader; #[doc = "Field `B1606` writer - B1606"] pub type B1606_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1607` reader - B1607"] pub type B1607_R = crate::BitReader; #[doc = "Field `B1607` writer - B1607"] pub type B1607_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1608` reader - B1608"] pub type B1608_R = crate::BitReader; #[doc = "Field `B1608` writer - B1608"] pub type B1608_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1609` reader - B1609"] pub type B1609_R = crate::BitReader; #[doc = "Field `B1609` writer - B1609"] pub type B1609_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1610` reader - B1610"] pub type B1610_R = crate::BitReader; #[doc = "Field `B1610` writer - B1610"] pub type B1610_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1611` reader - B1611"] pub type B1611_R = crate::BitReader; #[doc = "Field `B1611` writer - B1611"] pub type B1611_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1612` reader - B1612"] pub type B1612_R = crate::BitReader; #[doc = "Field `B1612` writer - B1612"] pub type B1612_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1613` reader - B1613"] pub type B1613_R = crate::BitReader; #[doc = "Field `B1613` writer - B1613"] pub type B1613_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1614` reader - B1614"] pub type B1614_R = crate::BitReader; #[doc = "Field `B1614` writer - B1614"] pub type B1614_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1615` reader - B1615"] pub type B1615_R = crate::BitReader; #[doc = "Field `B1615` writer - B1615"] pub type B1615_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1616` reader - B1616"] pub type B1616_R = crate::BitReader; #[doc = "Field `B1616` writer - B1616"] pub type B1616_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1617` reader - B1617"] pub type B1617_R = crate::BitReader; #[doc = "Field `B1617` writer - B1617"] pub type B1617_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1618` reader - B1618"] pub type B1618_R = crate::BitReader; #[doc = "Field `B1618` writer - B1618"] pub type B1618_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1619` reader - B1619"] pub type B1619_R = crate::BitReader; #[doc = "Field `B1619` writer - B1619"] pub type B1619_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1620` reader - B1620"] pub type B1620_R = crate::BitReader; #[doc = "Field `B1620` writer - B1620"] pub type B1620_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1621` reader - B1621"] pub type B1621_R = crate::BitReader; #[doc = "Field `B1621` writer - B1621"] pub type B1621_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1622` reader - B1622"] pub type B1622_R = crate::BitReader; #[doc = "Field `B1622` writer - B1622"] pub type B1622_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1623` reader - B1623"] pub type B1623_R = crate::BitReader; #[doc = "Field `B1623` writer - B1623"] pub type B1623_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1624` reader - B1624"] pub type B1624_R = crate::BitReader; #[doc = "Field `B1624` writer - B1624"] pub type B1624_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1625` reader - B1625"] pub type B1625_R = crate::BitReader; #[doc = "Field `B1625` writer - B1625"] pub type B1625_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1626` reader - B1626"] pub type B1626_R = crate::BitReader; #[doc = "Field `B1626` writer - B1626"] pub type B1626_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1627` reader - B1627"] pub type B1627_R = crate::BitReader; #[doc = "Field `B1627` writer - B1627"] pub type B1627_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1628` reader - B1628"] pub type B1628_R = crate::BitReader; #[doc = "Field `B1628` writer - B1628"] pub type B1628_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1629` reader - B1629"] pub type B1629_R = crate::BitReader; #[doc = "Field `B1629` writer - B1629"] pub type B1629_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1630` reader - B1630"] pub type B1630_R = crate::BitReader; #[doc = "Field `B1630` writer - B1630"] pub type B1630_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `B1631` reader - B1631"] pub type B1631_R = crate::BitReader; #[doc = "Field `B1631` writer - B1631"] pub type B1631_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - B1600"] #[inline(always)] pub fn b1600(&self) -> B1600_R { B1600_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - B1601"] #[inline(always)] pub fn b1601(&self) -> B1601_R { B1601_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - B1602"] #[inline(always)] pub fn b1602(&self) -> B1602_R { B1602_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - B1603"] #[inline(always)] pub fn b1603(&self) -> B1603_R { B1603_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - B1604"] #[inline(always)] pub fn b1604(&self) -> B1604_R { B1604_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - B1605"] #[inline(always)] pub fn b1605(&self) -> B1605_R { B1605_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - B1606"] #[inline(always)] pub fn b1606(&self) -> B1606_R { B1606_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - B1607"] #[inline(always)] pub fn b1607(&self) -> B1607_R { B1607_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - B1608"] #[inline(always)] pub fn b1608(&self) -> B1608_R { B1608_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - B1609"] #[inline(always)] pub fn b1609(&self) -> B1609_R { B1609_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - B1610"] #[inline(always)] pub fn b1610(&self) -> B1610_R { B1610_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - B1611"] #[inline(always)] pub fn b1611(&self) -> B1611_R { B1611_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - B1612"] #[inline(always)] pub fn b1612(&self) -> B1612_R { B1612_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - B1613"] #[inline(always)] pub fn b1613(&self) -> B1613_R { B1613_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 14 - B1614"] #[inline(always)] pub fn b1614(&self) -> B1614_R { B1614_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 15 - B1615"] #[inline(always)] pub fn b1615(&self) -> B1615_R { B1615_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bit 16 - B1616"] #[inline(always)] pub fn b1616(&self) -> B1616_R { B1616_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - B1617"] #[inline(always)] pub fn b1617(&self) -> B1617_R { B1617_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - B1618"] #[inline(always)] pub fn b1618(&self) -> B1618_R { B1618_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - B1619"] #[inline(always)] pub fn b1619(&self) -> B1619_R { B1619_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - B1620"] #[inline(always)] pub fn b1620(&self) -> B1620_R { B1620_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - B1621"] #[inline(always)] pub fn b1621(&self) -> B1621_R { B1621_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - B1622"] #[inline(always)] pub fn b1622(&self) -> B1622_R { B1622_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 23 - B1623"] #[inline(always)] pub fn b1623(&self) -> B1623_R { B1623_R::new(((self.bits >> 23) & 1) != 0) } #[doc = "Bit 24 - B1624"] #[inline(always)] pub fn b1624(&self) -> B1624_R { B1624_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 25 - B1625"] #[inline(always)] pub fn b1625(&self) -> B1625_R { B1625_R::new(((self.bits >> 25) & 1) != 0) } #[doc = "Bit 26 - B1626"] #[inline(always)] pub fn b1626(&self) -> B1626_R { B1626_R::new(((self.bits >> 26) & 1) != 0) } #[doc = "Bit 27 - B1627"] #[inline(always)] pub fn b1627(&self) -> B1627_R { B1627_R::new(((self.bits >> 27) & 1) != 0) } #[doc = "Bit 28 - B1628"] #[inline(always)] pub fn b1628(&self) -> B1628_R { B1628_R::new(((self.bits >> 28) & 1) != 0) } #[doc = "Bit 29 - B1629"] #[inline(always)] pub fn b1629(&self) -> B1629_R { B1629_R::new(((self.bits >> 29) & 1) != 0) } #[doc = "Bit 30 - B1630"] #[inline(always)] pub fn b1630(&self) -> B1630_R { B1630_R::new(((self.bits >> 30) & 1) != 0) } #[doc = "Bit 31 - B1631"] #[inline(always)] pub fn b1631(&self) -> B1631_R { B1631_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bit 0 - B1600"] #[inline(always)] #[must_use] pub fn b1600(&mut self) -> B1600_W<MPCBB1_VCTR50_SPEC, 0> { B1600_W::new(self) } #[doc = "Bit 1 - B1601"] #[inline(always)] #[must_use] pub fn b1601(&mut self) -> B1601_W<MPCBB1_VCTR50_SPEC, 1> { B1601_W::new(self) } #[doc = "Bit 2 - B1602"] #[inline(always)] #[must_use] pub fn b1602(&mut self) -> B1602_W<MPCBB1_VCTR50_SPEC, 2> { B1602_W::new(self) } #[doc = "Bit 3 - B1603"] #[inline(always)] #[must_use] pub fn b1603(&mut self) -> B1603_W<MPCBB1_VCTR50_SPEC, 3> { B1603_W::new(self) } #[doc = "Bit 4 - B1604"] #[inline(always)] #[must_use] pub fn b1604(&mut self) -> B1604_W<MPCBB1_VCTR50_SPEC, 4> { B1604_W::new(self) } #[doc = "Bit 5 - B1605"] #[inline(always)] #[must_use] pub fn b1605(&mut self) -> B1605_W<MPCBB1_VCTR50_SPEC, 5> { B1605_W::new(self) } #[doc = "Bit 6 - B1606"] #[inline(always)] #[must_use] pub fn b1606(&mut self) -> B1606_W<MPCBB1_VCTR50_SPEC, 6> { B1606_W::new(self) } #[doc = "Bit 7 - B1607"] #[inline(always)] #[must_use] pub fn b1607(&mut self) -> B1607_W<MPCBB1_VCTR50_SPEC, 7> { B1607_W::new(self) } #[doc = "Bit 8 - B1608"] #[inline(always)] #[must_use] pub fn b1608(&mut self) -> B1608_W<MPCBB1_VCTR50_SPEC, 8> { B1608_W::new(self) } #[doc = "Bit 9 - B1609"] #[inline(always)] #[must_use] pub fn b1609(&mut self) -> B1609_W<MPCBB1_VCTR50_SPEC, 9> { B1609_W::new(self) } #[doc = "Bit 10 - B1610"] #[inline(always)] #[must_use] pub fn b1610(&mut self) -> B1610_W<MPCBB1_VCTR50_SPEC, 10> { B1610_W::new(self) } #[doc = "Bit 11 - B1611"] #[inline(always)] #[must_use] pub fn b1611(&mut self) -> B1611_W<MPCBB1_VCTR50_SPEC, 11> { B1611_W::new(self) } #[doc = "Bit 12 - B1612"] #[inline(always)] #[must_use] pub fn b1612(&mut self) -> B1612_W<MPCBB1_VCTR50_SPEC, 12> { B1612_W::new(self) } #[doc = "Bit 13 - B1613"] #[inline(always)] #[must_use] pub fn b1613(&mut self) -> B1613_W<MPCBB1_VCTR50_SPEC, 13> { B1613_W::new(self) } #[doc = "Bit 14 - B1614"] #[inline(always)] #[must_use] pub fn b1614(&mut self) -> B1614_W<MPCBB1_VCTR50_SPEC, 14> { B1614_W::new(self) } #[doc = "Bit 15 - B1615"] #[inline(always)] #[must_use] pub fn b1615(&mut self) -> B1615_W<MPCBB1_VCTR50_SPEC, 15> { B1615_W::new(self) } #[doc = "Bit 16 - B1616"] #[inline(always)] #[must_use] pub fn b1616(&mut self) -> B1616_W<MPCBB1_VCTR50_SPEC, 16> { B1616_W::new(self) } #[doc = "Bit 17 - B1617"] #[inline(always)] #[must_use] pub fn b1617(&mut self) -> B1617_W<MPCBB1_VCTR50_SPEC, 17> { B1617_W::new(self) } #[doc = "Bit 18 - B1618"] #[inline(always)] #[must_use] pub fn b1618(&mut self) -> B1618_W<MPCBB1_VCTR50_SPEC, 18> { B1618_W::new(self) } #[doc = "Bit 19 - B1619"] #[inline(always)] #[must_use] pub fn b1619(&mut self) -> B1619_W<MPCBB1_VCTR50_SPEC, 19> { B1619_W::new(self) } #[doc = "Bit 20 - B1620"] #[inline(always)] #[must_use] pub fn b1620(&mut self) -> B1620_W<MPCBB1_VCTR50_SPEC, 20> { B1620_W::new(self) } #[doc = "Bit 21 - B1621"] #[inline(always)] #[must_use] pub fn b1621(&mut self) -> B1621_W<MPCBB1_VCTR50_SPEC, 21> { B1621_W::new(self) } #[doc = "Bit 22 - B1622"] #[inline(always)] #[must_use] pub fn b1622(&mut self) -> B1622_W<MPCBB1_VCTR50_SPEC, 22> { B1622_W::new(self) } #[doc = "Bit 23 - B1623"] #[inline(always)] #[must_use] pub fn b1623(&mut self) -> B1623_W<MPCBB1_VCTR50_SPEC, 23> { B1623_W::new(self) } #[doc = "Bit 24 - B1624"] #[inline(always)] #[must_use] pub fn b1624(&mut self) -> B1624_W<MPCBB1_VCTR50_SPEC, 24> { B1624_W::new(self) } #[doc = "Bit 25 - B1625"] #[inline(always)] #[must_use] pub fn b1625(&mut self) -> B1625_W<MPCBB1_VCTR50_SPEC, 25> { B1625_W::new(self) } #[doc = "Bit 26 - B1626"] #[inline(always)] #[must_use] pub fn b1626(&mut self) -> B1626_W<MPCBB1_VCTR50_SPEC, 26> { B1626_W::new(self) } #[doc = "Bit 27 - B1627"] #[inline(always)] #[must_use] pub fn b1627(&mut self) -> B1627_W<MPCBB1_VCTR50_SPEC, 27> { B1627_W::new(self) } #[doc = "Bit 28 - B1628"] #[inline(always)] #[must_use] pub fn b1628(&mut self) -> B1628_W<MPCBB1_VCTR50_SPEC, 28> { B1628_W::new(self) } #[doc = "Bit 29 - B1629"] #[inline(always)] #[must_use] pub fn b1629(&mut self) -> B1629_W<MPCBB1_VCTR50_SPEC, 29> { B1629_W::new(self) } #[doc = "Bit 30 - B1630"] #[inline(always)] #[must_use] pub fn b1630(&mut self) -> B1630_W<MPCBB1_VCTR50_SPEC, 30> { B1630_W::new(self) } #[doc = "Bit 31 - B1631"] #[inline(always)] #[must_use] pub fn b1631(&mut self) -> B1631_W<MPCBB1_VCTR50_SPEC, 31> { B1631_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 = "MPCBBx vector register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mpcbb1_vctr50::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 [`mpcbb1_vctr50::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct MPCBB1_VCTR50_SPEC; impl crate::RegisterSpec for MPCBB1_VCTR50_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`mpcbb1_vctr50::R`](R) reader structure"] impl crate::Readable for MPCBB1_VCTR50_SPEC {} #[doc = "`write(|w| ..)` method takes [`mpcbb1_vctr50::W`](W) writer structure"] impl crate::Writable for MPCBB1_VCTR50_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets MPCBB1_VCTR50 to value 0"] impl crate::Resettable for MPCBB1_VCTR50_SPEC { const RESET_VALUE: Self::Ux = 0; }
use super::wasm_buf_apply; use crate::api::{self, json::JsonError}; /// Encodes an `Call Account` JSON into SVM binary format. /// The JSON input is passed by giving WASM memory start address (`ptr` parameter). /// /// Returns a pointer to a `transaction buffer`. /// /// See also: `alloc` and `free` /// pub fn encode_call(offset: usize) -> Result<usize, JsonError> { wasm_buf_apply(offset, |json| api::json::encode_call_raw(&json.to_string())) } /// Decodes a `Call Account` transaction into a JSON, /// stores that JSON content into a new Wasm Buffer, /// and finally returns that Wasm buffer offset pub fn decode_call(offset: usize) -> Result<usize, JsonError> { wasm_buf_apply(offset, |json: &str| { let json = api::json::decode_call(json)?; Ok(api::json::to_bytes(&json)) }) } #[cfg(test)] mod test { use super::*; use crate::api::json::serde_types::HexBlob; use crate::api::wasm::{ error_as_string, free, to_wasm_buffer, wasm_buffer_data, BUF_OK_MARKER, }; use serde_json::{json, Value}; #[test] fn wasm_call_valid() { let target = "1122334455667788990011223344556677889900"; let verifydata = api::json::encode_inputdata( &json!({ "abi": ["bool", "i8"], "data": [true, 3] }) .to_string(), ) .unwrap(); let calldata = api::json::encode_inputdata( &json!({ "abi": ["i32", "i64"], "data": [10, 20] }) .to_string(), ) .unwrap(); let json = json!({ "version": 1, "target": target, "func_name": "do_something", "verifydata": verifydata["data"], "calldata": calldata["data"] }); let json = serde_json::to_string(&json).unwrap(); let json_buf = to_wasm_buffer(json.as_bytes()); let tx_buf = encode_call(json_buf).unwrap(); let data = wasm_buffer_data(tx_buf); assert_eq!(data[0], BUF_OK_MARKER); let data = HexBlob(&data[1..]); let json = json!({ "data": data }); let json = serde_json::to_string(&json).unwrap(); free(json_buf); let json_buf = to_wasm_buffer(json.as_bytes()); free(tx_buf); let tx_buf = decode_call(json_buf).unwrap(); let data = wasm_buffer_data(tx_buf); assert_eq!(data[0], BUF_OK_MARKER); let json: Value = serde_json::from_slice(&data[1..]).unwrap(); assert_eq!( json, json!({ "version": 1, "target": target, "func_name": "do_something", "verifydata": { "abi": ["bool", "i8"], "data": [true, 3], }, "calldata": { "abi": ["i32", "i64"], "data": [10, 20], } }) ); free(json_buf); free(tx_buf); } #[test] fn wasm_call_invalid() { let json = "{"; let json_buf = to_wasm_buffer(json.as_bytes()); let error_buf = encode_call(json_buf).unwrap(); let error = unsafe { error_as_string(error_buf) }; assert_eq!(error, "The given JSON is syntactically invalid due to EOF."); free(json_buf); free(error_buf); } }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - IPCC Processor 1 control register"] pub c1cr: C1CR, #[doc = "0x04 - IPCC Processor 1 mask register"] pub c1mr: C1MR, #[doc = "0x08 - IPCC Processor 1 status set clear register"] pub c1scr: C1SCR, #[doc = "0x0c - IPCC processor 1 to processor 2 status register"] pub c1toc2sr: C1TOC2SR, #[doc = "0x10 - IPCC Processor 2 control register"] pub c2cr: C2CR, #[doc = "0x14 - IPCC Processor 2 mask register"] pub c2mr: C2MR, #[doc = "0x18 - IPCC Processor 2 status set clear register"] pub c2scr: C2SCR, #[doc = "0x1c - IPCC processor 2 to processor 1 status register"] pub c2toc1sr: C2TOC1SR, _reserved8: [u8; 976usize], #[doc = "0x3f0 - hardware configuration register"] pub hwcfgr: HWCFGR, #[doc = "0x3f4 - version register"] pub verr: VERR, #[doc = "0x3f8 - ID register"] pub id: ID, #[doc = "0x3fc - size ID register"] pub sid: SID, } #[doc = "IPCC Processor 1 control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c1cr](c1cr) module"] pub type C1CR = crate::Reg<u32, _C1CR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _C1CR; #[doc = "`read()` method returns [c1cr::R](c1cr::R) reader structure"] impl crate::Readable for C1CR {} #[doc = "`write(|w| ..)` method takes [c1cr::W](c1cr::W) writer structure"] impl crate::Writable for C1CR {} #[doc = "IPCC Processor 1 control register"] pub mod c1cr; #[doc = "IPCC Processor 1 mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c1mr](c1mr) module"] pub type C1MR = crate::Reg<u32, _C1MR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _C1MR; #[doc = "`read()` method returns [c1mr::R](c1mr::R) reader structure"] impl crate::Readable for C1MR {} #[doc = "`write(|w| ..)` method takes [c1mr::W](c1mr::W) writer structure"] impl crate::Writable for C1MR {} #[doc = "IPCC Processor 1 mask register"] pub mod c1mr; #[doc = "IPCC Processor 1 status set clear register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c1scr](c1scr) module"] pub type C1SCR = crate::Reg<u32, _C1SCR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _C1SCR; #[doc = "`read()` method returns [c1scr::R](c1scr::R) reader structure"] impl crate::Readable for C1SCR {} #[doc = "`write(|w| ..)` method takes [c1scr::W](c1scr::W) writer structure"] impl crate::Writable for C1SCR {} #[doc = "IPCC Processor 1 status set clear register"] pub mod c1scr; #[doc = "IPCC processor 1 to processor 2 status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c1toc2sr](c1toc2sr) module"] pub type C1TOC2SR = crate::Reg<u32, _C1TOC2SR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _C1TOC2SR; #[doc = "`read()` method returns [c1toc2sr::R](c1toc2sr::R) reader structure"] impl crate::Readable for C1TOC2SR {} #[doc = "IPCC processor 1 to processor 2 status register"] pub mod c1toc2sr; #[doc = "IPCC Processor 2 control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c2cr](c2cr) module"] pub type C2CR = crate::Reg<u32, _C2CR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _C2CR; #[doc = "`read()` method returns [c2cr::R](c2cr::R) reader structure"] impl crate::Readable for C2CR {} #[doc = "`write(|w| ..)` method takes [c2cr::W](c2cr::W) writer structure"] impl crate::Writable for C2CR {} #[doc = "IPCC Processor 2 control register"] pub mod c2cr; #[doc = "IPCC Processor 2 mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c2mr](c2mr) module"] pub type C2MR = crate::Reg<u32, _C2MR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _C2MR; #[doc = "`read()` method returns [c2mr::R](c2mr::R) reader structure"] impl crate::Readable for C2MR {} #[doc = "`write(|w| ..)` method takes [c2mr::W](c2mr::W) writer structure"] impl crate::Writable for C2MR {} #[doc = "IPCC Processor 2 mask register"] pub mod c2mr; #[doc = "IPCC Processor 2 status set clear register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c2scr](c2scr) module"] pub type C2SCR = crate::Reg<u32, _C2SCR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _C2SCR; #[doc = "`read()` method returns [c2scr::R](c2scr::R) reader structure"] impl crate::Readable for C2SCR {} #[doc = "`write(|w| ..)` method takes [c2scr::W](c2scr::W) writer structure"] impl crate::Writable for C2SCR {} #[doc = "IPCC Processor 2 status set clear register"] pub mod c2scr; #[doc = "IPCC processor 2 to processor 1 status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [c2toc1sr](c2toc1sr) module"] pub type C2TOC1SR = crate::Reg<u32, _C2TOC1SR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _C2TOC1SR; #[doc = "`read()` method returns [c2toc1sr::R](c2toc1sr::R) reader structure"] impl crate::Readable for C2TOC1SR {} #[doc = "IPCC processor 2 to processor 1 status register"] pub mod c2toc1sr; #[doc = "hardware configuration register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [hwcfgr](hwcfgr) module"] pub type HWCFGR = crate::Reg<u32, _HWCFGR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _HWCFGR; #[doc = "`read()` method returns [hwcfgr::R](hwcfgr::R) reader structure"] impl crate::Readable for HWCFGR {} #[doc = "hardware configuration register"] pub mod hwcfgr; #[doc = "version register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [verr](verr) module"] pub type VERR = crate::Reg<u32, _VERR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _VERR; #[doc = "`read()` method returns [verr::R](verr::R) reader structure"] impl crate::Readable for VERR {} #[doc = "version register"] pub mod verr; #[doc = "ID register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [id](id) module"] pub type ID = crate::Reg<u32, _ID>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ID; #[doc = "`read()` method returns [id::R](id::R) reader structure"] impl crate::Readable for ID {} #[doc = "ID register"] pub mod id; #[doc = "size ID register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sid](sid) module"] pub type SID = crate::Reg<u32, _SID>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SID; #[doc = "`read()` method returns [sid::R](sid::R) reader structure"] impl crate::Readable for SID {} #[doc = "size ID register"] pub mod sid;
use std::io; ///Generalization for cleaning output streams pub trait LogFlush<'a> { ///Flush the output stream fn flush_out(&'a self) -> io::Result<()>; ///Flush the err-output stream fn flush_err(&'a self) -> io::Result<()>; ///Flush Out stream and Err stream #[inline] fn flush(&'a self) -> io::Result<()> { let e = self.flush_out(); let e2 = self.flush_err(); if let Err(_) = e { return e; } e2 } } impl<'a, 'l, A: LogFlush<'a>> LogFlush<'a> for &'l A { ///Flush the output stream #[inline(always)] fn flush_out(&'a self) -> io::Result<()> { A::flush_out(self) } ///Flush the err-output stream #[inline(always)] fn flush_err(&'a self) -> io::Result<()> { A::flush_err(self) } ///Flush Out stream and Err stream #[inline(always)] fn flush(&'a self) -> io::Result<()> { A::flush(self) } } impl<'a, 'l, A: LogFlush<'a>> LogFlush<'a> for &'l mut A { ///Flush the output stream #[inline(always)] fn flush_out(&'a self) -> io::Result<()> { A::flush_out(self) } ///Flush the err-output stream #[inline(always)] fn flush_err(&'a self) -> io::Result<()> { A::flush_err(self) } ///Flush Out stream and Err stream #[inline(always)] fn flush(&'a self) -> io::Result<()> { A::flush(self) } }
use std::fs::File; use std::io::Read; pub struct Program { pub data: Vec<u8>, } impl Program { pub fn new(path: &str) -> Program { let mut file = File::open(path).expect("File not found!"); let mut file_contents = Vec::new(); file.read_to_end(&mut file_contents) .expect("Cannot read file!"); Program { data: file_contents, } } }
/// Sod stands for Static or Dynamic. An enum to encapsulate values which /// are either dynamically, heap-allocated values, or statics. /// /// This allows us to define default primitives which are used throughout /// without the overhead of reference counting, while still supporting the /// flexibility to create primitives dynamically. /// /// Thanks to the `Deref` implementation, either variants are treated like /// the inner type without needing to worry about which it is. /// /// Many thanks to [panicbit](https://github.com/panicbit) for helping to /// get the `Deref` implementation working to make all the magic happen. use std::cmp::Ordering; use std::ops::Deref; use std::sync::Arc; #[derive(Debug)] /// Enum to hold either static references or reference-counted owned objects. /// Implements `Deref` to `T` for ease of use. /// Since internal data is either a static reference, or an `Arc`, cloning /// is a cheap operation. pub enum Sod<T: ?Sized + 'static> { /// Static reference to T Static(&'static T), /// Dynamically allocated T, on the heap, atomically reference-counted. Dynamic(Arc<T>), } impl<T: ?Sized> Deref for Sod<T> { type Target = T; fn deref(&self) -> &T { match *self { Sod::Static(t) => t, Sod::Dynamic(ref t) => t, } } } impl<T: ?Sized> Clone for Sod<T> { fn clone(&self) -> Self { match *self { Sod::Static(t) => Sod::Static(t), Sod::Dynamic(ref t) => Sod::Dynamic(Arc::clone(t)), } } } impl<T: PartialEq + ?Sized> PartialEq<Sod<T>> for Sod<T> { fn eq(&self, other: &Self) -> bool { self.deref().eq(other.deref()) } } impl<T: PartialOrd + ?Sized> PartialOrd<Sod<T>> for Sod<T> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { self.deref().partial_cmp(other.deref()) } }
/*! # Variants ## Plan - ~~Plan.~~ - Design. - MVP. ## Code ```rust // */ use crate::{ error::{Invalid, Void}, fail, graph::{Hyperedge, Scalar, Vector}, scalar, Result, }; use data_encoding::BASE64URL_NOPAD; use std::{ cmp::{Ord, Ordering}, collections::BTreeMap, convert::TryFrom, mem, ops::{Index, IndexMut}, }; use uuid::Uuid; use SimpleValue::*; pub trait PlainScalar: Scalar<bool> + Scalar<i128> + Scalar<f64> + Scalar<String> + Scalar<Vec<u8>> { fn bool(&self) -> Option<bool> { scalar!(self, to, bool) } fn is_bool(&self) -> bool { scalar!(self, is, bool) } fn integer(&self) -> Option<i128> { scalar!(self, to, i128) } fn is_integer(&self) -> bool { scalar!(self, is, i128) } fn as_integer(&self) -> Option<i128> { scalar!(self, as, i128) } fn as_usize(&self) -> Option<usize> { self.integer().and_then(|n| usize::try_from(n).ok()) } fn as_u64(&self) -> Option<u64> { self.integer().and_then(|n| u64::try_from(n).ok()) } fn float(&self) -> Option<f64> { scalar!(self, to, f64) } fn is_float(&self) -> bool { scalar!(self, is, f64) } fn as_float(&self) -> Option<f64> { scalar!(self, as, f64) } fn text(&self) -> Option<&str> { scalar!(self, String).map(String::as_str) } fn is_text(&self) -> bool { scalar!(self, is, String) } fn as_text(&self) -> Option<String> { scalar!(self, as, String) } fn binary(&self) -> Option<&[u8]> { scalar!(self, Vec<u8>).map(Vec::as_ref) } fn is_binary(&self) -> bool { scalar!(self, is, Vec<u8>) } fn as_binary(&self) -> Option<Vec<u8>> { scalar!(self, as, Vec<u8>) } } #[derive(Debug, Clone, PartialEq, PartialOrd)] pub enum SimpleValue { Bool(bool), Integer(i128), Float(f64), Text(String), Bytes(Vec<u8>), } impl SimpleValue { fn weight(&self) -> usize { match self { Bool(_) => 1, Integer(_) => 2, Float(_) => 3, Text(_) => 4, Bytes(_) => 5, } } } impl PlainScalar for SimpleValue {} impl Scalar<bool> for SimpleValue { fn scalar(&self) -> Option<&bool> { if let Bool(x) = self { Some(x) } else { None } } fn to_scalar(&self) -> Option<bool> { self.scalar().map(|x| *x) } fn as_scalar(&self) -> Option<bool> { Some(match self { Bool(true) => true, Integer(x) if *x != 0 => true, Text(x) if !x.is_empty() => true, Bytes(x) if !x.is_empty() => true, Float(_) => return None, _ => false, }) } } impl Scalar<i128> for SimpleValue { fn scalar(&self) -> Option<&i128> { if let Integer(x) = self { Some(x) } else { None } } fn to_scalar(&self) -> Option<i128> { self.scalar().map(|x| *x) } fn as_scalar(&self) -> Option<i128> { match self { Integer(x) => Some(*x), Text(x) => x.parse().ok(), // convert binary as big-endian data to i128 Bytes(x) => { let sz = x.len(); if sz > 16 { None } else { let start = 16 - sz; let mut b = [0; 16]; b[start..].copy_from_slice(x); Some(i128::from_be_bytes(b)) } } Float(x) => Some(x.round() as i128), _ => None, } } } impl Scalar<f64> for SimpleValue { fn scalar(&self) -> Option<&f64> { if let Float(x) = self { Some(x) } else { None } } fn to_scalar(&self) -> Option<f64> { self.scalar().map(|x| *x) } fn as_scalar(&self) -> Option<f64> { match self { Integer(x) => Some((*x) as f64), Float(x) => Some(*x), Text(x) => x.parse().ok(), Bytes(x) if x.len() == 8 => { let mut b = [0; 8]; b.copy_from_slice(&x[..]); Some(f64::from_be_bytes(b)) } _ => None, } } } impl Scalar<String> for SimpleValue { fn scalar(&self) -> Option<&String> { if let Text(x) = self { Some(x) } else { None } } fn to_scalar(&self) -> Option<String> { self.scalar().map(Clone::clone) } fn as_scalar(&self) -> Option<String> { Some(match self { Bool(x) => x.to_string(), Integer(x) => x.to_string(), Text(x) => x.clone(), Bytes(x) => String::from_utf8_lossy(x).to_string(), Float(x) => x.to_string(), }) } } impl Scalar<Vec<u8>> for SimpleValue { fn scalar(&self) -> Option<&Vec<u8>> { if let Bytes(x) = self { Some(x) } else { None } } fn to_scalar(&self) -> Option<Vec<u8>> { self.scalar().map(Clone::clone) } fn as_scalar(&self) -> Option<Vec<u8>> { Some(match self { Bool(true) => vec![1], Bool(false) => vec![0], Integer(x) => x.to_be_bytes().to_vec(), Text(x) => x.as_bytes().to_vec(), Bytes(x) => x.clone(), Float(x) => x.to_be_bytes().to_vec(), }) } } impl Eq for SimpleValue {} impl Ord for SimpleValue { fn cmp(&self, other: &SimpleValue) -> Ordering { if let Some(ord) = self.partial_cmp(other) { ord } else { self.weight().cmp(&other.weight()) } } } #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq)] pub enum Variant { Null, Scalar(SimpleValue), Array(Vec<Variant>), Table(BTreeMap<SimpleValue, Variant>), Index(SimpleValue), } impl Hyperedge<Variant> for usize { type Output = Variant; fn get(self, vector: &Variant) -> Option<&Self::Output> { if let Variant::Array(x) = vector { x.get(self) } else { None } } fn get_mut(self, vector: &mut Variant) -> Option<&mut Self::Output> { if let Variant::Array(x) = vector { x.get_mut(self) } else { None } } } impl Hyperedge<Variant> for &SimpleValue { type Output = Variant; fn get(self, vector: &Variant) -> Option<&Self::Output> { match vector { Variant::Table(x) => x.get(self), Variant::Array(x) if self.is_integer() => self.as_usize().and_then(|n| x.get(n)), _ => None, } } fn get_mut(self, vector: &mut Variant) -> Option<&mut Self::Output> { match vector { Variant::Table(x) => Some(x.entry(self.clone()).or_insert(Variant::Null)), Variant::Array(x) if self.is_integer() => { self.as_usize().and_then(move |n| x.get_mut(n)) } _ => None, } } } impl Hyperedge<Variant> for SimpleValue { type Output = Variant; fn get(self, vector: &Variant) -> Option<&Self::Output> { (&self).get(vector) } fn get_mut(self, vector: &mut Variant) -> Option<&mut Self::Output> { (&self).get_mut(vector) } } impl Vector<SimpleValue> for Variant { type Output = Result<Variant>; fn size(&self) -> Option<usize> { Some(match self { Variant::Null => 0, Variant::Scalar(_) => 1, Variant::Array(x) => x.len(), Variant::Table(x) => x.len(), Variant::Index(_) => return None, }) } fn get(&self, key: SimpleValue) -> Self::Output { key.get(self).map(Clone::clone).ok_or_else(|| Void.into()) } fn put(&mut self, key: SimpleValue, v: Variant) -> Self::Output { if let Some(x) = key.get_mut(self) { Ok(mem::replace(x, v)) } else { Err(Void.into()) } } fn delete(&mut self, key: SimpleValue) -> Self::Output { match self { Variant::Array(x) => { let n = key.as_usize().ok_or(Void)?; if n < x.len() { Ok(x.remove(n)) } else { Err(fail!(Invalid, "out of bound")) } } Variant::Table(x) => x.remove(&key).ok_or_else(|| Void.into()), _ => Err(fail!(Invalid, "invalid data type")), } } fn new(&mut self, v: Variant) -> Self::Output { match self { Variant::Array(x) => { x.push(v); let key = SimpleValue::Integer(x.len() as i128); Ok(Variant::Scalar(key)) } Variant::Table(x) => { let key = SimpleValue::Text(generate_key()); x.insert(key.clone(), v); Ok(Variant::Scalar(key)) } _ => Err(fail!(Invalid, "invalid inner type")), } } fn get_ref(&self, key: SimpleValue) -> Option<&Variant> { key.get(self) } fn get_mut(&mut self, key: SimpleValue) -> Option<&mut Variant> { key.get_mut(self) } fn with<F>(&self, key: SimpleValue, f: F) -> Self::Output where F: FnOnce(&Variant) -> Self::Output, { if let Some(x) = self.get_ref(key) { f(x) } else { Err(Void.into()) } } fn with_mut<F>(&mut self, key: SimpleValue, f: F) -> Self::Output where F: FnOnce(&mut Variant) -> Self::Output, { if let Some(x) = self.get_mut(key) { f(x) } else { Err(Void.into()) } } } impl<K: Into<SimpleValue>> Index<K> for Variant { type Output = Variant; fn index(&self, key: K) -> &Variant { let key = key.into(); self.get_ref(key) .expect("value of the index must be existed") } } impl<K: Into<SimpleValue>> IndexMut<K> for Variant { fn index_mut(&mut self, key: K) -> &mut Variant { let key = key.into(); self.get_mut(key) .expect("value of the index must be existed") } } pub fn generate_key() -> String { let id = Uuid::new_v4(); BASE64URL_NOPAD.encode(id.as_bytes()) } #[cfg(test)] mod tests { #[test] fn simple_graph() {} } /* ``` */
extern crate reqwest; extern crate json; extern crate serde; extern crate serde_xml_rs; extern crate serde_derive; extern crate serde_json; extern crate tokio; use std::collections::{HashMap, BTreeMap}; use json::object; use std::iter::FromIterator; use std::array::IntoIter; use tokio::runtime; struct DataServiceConfig { rootUrl: String, } impl DataServiceConfig { pub fn new(rootUrl: String) -> Self { Self { rootUrl } } } struct DataServiceRequestOpts { token: String, method: reqwest::Method, body: String, params: HashMap<String, String>, urlPath: String, headers: HashMap<String, String>, } impl DataServiceRequestOpts { pub fn new(token: String, method: reqwest::Method, body: String, params: HashMap<String, String>, urlPath: String, headers: HashMap<String, String>) -> Self { Self { token, method, body, params, urlPath, headers } } } struct DataServiceResponseObject { rawData: String, dataObject: serde_json::Value, } impl Default for DataServiceResponseObject { fn default() -> Self { return Self { rawData: "".to_owned(), dataObject: serde_json::from_str("{\"data\": \"\"}").unwrap() }; } } impl From<reqwest::Response> for DataServiceResponseObject { fn from(response: reqwest::Response) -> Self { let mut newObject : &mut DataServiceResponseObject = &mut DataServiceResponseObject::default(); //assert_eq!(response.status().as_str(), ""); if !(response.status().is_success()) { return Self { rawData: "".to_owned(), dataObject: serde_json::from_str("{\"data\": \"\"}").unwrap() }; } let tempData = futures::executor::block_on(response.text()); if tempData.is_err() { return Self { rawData: "".to_owned(), dataObject: serde_json::from_str("{\"data\": \"\"}").unwrap() }; } let tempDataUnwrapped: &String = &(tempData.unwrap()); newObject.rawData = tempDataUnwrapped.as_str().to_owned(); let jsonOut: Result<serde_json::Value, _> = serde_json::from_str(newObject.rawData.as_str()); //assert_eq!(tempDataUnwrapped, ""); //assert_eq!(jsonOut.is_ok().to_string(), ""); //err().unwrap().to_string(), ""); if jsonOut.is_ok() { newObject.dataObject = jsonOut.unwrap(); } else { let xmlOut = serde_xml_rs::from_str(newObject.rawData.as_str()); if xmlOut.is_ok() { newObject.dataObject = xmlOut.unwrap(); } else { newObject.dataObject = serde_json::from_str("{\"data\": \"\"}").unwrap(); } } // Insert custom data here return Self { rawData: newObject.rawData.to_owned(), dataObject: newObject.dataObject.to_owned() }; } } struct DataApiService { rootUrl: String, client: reqwest::Client, //setup: (inputConfig: DataServiceConfig) -> Self, //request: (opts: DataServiceRequestOpts) -> reqwest::Response, } impl Default for DataApiService { fn default() -> Self { return Self { rootUrl: "".to_owned(), client: reqwest::Client::new() }; } } impl DataApiService { pub fn setup(mut inputConfig: DataServiceConfig) -> Self { Self { rootUrl: inputConfig.rootUrl.to_owned(), client: reqwest::Client::new() } } pub async fn request(&self, opts: DataServiceRequestOpts) -> reqwest::Response { let mut headersVar = reqwest::header::HeaderMap::new(); for (key, value) in &opts.headers { headersVar.insert(reqwest::header::HeaderName::from_lowercase(key.to_lowercase().as_bytes()).unwrap(), value.parse().unwrap()); } let mut urlEnd: String = String::from(""); if opts.urlPath.starts_with("/") { urlEnd = opts.urlPath.chars().skip(1).collect(); } else { urlEnd = String::from(opts.urlPath.clone()).clone(); } let mut urlTotal = self.rootUrl.as_str().to_owned(); urlTotal.push_str(urlEnd.as_str()); let tokioRuntime = runtime::Builder::new_current_thread().enable_all().build().unwrap(); return tokioRuntime.block_on(async { return self.client.request(opts.method.clone().to_owned(), urlTotal.clone().as_str()).body(opts.body.to_owned()).bearer_auth(opts.token.to_owned()).headers(headersVar).query(&opts.params.to_owned()).send().await.unwrap(); }); } } #[cfg(test)] mod tests { use super::*; use std::array::IntoIter; use std::iter::FromIterator; #[test] fn test_setup() { let apiService: DataApiService = DataApiService::setup(DataServiceConfig::new("https://example.com/".to_owned())); let apiService2: DataApiService = DataApiService::setup(DataServiceConfig::new("https://example.org/".to_owned())); assert_eq!(apiService.rootUrl, "https://example.com/"); assert_eq!(apiService2.rootUrl, "https://example.org/"); } #[test] fn test_request() { let apiService: DataApiService = DataApiService::setup(DataServiceConfig::new("http://dummy.restapiexample.com/api/v1/employee/1".to_owned())); let response: reqwest::Response = futures::executor::block_on(apiService.request(DataServiceRequestOpts::new("".to_owned(), reqwest::Method::GET, "".to_owned(), HashMap::<_, _>::from_iter(IntoIter::new([/*("123".to_owned(), "456".to_owned()), ("abc".to_owned(), "def".to_owned())*/])), "".to_owned(), HashMap::<_, _>::from_iter(IntoIter::new([]))))); let output: DataServiceResponseObject = DataServiceResponseObject::from(response); //assert_eq!(serde_json::to_string(&output.dataObject).unwrap(), ""); assert_eq!(output.dataObject.get("status").unwrap().as_str().unwrap(), "success"); } } fn main() { // println!("Hello, world!"); }
use crate::captcha::Captcha; use async_recursion::async_recursion; use select::document::Document; use select::predicate::{And, Attr, Class, Name}; pub struct ExtItem { pub captcha: Captcha, pub cookie: String, pub base_url: String, pub uagent: String, pub id: String, pub magnet: String, } impl ExtItem { pub fn new(cookie: String, base_url: String, id: String, uagent: String) -> Self { Self { captcha: Captcha::new(base_url.clone()), cookie, base_url, id, uagent, magnet: String::new(), } } #[async_recursion(?Send)] pub async fn fetch(&mut self) -> Result<(), reqwest::Error> { let res = reqwest::ClientBuilder::new() .cookie_store(true) .user_agent(self.uagent.as_str()) .build()? .get(format!("https://{}{}", self.base_url, self.id).as_str()) .header("Cookie", self.cookie.as_str()) .send() .await?; if res.url().path() == "/threat_defence.php" { self.cookie = self.captcha.solve().await.unwrap().unwrap(); return self.fetch().await; } let doc = Document::from(res.text().await.unwrap().as_ref()); let links = doc .find(And(Class("lista-rounded"), Name("table"))) .flat_map(|x| x.find(Attr("href", ())).collect::<Vec<_>>()) .collect::<Vec<_>>(); let mut link_iter = links.iter(); link_iter.next(); self.magnet = link_iter.next().unwrap().attr("href").unwrap().to_string(); Ok(()) } }
// TODO: what is `Arc` and what is `Rc`? use std::cmp; use std::collections::HashMap; use std::rc::Rc; use std::sync::Arc; use crate::arc_list::ArcList; use crate::syntax::{BinaryOp, Ctor, Expr, Pattern, UnaryOp, Value as SynValue, Var}; #[derive(Debug, Clone)] pub struct Res<T> { pub result: T, pub work: u64, pub span: u64, } #[derive(Debug, Clone)] pub enum Err { InvalidIteCond { cond: Arc<Value>, }, InvalidUnaryOpArgs { op: UnaryOp, inner: Arc<Value>, }, InvalidBinaryOpArgs { op: BinaryOp, lhs: Arc<Value>, rhs: Arc<Value>, }, InvalidAppArgs { inner: Arc<Value>, }, CaseNoMatch { inner: Arc<Value>, patterns: Vec<Rc<Pattern>>, }, EnvNotFound { var: Var, }, PatternNotMatched { pattern: Pattern, value: Arc<Value>, }, CtorNotMatched { ctor_pattern: Ctor, ctor_value: Ctor, }, } type EResult<T> = Result<Res<T>, Err>; #[derive(Debug, Clone)] pub enum Value { Integer(i64), Boolean(bool), Pair { lhs: Arc<Value>, rhs: Arc<Value>, }, Ctor { ctor: Ctor, inner: Arc<Value>, }, Lambda { pattern: Rc<Pattern>, expr: Rc<Expr>, env: Env, }, } impl Value { pub fn coerce_bool(&self) -> Option<bool> { match self { Value::Boolean(b) => Some(*b), _ => None, } } } pub type EnvPiece = HashMap<Var, Arc<Value>>; pub type Env = ArcList<EnvPiece>; impl Env { fn eval_var(&self, var: &Var) -> Result<Arc<Value>, Err> { for map in self.iter() { if let Some(res) = map.get(var) { return Ok(res.clone()); } } Err(Err::EnvNotFound { var: var.clone() }) } fn eval_value(&self, value: &SynValue) -> Result<Arc<Value>, Err> { match value { SynValue::Integer(inner) => Ok(Arc::new(Value::Integer(*inner))), SynValue::Boolean(inner) => Ok(Arc::new(Value::Boolean(*inner))), SynValue::Pair { lhs, rhs } => { let lhs = self.eval_value(lhs)?; let rhs = self.eval_value(rhs)?; Ok(Arc::new(Value::Pair { lhs, rhs })) } SynValue::Ctor { ctor, inner } => { let inner = self.eval_value(inner)?; Ok(Arc::new(Value::Ctor { ctor: ctor.clone(), inner, })) } SynValue::Lambda { pattern, expr } => Ok(Arc::new(Value::Lambda { pattern: pattern.clone(), expr: expr.clone(), env: self.clone(), })), } } fn eval_pattern_inner( &self, pattern: &Pattern, value: &Arc<Value>, env_piece: &mut EnvPiece, ) -> Result<(), Err> { match (pattern, &**value) { (Pattern::Var(var), _) => { env_piece.insert(var.clone(), value.clone()); Ok(()) } ( Pattern::Pair { lhs: lhs_pattern, rhs: rhs_pattern, }, Value::Pair { lhs: lhs_value, rhs: rhs_value, }, ) => { self.eval_pattern_inner(lhs_pattern, lhs_value, env_piece)?; self.eval_pattern_inner(rhs_pattern, rhs_value, env_piece)?; Ok(()) } ( Pattern::Ctor { ctor: ctor_pattern, inner: inner_pattern, }, Value::Ctor { ctor: ctor_value, inner: inner_value, }, ) => { if ctor_pattern != ctor_value { return Err(Err::CtorNotMatched { ctor_pattern: ctor_pattern.clone(), ctor_value: ctor_value.clone(), }); } self.eval_pattern_inner(inner_pattern, inner_value, env_piece)?; Ok(()) } _ => Err(Err::PatternNotMatched { pattern: pattern.clone(), value: value.clone(), }), } } fn eval_pattern(&self, pattern: &Pattern, value: &Arc<Value>) -> Result<EnvPiece, Err> { let mut env_piece = EnvPiece::new(); self.eval_pattern_inner(pattern, value, &mut env_piece)?; Ok(env_piece) } fn eval_unary_op(op: UnaryOp, inner: &Arc<Value>) -> Result<Value, Err> { match (op, &**inner) { (UnaryOp::Not, Value::Boolean(inner)) => Ok(Value::Boolean(!inner)), (UnaryOp::Neg, Value::Integer(inner)) => Ok(Value::Integer(-inner)), _ => Err(Err::InvalidUnaryOpArgs { op, inner: inner.clone(), }), } } fn eval_binary_op(op: BinaryOp, lhs: &Arc<Value>, rhs: &Arc<Value>) -> Result<Value, Err> { match (op, &**lhs, &**rhs) { (BinaryOp::Or, Value::Boolean(lhs), Value::Boolean(rhs)) => { Ok(Value::Boolean(*lhs || *rhs)) } (BinaryOp::And, Value::Boolean(lhs), Value::Boolean(rhs)) => { Ok(Value::Boolean(*lhs && *rhs)) } (BinaryOp::Xor, Value::Boolean(lhs), Value::Boolean(rhs)) => { Ok(Value::Boolean(*lhs ^ *rhs)) } (BinaryOp::Plus, Value::Integer(lhs), Value::Integer(rhs)) => { Ok(Value::Integer(*lhs + *rhs)) } (BinaryOp::Minus, Value::Integer(lhs), Value::Integer(rhs)) => { Ok(Value::Integer(*lhs - *rhs)) } (BinaryOp::Times, Value::Integer(lhs), Value::Integer(rhs)) => { Ok(Value::Integer(*lhs * *rhs)) } (BinaryOp::Over, Value::Integer(lhs), Value::Integer(rhs)) => { Ok(Value::Integer(*lhs / *rhs)) } (BinaryOp::Equal, Value::Integer(lhs), Value::Integer(rhs)) => { Ok(Value::Boolean(*lhs == *rhs)) } (BinaryOp::Less, Value::Integer(lhs), Value::Integer(rhs)) => { Ok(Value::Boolean(*lhs < *rhs)) } (BinaryOp::Le, Value::Integer(lhs), Value::Integer(rhs)) => { Ok(Value::Boolean(*lhs <= *rhs)) } (_, _, _) => Err(Err::InvalidBinaryOpArgs { op, lhs: lhs.clone(), rhs: rhs.clone(), }), } } pub fn eval_expr(&self, expr: &Expr) -> EResult<Arc<Value>> { match expr { Expr::Var(var) => Ok(Res { result: self.eval_var(var)?, work: 1, span: 1, }), Expr::Value(value) => Ok(Res { result: self.eval_value(value)?, work: 1, span: 1, }), Expr::UnaryOp { op, inner } => { let inner = self.eval_expr(inner)?; let res = Self::eval_unary_op(*op, &inner.result)?; Ok(Res { result: Arc::new(res), work: inner.work + 1, span: inner.span + 1, }) } Expr::BinaryOp { op, lhs, rhs } => { let lhs = self.eval_expr(lhs)?; let rhs = self.eval_expr(rhs)?; let res = Self::eval_binary_op(*op, &lhs.result, &rhs.result)?; Ok(Res { result: Arc::new(res), work: lhs.work + rhs.work + 1, span: cmp::max(lhs.span, rhs.span) + 1, }) } Expr::SeqPair { lhs, rhs } => { let lhs = self.eval_expr(lhs)?; let rhs = self.eval_expr(rhs)?; Ok(Res { result: Arc::new(Value::Pair { lhs: lhs.result, rhs: rhs.result, }), work: lhs.work + rhs.work + 1, span: lhs.work + rhs.work + 1, }) } Expr::ParPair { lhs, rhs } => { let lhs = self.eval_expr(lhs)?; let rhs = self.eval_expr(rhs)?; Ok(Res { result: Arc::new(Value::Pair { lhs: lhs.result, rhs: rhs.result, }), work: lhs.work + rhs.work + 1, span: cmp::max(lhs.work, rhs.work) + 1, }) } Expr::Case { inner, arms } => { let inner = self.eval_expr(inner)?; for (pattern, expr) in arms.iter() { if let Ok(env_piece) = self.eval_pattern(pattern, &inner.result) { let env = self.clone().insert(env_piece); let inner = env.eval_expr(expr)?; return Ok(Res { result: inner.result, work: inner.work + 1, span: inner.span + 1, }); } } Err(Err::CaseNoMatch { inner: inner.result, patterns: arms.iter().map(|(p, _)| p.clone()).collect(), }) } Expr::Ite { cond, lhs, rhs } => { let cond = self.eval_expr(cond)?; let cond_result = cond .result .coerce_bool() .ok_or(Err::InvalidIteCond { cond: cond.result })?; let body = if cond_result { lhs } else { rhs }; let body = self.eval_expr(body)?; Ok(Res { result: body.result, work: cond.work + body.work + 1, span: cond.span + body.span + 1, }) } Expr::App { lhs, rhs } => { let lhs = self.eval_expr(lhs)?; let rhs = self.eval_expr(rhs)?; let (lhs_pattern, lhs_expr, lhs_env) = match &*lhs.result { Value::Lambda { pattern, expr, env } => (pattern, expr, env), _ => Err(Err::InvalidAppArgs { inner: lhs.result })?, }; let env_piece = self.eval_pattern(lhs_pattern, &rhs.result)?; let env = lhs_env.clone().insert(env_piece); let app = env.eval_expr(lhs_expr)?; Ok(Res { result: app.result, work: lhs.work + rhs.work + app.work + 1, span: cmp::max(lhs.span, rhs.span) + app.span + 1, }) } Expr::Let { binds, expr } => { let mut env_piece = HashMap::new(); let mut work = 0; let mut span = 0; for bind in binds.iter() { let res = self.eval_expr(&bind.expr)?; env_piece.insert(bind.var.clone(), res.result); work += res.work; span += res.span; } let env = self.clone().insert(env_piece); let res = env.eval_expr(expr)?; Ok(Res { result: res.result, work: work + res.work + 1, span: span + res.span + 1, }) } } } }
#[macro_use] pub(crate) mod compare;
// This file is part of Substrate. // Copyright (C) 2017-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. use super::*; use crate::testing::TaskExecutor; use assert_matches::assert_matches; use futures::{ compat::{Future01CompatExt, Stream01CompatExt}, executor, }; use sc_block_builder::BlockBuilderProvider; use sp_rpc::list::ListOrValue; use substrate_test_runtime_client::{ prelude::*, runtime::{Block, Header, H256}, sp_consensus::BlockOrigin, }; #[test] fn should_return_header() { let client = Arc::new(substrate_test_runtime_client::new()); let api = new_full(client.clone(), SubscriptionManager::new(Arc::new(TaskExecutor))); assert_matches!( api.header(Some(client.genesis_hash()).into()).wait(), Ok(Some(ref x)) if x == &Header { parent_hash: H256::from_low_u64_be(0), number: 0, state_root: x.state_root.clone(), extrinsics_root: "03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314".parse().unwrap(), digest: Default::default(), } ); assert_matches!( api.header(None.into()).wait(), Ok(Some(ref x)) if x == &Header { parent_hash: H256::from_low_u64_be(0), number: 0, state_root: x.state_root.clone(), extrinsics_root: "03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314".parse().unwrap(), digest: Default::default(), } ); assert_matches!(api.header(Some(H256::from_low_u64_be(5)).into()).wait(), Ok(None)); } #[test] fn should_return_a_block() { let mut client = Arc::new(substrate_test_runtime_client::new()); let api = new_full(client.clone(), SubscriptionManager::new(Arc::new(TaskExecutor))); let block = client.new_block(Default::default()).unwrap().build().unwrap().block; let block_hash = block.hash(); client.import(BlockOrigin::Own, block).unwrap(); // Genesis block is not justified assert_matches!( api.block(Some(client.genesis_hash()).into()).wait(), Ok(Some(SignedBlock { justification: None, .. })) ); assert_matches!( api.block(Some(block_hash).into()).wait(), Ok(Some(ref x)) if x.block == Block { header: Header { parent_hash: client.genesis_hash(), number: 1, state_root: x.block.header.state_root.clone(), extrinsics_root: "03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314".parse().unwrap(), digest: Default::default(), }, extrinsics: vec![], } ); assert_matches!( api.block(None.into()).wait(), Ok(Some(ref x)) if x.block == Block { header: Header { parent_hash: client.genesis_hash(), number: 1, state_root: x.block.header.state_root.clone(), extrinsics_root: "03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314".parse().unwrap(), digest: Default::default(), }, extrinsics: vec![], } ); assert_matches!(api.block(Some(H256::from_low_u64_be(5)).into()).wait(), Ok(None)); } #[test] fn should_return_block_hash() { let mut client = Arc::new(substrate_test_runtime_client::new()); let api = new_full(client.clone(), SubscriptionManager::new(Arc::new(TaskExecutor))); assert_matches!( api.block_hash(None.into()), Ok(ListOrValue::Value(Some(ref x))) if x == &client.genesis_hash() ); assert_matches!( api.block_hash(Some(ListOrValue::Value(0u64.into())).into()), Ok(ListOrValue::Value(Some(ref x))) if x == &client.genesis_hash() ); assert_matches!( api.block_hash(Some(ListOrValue::Value(1u64.into())).into()), Ok(ListOrValue::Value(None)) ); let block = client.new_block(Default::default()).unwrap().build().unwrap().block; client.import(BlockOrigin::Own, block.clone()).unwrap(); assert_matches!( api.block_hash(Some(ListOrValue::Value(0u64.into())).into()), Ok(ListOrValue::Value(Some(ref x))) if x == &client.genesis_hash() ); assert_matches!( api.block_hash(Some(ListOrValue::Value(1u64.into())).into()), Ok(ListOrValue::Value(Some(ref x))) if x == &block.hash() ); assert_matches!( api.block_hash(Some(ListOrValue::Value(sp_core::U256::from(1u64).into())).into()), Ok(ListOrValue::Value(Some(ref x))) if x == &block.hash() ); assert_matches!( api.block_hash(Some(vec![0u64.into(), 1u64.into(), 2u64.into()].into())), Ok(ListOrValue::List(list)) if list == &[client.genesis_hash().into(), block.hash().into(), None] ); } #[test] fn should_return_finalized_hash() { let mut client = Arc::new(substrate_test_runtime_client::new()); let api = new_full(client.clone(), SubscriptionManager::new(Arc::new(TaskExecutor))); assert_matches!( api.finalized_head(), Ok(ref x) if x == &client.genesis_hash() ); // import new block let block = client.new_block(Default::default()).unwrap().build().unwrap().block; client.import(BlockOrigin::Own, block).unwrap(); // no finalization yet assert_matches!( api.finalized_head(), Ok(ref x) if x == &client.genesis_hash() ); // finalize client.finalize_block(BlockId::number(1), None).unwrap(); assert_matches!( api.finalized_head(), Ok(ref x) if x == &client.block_hash(1).unwrap().unwrap() ); } #[test] fn should_notify_about_latest_block() { let (subscriber, id, transport) = Subscriber::new_test("test"); { let mut client = Arc::new(substrate_test_runtime_client::new()); let api = new_full(client.clone(), SubscriptionManager::new(Arc::new(TaskExecutor))); api.subscribe_all_heads(Default::default(), subscriber); // assert id assigned assert!(matches!(executor::block_on(id.compat()), Ok(Ok(SubscriptionId::String(_))))); let block = client.new_block(Default::default()).unwrap().build().unwrap().block; client.import(BlockOrigin::Own, block).unwrap(); } // assert initial head sent. let (notification, next) = executor::block_on(transport.into_future().compat()).unwrap(); assert!(notification.is_some()); // assert notification sent to transport let (notification, next) = executor::block_on(next.into_future().compat()).unwrap(); assert!(notification.is_some()); // no more notifications on this channel assert_eq!(executor::block_on(next.into_future().compat()).unwrap().0, None); } #[test] fn should_notify_about_best_block() { let (subscriber, id, transport) = Subscriber::new_test("test"); { let mut client = Arc::new(substrate_test_runtime_client::new()); let api = new_full(client.clone(), SubscriptionManager::new(Arc::new(TaskExecutor))); api.subscribe_new_heads(Default::default(), subscriber); // assert id assigned assert!(matches!(executor::block_on(id.compat()), Ok(Ok(SubscriptionId::String(_))))); let block = client.new_block(Default::default()).unwrap().build().unwrap().block; client.import(BlockOrigin::Own, block).unwrap(); } // assert initial head sent. let (notification, next) = executor::block_on(transport.into_future().compat()).unwrap(); assert!(notification.is_some()); // assert notification sent to transport let (notification, next) = executor::block_on(next.into_future().compat()).unwrap(); assert!(notification.is_some()); // no more notifications on this channel assert_eq!(executor::block_on(Stream01CompatExt::compat(next).into_future()).0, None); } #[test] fn should_notify_about_finalized_block() { let (subscriber, id, transport) = Subscriber::new_test("test"); { let mut client = Arc::new(substrate_test_runtime_client::new()); let api = new_full(client.clone(), SubscriptionManager::new(Arc::new(TaskExecutor))); api.subscribe_finalized_heads(Default::default(), subscriber); // assert id assigned assert!(matches!(executor::block_on(id.compat()), Ok(Ok(SubscriptionId::String(_))))); let block = client.new_block(Default::default()).unwrap().build().unwrap().block; client.import(BlockOrigin::Own, block).unwrap(); client.finalize_block(BlockId::number(1), None).unwrap(); } // assert initial head sent. let (notification, next) = executor::block_on(transport.into_future().compat()).unwrap(); assert!(notification.is_some()); // assert notification sent to transport let (notification, next) = executor::block_on(next.into_future().compat()).unwrap(); assert!(notification.is_some()); // no more notifications on this channel assert_eq!(executor::block_on(next.into_future().compat()).unwrap().0, None); }
use std::collections::HashMap; pub fn solve1a(input: Vec<i32>) -> i32 { let mut running_sum: i32 = 0; for num in input.iter() { running_sum += num } running_sum } pub fn solve1b(input: Vec<i32>) -> i32 { let mut seen_map: HashMap<i32, bool> = HashMap::new(); seen_map.insert(0, true); solve1b_rec(input, seen_map, 0) } fn solve1b_rec(input: Vec<i32>, mut seen_map: HashMap<i32, bool>, prev_running_sum: i32) -> i32 { let mut running_sum: i32 = prev_running_sum; for num in input.iter() { running_sum += num; if seen_map.contains_key(&running_sum) { return running_sum; } else { seen_map.insert(running_sum, true); } } solve1b_rec(input, seen_map, running_sum) }
use alga::general::{Real, SubsetOf, SupersetOf}; use alga::linear::Rotation; use core::{SquareMatrix, OwnedSquareMatrix}; use core::dimension::{DimName, DimNameAdd, DimNameSum, U1}; use core::storage::OwnedStorage; use core::allocator::{Allocator, OwnedAllocator}; use geometry::{PointBase, TranslationBase, IsometryBase, SimilarityBase, TransformBase, SuperTCategoryOf, TAffine}; /* * This file provides the following conversions: * ============================================= * * IsometryBase -> IsometryBase * IsometryBase -> SimilarityBase * IsometryBase -> TransformBase * IsometryBase -> Matrix (homogeneous) */ impl<N1, N2, D: DimName, SA, SB, R1, R2> SubsetOf<IsometryBase<N2, D, SB, R2>> for IsometryBase<N1, D, SA, R1> where N1: Real, N2: Real + SupersetOf<N1>, R1: Rotation<PointBase<N1, D, SA>> + SubsetOf<R2>, R2: Rotation<PointBase<N2, D, SB>>, SA: OwnedStorage<N1, D, U1>, SB: OwnedStorage<N2, D, U1>, SA::Alloc: OwnedAllocator<N1, D, U1, SA>, SB::Alloc: OwnedAllocator<N2, D, U1, SB> { #[inline] fn to_superset(&self) -> IsometryBase<N2, D, SB, R2> { IsometryBase::from_parts( self.translation.to_superset(), self.rotation.to_superset() ) } #[inline] fn is_in_subset(iso: &IsometryBase<N2, D, SB, R2>) -> bool { ::is_convertible::<_, TranslationBase<N1, D, SA>>(&iso.translation) && ::is_convertible::<_, R1>(&iso.rotation) } #[inline] unsafe fn from_superset_unchecked(iso: &IsometryBase<N2, D, SB, R2>) -> Self { IsometryBase::from_parts( iso.translation.to_subset_unchecked(), iso.rotation.to_subset_unchecked() ) } } impl<N1, N2, D: DimName, SA, SB, R1, R2> SubsetOf<SimilarityBase<N2, D, SB, R2>> for IsometryBase<N1, D, SA, R1> where N1: Real, N2: Real + SupersetOf<N1>, R1: Rotation<PointBase<N1, D, SA>> + SubsetOf<R2>, R2: Rotation<PointBase<N2, D, SB>>, SA: OwnedStorage<N1, D, U1>, SB: OwnedStorage<N2, D, U1>, SA::Alloc: OwnedAllocator<N1, D, U1, SA>, SB::Alloc: OwnedAllocator<N2, D, U1, SB> { #[inline] fn to_superset(&self) -> SimilarityBase<N2, D, SB, R2> { SimilarityBase::from_isometry( self.to_superset(), N2::one() ) } #[inline] fn is_in_subset(sim: &SimilarityBase<N2, D, SB, R2>) -> bool { ::is_convertible::<_, IsometryBase<N1, D, SA, R1>>(&sim.isometry) && sim.scaling() == N2::one() } #[inline] unsafe fn from_superset_unchecked(sim: &SimilarityBase<N2, D, SB, R2>) -> Self { ::convert_ref_unchecked(&sim.isometry) } } impl<N1, N2, D, SA, SB, R, C> SubsetOf<TransformBase<N2, D, SB, C>> for IsometryBase<N1, D, SA, R> where N1: Real, N2: Real + SupersetOf<N1>, SA: OwnedStorage<N1, D, U1>, SB: OwnedStorage<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>, C: SuperTCategoryOf<TAffine>, R: Rotation<PointBase<N1, D, SA>> + SubsetOf<OwnedSquareMatrix<N1, DimNameSum<D, U1>, SA::Alloc>> + // needed by: .to_homogeneous() SubsetOf<SquareMatrix<N2, DimNameSum<D, U1>, SB>>, // needed by: ::convert_unchecked(mm) D: DimNameAdd<U1>, SA::Alloc: OwnedAllocator<N1, D, U1, SA> + Allocator<N1, D, D> + // needed by R Allocator<N1, DimNameSum<D, U1>, DimNameSum<D, U1>> + // needed by: .to_homogeneous() Allocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>, // needed by R SB::Alloc: OwnedAllocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>, SB> + Allocator<N2, D, D> + // needed by: mm.fixed_slice_mut Allocator<N2, D, U1> + // needed by: m.fixed_slice Allocator<N2, U1, D> { // needed by: m.fixed_slice #[inline] fn to_superset(&self) -> TransformBase<N2, D, SB, C> { TransformBase::from_matrix_unchecked(self.to_homogeneous().to_superset()) } #[inline] fn is_in_subset(t: &TransformBase<N2, D, SB, C>) -> bool { <Self as SubsetOf<_>>::is_in_subset(t.matrix()) } #[inline] unsafe fn from_superset_unchecked(t: &TransformBase<N2, D, SB, C>) -> Self { Self::from_superset_unchecked(t.matrix()) } } impl<N1, N2, D, SA, SB, R> SubsetOf<SquareMatrix<N2, DimNameSum<D, U1>, SB>> for IsometryBase<N1, D, SA, R> where N1: Real, N2: Real + SupersetOf<N1>, SA: OwnedStorage<N1, D, U1>, SB: OwnedStorage<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>, R: Rotation<PointBase<N1, D, SA>> + SubsetOf<OwnedSquareMatrix<N1, DimNameSum<D, U1>, SA::Alloc>> + // needed by: .to_homogeneous() SubsetOf<SquareMatrix<N2, DimNameSum<D, U1>, SB>>, // needed by: ::convert_unchecked(mm) D: DimNameAdd<U1>, SA::Alloc: OwnedAllocator<N1, D, U1, SA> + Allocator<N1, D, D> + // needed by R Allocator<N1, DimNameSum<D, U1>, DimNameSum<D, U1>> + // needed by: .to_homogeneous() Allocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>, // needed by R SB::Alloc: OwnedAllocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>, SB> + Allocator<N2, D, D> + // needed by: mm.fixed_slice_mut Allocator<N2, D, U1> + // needed by: m.fixed_slice Allocator<N2, U1, D> { // needed by: m.fixed_slice #[inline] fn to_superset(&self) -> SquareMatrix<N2, DimNameSum<D, U1>, SB> { self.to_homogeneous().to_superset() } #[inline] fn is_in_subset(m: &SquareMatrix<N2, DimNameSum<D, U1>, SB>) -> bool { let rot = m.fixed_slice::<D, D>(0, 0); let bottom = m.fixed_slice::<U1, D>(D::dim(), 0); // Scalar types agree. m.iter().all(|e| SupersetOf::<N1>::is_in_subset(e)) && // The block part is a rotation. rot.is_special_orthogonal(N2::default_epsilon() * ::convert(100.0)) && // The bottom row is (0, 0, ..., 1) bottom.iter().all(|e| e.is_zero()) && m[(D::dim(), D::dim())] == N2::one() } #[inline] unsafe fn from_superset_unchecked(m: &SquareMatrix<N2, DimNameSum<D, U1>, SB>) -> Self { let t = m.fixed_slice::<D, U1>(0, D::dim()).into_owned(); let t = TranslationBase::from_vector(::convert_unchecked(t)); Self::from_parts(t, ::convert_unchecked(m.clone_owned())) } }
#[macro_export] macro_rules! declare_types { { $(#[$attr:meta])* pub class $cls:ident { $($body:tt)* } $($rest:tt)* } => { define_class! { #![reopen(false)] #![pub(true)] $(#[$attr])* pub class $cls { $($body)* } $($rest)* } }; { $(#[$attr:meta])* class $cls:ident { $($body:tt)* } $($rest:tt)* } => { define_class! { #![reopen(false)] #![pub(false)] $(#[$attr])* class $cls { $($body)* } $($rest)* } }; { $(#[$attr:meta])* pub reopen class $cls:ident { $($body:tt)* } $($rest:tt)* } => { define_class! { #![reopen(true)] #![pub(true)] $(#[$attr])* pub class $cls { $($body)* } $($rest)* } }; { $(#[$attr:meta])* reopen class $cls:ident { $($body:tt)* } $($rest:tt)* } => { define_class! { #![reopen(true)] #![pub(false)] $(#[$attr])* class $cls { $($body)* } $($rest)* } }; { } => { }; } #[doc(hidden)] #[macro_export] macro_rules! define_struct { (true $(#[$attr:meta])* $cls:ident $($fields:tt)*) => ( #[derive(Clone, Debug)] #[repr(C)] $(#[$attr])* pub struct $cls { helix: $crate::Metadata, $($fields)* } ); (false $(#[$attr:meta])* $cls:ident $($fields:tt)*) => ( #[derive(Clone, Debug)] #[repr(C)] $(#[$attr])* struct $cls { helix: $crate::Metadata, $($fields)* } ); } #[doc(hidden)] #[macro_export] macro_rules! define_class { { #![reopen(false)] #![pub($is_pub:tt)] $(#[$attr:meta])* class $cls:ident { struct { $($fields:tt)* } def initialize($($args:tt)*) { $($initbody:tt)* } $($body:tt)* } $($rest:tt)* } => { define_struct!($(#[$attr:meta])* $is_pub $cls $($fields)*); class_definition! { #![reopen(false)] $cls ; () ; () ; $($body)* fn initialize($($args)*) { $($initbody)* } } declare_types! { $($rest)* } }; { #![reopen(false)] #![pub($is_pub:tt)] $(#[$attr:meta])* class $cls:ident { $($body:tt)* } $($rest:tt)* } => { define_struct!($(#[$attr:meta])* $is_pub $cls); class_definition! { #![reopen(false)] $cls ; () ; () ; $($body)* () } declare_types! { $($rest)* } }; { #![reopen(true)] #![pub($is_pub:tt)] $(#[$attr:meta])* class $cls:ident { $($body:tt)* } $($rest:tt)* } => { define_struct!($(#[$attr:meta])* $is_pub $cls); class_definition! { #![reopen(true)] $cls ; () ; () ; $($body)* () } declare_types! { $($rest)* } }; } #[doc(hidden)] #[macro_export] macro_rules! class_definition { { #![reopen($expr:tt)] $cls:ident; ($($mimpl:tt)*) ; ($($mdef:tt)*) ; defn $name:ident ; { $($self_mod:tt)* } ; $self_arg:tt ; ($($arg:ident : $argty:ty),*) ; $body:block ; $ret:ty ; $($rest:tt)* } => { class_definition! { #![reopen($expr)] $cls ; ($($mimpl)* pub fn $name($($self_mod)* $self_arg, $($arg : $argty),*) -> $ret $body) ; ($($mdef)* { extern "C" fn __ruby_method__(rb_self: $crate::sys::VALUE, $($arg : $crate::sys::VALUE),*) -> $crate::sys::VALUE { let checked = __checked_call__(rb_self, $($arg),*); match checked { Ok(val) => $crate::ToRuby::to_ruby(val), Err(err) => { println!("TYPE ERROR: {:?}", err); unsafe { $crate::sys::Qnil } } } } fn __checked_call__(rb_self: $crate::sys::VALUE, $($arg : $crate::sys::VALUE),*) -> Result<$ret, ::std::ffi::CString> { #[allow(unused_imports)] use $crate::{ToRust}; let rust_self = $cls::from_checked_rb_value(rb_self); $( let $arg = try!($crate::UncheckedValue::<$argty>::to_checked($arg)); )* $( let $arg = $crate::ToRust::to_rust($arg); )* Ok(rust_self.$name($($arg),*)) } let name = stringify!($name); let arity = method_arity!($($arg),*); let method = __ruby_method__ as *const $crate::libc::c_void; $crate::MethodDefinition::new(name, method, arity) }) ; $($rest)* } }; // def ident(&self, ...args) -> ty { ... } { #![reopen($expr:tt)] $cls:ident; ($($mimpl:tt)*) ; ($($mdef:tt)*) ; def $name:ident( & $self_arg:tt , $($arg:ident : $argty:ty),* ) -> $ret:ty $body:block $($rest:tt)* } => { class_definition! { #![reopen($expr)] $cls; ($($mimpl)*) ; ($($mdef)*) ; defn $name ; { & } ; $self_arg ; ($($arg : $argty),*) ; $body ; $ret ; $($rest)* } }; // def ident(&self, ...args) { ... } { #![reopen($expr:tt)] $cls:ident; ($($mimpl:tt)*) ; ($($mdef:tt)*) ; def $name:ident( & $self_arg:tt , $($arg:ident : $argty:ty),* ) $body:block $($rest:tt)* } => { class_definition! { #![reopen($expr)] $cls; ($($mimpl)*) ; ($($mdef)*) ; defn $name ; { & } ; $self_arg ; ($($arg : $argty),*) ; $body ; () ; $($rest)* } }; // def ident(&self) -> ty { ... } { #![reopen($expr:tt)] $cls:ident; ($($mimpl:tt)*) ; ($($mdef:tt)*) ; def $name:ident( & $self_arg:tt ) -> $ret:ty $body:block $($rest:tt)* } => { class_definition! { #![reopen($expr)] $cls; ($($mimpl)*) ; ($($mdef)*) ; defn $name ; { & } ; $self_arg ; () ; $body ; $ret ; $($rest)* } }; // def ident(&self) { ... } { #![reopen($expr:tt)] $cls:ident; ($($mimpl:tt)*) ; ($($mdef:tt)*) ; def $name:ident( & $self_arg:tt ) $body:block $($rest:tt)* } => { class_definition! { #![reopen($expr)] $cls; ($($mimpl)*) ; ($($mdef)*) ; defn $name ; { & } ; $self_arg ; () ; $body ; () ; $($rest)* } }; // def ident(&mut self, ...args) -> ty { ... } { #![reopen($expr:tt)] $cls:ident; ($($mimpl:tt)*) ; ($($mdef:tt)*) ; def $name:ident( &mut $self_arg:tt , $($arg:ident : $argty:ty),* ) -> $ret:ty $body:block $($rest:tt)* } => { class_definition! { #![reopen($expr)] $cls; ($($mimpl)*) ; ($($mdef)*) ; defn $name ; { &mut } ; $self_arg ; ($($arg : $argty),*) ; $body ; $ret ; $($rest)* } }; // def ident(&mut self, ...args) { ... } { #![reopen($expr:tt)] $cls:ident; ($($mimpl:tt)*) ; ($($mdef:tt)*) ; def $name:ident( &mut $self_arg:tt , $($arg:ident : $argty:ty),* ) $body:block $($rest:tt)* } => { class_definition! { #![reopen($expr)] $cls; ($($mimpl)*) ; ($($mdef)*) ; defn $name ; { &mut } ; $self_arg ; ($($arg : $argty),*) ; $body ; () ; $($rest)* } }; // def ident(&mut self) -> ty { ... } { #![reopen($expr:tt)] $cls:ident; ($($mimpl:tt)*) ; ($($mdef:tt)*) ; def $name:ident( &mut $self_arg:tt ) -> $ret:ty $body:block $($rest:tt)* } => { class_definition! { #![reopen($expr)] $cls; ($($mimpl)*) ; ($($mdef)*) ; defn $name ; { &mut } ; $self_arg ; () ; $body ; $ret ; $($rest)* } }; // def ident(&mut self) { ... } { #![reopen($expr:tt)] $cls:ident; ($($mimpl:tt)*) ; ($($mdef:tt)*) ; def $name:ident( &mut $self_arg:tt ) $body:block $($rest:tt)* } => { class_definition! { #![reopen($expr)] $cls; ($($mimpl)*) ; ($($mdef)*) ; defn $name ; { &mut } ; $self_arg ; () ; $body ; () ; $($rest)* } }; ( #![reopen(false)] $cls:ident ; ($($mimpl:tt)*) ; ($($mdef:block)*) ; fn initialize($($args:tt)*) { $($initbody:tt)* } ) => { item! { impl $cls { fn initialize($($args)*) -> $cls { $($initbody)* } fn from_checked_rb_value<'a>(value: $crate::sys::VALUE) -> &'a mut $cls { unsafe { ::std::mem::transmute($crate::sys::Data_Get_Struct_Value(value)) } } $($mimpl)* } } item! { impl<'a> $crate::UncheckedValue<&'a $cls> for $crate::sys::VALUE { fn to_checked(self) -> $crate::CheckResult<&'a $cls> { use $crate::{CheckedValue, sys}; use ::std::ffi::{CStr, CString}; if unsafe { __HELIX_ID == ::std::mem::transmute(sys::rb_obj_class(self)) } { Ok(unsafe { CheckedValue::new(self) }) } else { let val = unsafe { CStr::from_ptr(sys::rb_obj_classname(self)).to_string_lossy() }; Err(CString::new(format!("No implicit conversion of {} into {}", val, stringify!($cls))).unwrap()) } } } } item! { impl<'a> $crate::ToRust<&'a $cls> for $crate::CheckedValue<&'a $cls> { fn to_rust(self) -> &'a $cls { unsafe { ::std::mem::transmute($crate::sys::Data_Get_Struct_Value(self.inner)) } } } } item! { impl<'a> $crate::ToRuby for &'a $cls { fn to_ruby(self) -> $crate::sys::VALUE { self.helix } } } static mut __HELIX_ID: usize = 0; init! { extern "C" fn __mark__(_klass: &$cls) {} extern "C" fn __free__(_klass: Option<Box<$cls>>) {} extern "C" fn __alloc__(klass: $crate::sys::VALUE) -> $crate::sys::VALUE { unsafe { let instance = $crate::sys::Data_Wrap_Struct( klass, ::std::mem::transmute(__mark__ as usize), ::std::mem::transmute(__free__ as usize), ::std::ptr::null() ); // FIXME: this should really be called during Ruby's initialize, with arguments __initialize__(instance); instance } } extern "C" fn __initialize__(rb_self: $crate::sys::VALUE) { unsafe { let data = Box::new($cls::initialize(rb_self)); $crate::sys::Data_Set_Struct_Value(rb_self, ::std::mem::transmute(data)); } } let def = $crate::ClassDefinition::wrapped(stringify!($cls), __alloc__)$(.define_method($mdef))*; unsafe { __HELIX_ID = ::std::mem::transmute(def.class) }; } }; ( #![reopen(false)] $cls:ident ; ($($mimpl:tt)*) ; ($($mdef:block)*) ; () ) => { impl_simple_class!( $cls ; ($($mimpl)*) ); static mut __HELIX_ID: usize = 0; init! { let def = $crate::ClassDefinition::new(stringify!($cls))$(.define_method($mdef))*; unsafe { __HELIX_ID = ::std::mem::transmute(def.class) }; } }; ( #![reopen(true)] $cls:ident ; ($($mimpl:tt)*) ; ($($mdef:block)*) ; () ) => { impl_simple_class!( $cls ; ($($mimpl)*) ); static mut __HELIX_ID: usize = 0; init! { let def = $crate::ClassDefinition::reopen(stringify!($cls))$(.define_method($mdef))*; unsafe { __HELIX_ID = ::std::mem::transmute(def.class) }; } }; } #[doc(hidden)] #[macro_export] macro_rules! impl_simple_class { ( $cls:ident ; ($($mimpl:tt)*) ) => { item! { impl $cls { $($mimpl)* fn from_checked_rb_value(value: $crate::sys::VALUE) -> $cls { $cls { helix: value } } } } item! { impl<'a> $crate::UncheckedValue<&'a $cls> for $crate::sys::VALUE { fn to_checked(self) -> $crate::CheckResult<&'a $cls> { use $crate::{CheckedValue, sys}; use ::std::ffi::{CStr, CString}; if unsafe { __HELIX_ID == ::std::mem::transmute(sys::rb_obj_class(self)) } { Ok(unsafe { CheckedValue::new(self) }) } else { let val = unsafe { CStr::from_ptr(sys::rb_obj_classname(self)).to_string_lossy() }; Err(CString::new(format!("No implicit conversion of {} into {}", val, stringify!($cls))).unwrap()) } } } } item! { impl<'a> $crate::ToRust<&'a $cls> for $crate::CheckedValue<&'a $cls> { fn to_rust(self) -> &'a $cls { unsafe { ::std::mem::transmute(self.inner) } } } } item! { impl<'a> $crate::ToRuby for &'a $cls { fn to_ruby(self) -> $crate::sys::VALUE { unsafe { ::std::mem::transmute(self) } } } } } } #[macro_export] macro_rules! init { { $($body:tt)* } => { #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn Init_native() { $crate::sys::check_version(); $($body)* } } } #[macro_export] macro_rules! method { ( $name:ident( $($args:ident),* ) { $($block:stmt;)* } ) => { #[no_mangle] pub extern "C" fn $name(rb_self: $crate::sys::VALUE, $($args : $crate::sys::VALUE),*) -> $crate::sys::VALUE { $($block;)* $crate::sys::Qnil } } } #[doc(hidden)] #[macro_export] macro_rules! item { ($it: item) => { $it } } #[doc(hidden)] #[macro_export] macro_rules! replace_expr { ($_t:tt $sub:expr) => {$sub}; } #[doc(hidden)] #[macro_export] macro_rules! method_arity { ( $($id:pat ),* ) => { { 0isize $(+ replace_expr!($id 1isize))* } } }
//! # 297. 二叉树的序列化与反序列化 //! https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/ //! 序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中, //! 同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。 use std::cell::RefCell; use std::rc::Rc; mod dfs; mod dfs_mid; // Definition for a binary tree node. #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { TreeNode { val, left: None, right: None, } } pub fn new_node( val: i32, left: Option<Rc<RefCell<TreeNode>>>, right: Option<Rc<RefCell<TreeNode>>>, ) -> Self { TreeNode { val, left, right } } } pub trait TreeCodec { fn serialize(&self, root: Option<Rc<RefCell<TreeNode>>>) -> String; fn deserialize(&self, data: String) -> Option<Rc<RefCell<TreeNode>>>; } pub struct Codec { codec: Box<dyn TreeCodec>, } /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl Codec { pub fn new() -> Self { Codec { // codec: Box::new(dfs::CodecDFS::new()), codec: Box::new(dfs_mid::CodecDFSMid::new()), } } pub fn serialize(&self, root: Option<Rc<RefCell<TreeNode>>>) -> String { self.codec.serialize(root) } pub fn deserialize(&self, data: String) -> Option<Rc<RefCell<TreeNode>>> { self.codec.deserialize(data) } } #[cfg(test)] mod tests { use super::Codec; use super::TreeNode; use std::cell::RefCell; use std::rc::Rc; #[test] fn it_works() { //Rc<RefCell<TreeNode>>> let node = Rc::new(RefCell::new(TreeNode::new_node( -1, Some(Rc::new(RefCell::new(TreeNode::new_node( 2, Some(Rc::new(RefCell::new(TreeNode::new(4)))), None, )))), Some(Rc::new(RefCell::new(TreeNode::new(3)))), ))); let seri = Codec::new().serialize(Some(node.clone())); println!("{}", seri.clone()); let deser = Codec::new().deserialize(seri); println!("{}", Codec::new().serialize(deser.clone())); // println!("{:?}", deser.clone()); assert_eq!(Some(node), deser); } }
/// Describe a game piece #[derive(Clone, PartialEq, Debug)] pub struct Tile { letter : char, wildcard : bool, points : u8, } impl Tile { /// Create a tile /// /// # Arguments /// * `letter` - The letter on the tile /// * `points` - The amount of points this letter gives /// * `wildcard` - Whether this tile is a joker pub fn new(letter : char, points : u8, wildcard : bool) -> Tile { Tile { letter, wildcard, points} } /// Get the letter pub fn letter(&self) -> char { self.letter } /// Get the wildcard field pub fn wildcard(&self) -> bool { self.wildcard } /// Get the amount of point it gives pub fn points(&self) -> u8 { self.points } /// Replace the char /// /// Works only when the tile has the wildcard flag /// /// # Argument /// * `c` - The letter to set pub fn set_wildcard(&mut self, c : char) { if self.wildcard == true { self.letter = c; } } }
use std::collections::linked_list::*; use std::iter::FromIterator; use std::str::Chars; #[derive(Clone,Debug)] pub enum Operator { Add, Sub, Mul, Div, Mode, Assign, And, Or, AddAssign, SubAssign, MulAssign, DivAssign, AndAssign, OrAssign, Compare, } #[derive(Clone,Debug)] pub enum Type { Str(String), Int(i64), Float(f64), } #[derive(Clone,Debug)] pub enum ReservedWord { If, Loop, FN, Let, LParen, RParen, LBrace, RBrace, Continue, Break, } #[derive(Clone,Debug)] pub enum Token { Operator(Operator), Type(Type), ReservedWord(ReservedWord), Identifier(String), Error, } struct Buffer { vec: Vec<char>, cur: usize, } impl Buffer { fn new(iter: Chars) -> Self { let vec = Vec::from_iter(iter); let cur = 0; Self { vec, cur } } fn next(&mut self) -> Option<&char> { let item = self.vec.get(self.cur); self.cur += 1; item } fn prev(&mut self) -> Option<&char> { self.cur -= 1; let item = self.vec.get(self.cur); item } } pub struct Tokenizer { Toks: Vec<Token>, } impl Tokenizer { pub fn new() -> Self { let Toks = Vec::new(); Self { Toks } } fn two_operator(c: char, b: &mut Buffer) -> Option<Token> { let x = b.next(); if x.is_some() { let x = x.unwrap(); if (*x == '=') { if (c == '+') { return Some(Token::Operator(Operator::AddAssign)); } else if (c == '-') { return Some(Token::Operator(Operator::SubAssign)); } else if (c == '*') { return Some(Token::Operator(Operator::MulAssign)); } else if (c == '/') { return Some(Token::Operator(Operator::DivAssign)); } else if (c == '=') { return Some(Token::Operator(Operator::Compare)); } else if (c == '&') { return Some(Token::Operator(Operator::AndAssign)); } else if (c == '|') { return Some(Token::Operator(Operator::OrAssign)); } else { return None; } } } b.prev(); if (c == '+') { Some(Token::Operator(Operator::Add)) } else if (c == '-') { Some(Token::Operator(Operator::Sub)) } else if (c == '*') { Some(Token::Operator(Operator::Mul)) } else if (c == '/') { Some(Token::Operator(Operator::Div)) } else if (c == '=') { Some(Token::Operator(Operator::Assign)) } else if (c == '&') { Some(Token::Operator(Operator::And)) } else if (c == '|') { Some(Token::Operator(Operator::Or)) } else { None } } fn get_token_kind(s: String) -> Token { if s == "if" { Token::ReservedWord(ReservedWord::If) } else if s == "loop" { Token::ReservedWord(ReservedWord::Loop) } else if s == "fn" { Token::ReservedWord(ReservedWord::FN) } else if s == "let" { Token::ReservedWord(ReservedWord::Let) } else if s == "continue" { Token::ReservedWord(ReservedWord::Continue) } else if s == "break" { Token::ReservedWord(ReservedWord::Break) } else { Token::Identifier(s) } } fn chars_to_id(s: char, b: &mut Buffer) -> String { let mut result: String = String::new(); result.push(s); loop { let x = b.next(); if x.is_none() { break; } let x = x.unwrap(); if !x.is_alphanumeric() { break; } result.push(*x) } b.prev(); result } fn chars_to_int(s: char, b: &mut Buffer) -> i64 { let mut result: i64 = s.to_digit(10).unwrap() as i64; loop { let x = b.next(); if x.is_none() { break; } let x = x.unwrap(); if !x.is_ascii_digit() { break; } result *= 10; result += x.to_digit(10).unwrap() as i64; } b.prev(); result } fn chars_to_str(s: char, b: &mut Buffer) -> String { let mut result: String = String::new(); loop { let x = b.next(); if x.is_none() { break; } let x = x.unwrap(); if *x == '"' { break; } result.push(*x) } result } pub fn tokenize(&mut self, s: &str) -> Vec<Token> { let len = s.len(); let mut char_buffer = Buffer::new(s.chars()); loop { let ch = char_buffer.next(); if (ch.is_none()) { break; } let ch = ch.unwrap(); if ch.is_ascii_whitespace() { continue; } if ch.is_ascii_alphabetic() { let t = Self::chars_to_id(*ch, &mut char_buffer); self.Toks.push(Self::get_token_kind(t)); } else if (ch.is_ascii_digit()) { let t = Self::chars_to_int(*ch, &mut char_buffer); self.Toks.push(Token::Type(Type::Int(t))); } else if (*ch == '"') { let t = Self::chars_to_str(*ch, &mut char_buffer); self.Toks.push(Token::Type(Type::Str(t.clone()))); } else if (*ch == '(') { self.Toks.push(Token::ReservedWord(ReservedWord::LParen)); } else if (*ch == ')') { self.Toks.push(Token::ReservedWord(ReservedWord::RParen)); } else if (*ch == '{') { self.Toks.push(Token::ReservedWord(ReservedWord::LBrace)); } else if (*ch == '}') { self.Toks.push(Token::ReservedWord(ReservedWord::RBrace)); } else if "+-*/&|=".contains(*ch) { if let Some(t) = Self::two_operator(*ch, &mut char_buffer) { self.Toks.push(t); } } } self.Toks.clone() } }
use crate::collect_vars; use once_cell::sync::OnceCell; use proc_macro2::{Delimiter, Ident, Literal, Punct, Span}; use std::sync::Mutex; use syn::{Block, Expr}; #[derive(Debug)] pub(crate) struct Rules { pub(crate) clause: Expr, pub(crate) rules: Vec<Rule>, } #[derive(Debug)] pub(crate) struct Rule { pub(crate) lhs: SubRule, pub(crate) rhs: Rhs, } #[derive(Debug, Clone)] pub(crate) enum Rhs { Expr(Expr), Block(Block), } #[derive(Debug, Clone)] pub(crate) struct SubRule { pub(crate) matchers: Vec<Fragment>, } #[derive(Debug, Clone)] pub(crate) enum Fragment { Var(Ident, Type), Repeat(SubRule, RepeatKind, Option<Punct>), Ident(Ident), Punct(Punct), Literal(Literal), Group(SubRule, Delimiter), } #[derive(Debug, Clone)] pub(crate) enum RepeatKind { // `*` ZeroOrMore, // `+` OneOrMore, // `?` ZeroOrOne, } #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub(crate) enum Type { Item, Block, Stmt, Expr, Pat, Lifetime, Path, Ty, Ident, Meta, Tt, Vis, Literal, } #[derive(Debug, Clone, Eq, PartialEq)] pub(crate) struct MetaVar { pub(crate) name: Ident, pub(crate) ty: MetaVarType, } #[derive(Debug, Clone, Eq, PartialEq)] pub(crate) enum MetaVarType { Vec(Box<MetaVarType>), Option(Box<MetaVarType>), T(Type), } pub(crate) struct RuleBuilder { pub(crate) matchers: Vec<FragmentBuilder>, pub(crate) variables: Vec<MetaVar>, pub(crate) parent_name: Option<Ident>, pub(crate) name: Ident, } pub(crate) enum FragmentBuilder { Var(Ident, Type), Repeat(RuleBuilder, RepeatKind, Option<Punct>), Ident(Ident), Punct(Punct), Literal(Literal), Group(RuleBuilder, Delimiter), } impl SubRule { pub(crate) fn into_builder(self, parent_name: Option<Ident>) -> RuleBuilder { let mut variables = vec![]; collect_vars(&self, &mut variables); let name = Ident::new(&next_builder_name(), Span::call_site()); RuleBuilder { matchers: self .matchers .into_iter() .map(|m| m.into_builder(Some(name.clone()))) .collect(), variables, name, parent_name, } } } fn next_builder_name() -> String { static NEXT_ID: OnceCell<Mutex<u32>> = OnceCell::with_value(Mutex::new(0)); let mut next_id = NEXT_ID.get().unwrap().lock().unwrap(); *next_id += 1; format!("MatchesBuilder{}", next_id) } impl Fragment { pub(crate) fn into_builder(self, parent_name: Option<Ident>) -> FragmentBuilder { match self { Fragment::Var(i, t) => FragmentBuilder::Var(i, t), Fragment::Repeat(r, rep, sep) => { FragmentBuilder::Repeat(r.into_builder(parent_name), rep, sep) } Fragment::Ident(i) => FragmentBuilder::Ident(i), Fragment::Punct(p) => FragmentBuilder::Punct(p), Fragment::Literal(l) => FragmentBuilder::Literal(l), Fragment::Group(r, d) => FragmentBuilder::Group(r.into_builder(parent_name), d), } } }
//! Client and responses for MetroBus endpoints. pub mod client; pub mod route; pub mod stop; mod traits; mod urls;
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ #[allow(clippy::module_inception)] mod windows_aligned_file_reader; pub use windows_aligned_file_reader::*;
use { data::semantics::{ properties::{CuiProperty, Property}, Group, Semantics, StaticValue, Value, }, std::collections::HashMap, transform::compile::css::Css, }; impl Semantics { pub fn html(&self) -> (String, HashMap<&str, String>) { log::debug!("...Writing HTML..."); let (contents, styles) = self.html_parts(); let homepage = contents.get("/").unwrap(); let root = &self.pages[self.pages[0].root_id]; // TODO: make this cleaner with a lightweight html!() macro let html = format!( "<html>{}{}</html>", format_args!("<head>{}{}</head>", format_args!("<title>{}</title>", root.title), format_args!("<style>{}</style>", styles) ), format_args!( "<body>{}{}{}</body>", homepage, "<noscript>This page contains Webassembly and Javascript content. Please make sure that you are using the latest version of a modern browser and that Javascript and Webassembly (Wasm) are enabled.</noscript>", format_args!( "<script type=\"module\">{}{}</script>", "import init from './cui/cui_app_template.js';", "init();" ) ) ); (html, contents) } pub fn html_parts(&self) -> (HashMap<&str, String>, String) { let contents = self .pages .iter() .map(|page| (page.route, self.groups[page.root_id].html(&self.groups))) .collect(); (contents, self.styles.css()) } } impl Group { fn html(&self, groups: &[Group]) -> String { let link = self.properties.get(&Property::Cui(CuiProperty::Link)); let attributes = [ ("style", &*self.properties.css()), ("class", &*self.class_names.join(" ")), ( "href", &*link .unwrap_or(&Value::Static(StaticValue::String("".to_string()))) .to_string(), ), ] .iter() .filter(|(_, value)| !value.is_empty()) .map(|(attribute, value)| format!(" {}='{}'", attribute, value)) .collect::<String>(); let children = self .elements .iter() .filter(|&&element_id| groups[element_id].is_static()) .map(|&child_id| groups[child_id].html(groups)) .collect::<String>(); let contents = format!( "{}{}", if let Some(value) = self.properties.get(&Property::Cui(CuiProperty::Text)) { value.to_string() } else { "".into() }, children ); format!("<{0}{1}>{2}</{0}>", self.tag, attributes, contents) } }
pub mod tree; pub mod parse_tree; pub mod parse_tree_visitor; pub mod terminal_node; pub mod terminal_node_impl;
use crate::system:: { System, SystemError, ReadWriteError, }; use crate::cache:: { SysCache, DownloaderCache, RestoreResult, DownloadResult, }; use crate::system::util::get_timestamp; use crate::ticket:: { TicketFactory, Ticket, }; use serde:: { Serialize, Deserialize, }; use std::fmt; use std::time:: { SystemTimeError }; #[derive(Debug)] pub enum FileResolution { AlreadyCorrect, Recovered, Downloaded, NeedsRebuild, } #[derive(Debug)] pub struct TargetFileInfo { pub path : String, pub history : TargetHistory, } #[derive(Clone, Serialize, Deserialize, Eq, PartialEq, Debug)] pub struct TargetContentInfo { pub ticket : Ticket, pub executable : bool, } #[derive(Debug)] pub enum BlobError { Contradiction(Vec<usize>), TargetSizesDifferWeird, } #[derive(Debug)] pub enum TargetTicketsParseError { NotProperBase64, } /* The target of a rule can be more than one file, and maybe one day, it can be a directory or a combination of those things. A RuleHistory contains a map from source-ticket to this struct. This struct represents: whatever tickets we need to recover the target files. */ #[derive(Clone, Serialize, Deserialize, Eq, PartialEq, Debug)] pub struct TargetTickets { infos : Vec<TargetContentInfo>, } impl TargetTickets { pub fn from_vec(tickets : Vec<Ticket>) -> TargetTickets { let mut infos = vec![]; for ticket in tickets { infos.push( TargetContentInfo { ticket : ticket, executable : false, } ); } TargetTickets{infos : infos} } pub fn from_infos(infos : Vec<TargetContentInfo>) -> TargetTickets { TargetTickets{infos : infos} } pub fn from_download_string(download_string : &str) -> Result<TargetTickets, TargetTicketsParseError> { let mut tickets = vec![]; for part in download_string.split("\n") { tickets.push(match Ticket::from_base64(part) { Ok(ticket) => ticket, Err(_) => return Err( TargetTicketsParseError::NotProperBase64), }); } Ok(TargetTickets::from_vec(tickets)) } /* Takes a TargetTickets and looks at how the lists differ. Returns Ok if they're idendical, otherwise returns an error enum that indicates the way in which they differ. If they differ in length, that's weird, and this function returns BlobError::TargetSizesDifferWeird If they have the same length, but contain tickets that differ, a vector containing the indices of those tickets is returned inside a BlobError::Contradiction */ pub fn compare( &self, other : TargetTickets) -> Result<(), BlobError> { let elen : usize = self.infos.len(); if elen != other.infos.len() { Err(BlobError::TargetSizesDifferWeird) } else { let mut contradicting_indices = Vec::new(); for i in 0..elen { if self.infos[i].ticket != other.infos[i].ticket { contradicting_indices.push(i); } } if contradicting_indices.len() == 0 { Ok(()) } else { Err(BlobError::Contradiction(contradicting_indices)) } } } fn get_info( &self, i : usize) -> TargetContentInfo { self.infos[i].clone() } /* Currently used by a display function, hence the formatting. */ pub fn base64(&self) -> String { let mut out = String::new(); for info in self.infos.iter() { out.push_str(" "); out.push_str(&info.ticket.base64()); out.push_str("\n"); } out } /* Currently used by a display function, hence the formatting. */ pub fn download_string(&self) -> String { self.infos.iter().map(|info|{info.ticket.base64()}).collect::<Vec<String>>().join("\n") } } /* Takes a System and a filepath as a string. If the file exists, returns a ticket. If the file does not exist, returns Ok, but with no Ticket inside If the file exists but does not open or some other error occurs when generating the ticket, returns an error. */ pub fn get_file_ticket_from_path<SystemType: System> ( system : &SystemType, path : &str ) -> Result<Option<Ticket>, ReadWriteError> { if system.is_file(&path) || system.is_dir(&path) { match TicketFactory::from_file(system, &path) { Ok(mut factory) => Ok(Some(factory.result())), Err(error) => Err(error), } } else { Ok(None) } } /* There are two steps to checking if a target file is up-to-date. First: check the rule-history to see what the target hash should be. Second: compare the hash it should be to the hash it actually is. TargetHistory is a small struct meant to be the type of a value in the map 'target_histories' whose purpose is to help ruler tell if a target is up-to-date */ #[derive(Clone, Serialize, Deserialize, PartialEq, Debug)] pub struct TargetHistory { pub ticket : Ticket, pub timestamp : u64, pub executable : bool, } impl TargetHistory { /* Create a new empty TargetHistory */ pub fn empty() -> TargetHistory { TargetHistory { ticket : TicketFactory::new().result(), timestamp : 0, executable : false, } } #[cfg(test)] pub fn new( ticket : Ticket, timestamp : u64) -> TargetHistory { TargetHistory { ticket : ticket, timestamp : timestamp, executable : false, } } #[cfg(test)] pub fn new_with_ticket( ticket : Ticket) -> TargetHistory { TargetHistory { ticket : ticket, timestamp : 0, executable : false, } } } /* Takes a system and a TargetFileInfo, and obtains a ticket for the file described. If the modified date of the file matches the one in TargetHistory exactly, this function assumes the ticket matches, too, this is part of the timestamp optimization. */ pub fn get_file_ticket<SystemType: System> ( system : &SystemType, target_info : &TargetFileInfo ) -> Result<Option<Ticket>, ReadWriteError> { /* The body of this match looks like it has unhandled errors. What's happening is: if any error occurs with the timestamp optimization, we skip the optimization. */ match system.get_modified(&target_info.path) { Ok(system_time) => { match get_timestamp(system_time) { Ok(timestamp) => { if timestamp == target_info.history.timestamp { return Ok(Some(target_info.history.ticket.clone())) } }, Err(_) => {}, } }, Err(_) => {}, } get_file_ticket_from_path(system, &target_info.path) } #[derive(Debug)] pub enum GetCurrentFileInfoError { ErrorConveratingModifiedDateToNumber(String, SystemTimeError), ErrorGettingFilePermissions(String, SystemError), ErrorGettingTicketForFile(String, ReadWriteError), TargetFileNotFound(String, SystemError), } impl fmt::Display for GetCurrentFileInfoError { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { match self { GetCurrentFileInfoError::ErrorConveratingModifiedDateToNumber(path, error) => write!(formatter, "Error converting from system time to number. File: {} Error: {}", path, error), GetCurrentFileInfoError::ErrorGettingFilePermissions(path, error) => write!(formatter, "Error getting executable permission from file. File: {} Error: {}", path, error), GetCurrentFileInfoError::ErrorGettingTicketForFile(path, error) => write!(formatter, "Read/write error while hashing file contents: File: {} Error: {}", path, error), GetCurrentFileInfoError::TargetFileNotFound(path, error) => write!(formatter, "System error while attempting to read file: {} Error: {}", path, error), } } } /* Takes a system and a TargetFileInfo, which contains a path and a TargetHistory. Returns a TargetHistory object, which is a little confiusing, I admit. TODO: Rename the arguments and maybe the function to make it more clear what's happening here. The function takes input and output. The input is: what state we last saw the file in the output is what state the file is currently. Why does the function take a TargetFileInfo, then? Why doens't it just take system and path? Because it does the following optimization: If the modified date of the file matches the one in TargetHistory exactly, it doesn't bother recomputing the ticket, instead it clones the ticket from the target_info's history. */ pub fn get_current_file_info<SystemType: System> ( system : &SystemType, target_info : &TargetFileInfo ) -> Result<TargetHistory, GetCurrentFileInfoError> { let system_time = match system.get_modified(&target_info.path) { Ok(system_time) => system_time, // Note: possibly there are other ways get_modified can fail than the file being absent. // Maybe this logic should change. Err(system_error) => return Err( GetCurrentFileInfoError::TargetFileNotFound( target_info.path.clone(), system_error)), }; let timestamp = match get_timestamp(system_time) { Ok(timestamp) => timestamp, Err(error) => return Err(GetCurrentFileInfoError::ErrorConveratingModifiedDateToNumber( target_info.path.clone(), error)), }; let executable = match system.is_executable(&target_info.path) { Ok(executable) => executable, Err(system_error) => return Err(GetCurrentFileInfoError::ErrorGettingFilePermissions( target_info.path.clone(), system_error)) }; if timestamp == target_info.history.timestamp { return Ok( TargetHistory { ticket : target_info.history.ticket.clone(), timestamp : timestamp, executable : executable } ) } match TicketFactory::from_file(system, &target_info.path) { Ok(mut factory) => Ok( TargetHistory { ticket : factory.result(), timestamp : timestamp, executable : executable }), Err(read_write_error) => Err(GetCurrentFileInfoError::ErrorGettingTicketForFile( target_info.path.clone(), read_write_error)), } } #[derive(Debug)] pub enum ResolutionError { FileNotAvailableToCache(String, ReadWriteError), CacheDirectoryMissing, CacheMalfunction(SystemError), TicketAlignmentError(ReadWriteError), } impl fmt::Display for ResolutionError { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { match self { ResolutionError::FileNotAvailableToCache(path, error) => write!(formatter, "Read/write error when attempting to read file from local cache. File: {} Error: {}", path, error), ResolutionError::CacheDirectoryMissing => write!(formatter, "Cache directory missing."), ResolutionError::CacheMalfunction(error) => write!(formatter, "System error while attempting to use cache. Error: {}", error), ResolutionError::TicketAlignmentError(error) => write!(formatter, "Ticket alignment error: {}", error), } } } fn restore_or_download<SystemType : System> ( system : &mut SystemType, cache : &mut SysCache<SystemType>, downloader_cache_opt : &Option<DownloaderCache>, remembered_target_content_info : &TargetContentInfo, target_info : &TargetFileInfo ) -> Result<FileResolution, ResolutionError> { match cache.restore_file( &remembered_target_content_info.ticket, &target_info.path) { RestoreResult::Done => return Ok(FileResolution::Recovered), RestoreResult::NotThere => {}, RestoreResult::CacheDirectoryMissing => return Err(ResolutionError::CacheDirectoryMissing), RestoreResult::SystemError(error) => return Err(ResolutionError::CacheMalfunction(error)), } match downloader_cache_opt { Some(downloader_cache) => { match downloader_cache.restore_file( &remembered_target_content_info.ticket, system, &target_info.path) { DownloadResult::Done => {} DownloadResult::NotThere => return Ok(FileResolution::NeedsRebuild), } return match system.set_is_executable(&target_info.path, remembered_target_content_info.executable) { Err(_) => { println!("Warning: failed to set executable"); Ok(FileResolution::Downloaded) }, Ok(_) => Ok(FileResolution::Downloaded) }; }, None => {} } Ok(FileResolution::NeedsRebuild) } /* Given a target-info and a remembered ticket for that target file, check the current ticket, and if it matches, return AlreadyCorrect. If it doesn't match, back up the current file, and then attempt to restore the remembered file from cache, if the cache doesn't have it attempt to download. If no recovery or download works, shrug and return NeedsRebuild */ pub fn resolve_single_target<SystemType : System> ( system : &mut SystemType, cache : &mut SysCache<SystemType>, downloader_cache_opt : &Option<DownloaderCache>, remembered_target_content_info : &TargetContentInfo, target_info : &TargetFileInfo ) -> Result<FileResolution, ResolutionError> { match get_file_ticket(system, target_info) { Ok(Some(current_target_ticket)) => { if remembered_target_content_info.ticket == current_target_ticket { return Ok(FileResolution::AlreadyCorrect); } match cache.back_up_file_with_ticket( &current_target_ticket, &target_info.path) { Ok(_) => {}, Err(error) => { return Err(ResolutionError::FileNotAvailableToCache( target_info.path.clone(), error)); }, } restore_or_download( system, cache, downloader_cache_opt, remembered_target_content_info, target_info) }, // None means the file is not there, in which case, we just try to restore/download, and then go home. Ok(None) => { restore_or_download( system, cache, downloader_cache_opt, remembered_target_content_info, target_info) }, Err(error) => { Err(ResolutionError::TicketAlignmentError(error)) }, } } pub fn resolve_remembered_target_tickets<SystemType : System> ( system : &mut SystemType, cache : &mut SysCache<SystemType>, downloader_cache_opt : &Option<DownloaderCache>, target_infos : &Vec<TargetFileInfo>, remembered_tickets : &TargetTickets, ) -> Result<Vec<FileResolution>, ResolutionError> { let mut resolutions = vec![]; for (i, target_info) in target_infos.iter().enumerate() { match resolve_single_target( system, cache, downloader_cache_opt, &remembered_tickets.get_info(i), target_info) { Ok(resolution) => resolutions.push(resolution), Err(error) => return Err(error), } } Ok(resolutions) } pub fn resolve_with_no_memory<SystemType : System> ( system : &mut SystemType, cache : &mut SysCache<SystemType>, target_infos : &Vec<TargetFileInfo>, ) -> Result<Vec<FileResolution>, ResolutionError> { let mut resolutions = vec![]; for target_info in target_infos.iter() { match get_file_ticket(system, target_info) { Ok(Some(current_target_ticket)) => { match cache.back_up_file_with_ticket( &current_target_ticket, &target_info.path) { Ok(_) => { // TODO: Maybe encode whether it was cached in the FileResoluton resolutions.push(FileResolution::NeedsRebuild); }, Err(error) => { return Err( ResolutionError::FileNotAvailableToCache( target_info.path.clone(), error)); } } }, Ok(None) => resolutions.push(FileResolution::NeedsRebuild), Err(error) => return Err(ResolutionError::TicketAlignmentError(error)), } } Ok(resolutions) } #[cfg(test)] mod test { use crate::ticket:: { TicketFactory, }; use crate::blob:: { TargetHistory, TargetTickets, BlobError, TargetFileInfo, get_file_ticket }; use crate::system:: { fake::FakeSystem, System }; use crate::system::util:: { write_str_to_file, }; use crate::blob:: { get_file_ticket_from_path, get_current_file_info, GetCurrentFileInfoError, }; /* Create a file, and make target_info that matches the reality of that file. Call get_current_file_info and check that the returned data matches. */ #[test] fn blob_get_current_file_info_complete_match() { let mut system = FakeSystem::new(23); write_str_to_file(&mut system, "quine.sh", "cat $0").unwrap(); let target_info = TargetFileInfo { path: "quine.sh".to_string(), history: TargetHistory { ticket : TicketFactory::from_str("cat $0").result(), timestamp : 23, executable : false, } }; let target_history = get_current_file_info(&system, &target_info).unwrap(); assert_eq!(target_history.ticket, TicketFactory::from_str("cat $0").result()); assert_eq!(target_history.timestamp, 23); assert_eq!(target_history.executable, false); } /* Create a file, and make target_info that matches the reality of that file, except for one detail: executable is different. Call get_current_file_info and check that the returned data matches, except executable. */ #[test] fn blob_get_current_file_info_executable_contradicts() { let mut system = FakeSystem::new(23); write_str_to_file(&mut system, "quine.sh", "cat $0").unwrap(); system.set_is_executable("quine.sh", true).unwrap(); let target_info = TargetFileInfo { path: "quine.sh".to_string(), history: TargetHistory { ticket : TicketFactory::from_str("cat $0").result(), timestamp : 23, executable : false, } }; let target_history = get_current_file_info(&system, &target_info).unwrap(); assert_eq!(target_history.ticket, TicketFactory::from_str("cat $0").result()); assert_eq!(target_history.timestamp, 23); assert_eq!(target_history.executable, true); } /* Create a file, and make target_info that matches the reality of that file, except for one detail: the timestamp is different. Call get_current_file_info and check that the returned data matches, except the timestamp which should be up-to-date. */ #[test] fn blob_get_current_file_info_old_timestamp() { let mut system = FakeSystem::new(24); write_str_to_file(&mut system, "quine.sh", "cat $0").unwrap(); let target_info = TargetFileInfo { path: "quine.sh".to_string(), history: TargetHistory { ticket : TicketFactory::from_str("cat $0").result(), timestamp : 11, executable : false, } }; let target_history = get_current_file_info(&system, &target_info).unwrap(); assert_eq!(target_history.ticket, TicketFactory::from_str("cat $0").result()); assert_eq!(target_history.timestamp, 24); assert_eq!(target_history.executable, false); } /* Create a file, and simulate a reasonable out-of-date TargetHistory for the input to get_current_file_info, one where the timestamp is out of date, and so is the content. Call get_current_file_info and check that the returned data matches the current file. */ #[test] fn blob_get_current_file_info_rough_draft_final_draft() { let mut system = FakeSystem::new(25); write_str_to_file(&mut system, "story.txt", "final draft").unwrap(); let target_info = TargetFileInfo { path: "story.txt".to_string(), history: TargetHistory { ticket : TicketFactory::from_str("rough draft").result(), timestamp : 11, executable : false, } }; let target_history = get_current_file_info(&system, &target_info).unwrap(); assert_eq!(target_history.ticket, TicketFactory::from_str("final draft").result()); assert_eq!(target_history.timestamp, 25); assert_eq!(target_history.executable, false); } /* Create a file, and simulate a very unlikely out-of-date TargetHistory for the input to get_current_file_info, one in which content is out of date, but somehow the timestamp matches. In this scenario, get_current_file_info should actually give the wrong answer, because it does the optimization where if the timestamp matches what's in the filesystem, it doesn't bother looking at the file's actual contents to compute a new ticket. Instead, it just repeats back the assumed ticket. */ #[test] fn blob_get_current_file_info_subvert_the_timestamp_optimization() { let mut system = FakeSystem::new(25); write_str_to_file(&mut system, "story.txt", "final draft").unwrap(); let target_info = TargetFileInfo { path: "story.txt".to_string(), history: TargetHistory { ticket : TicketFactory::from_str("rough draft").result(), timestamp : 25, executable : false, } }; let target_history = get_current_file_info(&system, &target_info).unwrap(); assert_eq!(target_history.ticket, TicketFactory::from_str("rough draft").result()); assert_eq!(target_history.timestamp, 25); assert_eq!(target_history.executable, false); } /* Create a TargetFileInfo for a file that does not exist. Check that get_current_file_info returns an appropriate error. */ #[test] fn blob_get_current_file_info_file_not_found() { let system = FakeSystem::new(25); let target_info = TargetFileInfo { path: "story.txt".to_string(), history: TargetHistory { ticket : TicketFactory::from_str("final draft").result(), timestamp : 10, executable : false, } }; match get_current_file_info(&system, &target_info) { Ok(_) => panic!("Unexpected success"), Err(GetCurrentFileInfoError::TargetFileNotFound(path, _system_error)) => { assert_eq!(path, "story.txt"); }, _ => panic!("Unexpected error"), } } /* Use a fake system to create a file, and write a string to it. Then use get_file_ticket_from_path to obtain a ticket for that file, and compare that against a ticket made directly from the string. */ #[test] fn blob_get_file_ticket_from_path() { let mut system = FakeSystem::new(10); write_str_to_file(&mut system, "quine.sh", "cat $0").unwrap(); match get_file_ticket_from_path( &system, "quine.sh") { Ok(ticket_opt) => match ticket_opt { Some(ticket) => assert_eq!(ticket, TicketFactory::from_str("cat $0").result()), None => panic!("Could not get ticket"), } Err(err) => panic!("Could not get ticket: {}", err), } } #[test] fn blob_compare_identical() { let a = TargetTickets::from_vec( vec![ TicketFactory::from_str("Roses are red\nViolets are blue\n").result(), TicketFactory::from_str("Sugar is sweet\nThis is a poem\n").result(), ] ); let b = TargetTickets::from_vec( vec![ TicketFactory::from_str("Roses are red\nViolets are blue\n").result(), TicketFactory::from_str("Sugar is sweet\nThis is a poem\n").result(), ] ); match a.compare(b) { Ok(_) => {}, Err(_) => panic!("Unexpected error when comparing identical blobs"), } } #[test] fn blob_compare_mismatched_sizes() { let a = TargetTickets::from_vec( vec![ TicketFactory::from_str("Roses are red\nViolets are blue\n").result(), TicketFactory::from_str("Sugar is sweet\nThis is a poem\n").result(), ] ); let b = TargetTickets::from_vec( vec![ TicketFactory::from_str("Roses are red\nViolets are blue\n").result(), ] ); match a.compare(b) { Ok(_) => panic!("Unexpected success"), Err(BlobError::TargetSizesDifferWeird) => {}, Err(_) => panic!("Wrong error when comparing blobs of different shapes"), } } #[test] fn blob_compare_contradiction() { let a = TargetTickets::from_vec( vec![ TicketFactory::from_str("Roses are red\nViolets are blue\n").result(), TicketFactory::from_str("Sugar is sweet\nThis is a poem\n").result(), ] ); let b = TargetTickets::from_vec( vec![ TicketFactory::from_str("Roses are red\nViolets are blue\n").result(), TicketFactory::from_str("Sugar is sweet\nChicken soup\n").result(), ] ); match a.compare(b) { Ok(_) => panic!("Unexpected success"), Err(BlobError::Contradiction(index_vec)) => { assert_eq!(index_vec, vec![1]); }, Err(_) => panic!("Unexpected error when comparing non-identical blobs of the same shape"), } } /* Use the system to create a file, and write a string to it. Then use get_file_ticket to obtain a ticket for that file, and compare that against a ticket made directly from the string. */ #[test] fn blob_get_tickets_from_filesystem() { let mut system = FakeSystem::new(10); match write_str_to_file(&mut system, "quine.sh", "cat $0") { Ok(_) => {}, Err(why) => panic!("Failed to make fake file: {}", why), } match get_file_ticket( &system, &TargetFileInfo { path : "quine.sh".to_string(), history : TargetHistory::new_with_ticket(TicketFactory::new().result()) }) { Ok(ticket_opt) => match ticket_opt { Some(ticket) => assert_eq!(ticket, TicketFactory::from_str("cat $0").result()), None => panic!("Could not get ticket"), } Err(err) => panic!("Could not get ticket: {}", err), } } /* Create a file and a TargetFileInfo for that file with matching timestamp. Then fill the file with some other data. Make sure that when we get_file_ticket, we get the one from the history instead of the one from the file. */ #[test] fn blob_test_timestamp_optimization() { // Set the clock to 11 let mut system = FakeSystem::new(11); let content = "int main(){printf(\"my game\"); return 0;}"; let content_ticket = TicketFactory::from_str(content).result(); // Doctor a TargetFileInfo to indicate the game.cpp was written at time 11 let target_file_info = TargetFileInfo { path : "game.cpp".to_string(), history : TargetHistory::new(content_ticket.clone(), 11), }; // Meanwhile, in the filesystem put some incorrect rubbish in game.cpp match write_str_to_file(&mut system, "game.cpp", "some rubbish") { Ok(_) => {}, Err(why) => panic!("Failed to make fake file: {}", why), } // Then get the ticket for the current target file, passing the TargetFileInfo // with timestamp 11. Check that it gives the ticket for the C++ code. match get_file_ticket( &system, &target_file_info) { Ok(ticket_opt) => { match ticket_opt { Some(ticket) => assert_eq!(ticket, content_ticket), None => panic!("Failed to generate ticket"), } }, Err(_) => panic!("Unexpected error getting file ticket"), } } /* Create a file and a TargetFileInfo for that file with not-matching timestamp. Fill the file with new and improved code. Make sure that when we get_file_ticket, we get the one from the file because the history doesn't match. */ #[test] fn blob_test_timestamp_mismatch() { // Set the clock to 11 let mut system = FakeSystem::new(11); let previous_content = "int main(){printf(\"my game\"); return 0;}"; let previous_ticket = TicketFactory::from_str(previous_content).result(); let current_content = "int main(){printf(\"my better game\"); return 0;}"; let current_ticket = TicketFactory::from_str(current_content).result(); // Doctor a TargetFileInfo to indicate the game.cpp was written at time 9 let target_file_info = TargetFileInfo { path : "game.cpp".to_string(), history : TargetHistory::new(previous_ticket.clone(), 9), }; // Meanwhile, in the filesystem, put new and improved game.cpp match write_str_to_file(&mut system, "game.cpp", current_content) { Ok(_) => {}, Err(why) => panic!("Failed to make fake file: {}", why), } // Then get the ticket for the current target file, passing the TargetFileInfo // with timestamp 11. Check that it gives the ticket for the C++ code. match get_file_ticket( &system, &target_file_info) { Ok(ticket_opt) => { match ticket_opt { Some(ticket) => assert_eq!(ticket, current_ticket), None => panic!("Failed to generate ticket"), } }, Err(_) => panic!("Unexpected error getting file ticket"), } } #[test] fn blob_test_download_string_round_trip() { let target_tickets = TargetTickets::from_vec(vec![ TicketFactory::from_str("Alabaster\n").result(), TicketFactory::from_str("Banana\n").result()]); assert_eq!(target_tickets, TargetTickets::from_download_string( &target_tickets.download_string()).unwrap()); } }
use actix_session::Session; use actix_web::{web, HttpRequest, HttpResponse}; use rustimate_service::AppConfig; /// Available at `/testbed/{key}` pub fn testbed_key(session: Session, cfg: web::Data<AppConfig>, key: web::Path<String>, req: HttpRequest) -> HttpResponse { crate::act(&session, &cfg, req, |ctx, router| { let k: &str = &key; match k { "dump" => rustimate_templates::testbed::dump(ctx, router), "gallery" => rustimate_templates::testbed::gallery(ctx, router), "prototype" => rustimate_templates::testbed::prototype(ctx, router), "scroll" => rustimate_templates::testbed::scroll(ctx, router), _ => Err(anyhow::anyhow!("Cannot find testbed matching [{}]", key)) } }) }
pub mod food_parameters; pub use food_parameters::FoodParameters;
//! The `AUTH` command used to support TLS //! //! A client requests TLS with the AUTH command and then decides if it //! wishes to secure the data connections by use of the PBSZ and PROT //! commands. use crate::{ auth::UserDetail, server::{ chancomms::ControlChanMsg, controlchan::{ error::ControlChanError, handler::{CommandContext, CommandHandler}, Reply, ReplyCode, }, }, storage::{Metadata, StorageBackend}, }; use async_trait::async_trait; // The parameter that can be given to the `AUTH` command. #[derive(Debug, PartialEq, Eq, Clone)] pub enum AuthParam { Ssl, Tls, } #[derive(Debug)] pub struct Auth { protocol: AuthParam, } impl Auth { pub fn new(protocol: AuthParam) -> Self { Auth { protocol } } } #[async_trait] impl<Storage, User> CommandHandler<Storage, User> for Auth where User: UserDetail + 'static, Storage: StorageBackend<User> + 'static, Storage::Metadata: Metadata, { #[tracing_attributes::instrument] async fn handle(&self, args: CommandContext<Storage, User>) -> Result<Reply, ControlChanError> { let tx = args.tx_control_chan.clone(); let logger = args.logger; match (args.tls_configured, self.protocol.clone()) { (true, AuthParam::Tls) => { tokio::spawn(async move { if let Err(err) = tx.send(ControlChanMsg::SecureControlChannel).await { slog::warn!(logger, "AUTH: Could not send internal message to notify of TLS upgrade: {}", err); } }); Ok(Reply::new(ReplyCode::AuthOkayNoDataNeeded, "Upgrading to TLS")) } (true, AuthParam::Ssl) => Ok(Reply::new(ReplyCode::CommandNotImplementedForParameter, "Auth SSL not implemented")), (false, _) => Ok(Reply::new(ReplyCode::CommandNotImplemented, "TLS/SSL not configured")), } } }
extern crate cribbage; extern crate serde; use serde::{Deserialize, Serialize}; use std::sync::mpsc; // Messages from the client handler threads to the game model thread; also the messages sent from // the client to the client handler thread over TCP #[derive(PartialEq, Serialize, Deserialize)] pub enum ClientToGame { // A message to initiate communication between the client thread and the game thread and to // indicate that the client thread is ready to receive requests Greeting, // A simple confirmation from the client to continue the game model progression Confirmation, // A simple denial for when the player is given a yes/no choice Denial, // The name the client wishes to be known by for the duration of the game // TODO A way to determine this with user authentication for eventual lobby and account system Name(String), // The index or indices given are to be discarded DiscardOne { index: u8 }, DiscardTwo { index_one: u8, index_two: u8 }, // That a given index has been played; as a hand is four cards, an index of 0 to 3 will // represent that card being played and a None will represent a go PlayTurn(Option<u8>), // That the included ScoreEvents have been given by the player for the most recent play PlayScore(Vec<cribbage::score::ScoreEvent>), TransmissionReceived, } // Messages sent from the game model to the client handler threads which more directly interact // with the players; also the messages sent from the client handler to the client over TCP #[derive(Serialize, Deserialize, Clone)] pub enum GameToClient { // Message indicating that the maximum number of cliets that can play have already joined DeniedTableFull, // That the game model is requesting the name that the client will go by WaitName, // That a player has successfully joined the game PlayerJoinNotification { name: String, number: u8, of: u8, }, // That the model is waiting for a confirmation event to process that player's initial cut WaitInitialCut, // That the named player has cut the specified card in their initial cut InitialCutResult { name: String, card: cribbage::deck::Card, }, // That the named player has been decided to be the first dealer as per the cut InitialCutSuccess(String), // That the cut has resulted in a tie and that it must be redone InitialCutFailure, // That the game is waiting for confirmation to deal the hand WaitDeal, // That cards are actively being dealt Dealing, // That the player's hand is the included vector DealtHand(Vec<cribbage::deck::Card>), // That the game is waiting for a discard selection of one card WaitDiscardOne, // That the game is waiting for a discard selection of two cards WaitDiscardTwo, // That someone has discarded their card DiscardPlacedOne(String), // That someone has discarded their cards DiscardPlacedTwo(String), // That all discards have been placed AllDiscards, // That the game is waiting for confirmation to cut the starter card WaitCutStarter, // That the starter card has been cut and the name of the player who cut it and its value CutStarter(String, cribbage::deck::Card), // That the game is waiting to know whether the dealer calls nibs or not WaitNibs, // That the dealer has cut a jack and received two points Nibs, // That a player has played a card and the following ScoreEvents have been claimed CardPlayed { name: String, card: cribbage::deck::Card, scores: Vec<cribbage::score::ScoreEvent>, }, // That the game is waiting for a player to place a card and that the valid indices are as // listed WaitPlay(Vec<u8>), // That the game is waiting for ScoreEvents for the previous play WaitPlayScore, // That the game rejected the scoring because there was an invalid ScoreEvent InvalidPlayScoring, // That the game has rejected the scoring because the scores are incomplete IncompletePlayScoring, // That the scores are as follows; contains a vector of pairs of names and scores ScoreUpdate(Vec<(String, u8)>), // That an error has occured Error(String), // That the client should not expect further messages from the game model Disconnect, } pub enum GameToMain { // That the main thread is ready to end as the match has finished EndServer, } pub enum MainToGame { // Message handing the transmitter and receiver from/to a new client thread to/from the game // model thread NewClient { transmitter: mpsc::Sender<GameToClient>, receiver: mpsc::Receiver<ClientToGame>, }, }
extern crate arrayfire; extern crate rand; extern crate rand_distr; use arrayfire::*; use rand::thread_rng; use rand_distr::*; pub fn d_row(rows: u64) -> Dim4 { return Dim4::new(&[1, rows, 1, 1]); } pub fn d_column(columns: u64) -> Dim4 { return Dim4::new(&[columns, 1, 1, 1]); } pub fn d_matrix(rows: u64, columns:u64) -> Dim4 { return Dim4::new(&[rows, columns, 1, 1]); } pub fn t(vector: &Array<f32>) -> Array<f32> { return transpose(vector, false); } pub fn array(data: &Vec<f32>, dims: Dim4) -> Array<f32> { return Array::new(data, dims); } /** * Multiplies two ArrayFire arrays. * * ArrayFire matrix multiplication rules. * | Size of Input Matrix A | Size of Input Matrix B | Output Matrix Size | * |------------------------|------------------------|--------------------| * | {M,K,1,1} | {K,N,1,1} | {M,N,1,1} | * | {M,K,b2,b3} | {K,N,b2,b3} | {M,N,b2,b3} | * | | {K,N,b2,b3} | {M,N,b2,b3} | * | {M,K,b2,b3} | {K,N,1,1} | {M,N,b2,b3} | * */ pub fn mdot(lhs: &Array<f32>, rhs: &Array<f32>) -> Array<f32> { if lhs.dims()[1] != rhs.dims()[0] { println!("lhs dims: {}, rhs dims: {}", lhs.dims(), rhs.dims()); panic!("mdot failed: dimension mismatch"); } return matmul(lhs, rhs, MatProp::NONE, MatProp::NONE); } pub fn relu(x: &Array<f32>) -> Array<f32> { return (abs(x) + x) / 2_f32; } pub fn relu_deriv(x: &Array<f32>) -> Array<f32> { let zeroes = constant(0.0_f32, x.dims()); let ones = constant(1.0_f32, x.dims()); let comparison = gt(x, &zeroes, false); return select(&ones, &comparison, &zeroes); } pub fn softmax(x: &Array<f32>) -> Array<f32> { let (m, _) = max_all(x); let max_vector = constant(m as f32, x.dims()); let delta = x - max_vector; let e_x = exp(&delta); let (s, _) = sum_all(&e_x); return e_x * (1.0_f32 / (s as f32)); } pub fn softmax_deriv(x: &Array<f32>) -> Array<f32> { let diagonal = diag_create(x, 1); let delta = mdot(x, &t(x)); let jac = diagonal - delta; return jac; } pub fn he_weights(width: u64, height: u64) -> Array<f32> { let dist = Normal::new(0_f64, 0.001_f64).unwrap(); let values: Vec<f32> = dist.sample_iter(thread_rng()) .take((width * height) as usize) .map(|f| f as f32) .collect(); return Array::new(&values, d_matrix(width, height)); } pub fn zero_biases(width: u64) -> Array<f32> { return constant(0_f32, d_row(width)); }
use std::ffi::{CStr, NulError}; use std::error::Error; use std::io; use std::fmt::{Display, Formatter, Result as FmtResult}; use std::str::Utf8Error; use trace_error::TraceResult; use ffi; /// Represents any errors that can be encountered by the Assimp library #[derive(Debug)] pub enum AiError { Io(io::Error), Utf8Error(Utf8Error), NulError(NulError), Internal(String), InvalidScene } /// Generic Result type with an `AiError` for the error type pub type AiResult<T> = TraceResult<T, AiError>; impl AiError { /// Checks Assimp for errors generated by previous operations, and returns an `AiResult` pub fn check() -> AiResult<()> { let err_str = unsafe { ffi::aiGetErrorString() }; if !err_str.is_null() { let err = unsafe { CStr::from_ptr(err_str) }.to_string_lossy(); if err.len() > 0 { throw!(AiError::Internal(err.to_string())); } } Ok(()) } } /// This performs a `try!(AiError::check())` in place, with or without a condition //#[macro_export] macro_rules! check_assimp_errors { () => { try!(AiError::check()) }; ($condition:expr) => { if $condition { try_rethrow!(AiError::check()) } }; } impl Display for AiError { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "{}", self.description()) } } impl From<io::Error> for AiError { fn from(err: io::Error) -> AiError { AiError::Io(err) } } impl From<Utf8Error> for AiError { fn from(err: Utf8Error) -> AiError { AiError::Utf8Error(err) } } impl From<NulError> for AiError { fn from(err: NulError) -> AiError { AiError::NulError(err) } } impl Error for AiError { fn description(&self) -> &str { match *self { AiError::Io(ref err) => err.description(), AiError::Utf8Error(ref err) => err.description(), AiError::NulError(ref err) => err.description(), AiError::Internal(ref err) => err, AiError::InvalidScene => "Invalid Scene" } } #[inline] fn cause(&self) -> Option<&Error> { match *self { AiError::Io(ref err) => Some(err), AiError::Utf8Error(ref err) => Some(err), _ => None } } }
// To find most minutes sleep guard is just accumulation of minutes over the given records // But is it just that? use regex::Regex; use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader}; use chrono::prelude::*; type Result<T> = ::std::result::Result<T, Box<::std::error::Error + Send + Sync>>; #[derive(Debug, PartialEq)] enum Action { Shift { guard: i32 }, Sleep, WakeUp, } #[derive(Debug, PartialEq)] struct Record { time: DateTime<Utc>, observation: Action, } // What do we need to keep stats of about the guards? // 1. We need to keep the total time they sleep // 2. Then we also need to know which minute of the hour they are most likely to fall asleep #[derive(Debug)] struct Stats { sleep_total: i32, sleep_times: HashMap<i32, i32>, } impl Stats { fn record(&mut self, start: DateTime<Utc>, duration: i32) { self.sleep_total += duration; let start_minute = start.minute(); for m in start_minute as i32..start_minute as i32 + duration { let count = self.sleep_times.entry(m).or_insert(0); *count += 1; } } fn empty() -> Self { Stats { sleep_total: 0, sleep_times: HashMap::new(), } } // Returns the most frequently slept minute and the times it was found to be fn get_most_frequent(&self) -> Option<(&i32, &i32)> { self.sleep_times.iter().max_by(|a, b| a.1.cmp(b.1)) } } impl Record { fn parse(srecord: &str) -> Result<Record> { if srecord.ends_with("begins shift") { Self::parse_shift_record(srecord) } else if srecord.ends_with("falls asleep") { Self::parse_sleep_record(srecord) } else if srecord.ends_with("wakes up") { Self::parse_wakeup_record(srecord) } else { Err(From::from(format!("Failed to parse record: {}", srecord))) } } fn parse_shift_record(srecord: &str) -> Result<Record> { lazy_static! { static ref RE: Regex = Regex::new(r"\[(?P<date>.*)\] Guard #(?P<id>\d+) begins shift").unwrap(); } match RE.captures(srecord) { Some(caps) => { let date = Utc.datetime_from_str(&caps["date"], "%Y-%m-%d %H:%M")?; let id = caps["id"].parse::<i32>()?; let record = Record { time: date, observation: Action::Shift { guard: id }, }; Ok(record) } None => Err(From::from(format!("Not a valid shift record: {}", srecord))), } } fn parse_sleep_record(srecord: &str) -> Result<Record> { lazy_static! { static ref RE: Regex = Regex::new(r"\[(?P<date>.*)\] falls asleep").unwrap(); } match RE.captures(srecord) { Some(caps) => { let date = Utc.datetime_from_str(&caps["date"], "%Y-%m-%d %H:%M")?; let record = Record { time: date, observation: Action::Sleep, }; Ok(record) } None => Err(From::from(format!("Not a valid sleep record: {}", srecord))), } } fn parse_wakeup_record(srecord: &str) -> Result<Record> { lazy_static! { static ref RE: Regex = Regex::new(r"\[(?P<date>.*)\] wakes up").unwrap(); } match RE.captures(srecord) { Some(caps) => { let date = Utc.datetime_from_str(&caps["date"], "%Y-%m-%d %H:%M")?; let record = Record { time: date, observation: Action::WakeUp, }; Ok(record) } None => Err(From::from(format!( "Not a valid wake up record: {}", srecord ))), } } // Sort records by the timestamp in the ascending order fn sort_records(rs: &mut Vec<Record>) { rs.sort_by(|a, b| a.time.cmp(&b.time)); } fn process(records: &Vec<Record>) -> HashMap<i32, Stats> { // Go through the records and process the sleep times of Guards let mut current_guard = None; let mut sleep_time = None; let mut stats = HashMap::new(); for r in records { match r.observation { Action::Shift { guard } => current_guard = Some(guard), Action::Sleep => sleep_time = Some(r.time), Action::WakeUp => { if let Some(st) = sleep_time { let duration = (r.time.minute() - st.minute()) as i32; let id = current_guard.expect("Invalid record - no guard to record time for"); let stat = stats.entry(id).or_insert(Stats::empty()); stat.record(st, duration); } else { println!("Error - sleep time not recorded!"); } } } } stats } fn find_best_by_total(stats: &HashMap<i32, Stats>) { // We need to find who sleeps the most let m = stats .iter() .map(|(id, st)| (id, st.sleep_total)) .max_by(|x, y| x.1.cmp(&y.1)); if let Some((guard, total)) = m { println!("Guard {} sleeps most with total {} minutes.", guard, total); // Then we need to find the minute they like to sleep the most let stat_for_guard = stats.get(guard).unwrap(); let (frequent_min, _) = stat_for_guard.get_most_frequent().unwrap(); println!("Most frequent minute: {:?}", frequent_min); let answer = frequent_min * guard; println!("Best by total number of minutes: {}", answer); } else { println!("Error: could not find the guard who sleeps most!"); } } fn find_best_by_most(stats: &HashMap<i32, Stats>) { let max_by_minute_times = stats .iter() .map(|(id, s)| { let (minute, times) = s.get_most_frequent().unwrap(); (id, times, minute) }) .max_by(|a, b| a.1.cmp(&b.1)); let (guard, _, minute) = max_by_minute_times.unwrap(); let answer = guard * minute; println!("Best by most minutes: {}", answer); } } pub fn day4(input: &str) { let f = File::open(input).expect("file not found"); let file = BufReader::new(&f); let mut records = vec![]; for line in file.lines() { let srecord = line.expect("failed to read input line"); if let Ok(record) = Record::parse(&srecord) { records.push(record); } else { println!("Failed to parse line: {}", srecord); } } Record::sort_records(&mut records); let records = Record::process(&records); Record::find_best_by_total(&records); Record::find_best_by_most(&records); } #[test] fn test_parse_date_format() { let d = Utc .datetime_from_str("1518-11-01 00:00", "%Y-%m-%d %H:%M") .unwrap(); assert_eq!(d.year(), 1518); assert_eq!(d.month(), 11); assert_eq!(d.day(), 1); assert_eq!(d.hour(), 0); assert_eq!(d.minute(), 0); let d = Utc .datetime_from_str("1518-11-04 00:36", "%Y-%m-%d %H:%M") .unwrap(); assert_eq!(d.year(), 1518); assert_eq!(d.month(), 11); assert_eq!(d.day(), 4); assert_eq!(d.hour(), 0); assert_eq!(d.minute(), 36); } #[test] fn test_parse_record() { let record = Record::parse("[1518-11-01 00:00] Guard #10 begins shift").unwrap(); assert_eq!(record.time.year(), 1518); assert_eq!(record.time.month(), 11); assert_eq!(record.time.day(), 1); assert_eq!(record.observation, Action::Shift { guard: 10 }); let record = Record::parse("[1518-7-8 00:05] falls asleep").unwrap(); assert_eq!(record.time.year(), 1518); assert_eq!(record.time.month(), 7); assert_eq!(record.time.day(), 8); assert_eq!(record.observation, Action::Sleep); let record = Record::parse("[1518-11-30 00:25] wakes up").unwrap(); assert_eq!(record.time.year(), 1518); assert_eq!(record.time.month(), 11); assert_eq!(record.time.day(), 30); assert_eq!(record.observation, Action::WakeUp); }
#[doc = "Reader of register WAKEUP_CONTROL"] pub type R = crate::R<u32, super::WAKEUP_CONTROL>; #[doc = "Writer for register WAKEUP_CONTROL"] pub type W = crate::W<u32, super::WAKEUP_CONTROL>; #[doc = "Register WAKEUP_CONTROL `reset()`'s with value 0"] impl crate::ResetValue for super::WAKEUP_CONTROL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `WAKEUP_INSTANT`"] pub type WAKEUP_INSTANT_R = crate::R<u16, u16>; #[doc = "Write proxy for field `WAKEUP_INSTANT`"] pub struct WAKEUP_INSTANT_W<'a> { w: &'a mut W, } impl<'a> WAKEUP_INSTANT_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 - Instant, with reference to the internal 16-bit clock reference, at which the hardware must wakeup from deep sleep mode. This is calculated by firmware based on the next closest instant where a controller operation is required (like advertiser/scanner). Firmware reads the next instant of the procedures in the corresponding *_NEXT_INSTANT registers. This value is used only when hardware auto wakeup from deep sleep mode is enabled in the clock control register. Note: it is recommended to program wakeup_instant such a way that the actual instant to wakeup shall be at least two counts (two slots of 625 us) ahead of reference clock when entering DSM. The actual instant to wakeup is 'wakeup_instant - dsm_offset_to_wakeup_instant - osc_startup_delay, and it shall be greater than 'reference clock + 2'"] #[inline(always)] pub fn wakeup_instant(&self) -> WAKEUP_INSTANT_R { WAKEUP_INSTANT_R::new((self.bits & 0xffff) as u16) } } impl W { #[doc = "Bits 0:15 - Instant, with reference to the internal 16-bit clock reference, at which the hardware must wakeup from deep sleep mode. This is calculated by firmware based on the next closest instant where a controller operation is required (like advertiser/scanner). Firmware reads the next instant of the procedures in the corresponding *_NEXT_INSTANT registers. This value is used only when hardware auto wakeup from deep sleep mode is enabled in the clock control register. Note: it is recommended to program wakeup_instant such a way that the actual instant to wakeup shall be at least two counts (two slots of 625 us) ahead of reference clock when entering DSM. The actual instant to wakeup is 'wakeup_instant - dsm_offset_to_wakeup_instant - osc_startup_delay, and it shall be greater than 'reference clock + 2'"] #[inline(always)] pub fn wakeup_instant(&mut self) -> WAKEUP_INSTANT_W { WAKEUP_INSTANT_W { w: self } } }
use hymns::p2; use hymns::runner::timed_run; use hymns::vector2::Point2; use std::collections::HashSet; use std::ops::RangeInclusive; type Point = Point2<isize>; type Velocity = Point2<isize>; fn step(point: &mut Point, velocity: &mut Velocity) { *point += *velocity; *velocity = p2!(velocity.x - velocity.x.signum(), velocity.y - 1); } fn check_velocity( start_velocity: Velocity, target_x: &RangeInclusive<isize>, target_y: &RangeInclusive<isize>, ) -> Option<isize> { let mut point = p2!(0, 0); let mut cur_velocity = start_velocity; let mut max_reached = 0; while point.x <= *target_x.end() { max_reached = max_reached.max(point.y); if target_x.contains(&point.x) && target_y.contains(&point.y) { return Some(max_reached); } if cur_velocity.x == 0 && point.y < *target_y.start() { break; } step(&mut point, &mut cur_velocity); } None } fn part1() -> isize { let target_x = 192..=251; let target_y = -89..=-59; // x velocity has to be less than target_x.end() let mut result = 0; for x_vel in 1..=(*target_x.end()) { for y_vel in *target_y.start()..=1000 { if let Some(max_height) = check_velocity(p2!(x_vel, y_vel), &target_x, &target_y) { result = result.max(max_height); } } } result } fn part2() -> usize { let target_x = 192..=251; let target_y = -89..=-59; let mut good_velocities = HashSet::new(); for x_vel in 1..=(*target_x.end()) { for y_vel in *target_y.start()..=1000 { let velocity = p2!(x_vel, y_vel); if check_velocity(velocity, &target_x, &target_y).is_some() { good_velocities.insert(velocity); } } } good_velocities.len() } fn main() { timed_run(1, part1); timed_run(2, part2); } #[cfg(test)] mod tests { use super::*; #[test] fn test_part1() { assert_eq!(part1(), 3916); } #[test] fn test_part2() { assert_eq!(part2(), 2986); } }
use std::{ io::{BufReader, Write}, path::Path, }; pub fn read<T: serde::de::DeserializeOwned, P: AsRef<Path>>( path: P, ) -> Result<T, Box<dyn std::error::Error>> { let file = std::fs::File::open(path)?; let reader = BufReader::new(file); serde_json::from_reader(reader).map_err(|e| e.into()) } pub fn write<T: serde::Serialize, P: AsRef<Path>>( path: P, data: T, ) -> Result<(), Box<dyn std::error::Error>> { std::fs::File::create(path)?.write_all(serde_json::to_string(&data)?.as_bytes())?; Ok(()) } #[cfg(test)] mod tests { use super::*; #[derive(Default, serde::Serialize, serde::Deserialize)] struct Scaf { id: i32, } #[test] fn test_create() { let path = format!( "/tmp/{}.json", std::time::SystemTime::now() .duration_since(std::time::SystemTime::UNIX_EPOCH) .unwrap() .as_nanos() ); write(&path, vec![1, 2, 3]).unwrap(); let data: Vec<i32> = read(&path).unwrap(); assert_eq!(data, [1, 2, 3]); } }
use gml_fmt_lib::*; const LANG_CONFIG: LangConfig = LangConfig { use_spaces: true, space_size: 4, newlines_at_end: 1, }; fn run_test(input: &str) -> String { run(input, &LANG_CONFIG, None).expect("Panicked during Integration Test!") } #[test] fn regions() { let input = "#region Test Test Test #endregion Okay "; let format = "#region Test Test Test #endregion Okay "; assert_eq!(run_test(input), format); } #[test] fn multiline_string() { let input = "@\"Test sure yup\""; let format = "@\"Test sure yup\"; "; assert_eq!(run_test(input), format); } #[test] fn else_if() { let input = "if (xx < (1 2.75)) { return x; } else if (xx < (2 / 2.75)) { return z; }"; let format = "if (xx < (1 2.75)) { return x; } else if (xx < (2 / 2.75)) { return z; } "; assert_eq!(run_test(input), format); } #[test] fn series_of_declarations() { let input = "var function, xx, xx2, xxm1; var x = 2, y, var q"; let format = "var function, xx, xx2, xxm1; var x = 2, y, var q; "; assert_eq!(run_test(input), format); } #[test] fn do_until() { let input = "do { // whatever show_debug_message(x); } until (test); do { // gah } until (true); "; let format = "do { // whatever show_debug_message(x); } until (test); do { // gah } until (true); "; assert_eq!(run_test(input), format); } #[test] fn for_loops() { let input = "for (var x = 0; i < 10; i++) { show_debug_message(\"test\"); for (; i < 10; i++) { show_debug_message(3); } } for (var i;; i++) { show_debug_message(3); } for (var i;;) { show_debug_message(4); } "; let format = "for (var x = 0; i < 10; i++) { show_debug_message(\"test\"); for (; i < 10; i++) { show_debug_message(3); } } for (var i;; i++) { show_debug_message(3); } for (var i;;) { show_debug_message(4); } "; assert_eq!(run_test(input), format); } #[test] fn decimal_number() { let input = "var x = .3; var z = 3.;"; let format = "var x = 0.3; var z = 3.0; "; assert_eq!(run_test(input), format); } #[test] fn trailing_commas() { let input = "func(a,b,c,);"; let format = "func(a, b, c,); "; assert_eq!(run_test(input), format); } #[test] fn not_trailing_commas() { let input = "fun( _e[Foo.bar], _e[Foo.bar], _e[Foo.bar] );"; let output = "fun( _e[Foo.bar], _e[Foo.bar], _e[Foo.bar] ); "; assert_eq!(run_test(input), output); } #[test] fn enum_test() { let input = "enum EInputConstants{//Starts at high negative number to not interfere with other input constants //P - Positive axis (Axis is regular coordinates with 0;0 being bottom left) //N - Negative axis //Note that return is always positive GP_AXISLV_P = -100, GP_AXISLV_N, GP_AXISLH_P, GP_AXISLH_N, GP_AXISRV_P, //down GP_AXISRV_N, //up GP_AXISRH_P, /* gah a test */ GP_AXISRH_N, SCROLL_DOWN, SCROLL_UP,ANY,NONE }"; let format = "enum EInputConstants { //Starts at high negative number to not interfere with other input constants //P - Positive axis (Axis is regular coordinates with 0;0 being bottom left) //N - Negative axis //Note that return is always positive GP_AXISLV_P = -100, GP_AXISLV_N, GP_AXISLH_P, GP_AXISLH_N, GP_AXISRV_P, //down GP_AXISRV_N, //up GP_AXISRH_P, /* gah a test */ GP_AXISRH_N, SCROLL_DOWN, SCROLL_UP, ANY, NONE } "; assert_eq!(run_test(input), format); } #[test] fn do_until_double_loop() { let input = "do { //If foo if (_a[# _x, _y] != _val){ if (array_find_index(_gah,_goo) == -1){ _a[# _x, _y] = _val; ++sha; } } //bar var _dir = irandom(3) * 200; _x += lengthdir_x(1,_dir); _y += lengthdir_y(1,_dir); } until(_gah / _boo > _bah); "; let output = "do { //If foo if (_a[# _x, _y] != _val) { if (array_find_index(_gah, _goo) == -1) { _a[# _x, _y] = _val; ++sha; } } //bar var _dir = irandom(3) * 200; _x += lengthdir_x(1, _dir); _y += lengthdir_y(1, _dir); } until (_gah / _boo > _bah); "; assert_eq!(run_test(input), output); } #[test] fn if_with_line() { let input = "if (a < 0) { var b = false; with (ident) { var dir = point_direction(other.x, other.y, a(), b()); with (other) { hspeed = hsp; vspeed = vsp; direction = angle_approach(direction, dir, rot); if (a(x, y, 2, target, false, false)) { z(0); e(); } speed = approach(speed, max_spd, acc); hsp = hspeed; vsp = vspeed; speed = 0; a += t * global.delta; } exists = true; } g -= global.delta; if (g < 0 || !exists) { a(); } val = true; } // Foo x += hsp*ss; y += vsp*ss;"; let output = "if (a < 0) { var b = false; with (ident) { var dir = point_direction(other.x, other.y, a(), b()); with (other) { hspeed = hsp; vspeed = vsp; direction = angle_approach(direction, dir, rot); if (a(x, y, 2, target, false, false)) { z(0); e(); } speed = approach(speed, max_spd, acc); hsp = hspeed; vsp = vspeed; speed = 0; a += t * global.delta; } exists = true; } g -= global.delta; if (g < 0 || !exists) { a(); } val = true; } // Foo x += hsp * ss; y += vsp * ss; "; assert_eq!(run_test(input), output); } #[test] fn do_access_cascading() { let input = "if (a(b[i])&& b[i] .c < 0) { var c = b[i].q; var l = b[i].q; b[i].q = c; b[i].q[0] = 30; } "; let output = "if (a(b[i]) && b[i].c < 0) { var c = b[i].q; var l = b[i].q; b[i].q = c; b[i].q[0] = 30; } "; assert_eq!(run_test(input), output); } #[test] fn ending_delimiter_enum() { let input = "colour = choose( 4, // foo 5, // foor 6, // foo, 7, // bar )"; let output = "colour = choose( 4, // foo 5, // foor 6, // foo, 7, // bar ); "; assert_eq!(run_test(input), output); } #[test] fn double_call() { let input = "func( a, b, c[a], d[Y], 5, 4, 1, global.q * 0.13, between(a, c * 0.72, u * 0.76) || between(b, d * 0.82, u * 0.86) || between(c, c * 0.92, u * 0.96) ? c_white : c_red ); "; assert_eq!(run_test(input), input); } #[test] fn non_block_if_else() { let input = "if (true) return false; else if (true) return false; if (true) return false; else if (true) return false; if (true) return false; if (true) return false; "; assert_eq!(run_test(input), input); } #[test] fn horrible_multiline_string() { let input = "var _bulletNormal = string_join(@\'{ \"type\": \"normal\", \"object\": \', Obj_Bullet, @\', \"speed\": 260, \"count\": 1, \"damage\": 1, \"knockback\": 0.1, \"lifetime\": 8000 }\'); "; assert_eq!(run_test(input), input); } #[test] fn nice_macro() { let input = "#macro give_me_five x =5+5;"; let output = "#macro give_me_five x =5+5; "; assert_eq!(run_test(input), output); } #[test] fn whitesmith_enum() { let input = "enum YosiFunction { init, main, new_player, new_zapper, new_laser, move_ground, rect, blueprint_read, player_die, } "; let output = "enum YosiFunction { init, main, new_player, new_zapper, new_laser, move_ground, rect, blueprint_read, player_die, } "; assert_eq!(run_test(input), output); } #[test] fn whitesmith_control_statement() { let input = "while true { // who would format like this } "; let output = "while true { // who would format like this } "; assert_eq!(run_test(input), output); } #[test] fn bad_for_loop() { let input = "for (var xx = clamp((global.cameraLeft - 25) div 192, 0, 6); xx <= clamp((global.cameraRight + 25) div 192, 0, 6); ++xx;) { // comments }"; let output = "for (var xx = clamp((global.cameraLeft - 25) div 192, 0, 6); xx <= clamp((global.cameraRight + 25) div 192, 0, 6); ++xx) { // comments } "; assert_eq!(run_test(input), output); } #[test] fn expression_no_semicolon_test() { let input = "call(z) call(q) x = 20 y = 10 "; let output = "call(z); call(q); x = 20; y = 10; "; assert_eq!(run_test(input), output); } #[test] fn mix_no_semicolon() { let input = "global.roundOver=true alarm[3]=room_speed/10; audio_stop_sound(aMusicTitle);"; let output = "global.roundOver = true; alarm[3] = room_speed / 10; audio_stop_sound(aMusicTitle); "; assert_eq!(run_test(input), output); }
// list of IO submodules pub mod compress; pub mod display; pub mod read_write;
use clap::{ app_from_crate, crate_authors, crate_description, crate_name, crate_version, App, Arg, ArgGroup, ArgMatches, }; use crate::fetch_ip_addr; use crate::ip_addr_client::prelude::*; pub fn get_clap_app() -> App<'static, 'static> { let app = app_from_crate!() .arg( Arg::with_name("aws") .short("A") .long("aws") .help("fetch for checkip.amazonaws.com"), ) .arg( Arg::with_name("httpbin") .short("B") .long("httpbin") .help("fetch for httpbin.org/ip"), ) .arg( Arg::with_name("ifconfig") .short("C") .long("ifconfig") .help("fetch for ifconfig.me"), ) .group(ArgGroup::with_name("hosts").args(&["aws", "httpbin", "ifconfig"])) .arg( Arg::with_name("ssl") .short("s") .long("ssl") .help("fetch using SSL"), ) .arg( Arg::with_name("no-ssl") .short("n") .long("no-ssl") .help("fetch using no SSL"), ) .group(ArgGroup::with_name("use-ssl").args(&["ssl", "no-ssl"])) .arg( Arg::with_name("verbose") .short("v") .long("verbose") .help("output verbose"), ); app } pub fn from_ipaddr_client(matches: &ArgMatches) -> Box<dyn IpAddrClient> { let verbose = matches.is_present("verbose"); let use_ssl = UseSsl::from(matches.is_present("ssl"), matches.is_present("no-ssl")); if verbose { eprintln!("Use SSL: {:?}", use_ssl); } let hosts = Host::from( matches.is_present("aws"), matches.is_present("httpbin"), matches.is_present("if_config"), ); if verbose { eprintln!("Host: {:?}", hosts); } match (hosts, use_ssl) { (Host::AmazonAws, UseSsl::Ssl) => Box::new(AmazonAws::new_https()), (Host::AmazonAws, UseSsl::NoSsl) => Box::new(AmazonAws::new_http()), (Host::AmazonAws, UseSsl::Undefined) => Box::new(AmazonAws::new_http()), (Host::HttpBin, UseSsl::Ssl) => Box::new(HttpBin::new_https()), (Host::HttpBin, UseSsl::NoSsl) => Box::new(HttpBin::new_http()), (Host::HttpBin, UseSsl::Undefined) => Box::new(HttpBin::new_http()), (Host::IfConfig, UseSsl::Ssl) => Box::new(IfConfig::new_https()), (Host::IfConfig, UseSsl::NoSsl) => Box::new(IfConfig::new_http()), (Host::IfConfig, UseSsl::Undefined) => Box::new(IfConfig::new_http()), (Host::Undefined, UseSsl::Ssl) => fetch_ip_addr::random_client_https(), (Host::Undefined, UseSsl::NoSsl) => fetch_ip_addr::random_client_http(), (Host::Undefined, UseSsl::Undefined) => fetch_ip_addr::random_client(), } } #[derive(Debug)] enum UseSsl { Undefined, NoSsl, Ssl, } impl UseSsl { fn from(ssl: bool, no_ssl: bool) -> Self { match (ssl, no_ssl) { (true, false) => UseSsl::Ssl, (false, true) => UseSsl::NoSsl, (false, false) => UseSsl::Undefined, (true, true) => unreachable!(), } } } #[derive(Debug)] enum Host { Undefined, AmazonAws, IfConfig, HttpBin, } impl Host { fn from(amazon_aws: bool, http_bin: bool, if_config: bool) -> Self { match (amazon_aws, http_bin, if_config) { (true, false, false) => Host::AmazonAws, (false, true, false) => Host::HttpBin, (false, false, true) => Host::IfConfig, (false, false, false) => Host::Undefined, _ => unreachable!(), } } }
use bot::Bot; use types::*; use board::Board; use std::time::*; pub struct StarterBot { rng_state: u64, board: Option<Board>, id: u32, round: u32 } impl StarterBot { pub fn new() -> Self { StarterBot { rng_state: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(), board: None, id: 0, round: 0 } } } impl Bot for StarterBot { fn get_move(&mut self) -> Move { self.rng_state = (1664525 * self.rng_state + 1013904223) % 4294967296; let moves: Vec<Move> = self.board .as_ref() .iter() .flat_map(|b| b.legal_moves(self.id)) .collect(); if moves.len() > 0 { moves.get(self.rng_state as usize % moves.len()).map(|m| (*m).clone()).unwrap() } else { Move::Up } } fn update_round(&mut self, round: u32) { self.round = round; } fn update_board(&mut self, board: Board) { self.board = Some(board); } fn set_setting(&mut self, setting: Setting) { match setting { Setting::BotId(id) => self.id = id, _ => {} } } }
// We give `ClassName` variables an identifier that uses upper-case. #![allow(non_snake_case)] use proc_macro2::Span; use quote::{ToTokens, Tokens}; use syn::Ident; use glib_utils::*; use gen::WithSuffix; use hir::{Class, Program}; pub struct ClassContext<'ast> { pub program: &'ast Program<'ast>, pub class: &'ast Class<'ast>, pub PrivateStructName: Ident, pub ModuleName: Ident, pub InstanceName: &'ast Ident, pub InstanceNameFfi: Ident, pub ClassName: Ident, pub PrivateClassName: Ident, pub ParentInstance: &'ast ToTokens, pub ParentInstanceFfi: &'ast Tokens, pub ParentClassFfi: &'ast Tokens, pub GObject: Tokens, pub GObjectFfi: Tokens, pub GObjectClassFfi: Tokens, pub InstanceExt: Ident, } impl<'ast> ClassContext<'ast> { #[cfg_attr(rustfmt, rustfmt_skip)] pub fn new(program: &'ast Program, class: &'ast Class) -> Self { // This function creates a ClassContext by generating the // commonly-used symbol names for the class in question, for // example, "FooClass" out of "Foo". ClassContext { program, class, PrivateStructName: class.name.with_suffix("Priv"), ModuleName: class.name.with_suffix("Mod"), // toplevel "InstanceMod" module name InstanceName: &class.name, ClassName: class.name.with_suffix("Class"), PrivateClassName: class.name.with_suffix("ClassPrivate"), ParentInstance: &class.parent, ParentInstanceFfi: &class.parent_ffi, ParentClassFfi: &class.parent_class_ffi, GObject: tokens_GObject(), GObjectFfi: tokens_GObjectFfi(), GObjectClassFfi: tokens_GObjectClassFfi(), InstanceExt: class.name.with_suffix("Ext"), // public trait with all the class's methods InstanceNameFfi: class.name.with_suffix("Ffi"), } } pub fn gen_class(&self) -> Tokens { self.gen_boilerplate() } pub fn exported_fn_name(&self, method_name: &str) -> Ident { Ident::new( &format!( "{}_{}", lower_case_instance_name(self.InstanceName.as_ref()), method_name ), Span::call_site(), ) } pub fn instance_get_type_fn_name(&self) -> Ident { self.exported_fn_name("get_type") } }
pub mod lifegame; pub use lifegame::*;
use std::io; use rand::Rng; const MAX_GAMES: u32 = 5; fn get_int_input(default: u32, question: String, validation_fn: impl Fn(u32) -> (bool, String)) -> u32{ // Passing closure as args let mut num: u32 = default; loop { println!("{}", question); let mut input1 = String::new(); io::stdin() .read_line(&mut input1) .expect("Failed to read from input"); let trimmed = input1.trim(); if trimmed.len() == 0 { break; } match trimmed.parse::<u32>() { Ok(i) => { let (is_valid, error_msg) = validation_fn(i); // Tuple destructuring assignment if is_valid { num = i; break } else { println!("{}", error_msg); } }, Err(e) => println!("Invalid number entered. Please try again. Error is {}", e) } } num } fn main() { let validate_total_games = |i: u32| -> (bool, String) { (i <= MAX_GAMES, format!("Max total game is {}", MAX_GAMES)) }; // Passing the validation closure as an arg to the get_int_input function let total_games = get_int_input(3, format!("How many games do you want to play in total? [{}]", 3), validate_total_games); let validate_games_to_win = |i: u32| -> (bool, String){ (i <= total_games, format!("Number of games to win {} must be less than or equal to total games {}", i, total_games)) }; let games_to_win = get_int_input(2, format!("How many games to win the overall game? [{}]", 2), validate_games_to_win); let mut games_played = 0; let mut games_user_won = 0; while games_played < total_games && games_user_won < games_to_win && games_played - games_user_won < games_to_win { println!("Game {} of {} starts now... input your choice [R]ock or [P]aper or [S]cissors:", games_played + 1, total_games); // R = 0, P = 1, S = 2 let choices = ["R", "P", "S"]; let computer_choice:i32 = rand::thread_rng().gen_range(0, 3); let player_choice: i32; let mut input3 = String::new(); io::stdin() .read_line(&mut input3) .expect("Error reading from input"); match input3.trim().to_uppercase().as_ref() { "R" => player_choice = 0, "P" => player_choice = 1, "S" => player_choice = 2, _ => { println!("Invalid choice - this game will be restarted"); continue; } } println!("Computer's choice is {}", choices[computer_choice as usize]); // R > P > S > R if player_choice - 1 == computer_choice || (player_choice == 0 && computer_choice == 2) { println!("You won this game"); games_user_won += 1; } else if player_choice == computer_choice { println!("This game is a tie, skipping"); continue } else { println!("You lost this game"); } games_played += 1; } if games_user_won >= games_to_win { println!("{} vs {}. You won the overall game", games_user_won, games_played - games_user_won); } else if games_played - games_user_won >= games_to_win { println!("{} vs {}. You lost the overall game", games_user_won, games_played - games_user_won); } else { println!("{} vs {}. Overall is a tie game", games_user_won, games_played - games_user_won); } }
use crate::{bool_to_option, to_option_string}; use wasm_bindgen::prelude::*; use yew::prelude::*; #[wasm_bindgen(module = "/build/mwc-linear-progress.js")] extern "C" { #[derive(Debug)] type LinearProgress; #[wasm_bindgen(getter, static_method_of = LinearProgress)] fn _dummy_loader() -> JsValue; } loader_hack!(LinearProgress); /// Props for [`MatLinearProgress`] /// /// [MWC Documentation for properties](https://github.com/material-components/material-components-web-components/tree/master/packages/linear-progress#propertiesattributes) #[derive(Debug, Properties, Clone)] pub struct LinearProgressProps { #[prop_or_default] pub indeterminate: bool, #[prop_or_default] pub progress: f32, #[prop_or_default] pub buffer: f32, #[prop_or_default] pub reverse: bool, #[prop_or_default] pub closed: bool, } component!( MatLinearProgress, LinearProgressProps, |props: &LinearProgressProps| { html! { <mwc-linear-progress indeterminate=bool_to_option(props.indeterminate) progress=to_option_string(props.progress) buffer=to_option_string(props.buffer) reverse=bool_to_option(props.reverse) closed=bool_to_option(props.closed) ></mwc-linear-progress> } }, LinearProgress, "linear-progress" );
use crate::test::spec::unified_runner::run_unified_tests; #[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] // multi_thread required for FailPoint #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn run_unified() { run_unified_tests(&["change-streams", "unified"]) .skip_files(&[ // TODO RUST-1281: unskip this file "change-streams-showExpandedEvents.json", // TODO RUST-1423: unskip this file "change-streams-disambiguatedPaths.json", ]) .skip_tests(&[ // TODO RUST-1658: unskip these tests "Test with document comment", "Test with string comment", "Test that comment is set on getMore", "Test with document comment - pre 4.4", "Test that comment is not set on getMore - pre 4.4", ]) .await; }
use crate::SdpTransport; use crate::SdpAttribute; mod media_format; pub use self::media_format::SdpMediaFormat; mod media_type; pub use self::media_type::SdpMediaType; pub use self::media_type::parse_media_type; mod parse; pub use self::parse::parse_media; pub use self::parse::parse_attribute; pub use self::parse::parse_media_lines; pub use self::parse::parse_optional_port; pub use self::parse::parse_attribute_list; pub use self::parse::parse_initial_media_format; mod encoding; pub use self::encoding::SdpEncoding; pub use self::encoding::parse_encoding; use std::fmt; #[derive(Debug, PartialEq, Clone)] pub struct SdpMedia { pub media: SdpMediaType, pub port: u32, pub port_count: Option<u32>, pub transport: SdpTransport, pub attributes: Vec<SdpAttribute>, pub formats: Vec<SdpMediaFormat> } impl SdpMedia { pub fn new(media: SdpMediaType, port: u32, transport: SdpTransport) -> SdpMedia { SdpMedia { media, port, port_count: None, transport, attributes: vec![], formats: vec![] } } pub fn attribute(mut self, attr: SdpAttribute) -> SdpMedia { self.attributes.push(attr); self } pub fn attributes(mut self, attrs: Vec<SdpAttribute>) -> SdpMedia { self.attributes = attrs; self } pub fn format(mut self, attr: SdpMediaFormat) -> SdpMedia { self.formats.push(attr); self } pub fn transport(mut self, trans: SdpTransport) -> SdpMedia { self.transport = trans; self } pub fn port_count(mut self, port_count: u32) -> SdpMedia { self.port_count = Some(port_count); self } } impl fmt::Display for SdpMedia { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(port_count) = self.port_count { write!(f, "{} {}/{} {}", self.media, self.port, port_count, self.transport)?; } else { write!(f, "{} {} {}", self.media, self.port, self.transport)?; } for format in &self.formats { write!(f, " {}", format.codec)?; } for attribute in &self.attributes { match attribute { SdpAttribute::SendOnly => write!(f, "\r\na=sendonly")?, SdpAttribute::RecvOnly => write!(f, "\r\na=recvonly")?, SdpAttribute::SendRecv => write!(f, "\r\na=sendrecv")?, SdpAttribute::RtpMap(data) => write!(f, "\r\na=rtpmap {}", data)?, SdpAttribute::Fmtp(data) => write!(f, "\r\na=fmtp {}", data)? } } for format in &self.formats { for attribute in &format.attributes { match attribute { SdpAttribute::SendOnly => write!(f, "\r\na=sendonly:{}", format.codec)?, SdpAttribute::RecvOnly => write!(f, "\r\na=recvonly:{}", format.codec)?, SdpAttribute::SendRecv => write!(f, "\r\na=sendrecv:{}", format.codec)?, SdpAttribute::RtpMap(data) => write!(f, "\r\na=rtpmap:{} {}", format.codec, data)?, SdpAttribute::Fmtp(data) => write!(f, "\r\na=fmtp:{} {}", format.codec, data)? } } } Ok(()) } }
#![deny(clippy::all, clippy::pedantic)] pub fn reply(message: &str) -> &str { let message = message.trim(); if message.is_empty() { return "Fine. Be that way!"; } let mut chars = message.chars().rev(); let last_char = chars.next().unwrap(); let mut chars = chars.filter(|c| c.is_alphabetic()).peekable(); let is_shouting = chars.peek().is_some() && chars.all(|c| c.is_uppercase()); match last_char { '?' if is_shouting => "Calm down, I know what I'm doing!", '?' => "Sure.", _ if is_shouting => "Whoa, chill out!", _ => "Whatever.", } }
extern crate bufstream; extern crate config; extern crate linkify; extern crate reqwest; extern crate select; extern crate serde; use bufstream::BufStream; use serde::Deserialize; use std::io::prelude::*; use std::net::TcpStream; use select::document::Document; use select::predicate::Name; fn get_title_from_link(link: linkify::Link) -> Result<String, String> { reqwest::blocking::get(link.as_str()) .map_err(|e| e.to_string()) .and_then(|res| Document::from_read(res).map_err(|e| e.to_string())) .and_then(|doc| { doc.find(Name("title")) .next() .ok_or(format!("No title found on url {}", link.as_str())) .map(|elem| elem.text()) }) } fn print_and_discard(r: &Result<String, String>) { match r { Ok(v) => println!("{}", v), Err(e) => println!("error: {}", e), } } #[derive(Debug, Deserialize)] struct Settings { channel: String, server: String, nick: String, name: String, user: String, } fn get_settings() -> Result<Settings, config::ConfigError> { let mut settings = config::Config::default(); settings.merge(config::File::with_name("Settings"))?; settings.try_into() } fn main() -> Result<(), String> { get_settings().map_err(|e| e.to_string()).and_then(|s| { TcpStream::connect(&s.server) .map_err(|e| e.to_string()) .map(|tcp_stream| BufStream::new(tcp_stream)) .and_then(|mut bufstream| { send_raw_msg_to_stream(&mut bufstream, &format!("NICK {}", &s.nick)) .and(send_raw_msg_to_stream( &mut bufstream, &format!("USER {} 0 * :{}", &s.user, &s.name), )) .and(send_raw_msg_to_stream( &mut bufstream, &format!("JOIN {}", &s.channel), )) .map(|_| irc_loop(bufstream, s)) }) }) } fn irc_loop(mut bufstream: BufStream<TcpStream>, s: Settings) { let split_by_channel = format!("PRIVMSG {}", &s.channel); let mut buffer = String::new(); while let Ok(_) = bufstream.read_line(&mut buffer) { print!(">> {}", buffer); if buffer.starts_with("PING") { print_and_discard(&send_raw_msg_to_stream( &mut bufstream, &buffer.replace("PING", "PONG").trim_end(), )); } else { buffer.split(&split_by_channel).nth(1).map(|chan_msg| { linkify::LinkFinder::new().links(chan_msg).for_each(|link| { print_and_discard(&get_title_from_link(link).and_then(|title| { send_raw_msg_to_stream(&mut bufstream, &as_channel_msg(&s.channel, &title)) })) }) }); } buffer.clear(); } } fn as_channel_msg(channel: &str, msg: &str) -> String { format!("PRIVMSG {} :{}", channel, msg) } fn send_raw_msg_to_stream<W: Write>(w: &mut W, msg: &str) -> Result<String, String> { let to_write = format!("{}\r\n", msg); w.write(to_write.as_bytes()) .and(w.flush()) .map_err(|e| e.to_string()) .map(|_| format!("<< {}", to_write)) }