text
stringlengths
8
4.13M
use rustc_hash::FxHashMap; use winit::event::{ElementState, VirtualKeyCode}; #[allow(unused_imports)] use winit::{ event::{self, Event, KeyboardInput, WindowEvent}, event_loop::ControlFlow, }; use crossbeam::atomic::AtomicCell; use crossbeam::channel; use std::sync::Arc; use crate::gui::GuiInput; use crate::{app::mainview::MainViewInput, gui::GuiMsg}; use crate::{app::AppInput, reactor::Reactor}; use crate::{app::SharedState, geometry::*}; pub mod binds; pub use binds::{BindableInput, DigitalState, SystemInputBindings}; use binds::*; struct SubsystemInput<T: InputPayload + BindableInput> { bindings: SystemInputBindings<T>, tx: channel::Sender<SystemInput<T>>, rx: channel::Receiver<SystemInput<T>>, } impl<T: InputPayload + BindableInput> SubsystemInput<T> { fn from_default_binds() -> Self { let bindings = T::default_binds(); let (tx, rx) = channel::unbounded::<SystemInput<T>>(); Self { bindings, tx, rx } } pub fn clone_rx(&self) -> channel::Receiver<SystemInput<T>> { self.rx.clone() } } pub struct InputManager { mouse_screen_pos: Arc<AtomicCell<Point>>, modifiers: AtomicCell<event::ModifiersState>, winit_rx: channel::Receiver<event::WindowEvent<'static>>, app: SubsystemInput<AppInput>, main_view: SubsystemInput<MainViewInput>, gui: SubsystemInput<GuiInput>, gui_focus_state: crate::gui::GuiFocusState, custom_binds: FxHashMap< winit::event::VirtualKeyCode, Arc<dyn Fn() + Send + Sync + 'static>, // Box<dyn Fn() + Send + Sync + 'static>, >, // custom_binds: Arc<Mutex<FxHashMap< // winit::event::VirtualKeyCode, // Box<dyn Fn() + Send + Sync + 'static>, // >>>, } impl InputManager { pub fn clone_app_rx(&self) -> channel::Receiver<SystemInput<AppInput>> { self.app.clone_rx() } pub fn clone_main_view_rx( &self, ) -> channel::Receiver<SystemInput<MainViewInput>> { self.main_view.clone_rx() } pub fn clone_gui_rx(&self) -> channel::Receiver<SystemInput<GuiInput>> { self.gui.clone_rx() } pub fn read_mouse_pos(&self) -> Point { self.mouse_screen_pos.load() } pub fn clone_mouse_pos(&self) -> Arc<AtomicCell<Point>> { self.mouse_screen_pos.clone() } pub fn add_binding<F>( &mut self, key_code: winit::event::VirtualKeyCode, command: F, ) where F: Fn() + Send + Sync + 'static, { let boxed = Arc::new(command) as Arc<dyn Fn() + Send + Sync + 'static>; // log::warn!("calling boxed binding command"); // boxed(); self.custom_binds.insert(key_code, boxed); } pub fn handle_events( &self, reactor: &mut Reactor, gui_msg_tx: &channel::Sender<GuiMsg>, ) { while let Ok(winit_ev) = self.winit_rx.try_recv() { if let event::WindowEvent::CursorMoved { position, .. } = winit_ev { self.mouse_screen_pos.store(Point { x: position.x as f32, y: position.y as f32, }); } if let event::WindowEvent::ModifiersChanged(mods) = winit_ev { self.modifiers.store(mods); gui_msg_tx.send(GuiMsg::SetModifiers(mods)).unwrap(); } let mouse_pos = self.mouse_screen_pos.load(); let gui_wants_keyboard = self.gui_focus_state.wants_keyboard_input(); let mouse_over_gui = self.gui_focus_state.mouse_over_gui(); // NB: on my machine at least, after a file is dropped, // keyboard events appear to not be generated until the // window loses and regains focus; i'm guessing it's a // winit bug, or a winit + sway (+ xwayland) bug if let event::WindowEvent::DroppedFile(ref path) = winit_ev { gui_msg_tx .send(GuiMsg::FileDropped { path: path.clone() }) .unwrap(); } let modifiers = self.modifiers.load(); if gui_wants_keyboard { if let event::WindowEvent::KeyboardInput { input, .. } = winit_ev { if let Some(gui_msg) = input.virtual_keycode.and_then(|key| { winit_to_clipboard_event( modifiers, input.state, key, ) }) { gui_msg_tx.send(gui_msg).unwrap(); } if let Some(event) = input.virtual_keycode.and_then(|key| { winit_to_egui_text_event(modifiers, input.state, key) }) { gui_msg_tx .send(crate::gui::GuiMsg::EguiEvent(event)) .unwrap(); } } if let event::WindowEvent::ReceivedCharacter(c) = winit_ev { if !c.is_ascii_control() { let event = received_char_to_egui_text(c); gui_msg_tx .send(crate::gui::GuiMsg::EguiEvent(event)) .unwrap(); } } } if let Some(app_inputs) = self.app.bindings.apply(&winit_ev, modifiers, mouse_pos) { for input in app_inputs { if !(input.is_keyboard() && gui_wants_keyboard) { self.app.tx.send(input).unwrap(); } } } if let Some(gui_inputs) = self.gui.bindings.apply(&winit_ev, modifiers, mouse_pos) { for input in gui_inputs { self.gui.tx.send(input).unwrap(); } } if let Some(main_view_inputs) = self .main_view .bindings .apply(&winit_ev, modifiers, mouse_pos) { for input in main_view_inputs { if (input.is_keyboard() && !gui_wants_keyboard) || (input.is_mouse() && !mouse_over_gui) || input.is_mouse_up() { self.main_view.tx.send(input).unwrap(); } } } if let event::WindowEvent::KeyboardInput { input, .. } = winit_ev { let pressed = input.state == ElementState::Pressed; if pressed && !gui_wants_keyboard { if let Some(command) = input .virtual_keycode .and_then(|kc| self.custom_binds.get(&kc)) { log::warn!("executing bound command!"); let command = command.clone(); if let Ok(handle) = reactor.spawn(async move { command() }) { handle.forget(); } } } } } } pub fn new( winit_rx: channel::Receiver<event::WindowEvent<'static>>, shared_state: &SharedState, ) -> Self { let mouse_screen_pos = shared_state.mouse_pos.clone(); let gui_focus_state = shared_state.gui_focus_state.clone(); let app = SubsystemInput::<AppInput>::from_default_binds(); let main_view = SubsystemInput::<MainViewInput>::from_default_binds(); let gui = SubsystemInput::<GuiInput>::from_default_binds(); Self { mouse_screen_pos, winit_rx, modifiers: AtomicCell::new(Default::default()), app, main_view, gui, gui_focus_state, custom_binds: FxHashMap::default(), } } } fn received_char_to_egui_text(c: char) -> egui::Event { egui::Event::Text(c.into()) } fn winit_to_clipboard_event( modifiers: event::ModifiersState, state: winit::event::ElementState, key_code: winit::event::VirtualKeyCode, ) -> Option<GuiMsg> { let modifiers = egui::Modifiers { alt: modifiers.alt(), ctrl: modifiers.ctrl(), shift: modifiers.shift(), mac_cmd: modifiers.logo(), command: modifiers.logo(), }; let pressed = matches!(state, winit::event::ElementState::Pressed); if (modifiers.ctrl || modifiers.mac_cmd) && pressed { match key_code { VirtualKeyCode::X => Some(GuiMsg::Cut), VirtualKeyCode::C => Some(GuiMsg::Copy), VirtualKeyCode::V => Some(GuiMsg::Paste), _ => None, } } else { None } } fn winit_to_egui_text_event( modifiers: event::ModifiersState, state: winit::event::ElementState, key_code: winit::event::VirtualKeyCode, ) -> Option<egui::Event> { let modifiers = egui::Modifiers { alt: modifiers.alt(), ctrl: modifiers.ctrl(), shift: modifiers.shift(), mac_cmd: modifiers.logo(), command: modifiers.logo(), }; let pressed = matches!(state, winit::event::ElementState::Pressed); let key_event = |key: egui::Key| -> Option<egui::Event> { Some(egui::Event::Key { key, pressed, modifiers, }) }; use egui::Key; let egui_event = match key_code { VirtualKeyCode::Escape => key_event(Key::Escape), VirtualKeyCode::Insert => key_event(Key::Insert), VirtualKeyCode::Home => key_event(Key::Home), VirtualKeyCode::Delete => key_event(Key::Delete), VirtualKeyCode::End => key_event(Key::End), VirtualKeyCode::PageDown => key_event(Key::PageDown), VirtualKeyCode::PageUp => key_event(Key::PageUp), VirtualKeyCode::Left => key_event(Key::ArrowLeft), VirtualKeyCode::Up => key_event(Key::ArrowUp), VirtualKeyCode::Right => key_event(Key::ArrowRight), VirtualKeyCode::Down => key_event(Key::ArrowDown), VirtualKeyCode::Back => key_event(Key::Backspace), VirtualKeyCode::Return => key_event(Key::Enter), VirtualKeyCode::Tab => key_event(Key::Tab), /* VirtualKeyCode::Key1 => key_event(Key::Num1), VirtualKeyCode::Key2 => key_event(Key::Num2), VirtualKeyCode::Key3 => key_event(Key::Num3), VirtualKeyCode::Key4 => key_event(Key::Num4), VirtualKeyCode::Key5 => key_event(Key::Num5), VirtualKeyCode::Key6 => key_event(Key::Num6), VirtualKeyCode::Key7 => key_event(Key::Num7), VirtualKeyCode::Key8 => key_event(Key::Num8), VirtualKeyCode::Key9 => key_event(Key::Num9), VirtualKeyCode::Key0 => key_event(Key::Num0), VirtualKeyCode::A => key_event(Key::A), VirtualKeyCode::B => key_event(Key::B), VirtualKeyCode::D => key_event(Key::D), VirtualKeyCode::E => key_event(Key::E), VirtualKeyCode::F => key_event(Key::F), VirtualKeyCode::G => key_event(Key::G), VirtualKeyCode::H => key_event(Key::H), VirtualKeyCode::I => key_event(Key::I), VirtualKeyCode::J => key_event(Key::J), VirtualKeyCode::K => key_event(Key::K), VirtualKeyCode::L => key_event(Key::L), VirtualKeyCode::M => key_event(Key::M), VirtualKeyCode::N => key_event(Key::N), VirtualKeyCode::O => key_event(Key::O), VirtualKeyCode::P => key_event(Key::P), VirtualKeyCode::Q => key_event(Key::Q), VirtualKeyCode::R => key_event(Key::R), VirtualKeyCode::S => key_event(Key::S), VirtualKeyCode::T => key_event(Key::T), VirtualKeyCode::U => key_event(Key::U), VirtualKeyCode::W => key_event(Key::W), VirtualKeyCode::X => key_event(Key::X), VirtualKeyCode::Y => key_event(Key::Y), VirtualKeyCode::Z => key_event(Key::Z), VirtualKeyCode::Space => key_event(Key::Space), VirtualKeyCode::Numpad0 => key_event(Key::Num0), VirtualKeyCode::Numpad1 => key_event(Key::Num1), VirtualKeyCode::Numpad2 => key_event(Key::Num2), VirtualKeyCode::Numpad3 => key_event(Key::Num3), VirtualKeyCode::Numpad4 => key_event(Key::Num4), VirtualKeyCode::Numpad5 => key_event(Key::Num5), VirtualKeyCode::Numpad6 => key_event(Key::Num6), VirtualKeyCode::Numpad7 => key_event(Key::Num7), VirtualKeyCode::Numpad8 => key_event(Key::Num8), VirtualKeyCode::Numpad9 => key_event(Key::Num9), VirtualKeyCode::NumpadAdd => text_event('+'), VirtualKeyCode::NumpadDivide => text_event('/'), VirtualKeyCode::NumpadDecimal => text_event('.'), VirtualKeyCode::NumpadComma => text_event(','), VirtualKeyCode::NumpadEnter => key_event(Key::Enter), VirtualKeyCode::NumpadEquals => text_event('='), VirtualKeyCode::NumpadMultiply => text_event('*'), VirtualKeyCode::NumpadSubtract => text_event('-'), VirtualKeyCode::Apostrophe => text_event('\''), VirtualKeyCode::Asterisk => text_event('*'), VirtualKeyCode::At => text_event('@'), // VirtualKeyCode::Ax => {} VirtualKeyCode::Backslash => text_event('\\'), VirtualKeyCode::Colon => text_event(':'), VirtualKeyCode::Comma => text_event(','), VirtualKeyCode::Equals => text_event('='), // VirtualKeyCode::Grave => {} VirtualKeyCode::Minus => text_event('-'), VirtualKeyCode::Period => text_event('.'), VirtualKeyCode::Plus => text_event('+'), VirtualKeyCode::Semicolon => text_event(';'), VirtualKeyCode::Slash => text_event('/'), VirtualKeyCode::Underline => text_event('_'), */ _ => None, }; egui_event }
mod slice { use quickcheck::TestResult; use quickcheck_macros::quickcheck; #[quickcheck] #[cfg(feature = "alloc")] fn max(mut v: Vec<(i32, i32)>, n: usize) -> TestResult { if v.len() < n { return TestResult::discard(); } let mut s = v.clone(); s.sort_by(|(a, _), (b, _)| a.cmp(b)); TestResult::from_bool( &mut s[v.len() - n..] == out::slice::max_by(&mut v, n, |(a, _), (b, _)| a.cmp(b)), ) } #[quickcheck] fn max_unstable(mut v: Vec<i32>, n: usize) -> TestResult { if v.len() < n { return TestResult::discard(); } let mut s = v.clone(); s.sort_unstable(); TestResult::from_bool(&mut s[v.len() - n..] == out::slice::max_unstable(&mut v, n)) } #[quickcheck] #[cfg(feature = "alloc")] fn max_by_cached_key(mut v: Vec<(i32, i32)>, n: usize) -> TestResult { if v.len() < n { return TestResult::discard(); } let mut s = v.clone(); s.sort_by_cached_key(|&(a, _)| a); TestResult::from_bool( &mut s[v.len() - n..] == out::slice::max_by_cached_key(&mut v, n, |&(a, _)| a), ) } } mod iter { use quickcheck::TestResult; use quickcheck_macros::quickcheck; #[quickcheck] #[cfg(feature = "alloc")] fn max(v: Vec<(i32, i32)>, n: usize) -> TestResult { if v.len() < n { return TestResult::discard(); } let mut s = v.clone(); s.sort_by(|(a, _), (b, _)| a.cmp(b)); TestResult::from_bool( s[v.len() - n..] == out::iter::max_by(v, n, |(a, _), (b, _)| a.cmp(b))[..], ) } #[quickcheck] #[cfg(feature = "alloc")] fn max_unstable(v: Vec<i32>, n: usize) -> TestResult { if v.len() < n { return TestResult::discard(); } let mut s = v.clone(); s.sort_unstable(); TestResult::from_bool(s[v.len() - n..] == out::iter::max_unstable(v, n)[..]) } }
// Represents shape to be rendered on the board // Cases are rectangle and circle, with measurement parameters attached for those shapes #[derive(Clone)] pub enum Shape { Rectangle { width: f64, height: f64 }, Circle { radius: f64 }, } #[derive(Copy, Clone)] pub struct Circle { pub x: f64, pub y: f64, pub radius: f64, } impl Circle { pub fn collides_with_rectangle(self, rect: Rectangle) -> bool { // http://www.jeffreythompson.org/collision-detection/circle-rect.php let test_x = if self.x < rect.x { rect.x } else if self.x > rect.x + rect.width { rect.x + rect.width } else { self.x }; let test_y = if self.y < rect.y { rect.y } else if self.y > rect.y + rect.height { rect.y + rect.height } else { self.y }; let dist_x = self.x - test_x; let dist_y = self.y - test_y; let distance = ((dist_x * dist_x) + (dist_y * dist_y)).sqrt(); distance <= self.radius } pub fn collides_with_circle(self, circle: Circle) -> bool { // http://www.jeffreythompson.org/collision-detection/circle-circle.php let dist_x = self.x - circle.x; let dist_y = self.y - circle.y; let distance = ((dist_x * dist_x) + (dist_y * dist_y)).sqrt(); distance <= (self.radius + circle.radius) } } #[derive(Copy, Clone)] pub struct Rectangle { pub x: f64, pub y: f64, pub width: f64, pub height: f64, }
use std::mem; use std::ops::{Add, AddAssign, Mul}; use num_traits::{PrimInt, Signed}; #[macro_export] macro_rules! p2 { ($x:expr, $y:expr) => { Point2::new($x, $y) }; } #[derive(Copy, Clone)] pub enum Rotation { Right90, OneEighty, Left90, } #[derive(Debug, Eq, PartialEq, Hash, Default, Copy, Clone)] pub struct Point2<T: PrimInt + AddAssign> { pub x: T, pub y: T, } impl<T: PrimInt + AddAssign> Point2<T> { pub fn new(x: T, y: T) -> Self { Self { x, y } } } impl<T: PrimInt + Signed + AddAssign> Point2<T> { pub fn rotate(&mut self, degrees: Rotation) { match degrees { Rotation::Right90 => { mem::swap(&mut self.x, &mut self.y); self.y = -self.y } Rotation::OneEighty => { self.x = -self.x; self.y = -self.y; } Rotation::Left90 => { mem::swap(&mut self.x, &mut self.y); self.x = -self.x; } } } } impl<T: PrimInt + AddAssign> AddAssign<Point2<T>> for Point2<T> { fn add_assign(&mut self, rhs: Point2<T>) { self.x += rhs.x; self.y += rhs.y; } } impl<T: PrimInt + AddAssign> Mul<T> for Point2<T> { type Output = Point2<T>; fn mul(self, rhs: T) -> Self::Output { Point2::new(self.x * rhs, self.y * rhs) } } impl<T: PrimInt + AddAssign> Add<Point2<T>> for Point2<T> { type Output = Point2<T>; fn add(self, rhs: Point2<T>) -> Self::Output { Point2::new(self.x + rhs.x, self.y + rhs.y) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_macro() { assert_eq!(p2!(10, 20), Point2::new(10, 20)); } }
fn main() { let mut idade = "Eu"; let mut nome = "Tharic"; println!("Hello, {}, você tem {} anos", idade, nome); idade = str(53); nome = "Vilmar"; println!("Hello, {}, você tem {} anos", nome, idade); } let mut idade = "Eu"; let mut idade = "Eu"; let mut idade = "Eu"; let mut idade = "Eu"; let mut idade = "Eu"; let mut idade = "Eu"; let mut idade = "Eu"; let mut idade = "Eu"; let mut idade = "Eu"; let mut idade = "Eu"; let mut idade = "Eu"; let mut idade = "Eu"; let mut idade = "Eu"; let mut idade = "Eu";
pub fn sort(list: &mut Vec<i32>) -> &mut Vec<i32> { if list.len() <= 1 { return list; } let middle = list.len() / 2; let mut beginning: Vec<i32> = list[0..middle]; let mut end: Vec<i32> = list[middle..]; println!("{:?}", beginning); println!("{:?}", end); list }
mod consts; pub mod prelude { pub use super::consts::*; }
// Using a hash map and vectors, create a text interface to allow a user to // add employee names to a department in a company. // For example, “Add Sally to Engineering” or “Add Amir to Sales.” // Then let the user retrieve a list of all people in // a department or all people in the company by department, // sorted alphabetically //Scenario: //TODO: Interface for adding users manually //TODO: Add framework text interface (add, report, quit) //TODO: Create functions, to reduce code //TODO: Remove redundant code //TODO: Handle ids vs names for departments. Unnecessary steps to convert //TODO: Redo if department doesn't exist //read chapter 9 first #![allow(unused_variables)] // #[warn(dead_code)] #[allow(dead_code)] use std::io; use std::collections::HashMap; fn main() { let departments = initialize_departments(); let users = initialize_users(); //let mut departments_users: HashMap<String, u8> = HashMap::new(); let mut departments_users: HashMap<String, &String> = HashMap::new(); println!( "There are {} new users in system, add these to correct department:", users.len() ); println!("",); for u in &users { for d in &departments { println!( "Type {} to add {} to {}", d.dep_id, u.first_name, d.dep_name ); } let mut input_string = String::new(); io::stdin() .read_line(&mut input_string) .expect("Failed to read line"); let added_department: u8 = input_string.trim().parse::<u8>().expect("Wanted a number"); //check that input exists // if !departments.iter().any(|department: &Department| department.dep_id == added_department) { //alternative to below // if !departments.iter().any(|d: &Department| d.dep_id == added_department) { //alternative //alternative to below if !departments.iter().any(|ref d| d.dep_id == added_department) { println!("Non-existing department, user not added. Please add a valid department"); } let department_name: &String = &departments .iter() .find(|d| d.dep_id == added_department) .expect("") .dep_name; departments_users.insert(u.first_name.to_string(), department_name); //departments_users.insert(u.first_name.to_string(), added_department); println!("{} added to {}.", u.first_name, department_name); println!(""); } println!("Type c to print all users in company, sorted alphabetically",); println!("Type d to print all users in department, sorted alphabetically",); println!("Type cd to print all users in company, by department, sorted alphabetically",); let mut print_operation = String::new(); io::stdin() .read_line(&mut print_operation) .expect("Failed to read line"); //print_string(print_operation); let mut print_company: Vec<_> = departments_users.iter().collect(); print_company.sort_by(|a, b| a.cmp(b)); match print_operation.trim().as_ref() { "c" => { println!("All users in company:",); print_company.iter().for_each(|&x| println!("{}", x.0)) } "d" => { println!("Type which department too see users for:"); departments .iter() .for_each(|ref d| println!("Type {} for {}", d.dep_id, d.dep_name)); let mut input_string = String::new(); io::stdin() .read_line(&mut input_string) .expect("Failed to read line"); let department_to_print: u8 = input_string.trim().parse::<u8>().expect("Wanted a number"); if !departments .iter() .any(|ref d| d.dep_id == department_to_print) { println!("Non-existing department, please add a valid department"); } let department_name: &String = &departments .iter() .find(|d| d.dep_id == department_to_print) .expect("") .dep_name; print_company.iter().filter(|&x|x.1 == &department_name).for_each(|&x| println!("{}", x.0)); } "cd" => { println!("All users in company, by department, sorted alphabetically: "); print_company.sort_by(|a, b| a.1.cmp(b.1).then_with(|| a.cmp(b))); print_company .iter() .for_each(|&x| println!("{}, {}", x.0, x.1)) } _ => (println!("LOL")), } } //main #[derive(Debug)] struct Department { dep_id: u8, dep_name: String, } impl PartialEq for Department { fn eq(&self, other: &Department) -> bool { self.dep_id == other.dep_id } } #[derive(Debug)] struct User { first_name: String, last_name: String, e_mail: String, } fn initialize_users() -> Vec<User> { let corp_mail_extension = "@coolcorp.com"; let mut users: Vec<User> = Vec::new(); let user1 = User { first_name: String::from("John"), last_name: String::from("McEnroe"), e_mail: String::from("jm@coolcorp.com"), }; users.push(user1); let user2 = User { first_name: String::from("Ivan"), last_name: String::from("Lendl"), e_mail: String::from("il@coolcorp.com"), }; users.push(user2); users.push(User { first_name: String::from("Andrè"), last_name: String::from("Agassi"), e_mail: String::from("aa@coolcorp.com"), }); users.push(User { first_name: String::from("Boris"), last_name: String::from("Becker"), e_mail: format!("bb{}", corp_mail_extension), }); users } fn initialize_departments() -> Vec<Department> { let mut departments: Vec<Department> = Vec::new(); departments.push(Department { dep_id: 1, dep_name: String::from("Sales"), }); departments.push(Department { dep_id: 2, dep_name: String::from("HR"), }); departments.push(Department { dep_id: 3, dep_name: String::from("Engineering"), }); departments.push(Department { dep_id: 4, dep_name: String::from("IT"), }); departments }
#[doc = "Register `TAMPCR` reader"] pub type R = crate::R<TAMPCR_SPEC>; #[doc = "Register `TAMPCR` writer"] pub type W = crate::W<TAMPCR_SPEC>; #[doc = "Field `TAMP1E` reader - RTC_TAMP1 input detection enable"] pub type TAMP1E_R = crate::BitReader; #[doc = "Field `TAMP1E` writer - RTC_TAMP1 input detection enable"] pub type TAMP1E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP1TRG` reader - Active level for RTC_TAMP1 input If TAMPFLT != 00 if TAMPFLT = 00:"] pub type TAMP1TRG_R = crate::BitReader; #[doc = "Field `TAMP1TRG` writer - Active level for RTC_TAMP1 input If TAMPFLT != 00 if TAMPFLT = 00:"] pub type TAMP1TRG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMPIE` reader - Tamper interrupt enable"] pub type TAMPIE_R = crate::BitReader; #[doc = "Field `TAMPIE` writer - Tamper interrupt enable"] pub type TAMPIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP2E` reader - RTC_TAMP2 input detection enable"] pub type TAMP2E_R = crate::BitReader; #[doc = "Field `TAMP2E` writer - RTC_TAMP2 input detection enable"] pub type TAMP2E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP2TRG` reader - Active level for RTC_TAMP2 input if TAMPFLT != 00: if TAMPFLT = 00:"] pub type TAMP2TRG_R = crate::BitReader; #[doc = "Field `TAMP2TRG` writer - Active level for RTC_TAMP2 input if TAMPFLT != 00: if TAMPFLT = 00:"] pub type TAMP2TRG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP3E` reader - RTC_TAMP3 detection enable"] pub type TAMP3E_R = crate::BitReader; #[doc = "Field `TAMP3E` writer - RTC_TAMP3 detection enable"] pub type TAMP3E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP3TRG` reader - Active level for RTC_TAMP3 input if TAMPFLT != 00: if TAMPFLT = 00:"] pub type TAMP3TRG_R = crate::BitReader; #[doc = "Field `TAMP3TRG` writer - Active level for RTC_TAMP3 input if TAMPFLT != 00: if TAMPFLT = 00:"] pub type TAMP3TRG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMPTS` reader - Activate timestamp on tamper detection event TAMPTS is valid even if TSE=0 in the RTC_CR register."] pub type TAMPTS_R = crate::BitReader; #[doc = "Field `TAMPTS` writer - Activate timestamp on tamper detection event TAMPTS is valid even if TSE=0 in the RTC_CR register."] pub type TAMPTS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMPFREQ` reader - Tamper sampling frequency Determines the frequency at which each of the RTC_TAMPx inputs are sampled."] pub type TAMPFREQ_R = crate::FieldReader; #[doc = "Field `TAMPFREQ` writer - Tamper sampling frequency Determines the frequency at which each of the RTC_TAMPx inputs are sampled."] pub type TAMPFREQ_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; #[doc = "Field `TAMPFLT` reader - RTC_TAMPx filter count These bits determines the number of consecutive samples at the specified level (TAMP*TRG) needed to activate a Tamper event. TAMPFLT is valid for each of the RTC_TAMPx inputs."] pub type TAMPFLT_R = crate::FieldReader; #[doc = "Field `TAMPFLT` writer - RTC_TAMPx filter count These bits determines the number of consecutive samples at the specified level (TAMP*TRG) needed to activate a Tamper event. TAMPFLT is valid for each of the RTC_TAMPx inputs."] pub type TAMPFLT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `TAMPPRCH` reader - RTC_TAMPx precharge duration These bit determines the duration of time during which the pull-up/is activated before each sample. TAMPPRCH is valid for each of the RTC_TAMPx inputs."] pub type TAMPPRCH_R = crate::FieldReader; #[doc = "Field `TAMPPRCH` writer - RTC_TAMPx precharge duration These bit determines the duration of time during which the pull-up/is activated before each sample. TAMPPRCH is valid for each of the RTC_TAMPx inputs."] pub type TAMPPRCH_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `TAMPPUDIS` reader - RTC_TAMPx pull-up disable This bit determines if each of the RTC_TAMPx pins are pre-charged before each sample."] pub type TAMPPUDIS_R = crate::BitReader; #[doc = "Field `TAMPPUDIS` writer - RTC_TAMPx pull-up disable This bit determines if each of the RTC_TAMPx pins are pre-charged before each sample."] pub type TAMPPUDIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP1IE` reader - Tamper 1 interrupt enable"] pub type TAMP1IE_R = crate::BitReader; #[doc = "Field `TAMP1IE` writer - Tamper 1 interrupt enable"] pub type TAMP1IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP1NOERASE` reader - Tamper 1 no erase"] pub type TAMP1NOERASE_R = crate::BitReader; #[doc = "Field `TAMP1NOERASE` writer - Tamper 1 no erase"] pub type TAMP1NOERASE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP1MF` reader - Tamper 1 mask flag"] pub type TAMP1MF_R = crate::BitReader; #[doc = "Field `TAMP1MF` writer - Tamper 1 mask flag"] pub type TAMP1MF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP2IE` reader - Tamper 2 interrupt enable"] pub type TAMP2IE_R = crate::BitReader; #[doc = "Field `TAMP2IE` writer - Tamper 2 interrupt enable"] pub type TAMP2IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP2NOERASE` reader - Tamper 2 no erase"] pub type TAMP2NOERASE_R = crate::BitReader; #[doc = "Field `TAMP2NOERASE` writer - Tamper 2 no erase"] pub type TAMP2NOERASE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP2MF` reader - Tamper 2 mask flag"] pub type TAMP2MF_R = crate::BitReader; #[doc = "Field `TAMP2MF` writer - Tamper 2 mask flag"] pub type TAMP2MF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP3IE` reader - Tamper 3 interrupt enable"] pub type TAMP3IE_R = crate::BitReader; #[doc = "Field `TAMP3IE` writer - Tamper 3 interrupt enable"] pub type TAMP3IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP3NOERASE` reader - Tamper 3 no erase"] pub type TAMP3NOERASE_R = crate::BitReader; #[doc = "Field `TAMP3NOERASE` writer - Tamper 3 no erase"] pub type TAMP3NOERASE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP3MF` reader - Tamper 3 mask flag"] pub type TAMP3MF_R = crate::BitReader; #[doc = "Field `TAMP3MF` writer - Tamper 3 mask flag"] pub type TAMP3MF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - RTC_TAMP1 input detection enable"] #[inline(always)] pub fn tamp1e(&self) -> TAMP1E_R { TAMP1E_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Active level for RTC_TAMP1 input If TAMPFLT != 00 if TAMPFLT = 00:"] #[inline(always)] pub fn tamp1trg(&self) -> TAMP1TRG_R { TAMP1TRG_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Tamper interrupt enable"] #[inline(always)] pub fn tampie(&self) -> TAMPIE_R { TAMPIE_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - RTC_TAMP2 input detection enable"] #[inline(always)] pub fn tamp2e(&self) -> TAMP2E_R { TAMP2E_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - Active level for RTC_TAMP2 input if TAMPFLT != 00: if TAMPFLT = 00:"] #[inline(always)] pub fn tamp2trg(&self) -> TAMP2TRG_R { TAMP2TRG_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - RTC_TAMP3 detection enable"] #[inline(always)] pub fn tamp3e(&self) -> TAMP3E_R { TAMP3E_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - Active level for RTC_TAMP3 input if TAMPFLT != 00: if TAMPFLT = 00:"] #[inline(always)] pub fn tamp3trg(&self) -> TAMP3TRG_R { TAMP3TRG_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - Activate timestamp on tamper detection event TAMPTS is valid even if TSE=0 in the RTC_CR register."] #[inline(always)] pub fn tampts(&self) -> TAMPTS_R { TAMPTS_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bits 8:10 - Tamper sampling frequency Determines the frequency at which each of the RTC_TAMPx inputs are sampled."] #[inline(always)] pub fn tampfreq(&self) -> TAMPFREQ_R { TAMPFREQ_R::new(((self.bits >> 8) & 7) as u8) } #[doc = "Bits 11:12 - RTC_TAMPx filter count These bits determines the number of consecutive samples at the specified level (TAMP*TRG) needed to activate a Tamper event. TAMPFLT is valid for each of the RTC_TAMPx inputs."] #[inline(always)] pub fn tampflt(&self) -> TAMPFLT_R { TAMPFLT_R::new(((self.bits >> 11) & 3) as u8) } #[doc = "Bits 13:14 - RTC_TAMPx precharge duration These bit determines the duration of time during which the pull-up/is activated before each sample. TAMPPRCH is valid for each of the RTC_TAMPx inputs."] #[inline(always)] pub fn tampprch(&self) -> TAMPPRCH_R { TAMPPRCH_R::new(((self.bits >> 13) & 3) as u8) } #[doc = "Bit 15 - RTC_TAMPx pull-up disable This bit determines if each of the RTC_TAMPx pins are pre-charged before each sample."] #[inline(always)] pub fn tamppudis(&self) -> TAMPPUDIS_R { TAMPPUDIS_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bit 16 - Tamper 1 interrupt enable"] #[inline(always)] pub fn tamp1ie(&self) -> TAMP1IE_R { TAMP1IE_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - Tamper 1 no erase"] #[inline(always)] pub fn tamp1noerase(&self) -> TAMP1NOERASE_R { TAMP1NOERASE_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - Tamper 1 mask flag"] #[inline(always)] pub fn tamp1mf(&self) -> TAMP1MF_R { TAMP1MF_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - Tamper 2 interrupt enable"] #[inline(always)] pub fn tamp2ie(&self) -> TAMP2IE_R { TAMP2IE_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - Tamper 2 no erase"] #[inline(always)] pub fn tamp2noerase(&self) -> TAMP2NOERASE_R { TAMP2NOERASE_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - Tamper 2 mask flag"] #[inline(always)] pub fn tamp2mf(&self) -> TAMP2MF_R { TAMP2MF_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - Tamper 3 interrupt enable"] #[inline(always)] pub fn tamp3ie(&self) -> TAMP3IE_R { TAMP3IE_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 23 - Tamper 3 no erase"] #[inline(always)] pub fn tamp3noerase(&self) -> TAMP3NOERASE_R { TAMP3NOERASE_R::new(((self.bits >> 23) & 1) != 0) } #[doc = "Bit 24 - Tamper 3 mask flag"] #[inline(always)] pub fn tamp3mf(&self) -> TAMP3MF_R { TAMP3MF_R::new(((self.bits >> 24) & 1) != 0) } } impl W { #[doc = "Bit 0 - RTC_TAMP1 input detection enable"] #[inline(always)] #[must_use] pub fn tamp1e(&mut self) -> TAMP1E_W<TAMPCR_SPEC, 0> { TAMP1E_W::new(self) } #[doc = "Bit 1 - Active level for RTC_TAMP1 input If TAMPFLT != 00 if TAMPFLT = 00:"] #[inline(always)] #[must_use] pub fn tamp1trg(&mut self) -> TAMP1TRG_W<TAMPCR_SPEC, 1> { TAMP1TRG_W::new(self) } #[doc = "Bit 2 - Tamper interrupt enable"] #[inline(always)] #[must_use] pub fn tampie(&mut self) -> TAMPIE_W<TAMPCR_SPEC, 2> { TAMPIE_W::new(self) } #[doc = "Bit 3 - RTC_TAMP2 input detection enable"] #[inline(always)] #[must_use] pub fn tamp2e(&mut self) -> TAMP2E_W<TAMPCR_SPEC, 3> { TAMP2E_W::new(self) } #[doc = "Bit 4 - Active level for RTC_TAMP2 input if TAMPFLT != 00: if TAMPFLT = 00:"] #[inline(always)] #[must_use] pub fn tamp2trg(&mut self) -> TAMP2TRG_W<TAMPCR_SPEC, 4> { TAMP2TRG_W::new(self) } #[doc = "Bit 5 - RTC_TAMP3 detection enable"] #[inline(always)] #[must_use] pub fn tamp3e(&mut self) -> TAMP3E_W<TAMPCR_SPEC, 5> { TAMP3E_W::new(self) } #[doc = "Bit 6 - Active level for RTC_TAMP3 input if TAMPFLT != 00: if TAMPFLT = 00:"] #[inline(always)] #[must_use] pub fn tamp3trg(&mut self) -> TAMP3TRG_W<TAMPCR_SPEC, 6> { TAMP3TRG_W::new(self) } #[doc = "Bit 7 - Activate timestamp on tamper detection event TAMPTS is valid even if TSE=0 in the RTC_CR register."] #[inline(always)] #[must_use] pub fn tampts(&mut self) -> TAMPTS_W<TAMPCR_SPEC, 7> { TAMPTS_W::new(self) } #[doc = "Bits 8:10 - Tamper sampling frequency Determines the frequency at which each of the RTC_TAMPx inputs are sampled."] #[inline(always)] #[must_use] pub fn tampfreq(&mut self) -> TAMPFREQ_W<TAMPCR_SPEC, 8> { TAMPFREQ_W::new(self) } #[doc = "Bits 11:12 - RTC_TAMPx filter count These bits determines the number of consecutive samples at the specified level (TAMP*TRG) needed to activate a Tamper event. TAMPFLT is valid for each of the RTC_TAMPx inputs."] #[inline(always)] #[must_use] pub fn tampflt(&mut self) -> TAMPFLT_W<TAMPCR_SPEC, 11> { TAMPFLT_W::new(self) } #[doc = "Bits 13:14 - RTC_TAMPx precharge duration These bit determines the duration of time during which the pull-up/is activated before each sample. TAMPPRCH is valid for each of the RTC_TAMPx inputs."] #[inline(always)] #[must_use] pub fn tampprch(&mut self) -> TAMPPRCH_W<TAMPCR_SPEC, 13> { TAMPPRCH_W::new(self) } #[doc = "Bit 15 - RTC_TAMPx pull-up disable This bit determines if each of the RTC_TAMPx pins are pre-charged before each sample."] #[inline(always)] #[must_use] pub fn tamppudis(&mut self) -> TAMPPUDIS_W<TAMPCR_SPEC, 15> { TAMPPUDIS_W::new(self) } #[doc = "Bit 16 - Tamper 1 interrupt enable"] #[inline(always)] #[must_use] pub fn tamp1ie(&mut self) -> TAMP1IE_W<TAMPCR_SPEC, 16> { TAMP1IE_W::new(self) } #[doc = "Bit 17 - Tamper 1 no erase"] #[inline(always)] #[must_use] pub fn tamp1noerase(&mut self) -> TAMP1NOERASE_W<TAMPCR_SPEC, 17> { TAMP1NOERASE_W::new(self) } #[doc = "Bit 18 - Tamper 1 mask flag"] #[inline(always)] #[must_use] pub fn tamp1mf(&mut self) -> TAMP1MF_W<TAMPCR_SPEC, 18> { TAMP1MF_W::new(self) } #[doc = "Bit 19 - Tamper 2 interrupt enable"] #[inline(always)] #[must_use] pub fn tamp2ie(&mut self) -> TAMP2IE_W<TAMPCR_SPEC, 19> { TAMP2IE_W::new(self) } #[doc = "Bit 20 - Tamper 2 no erase"] #[inline(always)] #[must_use] pub fn tamp2noerase(&mut self) -> TAMP2NOERASE_W<TAMPCR_SPEC, 20> { TAMP2NOERASE_W::new(self) } #[doc = "Bit 21 - Tamper 2 mask flag"] #[inline(always)] #[must_use] pub fn tamp2mf(&mut self) -> TAMP2MF_W<TAMPCR_SPEC, 21> { TAMP2MF_W::new(self) } #[doc = "Bit 22 - Tamper 3 interrupt enable"] #[inline(always)] #[must_use] pub fn tamp3ie(&mut self) -> TAMP3IE_W<TAMPCR_SPEC, 22> { TAMP3IE_W::new(self) } #[doc = "Bit 23 - Tamper 3 no erase"] #[inline(always)] #[must_use] pub fn tamp3noerase(&mut self) -> TAMP3NOERASE_W<TAMPCR_SPEC, 23> { TAMP3NOERASE_W::new(self) } #[doc = "Bit 24 - Tamper 3 mask flag"] #[inline(always)] #[must_use] pub fn tamp3mf(&mut self) -> TAMP3MF_W<TAMPCR_SPEC, 24> { TAMP3MF_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 = "RTC tamper and alternate function configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tampcr::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 [`tampcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct TAMPCR_SPEC; impl crate::RegisterSpec for TAMPCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`tampcr::R`](R) reader structure"] impl crate::Readable for TAMPCR_SPEC {} #[doc = "`write(|w| ..)` method takes [`tampcr::W`](W) writer structure"] impl crate::Writable for TAMPCR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets TAMPCR to value 0"] impl crate::Resettable for TAMPCR_SPEC { const RESET_VALUE: Self::Ux = 0; }
// This file is part of Substrate. // Copyright (C) 2020-2021 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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. //! Balances pallet benchmarking. #![cfg(feature = "runtime-benchmarks")] use super::*; use frame_benchmarking::{account, benchmarks, Zero}; use frame_support::traits::{Currency, Get, LockableCurrency, WithdrawReasons}; use frame_system::RawOrigin; use sp_runtime::traits::Saturating; use sp_runtime::traits::StaticLookup; use node_primitives::{credit::CreditInterface, user_privileges::Privilege}; use pallet_user_privileges::Pallet as UserPrivileges; use scale_info::prelude::string::ToString; const SEED: u32 = 0; const USER_SEED: u32 = 999666; // existential deposit multiplier const ED_MULTIPLIER: u32 = 10; const FORCE_LOCK_ID: [u8; 8] = *b"abcdefgh"; benchmarks! { where_clause { where T: Config, T: pallet_balances::Config + pallet_user_privileges::Config+ pallet_evm::Config } force_reserve_by_member { let existential_deposit = <T as pallet::Config>::Currency::minimum_balance(); let unlocker: T::AccountId = account("unlocker", 1, SEED); let unlocker_lookup: <T::Lookup as StaticLookup>::Source = T::Lookup::unlookup(unlocker.clone()); let _ = <T as pallet::Config>::Currency::make_free_balance_be(&unlocker, existential_deposit); let _ = UserPrivileges::<T>::set_user_privilege(RawOrigin::Root.into(),unlocker_lookup,Privilege::LockerMember); let source: T::AccountId = account("locked", 0, SEED); let source_lookup: <T::Lookup as StaticLookup>::Source = T::Lookup::unlookup(source.clone()); // Give some multiple of the existential deposit + creation fee + transfer fee let balance = existential_deposit.saturating_mul(ED_MULTIPLIER.into()); let _ = <T as pallet::Config>::Currency::make_free_balance_be(&source, balance); }: force_reserve_by_member(RawOrigin::Signed(unlocker), source_lookup, balance) verify { assert_eq!(pallet_balances::Account::<T>::get(&source).free, T::Balance::zero()); } force_remove_lock { let existential_deposit = <T as pallet::Config>::Currency::minimum_balance(); let source: T::AccountId = account("locked", 0, SEED); let source_lookup: <T::Lookup as StaticLookup>::Source = T::Lookup::unlookup(source.clone()); // Give some multiple of the existential deposit + creation fee + transfer fee let balance = existential_deposit.saturating_mul(ED_MULTIPLIER.into()); let _ = <T as pallet::Config>::Currency::make_free_balance_be(&source, balance); let _ = <T as pallet::Config>::Currency::set_lock(FORCE_LOCK_ID,&source, existential_deposit,WithdrawReasons::all()); }: force_remove_lock(RawOrigin::Root, FORCE_LOCK_ID,source_lookup) verify { assert_eq!(<T as pallet::Config>::Currency::free_balance(&source), balance); } set_release_limit_parameter { let existential_deposit = <T as pallet::Config>::Currency::minimum_balance(); let single_limit = existential_deposit * 10u32.into(); let daily_limit = existential_deposit * 1000u32.into(); }: set_release_limit_parameter(RawOrigin::Root, single_limit, daily_limit) verify { assert_eq!(SingleMaxLimit::<T>::get(),single_limit); assert_eq!(DailyMaxLimit::<T>::get(),daily_limit); } unstaking_release { let existential_deposit = <T as pallet::Config>::Currency::minimum_balance(); let admin: T::AccountId = account("a", 0, SEED); let admin_lookup: <T::Lookup as StaticLookup>::Source = T::Lookup::unlookup(admin.clone()); let _ = UserPrivileges::<T>::set_user_privilege(RawOrigin::Root.into(),admin_lookup,Privilege::ReleaseSetter); let single_limit = existential_deposit * 10u32.into(); let daily_limit = existential_deposit * 1000u32.into(); <SingleMaxLimit<T>>::put(single_limit); <DailyMaxLimit<T>>::put(daily_limit); let checked_account: T::AccountId = account("a", 100, USER_SEED); T::CreditInterface::add_or_update_credit(checked_account.clone(),99,None); let rinfo= ReleaseInfo::<T>::new(checked_account.clone(),2,0,existential_deposit * 10u32.into()); }: unstaking_release(RawOrigin::Signed(admin), rinfo) verify { assert_eq!(AccountsReleaseInfo::<T>::contains_key(&checked_account),true); } burn_for_ezc { let existential_deposit = T::MinimumBurnedDPR::get(); let user: T::AccountId = account("user", 0, SEED); let _ = <T as pallet::Config>::Currency::make_free_balance_be(&user, existential_deposit*2u32.into()); }: burn_for_ezc(RawOrigin::Signed(user.clone()), existential_deposit*1u32.into(), H160::zero()) verify { assert_eq!(<T as pallet::Config>::Currency::free_balance(&user),existential_deposit); } bridge_deeper_to_other { let user1: T::AccountId = account("b", 1, USER_SEED); let user2: T::AccountId = account("b", 2, USER_SEED); let account_lookup: <T::Lookup as StaticLookup>::Source = T::Lookup::unlookup(user1.clone()); let _ = UserPrivileges::<T>::set_user_privilege(RawOrigin::Root.into(),account_lookup,Privilege::BridgeAdmin); BridgeFundAddreess::<T>::put(user1.clone()); let existential_deposit = <T as pallet::Config>::Currency::minimum_balance(); let _ = <T as pallet::Config>::Currency::make_free_balance_be(&user1, existential_deposit*2u32.into()); let _ = <T as pallet::Config>::Currency::make_free_balance_be(&user2, existential_deposit*2u32.into()); }: bridge_deeper_to_other(RawOrigin::Signed(user1.clone()), H160::zero(),user2,existential_deposit,"test".to_string()) verify { } bridge_other_to_deeper { let user1: T::AccountId = account("b", 1, USER_SEED); let user2: T::AccountId = account("b", 2, USER_SEED); let account_lookup: <T::Lookup as StaticLookup>::Source = T::Lookup::unlookup(user1.clone()); let _ = UserPrivileges::<T>::set_user_privilege(RawOrigin::Root.into(),account_lookup,Privilege::BridgeAdmin); BridgeFundAddreess::<T>::put(user1.clone()); let existential_deposit = <T as pallet::Config>::Currency::minimum_balance(); let _ = <T as pallet::Config>::Currency::make_free_balance_be(&user1, existential_deposit*2u32.into()); let _ = <T as pallet::Config>::Currency::make_free_balance_be(&user2, existential_deposit*2u32.into()); }: bridge_other_to_deeper(RawOrigin::Signed(user1.clone()), user2,H160::zero(),existential_deposit,"test".to_string()) verify { } impl_benchmark_test_suite!(Operation, crate::tests::new_test_ext(), crate::tests::Test); }
use std::slice; fn read_nodes(l:&mut slice::Iter<usize>) -> usize{ let header = l.take(2).collect::<Vec<&usize>>(); let n_node = *header[0]; let n_metadata = *header[1]; let mut checksum = 0; for _ in 0..n_node { checksum += read_nodes(l); } checksum + l.take(n_metadata).sum::<usize>() } fn main() { use std::io::{self, BufRead}; let stdin = io::stdin(); let line = stdin.lock().lines().next().unwrap().unwrap().split(" ") .map(|s| s.parse::<usize>().unwrap()).collect::<Vec<usize>>(); println!("{}", read_nodes(&mut line.iter())); }
pub fn get_instructions()->String{ let data:&str = "rect 1x1 rotate row y=0 by 5 rect 1x1 rotate row y=0 by 6 rect 1x1 rotate row y=0 by 5 rect 1x1 rotate row y=0 by 2 rect 1x1 rotate row y=0 by 5 rect 2x1 rotate row y=0 by 2 rect 1x1 rotate row y=0 by 4 rect 1x1 rotate row y=0 by 3 rect 2x1 rotate row y=0 by 7 rect 3x1 rotate row y=0 by 3 rect 1x1 rotate row y=0 by 3 rect 1x2 rotate row y=1 by 13 rotate column x=0 by 1 rect 2x1 rotate row y=0 by 5 rotate column x=0 by 1 rect 3x1 rotate row y=0 by 18 rotate column x=13 by 1 rotate column x=7 by 2 rotate column x=2 by 3 rotate column x=0 by 1 rect 17x1 rotate row y=3 by 13 rotate row y=1 by 37 rotate row y=0 by 11 rotate column x=7 by 1 rotate column x=6 by 1 rotate column x=4 by 1 rotate column x=0 by 1 rect 10x1 rotate row y=2 by 37 rotate column x=19 by 2 rotate column x=9 by 2 rotate row y=3 by 5 rotate row y=2 by 1 rotate row y=1 by 4 rotate row y=0 by 4 rect 1x4 rotate column x=25 by 3 rotate row y=3 by 5 rotate row y=2 by 2 rotate row y=1 by 1 rotate row y=0 by 1 rect 1x5 rotate row y=2 by 10 rotate column x=39 by 1 rotate column x=35 by 1 rotate column x=29 by 1 rotate column x=19 by 1 rotate column x=7 by 2 rotate row y=4 by 22 rotate row y=3 by 5 rotate row y=1 by 21 rotate row y=0 by 10 rotate column x=2 by 2 rotate column x=0 by 2 rect 4x2 rotate column x=46 by 2 rotate column x=44 by 2 rotate column x=42 by 1 rotate column x=41 by 1 rotate column x=40 by 2 rotate column x=38 by 2 rotate column x=37 by 3 rotate column x=35 by 1 rotate column x=33 by 2 rotate column x=32 by 1 rotate column x=31 by 2 rotate column x=30 by 1 rotate column x=28 by 1 rotate column x=27 by 3 rotate column x=26 by 1 rotate column x=23 by 2 rotate column x=22 by 1 rotate column x=21 by 1 rotate column x=20 by 1 rotate column x=19 by 1 rotate column x=18 by 2 rotate column x=16 by 2 rotate column x=15 by 1 rotate column x=13 by 1 rotate column x=12 by 1 rotate column x=11 by 1 rotate column x=10 by 1 rotate column x=7 by 1 rotate column x=6 by 1 rotate column x=5 by 1 rotate column x=3 by 2 rotate column x=2 by 1 rotate column x=1 by 1 rotate column x=0 by 1 rect 49x1 rotate row y=2 by 34 rotate column x=44 by 1 rotate column x=40 by 2 rotate column x=39 by 1 rotate column x=35 by 4 rotate column x=34 by 1 rotate column x=30 by 4 rotate column x=29 by 1 rotate column x=24 by 1 rotate column x=15 by 4 rotate column x=14 by 1 rotate column x=13 by 3 rotate column x=10 by 4 rotate column x=9 by 1 rotate column x=5 by 4 rotate column x=4 by 3 rotate row y=5 by 20 rotate row y=4 by 20 rotate row y=3 by 48 rotate row y=2 by 20 rotate row y=1 by 41 rotate column x=47 by 5 rotate column x=46 by 5 rotate column x=45 by 4 rotate column x=43 by 5 rotate column x=41 by 5 rotate column x=33 by 1 rotate column x=32 by 3 rotate column x=23 by 5 rotate column x=22 by 1 rotate column x=21 by 2 rotate column x=18 by 2 rotate column x=17 by 3 rotate column x=16 by 2 rotate column x=13 by 5 rotate column x=12 by 5 rotate column x=11 by 5 rotate column x=3 by 5 rotate column x=2 by 5 rotate column x=1 by 5"; return String::from(data); }
use crate::{Artifact, ArtifactStore, Scope}; use std::fmt::{Display, Formatter, Result as FmtResult}; pub struct NodeDisplay<T>(pub T); impl<F> Display for NodeDisplay<(&Scope, &F)> where F: Fn(&str) -> bool, { fn fmt(&self, fmt: &mut Formatter) -> FmtResult { let (scope, matcher) = self.0; scope.fmt_tree(0, matcher, fmt) } } impl<F> Display for NodeDisplay<(usize, &Scope, &F)> where F: Fn(&str) -> bool, { fn fmt(&self, fmt: &mut Formatter) -> FmtResult { let (ident, scope, matcher) = self.0; scope.fmt_tree(ident, matcher, fmt) } } impl<F> Display for NodeDisplay<(&ArtifactStore, &F)> where F: Fn(&str) -> bool, { fn fmt(&self, fmt: &mut Formatter) -> FmtResult { let (store, matcher) = self.0; store.fmt_dot(matcher, fmt) } } impl<U, K> Display for NodeDisplay<(usize, &Artifact<U, K>)> { fn fmt(&self, fmt: &mut Formatter) -> FmtResult { let (ident, artifact) = self.0; artifact.fmt_tree(ident, fmt) } }
use super::KeyState; use super::sprite::RustConsoleSprite; use std::io::{Error, ErrorKind}; use std::mem::{swap, size_of, MaybeUninit}; use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; use std::iter::once; use libc::memset; mod bindings { windows::include_bindings!(); } use bindings::{ Windows::Win32::{ System::{ SystemServices::{ HANDLE, TRUE, FALSE }, WindowsProgramming::{ GetStdHandle, STD_OUTPUT_HANDLE, STD_INPUT_HANDLE }, Console::{ SetConsoleWindowInfo, SetCurrentConsoleFontEx, SetConsoleScreenBufferSize, SetConsoleActiveScreenBuffer, GetConsoleScreenBufferInfoEx, SetConsoleScreenBufferInfoEx, SetConsoleMode, GetConsoleWindow, SetConsoleTitleW, WriteConsoleOutputW, FlushConsoleInputBuffer, GetNumberOfConsoleInputEvents, ReadConsoleInputW, SMALL_RECT, CONSOLE_FONT_INFOEX, COORD, CONSOLE_SCREEN_BUFFER_INFOEX, CONSOLE_MODE, ENABLE_EXTENDED_FLAGS, CHAR_INFO, INPUT_RECORD, WINDOW_BUFFER_SIZE_EVENT } }, UI::{ WindowsAndMessaging::{ GetWindowLongW, SetWindowLongW, GetSystemMenu, SetLayeredWindowAttributes, GWL_STYLE, WS_MAXIMIZEBOX, WS_SIZEBOX, LWA_ALPHA, VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT }, KeyboardAndMouseInput::GetAsyncKeyState }, Graphics::Gdi::{ FF_DONTCARE, /*FF_MODERN, TMPF_TRUETYPE, TMPF_VECTOR,*/ FW_NORMAL } } }; pub struct RustConsole { width: usize, height: usize, font_width: i16, font_height: i16, h_console: HANDLE, h_console_input: HANDLE, rect_window: SMALL_RECT, screen: Vec<CHAR_INFO>, keys: [KeyState; 256], old_key_states: [i16; 256], new_key_states: [i16; 256] } impl RustConsole { pub const FG_BLACK: u16 = 0x0000; pub const FG_DARK_BLUE: u16 = 0x0001; pub const FG_DARK_GREEN: u16 = 0x0002; pub const FG_DARK_CYAN: u16 = 0x0003; pub const FG_DARK_RED: u16 = 0x0004; pub const FG_DARK_MAGENTA: u16 = 0x0005; pub const FG_DARK_YELLOW: u16 = 0x0006; pub const FG_GREY: u16 = 0x0007; pub const FG_DARK_GREY: u16 = 0x0008; pub const FG_BLUE: u16 = 0x0009; pub const FG_GREEN: u16 = 0x000a; pub const FG_CYAN: u16 = 0x000b; pub const FG_RED: u16 = 0x000c; pub const FG_MAGENTA: u16 = 0x000d; pub const FG_YELLOW: u16 = 0x000e; pub const FG_WHITE: u16 = 0x000f; pub const BG_BLACK: u16 = 0x0000; pub const BG_DARK_BLUE: u16 = 0x0010; pub const BG_DARK_GREEN: u16 = 0x0020; pub const BG_DARK_CYAN: u16 = 0x0030; pub const BG_DARK_RED: u16 = 0x0040; pub const BG_DARK_MAGENTA: u16 = 0x0050; pub const BG_DARK_YELLOW: u16 = 0x0060; pub const BG_GREY: u16 = 0x0070; pub const BG_DARK_GREY: u16 = 0x0080; pub const BG_BLUE: u16 = 0x0090; pub const BG_GREEN: u16 = 0x00a0; pub const BG_CYAN: u16 = 0x00b0; pub const BG_RED: u16 = 0x00c0; pub const BG_MAGENTA: u16 = 0x00d0; pub const BG_YELLOW: u16 = 0x00e0; pub const BG_WHITE: u16 = 0x00f0; pub const PIXEL_SOLID: char = '\u{2588}'; pub const PIXEL_THREEQUARTER: char = '\u{2593}'; pub const PIXEL_HALF: char = '\u{2592}'; pub const PIXEL_QUARTER: char = '\u{2591}'; pub const VK_UP: u32 = VK_UP; pub const VK_DOWN: u32 = VK_DOWN; pub const VK_LEFT: u32 = VK_LEFT; pub const VK_RIGHT: u32 = VK_RIGHT; pub(crate) fn new(width: usize, height: usize, font_width: i16, font_height: i16) -> Result<RustConsole, Error> { let h_console = unsafe { GetStdHandle(STD_OUTPUT_HANDLE) }; if h_console.is_invalid() { return Err(Error::last_os_error()); } if h_console.is_null() { return Err(Error::new(ErrorKind::Other, "NULL console handle")); } let h_console_input = unsafe { GetStdHandle(STD_INPUT_HANDLE) }; if h_console_input.is_invalid() { return Err(Error::last_os_error()); } if h_console_input.is_null() { return Err(Error::new(ErrorKind::Other, "NULL console input handle")); } let mut rect_window = SMALL_RECT { Left: 0, Top: 0, Right: 1, Bottom: 1 }; let mut ret = unsafe { SetConsoleWindowInfo(h_console, TRUE, &rect_window) }; if !ret.as_bool() { return Err(Error::last_os_error()); } let mut face_name: [u16; 32] = Default::default(); let v = OsStr::new("Consolas").encode_wide().chain(once(0)).collect::<Vec<u16>>(); face_name[..v.len()].clone_from_slice(&v[..]); let mut cfix = CONSOLE_FONT_INFOEX { cbSize: size_of::<CONSOLE_FONT_INFOEX>() as u32, nFont: 0, dwFontSize: COORD { X: font_width, Y: font_height }, FontFamily: FF_DONTCARE.0, // FF_MODERN.0 | TMPF_VECTOR | TMPF_TRUETYPE FontWeight: FW_NORMAL, FaceName: face_name }; ret = unsafe { SetCurrentConsoleFontEx(h_console, FALSE, &mut cfix) }; if !ret.as_bool() { return Err(Error::last_os_error()); } let coord = COORD { X: width as i16, Y: height as i16 }; ret = unsafe { SetConsoleScreenBufferSize(h_console, coord) }; if !ret.as_bool() { return Err(Error::last_os_error()); } ret = unsafe { SetConsoleActiveScreenBuffer(h_console) }; if !ret.as_bool() { return Err(Error::last_os_error()); } let mut csbix = unsafe { MaybeUninit::<CONSOLE_SCREEN_BUFFER_INFOEX>::zeroed().assume_init() }; csbix.cbSize = size_of::<CONSOLE_SCREEN_BUFFER_INFOEX>() as u32; ret = unsafe { GetConsoleScreenBufferInfoEx(h_console, &mut csbix) }; if !ret.as_bool() { return Err(Error::last_os_error()); } if width as i16 > csbix.dwMaximumWindowSize.X { return Err(Error::new(ErrorKind::Other, "Width / font width too big")); } if height as i16 > csbix.dwMaximumWindowSize.Y { return Err(Error::new(ErrorKind::Other, "Height / font height too big")); } csbix.bFullscreenSupported = FALSE; ret = unsafe { SetConsoleScreenBufferInfoEx(h_console, &mut csbix) }; if !ret.as_bool() { return Err(Error::last_os_error()); } rect_window = SMALL_RECT { Left: 0, Top: 0, Right: width as i16 - 1, Bottom: height as i16 - 1 }; ret = unsafe { SetConsoleWindowInfo(h_console, TRUE, &rect_window) }; if !ret.as_bool() { return Err(Error::last_os_error()); } ret = unsafe { SetConsoleMode(h_console_input, CONSOLE_MODE::from(ENABLE_EXTENDED_FLAGS)) }; if !ret.as_bool() { return Err(Error::last_os_error()); } let h_window = unsafe { GetConsoleWindow() }; let ret = unsafe { GetWindowLongW(h_window, GWL_STYLE) }; if ret == 0 { return Err(Error::last_os_error()); } let ret = unsafe { SetWindowLongW(h_window, GWL_STYLE, ret & !WS_MAXIMIZEBOX.0 as i32 & !WS_SIZEBOX.0 as i32) }; if ret == 0 { return Err(Error::last_os_error()); } unsafe { GetSystemMenu(h_window, TRUE) }; let ret = unsafe { SetLayeredWindowAttributes(h_window, 0, 255, LWA_ALPHA) }; if !ret.as_bool() { return Err(Error::last_os_error()); } Ok(RustConsole { width, height, font_width, font_height, h_console, h_console_input, rect_window, screen: vec![unsafe { MaybeUninit::<CHAR_INFO>::zeroed().assume_init() }; width * height], keys: [KeyState { pressed: false, released: false, held: false }; 256], old_key_states: unsafe { MaybeUninit::<[i16; 256]>::zeroed().assume_init() }, new_key_states: unsafe { MaybeUninit::<[i16; 256]>::zeroed().assume_init() } }) } pub(crate) fn write_output(&mut self) { let ret = unsafe { WriteConsoleOutputW(self.h_console, self.screen.as_ptr(), COORD { X: self.width as i16, Y: self.height as i16 }, COORD { X: 0, Y: 0 }, &mut self.rect_window) }; if !ret.as_bool() { panic!("Error writing console output: {:?}", Error::last_os_error()); } } pub(crate) fn update_key_states(&mut self) { for v_key in 0..256 { self.new_key_states[v_key] = unsafe { GetAsyncKeyState(v_key as i32) }; self.keys[v_key].pressed = false; self.keys[v_key].released = false; if self.new_key_states[v_key] != self.old_key_states[v_key] { if self.new_key_states[v_key] as u16 & 0x8000 != 0 { self.keys[v_key].pressed = !self.keys[v_key].held; self.keys[v_key].held = true; } else { self.keys[v_key].released = true; self.keys[v_key].held = false; } } self.old_key_states[v_key] = self.new_key_states[v_key]; } } pub(crate) fn flush_input_events(&self) { let ret = unsafe { FlushConsoleInputBuffer(self.h_console_input) }; if !ret.as_bool() { panic!("Error flushing console input: {:?}", Error::last_os_error()); } } pub(crate) fn handle_input_events(&mut self) { let mut events = 0; let mut buffer = [unsafe { MaybeUninit::<INPUT_RECORD>::zeroed().assume_init() }; 32]; let mut ret = unsafe { GetNumberOfConsoleInputEvents(self.h_console_input, &mut events) }; if !ret.as_bool() { panic!("Error getting number of console input events: {:?}", Error::last_os_error()); } if events > 0 { ret = unsafe { ReadConsoleInputW(self.h_console_input, buffer.as_mut_ptr(), events, &mut events) }; if !ret.as_bool() { panic!("Error reading console input: {:?}", Error::last_os_error()); } } for i in (0..events).rev() { match buffer[i as usize].EventType as u32 { WINDOW_BUFFER_SIZE_EVENT => { /*let wbsr = unsafe { buffer[i as usize].Event.WindowBufferSizeEvent }; self.width = wbsr.dwSize.X as usize; self.height = wbsr.dwSize.Y as usize; self.screen = vec![unsafe { MaybeUninit::<CHAR_INFO>::zeroed().assume_init() }; self.width * self.height];*/ }, _ => {} } } } pub fn width(&self) -> usize { self.width } pub fn height(&self) -> usize { self.height } pub fn font_width(&self) -> i16 { self.font_width } pub fn font_height(&self) -> i16 { self.font_height } pub fn key(&self, v_key: usize) -> KeyState { self.keys[v_key] } pub fn set_title(&self, title: String) { let ret = unsafe { SetConsoleTitleW(title) }; if !ret.as_bool() { panic!("Error setting window title: {:?}", Error::last_os_error()); } } pub fn resize(&mut self, new_width: usize, new_height: usize, new_font_width: i16, new_font_height: i16) { let mut rect_window = SMALL_RECT { Left: 0, Top: 0, Right: 1, Bottom: 1 }; let mut ret = unsafe { SetConsoleWindowInfo(self.h_console, TRUE, &rect_window) }; if !ret.as_bool() { panic!("Error resizing console window: {:?}", Error::last_os_error()); } let mut face_name: [u16; 32] = Default::default(); let v = OsStr::new("Consolas").encode_wide().chain(once(0)).collect::<Vec<u16>>(); face_name[..v.len()].clone_from_slice(&v[..]); let mut cfix = CONSOLE_FONT_INFOEX { cbSize: size_of::<CONSOLE_FONT_INFOEX>() as u32, nFont: 0, dwFontSize: COORD { X: new_font_width, Y: new_font_height }, FontFamily: FF_DONTCARE.0, // FF_MODERN.0 | TMPF_VECTOR | TMPF_TRUETYPE FontWeight: FW_NORMAL as u32, FaceName: face_name }; ret = unsafe { SetCurrentConsoleFontEx(self.h_console, FALSE, &mut cfix) }; if !ret.as_bool() { panic!("Error resizing console font: {:?}", Error::last_os_error()); } let coord = COORD { X: new_width as i16, Y: new_height as i16 }; ret = unsafe { SetConsoleScreenBufferSize(self.h_console, coord) }; if !ret.as_bool() { panic!("Error resizing console buffer: {:?}", Error::last_os_error()); } let mut csbix = unsafe { MaybeUninit::<CONSOLE_SCREEN_BUFFER_INFOEX>::zeroed().assume_init() }; csbix.cbSize = size_of::<CONSOLE_SCREEN_BUFFER_INFOEX>() as u32; ret = unsafe { GetConsoleScreenBufferInfoEx(self.h_console, &mut csbix) }; if !ret.as_bool() { panic!("Error getting console extended info: {:?}", Error::last_os_error()); } if new_width as i16 > csbix.dwMaximumWindowSize.X { panic!("Error resizing console: {:?}", Error::new(ErrorKind::Other, "Width / font width too big")); } if new_height as i16 > csbix.dwMaximumWindowSize.Y { panic!("Error resizing console: {:?}", Error::new(ErrorKind::Other, "Height / font height too big")); } rect_window = SMALL_RECT { Left: 0, Top: 0, Right: new_width as i16 - 1, Bottom: new_height as i16 - 1 }; ret = unsafe { SetConsoleWindowInfo(self.h_console, TRUE, &rect_window) }; if !ret.as_bool() { panic!("Error resizing console window: {:?}", Error::last_os_error()); } self.flush_input_events(); self.width = new_width; self.height = new_height; self.font_width = new_font_width; self.font_height = new_font_height; self.rect_window = rect_window; self.screen = vec![unsafe { MaybeUninit::<CHAR_INFO>::zeroed().assume_init() }; new_width * new_height]; } pub fn clear(&mut self) { unsafe { memset(self.screen.as_mut_ptr() as _, 0, self.screen.len() * size_of::<CHAR_INFO>()); } } pub fn draw(&mut self, x: usize, y: usize, c: char, col: u16) { if x < self.width && y < self.height { self.screen[y * self.width + x].Char.UnicodeChar = c as u16; self.screen[y * self.width + x].Attributes = col; } } pub fn fill(&mut self, x1: usize, y1: usize, x2: usize, y2: usize, c: char, col: u16) { for x in x1..x2 { for y in y1..y2 { self.draw(x, y, c, col); } } } pub fn draw_string(&mut self, x: usize, y: usize, s: &str, col: u16) { for (i, c) in s.chars().enumerate() { self.screen[y * self.width + x + i].Char.UnicodeChar = c as u16; self.screen[y * self.width + x + i].Attributes = col; } } pub fn draw_string_alpha(&mut self, x: usize, y: usize, s: &str, col: u16) { for (i, c) in s.chars().enumerate() { if c != ' ' { self.screen[y * self.width + x + i].Char.UnicodeChar = c as u16; self.screen[y * self.width + x + i].Attributes = col; } } } pub fn draw_line(&mut self, x1: usize, y1: usize, x2: usize, y2: usize, c: char, col: u16) { let dx = x2 as isize - x1 as isize; let dy = y2 as isize - y1 as isize; let dx1 = dx.abs(); let dy1 = dy.abs(); let mut px = 2 * dy1 - dx1; let mut py = 2 * dx1 - dy1; if dy1 <= dx1 { let (mut x, mut y, xe) = if dx >= 0 { (x1, y1, x2) } else { (x2, y2, x1) }; self.draw(x, y, c, col); for _i in x..xe { x += 1; if px < 0 { px = px + 2 * dy1; } else { if (dx < 0 && dy < 0) || (dx > 0 && dy > 0) { y += 1; } else { y -= 1; } px = px + 2 * (dy1 - dx1); } self.draw(x, y, c, col); } } else { let (mut x, mut y, ye) = if dy >= 0 { (x1, y1, y2) } else { (x2, y2, y1) }; self.draw(x, y, c, col); for _i in y..ye { y += 1; if py <= 0 { py = py + 2 * dx1; } else { if (dx < 0 && dy < 0) || (dx > 0 && dy > 0) { x += 1; } else { x -= 1; } py = py + 2 * (dx1 - dy1); } self.draw(x, y, c, col); } } } pub fn draw_triangle(&mut self, x1: usize, y1: usize, x2: usize, y2: usize, x3: usize, y3: usize, c: char, col: u16) { self.draw_line(x1, y1, x2, y2, c, col); self.draw_line(x2, y2, x3, y3, c, col); self.draw_line(x3, y3, x1, y1, c, col); } pub fn fill_triangle(&mut self, mut x1: usize, mut y1: usize, mut x2: usize, mut y2: usize, mut x3: usize, mut y3: usize, c: char, col: u16) { let mut changed1 = false; let mut changed2 = false; // sort vertices if y1 > y2 { swap(&mut y1, &mut y2); swap(&mut x1, &mut x2); } if y1 > y3 { swap(&mut y1, &mut y3); swap(&mut x1, &mut x3); } if y2 > y3 { swap(&mut y2, &mut y3); swap(&mut x2, &mut x3); } // starting points let mut t1x = x1 as isize; let mut t2x = x1 as isize; let mut y = y1; let mut dx1 = x2 as isize - x1 as isize; let signx1 = if dx1 < 0 { dx1 = -dx1; -1 } else { 1 }; let mut dy1 = y2 as isize - y1 as isize; let mut dx2 = x3 as isize - x1 as isize; let signx2 = if dx2 < 0 { dx2 = -dx2; -1 } else { 1 }; let mut dy2 = y3 as isize - y1 as isize; if dy1 > dx1 { swap(&mut dx1, & mut dy1); changed1 = true; } if dy2 > dx2 { swap(&mut dy2, &mut dx2); changed2 = true; } let mut e2 = dx2 >> 1; if y1 != y2 { // not flat top, so do the first half let mut e1 = dx1 >> 1; for mut i in 0..dx1 { let mut t1xp = 0; let mut t2xp = 0; let (mut minx, mut maxx) = if t1x < t2x { (t1x, t2x) } else { (t2x, t1x) }; // process first line until y value is about to change 'first_line_1: while i < dx1 { i += 1; e1 += dy1; while e1 >= dx1 { e1 -= dx1; if changed1 { t1xp = signx1; } else { break 'first_line_1; } } if changed1 { break 'first_line_1; } else { t1x += signx1; } } // process second line until y value is about to change 'second_line_1: loop { e2 += dy2; while e2 >= dx2 { e2 -= dx2; if changed2 { t2xp = signx2; } else { break 'second_line_1; } } if changed2 { break 'second_line_1; } else { t2x += signx2; } } if minx > t1x { minx = t1x; } if minx > t2x { minx = t2x; } if maxx < t1x { maxx = t1x; } if maxx < t2x { maxx = t2x; } // draw line from min to max points found on the y for j in minx..=maxx { self.draw(j as usize, y, c, col); } // now increase y if !changed1 { t1x += signx1; } t1x += t1xp; if !changed2 { t2x += signx2; } t2x += t2xp; y += 1; if y == y2 { break; } } } // now, do the second half dx1 = x3 as isize - x2 as isize; let signx1 = if dx1 < 0 { dx1 = -dx1; -1 } else { 1 }; dy1 = y3 as isize - y2 as isize; t1x = x2 as isize; if dy1 > dx1 { swap(&mut dy1, &mut dx1); changed1 = true; } else { changed1 = false; } let mut e1 = dx1 >> 1; for mut i in 0..=dx1 { let mut t1xp = 0; let mut t2xp = 0; let (mut minx, mut maxx) = if t1x < t2x { (t1x, t2x) } else { (t2x, t1x) }; // process first line until y value is about to change 'first_line_2: while i < dx1 { e1 += dy1; while e1 >= dx1 { e1 -= dx1; if changed1 { t1xp = signx1; break; } else { break 'first_line_2; } } if changed1 { break 'first_line_2; } else { t1x += signx1; } if i < dx1 { i += 1; } } // process second line until y value is about to change 'second_line_2: while t2x != x3 as isize { e2 += dy2; while e2 >= dx2 { e2 -= dx2; if changed2 { t2xp = signx2; } else { break 'second_line_2; } } if changed2 { break 'second_line_2; } else { t2x += signx2; } } if minx > t1x { minx = t1x; } if minx > t2x { minx = t2x; } if maxx < t1x { maxx = t1x; } if maxx < t2x { maxx = t2x; } // draw line from min to max points found on the y for j in minx..=maxx { self.draw(j as usize, y, c, col); } // now increase y if !changed1 { t1x += signx1; } t1x += t1xp; if !changed2 { t2x += signx2; } t2x += t2xp; y += 1; if y > y3 { return; } } } pub fn draw_circle(&mut self, xc: usize, yc: usize, r: usize, c: char, col: u16) { let mut x = 0; let mut y = r; let mut p = 3 - 2 * r as isize; if r == 0 { return; } while y >= x { self.draw(xc - x, yc - y, c, col); // upper left left self.draw(xc - y, yc - x, c, col); // upper upper left self.draw(xc + y, yc - x, c, col); // upper upper right self.draw(xc + x, yc - y, c, col); // upper right right self.draw(xc - x, yc + y, c, col); // lower left left self.draw(xc - y, yc + x, c, col); // lower lower left self.draw(xc + y, yc + x, c, col); // lower lower right self.draw(xc + x, yc + y, c, col); // lower right right if p < 0 { p += 4 * x as isize + 6; x += 1; } else { p += 4 * (x as isize - y as isize) + 10; x += 1; y -= 1; } } } pub fn fill_circle(&mut self, xc: usize, yc: usize, r: usize, c: char, col: u16) { let mut x = 0; let mut y = r; let mut p = 3 - 2 * r as isize; if r == 0 { return; } while y >= x { for i in xc - x..=xc + x { self.draw(i, yc - y, c, col); } for i in xc - y..=xc + y { self.draw(i, yc - x, c, col); } for i in xc - x..=xc + x { self.draw(i, yc + y, c, col); } for i in xc - y..=xc + y { self.draw(i, yc + x, c, col); } if p < 0 { p += 4 * x as isize + 6; x += 1; } else { p += 4 * (x as isize - y as isize) + 10; x += 1; y -= 1; } } } pub fn draw_sprite(&mut self, x: usize, y: usize, sprite: &RustConsoleSprite) { for i in 0..sprite.width() { for j in 0..sprite.height() { if sprite.get_glyph(i, j) != ' ' { self.draw(x + i, y + j, sprite.get_glyph(i, j), sprite.get_color(i, j)); } } } } }
use std::sync::Arc; use futures::future; use futures::sink::SinkExt; use tokio::net::UnixStream; use tokio_util::codec::{Framed, LinesCodec}; use persist_core::error::Error; use persist_core::protocol::{Response, StopRequest, StopResponse}; use crate::server::State; pub async fn handle( state: Arc<State>, conn: &mut Framed<UnixStream, LinesCodec>, request: StopRequest, ) -> Result<(), Error> { let names = match request.filters { Some(names) => names, None => { state .with_handles(|handles| handles.keys().cloned().collect()) .await } }; let futures = names.into_iter().map(|name| async { let res = state.stop(name.as_str()).await; let error = res.err().map(|err| err.to_string()); StopResponse { name, error } }); let responses = future::join_all(futures).await; let response = Response::Stop(responses); let serialized = json::to_string(&response)?; conn.send(serialized).await?; Ok(()) }
use anyhow::Result; pub fn part1(input_string: &str) -> Result<String> { Ok(get_fuel_requirement(input_string, |mass| mass / 3 - 2)) } pub fn part2(input_string: &str) -> Result<String> { fn mass_to_fuel(mass: u64) -> u64 { match (mass / 3).checked_sub(2) { Some(fuel) => fuel + mass_to_fuel(fuel), None => 0, } } Ok(get_fuel_requirement(input_string, mass_to_fuel)) } fn get_fuel_requirement(input_string: &str, mass_to_fuel: fn(u64) -> u64) -> String { input_string .lines() .map(|line| line.parse::<u64>().unwrap()) .map(mass_to_fuel) .sum::<u64>() .to_string() }
pub fn build_proverb(list: &[&str]) -> String { let mut result = String::new(); let length = if list.len() != 0 { list.len() - 1 } else { 0 }; for idx in 0..length { result.push_str( format!( "For want of a {} the {} was lost.\n", list[idx], list[idx + 1] ) .as_str(), ); } if list.len() >= 1 { result.push_str(format!("And all for the want of a {}.", list[0]).as_str()); } result }
pub fn spawn_http_server() { let port = std::env::var("PORT").unwrap_or_else(|_| "8080".to_string()); let address = "0.0.0.0"; tokio::spawn(async move { let server = simple_server::Server::new(|_request, mut response| { Ok(response.body(b"Hello Rust!".to_vec()).unwrap()) }); server.listen(address, &port); }); }
//! //! This module gives a handler for the keyboard interruption. //! pub extern "C" fn keyboard_handler() -> ! { panic!("Keyboard !"); }
pub mod comparisons; pub mod docs; pub mod index;
use regex::Regex; use serde_json::{Result, Value}; use std::cmp::{max, min}; use std::collections::HashSet; use std::io::{self}; fn count_numbers(line: &str) -> i64 { let re = Regex::new(r"([-]?\d+)").unwrap(); re.find_iter(&line) .map(|c| c.as_str().parse::<i64>().unwrap()) .fold(0, |acc, val| acc + val) } fn counter(vals: &Value, skip_red: bool) -> i64 { match vals { Value::Object(map) => { if !skip_red { for (k, v) in map { if v == &Value::String("red".to_string()) { return 0; } } } let mut sum = 0; for (k, v) in map { sum += counter(v, skip_red); } return sum; } Value::Array(array) => { return array .iter() .map(|v| counter(v, skip_red)) .fold(0, |acc, val| acc + val); } Value::Number(n) => { return n.as_i64().unwrap(); } _ => { return 0; } } } fn main() -> io::Result<()> { let files_results = vec![ ("test.txt", 51, 49), ("test3.txt", 2942, 0), ("test4.txt", 6, 6), ("input.txt", 111754, 65402), ]; for (f, result_1, result_2) in files_results.into_iter() { println!("File: {}", f); let file_content: Vec<String> = std::fs::read_to_string(f)? .lines() .map(|x| x.to_string()) .collect(); let line = &file_content[0]; assert_eq!(count_numbers(&line), result_1); let v: Value = serde_json::from_str(line).unwrap(); assert_eq!(counter(&v, true), result_1); assert_eq!(counter(&v, false), result_2); } Ok(()) }
use clap::{App, Arg}; use archiver::config; use archiver::ctx::Ctx; use archiver::device; use archiver::cli; fn cli_opts<'a, 'b>() -> App<'a, 'b> { cli::base_opts() .about("Smoke test the location and mounting") } fn main() { archiver::cli::run(|| { let matches = cli_opts().get_matches(); let cfg = config::Config::from_file(matches.value_of("config").unwrap_or("archiver.toml")); let ctx = Ctx::create_without_lock(cfg?)?; let devices = device::attached_devices(&ctx)?; for device in devices { println!(" {:?}", &device); } Ok(()) }); }
use super::*; /// The diagonal of an N-dimensional homotopy, resulting in a 1D homotopy. /// /// This interpolates along all dimensions at once. #[derive(Copy, Clone)] pub struct Diagonal<T, S> { shape: T, _s: PhantomData<S>, } impl<T, S> Diagonal<T, S> { /// Creates a new diagonal. pub fn new(shape: T) -> Self { Diagonal {shape, _s: PhantomData} } } impl<X, T> Homotopy<X> for Diagonal<T, [f64; 2]> where T: Homotopy<X, [f64; 2]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.shape.f(x)} fn g(&self, x: X) -> Self::Y {self.shape.g(x)} fn h(&self, x: X, s: f64) -> Self::Y {self.shape.h(x, [s; 2])} } impl<X, T> Homotopy<X> for Diagonal<T, [f64; 3]> where T: Homotopy<X, [f64; 3]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.shape.f(x)} fn g(&self, x: X) -> Self::Y {self.shape.g(x)} fn h(&self, x: X, s: f64) -> Self::Y {self.shape.h(x, [s; 3])} } impl<X, T> Homotopy<X> for Diagonal<T, [f64; 4]> where T: Homotopy<X, [f64; 4]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.shape.f(x)} fn g(&self, x: X) -> Self::Y {self.shape.g(x)} fn h(&self, x: X, s: f64) -> Self::Y {self.shape.h(x, [s; 4])} } /// The left side of an N-dimensional homotopy, resulting in a N-1 homotopy. #[derive(Copy, Clone)] pub struct Left<T>(pub T); impl<X, T> Homotopy<X> for Left<T> where T: Homotopy<X, [f64; 2]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.f(x)} fn g(&self, x: X) -> Self::Y {self.0.h(x, [0.0, 1.0])} fn h(&self, x: X, s: f64) -> Self::Y {self.0.h(x, [0.0, s])} } impl<X, T> Homotopy<X, [f64; 2]> for Left<T> where T: Homotopy<X, [f64; 3]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.f(x)} fn g(&self, x: X) -> Self::Y {self.0.h(x, [0.0, 1.0, 1.0])} fn h(&self, x: X, s: [f64; 2]) -> Self::Y {self.0.h(x, [0.0, s[0], s[1]])} } impl<X, T> Homotopy<X, [f64; 3]> for Left<T> where T: Homotopy<X, [f64; 4]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.f(x)} fn g(&self, x: X) -> Self::Y {self.0.h(x, [0.0, 1.0, 1.0, 1.0])} fn h(&self, x: X, s: [f64; 3]) -> Self::Y {self.0.h(x, [0.0, s[0], s[1], s[2]])} } /// The right side of an N-dimensional homotopy, resulting in a N-1 homotopy. #[derive(Copy, Clone)] pub struct Right<T>(pub T); impl<X, T> Homotopy<X> for Right<T> where T: Homotopy<X, [f64; 2]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [1.0, 0.0])} fn g(&self, x: X) -> Self::Y {self.0.g(x)} fn h(&self, x: X, s: f64) -> Self::Y {self.0.h(x, [1.0, s])} } impl<X, T> Homotopy<X, [f64; 2]> for Right<T> where T: Homotopy<X, [f64; 3]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [1.0, 0.0, 0.0])} fn g(&self, x: X) -> Self::Y {self.0.g(x)} fn h(&self, x: X, s: [f64; 2]) -> Self::Y {self.0.h(x, [1.0, s[0], s[1]])} } impl<X, T> Homotopy<X, [f64; 3]> for Right<T> where T: Homotopy<X, [f64; 4]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [1.0, 0.0, 0.0, 0.0])} fn g(&self, x: X) -> Self::Y {self.0.g(x)} fn h(&self, x: X, s: [f64; 3]) -> Self::Y {self.0.h(x, [1.0, s[0], s[1], s[2]])} } /// The top side of an N-dimensional homotopy, resulting in a N-1 homotopy. #[derive(Copy, Clone)] pub struct Top<T>(pub T); impl<X, T> Homotopy<X> for Top<T> where T: Homotopy<X, [f64; 2]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.f(x)} fn g(&self, x: X) -> Self::Y {self.0.h(x, [1.0, 0.0])} fn h(&self, x: X, s: f64) -> Self::Y {self.0.h(x, [s, 0.0])} } impl<X, T> Homotopy<X, [f64; 2]> for Top<T> where T: Homotopy<X, [f64; 3]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.f(x)} fn g(&self, x: X) -> Self::Y {self.0.h(x, [1.0, 0.0, 1.0])} fn h(&self, x: X, s: [f64; 2]) -> Self::Y {self.0.h(x, [s[0], 0.0, s[1]])} } impl<X, T> Homotopy<X, [f64; 3]> for Top<T> where T: Homotopy<X, [f64; 4]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.f(x)} fn g(&self, x: X) -> Self::Y {self.0.h(x, [1.0, 0.0, 1.0, 1.0])} fn h(&self, x: X, s: [f64; 3]) -> Self::Y {self.0.h(x, [s[0], 0.0, s[1], s[2]])} } /// The bottom side of an N-dimensional homotopy, resulting in a N-1 homotopy. #[derive(Copy, Clone)] pub struct Bottom<T>(pub T); impl<X, T> Homotopy<X> for Bottom<T> where T: Homotopy<X, [f64; 2]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [0.0, 1.0])} fn g(&self, x: X) -> Self::Y {self.0.g(x)} fn h(&self, x: X, s: f64) -> Self::Y {self.0.h(x, [s, 1.0])} } impl<X, T> Homotopy<X, [f64; 2]> for Bottom<T> where T: Homotopy<X, [f64; 3]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [0.0, 1.0, 0.0])} fn g(&self, x: X) -> Self::Y {self.0.g(x)} fn h(&self, x: X, s: [f64; 2]) -> Self::Y {self.0.h(x, [s[0], 1.0, s[1]])} } impl<X, T> Homotopy<X, [f64; 3]> for Bottom<T> where T: Homotopy<X, [f64; 4]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [0.0, 1.0, 0.0, 0.0])} fn g(&self, x: X) -> Self::Y {self.0.g(x)} fn h(&self, x: X, s: [f64; 3]) -> Self::Y {self.0.h(x, [s[0], 1.0, s[1], s[2]])} } /// The front side of an N-dimensional homotopy, resulting in a N-1 homotopy. #[derive(Copy, Clone)] pub struct Front<T>(pub T); impl<X, T> Homotopy<X, [f64; 2]> for Front<T> where T: Homotopy<X, [f64; 3]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.f(x)} fn g(&self, x: X) -> Self::Y {self.0.h(x, [1.0, 1.0, 0.0])} fn h(&self, x: X, s: [f64; 2]) -> Self::Y {self.0.h(x, [s[0], s[1], 0.0])} } impl<X, T> Homotopy<X, [f64; 3]> for Front<T> where T: Homotopy<X, [f64; 4]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.f(x)} fn g(&self, x: X) -> Self::Y {self.0.h(x, [1.0, 1.0, 0.0, 1.0])} fn h(&self, x: X, s: [f64; 3]) -> Self::Y {self.0.h(x, [s[0], s[1], 0.0, s[2]])} } /// The back side of an N-dimensional homotopy, resulting in a N-1 homotopy. #[derive(Copy, Clone)] pub struct Back<T>(pub T); impl<X, T> Homotopy<X, [f64; 2]> for Back<T> where T: Homotopy<X, [f64; 3]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [0.0, 0.0, 1.0])} fn g(&self, x: X) -> Self::Y {self.0.g(x)} fn h(&self, x: X, s: [f64; 2]) -> Self::Y {self.0.h(x, [s[0], s[1], 1.0])} } impl<X, T> Homotopy<X, [f64; 3]> for Back<T> where T: Homotopy<X, [f64; 4]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [0.0, 0.0, 1.0, 0.0])} fn g(&self, x: X) -> Self::Y {self.0.g(x)} fn h(&self, x: X, s: [f64; 3]) -> Self::Y {self.0.h(x, [s[0], s[1], 1.0, s[2]])} } /// The past side of an N-dimensional homotopy, resuling in a N-1 homotopy. #[derive(Copy, Clone)] pub struct Past<T>(pub T); impl<X, T> Homotopy<X, [f64; 3]> for Past<T> where T: Homotopy<X, [f64; 4]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.f(x)} fn g(&self, x: X) -> Self::Y {self.0.h(x, [1.0, 1.0, 1.0, 0.0])} fn h(&self, x: X, s: [f64; 3]) -> Self::Y {self.0.h(x, [s[0], s[1], s[2], 0.0])} } /// The future side of an N-dimensional homotopy, resuling in a N-1 homotopy. #[derive(Copy, Clone)] pub struct Future<T>(pub T); impl<X, T> Homotopy<X, [f64; 3]> for Future<T> where T: Homotopy<X, [f64; 4]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [0.0, 0.0, 0.0, 1.0])} fn g(&self, x: X) -> Self::Y {self.0.g(x)} fn h(&self, x: X, s: [f64; 3]) -> Self::Y {self.0.h(x, [s[0], s[1], s[2], 1.0])} } /// Intersects from left to right. #[derive(Copy, Clone)] pub struct LeftRight<T>(pub T, pub f64); impl<X, T> Homotopy<X> for LeftRight<T> where T: Homotopy<X, [f64; 2]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [self.1, 0.0])} fn g(&self, x: X) -> Self::Y {self.0.h(x, [self.1, 1.0])} fn h(&self, x: X, s: f64) -> Self::Y {self.0.h(x, [self.1, s])} } impl<X, T> Homotopy<X, [f64; 2]> for LeftRight<T> where T: Homotopy<X, [f64; 3]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [self.1, 0.0, 0.0])} fn g(&self, x: X) -> Self::Y {self.0.h(x, [self.1, 1.0, 1.0])} fn h(&self, x: X, s: [f64; 2]) -> Self::Y {self.0.h(x, [self.1, s[0], s[1]])} } impl<X, T> Homotopy<X, [f64; 3]> for LeftRight<T> where T: Homotopy<X, [f64; 4]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [self.1, 0.0, 0.0, 0.0])} fn g(&self, x: X) -> Self::Y {self.0.h(x, [self.1, 1.0, 1.0, 1.0])} fn h(&self, x: X, s: [f64; 3]) -> Self::Y {self.0.h(x, [self.1, s[0], s[1], s[2]])} } /// Intersects from top to botttom. #[derive(Copy, Clone)] pub struct TopBottom<T>(pub T, pub f64); impl<X, T> Homotopy<X> for TopBottom<T> where T: Homotopy<X, [f64; 2]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [0.0, self.1])} fn g(&self, x: X) -> Self::Y {self.0.h(x, [1.0, self.1])} fn h(&self, x: X, s: f64) -> Self::Y {self.0.h(x, [s, self.1])} } impl<X, T> Homotopy<X, [f64; 2]> for TopBottom<T> where T: Homotopy<X, [f64; 3]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [0.0, self.1, 0.0])} fn g(&self, x: X) -> Self::Y {self.0.h(x, [1.0, self.1, 1.0])} fn h(&self, x: X, s: [f64; 2]) -> Self::Y {self.0.h(x, [s[0], self.1, s[1]])} } impl<X, T> Homotopy<X, [f64; 3]> for TopBottom<T> where T: Homotopy<X, [f64; 4]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [0.0, self.1, 0.0, 0.0])} fn g(&self, x: X) -> Self::Y {self.0.h(x, [1.0, self.1, 1.0, 1.0])} fn h(&self, x: X, s: [f64; 3]) -> Self::Y {self.0.h(x, [s[0], self.1, s[1], s[2]])} } /// Intersects from front to back. #[derive(Copy, Clone)] pub struct FrontBack<T>(pub T, pub f64); impl<X, T> Homotopy<X, [f64; 2]> for FrontBack<T> where T: Homotopy<X, [f64; 3]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [0.0, 0.0, self.1])} fn g(&self, x: X) -> Self::Y {self.0.h(x, [1.0, 1.0, self.1])} fn h(&self, x: X, s: [f64; 2]) -> Self::Y {self.0.h(x, [s[0], s[1], self.1])} } impl<X, T> Homotopy<X, [f64; 3]> for FrontBack<T> where T: Homotopy<X, [f64; 4]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [0.0, 0.0, self.1, 0.0])} fn g(&self, x: X) -> Self::Y {self.0.h(x, [1.0, 1.0, self.1, 1.0])} fn h(&self, x: X, s: [f64; 3]) -> Self::Y {self.0.h(x, [s[0], s[1], self.1, s[2]])} } /// Intersects from past to future. #[derive(Copy, Clone)] pub struct PastFuture<T>(pub T, pub f64); impl<X, T> Homotopy<X, [f64; 3]> for PastFuture<T> where T: Homotopy<X, [f64; 4]> { type Y = T::Y; fn f(&self, x: X) -> Self::Y {self.0.h(x, [0.0, 0.0, 0.0, self.1])} fn g(&self, x: X) -> Self::Y {self.0.h(x, [1.0, 1.0, 1.0, self.1])} fn h(&self, x: X, s: [f64; 3]) -> Self::Y {self.0.h(x, [s[0], s[1], s[2], self.1])} }
use std::net::SocketAddr; use rsocket_rust::async_trait; use rsocket_rust::{error::RSocketError, transport::Transport, Result}; use tokio::net::TcpStream; use tokio_native_tls::{TlsConnector, TlsStream}; use crate::connection::TlsConnection; #[derive(Debug)] enum Connector { Direct(TlsStream<TcpStream>), Lazy(String, SocketAddr, TlsConnector), } pub struct TlsClientTransport { connector: Connector, } impl TlsClientTransport { pub fn new(domain: String, addr: SocketAddr, connector: TlsConnector) -> Self { Self { connector: Connector::Lazy(domain, addr, connector), } } } #[async_trait] impl Transport for TlsClientTransport { type Conn = TlsConnection; async fn connect(self) -> Result<Self::Conn> { match self.connector { Connector::Direct(stream) => Ok(TlsConnection::from(stream)), Connector::Lazy(domain, addr, cx) => match TcpStream::connect(addr).await { Ok(stream) => match cx.connect(&domain, stream).await { Ok(stream) => Ok(TlsConnection::from(stream)), Err(e) => Err(RSocketError::Other(e.into()).into()), }, Err(e) => Err(RSocketError::IO(e).into()), }, } } } impl From<TlsStream<TcpStream>> for TlsClientTransport { fn from(stream: TlsStream<TcpStream>) -> Self { Self { connector: Connector::Direct(stream), } } }
#![feature(uniform_paths)] mod multicolumn; mod cli; use multicolumn::Multicolumn; use std::env; use termion::style; fn main() { //termion::terminal_size() let matches = cli::build_cli().get_matches_safe().unwrap_or_else(|e| e.exit()); let paths = match matches.values_of("path") { None => vec!(env::current_dir().expect("there is not a current directory")), Some(i) => i.map(|path| std::path::PathBuf::from(path)).collect::<Vec<std::path::PathBuf>>() }; match paths.len() { 1 => { println!("{}{}", style::Bold, Multicolumn::new(termion::terminal_size().unwrap(), &paths[0])); }, _ => { paths.iter().for_each(|path| { println!("{}{}:", style::Reset, path.display()); println!("{}{}\n", style::Bold, Multicolumn::new(termion::terminal_size().unwrap(), &paths[0])); }); }, } }
#[doc = "Reader of register HOST_EP1_CTL"] pub type R = crate::R<u32, super::HOST_EP1_CTL>; #[doc = "Writer for register HOST_EP1_CTL"] pub type W = crate::W<u32, super::HOST_EP1_CTL>; #[doc = "Register HOST_EP1_CTL `reset()`'s with value 0x8100"] impl crate::ResetValue for super::HOST_EP1_CTL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x8100 } } #[doc = "Reader of field `PKS1`"] pub type PKS1_R = crate::R<u16, u16>; #[doc = "Write proxy for field `PKS1`"] pub struct PKS1_W<'a> { w: &'a mut W, } impl<'a> PKS1_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 & !0x01ff) | ((value as u32) & 0x01ff); self.w } } #[doc = "Reader of field `NULLE`"] pub type NULLE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `NULLE`"] pub struct NULLE_W<'a> { w: &'a mut W, } impl<'a> NULLE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `DMAE`"] pub type DMAE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DMAE`"] pub struct DMAE_W<'a> { w: &'a mut W, } impl<'a> DMAE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `DIR`"] pub type DIR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DIR`"] pub struct DIR_W<'a> { w: &'a mut W, } impl<'a> DIR_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `BFINI`"] pub type BFINI_R = crate::R<bool, bool>; #[doc = "Write proxy for field `BFINI`"] pub struct BFINI_W<'a> { w: &'a mut W, } impl<'a> BFINI_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } impl R { #[doc = "Bits 0:8 - This bit specifies the maximum size transferred by one packet. The configurable range is from 0x001 to 0x100. - If automatic buffer transfer mode (DMEA='1') is used, this Endpoint must not set from 0 to 2."] #[inline(always)] pub fn pks1(&self) -> PKS1_R { PKS1_R::new((self.bits & 0x01ff) as u16) } #[doc = "Bit 10 - When a data transfer request in OUT the direction is transmitted while automatic buffer transfer mode is set (DMAE = 1), this bit sets a mode that transfers 0-byte data automatically upon the detection of the last packet transfer. '0' : Releases the NULL automatic transfer mode. '1' : Sets the NULL automatic transfer mode. Note : - For data transfer in the IN direction or when automatic buffer transfer mode is not set, the NULL bit configuration does not affect communication."] #[inline(always)] pub fn nulle(&self) -> NULLE_R { NULLE_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - This bit sets a mode that uses DMA for writing or reading transfer data to/from send/receive buffer, and automatically transfers the send/receive data synchronized with an data request in the IN or OUT direction. Until the data size set in the DMA is reached, the data is transferred. '0' : Releases the automatic buffer transfer mode. '1' : Sets the automatic buffer transfer mode. Note : - The CPU must not access the send/receive buffer while the DMAE bit is set to '1'. For data transfer in the IN direction, set the DMA transfer size to the multiples of that set in PKS bits of the Host EP1 Control Register (HOST_EP1_CTL) and Host EP2 Control Register (HOST_EP2_CTR)."] #[inline(always)] pub fn dmae(&self) -> DMAE_R { DMAE_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - This bit specifies the transfer direction the Endpoint support. '0' : IN Endpoint. '1' : OUT Endpoint Note: - This bit must be changed when INI_ST bit of the Host Endpoint 1 Status Register (HOST_EP1_STATUS) is '1'."] #[inline(always)] pub fn dir(&self) -> DIR_R { DIR_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 15 - This bit initializes the send/receive buffer of transfer data. The BFINI bit is also automatically set by setting the RST bit of the HOST Control 1 Register (HOST_CTL1). If the RST bit was used for resetting, therefore, set the RST bit to '0' before clearing the BFINI bit. '0' : Clears the initialization. '1' : Initializes the send/receive buffer Note : - The EP1 buffer has a double-buffer configuration. The BFINI bit initialization initializes the double buffers concurrently and also initializes the EP1DRQ and EP1SPK bits."] #[inline(always)] pub fn bfini(&self) -> BFINI_R { BFINI_R::new(((self.bits >> 15) & 0x01) != 0) } } impl W { #[doc = "Bits 0:8 - This bit specifies the maximum size transferred by one packet. The configurable range is from 0x001 to 0x100. - If automatic buffer transfer mode (DMEA='1') is used, this Endpoint must not set from 0 to 2."] #[inline(always)] pub fn pks1(&mut self) -> PKS1_W { PKS1_W { w: self } } #[doc = "Bit 10 - When a data transfer request in OUT the direction is transmitted while automatic buffer transfer mode is set (DMAE = 1), this bit sets a mode that transfers 0-byte data automatically upon the detection of the last packet transfer. '0' : Releases the NULL automatic transfer mode. '1' : Sets the NULL automatic transfer mode. Note : - For data transfer in the IN direction or when automatic buffer transfer mode is not set, the NULL bit configuration does not affect communication."] #[inline(always)] pub fn nulle(&mut self) -> NULLE_W { NULLE_W { w: self } } #[doc = "Bit 11 - This bit sets a mode that uses DMA for writing or reading transfer data to/from send/receive buffer, and automatically transfers the send/receive data synchronized with an data request in the IN or OUT direction. Until the data size set in the DMA is reached, the data is transferred. '0' : Releases the automatic buffer transfer mode. '1' : Sets the automatic buffer transfer mode. Note : - The CPU must not access the send/receive buffer while the DMAE bit is set to '1'. For data transfer in the IN direction, set the DMA transfer size to the multiples of that set in PKS bits of the Host EP1 Control Register (HOST_EP1_CTL) and Host EP2 Control Register (HOST_EP2_CTR)."] #[inline(always)] pub fn dmae(&mut self) -> DMAE_W { DMAE_W { w: self } } #[doc = "Bit 12 - This bit specifies the transfer direction the Endpoint support. '0' : IN Endpoint. '1' : OUT Endpoint Note: - This bit must be changed when INI_ST bit of the Host Endpoint 1 Status Register (HOST_EP1_STATUS) is '1'."] #[inline(always)] pub fn dir(&mut self) -> DIR_W { DIR_W { w: self } } #[doc = "Bit 15 - This bit initializes the send/receive buffer of transfer data. The BFINI bit is also automatically set by setting the RST bit of the HOST Control 1 Register (HOST_CTL1). If the RST bit was used for resetting, therefore, set the RST bit to '0' before clearing the BFINI bit. '0' : Clears the initialization. '1' : Initializes the send/receive buffer Note : - The EP1 buffer has a double-buffer configuration. The BFINI bit initialization initializes the double buffers concurrently and also initializes the EP1DRQ and EP1SPK bits."] #[inline(always)] pub fn bfini(&mut self) -> BFINI_W { BFINI_W { w: self } } }
extern crate itertools; use ::net; use ::config; use ::std; // Import and alias use serde_json; use serde_json::Value as Json; #[derive(Debug, Deserialize)] struct Computer { #[serde(rename="displayName")] name: String, #[serde(rename="numExecutors")] executors: u16, #[serde(rename="offlineCauseReason")] offline: Option<String>, } impl std::fmt::Display for Computer { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{} ({})", self.name, self.executors)?; if let Some(ref offline_because) = self.offline { if offline_because.len() > 0 { write!(f, " \"{}\"", offline_because)?; } } Ok(()) } } fn list_computers<'api>(api_response: &'api Json) -> Vec<Computer> { return serde_json::from_value(api_response["computer"].clone()).expect("Could not deserialize computer array"); } // Function for the "list nodes" command pub fn execute(config: &config::Config) { // Declare that we want to use the `Itertools` trait use self::itertools::Itertools; // Nested functions are also cool fn is_some_and_not_empty(c: &Computer) -> bool { // We can do this with Option::filter in newer Rust versions c.offline.as_ref().map_or(false, |s| s.len() > 0) } match net::api(&[&config.jenkins.server, "computer"]) { Ok(ref response) => { // Use of `ref` keyword to capture by refence, cause the type to be &Json println!("Listing jobs:"); // Must sort the computers to get our nodes in order, we can use some built in functions // To sort on the `offline` field let mut computers = list_computers(response); computers.sort_by(|a, b| Ord::cmp(&a.offline, &b.offline)); for (offline, computers) in &computers.into_iter().group_by(is_some_and_not_empty) { // We don't need ternary operators, because "if" is an expression println!("{}:", if offline { "offline" } else { "online" }); for comp in computers { println!(" {}", comp); } } }, Err(err) => println!("Could not fetch computer list! ({:?})", err), } }
use super::connection::{Connection, ConnectionError}; use super::config::*; use std::sync::{Arc, Mutex}; #[derive(Clone)] pub struct Pool { inner: Arc<Inner>, } struct Inner { conf: PqConfig, // vector of free connection in pool conns: Mutex<Vec<Connection>>, // 0: total of connection allocated // 1: total of connection pending conn_allocated: Mutex<(usize, usize)>, max_conn: usize, } impl Pool { pub fn new<C: ToPqConfig>(conf: C, max_conn: usize) -> Result<Pool, ConfParseError> { Ok(Pool { inner: Arc::new(Inner { conf: conf.to_pq_config()?, conns: Mutex::new(Vec::with_capacity(max_conn)), conn_allocated: Mutex::new((0, 0)), max_conn, }), }) } pub async fn get_conn(&self) -> Result<PooledConnection, ConnectionPoolError> { let conn: Option<Connection> = { let mut conns = self.inner.conns.lock().unwrap(); conns.pop() }; match conn { Some(c) => Ok(PooledConnection { pool: self.clone(), conn: Some(c), }), None => { let mut allocated = self.inner.conn_allocated.lock().unwrap(); // max conn check if allocated.0 + allocated.1 >= self.inner.max_conn { return Err(ConnectionPoolError::Exhausted); } // allocate new connection // add new pending, drop the mutex allocated.1 += 1; debug!( "Creating new connection, total allocated: {}, pending: {}", allocated.0, allocated.1 ); drop(allocated); let mut conn = Connection::new(self.inner.conf.address) .await .map_err(|e| ConnectionPoolError::Connection(e))?; conn.startup(self.inner.conf.cred.as_ref(), self.inner.conf.dbname.as_deref()) .await .map_err(|e| ConnectionPoolError::Connection(e))?; ; let mut allocated = self.inner.conn_allocated.lock().unwrap(); allocated.0 += 1; allocated.1 -= 1; debug!( "Allocated new connection, total allocated: {}, pending: {}", allocated.0, allocated.1 ); Ok(PooledConnection { pool: self.clone(), conn: Some(conn), }) } } } pub fn put_back(&self, conn: Connection) { let mut vec = self.inner.conns.lock().unwrap(); debug!("#REMOVE total in pools: {}", vec.len()); vec.push(conn); } } pub struct PooledConnection { pool: Pool, conn: Option<Connection>, } impl Drop for PooledConnection { fn drop(&mut self) { self.pool.put_back(self.conn.take().unwrap()); } } #[derive(Debug)] pub enum ConnectionPoolError { Connection(ConnectionError), Exhausted, } use std::fmt; impl fmt::Display for ConnectionPoolError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Connection pool error") } } impl std::error::Error for ConnectionPoolError {}
mod env; mod handler; mod server; mod state; use {actix_rt::System, env_logger, server::start, std::io::Result}; fn main() -> Result<()> { env_logger::init(); System::new().block_on(async { start().await }) }
use {data::semantics::Semantics, misc::id_gen::generate_mutable_id}; impl Semantics { fn create_element_from_group(&mut self, source_id: usize, parent_id: usize) { let element_id = self.groups.len(); log::debug!(" Creating new element group {}", element_id); let source = &mut self.groups[source_id]; let element = source.class_to_new_static_element(source_id); source.members.push(element_id); self.groups.push(element); self.groups[parent_id].elements.push(element_id); } pub fn cascade(&mut self, source_id: usize, target_id: usize, virtual_: bool) { log::debug!( "Cascading from group {} into group {}", source_id, target_id ); if source_id == target_id { panic!("the build process should never try to cascade a group into itself") } if !virtual_ { for (property, value) in self.groups[source_id].properties.clone() { log::debug!(" Cascading cui property {:?}:{:?}", property, value); self.groups[target_id] .properties .entry(property) .or_insert(value); } for (name, value) in self.groups[source_id].variables.clone() { log::debug!(" Cascading variable '{}': {:?}", name, value); self.groups[target_id] .variables .entry(name) .or_insert(value); } } else { for name in self.groups[source_id].variables.keys() { if self.groups[source_id].listener_scope != self.groups[target_id].listener_scope { if let Some(&variable_id) = self.groups[target_id].variables.get(name) { log::debug!(" Adding mutable flag to variable '{}'", name); let mutable_id = generate_mutable_id(); self.variables[variable_id] = (self.variables[variable_id].0.clone(), Some(mutable_id)); } } } } for listener_id in self.groups[source_id].listeners.clone() { log::debug!(" Cascading scoped listener {}", listener_id); self.groups[target_id].listeners.push(listener_id); self.cascade(listener_id, target_id, true); } for (name, class_ids) in self.groups[source_id].classes.clone() { for class_id in class_ids { log::debug!(" Cascading scoped class {} with name {}", class_id, name); self.groups[target_id] .classes .entry(name.clone()) .or_default() .push(class_id); } } if (self.groups[source_id].listener_scope == self.groups[target_id].listener_scope) && !self.groups[source_id].elements.is_empty() && !self.groups[target_id].elements.is_empty() { panic!("Source and target group specify different contents for the same element") } for source_id in self.groups[source_id].elements.clone() { log::debug!( " Cascading element with name {}", self.groups[source_id].name.clone().unwrap() ); if self.groups[source_id].is_static() { self.create_element_from_group(source_id, target_id); } else { self.groups[target_id].elements.push(source_id); } } } }
//! This module defines the command-line interface of the application //! - Defines parameters //! - Defines validators use clap::{Arg, App}; use std::path::Path; use std::panic::catch_unwind; use tsp::{TSP, file_parser}; use std::fs::File; use std::io::Read; use slog::*; use af::*; // Specify command line parameters pub fn app_gen<'a, 'b: 'a>() -> App<'a, 'b> { App::new("Traveling Salesman Problem Genetic Algorithm Optimizer") .author("William Cole, william.col3@gmail.com") .version(crate_version!()) .about("This crate takes a formulation of a traveling salesman problem in \ the format specified by TSPLIB at \ comopt.ifi.uni-heidelberg.de/software/TSPLIB95/ for symmetric \ traveling salesman problems, or generates one randomly, and runs \ a heuristic optimization using genetic algorithms accelerated by \ GPU programming.") .arg(Arg::with_name("input") .long("input") .short("i") .value_name("INPUT") .validator(validate_input_path) .help("Specify file to input predetermined TSP") .takes_value(true)) .arg(Arg::with_name("output") .long("output") .short("o") .value_name("OUTPUT") .help("Specify outfile file for log and optimization results") .takes_value(true) .hidden(true)) .arg(Arg::with_name("compute") .long("compute_framework") .short("c") .value_name("FRAMEWORK") .help("The compute framework to be used. Default order of use is OpenCL -> CUDA -> \ CPU.") .takes_value(true) .possible_value("CUDA") .possible_value("OpenCL") .possible_value("CPU")) .arg(Arg::with_name("cities") .long("cities") .short("n") .value_name("NUMBER") .validator(validate_positive_integer) .help("Number of cities generated when optimizing a random TSP. Default: 20") .conflicts_with("input") .takes_value(true)) // TODO: Validate as numeric value. .arg(Arg::with_name("generations") .long("generations") .short("g") .value_name("NUMBER") .validator(validate_positive_integer) .help("Number of generations to run in the genetic algorithm. Default: 50") .takes_value(true)) // TODO: Validate as numeric value. // More options will come later for more termination criteria, etc. } /// Validate integers given for /// + Generations /// + Cities fn validate_positive_integer(arg: String) -> Result<(), String> { let parsed = arg.parse::<u64>() .map_err(|_| "Failed to parse supplied argument into integer.".to_owned()); if let Ok(i) = parsed { if i <= 0 { Err("Supplied argument integer must be greater than 0.".to_owned()) } else { Ok(()) } } else { parsed.map(|_| ()) } } /// Validate input path to gen TSP /// This validator checks that: /// + A file exists at the given path /// + The file at the given path is a valid TSPLIB95 data file /// + The data file correctly parses into a relevant symmetric TSP fn validate_input_path(arg: String) -> Result<(), String> { let path = Path::new(&arg); if !path.is_file() { return Err("The specified path is not a file".to_owned()); }; let file = File::open(path); if let Err(_) = file { return Err("Failed to open file at specified path".to_owned()); } let mut data: Vec<u8> = Vec::new(); if let Err(_) = file.unwrap().read_to_end(&mut data) { return Err("Problem reading file contents into program".to_owned()); } // change the backend to cpu and then back to default (in case processor does not support double set_backend(Backend::CPU); if let Ok(data_file) = catch_unwind(|| file_parser(&data)) { // Check that it parses into a synchronous TSP if let Ok(_) = catch_unwind(|| { TSP::from_tsplib95(data_file.unwrap().1, Logger::root(Discard, o!())) }) { set_backend(Backend::DEFAULT); Ok(()) } else { Err("Problem interpreting supplied TSP file as symmetric TSP.".to_owned()) } } else { Err("Problem parsing TSP file by TSPLIB95 spec. \ Make sure the supplied file is well-formed." .to_owned()) } }
#[doc = "Register `DDRPHYC_DTPR2` reader"] pub type R = crate::R<DDRPHYC_DTPR2_SPEC>; #[doc = "Register `DDRPHYC_DTPR2` writer"] pub type W = crate::W<DDRPHYC_DTPR2_SPEC>; #[doc = "Field `TXS` reader - TXS"] pub type TXS_R = crate::FieldReader<u16>; #[doc = "Field `TXS` writer - TXS"] pub type TXS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 10, O, u16>; #[doc = "Field `TXP` reader - TXP"] pub type TXP_R = crate::FieldReader; #[doc = "Field `TXP` writer - TXP"] pub type TXP_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O>; #[doc = "Field `TCKE` reader - TCKE"] pub type TCKE_R = crate::FieldReader; #[doc = "Field `TCKE` writer - TCKE"] pub type TCKE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `TDLLK` reader - TDLLK"] pub type TDLLK_R = crate::FieldReader<u16>; #[doc = "Field `TDLLK` writer - TDLLK"] pub type TDLLK_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 10, O, u16>; impl R { #[doc = "Bits 0:9 - TXS"] #[inline(always)] pub fn txs(&self) -> TXS_R { TXS_R::new((self.bits & 0x03ff) as u16) } #[doc = "Bits 10:14 - TXP"] #[inline(always)] pub fn txp(&self) -> TXP_R { TXP_R::new(((self.bits >> 10) & 0x1f) as u8) } #[doc = "Bits 15:18 - TCKE"] #[inline(always)] pub fn tcke(&self) -> TCKE_R { TCKE_R::new(((self.bits >> 15) & 0x0f) as u8) } #[doc = "Bits 19:28 - TDLLK"] #[inline(always)] pub fn tdllk(&self) -> TDLLK_R { TDLLK_R::new(((self.bits >> 19) & 0x03ff) as u16) } } impl W { #[doc = "Bits 0:9 - TXS"] #[inline(always)] #[must_use] pub fn txs(&mut self) -> TXS_W<DDRPHYC_DTPR2_SPEC, 0> { TXS_W::new(self) } #[doc = "Bits 10:14 - TXP"] #[inline(always)] #[must_use] pub fn txp(&mut self) -> TXP_W<DDRPHYC_DTPR2_SPEC, 10> { TXP_W::new(self) } #[doc = "Bits 15:18 - TCKE"] #[inline(always)] #[must_use] pub fn tcke(&mut self) -> TCKE_W<DDRPHYC_DTPR2_SPEC, 15> { TCKE_W::new(self) } #[doc = "Bits 19:28 - TDLLK"] #[inline(always)] #[must_use] pub fn tdllk(&mut self) -> TDLLK_W<DDRPHYC_DTPR2_SPEC, 19> { TDLLK_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 = "DDRPHYC DTP register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ddrphyc_dtpr2::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 [`ddrphyc_dtpr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct DDRPHYC_DTPR2_SPEC; impl crate::RegisterSpec for DDRPHYC_DTPR2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ddrphyc_dtpr2::R`](R) reader structure"] impl crate::Readable for DDRPHYC_DTPR2_SPEC {} #[doc = "`write(|w| ..)` method takes [`ddrphyc_dtpr2::W`](W) writer structure"] impl crate::Writable for DDRPHYC_DTPR2_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets DDRPHYC_DTPR2 to value 0x2004_0d84"] impl crate::Resettable for DDRPHYC_DTPR2_SPEC { const RESET_VALUE: Self::Ux = 0x2004_0d84; }
extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2::Span; use quote::quote; use syn::{Data, DataEnum, DataStruct, DeriveInput, Ident, IntSuffix, LitInt, WhereClause}; #[proc_macro_derive(Generic)] pub fn generic_macro_derive(input: TokenStream) -> TokenStream { let DeriveInput { ident: name, vis: _, attrs: _, generics, data, } = syn::parse(input).unwrap(); let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let ty; let ty_predicates; let into; let from; match data { Data::Struct(DataStruct { fields, .. }) => { ty = fields .iter() .fold(quote! { ::generics::Unit }, |acc, field| { let field_ty = &field.ty; quote! { ::generics::Prod<#acc, <#field_ty as ::generics::Generic>::Repr> } }); ty_predicates = fields .iter() .map(|field| { let field_ty = &field.ty; quote! { #field_ty : ::generics::Generic } }) .collect::<Vec<_>>(); let ref self_fields = fields .iter() .enumerate() .map(|(i, field)| match &field.ident { Some(ident) => quote! { #ident }, None => { let lit = LitInt::new(i as u64, IntSuffix::None, Span::call_site()); quote! { #lit } } }) .collect::<Vec<_>>(); let ref ordinals = fields .iter() .enumerate() .map(|(i, _)| Ident::new(&format!("_{}", i), Span::call_site())) .collect::<Vec<_>>(); let repr_structure = ordinals .iter() .fold(quote! { ::generics::Unit }, |acc, ordinal| { quote! { ::generics::Prod(#acc, #ordinal) } }); let into_conversions = ordinals.iter().map(|ordinal| { quote! { let #ordinal = ::generics::Generic::into_repr(#ordinal); } }); let from_conversions = ordinals.iter().map(|ordinal| { quote! { let #ordinal = ::generics::Generic::from_repr(#ordinal); } }); into = quote! { let Self { #(#self_fields : #ordinals),* } = self; #( #into_conversions )* #repr_structure }; from = quote! { let #repr_structure = repr; #( #from_conversions )* Self { #(#self_fields : #ordinals),* } }; } Data::Enum(DataEnum { variants, .. }) => { unimplemented!(); } Data::Union(_) => panic!("`Generic` cannot be derived for unions"), }; let combined_where_clause = match where_clause { Some(WhereClause { where_token: _, predicates, }) => { quote! { where #(#ty_predicates ,)* #predicates } } None => { quote! { where #(#ty_predicates ,)* } } }; TokenStream::from(quote! { impl #impl_generics Generic for #name #ty_generics #combined_where_clause { type Repr = #ty; fn into_repr(self: Self) -> Self::Repr { #into } fn from_repr(repr: Self::Repr) -> Self { #from } } }) }
// Copyright 2020 The RustExample Authors. // // Code is licensed under Apache License, Version 2.0. extern crate reqwest; use anyhow::Result; use regex::Regex; use select::document::Document; use select::predicate::Name; use std::thread::sleep; use std::time::{Duration, Instant}; use super::*; struct Wallhaven { //url: &'static str, pattern: &'static str, max_page: u32, timeout:u64, } impl Index for Wallhaven { fn new(_url: &'static str, pattern: &'static str, max_page: u32) -> Self { Wallhaven { //url, //"https://wallhaven.cc/" pattern, //"https://wallhaven.cc/search?q=id%3A{}&page={}" max_page, //2 timeout: 10, } } fn make_url(&self, tag: &'static str, page: u32) -> String { let str = String::from(self.pattern); let m = str.replacen("{}", tag, 1); let n = m.replacen("{}", &page.to_string(), 1); n } fn make_filename(&self, url: &'static str, tag: &'static str) -> String { let re = Regex::new(r"\w+-\w+[\.][j|p][p|n]g$").unwrap(); let cap = re.captures(url).unwrap(); let mut str = "wallhaven_cc_tag_".to_string(); str.push_str(tag); str.push('/'); str.push_str(&cap[0]); str } fn parse_urls(&self, tag: &'static str) -> Result<Vec<String>> { let mut rv = Vec::new(); let mut page: u32 = 1; loop { let mut uv = Vec::new(); if page > self.max_page { break; } let timeout = Duration::from_secs(self.timeout); let instant = Instant::now(); let url = self.make_url(tag, page); let client = reqwest::blocking::Client::builder() .user_agent(APP_USER_AGENT) .cookie_store(true) .build()?; let res = client.get(&url).send()?; if res.status().is_success() == false { break; } if timeout >= instant.elapsed() { sleep(timeout - instant.elapsed()); } println!("page={}, url={}", page, url); Document::from_read(res) .unwrap() .find(Name("a")) .filter_map(|n| n.attr("href")) .for_each(|x| { if x.find("/w/").is_some() { uv.push(format!("{}", x.to_string())); } }); for u in uv { //let instant = Instant::now(); let client = reqwest::blocking::Client::builder() .user_agent(APP_USER_AGENT) .build()?; let res = client.get(&u).send()?; if res.status().is_success() { let document = Document::from_read(res).unwrap(); for node in document.find(Name("img")) { if node.attr("id").is_some() { if node.attr("id").unwrap() == "wallpaper" { if node.attr("src").is_some() { rv.push(node.attr("src").unwrap().to_string()); } } } } } if timeout >= instant.elapsed() { sleep(timeout - instant.elapsed()); } } page += 1; } return Ok(rv); } } #[cfg(test)] mod tests { // Note this useful idiom: importing names from outer (for mod tests) scope. use super::*; #[test] fn test_make_url() { let r = Wallhaven::new( "https://wallhaven.cc", "https://wallhaven.cc/search?q=id%3A{}&page={}", 2, ); let u = r.make_url("449", 1); assert_eq!(u, "https://wallhaven.cc/search?q=id%3A449&page=1"); } #[test] fn test_parse_url() { let r = Wallhaven::new( "https://wallhaven.cc", "https://wallhaven.cc/search?q=id%3A{}&page={}", 2, ); let m = r.parse_urls("449"); println!("{:?}", m); } #[test] fn test_make_filename() { let r = Wallhaven::new( "https://wallhaven.cc", "https://wallhaven.cc/search?q=id%3A{}&page={}", 2, ); let m = r.make_filename("https://w.wallhaven.cc/full/96/wallhaven-96kx6x.jpg", "449"); println!("{:?}", m); } }
use std::fmt; use std::fs::File; use std::io::{BufRead, BufReader}; use clap::{App, Arg}; #[derive(PartialEq, Eq, Hash, Clone, Copy)] struct Addr(u64); impl fmt::Debug for Addr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("0x")?; fmt::LowerHex::fmt(&self.0, f) } } #[derive(Debug, PartialEq, Eq)] struct MapEvent { kind: MapKind, address: Addr, size: u64, } #[derive(Debug, PartialEq, Eq)] enum MapKind { Map, Unmap, } fn parse_mmap_line(line: &str) -> Option<MapEvent> { let line = line.trim(); if !line.starts_with("mmap(") { return None; } let mut arg_iter = line.split_terminator(','); arg_iter.next(); // skip first arg let size = match arg_iter.next() { None => { return None; } Some(size) => match str::parse::<u64>(size.trim()) { Err(_) => { return None; } Ok(size) => size, }, }; let mut rsplit = line.rsplit(" = "); let address = match rsplit.next() { None => { return None; } Some(addr) => { // Drop 0x prefix before parsing match u64::from_str_radix(&addr[2..], 16) { Err(err) => { eprintln!("Can't parse address {}: {}", addr, err); return None; } Ok(addr) => Addr(addr), } } }; Some(MapEvent { kind: MapKind::Map, address, size, }) } fn parse_munmap_line(line: &str) -> Option<MapEvent> { let line = line.trim(); if !line.starts_with("munmap(") { return None; } let line = &line["munmap(".len()..]; let mut arg_iter = line.split_terminator(", "); let address = match arg_iter.next() { None => { return None; } Some(addr) => match u64::from_str_radix(&addr[2..], 16) { Err(err) => { eprintln!("Can't parse address {}: {}", addr, err); return None; } Ok(addr) => Addr(addr), }, }; let size = match arg_iter.next() { None => { return None; } Some(rest) => match rest.split(')').next() { None => { return None; } Some(size) => match str::parse::<u64>(size) { Err(_) => { return None; } Ok(size) => size, }, }, }; Some(MapEvent { kind: MapKind::Unmap, address, size, }) } fn main() { let args = App::new("mmap-search") .about("Given a `strace -e trace=%memory` output and a address, finds which mmap/unmap calls map and unmap the address.") .arg(Arg::with_name("mmap-file").takes_value(true).required(true)) .arg(Arg::with_name("address").takes_value(true).required(true)) .get_matches(); let mmap_file = args.value_of("mmap-file").unwrap(); let addr = args.value_of("address").unwrap(); let address = match u64::from_str_radix(&addr[2..], 16) { Err(err) => { eprintln!("Can't parse address: {}", err); ::std::process::exit(1); } Ok(address) => address, }; let f = File::open(mmap_file).unwrap(); let f = BufReader::new(f); for (line_idx, line) in f.lines().enumerate() { let line = line.unwrap(); if let Some(map_event) = parse_mmap_line(&line).or_else(|| parse_munmap_line(&line)) { let start = map_event.address.0; let end = map_event.address.0 + map_event.size; if address >= start && address < end { println!("{}: {:?}", line_idx + 1, map_event); } } } } #[test] fn mmap_parse_1() { // strace format assert_eq!( parse_mmap_line("mmap(NULL, 278570, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fe287e65000\n"), Some(MapEvent { kind: MapKind::Map, address: Addr(0x7fe287e65000), size: 278570 }) ); } #[test] fn mmap_parse_2() { // Custom format assert_eq!( parse_mmap_line("mmap((nil), 1600,) = 0x7fc69d0bd000\n"), Some(MapEvent { kind: MapKind::Map, address: Addr(0x7fc69d0bd000), size: 1600, }) ); } #[test] fn munmap_parse() { assert_eq!( parse_munmap_line("munmap(0x40ac8000, 4096) = 0\n"), Some(MapEvent { kind: MapKind::Unmap, address: Addr(0x40ac8000), size: 4096 }) ); assert_eq!( parse_munmap_line("munmap(0x7f6aae93f000, 1600)\n"), Some(MapEvent { kind: MapKind::Unmap, address: Addr(0x7f6aae93f000), size: 1600 }) ); }
//! Render commands for model files. use errors::Result; use util::cur::Cur; pub struct SkinTerm { pub weight: f32, pub stack_pos: u8, pub inv_bind_idx: u8, } /// A render command is analyzed into zero or more render ops (think micro-ops /// to a CPU instruction). pub enum Op { /// cur_matrix = matrix_stack[stack_pos] LoadMatrix { stack_pos: u8 }, /// matrix_stack[stack_pos] = cur_matrix StoreMatrix { stack_pos: u8 }, /// cur_matrix = cur_matrix * object_matrices[object_idx] MulObject { object_idx: u8 }, /// cur_matrix = ∑_{term} /// term.weight * /// matrix_stack[term.stack_pos] * /// inv_bind_matrices[term.inv_bind_idx] /// (ie. the skinning equation) Skin { terms: Box<[SkinTerm]> }, /// cur_matrix = cur_matrix * scale(up_scale) ScaleUp, /// cur_matrix = cur_matrix * scale(model.down_scale) ScaleDown, /// Bind materials[material_idx] for subsequent draw calls. BindMaterial { material_idx: u8 }, /// Draw pieces[piece_idx]. Draw { piece_idx: u8 }, } /// Parses a bytestream of render commands into a list of render ops. pub fn parse_render_cmds(mut cur: Cur) -> Result<Vec<Op>> { trace!("render commands @ {:#x}", cur.pos()); let mut ops: Vec<Op> = vec![]; loop { let (opcode, params) = next_opcode_params(&mut cur)?; trace!("cmd {:#2x} {:?}", opcode, params); match opcode { 0x00 => { // NOP } 0x01 => { // End render commands return Ok(ops); } 0x02 => { // Unknown // Here's what I know about it: // * there is always one of them in a model, after the initial matrix // stack setup but before the 0x03/0x04/0x05 command sequences // * the first parameter is num_objects - 1 (ie. the index of the last // object) // * the second parameter is always 1; if this 1 is changed to a zero // using a debugger, the model is not drawn (this is probably why // other people have called this "visibility") // * running it emits no GPU commands } 0x03 => { // Load a matrix from the stack ops.push(Op::LoadMatrix { stack_pos: params[0] }); } 0x04 | 0x24 | 0x44 => { // Bind a material ops.push(Op::BindMaterial { material_idx: params[0] }); } 0x05 => { // Draw a piece of the model ops.push(Op::Draw { piece_idx: params[0] }); } 0x06 | 0x26 | 0x46 | 0x66 => { // Multiply the current matrix by an object matrix, possibly // loading a matrix from the stack beforehand, and possibly // storing the result to a stack location after. let object_idx = params[0]; let _parent_id = params[1]; let _unknown = params[2]; let (store_pos, load_pos) = match opcode { 0x06 => (None, None), 0x26 => (Some(params[3]), None), 0x46 => (None, Some(params[3])), 0x66 => (Some(params[3]), Some(params[4])), _ => unreachable!(), }; if let Some(stack_pos) = load_pos { ops.push(Op::LoadMatrix { stack_pos }); } ops.push(Op::MulObject { object_idx }); if let Some(stack_pos) = store_pos { ops.push(Op::StoreMatrix { stack_pos }); } } 0x09 => { // Creates a matrix from the skinning equation and stores it to // a stack slot. The skinning equation is // // ∑ weight * matrix_stack[stack_pos] * inv_binds[inv_bind_idx] // // Note that vertices to which a skinning matrix are applied are // given in model space -- the inverse bind matrices bring it // into the local space of each of its influencing objects. // Normal vertices are given directly in the local space of the // object that gets applied to them. let store_pos = params[0]; let num_terms = params[1] as usize; let mut i = 2; let terms = (0..num_terms) .map(|_| { let stack_pos = params[i]; let inv_bind_idx = params[i + 1]; let weight = params[i + 2] as f32 / 256.0; // denormalize i += 3; SkinTerm { weight, stack_pos, inv_bind_idx } }) .collect::<Vec<_>>() .into_boxed_slice(); ops.push(Op::Skin { terms }); ops.push(Op::StoreMatrix { stack_pos: store_pos }); } 0x0b => { // Scale up by a per-model constant. ops.push(Op::ScaleUp); } 0x2b => { // Scale down by a per-model constant. ops.push(Op::ScaleDown); } _ => { debug!("skipping unknown render command {:#x}", opcode); } } } } /// Fetch the next opcode and its parameters from the bytestream. fn next_opcode_params<'a>(cur: &mut Cur<'a>) -> Result<(u8, &'a [u8])> { let opcode = cur.next::<u8>()?; // The only variable-length command if opcode == 0x09 { // 1 byte + 1 byte (count) + count u8[3]s let count = cur.nth::<u8>(1)?; let params_len = 1 + 1 + 3 * count; let params = cur.next_n_u8s(params_len as usize)?; return Ok((opcode, params)); } let params_len = match opcode { 0x00 => 0, 0x01 => 0, 0x02 => 2, 0x03 => 1, 0x04 => 1, 0x05 => 1, 0x06 => 3, 0x07 => 1, 0x08 => 1, 0x0b => 0, 0x0c => 2, 0x0d => 2, 0x24 => 1, 0x26 => 4, 0x2b => 0, 0x40 => 0, 0x44 => 1, 0x46 => 4, 0x47 => 2, 0x66 => 5, 0x80 => 0, _ => bail!("unknown render command opcode: {:#x}", opcode), }; let params = cur.next_n_u8s(params_len)?; Ok((opcode, params)) }
use crate::model::Move; use crate::utils::Bound; use priority_queue::PriorityQueue; use core::fmt; use core::fmt::Write; use core::cmp::Ordering; use std::collections::HashMap; /// Decartes coordinates, (x, y) /// make our own coordinate system, in the name of René Descartes /// ^ y /// | /// | /// +-------> x #[derive(Clone, Copy, Eq, PartialEq, Hash, PartialOrd)] pub struct P(pub i16, pub i16); impl Ord for P { fn cmp(&self, other: &Self) -> Ordering { if self.0 < other.0 { Ordering::Less } else if self.0 > other.0 { Ordering::Greater } else { self.1.cmp(&other.1) } } } impl fmt::Debug for P { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_char('(')?; fmt.write_str(&self.0.to_string())?; fmt.write_char(',')?; fmt.write_str(&self.1.to_string())?; fmt.write_char(')')?; Ok(()) } } impl fmt::Display for P { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_char('(')?; fmt.write_str(&self.0.to_string())?; fmt.write_char(',')?; fmt.write_str(&self.1.to_string())?; fmt.write_char(')')?; Ok(()) } } pub fn distance(p: &P, q: &P) -> i32 { ((p.0 - q.0).abs() as i32) + ((p.1 - q.1).abs() as i32) } pub fn may_be_selected(base: P, arrow: P, cur: P) -> bool { let P(xb, yb) = base; let P(xa, ya) = arrow; let P(xc, yc) = cur; // 4 3 2 // 5 9 1 // 6 7 8 if false { false } else if xb == xa && yb < ya { ya <= yc } else if xb > xa && yb < ya { xc <= xa && ya <= yc } else if xb > xa && yb == ya { xc <= xa } else if xb > xa && yb > ya { xc <= xa && yc <= ya } else if xb == xa && yb > ya { yc <= ya } else if xb < xa && yb > ya { xa <= xc && yc <= ya } else if xb < xa && yb == ya { xa <= xc } else if xb < xa && yb < ya { xa <= xc && ya <= yc } else if xb == xa && yb < ya { ya <= yc } else { xa != xc && ya != yc } } pub fn direction(src: &P, dst: &P) -> Move { let P(sx, sy) = src; let P(dx, dy) = dst; if dx == sx && dy <= sy { Move::Down } else if dx == sx && dy > sy { Move::Up } else if dx < sx { Move::Left } else { Move::Right } } pub fn build_path(src: &P, dst: &P, horz_first: bool) -> Vec<P> { fn h(y: i16, a: i16, b: i16) -> Vec<P> { if a < b { ((a + 1)..=b).map(|x| P(x, y)).collect() } else if b < a { (b..a).map(|x| P(x, y)).rev().collect() } else { vec![] } } fn v(x: i16, a: i16, b: i16) -> Vec<P> { if a < b { ((a + 1)..=b).map(|y| P(x, y)).collect() } else if b < a { (b..a).map(|y| P(x, y)).rev().collect() } else { vec![] } } let P(xs, ys) = src; let P(xd, yd) = dst; let mut path = vec![]; if horz_first { // do ← → then ↑ ↓ path.append(&mut h(*ys, *xs, *xd)); path.append(&mut v(*xd, *ys, *yd)); } else { // do ↑ ↓ then ← → path.append(&mut v(*xs, *ys, *yd)); path.append(&mut h(*yd, *xs, *xd)); }; path } pub fn find_closest(m: i16, n: i16, src: &P, max: i16, predicate: impl Fn(&P) -> bool) -> Option<P> { let P(xs, ys) = src; let bounded = |p: &P| { let P(x, y) = *p; if 0 <= x && x < n && 0 <= y && y < m { *p } else { P(x.bound(0, n - 1), y.bound(0, m - 1)) } }; for r in 1..max { for k in 0..r { let ps = [ P(xs - k, ys + r - k), P(xs - r + k, ys - k), P(xs + k, ys - r + k), P(xs + r - k, ys + k), ]; let opt = ps.iter().map(bounded).find(&predicate); if opt.is_some() { return opt; } } } None } const NEIGHBORS: &[(i16, i16)] = &[(0, -1), (-1, 0), (0, 1), (1, 0)]; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct Weight { // h_score: f32, // heuristic distance from the end node pub f_score: i32, // g + h pub g_score: i32, // distance from the starting node pub parent: P, // the point where we came from } impl PartialOrd for Weight { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.f_score.cmp(&other.f_score).reverse()) } } impl Ord for Weight { fn cmp(&self, other: &Self) -> Ordering { // partial_cmp for W is never None self.partial_cmp(&other).unwrap() } } // for debug you can add pub fn a_star_find(src: &P, dst: &P, is_accessible: impl Fn(&P) -> bool, heuristic: impl Fn(&P, &P) -> i32, mut logger: Option<impl FnMut(&PriorityQueue<P, Weight>, &HashMap<P, P>) -> ()>, ) -> Option<Vec<P>> { let mut open_list: PriorityQueue<P, Weight> = PriorityQueue::new(); let mut closed_list: HashMap<P, P> = HashMap::new(); // 1. Take the start node and put it on the open list open_list.push(*src, Weight { f_score: 0, g_score: 0, parent: *src}); // 2. While there are nodes in the open list: while !open_list.is_empty() { // 3. Pick the node from the open list having the smallest `f` score. // Put it on the closed list (you don't want to consider it again). let (cur_p, cur_w) = open_list.pop().unwrap(); closed_list.insert(cur_p, cur_w.parent); // 4. if reached the end position, construct the path and return it if cur_p == *dst { return backtrace(&closed_list, *dst); } // 5. For each neighbor (adjacent cell) which isn't in the closed list: // a. Set its parent to current node. // b. Calculate `g` score (distance from starting node to this neighbor) and add it to the open list // c. Calculate `f` score by adding heuristics to the `g` value. let accessible_neigh = NEIGHBORS.iter() .map(|(dx, dy)| P(cur_p.0 + dx, cur_p.1 + dy)) .filter(|p| !closed_list.contains_key(&p) && is_accessible(&p)); for np in accessible_neigh { // the neighbour could be already accessible from the different node let g_score = cur_w.g_score + if np != cur_p { 1 } else { 0 }; let f_score = g_score + heuristic(&np, &dst); let parent = cur_p; let w_opt = open_list.get_priority(&np).map(|w| w.clone()); match w_opt { Some(w) => { if g_score < w.g_score { // the neighbour can be reached with smaller cost open_list.change_priority(&np, Weight { f_score, g_score, parent }); }; // otherwise don't touch the neighbour, it will be taken by open_list.pop() }, None => { // the neighbour is the new open_list.push(np, Weight { f_score, g_score, parent }); }, }; } if let Some(ref mut log) = logger { log(&open_list, &closed_list); } } None } pub fn backtrace(closed_list: &HashMap<P, P>, dst: P) -> Option<Vec<P>> { let mut p = dst; let mut result = vec![p]; while let Some(parent) = closed_list.get(&p) { if p == *parent { // for src we have src.par = src break; } result.push(*parent); p = *parent; } result.reverse(); Some(result) }
#[derive(Debug, Clone)] pub struct Redirect { path: String, is_over:bool } impl Redirect { pub fn new(path:&str, is_over:bool) -> Self { Self { path:path.to_string(), is_over, } } pub fn get_redirect_path(&self) -> &str { &self.path } pub fn get_is_over(&self) -> bool { self.is_over } }
// Convert hex to base64 // The string: // // 49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d // Should produce: // // SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t // So go ahead and make that happen. You'll need to use this code for the rest of the exercises. // // Cryptopals Rule // Always operate on raw bytes, never on encoded strings. Only use hex and base64 for pretty-printing. #[macro_use] extern crate log; extern crate cryptopalslib; #[cfg(not(test))] fn main() { println!("Set 1, Challenge 1"); let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"; println!("input string: {:?}", input); let output = cryptopalslib::convert::hex_to_base64(input); println!("output string: {:?}", output); } #[cfg(test)] mod set1challenge1 { extern crate cryptopalslib; #[test] fn challenge() { let output = cryptopalslib::convert::hex_to_base64("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"); assert_eq!(output, "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"); } }
use std::{ fs::File, io::{self, Read, Seek, SeekFrom, Write}, }; pub trait ReadSeek: Read + Seek + Send + Sync {} impl<T> ReadSeek for T where T: Read + Seek + Send + Sync {} pub struct OffsetSeeker { file: File, offset: u64, cursor: u64, length: u64, } impl OffsetSeeker { pub fn new(mut file: File, offset: u64, length: u64) -> io::Result<Self> { file.seek(SeekFrom::Start(offset))?; Ok(OffsetSeeker { file, offset, cursor: 0, length, }) } } impl Seek for OffsetSeeker { fn seek(&mut self, seek_from: SeekFrom) -> io::Result<u64> { let new_cursor = match seek_from { SeekFrom::Start(i) => i as i64, SeekFrom::End(i) => self.length as i64 + i, SeekFrom::Current(i) => self.cursor as i64 + i, }; if new_cursor < 0 { Err(io::Error::new( io::ErrorKind::Other, "Cannot seek before byte 0.", )) } else { self.cursor = if new_cursor <= self.length as i64 { new_cursor as u64 } else { self.length }; self.file.seek(SeekFrom::Start(self.cursor + self.offset))?; Ok(self.cursor) } } } impl Read for OffsetSeeker { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let resized_buf = if self.cursor + buf.len() as u64 > self.length { &mut buf[..(self.length - self.cursor) as usize] } else { buf }; let result = self.file.read(resized_buf)?; self.cursor += result as u64; Ok(result) } } pub struct SeekableVec { cursor: usize, vec: Vec<u8>, } impl SeekableVec { pub fn new(vec: Vec<u8>) -> Self { SeekableVec { cursor: 0, vec } } pub fn into_vec(self) -> Vec<u8> { self.vec } fn validate_and_set_cursor(&mut self, new_cursor: i64) -> io::Result<u64> { if new_cursor < 0 { Err(io::Error::new( io::ErrorKind::Other, "Cannot seek before byte 0.", )) } else { self.cursor = if new_cursor <= self.vec.len() as i64 { new_cursor as usize } else { self.vec.len() }; Ok(self.cursor as u64) } } fn read_byte(&mut self) -> Option<u8> { if self.cursor == self.vec.len() { None } else { let r = Some(self.vec[self.cursor]); self.cursor += 1; r } } fn write_byte(&mut self, byte: u8) { if self.cursor == self.vec.len() { self.vec.push(byte); } else { self.vec[self.cursor] = byte; } self.cursor += 1; } } impl Seek for SeekableVec { fn seek(&mut self, seek_from: SeekFrom) -> io::Result<u64> { match seek_from { SeekFrom::Start(i) => self.validate_and_set_cursor(i as i64), SeekFrom::End(i) => self.validate_and_set_cursor(self.vec.len() as i64 + i), SeekFrom::Current(i) => self.validate_and_set_cursor(self.cursor as i64 + i), } } } impl Read for SeekableVec { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { for (i, v) in buf.iter_mut().enumerate() { match self.read_byte() { Some(byte) => *v = byte, None => return Ok(i), } } Ok(buf.len()) } } impl Write for SeekableVec { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { for byte in buf { self.write_byte(*byte); } Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn seekable_vec_no_negative_cursor() { { let mut s = SeekableVec::new(Vec::new()); let result = s.seek(SeekFrom::End(-1)); assert_eq!(result.is_err(), true); assert_eq!( format!("{}", result.err().unwrap()), "Cannot seek before byte 0." ); } { let mut s = SeekableVec::new(Vec::new()); s.write_all(b"abc").unwrap(); let result = s.seek(SeekFrom::End(-4)); assert_eq!(result.is_err(), true); assert_eq!( format!("{}", result.err().unwrap()), "Cannot seek before byte 0." ); } } #[test] fn seekable_vec_past_end_ok() { { let mut s = SeekableVec::new(Vec::new()); let result = s.seek(SeekFrom::End(1)); assert_eq!(result.is_ok(), true); assert_eq!(result.unwrap(), 0); } { let mut s = SeekableVec::new(Vec::new()); s.write_all(b"abc").unwrap(); let result = s.seek(SeekFrom::End(3)); assert_eq!(result.is_ok(), true); assert_eq!(result.unwrap(), 3); } } #[test] fn seekable_vec_random_reads_writes() { let mut s = SeekableVec::new(Vec::new()); s.write_all(b"abcdef").unwrap(); s.seek(SeekFrom::Start(1)).unwrap(); s.write_all(b"B").unwrap(); s.seek(SeekFrom::End(-3)).unwrap(); s.write_all(b"D").unwrap(); s.seek(SeekFrom::Current(1)).unwrap(); s.write_all(b"F").unwrap(); s.seek(SeekFrom::End(0)).unwrap(); s.write_all(b"g").unwrap(); let mut result_string = String::new(); s.seek(SeekFrom::Start(0)).unwrap(); s.read_to_string(&mut result_string).unwrap(); assert_eq!(result_string, "aBcDeFg"); assert_eq!( s.into_vec() .into_iter() .map(|b| b.into()) .collect::<Vec<char>>(), vec!['a', 'B', 'c', 'D', 'e', 'F', 'g'] ) } }
//! # System Control //! //! The SYSCTL peripheral controls clocks and power. //! //! The TM4C123x can be clocked from the Main Oscillator or the PLL, through a //! divider. The Main Oscillator can be either the internal 16 MHz precision //! oscillator, a 4 MHz derivation of the same, or an external crystal. //! //! SYSCTL includes the following registers: //! //! * Device ID (class, major, minor, family, package, temperature range, ) //! * Brown-out reset control //! * Brown-out/PLL interrupt control //! * Reset cause //! * Run-time clock configuration //! * GPIO high-performance bus control //! * System Properties //! * Registers to indicate whether peripherals are present //! * Registers to reset peripherals //! * Registers to enable/disable clocking of peripherals //! //! See the LM4F120 datasheet, page 228 for a full list. use super::bb; use cortex_m::asm::nop; use time::{Hertz, U32Ext}; use tm4c123x; /// Constrained SYSCTL peripheral. pub struct Sysctl { /// Power control methods will require `&mut this.power_control` to /// prevent them from running concurrently. pub power_control: PowerControl, /// Clock configuration will consume this and give you `Clocks`. pub clock_setup: ClockSetup, } /// Used to gate access to the run-time power control features of the chip. pub struct PowerControl { _0: (), } /// Used to configure the clock generators. pub struct ClockSetup { /// The system oscillator configuration pub oscillator: Oscillator, // Make this type uncreatable _0: (), } /// Selects the system oscillator source #[derive(Clone, Copy)] pub enum Oscillator { /// Use the main oscillator (with the given crystal), into the PLL or a clock divider Main(CrystalFrequency, SystemClock), /// Use the 16 MHz precision internal oscillator, into the PLL or a clock divider PrecisionInternal(SystemClock), /// Use the 16 MHz precision internal oscillator, divided down to 4 MHz /// and then divided down again by the given value. PrecisionInternalDiv4(Divider), /// Use the 30 kHz internal oscillator, divided by the given value. LowFrequencyInternal(Divider), } /// Selects the source for the system clock #[derive(Clone, Copy)] pub enum SystemClock { /// Clock the system direct from the system oscillator UseOscillator(Divider), /// Clock the system from the PLL (which is driven by the system /// oscillator), divided down from 400MHz to the given frequency. UsePll(PllOutputFrequency), } /// Selects which crystal is fitted to the XOSC pins. #[derive(Clone, Copy)] pub enum CrystalFrequency { /// 4 MHz _4mhz, /// 4.096 MHz _4_09mhz, /// 4.9152 MHz _4_91mhz, /// 5 MHz _5mhz, /// 5.12 MHz _5_12mhz, /// 6 MHz _6mhz, /// 6.144 MHz _6_14mhz, /// 7.3728 MHz _7_37mhz, /// 8 MHz _8mhz, /// 8.192 MHz _8_19mhz, /// 10 MHz _10mhz, /// 12 MHz _12mhz, /// 12.288 MHz _12_2mhz, /// 13.56 MHz _13_5mhz, /// 14.31818 MHz _14_3mhz, /// 16 MHz _16mhz, /// 16.384 MHz _16_3mhz, /// 18.0 MHz (USB) _18mhz, /// 20.0 MHz (USB) _20mhz, /// 24.0 MHz (USB) _24mhz, /// 25.0 MHz (USB) _25mhz, } /// Selects what to divide the PLL's 400MHz down to. #[derive(Clone, Copy)] pub enum PllOutputFrequency { /// 80.00 MHz _80_00mhz = 0, /// 66.67 MHz _66_67mhz = 2, /// 50 MHz _50_00mhz = 3, /// 40 MHz _40_00mhz = 4, /// 33.33 MHz _33_33mhz = 5, /// 28.57 MHz _28_57mhz = 6, /// 25 MHz _25mhz = 7, /// 22.22 MHz _22_22mhz = 8, /// 20 MHz _20mhz = 9, /// 18.18 MHz _18_18mhz = 10, /// 16.67 MHz _16_67mhz = 11, /// 15.38 MHz _15_38mhz = 12, /// 14.29 MHz _14_29mhz = 13, /// 13.33 MHz _13_33mhz = 14, /// 12.5 MHz _12_5mhz = 15, } /// Selects how much to divide the system oscillator down. #[derive(Clone, Copy)] pub enum Divider { /// Divide by 1 _1 = 1, /// Divide by 2 _2 = 2, /// Divide by 3 _3 = 3, /// Divide by 4 _4 = 4, /// Divide by 5 _5 = 5, /// Divide by 6 _6 = 6, /// Divide by 7 _7 = 7, /// Divide by 8 _8 = 8, /// Divide by 9 _9 = 9, /// Divide by 10 _10 = 10, /// Divide by 11 _11 = 11, /// Divide by 12 _12 = 12, /// Divide by 13 _13 = 13, /// Divide by 14 _14 = 14, /// Divide by 15 _15 = 15, /// Divide by 16 _16 = 16, } /// Frozen clock frequencies /// /// The existence of this value indicates that the clock configuration can no longer be changed #[derive(Clone, Copy)] pub struct Clocks { /// System oscillator clock speed pub osc: Hertz, /// System clock speed pub sysclk: Hertz, } /// List of peripherals that can be enabled or disabled #[derive(Copy, Clone)] pub enum Domain { /// Watchdog 1 Watchdog1, /// Watchdog 0 Watchdog0, /// 32/16-bit Timer 5 Timer5, /// 32/16-bit Timer 4 Timer4, /// 32/16-bit Timer 3 Timer3, /// 32/16-bit Timer 2 Timer2, /// 32/16-bit Timer 1 Timer1, /// 32/16-bit Timer 0 Timer0, /// GPIO F GpioF, /// GPIO E GpioE, /// GPIO D GpioD, /// GPIO C GpioC, /// GPIO B GpioB, /// GPIO A GpioA, /// µDMA MicroDma, /// Hibernation Hibernation, /// UART 7 Uart7, /// UART 6 Uart6, /// UART 5 Uart5, /// UART 4 Uart4, /// UART 3 Uart3, /// UART 2 Uart2, /// UART 1 Uart1, /// UART 0 Uart0, /// SSI 3 Ssi3, /// SSI 2 Ssi2, /// SSI 1 Ssi1, /// SSI 0 Ssi0, /// I2C 3 I2c3, /// I2C 2 I2c2, /// I2C 1 I2c1, /// I2C 0 I2c0, /// USB Usb, /// CAN Can, /// ADC 1 Adc1, /// ADC 0 Adc0, /// Analog Comparator AnalogComparator, /// EEPROM Eeprom, /// 64/32-bit Timer 5 WideTimer5, /// 64/32-bit Timer 4 WideTimer4, /// 64/32-bit Timer 3 WideTimer3, /// 64/32-bit Timer 2 WideTimer2, /// 64/32-bit Timer 1 WideTimer1, /// 64/32-bit Timer 0 WideTimer0, } #[derive(Copy, Clone)] /// Select in which mode the peripheral should be affected pub enum RunMode { /// Run mode Run, /// Sleep mode (i.e. WFI is being executed) Sleep, /// Deep-Sleep mode (i.e. WFI is being executed with SLEEP DEEP bit set) DeepSleep, } #[derive(Copy, Clone)] /// Select whether the peripheral should be on or off pub enum PowerState { /// Turn peripheral clocks/power off Off, /// Turn peripheral clocks/power on On, } /// Reset a peripheral pub fn reset(_lock: &PowerControl, pd: Domain) { // We use bit-banding to make an atomic write, so this is safe let p = unsafe { &*tm4c123x::SYSCTL::ptr() }; match pd { Domain::Watchdog1 => unsafe { bb::toggle_bit(&p.srwd, 1); bb::spin_bit(&p.prwd, 1); }, Domain::Watchdog0 => unsafe { bb::toggle_bit(&p.srwd, 0); bb::spin_bit(&p.prwd, 0); }, Domain::Timer5 => unsafe { bb::toggle_bit(&p.srtimer, 5); bb::spin_bit(&p.prtimer, 5); }, Domain::Timer4 => unsafe { bb::toggle_bit(&p.srtimer, 4); bb::spin_bit(&p.prtimer, 4); }, Domain::Timer3 => unsafe { bb::toggle_bit(&p.srtimer, 3); bb::spin_bit(&p.prtimer, 3); }, Domain::Timer2 => unsafe { bb::toggle_bit(&p.srtimer, 2); bb::spin_bit(&p.prtimer, 2); }, Domain::Timer1 => unsafe { bb::toggle_bit(&p.srtimer, 1); bb::spin_bit(&p.prtimer, 1); }, Domain::Timer0 => unsafe { bb::toggle_bit(&p.srtimer, 0); bb::spin_bit(&p.prtimer, 0); }, Domain::GpioF => unsafe { bb::toggle_bit(&p.srgpio, 5); bb::spin_bit(&p.prgpio, 5); }, Domain::GpioE => unsafe { bb::toggle_bit(&p.srgpio, 4); bb::spin_bit(&p.prgpio, 4); }, Domain::GpioD => unsafe { bb::toggle_bit(&p.srgpio, 3); bb::spin_bit(&p.prgpio, 3); }, Domain::GpioC => unsafe { bb::toggle_bit(&p.srgpio, 2); bb::spin_bit(&p.prgpio, 2); }, Domain::GpioB => unsafe { bb::toggle_bit(&p.srgpio, 1); bb::spin_bit(&p.prgpio, 1); }, Domain::GpioA => unsafe { bb::toggle_bit(&p.srgpio, 0); bb::spin_bit(&p.prgpio, 0); }, Domain::MicroDma => unsafe { bb::toggle_bit(&p.srdma, 0); bb::spin_bit(&p.prdma, 0); }, Domain::Hibernation => unsafe { bb::toggle_bit(&p.srhib, 0); bb::spin_bit(&p.prhib, 0); }, Domain::Uart7 => unsafe { bb::toggle_bit(&p.sruart, 7); bb::spin_bit(&p.pruart, 7); }, Domain::Uart6 => unsafe { bb::toggle_bit(&p.sruart, 6); bb::spin_bit(&p.pruart, 6); }, Domain::Uart5 => unsafe { bb::toggle_bit(&p.sruart, 5); bb::spin_bit(&p.pruart, 5); }, Domain::Uart4 => unsafe { bb::toggle_bit(&p.sruart, 4); bb::spin_bit(&p.pruart, 4); }, Domain::Uart3 => unsafe { bb::toggle_bit(&p.sruart, 3); bb::spin_bit(&p.pruart, 3); }, Domain::Uart2 => unsafe { bb::toggle_bit(&p.sruart, 2); bb::spin_bit(&p.pruart, 2); }, Domain::Uart1 => unsafe { bb::toggle_bit(&p.sruart, 1); bb::spin_bit(&p.pruart, 1); }, Domain::Uart0 => unsafe { bb::toggle_bit(&p.sruart, 0); bb::spin_bit(&p.pruart, 0); }, Domain::Ssi3 => unsafe { bb::toggle_bit(&p.srssi, 3); bb::spin_bit(&p.prssi, 3); }, Domain::Ssi2 => unsafe { bb::toggle_bit(&p.srssi, 2); bb::spin_bit(&p.prssi, 2); }, Domain::Ssi1 => unsafe { bb::toggle_bit(&p.srssi, 1); bb::spin_bit(&p.prssi, 1); }, Domain::Ssi0 => unsafe { bb::toggle_bit(&p.srssi, 0); bb::spin_bit(&p.prssi, 0); }, Domain::I2c3 => unsafe { bb::toggle_bit(&p.sri2c, 3); bb::spin_bit(&p.pri2c, 3); }, Domain::I2c2 => unsafe { bb::toggle_bit(&p.sri2c, 2); bb::spin_bit(&p.pri2c, 2); }, Domain::I2c1 => unsafe { bb::toggle_bit(&p.sri2c, 1); bb::spin_bit(&p.pri2c, 1); }, Domain::I2c0 => unsafe { bb::toggle_bit(&p.sri2c, 0); bb::spin_bit(&p.pri2c, 0); }, Domain::Usb => unsafe { bb::toggle_bit(&p.srusb, 0); bb::spin_bit(&p.prusb, 0); }, Domain::Can => unsafe { bb::toggle_bit(&p.srcan, 0); bb::spin_bit(&p.prcan, 0); }, Domain::Adc1 => unsafe { bb::toggle_bit(&p.sradc, 1); bb::spin_bit(&p.pradc, 1); }, Domain::Adc0 => unsafe { bb::toggle_bit(&p.sradc, 0); bb::spin_bit(&p.pradc, 0); }, Domain::AnalogComparator => unsafe { bb::toggle_bit(&p.sracmp, 0); bb::spin_bit(&p.pracmp, 0); }, Domain::Eeprom => unsafe { bb::toggle_bit(&p.sreeprom, 0); bb::spin_bit(&p.preeprom, 0); }, Domain::WideTimer5 => unsafe { bb::toggle_bit(&p.srwtimer, 5); bb::spin_bit(&p.prwtimer, 5); }, Domain::WideTimer4 => unsafe { bb::toggle_bit(&p.srwtimer, 4); bb::spin_bit(&p.prwtimer, 4); }, Domain::WideTimer3 => unsafe { bb::toggle_bit(&p.srwtimer, 3); bb::spin_bit(&p.prwtimer, 3); }, Domain::WideTimer2 => unsafe { bb::toggle_bit(&p.srwtimer, 2); bb::spin_bit(&p.prwtimer, 2); }, Domain::WideTimer1 => unsafe { bb::toggle_bit(&p.srwtimer, 1); bb::spin_bit(&p.prwtimer, 1); }, Domain::WideTimer0 => unsafe { bb::toggle_bit(&p.srwtimer, 0); bb::spin_bit(&p.prwtimer, 0); }, } } /// Activate or De-Activate clocks and power to the given peripheral in the /// given run mode. /// /// We take a reference to PowerControl as a permission check. We don't need /// an &mut reference as we use atomic writes in the bit-banding area so it's /// interrupt safe. pub fn control_power(_lock: &PowerControl, pd: Domain, run_mode: RunMode, state: PowerState) { let on = match state { PowerState::On => true, PowerState::Off => false, }; match run_mode { RunMode::Run => control_run_power(pd, on), RunMode::Sleep => control_sleep_power(pd, on), RunMode::DeepSleep => control_deep_sleep_power(pd, on), } // Section 5.2.6 - "There must be a delay of 3 system clocks after a // peripheral module clock is enabled in the RCGC register before any // module registers are accessed." nop(); nop(); nop(); } fn control_run_power(pd: Domain, on: bool) { // We use bit-banding to make an atomic write, so this is safe let p = unsafe { &*tm4c123x::SYSCTL::ptr() }; match pd { Domain::Watchdog1 => unsafe { bb::change_bit(&p.rcgcwd, 1, on) }, Domain::Watchdog0 => unsafe { bb::change_bit(&p.rcgcwd, 0, on) }, Domain::Timer5 => unsafe { bb::change_bit(&p.rcgctimer, 5, on) }, Domain::Timer4 => unsafe { bb::change_bit(&p.rcgctimer, 4, on) }, Domain::Timer3 => unsafe { bb::change_bit(&p.rcgctimer, 3, on) }, Domain::Timer2 => unsafe { bb::change_bit(&p.rcgctimer, 2, on) }, Domain::Timer1 => unsafe { bb::change_bit(&p.rcgctimer, 1, on) }, Domain::Timer0 => unsafe { bb::change_bit(&p.rcgctimer, 0, on) }, Domain::GpioF => unsafe { bb::change_bit(&p.rcgcgpio, 5, on) }, Domain::GpioE => unsafe { bb::change_bit(&p.rcgcgpio, 4, on) }, Domain::GpioD => unsafe { bb::change_bit(&p.rcgcgpio, 3, on) }, Domain::GpioC => unsafe { bb::change_bit(&p.rcgcgpio, 2, on) }, Domain::GpioB => unsafe { bb::change_bit(&p.rcgcgpio, 1, on) }, Domain::GpioA => unsafe { bb::change_bit(&p.rcgcgpio, 0, on) }, Domain::MicroDma => unsafe { bb::change_bit(&p.rcgcdma, 0, on) }, Domain::Hibernation => unsafe { bb::change_bit(&p.rcgchib, 0, on) }, Domain::Uart7 => unsafe { bb::change_bit(&p.rcgcuart, 7, on) }, Domain::Uart6 => unsafe { bb::change_bit(&p.rcgcuart, 6, on) }, Domain::Uart5 => unsafe { bb::change_bit(&p.rcgcuart, 5, on) }, Domain::Uart4 => unsafe { bb::change_bit(&p.rcgcuart, 4, on) }, Domain::Uart3 => unsafe { bb::change_bit(&p.rcgcuart, 3, on) }, Domain::Uart2 => unsafe { bb::change_bit(&p.rcgcuart, 2, on) }, Domain::Uart1 => unsafe { bb::change_bit(&p.rcgcuart, 1, on) }, Domain::Uart0 => unsafe { bb::change_bit(&p.rcgcuart, 0, on) }, Domain::Ssi3 => unsafe { bb::change_bit(&p.rcgcssi, 3, on) }, Domain::Ssi2 => unsafe { bb::change_bit(&p.rcgcssi, 2, on) }, Domain::Ssi1 => unsafe { bb::change_bit(&p.rcgcssi, 1, on) }, Domain::Ssi0 => unsafe { bb::change_bit(&p.rcgcssi, 0, on) }, Domain::I2c3 => unsafe { bb::change_bit(&p.rcgci2c, 3, on) }, Domain::I2c2 => unsafe { bb::change_bit(&p.rcgci2c, 2, on) }, Domain::I2c1 => unsafe { bb::change_bit(&p.rcgci2c, 1, on) }, Domain::I2c0 => unsafe { bb::change_bit(&p.rcgci2c, 0, on) }, Domain::Usb => unsafe { bb::change_bit(&p.rcgcusb, 0, on) }, Domain::Can => unsafe { bb::change_bit(&p.rcgccan, 0, on) }, Domain::Adc1 => unsafe { bb::change_bit(&p.rcgcadc, 1, on) }, Domain::Adc0 => unsafe { bb::change_bit(&p.rcgcadc, 0, on) }, Domain::AnalogComparator => unsafe { bb::change_bit(&p.rcgcacmp, 0, on) }, Domain::Eeprom => unsafe { bb::change_bit(&p.rcgceeprom, 0, on) }, Domain::WideTimer5 => unsafe { bb::change_bit(&p.rcgcwtimer, 5, on) }, Domain::WideTimer4 => unsafe { bb::change_bit(&p.rcgcwtimer, 4, on) }, Domain::WideTimer3 => unsafe { bb::change_bit(&p.rcgcwtimer, 3, on) }, Domain::WideTimer2 => unsafe { bb::change_bit(&p.rcgcwtimer, 2, on) }, Domain::WideTimer1 => unsafe { bb::change_bit(&p.rcgcwtimer, 1, on) }, Domain::WideTimer0 => unsafe { bb::change_bit(&p.rcgcwtimer, 0, on) }, } } fn control_sleep_power(pd: Domain, on: bool) { // We use bit-banding to make an atomic write, so this is safe let p = unsafe { &*tm4c123x::SYSCTL::ptr() }; match pd { Domain::Watchdog1 => unsafe { bb::change_bit(&p.scgcwd, 1, on) }, Domain::Watchdog0 => unsafe { bb::change_bit(&p.scgcwd, 0, on) }, Domain::Timer5 => unsafe { bb::change_bit(&p.scgctimer, 5, on) }, Domain::Timer4 => unsafe { bb::change_bit(&p.scgctimer, 4, on) }, Domain::Timer3 => unsafe { bb::change_bit(&p.scgctimer, 3, on) }, Domain::Timer2 => unsafe { bb::change_bit(&p.scgctimer, 2, on) }, Domain::Timer1 => unsafe { bb::change_bit(&p.scgctimer, 1, on) }, Domain::Timer0 => unsafe { bb::change_bit(&p.scgctimer, 0, on) }, Domain::GpioF => unsafe { bb::change_bit(&p.scgcgpio, 5, on) }, Domain::GpioE => unsafe { bb::change_bit(&p.scgcgpio, 4, on) }, Domain::GpioD => unsafe { bb::change_bit(&p.scgcgpio, 3, on) }, Domain::GpioC => unsafe { bb::change_bit(&p.scgcgpio, 2, on) }, Domain::GpioB => unsafe { bb::change_bit(&p.scgcgpio, 1, on) }, Domain::GpioA => unsafe { bb::change_bit(&p.scgcgpio, 0, on) }, Domain::MicroDma => unsafe { bb::change_bit(&p.scgcdma, 0, on) }, Domain::Hibernation => unsafe { bb::change_bit(&p.scgchib, 0, on) }, Domain::Uart7 => unsafe { bb::change_bit(&p.scgcuart, 7, on) }, Domain::Uart6 => unsafe { bb::change_bit(&p.scgcuart, 6, on) }, Domain::Uart5 => unsafe { bb::change_bit(&p.scgcuart, 5, on) }, Domain::Uart4 => unsafe { bb::change_bit(&p.scgcuart, 4, on) }, Domain::Uart3 => unsafe { bb::change_bit(&p.scgcuart, 3, on) }, Domain::Uart2 => unsafe { bb::change_bit(&p.scgcuart, 2, on) }, Domain::Uart1 => unsafe { bb::change_bit(&p.scgcuart, 1, on) }, Domain::Uart0 => unsafe { bb::change_bit(&p.scgcuart, 0, on) }, Domain::Ssi3 => unsafe { bb::change_bit(&p.scgcssi, 3, on) }, Domain::Ssi2 => unsafe { bb::change_bit(&p.scgcssi, 2, on) }, Domain::Ssi1 => unsafe { bb::change_bit(&p.scgcssi, 1, on) }, Domain::Ssi0 => unsafe { bb::change_bit(&p.scgcssi, 0, on) }, Domain::I2c3 => unsafe { bb::change_bit(&p.scgci2c, 3, on) }, Domain::I2c2 => unsafe { bb::change_bit(&p.scgci2c, 2, on) }, Domain::I2c1 => unsafe { bb::change_bit(&p.scgci2c, 1, on) }, Domain::I2c0 => unsafe { bb::change_bit(&p.scgci2c, 0, on) }, Domain::Usb => unsafe { bb::change_bit(&p.scgcusb, 0, on) }, Domain::Can => unsafe { bb::change_bit(&p.scgccan, 0, on) }, Domain::Adc1 => unsafe { bb::change_bit(&p.scgcadc, 1, on) }, Domain::Adc0 => unsafe { bb::change_bit(&p.scgcadc, 0, on) }, Domain::AnalogComparator => unsafe { bb::change_bit(&p.scgcacmp, 0, on) }, Domain::Eeprom => unsafe { bb::change_bit(&p.scgceeprom, 0, on) }, Domain::WideTimer5 => unsafe { bb::change_bit(&p.scgcwtimer, 5, on) }, Domain::WideTimer4 => unsafe { bb::change_bit(&p.scgcwtimer, 4, on) }, Domain::WideTimer3 => unsafe { bb::change_bit(&p.scgcwtimer, 3, on) }, Domain::WideTimer2 => unsafe { bb::change_bit(&p.scgcwtimer, 2, on) }, Domain::WideTimer1 => unsafe { bb::change_bit(&p.scgcwtimer, 1, on) }, Domain::WideTimer0 => unsafe { bb::change_bit(&p.scgcwtimer, 0, on) }, } } fn control_deep_sleep_power(pd: Domain, on: bool) { // We use bit-banding to make an atomic write, so this is safe let p = unsafe { &*tm4c123x::SYSCTL::ptr() }; match pd { Domain::Watchdog1 => unsafe { bb::change_bit(&p.dcgcwd, 1, on) }, Domain::Watchdog0 => unsafe { bb::change_bit(&p.dcgcwd, 0, on) }, Domain::Timer5 => unsafe { bb::change_bit(&p.dcgctimer, 5, on) }, Domain::Timer4 => unsafe { bb::change_bit(&p.dcgctimer, 4, on) }, Domain::Timer3 => unsafe { bb::change_bit(&p.dcgctimer, 3, on) }, Domain::Timer2 => unsafe { bb::change_bit(&p.dcgctimer, 2, on) }, Domain::Timer1 => unsafe { bb::change_bit(&p.dcgctimer, 1, on) }, Domain::Timer0 => unsafe { bb::change_bit(&p.dcgctimer, 0, on) }, Domain::GpioF => unsafe { bb::change_bit(&p.dcgcgpio, 5, on) }, Domain::GpioE => unsafe { bb::change_bit(&p.dcgcgpio, 4, on) }, Domain::GpioD => unsafe { bb::change_bit(&p.dcgcgpio, 3, on) }, Domain::GpioC => unsafe { bb::change_bit(&p.dcgcgpio, 2, on) }, Domain::GpioB => unsafe { bb::change_bit(&p.dcgcgpio, 1, on) }, Domain::GpioA => unsafe { bb::change_bit(&p.dcgcgpio, 0, on) }, Domain::MicroDma => unsafe { bb::change_bit(&p.dcgcdma, 0, on) }, Domain::Hibernation => unsafe { bb::change_bit(&p.dcgchib, 0, on) }, Domain::Uart7 => unsafe { bb::change_bit(&p.dcgcuart, 7, on) }, Domain::Uart6 => unsafe { bb::change_bit(&p.dcgcuart, 6, on) }, Domain::Uart5 => unsafe { bb::change_bit(&p.dcgcuart, 5, on) }, Domain::Uart4 => unsafe { bb::change_bit(&p.dcgcuart, 4, on) }, Domain::Uart3 => unsafe { bb::change_bit(&p.dcgcuart, 3, on) }, Domain::Uart2 => unsafe { bb::change_bit(&p.dcgcuart, 2, on) }, Domain::Uart1 => unsafe { bb::change_bit(&p.dcgcuart, 1, on) }, Domain::Uart0 => unsafe { bb::change_bit(&p.dcgcuart, 0, on) }, Domain::Ssi3 => unsafe { bb::change_bit(&p.dcgcssi, 3, on) }, Domain::Ssi2 => unsafe { bb::change_bit(&p.dcgcssi, 2, on) }, Domain::Ssi1 => unsafe { bb::change_bit(&p.dcgcssi, 1, on) }, Domain::Ssi0 => unsafe { bb::change_bit(&p.dcgcssi, 0, on) }, Domain::I2c3 => unsafe { bb::change_bit(&p.dcgci2c, 3, on) }, Domain::I2c2 => unsafe { bb::change_bit(&p.dcgci2c, 2, on) }, Domain::I2c1 => unsafe { bb::change_bit(&p.dcgci2c, 1, on) }, Domain::I2c0 => unsafe { bb::change_bit(&p.dcgci2c, 0, on) }, Domain::Usb => unsafe { bb::change_bit(&p.dcgcusb, 0, on) }, Domain::Can => unsafe { bb::change_bit(&p.dcgccan, 0, on) }, Domain::Adc1 => unsafe { bb::change_bit(&p.dcgcadc, 1, on) }, Domain::Adc0 => unsafe { bb::change_bit(&p.dcgcadc, 0, on) }, Domain::AnalogComparator => unsafe { bb::change_bit(&p.dcgcacmp, 0, on) }, Domain::Eeprom => unsafe { bb::change_bit(&p.dcgceeprom, 0, on) }, Domain::WideTimer5 => unsafe { bb::change_bit(&p.dcgcwtimer, 5, on) }, Domain::WideTimer4 => unsafe { bb::change_bit(&p.dcgcwtimer, 4, on) }, Domain::WideTimer3 => unsafe { bb::change_bit(&p.dcgcwtimer, 3, on) }, Domain::WideTimer2 => unsafe { bb::change_bit(&p.dcgcwtimer, 2, on) }, Domain::WideTimer1 => unsafe { bb::change_bit(&p.dcgcwtimer, 1, on) }, Domain::WideTimer0 => unsafe { bb::change_bit(&p.dcgcwtimer, 0, on) }, } } /// Extension trait that constrains the `SYSCTL` peripheral pub trait SysctlExt { /// Constrains the `SYSCTL` peripheral so it plays nicely with the other abstractions fn constrain(self) -> Sysctl; } impl SysctlExt for tm4c123x::SYSCTL { fn constrain(self) -> Sysctl { Sysctl { power_control: PowerControl { _0: () }, clock_setup: ClockSetup { oscillator: Oscillator::PrecisionInternal(SystemClock::UseOscillator(Divider::_1)), _0: (), }, } } } impl ClockSetup { /// Fix the clock configuration and produce a record of the configuration /// so that other modules can calibrate themselves (e.g. the UARTs). pub fn freeze(self) -> Clocks { // We own the SYSCTL at this point - no one else can be running. let p = unsafe { &*tm4c123x::SYSCTL::ptr() }; let mut osc = 0u32; let mut sysclk = 0u32; match self.oscillator { Oscillator::Main(crystal_frequency, system_clock) => { p.rcc.write(|w| { // BYPASS on w.bypass().set_bit(); // OSCSRC = Main Oscillator w.oscsrc().main(); // Main Oscillator not disabled w.moscdis().clear_bit(); // SysDiv = 0x00 unsafe { w.sysdiv().bits(0x00); } // Set crystal frequency osc = match crystal_frequency { CrystalFrequency::_4mhz => { w.xtal()._4mhz(); 4_000_000 } CrystalFrequency::_4_09mhz => { w.xtal()._4_09mhz(); 4_090_000 } CrystalFrequency::_4_91mhz => { w.xtal()._4_91mhz(); 4_910_000 } CrystalFrequency::_5mhz => { w.xtal()._5mhz(); 5_000_000 } CrystalFrequency::_5_12mhz => { w.xtal()._5_12mhz(); 5_120_000 } CrystalFrequency::_6mhz => { w.xtal()._6mhz(); 6_000_000 } CrystalFrequency::_6_14mhz => { w.xtal()._6_14mhz(); 6_140_000 } CrystalFrequency::_7_37mhz => { w.xtal()._7_37mhz(); 7_370_000 } CrystalFrequency::_8mhz => { w.xtal()._8mhz(); 8_000_000 } CrystalFrequency::_8_19mhz => { w.xtal()._8_19mhz(); 8_190_000 } CrystalFrequency::_10mhz => { w.xtal()._10mhz(); 10_000_000 } CrystalFrequency::_12mhz => { w.xtal()._12mhz(); 12_000_000 } CrystalFrequency::_12_2mhz => { w.xtal()._12_2mhz(); 12_200_000 } CrystalFrequency::_13_5mhz => { w.xtal()._13_5mhz(); 13_500_000 } CrystalFrequency::_14_3mhz => { w.xtal()._14_3mhz(); 14_300_000 } CrystalFrequency::_16mhz => { w.xtal()._16mhz(); 16_000_000 } CrystalFrequency::_16_3mhz => { w.xtal()._16_3mhz(); 16_300_000 } CrystalFrequency::_18mhz => { w.xtal()._18mhz(); 18_000_000 } CrystalFrequency::_20mhz => { w.xtal()._20mhz(); 20_000_000 } CrystalFrequency::_24mhz => { w.xtal()._24mhz(); 24_000_000 } CrystalFrequency::_25mhz => { w.xtal()._25mhz(); 25_000_000 } }; if let SystemClock::UseOscillator(div) = system_clock { w.usesysdiv().set_bit(); unsafe { w.sysdiv().bits(div as u8); } sysclk = osc / (div as u32); } else { // Run 1:1 now, do PLL later w.usesysdiv().clear_bit(); unsafe { w.sysdiv().bits(0); } sysclk = osc; } w }); } // The default Oscillator::PrecisionInternal(system_clock) => { osc = 16_000_000; p.rcc.write(|w| { // BYPASS on w.bypass().set_bit(); // OSCSRC = Internal Oscillator w.oscsrc().int(); // Main Oscillator disabled w.moscdis().set_bit(); // SysDiv = ? if let SystemClock::UseOscillator(div) = system_clock { w.usesysdiv().set_bit(); unsafe { w.sysdiv().bits(div as u8); } sysclk = osc / (div as u32); } else { // Run 1:1 now, do PLL later w.usesysdiv().clear_bit(); unsafe { w.sysdiv().bits(0); } sysclk = osc; } w }); } Oscillator::PrecisionInternalDiv4(div) => { osc = 4_000_000; p.rcc.write(|w| { // BYPASS on w.bypass().set_bit(); // OSCSRC = Internal Oscillator / 4 w.oscsrc().int4(); // Main Oscillator disabled w.moscdis().set_bit(); w.usesysdiv().set_bit(); unsafe { w.sysdiv().bits(div as u8); } sysclk = osc / (div as u32); w }); } Oscillator::LowFrequencyInternal(div) => { osc = 30_000; p.rcc.write(|w| { // BYPASS on w.bypass().set_bit(); // OSCSRC = Low Frequency internal (30 kHz) w.oscsrc()._30(); // Main Oscillator disabled w.moscdis().set_bit(); w.usesysdiv().set_bit(); unsafe { w.sysdiv().bits(div as u8); } sysclk = osc / (div as u32); w }); } } match self.oscillator { Oscillator::PrecisionInternal(SystemClock::UsePll(f)) | Oscillator::Main(_, SystemClock::UsePll(f)) => { // Configure 400MHz PLL with divider f // Set PLL bit in masked interrupt status to clear // PLL lock status p.misc.write(|w| w.plllmis().set_bit()); // Enable the PLL p.rcc.modify(|_, w| w.pwrdn().clear_bit()); while p.pllstat.read().lock().bit_is_clear() { nop(); } match f { // We need to use RCC2 for this one PllOutputFrequency::_80_00mhz => { p.rcc2.write(|w| { w.usercc2().set_bit(); // Divide 400 MHz not 200 MHz w.div400().set_bit(); // div=2 with lsb=0 gives divide by 5, so 400 MHz => 80 MHz w.sysdiv2lsb().clear_bit(); unsafe { w.sysdiv2().bits(2) }; w.bypass2().clear_bit(); w }); sysclk = 400_000_000u32 / 5; } _ => { // All the other frequencies can be done with legacy registers p.rcc.modify(|_, w| { unsafe { w.sysdiv().bits(f as u8) }; w.usesysdiv().set_bit(); w.bypass().clear_bit(); w }); sysclk = 400_000_000u32 / (2 * ((f as u32) + 1)); } } } _ => {} } Clocks { osc: osc.hz(), sysclk: sysclk.hz(), } } } impl Clocks { /// Returns the frequency of the oscillator. pub fn osc(&self) -> Hertz { self.osc } /// Returns the system (core) frequency pub fn sysclk(&self) -> Hertz { self.sysclk } } impl PowerControl {} /// This module is all about identifying the physical chip we're running on. pub mod chip_id { /// Possible errors we can get back when parsing the ID registers. #[derive(Debug)] pub enum Error { /// Unknown value in DID0 UnknownDid0Ver(u8), /// Unknown value in DID1 UnknownDid1Ver(u8), } /// What sort of device is this? #[derive(Debug)] pub enum DeviceClass { /// It's a Stellaris LM4F or a TM4C123 (they have the same value) StellarisBlizzard, /// I don't know what chip this is Unknown, } /// How many pins on this chip's package? #[derive(Debug)] pub enum PinCount { /// It's a 28 pin package _28, /// It's a 48 pin package _48, /// It's a 100 pin package _100, /// It's a 64 pin package _64, /// It's a 144 pin package _144, /// It's a 157 pin package _157, /// It's a 168 pin package (TM4C123 only) _168, /// I don't know what chip this is Unknown, } /// What temperature range does this chip support? #[derive(Debug)] pub enum TempRange { /// It's Commercial temperature range (0°C - +70°C) Commercial, /// It's Industrial temperature range (-40°C - +85°C) Industrial, /// It's Extended temperature range (-40°C - +105°C) Extended, /// I don't know what temperature range this is Unknown, } /// What package is this chip in? #[derive(Debug)] pub enum Package { /// It's a SOIC package Soic, /// It's a LQFP package Lqfp, /// It's a BGA package Bga, /// I don't know what package this is Unknown, } /// Is this an experimental chip or a production part? #[derive(Debug)] pub enum Qualification { /// It's a Engineering Sample chip EngineeringSample, /// It's a Pilot Production chip PilotProduction, /// It's a Fully Qualified chip FullyQualified, /// I don't know what qualification this is Unknown, } /// These values describe the part number #[derive(Debug)] pub enum PartNo { /// It's a TM4C123GH6PM Tm4c123gh6pm, /// It's a LM4F120H5QR Lm4f120h5qr, /// It's an unknown chip - please file a bug report Unknown(u8), } /// These values describe the physical LM4F/TM4C chip #[derive(Debug)] pub struct ChipId { /// The device class pub device_class: DeviceClass, /// The major revision pub major: u8, /// The minor revision pub minor: u8, /// The chip's pin count pub pin_count: PinCount, /// The chip's temperature range pub temp_range: TempRange, /// The chip's package pub package: Package, /// True if the chip is RoHS compliant pub rohs_compliant: bool, /// The chip's qualification pub qualification: Qualification, /// The chip's part number pub part_no: PartNo, } /// Read DID0 and DID1 to discover what sort of /// TM4C123/LM4F123 this is. pub fn get() -> Result<ChipId, Error> { use tm4c123x; // This is safe as it's read only let p = unsafe { &*tm4c123x::SYSCTL::ptr() }; let did0 = p.did0.read(); if did0.ver().bits() != 0x01 { return Err(Error::UnknownDid0Ver(did0.ver().bits())); } let device_class = match did0.class().bits() { 5 => DeviceClass::StellarisBlizzard, _ => DeviceClass::Unknown, }; let major = did0.maj().bits(); let minor = did0.min().bits(); let did1 = p.did1.read(); if did1.ver().bits() != 0x01 { // Stellaris LM3F (0x00) is not supported return Err(Error::UnknownDid1Ver(did1.ver().bits())); } let part_no = match did1.prtno().bits() { 0x04 => PartNo::Lm4f120h5qr, 0xA1 => PartNo::Tm4c123gh6pm, _ => PartNo::Unknown(did1.prtno().bits()), }; let pin_count = match did1.pincnt().bits() { 0 => PinCount::_28, 1 => PinCount::_48, 2 => PinCount::_100, 3 => PinCount::_64, 4 => PinCount::_144, 5 => PinCount::_157, 6 => PinCount::_168, _ => PinCount::Unknown, }; let temp_range = match did1.temp().bits() { 0 => TempRange::Commercial, 1 => TempRange::Industrial, 2 => TempRange::Extended, _ => TempRange::Unknown, }; let package = match did1.pkg().bits() { 0 => Package::Soic, 1 => Package::Lqfp, 2 => Package::Bga, _ => Package::Unknown, }; let rohs_compliant = did1.rohs().bit_is_set(); let qualification = match did1.qual().bits() { 0 => Qualification::EngineeringSample, 1 => Qualification::PilotProduction, 2 => Qualification::FullyQualified, _ => Qualification::Unknown, }; Ok(ChipId { device_class, major, minor, pin_count, temp_range, package, rohs_compliant, qualification, part_no, }) } } // End of file
use crate::format::ParseError; use core::fmt; /// A unified error type for anything returned by a method in the time crate. /// /// This can be used when you either don't know or don't care about the exact /// error returned. `Result<_, time::Error>` will work in these situations. #[allow(clippy::missing_docs_in_private_items)] // variants only #[non_exhaustive] #[derive(Debug, Clone, PartialEq, Eq)] pub enum Error { ConversionRange(ConversionRangeError), ComponentRange(ComponentRangeError), Parse(ParseError), } impl fmt::Display for Error { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::ConversionRange(e) => e.fmt(f), Self::ComponentRange(e) => e.fmt(f), Self::Parse(e) => e.fmt(f), } } } #[cfg(feature = "std")] impl std::error::Error for Error {} /// An error type indicating that a conversion failed because the target type /// could not store the initial value. #[non_exhaustive] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ConversionRangeError; impl fmt::Display for ConversionRangeError { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Source value is out of range for the target type") } } #[cfg(feature = "std")] impl std::error::Error for ConversionRangeError {} impl From<ConversionRangeError> for Error { #[inline(always)] fn from(original: ConversionRangeError) -> Self { Self::ConversionRange(original) } } /// An error type indicating that a component provided to a method was out of /// range, causing a failure. #[allow(missing_copy_implementations)] // Non-copy fields may be added. #[non_exhaustive] #[derive(Debug, Clone, PartialEq, Eq)] pub struct ComponentRangeError; impl fmt::Display for ComponentRangeError { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("A component's value is out of range") } } impl From<ComponentRangeError> for Error { #[inline(always)] fn from(original: ComponentRangeError) -> Self { Self::ComponentRange(original) } } #[cfg(feature = "std")] impl std::error::Error for ComponentRangeError {} impl From<ParseError> for Error { #[inline(always)] fn from(original: ParseError) -> Self { Self::Parse(original) } }
use crate::arena::{block, resource, BlockRef}; use crate::libs::random_id::U128Id; use crate::libs::three; use std::cell::Cell; use std::collections::HashMap; use std::rc::Rc; use wasm_bindgen::{prelude::*, JsCast}; pub struct TextureTable { data: HashMap<U128Id, Texture>, text: HashMap<(String, String), Fate<Rc<TextTexture>>>, } pub enum Texture { Image(Rc<three::Texture>), Block(Rc<three::Texture>), Terran(f64, Rc<three::Texture>), } pub struct TextTexture { pub data: three::Texture, pub size: [f64; 2], } struct Fate<V> { value: V, life_expectancy: usize, is_used: Cell<bool>, } impl TextureTable { pub fn new() -> Self { Self { data: HashMap::new(), text: HashMap::new(), } } pub fn update(&mut self) { let mut deleted = vec![]; for (key_text, tex) in &mut self.text { if tex.aging() { deleted.push(key_text.clone()); } } for key_text in &deleted { if let Some(tex) = self.text.remove(key_text) { tex.data.dispose(); } } } pub fn load_image( &mut self, image: BlockRef<resource::ImageData>, ) -> Option<Rc<three::Texture>> { let image_id = image.id(); if let Some(Texture::Image(texture)) = self.data.get(&image_id) { return Some(Rc::clone(texture)); } let texture = image.map(|image| { let texture = Rc::new(three::Texture::new_with_image(image.element())); texture.set_needs_update(true); texture }); texture.map(|texture| { self.data .insert(image_id, Texture::Image(Rc::clone(&texture))); texture }) } pub fn load_block( &mut self, block_texture: BlockRef<resource::BlockTexture>, ) -> Option<Rc<three::Texture>> { let texture_id = block_texture.id(); if let Some(Texture::Block(texture)) = self.data.get(&texture_id) { return Some(Rc::clone(texture)); } let texture = block_texture.map(|block_texture| { let texture = Rc::new(three::Texture::new_with_image( block_texture.data().element(), )); texture.set_wrap_s(three::REPEAT_WRAPPING); texture.set_needs_update(true); texture }); texture.map(|texture| { self.data .insert(texture_id, Texture::Block(Rc::clone(&texture))); texture }) } pub fn load_terran( &mut self, terran_texture: BlockRef<block::TerranTexture>, ) -> Option<Rc<three::Texture>> { let texture_id = terran_texture.id(); if let Some(Texture::Terran(timestamp, texture)) = self.data.get_mut(&texture_id) { if *timestamp < terran_texture.timestamp() { texture.set_needs_update(true); *timestamp = terran_texture.timestamp(); } crate::debug::log_1("load terran texture"); return Some(Rc::clone(texture)); } let texture = terran_texture.map(|terran_texture| { let texture = Rc::new(three::Texture::new_with_canvas(terran_texture.data())); texture.set_needs_update(true); texture }); texture.map(|texture| { self.data.insert( texture_id, Texture::Terran(terran_texture.timestamp(), Rc::clone(&texture)), ); crate::debug::log_1("create terran texture"); texture }) } pub fn load_text(&mut self, text: &(String, String)) -> Rc<TextTexture> { if let Some(texture) = self.text.get(text) { return Rc::clone(texture); } let text_1 = text.1 != ""; let canvas = crate::libs::element::html_canvas_element(); let ctx = canvas .get_context("2d") .unwrap() .unwrap() .dyn_into::<web_sys::CanvasRenderingContext2d>() .unwrap(); let font_size = (64.0, 32.0); let text_size = if text_1 { ( Self::calc_text_size(&ctx, font_size.0, &text.0), Self::calc_text_size(&ctx, font_size.1, &text.1), ) } else { (Self::calc_text_size(&ctx, font_size.0, &text.0), [0.0, 0.0]) }; let canvas_size = [ f64::max(text_size.0[0], text_size.1[0]), text_size.0[1] + text_size.1[1], ]; canvas.set_width(canvas_size[0] as u32); canvas.set_height(canvas_size[1] as u32); let ctx = canvas .get_context("2d") .unwrap() .unwrap() .dyn_into::<web_sys::CanvasRenderingContext2d>() .unwrap(); ctx.set_fill_style(&JsValue::from("#000000")); ctx.fill_rect(0.0, 0.0, canvas_size[0], canvas_size[1]); ctx.set_text_baseline("top"); ctx.set_fill_style(&JsValue::from("#FFFFFF")); ctx.set_font(&format!("{}px sans-serif", font_size.0)); Self::fill_lines(&ctx, &text.0, 0.0, text_size.1[1], font_size.0); if text_1 { ctx.set_font(&format!("{}px sans-serif", font_size.1)); Self::fill_lines(&ctx, &text.1, 0.0, 0.0, font_size.1); } let texture = three::Texture::new_with_canvas(&canvas); texture.set_needs_update(true); let texture = TextTexture { data: texture, size: [canvas_size[0] / font_size.0, canvas_size[1] / font_size.0], }; let texture = Rc::new(texture); self.text .insert(text.clone(), Fate::new(Rc::clone(&texture))); texture } fn fill_lines( ctx: &web_sys::CanvasRenderingContext2d, text: &String, x: f64, y: f64, font_size: f64, ) { let mut line_num = 0.0; for line in text.lines() { let _ = ctx.fill_text(line, x, y + line_num * font_size); line_num += 1.0; } } fn calc_text_size( ctx: &web_sys::CanvasRenderingContext2d, font_size: f64, text: &String, ) -> [f64; 2] { ctx.set_font(&format!("{}px sans-serif", font_size)); let mut width: f64 = 0.0; for line in text.lines() { let metrix = ctx.measure_text(line).unwrap(); width = width.max(metrix.width()); } let line_num = text.lines().count(); let height = font_size * line_num as f64; [width, height] } } impl<V> Fate<V> { pub fn new(value: V) -> Self { Self { value, life_expectancy: 0, is_used: Cell::new(true), } } pub fn aging(&mut self) -> bool { if self.is_used.get() { self.life_expectancy += 1; self.is_used.set(false); false } else if self.life_expectancy == 0 { true } else { self.life_expectancy -= 1; false } } } impl<V> std::ops::Deref for Fate<V> { type Target = V; fn deref(&self) -> &Self::Target { self.is_used.set(true); &self.value } } impl<V> std::ops::DerefMut for Fate<V> { fn deref_mut(&mut self) -> &mut Self::Target { self.is_used.set(true); &mut self.value } }
pub mod material; pub mod render_mesh; pub mod shader; pub mod texture; pub mod light; pub mod light_conversion; use luminance::{ shader::program::{ Uniform, Uniformable, }, linear::M44 }; use luminance_derive::UniformInterface; #[derive(Debug, UniformInterface)] pub struct ShaderInterface { #[uniform(unbound)] //Tells luminance that it shouldn't generate an error if the GPU variable doesn't exist pub projection: Uniform<M44>, #[uniform(unbound)] //#[uniform(name = "foo")] can be used to rename a uniform pub view: Uniform<M44>, #[uniform(unbound)] pub model: Uniform<M44>, } //TODO: Add many more types #[derive(PartialEq)] pub enum UniformType { //Basic data types Float, Integer, //Vectors Vector2, Vector3, Vector4, IVector2, IVector3, IVector4, //Matrices Matrix2, Matrix3, Matrix4, Matrix2x3, Matrix2x4, Matrix3x2, Matrix3x4, Matrix4x2, Matrix4x3, //Other data types Sampler2D, Other(String) }
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 #[allow(unused_imports)] use log::{info, warn}; use itertools::Itertools; use num::BigUint; use regex::Regex; use serde::Serialize; use spec_lang::{ ast::{ModuleName, SpecBlockInfo, SpecBlockTarget}, code_writer::CodeWriter, emit, emitln, env::{FunctionEnv, GlobalEnv, ModuleEnv, Parameter, StructEnv, TypeConstraint, TypeParameter}, symbol::Symbol, ty::TypeDisplayContext, }; use std::{ cell::RefCell, collections::{BTreeMap, VecDeque}, rc::Rc, }; const KEYWORDS: &[&str] = &[ "abort", "acquires", "as", "break", "continue", "copy", "copyable", "else", "false", "if", "invariant", "let", "loop", "module", "move", "native", "public", "resource", "return", "spec", "struct", "true", "use", "while", "fun", "script", ]; const WEAK_KEYWORDS: &[&str] = &[ "apply", "assert", "assume", "decreases", "aborts_if", "ensures", "requires", "pack", "unpack", "update", "to", "schema", "include", "old", "except", "global", "mut", ]; /// Options passed into the documentation generator. #[derive(Debug, Clone, Serialize)] pub struct DocgenOptions { /// The level where we start sectioning. Often markdown sections are rendered with /// unnecessary large section fonts, setting this value high reduces the size. pub section_level_start: usize, /// Whether to include private functions in the generated docs. pub include_private_fun: bool, /// Whether to include specifications in the generated docs. pub include_specs: bool, /// Whether to put specifications in the same section as a declaration or put them all /// into an independent section. pub specs_inlined: bool, /// Whether to include Move implementations. pub include_impl: bool, /// Max depth to which sections are displayed in table-of-contents. pub toc_depth: usize, /// Whether to use collapsed sections (<details>) for impl and specs pub collapsed_sections: bool, } impl Default for DocgenOptions { fn default() -> Self { Self { section_level_start: 1, include_private_fun: false, include_specs: true, specs_inlined: true, include_impl: true, toc_depth: 3, collapsed_sections: true, } } } /// The documentation generator. pub struct Docgen<'env> { env: &'env GlobalEnv, options: &'env DocgenOptions, writer: CodeWriter, toc: RefCell<VecDeque<Vec<TocEntry>>>, } /// A table-of-contents entry. #[derive(Debug, Default)] struct TocEntry { label: String, title: String, sub_entries: Vec<TocEntry>, } /// A map from spec block targets to associated spec blocks. type SpecBlockMap<'a> = BTreeMap<SpecBlockTarget, Vec<&'a SpecBlockInfo>>; impl<'env> Docgen<'env> { /// Creates a new documentation generator. pub fn new(env: &'env GlobalEnv, options: &'env DocgenOptions) -> Self { let mut toc = VecDeque::new(); toc.push_back(Vec::new()); Self { env, options, writer: CodeWriter::new(env.unknown_loc()), toc: RefCell::new(toc), } } /// Returns the code writer of this generator, consuming it. pub fn into_code_writer(self) -> CodeWriter { self.writer } /// Generate documentation for all modules in the environment which are not in the dependency /// set. pub fn gen(&mut self) { emitln!( self.writer, "{} Table of Contents", self.repeat_str("#", self.options.section_level_start + 1) ); let toc_label = self.writer.create_label(); for m in self.env.get_modules() { if !m.is_in_dependency() { self.gen_module(&m); } } // Generate table of contents. We put this into a separate code writer which we then // merge into the main one. let mut toc_writer = CodeWriter::new(self.env.unknown_loc()); let writer = std::mem::replace(&mut self.writer, toc_writer); let toc = self.toc.borrow(); assert_eq!(toc.len(), 1, "unbalanced sectioning"); self.begin_items(); for entry in toc.front().unwrap() { self.gen_toc(entry, 1); } self.end_items(); toc_writer = std::mem::replace(&mut self.writer, writer); toc_writer.process_result(|s| self.writer.insert_at_label(toc_label, s)); } /// Generates a toc-entry, recursively. fn gen_toc(&self, entry: &TocEntry, depth: usize) { if depth > self.options.toc_depth { return; } self.item_text(None, &format!("[{}](#{})", entry.title, entry.label)); if !entry.sub_entries.is_empty() { self.writer.indent(); self.begin_items(); for sub_entry in &entry.sub_entries { self.gen_toc(sub_entry, depth + 1); } self.end_items(); self.writer.unindent(); } } /// Generates documentation for a module. fn gen_module(&self, module_env: &ModuleEnv<'_>) { let module_name = format!( "{}", module_env.get_name().display_full(module_env.symbol_pool()) ); self.section_header( &format!("Module `{}`", module_name), &self.label_for_module(module_env), ); self.increment_section_nest(); self.doc_text(module_env, module_env.get_doc()); let spec_block_map = self.organize_spec_blocks(module_env); if self.options.specs_inlined { self.gen_spec_blocks(module_env, "", &SpecBlockTarget::Module, &spec_block_map); } if !module_env.get_structs().count() > 0 { for s in module_env .get_structs() .sorted_by(|a, b| Ord::cmp(&a.get_loc(), &b.get_loc())) { self.gen_struct(&spec_block_map, &s); } } let funs = module_env .get_functions() .filter(|f| self.options.include_private_fun || f.is_public()) .sorted_by(|a, b| Ord::cmp(&a.get_loc(), &b.get_loc())) .collect_vec(); if !funs.is_empty() { for f in funs { self.gen_function(&spec_block_map, &f); } } if !self.options.specs_inlined { self.gen_spec_section(module_env, &spec_block_map); } self.decrement_section_nest(); } /// Generates documentation for a struct. fn gen_struct(&self, spec_block_map: &SpecBlockMap<'_>, struct_env: &StructEnv<'_>) { let name = self.name_string(struct_env.get_name()); self.section_header(&format!("Struct `{}`", name), name.as_str()); self.increment_section_nest(); self.doc_text(&struct_env.module_env, struct_env.get_doc()); self.code_block( &struct_env.module_env, &self.struct_header_display(struct_env), ); if self.options.include_impl || (self.options.include_specs && self.options.specs_inlined) { // Include field documentation if either impls or specs are present and inlined, // because they are used by both. self.begin_collapsed("Fields"); self.gen_struct_fields(struct_env); self.end_collapsed(); } if self.options.specs_inlined { self.gen_spec_blocks( &struct_env.module_env, "Specification", &SpecBlockTarget::Struct(struct_env.module_env.get_id(), struct_env.get_id()), spec_block_map, ); } self.decrement_section_nest(); } /// Generates code signature for a struct. fn struct_header_display(&self, struct_env: &StructEnv<'_>) -> String { let name = self.name_string(struct_env.get_name()); let kind = if struct_env.is_resource() { "resource struct" } else { "struct" }; format!( "{} {}{}", kind, name, self.type_parameter_list_display(&struct_env.get_named_type_parameters()), ) } fn gen_struct_fields(&self, struct_env: &StructEnv<'_>) { let tctx = self.type_display_context_for_struct(struct_env); self.begin_definitions(); for field in struct_env.get_fields() { self.definition_text( Some(&struct_env.module_env), &format!( "`{}: {}`", self.name_string(field.get_name()), field.get_type().display(&tctx) ), field.get_doc(), ); } self.end_definitions(); } /// Generates documentation for a function. fn gen_function(&self, spec_block_map: &SpecBlockMap<'_>, func_env: &FunctionEnv<'_>) { let name = self.name_string(func_env.get_name()); self.section_header(&format!("Function `{}`", name), name.as_str()); self.increment_section_nest(); self.doc_text(&func_env.module_env, func_env.get_doc()); let sig = self.function_header_display(func_env); self.code_block(&func_env.module_env, &sig); if self.options.specs_inlined { self.gen_spec_blocks( &func_env.module_env, "Specification", &SpecBlockTarget::Function(func_env.module_env.get_id(), func_env.get_id()), spec_block_map, ) } if self.options.include_impl { self.begin_collapsed("Implementation"); let source = match self.env.get_source(&func_env.get_loc()) { Ok(s) => s, Err(_) => "<source unavailable>", }; self.code_block(&func_env.module_env, &self.fix_indent(source)); self.end_collapsed(); } self.decrement_section_nest(); } /// Generates documentation for a function signature. fn function_header_display(&self, func_env: &FunctionEnv<'_>) -> String { let name = self.name_string(func_env.get_name()); let visibility = if func_env.is_public() { "public " } else { "" }; let tctx = &self.type_display_context_for_fun(&func_env); let params = func_env .get_parameters() .iter() .map(|Parameter(name, ty)| format!("{}: {}", self.name_string(*name), ty.display(tctx))) .join(", "); let return_types = func_env.get_return_types(); let return_str = match return_types.len() { 0 => "".to_owned(), 1 => format!(": {}", return_types[0].display(tctx)), _ => format!( ": ({})", return_types.iter().map(|ty| ty.display(tctx)).join(", ") ), }; format!( "{}fun {}{}({}){}", visibility, name, self.type_parameter_list_display(&func_env.get_named_type_parameters()), params, return_str ) } /// Generates documentation for a series of spec blocks associated with spec block target. fn gen_spec_blocks( &self, module_env: &ModuleEnv<'_>, title: &str, target: &SpecBlockTarget, spec_block_map: &SpecBlockMap, ) { let no_blocks = &vec![]; let blocks = spec_block_map.get(target).unwrap_or(no_blocks); if blocks.is_empty() || !self.options.include_specs { return; } if !title.is_empty() { self.begin_collapsed(title); } for block in blocks { self.doc_text(module_env, self.env.get_doc(&block.loc)); let mut in_code = false; let (is_schema, schema_header) = if let SpecBlockTarget::Schema(_, sid, type_params) = &block.target { ( true, format!( "schema {}{} {{", self.name_string(sid.symbol()), self.type_parameter_list_display(type_params) ), ) } else { (false, "".to_owned()) }; let begin_code = |in_code: &mut bool| { if !*in_code { self.begin_code(); if is_schema { self.code_text(module_env, &schema_header); self.writer.indent(); } *in_code = true; } }; let end_code = |in_code: &mut bool| { if *in_code { if is_schema { self.writer.unindent(); self.code_text(module_env, "}"); } self.end_code(); *in_code = false; } }; for loc in &block.member_locs { let doc = self.env.get_doc(loc); if !doc.is_empty() { end_code(&mut in_code); self.doc_text(module_env, doc); } let member_source = match self.env.get_source(loc) { Ok(s) => s, Err(_) => "<unknown source>", }; begin_code(&mut in_code); self.code_text(module_env, member_source); } end_code(&mut in_code); } if !title.is_empty() { self.end_collapsed(); } } /// Organizes spec blocks in the module such that free items like schemas and module blocks /// are associated with the context they appear in. fn organize_spec_blocks(&self, module_env: &'env ModuleEnv<'env>) -> SpecBlockMap<'env> { let mut result = BTreeMap::new(); let mut current_target = SpecBlockTarget::Module; for block in module_env.get_spec_block_infos() { if !matches!( block.target, SpecBlockTarget::Schema(..) | SpecBlockTarget::Module ) { // Switch target if it's not a schema or module. Those will be associated with // the last target. current_target = block.target.clone(); } result .entry(current_target.clone()) .or_insert_with(Vec::new) .push(block); } result } /// Generates standalone spec section. This is used if `options.specs_inlined` is false. fn gen_spec_section(&self, module_env: &ModuleEnv<'_>, spec_block_map: &SpecBlockMap<'_>) { if spec_block_map.is_empty() || !self.options.include_specs { return; } self.section_header("Specification", "Specification"); self.increment_section_nest(); self.gen_spec_blocks(module_env, "", &SpecBlockTarget::Module, spec_block_map); for struct_env in module_env .get_structs() .sorted_by(|a, b| Ord::cmp(&a.get_loc(), &b.get_loc())) { let target = SpecBlockTarget::Struct(struct_env.module_env.get_id(), struct_env.get_id()); if spec_block_map.contains_key(&target) { let name = self.name_string(struct_env.get_name()); self.section_header(&format!("Struct `{}`", name), name.as_str()); self.code_block(module_env, &self.struct_header_display(&struct_env)); self.gen_struct_fields(&struct_env); self.gen_spec_blocks(module_env, "", &target, spec_block_map); } } for func_env in module_env .get_functions() .sorted_by(|a, b| Ord::cmp(&a.get_loc(), &b.get_loc())) { let target = SpecBlockTarget::Function(func_env.module_env.get_id(), func_env.get_id()); if spec_block_map.contains_key(&target) { let name = self.name_string(func_env.get_name()); self.section_header(&format!("Function `{}`", name), name.as_str()); self.code_block( &func_env.module_env, &self.function_header_display(&func_env), ); self.gen_spec_blocks(module_env, "", &target, spec_block_map); } } self.decrement_section_nest(); } // ============================================================================================ // Helpers /// Returns a string for a name symbol. fn name_string(&self, name: Symbol) -> Rc<String> { self.env.symbol_pool().string(name) } /// Creates a type display context for a function. fn type_display_context_for_fun(&self, func_env: &FunctionEnv<'_>) -> TypeDisplayContext<'_> { let type_param_names = Some( func_env .get_named_type_parameters() .iter() .map(|TypeParameter(name, _)| *name) .collect_vec(), ); TypeDisplayContext::WithEnv { env: self.env, type_param_names, } } /// Creates a type display context for a struct. fn type_display_context_for_struct( &self, struct_env: &StructEnv<'_>, ) -> TypeDisplayContext<'_> { let type_param_names = Some( struct_env .get_named_type_parameters() .iter() .map(|TypeParameter(name, _)| *name) .collect_vec(), ); TypeDisplayContext::WithEnv { env: self.env, type_param_names, } } /// Increments section nest. fn increment_section_nest(&self) { self.toc.borrow_mut().push_back(Vec::new()); } /// Decrements section nest, committing sub-sections to the table-of-contents map. fn decrement_section_nest(&self) { let mut toc = self.toc.borrow_mut(); let sub_sections = toc.pop_back().expect("unbalanced sections"); if !sub_sections.is_empty() { let entry = toc .back_mut() .expect("balanced section nest") .last_mut() .expect("linear sectioning"); entry.sub_entries = sub_sections; } } /// Creates a new section header and inserts a table-of-contents entry into the generator. fn section_header(&self, s: &str, relative_label: &str) { let level = self.toc.borrow().len(); let parent_label = if level > 1 { self.toc.borrow()[level - 2] .last() .map(|entry| entry.label.to_string()) } else { None }; let qualified_label = if let Some(l) = parent_label { format!("{}_{}", l, relative_label) } else { relative_label.to_string() }; emitln!(self.writer); emitln!(self.writer, "<a name=\"{}\"></a>", qualified_label); emitln!(self.writer); emitln!( self.writer, "{} {}", self.repeat_str( "#", self.options.section_level_start + self.toc.borrow().len() ), s, ); emitln!(self.writer); let entry = TocEntry { title: s.to_owned(), label: qualified_label, sub_entries: vec![], }; self.toc .borrow_mut() .back_mut() .expect("linear sectioning") .push(entry); } /// Begins a collapsed section. fn begin_collapsed(&self, summary: &str) { if self.options.collapsed_sections { emitln!(self.writer); emitln!(self.writer, "<details>"); emitln!(self.writer, "<summary>{}</summary>", summary); emitln!(self.writer); } else { emitln!(self.writer); emitln!(self.writer, "##### {}", summary); emitln!(self.writer); } } /// Ends a collapsed section. fn end_collapsed(&self) { if self.options.collapsed_sections { emitln!(self.writer); emitln!(self.writer, "</details>"); } } /// Outputs documentation text. fn doc_text(&self, module_env: &ModuleEnv<'_>, text: &str) { for line in self.decorate_text(module_env, text).lines() { let line = line.trim(); if line.starts_with('#') { // Add current section level emitln!( self.writer, "{}{}", self.repeat_str( "#", self.options.section_level_start + self.toc.borrow().len() - 1 ), line ); } else { emitln!(self.writer, line) } } // Always be sure to have an empty line at the end of block. emitln!(self.writer); } /// Decorates documentation text, identifying code fragments and decorating them /// as code. fn decorate_text(&self, module_env: &ModuleEnv<'_>, text: &str) -> String { let rex = Regex::new(r"(?m)`[^`]+`").unwrap(); let mut r = String::new(); let mut at = 0; while let Some(m) = rex.find(&text[at..]) { r += &text[at..at + m.start()]; // If the current text does not start on a newline, we need to add one. // Some markdown processors won't recognize a <code> if its not on a new // line. However, if we insert a blank line, we get a paragraph break, so we // need to avoid this. if !r.trim_end_matches(' ').ends_with('\n') { r += "\n"; } r += &format!( "<code>{}</code>", &self.decorate_code(module_env, &m.as_str()[1..&m.as_str().len() - 1]) ); at += m.end(); } r += &text[at..]; r } /// Begins a code block. This uses html, not markdown code blocks, so we are able to /// insert style and links into the code. fn begin_code(&self) { emitln!(self.writer); // If we newline after <pre><code>, an empty line will be created. So we don't. // This, however, creates some ugliness with indented code. emit!(self.writer, "<pre><code>"); } /// Ends a code block. fn end_code(&self) { emitln!(self.writer, "</code></pre>\n"); // Always be sure to have an empty line at the end of block. emitln!(self.writer); } /// Outputs decorated code text in context of a module. fn code_text(&self, module_env: &ModuleEnv<'_>, code: &str) { emitln!(self.writer, &self.decorate_code(module_env, code)); } /// Decorates a code fragment, for use in an html block. Replaces < and >, bolds keywords and /// tries to resolve and cross-link references. fn decorate_code(&self, module_env: &ModuleEnv<'_>, code: &str) -> String { let rex = Regex::new( r"(?P<ident>(\b\w+\b\s*::\s*)*\b\w+\b)(?P<call>\s*[(<])?|(?P<lt><)|(?P<gt>>)", ) .unwrap(); let mut r = String::new(); let mut at = 0; while let Some(cap) = rex.captures(&code[at..]) { let replacement = { if cap.name("lt").is_some() { "&lt;".to_owned() } else if cap.name("gt").is_some() { "&gt;".to_owned() } else if let Some(m) = cap.name("ident") { let is_call = cap.name("call").is_some(); let s = m.as_str(); if KEYWORDS.contains(&s) || WEAK_KEYWORDS.contains(&s) { format!("<b>{}</b>", &code[at + m.start()..at + m.end()]) } else if let Some(label) = self.resolve_to_label(module_env, s, is_call) { format!("<a href=\"#{}\">{}</a>", label, s) } else { "".to_owned() } } else { "".to_owned() } }; if replacement.is_empty() { r += &code[at..at + cap.get(0).unwrap().end()].replace("<", "&lt;"); } else { r += &code[at..at + cap.get(0).unwrap().start()]; r += &replacement; if let Some(m) = cap.name("call") { // Append the call or generic open we may have also matched to distinguish // a simple name from a function call or generic instantiation. Need to // replace the `<` as well. r += &m.as_str().replace("<", "&lt;"); } } at += cap.get(0).unwrap().end(); } r += &code[at..]; r } /// Resolve a string of the form `ident`, `ident::ident`, or `0xN::ident::ident` into /// the label for the declaration inside of this documentation. This uses a /// heuristic and may not work in all cases or produce wrong results (for instance, it /// ignores aliases). To improve on this, we would need best direct support by the compiler. fn resolve_to_label( &self, module_env: &ModuleEnv<'_>, s: &str, is_followed_by_open: bool, ) -> Option<String> { let parts_data: Vec<&str> = s.splitn(3, "::").collect(); let mut parts = parts_data.as_slice(); let skip_dependency = |module: ModuleEnv<'env>| -> Option<ModuleEnv<'env>> { if module.is_in_dependency() { // Don't create references for code not part of this documentation. None } else { Some(module) } }; let module_opt = if parts[0].starts_with("0x") { if parts.len() == 1 { // Cannot resolve. return None; } let addr = BigUint::parse_bytes(&parts[0][2..].as_bytes(), 16)?; let mname = ModuleName::new(addr, self.env.symbol_pool().make(parts[1])); parts = &parts[2..]; Some(self.env.find_module(&mname)?).and_then(skip_dependency) } else { None }; let try_func_or_struct = |module: &ModuleEnv<'_>, name: Symbol, is_qualified: bool| { // Below we only resolve a simple name to a function if it is followed by a ( or <. // Otherwise we get too many false positives where names are resolved to functions // but were actual fields. if module.find_struct(name).is_some() || ((is_qualified || is_followed_by_open) && module.find_function(name).is_some()) { Some(self.label_for_module_item(&module, name)) } else { None } }; let parts_sym = parts .iter() .map(|p| self.env.symbol_pool().make(p)) .collect_vec(); match (module_opt, parts_sym.len()) { (Some(module), 0) => Some(self.label_for_module(&module)), (Some(module), 1) => try_func_or_struct(&module, parts_sym[0], true), (None, 0) => None, (None, 1) => { // A simple name. Resolve either to module or to item in current module. if let Some(module) = self .env .find_module_by_name(parts_sym[0]) .and_then(skip_dependency) { Some(self.label_for_module(&module)) } else { try_func_or_struct(module_env, parts_sym[0], false) } } (None, 2) => { // A qualified name, but without the address. This must be an item in a module // denoted by the first name. let module_opt = if parts[0] == "Self" { Some(module_env.clone()) } else { self.env .find_module_by_name(parts_sym[0]) .and_then(skip_dependency) }; if let Some(module) = module_opt { try_func_or_struct(&module, parts_sym[1], true) } else { None } } (_, _) => None, } } /// Return the link label for a module. fn label_for_module(&self, module_env: &ModuleEnv<'_>) -> String { module_env .get_name() .display_full(self.env.symbol_pool()) .to_string() .replace("::", "_") } /// Return the link label for an item in a module. fn label_for_module_item(&self, module_env: &ModuleEnv<'_>, item: Symbol) -> String { format!( "{}_{}", self.label_for_module(module_env), item.display(self.env.symbol_pool()) ) } /// Shortcut for code_block in a module context. fn code_block(&self, module_env: &ModuleEnv<'_>, code: &str) { self.begin_code(); self.code_text(module_env, code); self.end_code(); } /// Begin an itemized list. fn begin_items(&self) {} /// End an itemized list. fn end_items(&self) {} /// Emit an item. With use the optional module env to do text decoration. fn item_text(&self, module_env_opt: Option<&ModuleEnv<'_>>, text: &str) { match module_env_opt { Some(module_env) => emitln!(self.writer, "- {}", self.decorate_text(module_env, text)), None => emitln!(self.writer, "- {}", text), } } /// Begin a definition list. fn begin_definitions(&self) { emitln!(self.writer); emitln!(self.writer, "<dl>"); } /// End a definition list. fn end_definitions(&self) { emitln!(self.writer, "</dl>"); emitln!(self.writer); } /// Emit a definition. fn definition_text(&self, module_env_opt: Option<&ModuleEnv<'_>>, term: &str, def: &str) { let decorate = |s| match module_env_opt { Some(m) => self.decorate_text(m, s), None => s.to_string(), }; emitln!(self.writer, "<dt>\n{}\n</dt>", decorate(term)); emitln!(self.writer, "<dd>\n{}\n</dd>", decorate(def)); } /// Display a type parameter. fn type_parameter_display(&self, tp: &TypeParameter) -> String { format!( "{}{}", self.name_string(tp.0), match tp.1 { TypeConstraint::None => "", TypeConstraint::Resource => ": resource", TypeConstraint::Copyable => ": copyable", } ) } /// Display a type parameter list. fn type_parameter_list_display(&self, tps: &[TypeParameter]) -> String { if tps.is_empty() { "".to_owned() } else { format!( "<{}>", tps.iter() .map(|tp| self.type_parameter_display(tp)) .join(", ") ) } } /// Fixes indentation of source code as obtained via original source. /// Typically code has the first line unindented because location tracking starts /// at the first keyword of the item (e.g. `public fun`), but subsequent lines are then /// indented. This uses a heuristic by taking the indentation of the last line as a basis. fn fix_indent(&self, s: &str) -> String { let lines = s.lines().collect_vec(); if lines.is_empty() { return s.to_owned(); } let last_line = lines[lines.len() - 1]; let last_indent = last_line.len() - last_line.trim_start().len(); lines .iter() .map(|l| { let mut i = 0; while i < last_indent && l.starts_with(' ') { i += 1; } &l[i..] }) .join("\n") } /// Repeats a string n times. fn repeat_str(&self, s: &str, n: usize) -> String { (0..n).map(|_| s).collect::<String>() } }
//! Contains types for using resource kinds not known at compile-time. //! //! For concrete usage see [examples prefixed with dynamic_](https://github.com/kube-rs/kube/tree/main/examples). pub use crate::discovery::ApiResource; use crate::{ metadata::TypeMeta, resource::{DynamicResourceScope, Resource}, }; use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta; use std::borrow::Cow; use thiserror::Error; #[derive(Debug, Error)] #[error("failed to parse this DynamicObject into a Resource: {source}")] /// Failed to parse `DynamicObject` into `Resource` pub struct ParseDynamicObjectError { #[from] source: serde_json::Error, } /// A dynamic representation of a kubernetes object /// /// This will work with any non-list type object. #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] pub struct DynamicObject { /// The type fields, not always present #[serde(flatten, default)] pub types: Option<TypeMeta>, /// Object metadata #[serde(default)] pub metadata: ObjectMeta, /// All other keys #[serde(flatten)] pub data: serde_json::Value, } impl DynamicObject { /// Create a DynamicObject with minimal values set from ApiResource. #[must_use] pub fn new(name: &str, resource: &ApiResource) -> Self { Self { types: Some(TypeMeta { api_version: resource.api_version.to_string(), kind: resource.kind.to_string(), }), metadata: ObjectMeta { name: Some(name.to_string()), ..Default::default() }, data: Default::default(), } } /// Attach dynamic data to a DynamicObject #[must_use] pub fn data(mut self, data: serde_json::Value) -> Self { self.data = data; self } /// Attach a namespace to a DynamicObject #[must_use] pub fn within(mut self, ns: &str) -> Self { self.metadata.namespace = Some(ns.into()); self } /// Attempt to convert this `DynamicObject` to a `Resource` pub fn try_parse<K: Resource + for<'a> serde::Deserialize<'a>>( self, ) -> Result<K, ParseDynamicObjectError> { Ok(serde_json::from_value(serde_json::to_value(self)?)?) } } impl Resource for DynamicObject { type DynamicType = ApiResource; type Scope = DynamicResourceScope; fn group(dt: &ApiResource) -> Cow<'_, str> { dt.group.as_str().into() } fn version(dt: &ApiResource) -> Cow<'_, str> { dt.version.as_str().into() } fn kind(dt: &ApiResource) -> Cow<'_, str> { dt.kind.as_str().into() } fn api_version(dt: &ApiResource) -> Cow<'_, str> { dt.api_version.as_str().into() } fn plural(dt: &ApiResource) -> Cow<'_, str> { dt.plural.as_str().into() } fn meta(&self) -> &ObjectMeta { &self.metadata } fn meta_mut(&mut self) -> &mut ObjectMeta { &mut self.metadata } } #[cfg(test)] mod test { use crate::{ dynamic::{ApiResource, DynamicObject}, gvk::GroupVersionKind, params::{Patch, PatchParams, PostParams}, request::Request, resource::Resource, }; use k8s_openapi::api::core::v1::Pod; #[test] fn raw_custom_resource() { let gvk = GroupVersionKind::gvk("clux.dev", "v1", "Foo"); let res = ApiResource::from_gvk(&gvk); let url = DynamicObject::url_path(&res, Some("myns")); let pp = PostParams::default(); let req = Request::new(&url).create(&pp, vec![]).unwrap(); assert_eq!(req.uri(), "/apis/clux.dev/v1/namespaces/myns/foos?"); let patch_params = PatchParams::default(); let req = Request::new(url) .patch("baz", &patch_params, &Patch::Merge(())) .unwrap(); assert_eq!(req.uri(), "/apis/clux.dev/v1/namespaces/myns/foos/baz?"); assert_eq!(req.method(), "PATCH"); } #[test] fn raw_resource_in_default_group() { let gvk = GroupVersionKind::gvk("", "v1", "Service"); let api_resource = ApiResource::from_gvk(&gvk); let url = DynamicObject::url_path(&api_resource, None); let pp = PostParams::default(); let req = Request::new(url).create(&pp, vec![]).unwrap(); assert_eq!(req.uri(), "/api/v1/services?"); } #[test] fn can_parse_dynamic_object_into_pod() -> Result<(), serde_json::Error> { let original_pod: Pod = serde_json::from_value(serde_json::json!({ "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "example" }, "spec": { "containers": [{ "name": "example", "image": "alpine", // Do nothing "command": ["tail", "-f", "/dev/null"], }], } }))?; let dynamic_pod: DynamicObject = serde_json::from_str(&serde_json::to_string(&original_pod)?)?; let parsed_pod: Pod = dynamic_pod.try_parse().unwrap(); assert_eq!(parsed_pod, original_pod); Ok(()) } }
use std::{fmt::Debug, sync::Arc}; use serde::{Deserialize, Serialize}; use tokio::sync::RwLock; use crate::{ task::{Handle, Id}, Job, Keyed, }; pub(crate) mod jobs; mod managed_job; pub(crate) use managed_job::ManagedJob; #[cfg(test)] mod tests; /// A background jobs manager. #[derive(Debug)] pub struct Manager<Key = ()> { pub(crate) jobs: Arc<RwLock<jobs::Jobs<Key>>>, } impl<Key> Default for Manager<Key> where Key: Clone + std::hash::Hash + Eq + Send + Sync + Debug + 'static, { fn default() -> Self { Self { jobs: Arc::new(RwLock::new(jobs::Jobs::new())), } } } impl<Key> Clone for Manager<Key> { fn clone(&self) -> Self { Self { jobs: self.jobs.clone(), } } } impl<Key> Manager<Key> where Key: Clone + std::hash::Hash + Eq + Send + Sync + Debug + 'static, { /// Pushes a `job` into the queue. Pushing the same job definition twice /// will yield two tasks in the queue. pub async fn enqueue<J: Job + 'static>(&self, job: J) -> Handle<J::Output, Key> { let mut jobs = self.jobs.write().await; jobs.enqueue(job, None, self.clone()) } /// Uses [`Keyed::key`] to ensure no other job with the same `key` is /// currently running. If another job is already running that matches, a /// clone of that [`Handle`] will be returned. When the job finishes, all /// [`Handle`] clones will be notified with a copy of the result. pub async fn lookup_or_enqueue<J: Keyed<Key>>( &self, job: J, ) -> Handle<<J as Job>::Output, Key> { let mut jobs = self.jobs.write().await; jobs.lookup_or_enqueue(job, self.clone()) } async fn job_completed< T: Clone + Serialize + for<'de> Deserialize<'de> + Send + Sync + 'static, >( &self, id: Id, key: Option<&Key>, result: Result<T, anyhow::Error>, ) { let mut jobs = self.jobs.write().await; jobs.job_completed(id, key, result).await; } /// Spawns a worker. In general, you shouldn't need to call this function /// directly. pub fn spawn_worker(&self) { let manager = self.clone(); tokio::spawn(async move { manager.execute_jobs().await; }); } async fn execute_jobs(&self) { let receiver = { let jobs = self.jobs.read().await; jobs.queue() }; while let Ok(mut job) = receiver.recv_async().await { job.execute().await; } } }
#![feature(proc_macro_hygiene, decl_macro)] extern crate glob; extern crate regex; extern crate serde; #[macro_use] extern crate rocket; #[macro_use] extern crate rocket_contrib; #[macro_use(block)] extern crate nb; extern crate embedded_hal as hal; mod irsend; mod protocol; mod temperature; use std::sync::RwLock; use rocket::http::Status; use rocket::response::status::Custom; use rocket::State; use rocket_contrib::json::{Json, JsonValue}; use protocol::electra::*; use protocol::Protocol; type ElectraState = RwLock<Electra>; fn internal_error<E: ToString>(e: E) -> Custom<JsonValue> { Custom( Status::InternalServerError, json!({ "status": "error", "reason": e.to_string() }), ) } #[get("/", format = "json")] fn get(state: State<ElectraState>) -> Json<Electra> { let data = state.read().unwrap(); Json(*data) } #[post("/", format = "json", data = "<message>")] fn update(message: Json<Electra>, state: State<ElectraState>) -> Result<Status, Custom<JsonValue>> { let ir_message = message.0.build_message(); // Update state. let mut writable_state = state.write().unwrap(); *writable_state = message.0; if let Err(e) = irsend::send(&ir_message) { return Err(internal_error(e)); } Ok(Status::NoContent) } #[get("/temperature")] fn temperature() -> Result<JsonValue, Custom<JsonValue>> { use temperature; temperature::read_u32() .map(|t| json!({ "temperature": t })) .map_err(|e| internal_error(e)) } #[catch(404)] fn not_found() -> JsonValue { json!({ "status": "error", "reason": "Resource was not found." }) } fn rocket() -> rocket::Rocket { rocket::ignite() .mount("/", routes![temperature]) .mount("/remote", routes![get, update]) .register(catchers![not_found]) .manage(RwLock::new(Electra::new())) } fn main() { rocket().launch(); }
use log::*; use serenity::framework::standard::CommandError; use serenity::model::channel::Message; use serenity::model::id::UserId; use serenity::prelude::Context; use crate::commands::servers::*; use crate::db::*; use crate::model::enums::*; use crate::model::GameServerState; use crate::server::ServerConnection; use crate::snek::SnekGameStatus; fn turns_helper<C: ServerConnection>( user_id: UserId, db_conn: &DbConnection, read_handle: &crate::CacheReadHandle, ) -> Result<String, CommandError> { debug!("Starting !turns"); let servers_and_nations_for_player = db_conn.servers_for_player(user_id)?; let mut text = "Your turns:\n".to_string(); for (server, _) in servers_and_nations_for_player { if let GameServerState::StartedState(started_state, option_lobby_state) = server.state { let option_option_game_details = read_handle.get_clone(&server.alias); match option_option_game_details { Some(Some(cache)) => { let details: GameDetails = started_details_from_server( db_conn, &started_state, option_lobby_state.as_ref(), &server.alias, cache.game_data, cache.option_snek_state, ) .unwrap(); match details.nations { NationDetails::Started(started_state) => match started_state.state { StartedStateDetails::Uploading(uploading_state) => { turns_for_uploading_state( &mut text, &uploading_state, user_id, &server.alias, details .cache_entry .and_then(|cache_entry| cache_entry.option_snek_state) .as_ref(), ); } StartedStateDetails::Playing(playing_state) => { turns_for_playing_state( &mut text, &playing_state, user_id, &server.alias, details .cache_entry .and_then(|cache_entry| cache_entry.option_snek_state) .as_ref(), ); } }, NationDetails::Lobby(_) => continue, } } Some(None) => { text.push_str(&format!("{}: Cannot connect to server!\n", server.alias)); } None => { text.push_str(&format!( "{}: Server starting up, please try again in 1 min.\n", server.alias )); } } } } Ok(text) } fn turns_for_uploading_state( text: &mut String, uploading_state: &UploadingState, user_id: UserId, alias: &str, option_snek_state: Option<&SnekGameStatus>, ) { let player_count = uploading_state.uploading_players.len(); let uploaded_player_count = uploading_state .uploading_players .iter() .filter(|uploading_player| match uploading_player.potential_player { PotentialPlayer::GameOnly(_) => true, PotentialPlayer::RegisteredAndGame(_, _) => true, PotentialPlayer::RegisteredOnly(_, _) => false, }) .count(); for uploading_player in &uploading_state.uploading_players { match &uploading_player.potential_player { // This isn't them - it's somebody not registered PotentialPlayer::GameOnly(_) => (), PotentialPlayer::RegisteredAndGame(registered_user_id, player_details) => // is this them? { // FIXME: there used to be a nation_id check on here. What is this for? // does it fail only when people are registered multiple times? if *registered_user_id == user_id { let turn_str = format!( "{} uploading: {} (uploaded: {}, {}/{})\n", alias, player_details.nation_identifier.name(option_snek_state), SubmissionStatus::Submitted.show(), uploaded_player_count, player_count, ); text.push_str(&turn_str); } } // If this is them, they haven't uploaded PotentialPlayer::RegisteredOnly(registered_user_id, registered_nation_identifier) => { // FIXME: there used to be a nation_id check on here. What is this for? // does it fail only when people are registered multiple times? if *registered_user_id == user_id { let turn_str = format!( "{} uploading: {} (uploaded: {}, {}/{})\n", alias, registered_nation_identifier.name(option_snek_state), SubmissionStatus::NotSubmitted.show(), uploaded_player_count, player_count, ); text.push_str(&turn_str); } } } } } fn turns_for_playing_state( text: &mut String, playing_state: &PlayingState, user_id: UserId, alias: &str, option_snek_state: Option<&SnekGameStatus>, ) { let (playing_players, submitted_players) = count_playing_and_submitted_players(&playing_state.players); for playing_player in &playing_state.players { match playing_player { PotentialPlayer::RegisteredOnly(_, _) => (), PotentialPlayer::GameOnly(_) => (), PotentialPlayer::RegisteredAndGame( potential_player_user_id, potential_player_details, ) => { // FIXME: there used to be a nation_id check on here. What is this for? // does it fail only when people are registered multiple times? if *potential_player_user_id == user_id { if potential_player_details.player_status.is_human() { let turn_str = format!( "{} turn {} ({}h {}m): {} (submitted: {}, {}/{})\n", alias, playing_state.turn, playing_state.hours_remaining, playing_state.mins_remaining, potential_player_details .nation_identifier .name(option_snek_state), potential_player_details.submitted.show(), submitted_players, playing_players, ); text.push_str(&turn_str); } } } } } } fn count_playing_and_submitted_players(players: &Vec<PotentialPlayer>) -> (u32, u32) { let mut playing_players = 0; let mut submitted_players = 0; for playing_player in players { match playing_player { PotentialPlayer::RegisteredOnly(_, _) => (), PotentialPlayer::RegisteredAndGame(_, player_details) => { if player_details.player_status.is_human() { playing_players += 1; if let SubmissionStatus::Submitted = player_details.submitted { submitted_players += 1; } } } PotentialPlayer::GameOnly(player_details) => { if player_details.player_status.is_human() { playing_players += 1; if let SubmissionStatus::Submitted = player_details.submitted { submitted_players += 1; } } } } } (playing_players, submitted_players) } pub fn turns2<C: ServerConnection>( context: &mut Context, message: &Message, ) -> Result<(), CommandError> { let data = context.data.lock(); let db_conn = data .get::<DbConnectionKey>() .ok_or_else(|| CommandError("No db connection".to_string()))?; let read_handle = data .get::<crate::DetailsReadHandleKey>() .ok_or("No ReadHandle was created on startup. This is a bug.")?; let text = turns_helper::<C>(message.author.id, db_conn, read_handle)?; info!("turns: replying with: {}", text); let private_channel = message.author.id.create_dm_channel()?; private_channel.say(&text)?; Ok(()) }
// This file was generated by gir (https://github.com/gtk-rs/gir @ fbb95f4) // from gir-files (https://github.com/gtk-rs/gir-files @ 77d1f70) // DO NOT EDIT use ActionGroup; use ActionMap; use ApplicationFlags; use Cancellable; use Error; use File; #[cfg(any(feature = "v2_40", feature = "dox"))] use Notification; use ffi; use glib; use glib::StaticType; use glib::Value; use glib::object::Downcast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::boxed::Box as Box_; use std::mem; use std::mem::transmute; use std::ptr; glib_wrapper! { pub struct Application(Object<ffi::GApplication, ffi::GApplicationClass>): ActionGroup, ActionMap; match fn { get_type => || ffi::g_application_get_type(), } } impl Application { pub fn new<'a, P: Into<Option<&'a str>>>(application_id: P, flags: ApplicationFlags) -> Application { let application_id = application_id.into(); let application_id = application_id.to_glib_none(); unsafe { from_glib_full(ffi::g_application_new(application_id.0, flags.to_glib())) } } pub fn get_default() -> Option<Application> { unsafe { from_glib_none(ffi::g_application_get_default()) } } pub fn id_is_valid(application_id: &str) -> bool { unsafe { from_glib(ffi::g_application_id_is_valid(application_id.to_glib_none().0)) } } } pub trait ApplicationExt { fn activate(&self); //#[cfg(any(feature = "v2_42", feature = "dox"))] //fn add_main_option<'a, P: Into<Option<&'a str>>>(&self, long_name: &str, short_name: glib::Char, flags: /*Ignored*/glib::OptionFlags, arg: /*Ignored*/glib::OptionArg, description: &str, arg_description: P); //#[cfg(any(feature = "v2_40", feature = "dox"))] //fn add_main_option_entries(&self, entries: /*Ignored*/&[&glib::OptionEntry]); //#[cfg(any(feature = "v2_40", feature = "dox"))] //fn add_option_group(&self, group: /*Ignored*/&glib::OptionGroup); #[cfg(any(feature = "v2_44", feature = "dox"))] fn bind_busy_property<P: IsA<glib::Object>>(&self, object: &P, property: &str); fn get_application_id(&self) -> Option<String>; //#[cfg(any(feature = "v2_34", feature = "dox"))] //fn get_dbus_connection(&self) -> /*Ignored*/Option<DBusConnection>; #[cfg(any(feature = "v2_34", feature = "dox"))] fn get_dbus_object_path(&self) -> Option<String>; fn get_flags(&self) -> ApplicationFlags; fn get_inactivity_timeout(&self) -> u32; #[cfg(any(feature = "v2_44", feature = "dox"))] fn get_is_busy(&self) -> bool; fn get_is_registered(&self) -> bool; fn get_is_remote(&self) -> bool; #[cfg(any(feature = "v2_42", feature = "dox"))] fn get_resource_base_path(&self) -> Option<String>; fn hold(&self); #[cfg(any(feature = "v2_38", feature = "dox"))] fn mark_busy(&self); fn open(&self, files: &[File], hint: &str); fn quit(&self); fn register<'a, P: Into<Option<&'a Cancellable>>>(&self, cancellable: P) -> Result<(), Error>; fn release(&self); #[cfg(any(feature = "v2_40", feature = "dox"))] fn send_notification<'a, P: Into<Option<&'a str>>>(&self, id: P, notification: &Notification); #[deprecated] fn set_action_group<'a, P: IsA<ActionGroup> + 'a, Q: Into<Option<&'a P>>>(&self, action_group: Q); fn set_application_id<'a, P: Into<Option<&'a str>>>(&self, application_id: P); fn set_default(&self); fn set_flags(&self, flags: ApplicationFlags); fn set_inactivity_timeout(&self, inactivity_timeout: u32); #[cfg(any(feature = "v2_42", feature = "dox"))] fn set_resource_base_path<'a, P: Into<Option<&'a str>>>(&self, resource_path: P); #[cfg(any(feature = "v2_44", feature = "dox"))] fn unbind_busy_property<P: IsA<glib::Object>>(&self, object: &P, property: &str); #[cfg(any(feature = "v2_38", feature = "dox"))] fn unmark_busy(&self); #[cfg(any(feature = "v2_40", feature = "dox"))] fn withdraw_notification(&self, id: &str); fn get_property_resource_base_path(&self) -> Option<String>; fn set_property_resource_base_path(&self, resource_base_path: Option<&str>); fn connect_activate<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; //fn connect_command_line<Unsupported or ignored types>(&self, f: F) -> SignalHandlerId; //#[cfg(any(feature = "v2_40", feature = "dox"))] //fn connect_handle_local_options<Unsupported or ignored types>(&self, f: F) -> SignalHandlerId; fn connect_shutdown<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_startup<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_action_group_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_application_id_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_flags_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_inactivity_timeout_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; #[cfg(any(feature = "v2_44", feature = "dox"))] fn connect_property_is_busy_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_is_registered_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_is_remote_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_resource_base_path_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<Application> + IsA<glib::object::Object>> ApplicationExt for O { fn activate(&self) { unsafe { ffi::g_application_activate(self.to_glib_none().0); } } //#[cfg(any(feature = "v2_42", feature = "dox"))] //fn add_main_option<'a, P: Into<Option<&'a str>>>(&self, long_name: &str, short_name: glib::Char, flags: /*Ignored*/glib::OptionFlags, arg: /*Ignored*/glib::OptionArg, description: &str, arg_description: P) { // unsafe { TODO: call ffi::g_application_add_main_option() } //} //#[cfg(any(feature = "v2_40", feature = "dox"))] //fn add_main_option_entries(&self, entries: /*Ignored*/&[&glib::OptionEntry]) { // unsafe { TODO: call ffi::g_application_add_main_option_entries() } //} //#[cfg(any(feature = "v2_40", feature = "dox"))] //fn add_option_group(&self, group: /*Ignored*/&glib::OptionGroup) { // unsafe { TODO: call ffi::g_application_add_option_group() } //} #[cfg(any(feature = "v2_44", feature = "dox"))] fn bind_busy_property<P: IsA<glib::Object>>(&self, object: &P, property: &str) { unsafe { ffi::g_application_bind_busy_property(self.to_glib_none().0, object.to_glib_none().0, property.to_glib_none().0); } } fn get_application_id(&self) -> Option<String> { unsafe { from_glib_none(ffi::g_application_get_application_id(self.to_glib_none().0)) } } //#[cfg(any(feature = "v2_34", feature = "dox"))] //fn get_dbus_connection(&self) -> /*Ignored*/Option<DBusConnection> { // unsafe { TODO: call ffi::g_application_get_dbus_connection() } //} #[cfg(any(feature = "v2_34", feature = "dox"))] fn get_dbus_object_path(&self) -> Option<String> { unsafe { from_glib_none(ffi::g_application_get_dbus_object_path(self.to_glib_none().0)) } } fn get_flags(&self) -> ApplicationFlags { unsafe { from_glib(ffi::g_application_get_flags(self.to_glib_none().0)) } } fn get_inactivity_timeout(&self) -> u32 { unsafe { ffi::g_application_get_inactivity_timeout(self.to_glib_none().0) } } #[cfg(any(feature = "v2_44", feature = "dox"))] fn get_is_busy(&self) -> bool { unsafe { from_glib(ffi::g_application_get_is_busy(self.to_glib_none().0)) } } fn get_is_registered(&self) -> bool { unsafe { from_glib(ffi::g_application_get_is_registered(self.to_glib_none().0)) } } fn get_is_remote(&self) -> bool { unsafe { from_glib(ffi::g_application_get_is_remote(self.to_glib_none().0)) } } #[cfg(any(feature = "v2_42", feature = "dox"))] fn get_resource_base_path(&self) -> Option<String> { unsafe { from_glib_none(ffi::g_application_get_resource_base_path(self.to_glib_none().0)) } } fn hold(&self) { unsafe { ffi::g_application_hold(self.to_glib_none().0); } } #[cfg(any(feature = "v2_38", feature = "dox"))] fn mark_busy(&self) { unsafe { ffi::g_application_mark_busy(self.to_glib_none().0); } } fn open(&self, files: &[File], hint: &str) { let n_files = files.len() as i32; unsafe { ffi::g_application_open(self.to_glib_none().0, files.to_glib_none().0, n_files, hint.to_glib_none().0); } } fn quit(&self) { unsafe { ffi::g_application_quit(self.to_glib_none().0); } } fn register<'a, P: Into<Option<&'a Cancellable>>>(&self, cancellable: P) -> Result<(), Error> { let cancellable = cancellable.into(); let cancellable = cancellable.to_glib_none(); unsafe { let mut error = ptr::null_mut(); let _ = ffi::g_application_register(self.to_glib_none().0, cancellable.0, &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } fn release(&self) { unsafe { ffi::g_application_release(self.to_glib_none().0); } } #[cfg(any(feature = "v2_40", feature = "dox"))] fn send_notification<'a, P: Into<Option<&'a str>>>(&self, id: P, notification: &Notification) { let id = id.into(); let id = id.to_glib_none(); unsafe { ffi::g_application_send_notification(self.to_glib_none().0, id.0, notification.to_glib_none().0); } } fn set_action_group<'a, P: IsA<ActionGroup> + 'a, Q: Into<Option<&'a P>>>(&self, action_group: Q) { let action_group = action_group.into(); let action_group = action_group.to_glib_none(); unsafe { ffi::g_application_set_action_group(self.to_glib_none().0, action_group.0); } } fn set_application_id<'a, P: Into<Option<&'a str>>>(&self, application_id: P) { let application_id = application_id.into(); let application_id = application_id.to_glib_none(); unsafe { ffi::g_application_set_application_id(self.to_glib_none().0, application_id.0); } } fn set_default(&self) { unsafe { ffi::g_application_set_default(self.to_glib_none().0); } } fn set_flags(&self, flags: ApplicationFlags) { unsafe { ffi::g_application_set_flags(self.to_glib_none().0, flags.to_glib()); } } fn set_inactivity_timeout(&self, inactivity_timeout: u32) { unsafe { ffi::g_application_set_inactivity_timeout(self.to_glib_none().0, inactivity_timeout); } } #[cfg(any(feature = "v2_42", feature = "dox"))] fn set_resource_base_path<'a, P: Into<Option<&'a str>>>(&self, resource_path: P) { let resource_path = resource_path.into(); let resource_path = resource_path.to_glib_none(); unsafe { ffi::g_application_set_resource_base_path(self.to_glib_none().0, resource_path.0); } } #[cfg(any(feature = "v2_44", feature = "dox"))] fn unbind_busy_property<P: IsA<glib::Object>>(&self, object: &P, property: &str) { unsafe { ffi::g_application_unbind_busy_property(self.to_glib_none().0, object.to_glib_none().0, property.to_glib_none().0); } } #[cfg(any(feature = "v2_38", feature = "dox"))] fn unmark_busy(&self) { unsafe { ffi::g_application_unmark_busy(self.to_glib_none().0); } } #[cfg(any(feature = "v2_40", feature = "dox"))] fn withdraw_notification(&self, id: &str) { unsafe { ffi::g_application_withdraw_notification(self.to_glib_none().0, id.to_glib_none().0); } } fn get_property_resource_base_path(&self) -> Option<String> { unsafe { let mut value = Value::from_type(<String as StaticType>::static_type()); gobject_ffi::g_object_get_property(self.to_glib_none().0, "resource-base-path".to_glib_none().0, value.to_glib_none_mut().0); value.get() } } fn set_property_resource_base_path(&self, resource_base_path: Option<&str>) { unsafe { gobject_ffi::g_object_set_property(self.to_glib_none().0, "resource-base-path".to_glib_none().0, Value::from(resource_base_path).to_glib_none().0); } } fn connect_activate<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "activate", transmute(activate_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } //fn connect_command_line<Unsupported or ignored types>(&self, f: F) -> SignalHandlerId { // Ignored command_line: Gio.ApplicationCommandLine //} //#[cfg(any(feature = "v2_40", feature = "dox"))] //fn connect_handle_local_options<Unsupported or ignored types>(&self, f: F) -> SignalHandlerId { // Ignored options: GLib.VariantDict //} fn connect_shutdown<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "shutdown", transmute(shutdown_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } fn connect_startup<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "startup", transmute(startup_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } fn connect_property_action_group_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "notify::action-group", transmute(notify_action_group_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } fn connect_property_application_id_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "notify::application-id", transmute(notify_application_id_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } fn connect_property_flags_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "notify::flags", transmute(notify_flags_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } fn connect_property_inactivity_timeout_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "notify::inactivity-timeout", transmute(notify_inactivity_timeout_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } #[cfg(any(feature = "v2_44", feature = "dox"))] fn connect_property_is_busy_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "notify::is-busy", transmute(notify_is_busy_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } fn connect_property_is_registered_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "notify::is-registered", transmute(notify_is_registered_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } fn connect_property_is_remote_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "notify::is-remote", transmute(notify_is_remote_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } fn connect_property_resource_base_path_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "notify::resource-base-path", transmute(notify_resource_base_path_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } } unsafe extern "C" fn activate_trampoline<P>(this: *mut ffi::GApplication, f: glib_ffi::gpointer) where P: IsA<Application> { callback_guard!(); let f: &&(Fn(&P) + 'static) = transmute(f); f(&Application::from_glib_borrow(this).downcast_unchecked()) } unsafe extern "C" fn shutdown_trampoline<P>(this: *mut ffi::GApplication, f: glib_ffi::gpointer) where P: IsA<Application> { callback_guard!(); let f: &&(Fn(&P) + 'static) = transmute(f); f(&Application::from_glib_borrow(this).downcast_unchecked()) } unsafe extern "C" fn startup_trampoline<P>(this: *mut ffi::GApplication, f: glib_ffi::gpointer) where P: IsA<Application> { callback_guard!(); let f: &&(Fn(&P) + 'static) = transmute(f); f(&Application::from_glib_borrow(this).downcast_unchecked()) } unsafe extern "C" fn notify_action_group_trampoline<P>(this: *mut ffi::GApplication, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<Application> { callback_guard!(); let f: &&(Fn(&P) + 'static) = transmute(f); f(&Application::from_glib_borrow(this).downcast_unchecked()) } unsafe extern "C" fn notify_application_id_trampoline<P>(this: *mut ffi::GApplication, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<Application> { callback_guard!(); let f: &&(Fn(&P) + 'static) = transmute(f); f(&Application::from_glib_borrow(this).downcast_unchecked()) } unsafe extern "C" fn notify_flags_trampoline<P>(this: *mut ffi::GApplication, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<Application> { callback_guard!(); let f: &&(Fn(&P) + 'static) = transmute(f); f(&Application::from_glib_borrow(this).downcast_unchecked()) } unsafe extern "C" fn notify_inactivity_timeout_trampoline<P>(this: *mut ffi::GApplication, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<Application> { callback_guard!(); let f: &&(Fn(&P) + 'static) = transmute(f); f(&Application::from_glib_borrow(this).downcast_unchecked()) } #[cfg(any(feature = "v2_44", feature = "dox"))] unsafe extern "C" fn notify_is_busy_trampoline<P>(this: *mut ffi::GApplication, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<Application> { callback_guard!(); let f: &&(Fn(&P) + 'static) = transmute(f); f(&Application::from_glib_borrow(this).downcast_unchecked()) } unsafe extern "C" fn notify_is_registered_trampoline<P>(this: *mut ffi::GApplication, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<Application> { callback_guard!(); let f: &&(Fn(&P) + 'static) = transmute(f); f(&Application::from_glib_borrow(this).downcast_unchecked()) } unsafe extern "C" fn notify_is_remote_trampoline<P>(this: *mut ffi::GApplication, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<Application> { callback_guard!(); let f: &&(Fn(&P) + 'static) = transmute(f); f(&Application::from_glib_borrow(this).downcast_unchecked()) } unsafe extern "C" fn notify_resource_base_path_trampoline<P>(this: *mut ffi::GApplication, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<Application> { callback_guard!(); let f: &&(Fn(&P) + 'static) = transmute(f); f(&Application::from_glib_borrow(this).downcast_unchecked()) }
mod blake224; mod blake256; mod blake28; mod blake32; mod blake384; mod blake48; mod blake512; mod blake64; use core::cmp::Ordering; use crate::consts::{C32, C64, IV224, IV256, IV384, IV512, SIGMA}; // Round1/2 submission version pub use blake28::Blake28; pub use blake32::Blake32; pub use blake48::Blake48; pub use blake64::Blake64; // Final version pub use blake224::Blake224; pub use blake256::Blake256; pub use blake384::Blake384; pub use blake512::Blake512; // Blake<u32>: BLAKE-224(BLAKE-28) and BLAKE-256(BLAKE-32) // Blake<u64>: BLAKE-384(BLAKE-48) and BLAKE-512(BLAKE-64) struct Blake<T> { salt: [T; 4], l: usize, // 未処理のビット数 pub(crate) h: [T; 8], t: [T; 2], // counter: 処理したビット数(と次に処理をするブロックのビット数?) v: [T; 16], // state ignore_counter: bool, round_limit: usize, } impl Blake<u32> { const fn new(h: [u32; 8], salt: [u32; 4], round_limit: usize) -> Self { Self { salt, l: 0, h, t: [0; 2], v: [0; 16], ignore_counter: false, round_limit, } } #[allow(clippy::too_many_arguments, clippy::many_single_char_names)] fn g(&mut self, block: &[u32; 16], i: usize, r: usize, a: usize, b: usize, c: usize, d: usize) { self.v[a] = self.v[a] .wrapping_add(self.v[b]) .wrapping_add(block[SIGMA[r % 10][2 * i]] ^ C32[SIGMA[r % 10][2 * i + 1]]); self.v[d] = (self.v[d] ^ self.v[a]).rotate_right(16); self.v[c] = self.v[c].wrapping_add(self.v[d]); self.v[b] = (self.v[b] ^ self.v[c]).rotate_right(12); self.v[a] = self.v[a] .wrapping_add(self.v[b]) .wrapping_add(block[SIGMA[r % 10][2 * i + 1]] ^ C32[SIGMA[r % 10][2 * i]]); self.v[d] = (self.v[d] ^ self.v[a]).rotate_right(8); self.v[c] = self.v[c].wrapping_add(self.v[d]); self.v[b] = (self.v[b] ^ self.v[c]).rotate_right(7); } fn compress(&mut self, block: &[u32; 16]) { // update counter if self.l > 512 { self.t[0] += 512; self.l -= 512; } else { self.t[0] += self.l as u32; self.l = 0; } // initialize state self.v[0] = self.h[0]; self.v[1] = self.h[1]; self.v[2] = self.h[2]; self.v[3] = self.h[3]; self.v[4] = self.h[4]; self.v[5] = self.h[5]; self.v[6] = self.h[6]; self.v[7] = self.h[7]; self.v[8] = self.salt[0] ^ C32[0]; self.v[9] = self.salt[1] ^ C32[1]; self.v[10] = self.salt[2] ^ C32[2]; self.v[11] = self.salt[3] ^ C32[3]; // ブロック数が2以上かつ最後のブロックの処理時にカウンター(l)が0のときはこうするらしい(仕様書内に対応する記述を見つけられていない)。 if self.ignore_counter { self.v[12] = C32[4]; self.v[13] = C32[5]; self.v[14] = C32[6]; self.v[15] = C32[7]; } else { self.v[12] = self.t[0] ^ C32[4]; self.v[13] = self.t[0] ^ C32[5]; self.v[14] = self.t[1] ^ C32[6]; self.v[15] = self.t[1] ^ C32[7]; } // round for r in 0..self.round_limit { self.g(block, 0, r, 0, 4, 8, 12); self.g(block, 1, r, 1, 5, 9, 13); self.g(block, 2, r, 2, 6, 10, 14); self.g(block, 3, r, 3, 7, 11, 15); self.g(block, 4, r, 0, 5, 10, 15); self.g(block, 5, r, 1, 6, 11, 12); self.g(block, 6, r, 2, 7, 8, 13); self.g(block, 7, r, 3, 4, 9, 14); } // finalize for i in 0..8 { self.h[i] ^= self.salt[i % 4] ^ self.v[i] ^ self.v[i + 8]; } } fn blake(&mut self, message: &[u8], last_byte: u8) { self.l = message.len() * 8; let l = message.len(); let mut block = [0u32; 16]; if l >= 64 { message.chunks_exact(64).for_each(|bytes| { (0..16).for_each(|i| { block[i] = u32::from_be_bytes([ bytes[i * 4], bytes[i * 4 + 1], bytes[i * 4 + 2], bytes[i * 4 + 3], ]); }); self.compress(&block); }); } else if l == 0 { self.compress(&[ u32::from_be_bytes([0x80, 0, 0, 0]), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, last_byte as u32, 0, 0, ]) } if l != 0 { let offset = (l / 64) * 64; let remainder = l % 64; match (l % 64).cmp(&55) { Ordering::Greater => { // two blocks let mut byte_block = [0u8; 128]; byte_block[..remainder].copy_from_slice(&message[offset..]); byte_block[remainder] = 0x80; byte_block[119] |= last_byte; byte_block[120..].copy_from_slice(&(8 * l as u64).to_be_bytes()); byte_block.chunks_exact(64).for_each(|bytes| { (0..16).for_each(|i| { block[i] = u32::from_be_bytes([ bytes[i * 4], bytes[i * 4 + 1], bytes[i * 4 + 2], bytes[i * 4 + 3], ]); }); self.compress(&block); self.ignore_counter = true; }); } Ordering::Less | Ordering::Equal => { // one block let mut byte_block = [0u8; 64]; byte_block[..remainder].copy_from_slice(&message[offset..]); byte_block[remainder] = 0x80; byte_block[55] |= last_byte; byte_block[56..].copy_from_slice(&(8 * l as u64).to_be_bytes()); (0..16).for_each(|i| { block[i] = u32::from_be_bytes([ byte_block[i * 4], byte_block[i * 4 + 1], byte_block[i * 4 + 2], byte_block[i * 4 + 3], ]); }); if self.l == 0 { self.ignore_counter = true; } self.compress(&block); } } } } } impl Blake<u64> { const fn new(h: [u64; 8], salt: [u64; 4], round_limit: usize) -> Self { Self { salt, l: 0, h, t: [0; 2], v: [0; 16], ignore_counter: false, round_limit, } } #[inline(always)] #[allow(clippy::too_many_arguments, clippy::many_single_char_names)] fn g(&mut self, block: &[u64; 16], i: usize, r: usize, a: usize, b: usize, c: usize, d: usize) { // a,b,c,d: index of self.v // i: number of function G // r: round count self.v[a] = self.v[a] .wrapping_add(self.v[b]) .wrapping_add(block[SIGMA[r % 10][2 * i]] ^ C64[SIGMA[r % 10][2 * i + 1]]); self.v[d] = (self.v[d] ^ self.v[a]).rotate_right(32); self.v[c] = self.v[c].wrapping_add(self.v[d]); self.v[b] = (self.v[b] ^ self.v[c]).rotate_right(25); self.v[a] = self.v[a] .wrapping_add(self.v[b]) .wrapping_add(block[SIGMA[r % 10][2 * i + 1]] ^ C64[SIGMA[r % 10][2 * i]]); self.v[d] = (self.v[d] ^ self.v[a]).rotate_right(16); self.v[c] = self.v[c].wrapping_add(self.v[d]); self.v[b] = (self.v[b] ^ self.v[c]).rotate_right(11); } #[inline(always)] fn compress(&mut self, block: &[u64; 16]) { // update counter if self.l > 1024 { self.t[0] += 1024; self.l -= 1024; } else { self.t[0] += self.l as u64; self.l = 0; } // initialize state self.v[0] = self.h[0]; self.v[1] = self.h[1]; self.v[2] = self.h[2]; self.v[3] = self.h[3]; self.v[4] = self.h[4]; self.v[5] = self.h[5]; self.v[6] = self.h[6]; self.v[7] = self.h[7]; self.v[8] = self.salt[0] ^ C64[0]; self.v[9] = self.salt[1] ^ C64[1]; self.v[10] = self.salt[2] ^ C64[2]; self.v[11] = self.salt[3] ^ C64[3]; // ブロック数が2以上かつ最後のブロックの処理時にカウンター(l)が0のときはこうするらしい(仕様書内に対応する記述を見つけられていない)。 if self.ignore_counter { self.v[12] = C64[4]; self.v[13] = C64[5]; self.v[14] = C64[6]; self.v[15] = C64[7]; } else { self.v[12] = self.t[0] ^ C64[4]; self.v[13] = self.t[0] ^ C64[5]; self.v[14] = self.t[1] ^ C64[6]; self.v[15] = self.t[1] ^ C64[7]; } // round for r in 0..self.round_limit { self.g(block, 0, r, 0, 4, 8, 12); self.g(block, 1, r, 1, 5, 9, 13); self.g(block, 2, r, 2, 6, 10, 14); self.g(block, 3, r, 3, 7, 11, 15); self.g(block, 4, r, 0, 5, 10, 15); self.g(block, 5, r, 1, 6, 11, 12); self.g(block, 6, r, 2, 7, 8, 13); self.g(block, 7, r, 3, 4, 9, 14); } // finalize for i in 0..8 { self.h[i] ^= self.salt[i % 4] ^ self.v[i] ^ self.v[i + 8]; } } #[inline(always)] fn blake(&mut self, message: &[u8], last_byte: u8) { #[inline(always)] fn bytes_to_block(block: &mut [u64; 16], bytes: &[u8]) { // let mut block = [0u64; 16]; for i in 0..16 { block[i] = u64::from_be_bytes([ bytes[i * 8], bytes[i * 8 + 1], bytes[i * 8 + 2], bytes[i * 8 + 3], bytes[i * 8 + 4], bytes[i * 8 + 5], bytes[i * 8 + 6], bytes[i * 8 + 7], ]); } } self.l = message.len() * 8; let l = message.len(); let mut block = [0u64; 16]; if l >= 128 { message.chunks_exact(128).for_each(|bytes| { bytes_to_block(&mut block, bytes); // (0..16).for_each(|i| { // block[i] = u64::from_be_bytes([ // bytes[i * 8], // bytes[i * 8 + 1], // bytes[i * 8 + 2], // bytes[i * 8 + 3], // bytes[i * 8 + 4], // bytes[i * 8 + 5], // bytes[i * 8 + 6], // bytes[i * 8 + 7], // ]); // }); self.compress(&block); }); } else if l == 0 { self.compress(&[ u64::from_be_bytes([0x80, 0, 0, 0, 0, 0, 0, 0]), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, last_byte as u64, 0, 0, ]) } if l != 0 { let offset = (l / 128) * 128; let remainder = l % 128; match (l % 128).cmp(&111) { Ordering::Greater => { // two blocks let mut byte_block = [0u8; 256]; byte_block[..remainder].copy_from_slice(&message[offset..]); byte_block[remainder] = 0x80; byte_block[239] |= last_byte; byte_block[240..].copy_from_slice(&(8 * l as u128).to_be_bytes()); byte_block.chunks_exact(128).for_each(|bytes| { (0..16).for_each(|i| { block[i] = u64::from_be_bytes([ bytes[i * 8], bytes[i * 8 + 1], bytes[i * 8 + 2], bytes[i * 8 + 3], bytes[i * 8 + 4], bytes[i * 8 + 5], bytes[i * 8 + 6], bytes[i * 8 + 7], ]); }); self.compress(&block); self.ignore_counter = true; }); } Ordering::Less | Ordering::Equal => { // one block let mut byte_block = [0u8; 128]; byte_block[..remainder].copy_from_slice(&message[offset..]); byte_block[remainder] = 0x80; byte_block[111] |= last_byte; byte_block[112..].copy_from_slice(&(8 * l as u128).to_be_bytes()); (0..16).for_each(|i| { block[i] = u64::from_be_bytes([ byte_block[i * 8], byte_block[i * 8 + 1], byte_block[i * 8 + 2], byte_block[i * 8 + 3], byte_block[i * 8 + 4], byte_block[i * 8 + 5], byte_block[i * 8 + 6], byte_block[i * 8 + 7], ]); }); if self.l == 0 { self.ignore_counter = true; } self.compress(&block); } } } } }
extern crate num_traits; extern crate sdl2; use num_traits::cast::ToPrimitive; use sdl2::keyboard::Scancode; // XT Scan codes, since I chose the wrong table and I don't feel like changing them // Retro! // NB: Any code longer than 2 bytes is omitted, because who uses `pause` anyway // NB: All nonstandard (multimedia) keys are omitted const SCANCODE_TABLE: &'static [([u8; 2], [u8; 2])] = &[ ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_UNKNOWN ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x1E, 0x00], [0x9E, 0x00]), // SDL_SCANCODE_A ([0x30, 0x00], [0xB0, 0x00]), // SDL_SCANCODE_B ([0x2E, 0x00], [0xAE, 0x00]), // SDL_SCANCODE_C ([0x20, 0x00], [0xA0, 0x00]), // SDL_SCANCODE_D ([0x12, 0x00], [0x92, 0x00]), // SDL_SCANCODE_E ([0x21, 0x00], [0xA1, 0x00]), // SDL_SCANCODE_F ([0x22, 0x00], [0xA2, 0x00]), // SDL_SCANCODE_G ([0x23, 0x00], [0xA3, 0x00]), // SDL_SCANCODE_H ([0x17, 0x00], [0x97, 0x00]), // SDL_SCANCODE_I ([0x24, 0x00], [0xA4, 0x00]), // SDL_SCANCODE_J ([0x25, 0x00], [0xA5, 0x00]), // SDL_SCANCODE_K ([0x26, 0x00], [0xA6, 0x00]), // SDL_SCANCODE_L ([0x32, 0x00], [0xB2, 0x00]), // SDL_SCANCODE_M ([0x31, 0x00], [0xB1, 0x00]), // SDL_SCANCODE_N ([0x18, 0x00], [0x98, 0x00]), // SDL_SCANCODE_O ([0x19, 0x00], [0x99, 0x00]), // SDL_SCANCODE_P ([0x10, 0x00], [0x90, 0x00]), // SDL_SCANCODE_Q ([0x13, 0x00], [0x93, 0x00]), // SDL_SCANCODE_R ([0x1F, 0x00], [0x9F, 0x00]), // SDL_SCANCODE_S ([0x14, 0x00], [0x94, 0x00]), // SDL_SCANCODE_T ([0x16, 0x00], [0x96, 0x00]), // SDL_SCANCODE_U ([0x2F, 0x00], [0xAF, 0x00]), // SDL_SCANCODE_V ([0x11, 0x00], [0x91, 0x00]), // SDL_SCANCODE_W ([0x2D, 0x00], [0xAD, 0x00]), // SDL_SCANCODE_X ([0x15, 0x00], [0x95, 0x00]), // SDL_SCANCODE_Y ([0x2C, 0x00], [0xAC, 0x00]), // SDL_SCANCODE_Z ([0x02, 0x00], [0x82, 0x00]), // SDL_SCANCODE_1 ([0x03, 0x00], [0x83, 0x00]), // SDL_SCANCODE_2 ([0x04, 0x00], [0x84, 0x00]), // SDL_SCANCODE_3 ([0x05, 0x00], [0x85, 0x00]), // SDL_SCANCODE_4 ([0x06, 0x00], [0x86, 0x00]), // SDL_SCANCODE_5 ([0x07, 0x00], [0x87, 0x00]), // SDL_SCANCODE_6 ([0x08, 0x00], [0x88, 0x00]), // SDL_SCANCODE_7 ([0x09, 0x00], [0x89, 0x00]), // SDL_SCANCODE_8 ([0x0A, 0x00], [0x8A, 0x00]), // SDL_SCANCODE_9 ([0x0B, 0x00], [0x8B, 0x00]), // SDL_SCANCODE_0 ([0x1C, 0x00], [0x9C, 0x00]), // SDL_SCANCODE_RETURN ([0x01, 0x00], [0x81, 0x00]), // SDL_SCANCODE_ESCAPE ([0x0E, 0x00], [0x8E, 0x00]), // SDL_SCANCODE_BACKSPACE ([0x0F, 0x00], [0x8F, 0x00]), // SDL_SCANCODE_TAB ([0x39, 0x00], [0xB9, 0x00]), // SDL_SCANCODE_SPACE ([0x0C, 0x00], [0x8C, 0x00]), // SDL_SCANCODE_MINUS ([0x0D, 0x00], [0x8D, 0x00]), // SDL_SCANCODE_EQUALS ([0x1A, 0x00], [0x9A, 0x00]), // SDL_SCANCODE_LEFTBRACKET ([0x1B, 0x00], [0x9B, 0x00]), // SDL_SCANCODE_RIGHTBRACKET ([0x2B, 0x00], [0xAB, 0x00]), // SDL_SCANCODE_BACKSLASH ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_NONUSHASH ([0x27, 0x00], [0xA7, 0x00]), // SDL_SCANCODE_SEMICOLON ([0x28, 0x00], [0xA8, 0x00]), // SDL_SCANCODE_APOSTROPHE ([0x29, 0x00], [0x89, 0x00]), // SDL_SCANCODE_GRAVE ([0x33, 0x00], [0xB3, 0x00]), // SDL_SCANCODE_COMMA ([0x34, 0x00], [0xB4, 0x00]), // SDL_SCANCODE_PERIOD ([0x35, 0x00], [0xB5, 0x00]), // SDL_SCANCODE_SLASH ([0x3A, 0x00], [0xBA, 0x00]), // SDL_SCANCODE_CAPSLOCK ([0x3B, 0x00], [0xBB, 0x00]), // SDL_SCANCODE_F1 ([0x3C, 0x00], [0xBC, 0x00]), // SDL_SCANCODE_F2 ([0x3D, 0x00], [0xBD, 0x00]), // SDL_SCANCODE_F3 ([0x3E, 0x00], [0xBE, 0x00]), // SDL_SCANCODE_F4 ([0x3F, 0x00], [0xBF, 0x00]), // SDL_SCANCODE_F5 ([0x40, 0x00], [0xC0, 0x00]), // SDL_SCANCODE_F6 ([0x41, 0x00], [0xC1, 0x00]), // SDL_SCANCODE_F7 ([0x42, 0x00], [0xC2, 0x00]), // SDL_SCANCODE_F8 ([0x43, 0x00], [0xC3, 0x00]), // SDL_SCANCODE_F9 ([0x44, 0x00], [0xC4, 0x00]), // SDL_SCANCODE_F10 ([0x57, 0x00], [0xD7, 0x00]), // SDL_SCANCODE_F11 ([0x58, 0x00], [0xD8, 0x00]), // SDL_SCANCODE_F12 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_PRINTSCREEN ([0x46, 0x00], [0xC6, 0x00]), // SDL_SCANCODE_SCROLLLOCK ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_PAUSE ([0xE0, 0x52], [0xE0, 0xD2]), // SDL_SCANCODE_INSERT ([0xE0, 0x47], [0xE0, 0x97]), // SDL_SCANCODE_HOME ([0xE0, 0x49], [0xE0, 0xC9]), // SDL_SCANCODE_PAGEUP ([0xE0, 0x53], [0xE0, 0xD3]), // SDL_SCANCODE_DELETE ([0xE0, 0x4F], [0xE0, 0xCF]), // SDL_SCANCODE_END ([0xE0, 0x51], [0xE0, 0xD1]), // SDL_SCANCODE_PAGEDOWN ([0xE0, 0x4D], [0xE0, 0xCD]), // SDL_SCANCODE_RIGHT ([0xE0, 0x4B], [0xE0, 0xCB]), // SDL_SCANCODE_LEFT ([0xE0, 0x50], [0xE0, 0xD0]), // SDL_SCANCODE_DOWN ([0xE0, 0x48], [0xE0, 0xC8]), // SDL_SCANCODE_UP ([0x45, 0x00], [0xC5, 0x00]), // SDL_SCANCODE_NUMLOCKCLEAR ([0xE0, 0x35], [0xE0, 0xB5]), // SDL_SCANCODE_KP_DIVIDE ([0x37, 0x00], [0xB7, 0x00]), // SDL_SCANCODE_KP_MULTIPLY ([0x4A, 0x00], [0xCA, 0x00]), // SDL_SCANCODE_KP_MINUS ([0x4E, 0x00], [0xCE, 0x00]), // SDL_SCANCODE_KP_PLUS ([0xE0, 0x1C], [0xE0, 0x9C]), // SDL_SCANCODE_KP_ENTER ([0x4F, 0x00], [0xCF, 0x00]), // SDL_SCANCODE_KP_1 ([0x50, 0x00], [0xD0, 0x00]), // SDL_SCANCODE_KP_2 ([0x51, 0x00], [0xD1, 0x00]), // SDL_SCANCODE_KP_3 ([0x4B, 0x00], [0xCB, 0x00]), // SDL_SCANCODE_KP_4 ([0x4C, 0x00], [0xCC, 0x00]), // SDL_SCANCODE_KP_5 ([0x4D, 0x00], [0xCD, 0x00]), // SDL_SCANCODE_KP_6 ([0x47, 0x00], [0xC7, 0x00]), // SDL_SCANCODE_KP_7 ([0x48, 0x00], [0xC8, 0x00]), // SDL_SCANCODE_KP_8 ([0x49, 0x00], [0xC9, 0x00]), // SDL_SCANCODE_KP_9 ([0x52, 0x00], [0xD2, 0x00]), // SDL_SCANCODE_KP_0 ([0x53, 0x00], [0xD3, 0x00]), // SDL_SCANCODE_KP_PERIOD ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_NONUSBACKSLASH ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_APPLICATION ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_POWER ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_EQUALS ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_F13 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_F14 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_F15 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_F16 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_F17 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_F18 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_F19 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_F20 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_F21 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_F22 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_F23 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_F24 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_EXECUTE ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_HELP ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_MENU ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_SELECT ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_STOP ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_AGAIN ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_UNDO ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_CUT ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_COPY ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_PASTE ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_FIND ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_MUTE ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_VOLUMEUP ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_VOLUMEDOWN ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_COMMA ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_EQUALSAS400 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_INTERNATIONAL1 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_INTERNATIONAL2 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_INTERNATIONAL3 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_INTERNATIONAL4 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_INTERNATIONAL5 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_INTERNATIONAL6 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_INTERNATIONAL7 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_INTERNATIONAL8 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_INTERNATIONAL9 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_LANG1 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_LANG2 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_LANG3 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_LANG4 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_LANG5 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_LANG6 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_LANG7 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_LANG8 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_LANG9 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_ALTERASE ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_SYSREQ ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_CANCEL ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_CLEAR ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_PRIOR ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_RETURN2 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_SEPARATOR ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_OUT ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_OPER ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_CLEARAGAIN ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_CRSEL ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_EXSEL ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_00 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_000 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_THOUSANDSSEPARATOR ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_DECIMALSEPARATOR ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_CURRENCYUNIT ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_CURRENCYSUBUNIT ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_LEFTPAREN ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_RIGHTPAREN ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_LEFTBRACE ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_RIGHTBRACE ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_TAB ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_BACKSPACE ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_A ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_B ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_C ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_D ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_E ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_F ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_XOR ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_POWER ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_PERCENT ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_LESS ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_GREATER ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_AMPERSAND ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_DBLAMPERSAND ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_VERTICALBAR ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_DBLVERTICALBAR ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_COLON ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_HASH ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_SPACE ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_AT ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_EXCLAM ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_MEMSTORE ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_MEMRECALL ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_MEMCLEAR ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_MEMADD ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_MEMSUBTRACT ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_MEMMULTIPLY ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_MEMDIVIDE ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_PLUSMINUS ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_CLEAR ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_CLEARENTRY ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_BINARY ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_OCTAL ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_DECIMAL ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KP_HEXADECIMAL ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x1D, 0x00], [0x9D, 0x00]), // SDL_SCANCODE_LCTRL ([0x2A, 0x00], [0xAA, 0x00]), // SDL_SCANCODE_LSHIFT ([0x38, 0x00], [0xB8, 0x00]), // SDL_SCANCODE_LALT ([0xE0, 0x5B], [0xE0, 0xDB]), // SDL_SCANCODE_LGUI ([0xE0, 0x1D], [0xE0, 0x9D]), // SDL_SCANCODE_RCTRL ([0x36, 0x00], [0xB6, 0x00]), // SDL_SCANCODE_RSHIFT ([0xE0, 0x38], [0xE0, 0xB8]), // SDL_SCANCODE_RALT ([0xE0, 0x5C], [0xE0, 0xDC]), // SDL_SCANCODE_RGUI ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_MODE ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_AUDIONEXT ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_AUDIOPREV ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_AUDIOSTOP ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_AUDIOPLAY ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_AUDIOMUTE ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_MEDIASELECT ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_WWW ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_MAIL ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_CALCULATOR ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_COMPUTER ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_AC_SEARCH ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_AC_HOME ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_AC_BACK ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_AC_FORWARD ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_AC_STOP ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_AC_REFRESH ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_AC_BOOKMARKS ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_BRIGHTNESSDOWN ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_BRIGHTNESSUP ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_DISPLAYSWITCH ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KBDILLUMTOGGLE ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KBDILLUMDOWN ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_KBDILLUMUP ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_EJECT ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_SLEEP ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_APP1 ([0x00, 0x00], [0x00, 0x00]), // SDL_SCANCODE_APP2 ]; pub fn encode<'a>(code: Scancode, is_pressed: bool) -> &'static [u8] { if is_pressed { &SCANCODE_TABLE[code.to_usize().unwrap()].0 } else { &SCANCODE_TABLE[code.to_usize().unwrap()].1 } } #[cfg(test)] mod tests { use sdl2::keyboard::Scancode; #[test] fn test_alpha() { assert_eq!(::encode(Scancode::A, true), &[0x1E, 0x00]); assert_eq!(::encode(Scancode::A, false), &[0x9E, 0x00]); assert_eq!(::encode(Scancode::R, true), &[0x13, 0x00]); assert_eq!(::encode(Scancode::R, false), &[0x93, 0x00]); } #[test] fn test_mod() { assert_eq!(::encode(Scancode::RShift, true), &[0x36, 0x00]); assert_eq!(::encode(Scancode::RShift, false), &[0xB6, 0x00]); assert_eq!(::encode(Scancode::RCtrl, true), &[0xE0, 0x1D]); assert_eq!(::encode(Scancode::RCtrl, false), &[0xE0, 0x9D]); } }
//! `cargo arch` is a Cargo plugin for making Arch Linux packages. //! Packages' information is extract from `Cargo.toml`. //! You can add additional information in `[package.metadata.arch]` section. #[macro_use] extern crate serde_derive; use clap::{App, load_yaml}; pub mod config; fn build_arch_package(mksrcinfo: bool, build: bool, install: bool, syncdeps: bool, force: bool, manifest_path: Option<&str>) { use std::process::Command; use std::fs::File; use std::io::Write; use crate::config::core::GeneratePackageConfig; config::ArchConfig::new(manifest_path).generate_package_config(); if mksrcinfo { let output = Command::new("makepkg") .args(&["--printsrcinfo"]) .output() .expect("failed to generate .SRCINFO"); let mut file = File::create(".SRCINFO").unwrap(); file.write_all(&output.stdout).unwrap(); } //////////////////// // Build Package //////////////////// if build { let mut args = vec![]; if install { args.push("--install"); } if syncdeps { args.push("--syncdeps"); } if force { args.push("--force"); } Command::new("makepkg") .args(&args) .spawn() .unwrap() .wait() .expect("failed to build package"); } } fn main() { //////////////////// // Parse Arguments //////////////////// let yml = load_yaml!("arguments.yml"); let arguments = App::from_yaml(yml).get_matches(); let arguments = arguments.subcommand_matches("arch").unwrap(); let build = arguments.value_of("build").unwrap().parse::<bool>().unwrap(); let install = arguments.is_present("install"); let syncdeps = arguments.is_present("syncdeps"); let force = arguments.is_present("force"); let mksrcinfo = arguments.is_present("mksrcinfo"); let manifest_path = arguments.value_of("manifest-path"); //////////////////// // Build Arch Package //////////////////// build_arch_package(mksrcinfo, build, install, syncdeps, force, manifest_path); }
use bytes::Bytes; use bytes::BytesMut; use std::error::Error; use std::future::Future; use std::io; use std::pin::Pin; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll, Waker}; use std::time::{Duration, SystemTime}; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite}; use tokio::net::TcpStream; pub fn make_error(desc: &str) -> Box<dyn Error> { Box::new(std::io::Error::new(std::io::ErrorKind::Other, desc)) } pub fn make_io_error(desc: &str) -> std::io::Error { std::io::Error::new(std::io::ErrorKind::Other, desc) } pub struct RelayState { shutdown: bool, waker: Option<Waker>, pending_timestamp: Option<SystemTime>, } impl RelayState { pub fn new() -> Self { Self { shutdown: false, waker: None, pending_timestamp: None, } } fn clear_waker(&mut self) { let _ = self.waker.take(); let _ = self.pending_timestamp.take(); } fn set_waker(&mut self, w: Waker) { self.waker = Some(w); self.pending_timestamp = Some(SystemTime::now()); } pub fn is_closed(&self) -> bool { self.shutdown } pub fn close(&mut self) { if !self.shutdown { self.shutdown = true; if let Some(waker) = self.waker.take() { waker.wake() } } } pub fn pending_elapsed(&self) -> Duration { if self.shutdown { return Duration::from_secs(std::u32::MAX as u64); } match self.pending_timestamp { Some(v) => v.elapsed().unwrap(), None => Duration::from_secs(0), } } } pub struct RelayBufCopy<'a, R: ?Sized, W: ?Sized> { reader: &'a mut R, read_done: bool, writer: &'a mut W, pos: usize, cap: usize, amt: u64, buf: Vec<u8>, state: Arc<Mutex<RelayState>>, } pub fn relay_buf_copy<'a, R, W>( reader: &'a mut R, writer: &'a mut W, buf: Vec<u8>, state: Arc<Mutex<RelayState>>, ) -> RelayBufCopy<'a, R, W> where R: AsyncRead + Unpin + ?Sized, W: AsyncWrite + Unpin + ?Sized, { RelayBufCopy { reader, read_done: false, writer, amt: 0, pos: 0, cap: 0, buf, state, } } impl<R, W> Future for RelayBufCopy<'_, R, W> where R: AsyncRead + Unpin + ?Sized, W: AsyncWrite + Unpin + ?Sized, { type Output = io::Result<u64>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> { loop { self.state.lock().unwrap().clear_waker(); if self.state.lock().unwrap().shutdown { return Poll::Ready(Ok(self.amt)); } // If our buffer is empty, then we need to read some data to // continue. if self.pos == self.cap && !self.read_done { let me = &mut *self; let pin_reader = Pin::new(&mut *me.reader); let n = match pin_reader.poll_read(cx, &mut me.buf) { Poll::Pending => { let mut shared_state = self.state.lock().unwrap(); shared_state.set_waker(cx.waker().clone()); return Poll::Pending; } Poll::Ready(Err(e)) => { return Poll::Ready(Err(e)); } Poll::Ready(Ok(n)) => n, }; //let n = ready!(Pin::new(&mut *me.reader).poll_read(cx, &mut me.buf))?; if n == 0 { self.read_done = true; } else { self.pos = 0; self.cap = n; } } // If our buffer has some data, let's write it out! while self.pos < self.cap { let me = &mut *self; let pin_writer = Pin::new(&mut *me.writer); let i = match pin_writer.poll_write(cx, &me.buf[me.pos..me.cap]) { Poll::Pending => { let mut shared_state = self.state.lock().unwrap(); shared_state.set_waker(cx.waker().clone()); return Poll::Pending; } Poll::Ready(Err(e)) => { return Poll::Ready(Err(e)); } Poll::Ready(Ok(n)) => n, }; //let i = ready!(Pin::new(&mut *me.writer).poll_write(cx, &me.buf[me.pos..me.cap]))?; if i == 0 { return Poll::Ready(Err(io::Error::new( io::ErrorKind::WriteZero, "write zero byte into writer", ))); } else { self.pos += i; self.amt += i as u64; } } // If we've written all the data and we've seen EOF, flush out the // data and finish the transfer. if self.pos == self.cap && self.read_done { let me = &mut *self; let pin_writer = Pin::new(&mut *me.writer); match pin_writer.poll_flush(cx) { Poll::Pending => { let mut shared_state = self.state.lock().unwrap(); shared_state.set_waker(cx.waker().clone()); return Poll::Pending; } Poll::Ready(Err(e)) => { return Poll::Ready(Err(e)); } Poll::Ready(_) => {} } //ready!(Pin::new(&mut *me.writer).poll_flush(cx))?; return Poll::Ready(Ok(self.amt)); } } } } pub async fn read_until_separator( stream: &mut TcpStream, separator: &str, ) -> Result<(Bytes, Bytes), std::io::Error> { let mut buf = BytesMut::with_capacity(1024); let mut b = [0u8; 1024]; loop { let n = stream.read(&mut b).await?; if n > 0 { buf.extend_from_slice(&b[0..n]); } else { return Ok((buf.freeze(), Bytes::default())); } if let Some(pos) = twoway::find_bytes(&buf[..], separator.as_bytes()) { let wsize = separator.len(); let body = buf.split_off(pos + wsize); return Ok((buf.freeze(), body.freeze())); } } } pub fn clear_channel<T>(channel: &mut tokio::sync::mpsc::Receiver<T>) { channel.close(); while true { match channel.try_recv() { Ok(_) => { continue; } _ => { break; } } } } pub fn clear_unbounded_channel<T>(channel: &mut tokio::sync::mpsc::UnboundedReceiver<T>) { channel.close(); while true { match channel.try_recv() { Ok(_) => { continue; } _ => { break; } } } }
use super::PAGE_SIZE; /* * We are targeting x64 and thus use a 4 level paging structure * PML4 -> PDP -> PD -> PT */ // With 4k pages, we can fit 512 8 byte entries per page pub const ENTRY_COUNT: usize = 512; // Since pml4 is recursively mapped, here is the constant addr to access it pub const PML4: *mut PageTable = 0xffffffff_fffff000 as *mut _; // Useful aliases pub type PhysAddress = usize; pub type VirtAddress = usize; bitfield! { pub struct Entry(u64); impl Debug; u8; get_present, set_present: 1, 0; get_writable, set_writable: 2, 1; get_useraccess, set_useraccess: 3, 2; get_writethru, set_writethru: 4, 3; get_disablecache, set_disablecache: 5, 4; get_accessed, set_accessed: 6, 5; get_dirty, set_dirty: 7, 6; get_hugepage, set_hugepage: 8, 7; get_global, set_global: 9, 8; get_unused1, set_unused1: 12, 9; u64, get_physaddr, set_physaddr: 52, 12; u8; get_unused2, set_unused2: 63, 52; get_nx, set_nx: 64, 63; } impl<'r> Entry<'r> { fn check_unused(&self) -> bool { return self.0 as u64 == 0; } } // TODO: Come up with some way to specify page table level (pml4, pdp, pd, pt) pub struct PageTable { entries: [Entry; ENTRY_COUNT], } impl Index<usize> for PageTable { type Output = Entry; fn index(&self, index: usize) -> &Entry { &self.entries[index] } } impl IndexMut<usize> for PageTable { fn index_mut(&mut self, index: usize) -> &mut Entry { &mut self.entries[index] } } impl PageTable { fn get_entry_address(&self, index: usize) -> Option<usize> { let entry: Entry = self[index]; if entry.get_present() && !entry.get_hugepage() { let pt_addr = self as *const _ as usize; Some((pt_addr << 9) | (index << 12)) } else { None } } // If you call these on pt, bad things will happen. They also require recursively mapped tables pub fn get_entry<'a>(&'a self, index: usize) -> Option<&'a PageTable> { // Do some weird stuff (address -> raw pointer -> dereference raw pointer and make it a reference) self.get_entry_address(index).map(|addr| unsafe { & *(addr as *const _) }) } pub fn get_entry_mut<'a>(&'a self, index: usize) -> Option<&'a mut PageTable> { // Do some weird stuff (address -> raw pointer -> dereference raw pointer and make it a reference) self.get_entry_address(index).map(|addr| unsafe { &mut *(addr as *mut _) }) } }
#![deny(clippy::all, clippy::pedantic)] #[derive(Clone, Copy, PartialEq, Debug)] pub enum Direction { North = 0, East = 1, South = 2, West = 3, } use Direction::{East, North, South, West}; const DIRECTIONS: [Direction; 4] = [North, East, South, West]; pub struct Robot { x: i32, y: i32, facing: Direction, } impl Robot { pub fn new(x: i32, y: i32, facing: Direction) -> Self { Self { x, y, facing } } pub fn turn_right(mut self) -> Self { self.facing = DIRECTIONS[(self.facing as usize + 1) % 4]; self } pub fn turn_left(mut self) -> Self { self.facing = DIRECTIONS[(self.facing as usize).checked_sub(1).unwrap_or(3) % 4]; self } pub fn advance(mut self) -> Self { match self.facing { North => self.y += 1, East => self.x += 1, South => self.y -= 1, West => self.x -= 1, } self } pub fn instructions(mut self, instructions: &str) -> Self { for c in instructions.chars() { self = match c { 'A' => self.advance(), 'L' => self.turn_left(), 'R' => self.turn_right(), _ => self, }; } self } pub fn position(&self) -> (i32, i32) { (self.x, self.y) } pub fn direction(&self) -> &Direction { &self.facing } }
use arduino_mqtt_pin::pin::{PinOperation, Temperature, PinCollection, PinState, PinValue}; use std::collections::HashMap; use chrono::{DateTime, Local, NaiveDateTime, TimeZone}; use diesel::{insert_into, RunQueryDsl, SqliteConnection}; use diesel::prelude::*; use arduino_mqtt_pin::helper::average; use crate::config::ControlNodes; use crate::schema::pin_states; use crate::schema::temperatures; use crate::schema::pin_states::BoxedQuery; use diesel::query_dsl::QueryDsl; use uuid::Uuid; use diesel::sqlite::{Sqlite}; use derive_new::{new}; pub type States = HashMap<String, HashMap<u8, PinCollection>>; #[derive(new, Insertable, Queryable, Identifiable, Debug, PartialEq)] #[table_name = "pin_states"] struct PinRow { id: String, name: String, pin: i32, input_type: i32, value: i32, dtc: NaiveDateTime } // #[derive(new, Insertable, Queryable, Identifiable, Debug, PartialEq)] #[table_name = "temperatures"] struct PinTemperature { id: String, name: String, pin: i32, temperature: f32, dtc: NaiveDateTime } #[derive(new)] pub struct PinStateRepository<'a> { conn: &'a SqliteConnection } struct PinStateBuilder { builder: BoxedQuery<'static, Sqlite> } impl PinStateBuilder { pub fn from_name(name_id: &str, pin_id: u8) -> PinStateBuilder { use crate::schema::pin_states::dsl::{name, pin, pin_states}; let builder: BoxedQuery<'static, Sqlite> = pin_states.filter(name.eq(name_id.to_owned())) .filter(pin.eq(pin_id as i32)).into_boxed(); PinStateBuilder { builder } } pub fn with_value(self, state: bool) -> PinStateBuilder { use crate::schema::pin_states::dsl::{value}; if state { PinStateBuilder { builder: self.builder.filter(value.gt(0)) } } else { PinStateBuilder { builder: self.builder.filter(value.eq(0)) } } } pub fn with_less(self, time: &NaiveDateTime) -> PinStateBuilder { use crate::schema::pin_states::dsl::{dtc}; PinStateBuilder { builder: self.builder.filter(dtc.lt(time.clone())) } } pub fn with_less_or_eq(self, time: &NaiveDateTime) -> PinStateBuilder { use crate::schema::pin_states::dsl::{dtc}; PinStateBuilder { builder: self.builder.filter(dtc.le(time.clone())) } } pub fn within_period(self, from: &NaiveDateTime, to: &NaiveDateTime) -> PinStateBuilder { use crate::schema::pin_states::dsl::{dtc}; PinStateBuilder { builder: self.builder .filter(dtc.le(to.clone())) .filter(dtc.gt(from.clone())) } } pub fn order_by_time(self, desc: bool) -> PinStateBuilder { use crate::schema::pin_states::dsl::{dtc}; if desc { PinStateBuilder { builder: self.builder.order(dtc.desc() ) } } else { PinStateBuilder { builder: self.builder.order(dtc.asc() ) } } } pub fn first_to_state(self, conn: &SqliteConnection) -> Option<PinState> { self.builder.limit(1).load::<PinRow>(conn).ok() .and_then(|arr| { arr.first().and_then(|row| { Some(PinState::new( row.pin as u8, match row.input_type { 0 => PinValue::Digital(row.value > 0), _ => PinValue::Analog(row.value as u16) }, Local.from_local_datetime(&row.dtc).single()?, None )) }) }) } } impl PinStateRepository<'_> { pub fn save_state(&self, op: &PinOperation) { use crate::schema::temperatures::dsl::{temperatures}; use crate::schema::pin_states::dsl::{pin_states}; if let PinValue::Temperature(temp) = &op.pin_state.value { let temp = PinTemperature::new(format!("{}", Uuid::new_v4()), op.node.clone(), op.pin_state.pin as i32, temp.value, op.pin_state.dt.naive_local()); insert_into(temperatures).values(&temp).execute(self.conn).unwrap(); } else { let pin = PinRow::new( format!("{}", Uuid::new_v4()), op.node.clone(), op.pin_state.pin as i32, match op.pin_state.value { PinValue::Digital(v) => 0, _ => 1 }, op.pin_state.value.as_u16() as i32, op.pin_state.dt.naive_local() ); insert_into(pin_states).values(&pin).execute(self.conn).unwrap(); } } pub fn get_last_changed_pin_state(&self, name_id: &str, pin_id: u8) -> Option<PinState> { self.get_pin_changes(name_id, pin_id, 1).and_then(|arr| arr.first().cloned() ) } pub fn get_last_pin_state(&self, name_id: &str, pin_id: u8) -> Option<PinState> { PinStateBuilder::from_name(name_id, pin_id).order_by_time(true).first_to_state(self.conn) } // node1 0 12:32:36 -> returns // node1 1 12:32:35 -> returns // node1 0 12:32:34 // node1 0 12:32:33 -> returns // node2 1 12:32:38 // node3 1 12:32:37 -> returns pub fn get_pin_changes(&self, name_id: &str, pin_id: u8, how_many: usize) -> Option<Vec<PinState>> { if let Some(changed_dates) = self.get_latest_pin_change_dates(name_id, pin_id, how_many + 1) { let mut it = changed_dates.into_iter(); let mut state_arr = Vec::new(); let mut i = 0; let mut latest_state = it.next(); while i < how_many { if let Some((latest_value, latest_dtc)) = latest_state { if let Some((previous_value, previous_dtc)) = it.next() { if let Some(state) = PinStateBuilder::from_name(name_id, pin_id) .with_value(latest_value) .order_by_time(false) .within_period(&previous_dtc, &latest_dtc) .first_to_state(self.conn) { state_arr.push(state); } latest_state = Some((previous_value, previous_dtc)); } else { if let Some(state) = PinStateBuilder::from_name(name_id, pin_id) .with_value(latest_value) .order_by_time(false) .with_less_or_eq(&latest_dtc) .first_to_state(self.conn) { state_arr.push(state); } latest_state = None; } } else { break; } i += 1; } return Some(state_arr); } None } pub fn get_average_temperature(&self, name_id: &str, pin_id: u8, since: &DateTime<Local>) -> Option<Temperature> { use crate::schema::temperatures::dsl::*; let values = temperatures.filter(pin.eq(pin_id as i32)) .filter(dtc.ge(since.naive_local())) .filter(name.eq(name_id)) .select(temperature) .load::<f32>(self.conn); values.ok().and_then(|v| if v.len() > 0 { Some(v) } else { None }).map(|v| Temperature::new(average(&v))) } // node1 1 333 12:32:32 // node1 2 333 12:32:33 // node1 2 0 12:32:34 // node2 1 0 12:32:35 // node3 3 0 12:32:36 // node1 1 222 12:32:37 pub fn get_first_zone_on_dt(&self, control_nodes: &ControlNodes, since: &DateTime<Local>) -> Option<DateTime<Local>> { control_nodes.iter().filter_map(|(control_name, control_node)| { control_node.zones.iter().filter_map(|(zone_name, zone)| { self.get_last_changed_pin_state(control_name, zone.control_pin).and_then(|state| { state.is_on(); if state.is_on() && state.dt > *since { Some(state.dt) } else { None } }) }).min() }).min().map(|dt| dt.clone()) } // returns only pairs // node1 1 12:32:33 -> returns // node1 1 12:32:32 // node1 0 12:32:36 -> returns // node1 0 12:32:33 // node1 1 12:32:37 -> returns fn get_latest_pin_change_dates(&self, name_id: &str, pin_id: u8, size: usize) -> Option<Vec<(bool, NaiveDateTime)>> { if let Some(state) = self.get_last_pin_state(name_id, pin_id) { let mut arr = vec![(state.is_on(), state.dt.naive_local())]; let mut state_index = state; while arr.len() < size { if let Some(state) = PinStateBuilder::from_name(name_id, pin_id) .with_value(!state_index.is_on()) .order_by_time(true) .with_less(&state_index.dt.naive_local()) .first_to_state(self.conn) { arr.push((state.value.is_on(), state.dt.naive_local())); state_index = state; } else { break; } } return Some(arr); } None } } #[cfg(test)] pub mod test_repository { use speculate::speculate; use super::*; use arduino_mqtt_pin::pin::PinValue; use chrono::{TimeZone, NaiveTime}; use crate::zone::{Zone, Interval}; use crate::config::{ControlNode}; use crate::embedded_migrations; pub fn get_data() -> HashMap<String, HashMap<u8, Vec<PinState>>> { let pin_one_states = vec![ PinState::new(1, PinValue::Analog(0), Local.ymd(2019, 8, 1).and_hms(8, 0, 0), None), PinState::new(1, PinValue::Analog(0), Local.ymd(2019, 8, 1).and_hms(8, 1, 0), None), PinState::new(1, PinValue::Analog(0), Local.ymd(2019, 8, 1).and_hms(8, 2, 0), None), PinState::new(1, PinValue::Analog(255), Local.ymd(2019, 8, 2).and_hms(8, 0, 0), None), ]; let temperature_one_states = vec![ PinState::new(4, PinValue::Temperature(Temperature::new(18.5)), Local.ymd(2019, 8, 2).and_hms(7, 40, 0), None), PinState::new(4, PinValue::Temperature(Temperature::new(17.0)), Local.ymd(2019, 8, 2).and_hms(8, 3, 0), None), PinState::new(4, PinValue::Temperature(Temperature::new(18.5)), Local.ymd(2019, 8, 2).and_hms(8, 30, 0), None), PinState::new(4, PinValue::Temperature(Temperature::new(19.5)), Local.ymd(2019, 8, 2).and_hms(8, 50, 0), None), PinState::new(4, PinValue::Temperature(Temperature::new(19.5)), Local.ymd(2019, 8, 2).and_hms(8, 55, 0), None), ]; let pin_two_states = vec![ PinState::new(2, PinValue::Analog(122), Local.ymd(2019, 8, 1).and_hms(8, 0, 0), None), PinState::new(2, PinValue::Analog(0), Local.ymd(2019, 8, 1).and_hms(9, 0, 0), None), PinState::new(2, PinValue::Analog(0), Local.ymd(2019, 8, 1).and_hms(10, 0, 0), None), PinState::new(2, PinValue::Analog(0), Local.ymd(2019, 8, 1).and_hms(11, 0, 0), None), ]; let temperature_two_states = vec![ PinState::new(4, PinValue::Temperature(Temperature::new(20.5)), Local.ymd(2019, 8, 1).and_hms(8, 50, 0), None), ]; let pin_five_states = vec![ PinState::new(5, PinValue::Analog(0), Local.ymd(2019, 8, 2).and_hms(8, 5, 0), None), ]; let temperature_five_states = vec![ PinState::new(4, PinValue::Temperature(Temperature::new(22.5)), Local.ymd(2019, 8, 2).and_hms(8, 30, 0), None), ]; let pin_heater_states = vec![ PinState::new(34, PinValue::Digital(true), Local.ymd(2019, 8, 2).and_hms(8, 10, 0), None), PinState::new(34, PinValue::Digital(true), Local.ymd(2019, 8, 2).and_hms(8, 11, 0), None), PinState::new(34, PinValue::Digital(true), Local.ymd(2019, 8, 2).and_hms(8, 12, 0), None), ]; let pin_eight_states = vec![ PinState::new(8, PinValue::Analog(1), Local.ymd(2018, 8, 2).and_hms(8, 5, 0), None), PinState::new(8, PinValue::Analog(0), Local.ymd(2018, 8, 2).and_hms(8, 6, 0), None), PinState::new(8, PinValue::Analog(0), Local.ymd(2018, 8, 2).and_hms(8, 7, 0), None), PinState::new(8, PinValue::Analog(0), Local.ymd(2018, 8, 2).and_hms(8, 8, 0), None), PinState::new(8, PinValue::Analog(1), Local.ymd(2018, 8, 2).and_hms(8, 9, 0), None), PinState::new(8, PinValue::Analog(1), Local.ymd(2018, 8, 2).and_hms(8, 9, 1), None), PinState::new(8, PinValue::Analog(1), Local.ymd(2018, 8, 2).and_hms(8, 9, 2), None), PinState::new(8, PinValue::Analog(1), Local.ymd(2018, 8, 2).and_hms(8, 9, 3), None), PinState::new(8, PinValue::Analog(0), Local.ymd(2018, 8, 2).and_hms(8, 10, 0), None), PinState::new(8, PinValue::Analog(0), Local.ymd(2018, 8, 2).and_hms(8, 11, 0), None), ]; let pin_nine_states = vec![ PinState::new(9, PinValue::Analog(1), Local.ymd(2018, 8, 2).and_hms(8, 5, 0), None), PinState::new(9, PinValue::Analog(1), Local.ymd(2018, 8, 2).and_hms(8, 6, 0), None), PinState::new(9, PinValue::Analog(0), Local.ymd(2018, 8, 2).and_hms(8, 7, 0), None), PinState::new(9, PinValue::Analog(0), Local.ymd(2018, 8, 2).and_hms(8, 8, 0), None), PinState::new(9, PinValue::Analog(1), Local.ymd(2018, 8, 2).and_hms(8, 9, 0), None), PinState::new(9, PinValue::Analog(1), Local.ymd(2018, 8, 2).and_hms(8, 9, 1), None), PinState::new(9, PinValue::Analog(1), Local.ymd(2018, 8, 2).and_hms(8, 9, 2), None), PinState::new(9, PinValue::Analog(1), Local.ymd(2018, 8, 2).and_hms(8, 9, 3), None), PinState::new(9, PinValue::Analog(1), Local.ymd(2018, 8, 2).and_hms(8, 10, 0), None), PinState::new(9, PinValue::Analog(1), Local.ymd(2018, 8, 2).and_hms(8, 11, 0), None), ]; let data = map!{ "main".to_owned() => map!{ 1 => pin_one_states, 2 => pin_two_states, 5 => pin_five_states, 8 => pin_eight_states, 9 => pin_nine_states, 34 => pin_heater_states }, "zone1".to_owned() => map!{ 4 => temperature_one_states }, "zone2".to_owned() => map!{ 4 => temperature_two_states }, "zone4".to_owned() => map!{ 4 => temperature_five_states } }; data } pub fn create_repository(conn: &SqliteConnection) -> PinStateRepository { let data = get_data(); let repo = PinStateRepository::new(conn); for (op_name, pin_states) in data { for (pin, states) in pin_states { for state in states { repo.save_state(&PinOperation::new(state, op_name.clone())); } } } repo } pub fn create_zone(control_pin: u8) -> Zone { let intervals = vec![ Interval::new(NaiveTime::from_hms(8, 0, 0), NaiveTime::from_hms(9, 0, 0), Temperature::new(20.0)), Interval::new(NaiveTime::from_hms(23, 1, 0), NaiveTime::from_hms(23, 31, 0), Temperature::new(30.5)) ]; Zone::new(format!("zone{}", control_pin), 4, intervals, control_pin) } pub fn create_nodes() -> ControlNodes { let nodes = map!{"main".to_owned() => ControlNode::new( "main".to_owned(), 34, map!{ "zone1".to_owned() => create_zone(1), "zone2".to_owned() => create_zone(2), "zone4".to_owned() => create_zone(4) } )}; nodes } speculate!{ describe "state repository" { before { let connection = SqliteConnection::establish(":memory:").unwrap(); embedded_migrations::run(&connection); let repository = create_repository(&connection); let data = get_data(); } it "should get last pin state" { for (name, expected, pin) in vec![ ("exists 1", true, 1), ("exists 2", true, 2), ("does not exists", false, 3), ] { assert_eq!( repository.get_last_changed_pin_state("main", pin).is_some(), expected, "{}", name ); } for (expected, pin) in vec![ (255, 1), ( 0, 2), ] { assert_eq!( repository.get_last_changed_pin_state("main", pin).unwrap().value, PinValue::Analog(expected), "should be: {}", expected ); } } it "should get last pins" { for (zone, pin, get_len, expected_indexes) in vec![ ("main", 8, 5, vec![8, 4, 1, 0]), ("main", 9, 2, vec![4, 2]), ] { assert_eq!( repository.get_pin_changes(zone, pin, get_len).unwrap()[..], data.get(zone).and_then(|m| m.get(&pin)).map(|data_array| expected_indexes.iter().map(|i| data_array[*i].clone()).collect::<Vec<PinState>>()).unwrap()[..], ); } } it "should get average temperature" { let since = Local.ymd(2019, 8, 2).and_hms(8, 30, 0); assert_eq!( repository.get_average_temperature("zone1", 4, &since).expect("zone 1 temp"), Temperature::new(19.166666) ); assert!( repository.get_average_temperature("main", 34, &since).is_none() ); assert_eq!( repository.get_average_temperature("zone4", 4, &since).expect("zone 5 temp"), Temperature::new(22.5) ); } it "should get last dt on" { let nodes = create_nodes(); let since = Local.ymd(2019, 8, 1).and_hms(7, 0, 0); let expected = Local.ymd(2019, 8, 2).and_hms(8, 0, 0); assert_eq!( repository.get_first_zone_on_dt(&nodes, &since), Some(expected) ); let since = Local.ymd(2019, 9, 1).and_hms(7, 0, 0); assert_eq!( repository.get_first_zone_on_dt(&nodes, &since), None ); } } } }
mod echo; mod pitch; mod select; mod volume; use nom::{ branch::alt, bytes::complete::tag, combinator::{map, opt}, multi::separated_list0, number::complete::float, IResult, }; pub use self::{ echo::EchoModifier, pitch::PitchModifier, select::SelectModifier, volume::VolumeModifier, }; use crate::BoxSource; pub trait ModifierTrait: Send + std::fmt::Debug + PartialEq { fn parse(input: &str) -> IResult<&str, Self> where Self: Sized; fn modify(&self, source: BoxSource) -> BoxSource { source } } #[derive(Debug, PartialEq)] pub enum Modifier { Pitch(PitchModifier), Volume(VolumeModifier), Echo(EchoModifier), Select(SelectModifier), } impl ModifierTrait for Modifier { fn parse(input: &str) -> IResult<&str, Self> { alt(( map(PitchModifier::parse, Modifier::Pitch), map(VolumeModifier::parse, Modifier::Volume), map(EchoModifier::parse, Modifier::Echo), map(SelectModifier::parse, Modifier::Select), ))(input) } fn modify(&self, source: BoxSource) -> BoxSource { match self { Modifier::Pitch(modifier) => modifier.modify(source), Modifier::Volume(modifier) => modifier.modify(source), Modifier::Echo(modifier) => modifier.modify(source), Modifier::Select(modifier) => modifier.modify(source), } } } pub fn parse_modifier(input: &str) -> IResult<&str, Modifier> { // input = ":pitch(2)" let (input, _) = tag(":")(input)?; // input = "pitch(2)" let (input, modifier) = Modifier::parse(input)?; Ok((input, modifier)) } type Args = Vec<Option<f32>>; fn parse_arg(input: &str) -> IResult<&str, Option<f32>> { // " 123 ," // ^ let input = input.trim_start(); let (input, maybe) = opt(float)(input)?; // " ," // ^ let input = input.trim_start(); Ok((input, maybe)) } fn parse_arg_list(s: &str) -> IResult<&str, Args> { let sep = tag(","); let mut list = Vec::new(); // fix separated_list0 not working if you start with a separator let mut s = s; loop { let (s2, maybe_first) = opt(&sep)(s)?; s = s2; if maybe_first.is_some() { list.push(None); } else { break; } } let (s, mut items) = separated_list0(&sep, parse_arg)(s)?; list.append(&mut items); Ok((s, list)) } pub fn parse_args(input: &str) -> IResult<&str, Args> { let (input, _) = tag("(")(input)?; // fix for "( )" // " )" // ^ let input = input.trim_start(); let (input, args) = opt(parse_arg_list)(input)?; let (input, _) = tag(")")(input)?; Ok((input, args.unwrap_or_default())) } #[test] fn test_parse_args() { assert_eq!(parse_args("()"), Ok(("", vec![None]))); assert_eq!(parse_args("( )"), Ok(("", vec![None]))); assert_eq!(parse_args("(1)"), Ok(("", vec![Some(1.0)]))); assert_eq!(parse_args("(1, 3)"), Ok(("", vec![Some(1.0), Some(3.0)]))); assert_eq!( parse_args("(1, 3, 5)"), Ok(("", vec![Some(1.0), Some(3.0), Some(5.0)])) ); assert_eq!( parse_args("( 1 , 3 , 5 )"), Ok(("", vec![Some(1.0), Some(3.0), Some(5.0)])) ); assert_eq!(parse_args("( , )"), Ok(("", vec![None, None]))); assert_eq!(parse_args("( , 2 )"), Ok(("", vec![None, Some(2.0)]))); assert_eq!( parse_args("( , 2 , )"), Ok(("", vec![None, Some(2.0), None])) ); assert_eq!( parse_args("(, , 2 , ,)"), Ok(("", vec![None, None, Some(2.0), None, None])) ); assert_eq!( parse_args("( , 2 , ,)"), Ok(("", vec![None, Some(2.0), None, None])) ); assert_eq!( parse_args("( , -2.1 , ,)"), Ok(("", vec![None, Some(-2.1), None, None])) ); }
use crate::cell::{ Merge }; use std::ops::{ Add, Sub, Mul, Div }; use ordered_float::NotNan; #[derive(Hash, Debug, PartialEq, Eq, Clone)] pub struct Float(NotNan<f64>); impl Float { pub fn new(val: f64) -> Self { Self(NotNan::new(val).unwrap()) } } impl Add for Float { type Output = Float; fn add(self, other: Self) -> Self { Self(self.0 + other.0) } } impl Sub for Float { type Output = Float; fn sub(self, other: Self) -> Self { Self(self.0 - other.0) } } impl Merge for Float { fn is_valid(&self, value: &Self) -> bool { self == value } fn merge(&self, _other: &Self) -> Self { self.clone() } }
use std::env; use log::error; use nego::http; fn main() { env::set_var("RUST_LOG", "debug"); env_logger::init(); let args: Vec<String> = env::args().collect(); if args.len() != 2 { error!("Bad number of arguments."); std::process::exit(1); } let mut server = http::Server::new(&args[1]).unwrap_or_else(|e| { error!("{}", e); panic!(); }); server.run().unwrap_or_else(|e| { error!("{}", e); panic!(); }); }
use crate::config; use crate::maze::maze_genotype::MazeGenome; use crate::mcc::maze::maze_queue::MazeQueue; #[derive(Debug, Clone)] pub struct MazeSpeciesStatistics { average_sizes: Vec<f64>, maximum_sizes: Vec<u32>, minimum_sizes: Vec<u32>, average_size_increases: Vec<f64>, average_path_complexities: Vec<f64>, maximum_path_complexities: Vec<u32>, minimum_path_complexities: Vec<u32>, average_path_complexity_increases: Vec<f64>, } impl MazeSpeciesStatistics { pub fn get_overall_average_increase(&self) -> f64 { if self.average_size_increases.is_empty() { return 0.0; } self.average_size_increases.iter().sum::<f64>() as f64 / self.average_size_increases.len() as f64 } pub fn get_overall_average_path_complexity_increase(&self) -> f64 { if self.average_path_complexity_increases.is_empty() { return 0.0; } self.average_path_complexity_increases.iter().sum::<f64>() as f64 / self.average_path_complexity_increases.len() as f64 } pub fn get_current_average_size_increase(&self) -> f64 { let last = self.average_size_increases.last(); if last.is_some() { *last.unwrap() } else { 0.0 } } pub fn get_current_average_complexity_increase(&self) -> f64 { let last = self.average_path_complexity_increases.last(); if last.is_some() { *last.unwrap() } else { 0.0 } } pub fn get_overall_score(&self) -> f64 { self.get_overall_average_increase() + self.get_overall_average_path_complexity_increase() } } #[derive(Debug, Clone)] pub struct MazeSpecies { centroid: MazeGenome, pub maze_queue: MazeQueue, pub id: u32, pub statistics: MazeSpeciesStatistics, } impl MazeSpecies { pub fn new(maze: MazeGenome, max_items_limit: u32, id: u32) -> MazeSpecies { MazeSpecies { maze_queue: MazeQueue::new(vec![maze.clone()], max_items_limit), centroid: maze.clone(), id, statistics: MazeSpeciesStatistics { average_sizes: vec![], maximum_sizes: vec![], minimum_sizes: vec![], average_size_increases: vec![], average_path_complexities: vec![], maximum_path_complexities: vec![], minimum_path_complexities: vec![], average_path_complexity_increases: vec![], }, } } pub fn iter(&self) -> impl Iterator<Item = &MazeGenome> { self.maze_queue.iter() } pub fn len(&self) -> usize { self.maze_queue.len() } pub fn push(&mut self, agent: MazeGenome) { self.maze_queue.push(agent); } pub fn get_children(&mut self, amount: usize) -> Vec<MazeGenome> { self.maze_queue.get_children(amount) } pub fn distance(&self, other: &MazeGenome) -> f64 { self.centroid.distance(other) } pub fn save_state(&mut self) { let last_average_size = self.statistics.average_sizes.last(); if last_average_size.is_some() { let new_average_increase = self.maze_queue.get_average_size() - *last_average_size.unwrap(); self.statistics .average_size_increases .push(new_average_increase); } else { let new_average_increase = self.maze_queue.get_average_size() - config::MCC.default_maze_size as f64; self.statistics .average_size_increases .push(new_average_increase); } let last_average_complexity = self.statistics.average_path_complexities.last(); if last_average_complexity.is_some() { let new_average_complexity = self.maze_queue.get_average_path_size() - *last_average_complexity.unwrap(); self.statistics .average_path_complexity_increases .push(new_average_complexity); } self.statistics .average_sizes .push(self.maze_queue.get_average_size()); self.statistics .maximum_sizes .push(self.maze_queue.get_largest_size()); self.statistics .minimum_sizes .push(self.maze_queue.get_smallest_size()); self.statistics .average_path_complexities .push(self.maze_queue.get_average_path_size()); self.statistics .maximum_path_complexities .push(self.maze_queue.get_largest_path_size()); self.statistics .minimum_path_complexities .push(self.maze_queue.get_smallest_path_size()); } }
extern crate cgmath; #[macro_use] extern crate puck_core; extern crate alto; extern crate lewton; extern crate time; extern crate notify; extern crate rand; extern crate image; #[macro_use] extern crate gfx; extern crate gfx_device_gl; extern crate gfx_window_glutin; extern crate glutin; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate multimap; pub mod audio; pub mod render; pub mod app; pub mod input; pub mod dimensions; pub mod camera; pub mod resources; pub use input::*; pub use camera::*; pub use dimensions::*; pub use resources::*; use std::io; use std::path::PathBuf; pub type PuckResult<T> = Result<T, PuckError>; #[derive(Debug)] pub enum PuckError { IO(io::Error), FileDoesntExist(PathBuf), PipelineError(gfx::PipelineStateError<String>), CombinedGFXError(gfx::CombinedError), ContextError(glutin::ContextError), NoTexture(), NoPipeline(), BufferCreationError(gfx::buffer::CreationError), TextureCreationError(gfx::texture::CreationError), ResourceViewError(gfx::ResourceViewError), // FontLoadError(FontLoadError), ImageError(image::ImageError), MustLoadTextureBeforeFont, NoFiles, MismatchingDimensions, // path buf, expectation RenderingPipelineIncomplete, } impl From<image::ImageError> for PuckError { fn from(err: image::ImageError) -> Self { PuckError::ImageError(err) } } impl From<io::Error> for PuckError { fn from(val: io::Error) -> PuckError { PuckError::IO(val) } } #[derive(Copy, Clone)] pub struct RenderTick { pub n: u64, pub accu_alpha: f64, // percentage of a frame that has accumulated pub tick_rate: u64, // per second }
//! Container types returned during partial parsing. use std::io::{Read, Seek}; use crate::error::TychoResult; use crate::partial::container::{PartialContainer, PartialContainerType}; use crate::partial::element::{PartialElement, read_partial_element}; use crate::partial::reader::PartialReader; use crate::read::string::read_tstring; use crate::read::value::read_value; use crate::types::ident::ValueIdent; use crate::Value; use crate::partial::PartialPointer; use crate::read::func::read_bytes; #[derive(Debug, Clone)] /// The inner implementation structure for a struct. pub struct PartialStructInner; impl PartialContainerType for PartialStructInner { type ItemType = (String, PartialElement); type ItemParam = (); fn read_item<R: Read + Seek>(reader: &mut PartialReader<R>, _: &()) -> TychoResult<Self::ItemType> { let key = read_tstring(reader)?; let value = read_partial_element(reader)?; Ok((key, value)) } } /// A unprocessed struct object. pub type PartialStruct = PartialContainer<PartialStructInner>; #[derive(Debug, Clone)] /// The inner implementation structure for a list. pub struct PartialListInner; impl PartialContainerType for PartialListInner { type ItemType = PartialElement; type ItemParam = (); fn read_item<R: Read + Seek>(reader: &mut PartialReader<R>, _: &()) -> TychoResult<Self::ItemType> { read_partial_element(reader) } } /// A unprocessed list object. pub type PartialList = PartialContainer<PartialListInner>; #[derive(Debug, Clone)] /// The inner implementation structure for a map. pub struct PartialMapInner; impl PartialContainerType for PartialMapInner { type ItemType = (Value, PartialElement); type ItemParam = ValueIdent; fn read_item<R: Read + Seek>(reader: &mut PartialReader<R>, params: &ValueIdent) -> TychoResult<Self::ItemType> { let key = read_value(reader, &params)?; let value = read_partial_element(reader)?; Ok((key, value)) } } /// A unprocessed map object. pub type PartialMap = PartialContainer<PartialMapInner>; #[derive(Debug, Clone)] /// The inner implementation structure for a array. pub struct PartialArrayInner; impl PartialContainerType for PartialArrayInner { type ItemType = Value; type ItemParam = ValueIdent; fn read_item<R: Read + Seek>(reader: &mut PartialReader<R>, params: &ValueIdent) -> TychoResult<Self::ItemType> { let item = read_value(reader, &params)?; Ok(item) } } /// A unprocessed array object. pub type PartialArray = PartialContainer<PartialArrayInner>; #[derive(Debug, Clone)] /// A unprocessed compression object. pub struct PartialCompression { pub pointer: PartialPointer, } impl PartialCompression { pub(crate) fn new(pointer: PartialPointer) -> Self { PartialCompression { pointer } } /// Get the bytes within the compression object. pub fn bytes<R: Read + Seek>(&mut self, reader: &mut PartialReader<R>) -> TychoResult<Vec<u8>> { let top = reader.pointer.clone(); reader.jump(&self.pointer.pos)?; let bytes = read_bytes(reader, self.pointer.size as usize)?; reader.jump(&top)?; Ok(bytes) } #[cfg(feature="compression")] /// Get the element within the compression object. /// /// (requires `compression` feature) pub fn element<R: Read + Seek>(&mut self, reader: &mut PartialReader<R>) -> TychoResult<PartialElement> { let top = reader.pointer.clone(); reader.jump(&self.pointer.pos)?; let element = read_partial_element(reader)?; reader.jump(&top)?; Ok(element) } } #[cfg(feature = "async_tokio")] pub use super::async_::types::PartialCompressionAsync;
use std::env; use std::fs; use std::path::Path; use colored::*; use std::{thread, time}; const MATRIX_SIZE:i32 = 100; fn read_light_setup(filename:&str) -> String{ let fpath = Path::new(filename); let abspath = env::current_dir() .unwrap() .into_boxed_path() .join(fpath); let light_data = fs::read_to_string(abspath) .expect("Error reading light data!"); return light_data; } fn set_initial_light_config(light_data:&str,is_game_of_life:bool)->Vec<Vec<[i32;2]>>{ let mut lights = vec![vec![[0i32;2];MATRIX_SIZE as usize];MATRIX_SIZE as usize]; for (r, row) in light_data.lines().enumerate(){ for (c,light) in row.chars().enumerate(){ match light{ '.' => lights[r][c] = [0,0], '#' => lights[r][c] = [1,0], _ => panic!("Unexpected value!") } } } if is_game_of_life{ set_restrictions( &mut lights); } return lights; } fn set_restrictions(lights:&mut Vec<Vec<[i32;2]>>){ let msize:usize = MATRIX_SIZE as usize; lights[0][0] = [1,0]; lights[0][msize-1] = [1,0]; lights[msize-1][0] = [1,0]; lights[msize-1][msize-1] =[1,0]; } fn let_there_be_light(lights:&mut Vec<Vec<[i32;2]>>, steps:i32, is_game_of_life:bool){ let msize:usize = (MATRIX_SIZE -1) as usize; let restricted = vec![(0,0),(msize,0),(0,msize),(msize,msize)]; for _t in 0..steps{ for r in 0..MATRIX_SIZE{ for c in 0..MATRIX_SIZE{ if is_game_of_life{ let is_restricted = restricted.iter() .position(|&e|e.0 == r as usize && e.1 == c as usize); if is_restricted != None{ continue; } } let (on, _off) = scan_adjacent(lights, r, c); match lights[r as usize][c as usize][0]{ 0 => { if on == 3 { lights[r as usize][c as usize][1] = 1; continue; } lights[r as usize][c as usize][1] = lights[r as usize][c as usize][0] }, 1 => { if on != 2 && on != 3 { lights[r as usize][c as usize][1]= 0; continue; } lights[r as usize][c as usize][1] = lights[r as usize][c as usize][0] }, _ => () } } } debug_lights(lights,is_game_of_life); } } fn scan_adjacent(lights:&mut Vec<Vec<[i32;2]>>, r:i32, c:i32)->(i32, i32){ let directions = vec![(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1)]; let (mut on, mut off) = (0,0); for d in directions.iter(){ let dc =d.0 + c; let dr = d.1+ r; if dc < MATRIX_SIZE && dr < MATRIX_SIZE && dc >= 0 && dr >= 0{ match lights[dr as usize][dc as usize][0]{ 0 => off += 1, 1 => on +=1, _ => () } } } return (on, off); } fn debug_lights(lights:&mut Vec<Vec<[i32;2]>>, is_game_of_life:bool){ let tsleep = time::Duration::from_millis(5); let msize:usize = (MATRIX_SIZE -1) as usize; let restricted = vec![(0,0),(msize,0),(0,msize),(msize,msize)]; //print!("{}[2J", 27 as char); for r in 0..MATRIX_SIZE as usize{ for c in 0..MATRIX_SIZE as usize{ if is_game_of_life{ let is_restricted = restricted.iter() .position(|&e|e.0 == r && e.1 == c); if is_restricted == None{ lights[r][c].swap(1, 0); } }else{ lights[r][c].swap(1, 0); } match lights[r][c][0]{ 0 => print!("{}", "⚯".black()), 1 => print!("{}", "⊷".bright_cyan() ), _ => () } } println!("{}",""); } thread::sleep(tsleep); } fn count_lights(lights:&mut Vec<Vec<[i32;2]>>) -> i32{ let mut count = 0; for r in 0..MATRIX_SIZE as usize{ for c in 0..MATRIX_SIZE as usize{ match lights[r][c][0]{ 1 => count+=1, _ => () } } } return count; } pub fn run(){ let light_data = read_light_setup("inputs/day-18.txt"); let mut lights = set_initial_light_config(&light_data, false); let_there_be_light(&mut lights, 100, false); let count =count_lights(&mut lights); println!("\n\nPART I: {}", count); println!("{}", "\n \n Resuming in 5 seconds...\n"); let tsleep = time::Duration::from_secs(5); thread::sleep(tsleep); let mut lights = set_initial_light_config(&light_data, true); let_there_be_light(&mut lights, 100, true); let count =count_lights(&mut lights); println!("\n\n PART II: {}", count); }
use crate::irust::buffer::Buffer; use crate::irust::irust_error::IRustError; use crate::irust::{CTRL_KEYMODIFIER, NO_MODIFIER}; use crate::utils::StringTools; use crossterm::{event::*, style::Color}; enum Dir { Up, Down, } impl super::IRust { pub fn handle_up(&mut self) -> Result<(), IRustError> { if self.printer.cursor.is_at_first_input_line() { let buffer = self.buffer.take(); self.handle_history(Dir::Up, buffer)?; self.history.lock(); } else { self.printer.cursor.move_up_bounded(1); // set buffer cursor let buffer_pos = self.printer.cursor.cursor_pos_to_buffer_pos(); self.buffer.set_buffer_pos(buffer_pos); } Ok(()) } pub fn handle_down(&mut self) -> Result<(), IRustError> { if self.buffer.is_empty() { return Ok(()); } if self.printer.cursor.is_at_last_input_line(&self.buffer) { let buffer = self.buffer.take(); self.handle_history(Dir::Down, buffer)?; self.history.lock(); } else { self.printer.cursor.move_down_bounded(1, &self.buffer); // set buffer cursor let buffer_pos = self.printer.cursor.cursor_pos_to_buffer_pos(); self.buffer.set_buffer_pos(buffer_pos); } Ok(()) } fn handle_history(&mut self, direction: Dir, buffer: Vec<char>) -> Result<(), IRustError> { let history = match direction { Dir::Up => self.history.up(&buffer), Dir::Down => self.history.down(&buffer), }; if let Some(history) = history { self.buffer = Buffer::from_string(&history); } else { self.buffer.buffer = buffer; } self.printer.print_input(&self.buffer, &self.theme)?; let last_input_pos = self.printer.cursor.input_last_pos(&self.buffer); self.buffer.goto_end(); self.printer.cursor.goto(last_input_pos.0, last_input_pos.1); Ok(()) } pub fn handle_ctrl_r(&mut self) -> Result<(), IRustError> { // make space for the search bar if self.printer.cursor.is_at_last_terminal_row() { self.printer.scroll_up(1); } self.printer.cursor.goto_input_start_col(); const SEARCH_TITLE: &str = "search history: "; const TITLE_WIDTH: usize = 16; // SEARCH_TITLE.chars().count() self.printer.write_at_no_cursor( &SEARCH_TITLE, Color::Red, 0, self.printer.cursor.bound.height - 1, )?; let mut needle = String::new(); use std::io::Write; loop { self.printer.writer.raw.flush()?; if let Ok(key_event) = read() { match key_event { Event::Key(KeyEvent { code: KeyCode::Char(c), modifiers: NO_MODIFIER, }) => { // max search len if StringTools::chars_count(&needle) + TITLE_WIDTH == self.printer.cursor.bound.width - 1 { continue; } needle.push(c); // search history if let Some(hit) = self.history.find(&needle) { self.buffer = Buffer::from_string(&hit); } else { self.buffer = Buffer::new(); } self.printer.print_input(&self.buffer, &self.theme)?; self.printer.clear_last_line()?; self.printer.write_at_no_cursor( &SEARCH_TITLE, Color::Red, 0, self.printer.cursor.bound.height - 1, )?; self.printer.write_at_no_cursor( &needle, Color::White, TITLE_WIDTH, self.printer.cursor.bound.height - 1, )?; } Event::Key(KeyEvent { code: KeyCode::Backspace, .. }) => { needle.pop(); // search history if !needle.is_empty() { if let Some(hit) = self.history.find(&needle) { self.buffer = Buffer::from_string(&hit); } else { self.buffer = Buffer::new(); } self.printer.print_input(&self.buffer, &self.theme)?; } else { self.buffer = Buffer::new(); self.printer.print_input(&self.buffer, &self.theme)?; } self.printer.clear_last_line()?; self.printer.write_at_no_cursor( &SEARCH_TITLE, Color::Red, 0, self.printer.cursor.bound.height - 1, )?; self.printer.write_at_no_cursor( &needle, Color::White, TITLE_WIDTH, self.printer.cursor.bound.height - 1, )?; } Event::Key(KeyEvent { code: KeyCode::Char('c'), modifiers: CTRL_KEYMODIFIER, }) => { self.buffer.clear(); self.printer.print_input(&self.buffer, &self.theme)?; needle.clear(); self.printer.clear_last_line()?; self.printer.write_at_no_cursor( &SEARCH_TITLE, Color::Red, 0, self.printer.cursor.bound.height - 1, )?; } Event::Key(KeyEvent { code: KeyCode::Enter, .. }) | Event::Key(KeyEvent { code: KeyCode::Esc, .. }) => break, Event::Key(KeyEvent { code: KeyCode::Char('d'), modifiers: CTRL_KEYMODIFIER, }) => { if needle.is_empty() { break; } } _ => (), } } } self.printer.clear_last_line()?; self.printer.print_input(&self.buffer, &self.theme)?; Ok(()) } }
// Copyright (c) 2020 Ant Financial // // SPDX-License-Identifier: Apache-2.0 // pub mod agent; pub mod agent_ttrpc; pub mod empty; mod gogo; pub mod health; pub mod health_ttrpc; mod oci; pub mod types;
use rand::random; use std::fmt::Debug; trait ReservoirSampler { // 每种抽样器只会在一种总体中抽样,而总体中所有个体都属于相同类型 type Item; // 流式采样器无法知道总体数据有多少个样本,因此只逐个处理,并返回是否将样本纳入 // 样本池的结果,以及可能被替换出来的样本 fn sample(&mut self, it: Self::Item) -> (bool, Option<Self::Item>); // 任意时候应当知道当前蓄水池的状态 fn samples(&self) -> &[Option<Self::Item>]; } struct Lottery<P> { // 记录当前参与的总人数 total: usize, // 奖品的名称与人数 prices: Vec<Price>, // 当前的幸运儿 lucky: Vec<Option<P>>, } #[derive(Clone, Debug)] struct Price { name: String, cap: usize, } impl<P> ReservoirSampler for Lottery<P> { type Item = P; fn sample(&mut self, it: Self::Item) -> (bool, Option<Self::Item>) { let lucky_cap = self.lucky.capacity(); self.total += 1; // 概率渐小的随机替换 let r = random::<usize>() % self.total + 1; let mut replaced = None; if r <= lucky_cap { replaced = self.lucky[r - 1].take(); self.lucky[r - 1] = Some(it); } if self.total <= lucky_cap && r < self.total { self.lucky[self.total - 1] = replaced.take(); } (r <= lucky_cap, replaced) } fn samples(&self) -> &[Option<Self::Item>] { &self.lucky[..] } } impl<P: Debug> Lottery<P> { fn release(self) -> Result<Vec<(String, Vec<P>)>, &'static str> { let lucky_cap = self.lucky.capacity(); if self.lucky.len() == 0 { return Err("No one attended to the lottery!"); } let mut final_lucky = self.lucky.into_iter().collect::<Vec<Option<P>>>(); let mut i = self.total; while i < lucky_cap { i += 1; // 概率渐小的随机替换 let r = random::<usize>() % i + 1; if r <= lucky_cap { final_lucky[i - 1] = final_lucky[r - 1].take(); } } println!("{:?}", final_lucky); let mut result = Vec::with_capacity(self.prices.len()); let mut counted = 0; for p in self.prices { let mut luck = Vec::with_capacity(p.cap); for i in 0 .. p.cap { if let Some(it) = final_lucky[counted + i].take() { luck.push(it); } } result.push((p.name, luck)); counted += p.cap; } Ok(result) } } // 构建者模式(Builder Pattern),将所有可能的初始化行为提取到单独的构建者结构中,以保证初始化 // 后的对象(Target)的数据可靠性。此处用以保证所有奖品都确定后才能开始抽奖 struct LotteryBuilder { prices: Vec<Price>, } impl LotteryBuilder { fn new() -> Self { LotteryBuilder { prices: Vec::new(), } } fn add_price(&mut self, name: &str, cap: usize) -> &mut Self { self.prices.push(Price { name: name.into(), cap }); self } fn build<P: Clone>(&self) -> Lottery<P> { let lucky_cap = self.prices.iter() .map(|p| p.cap) .sum::<usize>(); Lottery { total: 0, prices: self.prices.clone(), lucky: std::vec::from_elem(Option::<P>::None, lucky_cap), } } } fn main() { let v = vec![8, 1, 1, 9, 2]; let mut lottery = LotteryBuilder::new() .add_price("一等奖", 1) .add_price("二等奖", 1) .add_price("三等奖", 5) .build::<usize>(); for it in v { lottery.sample(it); println!("{:?}", lottery.samples()); } println!("{:?}", lottery.release().unwrap()); }
#[doc = "Reader of register CONN_4_DATA_LIST_ACK"] pub type R = crate::R<u32, super::CONN_4_DATA_LIST_ACK>; #[doc = "Writer for register CONN_4_DATA_LIST_ACK"] pub type W = crate::W<u32, super::CONN_4_DATA_LIST_ACK>; #[doc = "Register CONN_4_DATA_LIST_ACK `reset()`'s with value 0"] impl crate::ResetValue for super::CONN_4_DATA_LIST_ACK { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `LIST_INDEX__TX_ACK_3_0_C1`"] pub type LIST_INDEX__TX_ACK_3_0_C1_R = crate::R<u8, u8>; #[doc = "Write proxy for field `LIST_INDEX__TX_ACK_3_0_C1`"] pub struct LIST_INDEX__TX_ACK_3_0_C1_W<'a> { w: &'a mut W, } impl<'a> LIST_INDEX__TX_ACK_3_0_C1_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } #[doc = "Write proxy for field `SET_CLEAR_C1`"] pub struct SET_CLEAR_C1_W<'a> { w: &'a mut W, } impl<'a> SET_CLEAR_C1_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } impl R { #[doc = "Bits 0:3 - Write: Indicates the buffer index for which the ACK bit is being updated by firmware. The default number of buffers in the IP is 5. The index range is 0-3. Read: Reads TX_ACK\\[3:0\\] If a particular bit is set, then the packet in the selected buffer has been transmitted (at least once) by the hardware and hardware is waiting for acknowledgement. Example1 : If the read value is : 0x03, then packets in FIFO-0 and FIFO-1 are acknowledged by the remote device. These acknowledgements are pending to be processed by firmware. Example2 : If the read value is : 0x02, then packet FIFO-1 is acknowledged by the remote device. This acknowledgement is pending to be processed by firmware."] #[inline(always)] pub fn list_index__tx_ack_3_0_c1(&self) -> LIST_INDEX__TX_ACK_3_0_C1_R { LIST_INDEX__TX_ACK_3_0_C1_R::new((self.bits & 0x0f) as u8) } } impl W { #[doc = "Bits 0:3 - Write: Indicates the buffer index for which the ACK bit is being updated by firmware. The default number of buffers in the IP is 5. The index range is 0-3. Read: Reads TX_ACK\\[3:0\\] If a particular bit is set, then the packet in the selected buffer has been transmitted (at least once) by the hardware and hardware is waiting for acknowledgement. Example1 : If the read value is : 0x03, then packets in FIFO-0 and FIFO-1 are acknowledged by the remote device. These acknowledgements are pending to be processed by firmware. Example2 : If the read value is : 0x02, then packet FIFO-1 is acknowledged by the remote device. This acknowledgement is pending to be processed by firmware."] #[inline(always)] pub fn list_index__tx_ack_3_0_c1(&mut self) -> LIST_INDEX__TX_ACK_3_0_C1_W { LIST_INDEX__TX_ACK_3_0_C1_W { w: self } } #[doc = "Bit 7 - Write: Firmware uses the field to clear and ACK bit in the hardware to indicate that the acknowledgement for the transmit packet has been received and processed by firmware. Firmware clears the ACK bit in the hardware by writing in this register only after the acknowledgement is processed successfully by firmware. For clearing ack for a packet transmitted in fifo-index : '3', firm-ware will write '3' in the 'list-index' field and set this bit (BIT7) to 0. This is the indication that the corresponding packet buffer identi-fied by List-Index is cleared of previous transmission and can be re-used for another packet from now on. The ACK bit in hardware is set by hardware when it has success-fully transmitted a packet."] #[inline(always)] pub fn set_clear_c1(&mut self) -> SET_CLEAR_C1_W { SET_CLEAR_C1_W { w: self } } }
mod bot; mod result; mod models; pub use self::bot::DexBot; pub use self::result::TelegramResult; pub use self::fetcher::{DefinitionFetcher, MockDefinitionFetcher}; mod fetcher { pub trait DefinitionFetcher { fn new(name: &str) -> Self; fn name(&self) -> &str; fn get_definitions(&self, word: &str) -> Vec<&str>; } pub struct MockDefinitionFetcher { name: String, } impl DefinitionFetcher for MockDefinitionFetcher { fn new(name: &str) -> MockDefinitionFetcher { MockDefinitionFetcher { name: String::from(name), } } fn name(&self) -> &str { &self.name } fn get_definitions(&self, word: &str) -> Vec<&str> { let definitions = hashmap! { "doggo" => vec!["good boy", "very good boy"], "pupper" => vec!["small good boy", "tiny good boy"], "woofer" => vec!["large good boy", "oversized doggo"], }; match definitions.get(word) { Some(definitions) => definitions.to_owned(), None => Vec::new(), } } } }
//! # zk-SNARK MPCs, made easy. //! //! ## Make your circuit //! //! Grab the [`bellperson`](https://github.com/filecoin-project/bellman) crate. Bellman //! provides a trait called `Circuit`, which you must implement //! for your computation. //! //! Here's a silly example: proving you know the cube root of //! a field element. //! //! ```no_run //! use fff::Field; //! use bellperson::{ //! Circuit, //! ConstraintSystem, //! SynthesisError, //! bls::Engine, //! }; //! //! struct CubeRoot<E: Engine> { //! cube_root: Option<E::Fr> //! } //! //! impl<E: Engine> Circuit<E> for CubeRoot<E> { //! fn synthesize<CS: ConstraintSystem<E>>( //! self, //! cs: &mut CS //! ) -> Result<(), SynthesisError> //! { //! // Witness the cube root //! let root = cs.alloc(|| "root", || { //! self.cube_root.ok_or(SynthesisError::AssignmentMissing) //! })?; //! //! // Witness the square of the cube root //! let square = cs.alloc(|| "square", || { //! self.cube_root //! .ok_or(SynthesisError::AssignmentMissing) //! .map(|mut root| {root.square(); root }) //! })?; //! //! // Enforce that `square` is root^2 //! cs.enforce( //! || "squaring", //! |lc| lc + root, //! |lc| lc + root, //! |lc| lc + square //! ); //! //! // Witness the cube, as a public input //! let cube = cs.alloc_input(|| "cube", || { //! self.cube_root //! .ok_or(SynthesisError::AssignmentMissing) //! .map(|root| { //! let mut tmp = root; //! tmp.square(); //! tmp.mul_assign(&root); //! tmp //! }) //! })?; //! //! // Enforce that `cube` is root^3 //! // i.e. that `cube` is `root` * `square` //! cs.enforce( //! || "cubing", //! |lc| lc + root, //! |lc| lc + square, //! |lc| lc + cube //! ); //! //! Ok(()) //! } //! } //! ``` //! //! ## Create some proofs //! //! Now that we have `CubeRoot<E>` implementing `Circuit`, //! let's create some parameters and make some proofs. //! //! ```compile_fail,no_run //! use bellperson::bls::{Bls12, Fr}; //! use bellperson::groth16::{ //! generate_random_parameters, //! create_random_proof, //! prepare_verifying_key, //! verify_proof //! }; //! use rand::rngs::OsRng; //! //! let rng = &mut OsRng::new(); //! //! // Create public parameters for our circuit //! let params = { //! let circuit = CubeRoot::<Bls12> { //! cube_root: None //! }; //! //! generate_random_parameters::<Bls12, _, _>( //! circuit, //! rng //! ).unwrap() //! }; //! //! // Prepare the verifying key for verification //! let pvk = prepare_verifying_key(&params.vk); //! //! // Let's start making proofs! //! for _ in 0..50 { //! // Verifier picks a cube in the field. //! // Let's just make a random one. //! let root = Fr::rand(rng); //! let mut cube = root; //! cube.square(); //! cube.mul_assign(&root); //! //! // Prover gets the cube, figures out the cube //! // root, and makes the proof: //! let proof = create_random_proof( //! CubeRoot::<Bls12> { //! cube_root: Some(root) //! }, &params, rng //! ).unwrap(); //! //! // Verifier checks the proof against the cube //! assert!(verify_proof(&pvk, &proof, &[cube]).unwrap()); //! } //! ``` //! ## Creating parameters //! //! Notice in the previous example that we created our zk-SNARK //! parameters by calling `generate_random_parameters`. However, //! if you wanted you could have called `generate_parameters` //! with some secret numbers you chose, and kept them for //! yourself. Given those numbers, you can create false proofs. //! //! In order to convince others you didn't, a multi-party //! computation (MPC) can be used. The MPC has the property that //! only one participant needs to be honest for the parameters to //! be secure. This crate (`filecoin-phase2`) is about creating parameters //! securely using such an MPC. //! //! Let's start by using `filecoin-phase2` to create some base parameters //! for our circuit: //! //! ```compile_fail,no_run //! let mut params = crate::MPCParameters::new(CubeRoot { //! cube_root: None //! }).unwrap(); //! ``` //! //! The first time you try this, it will try to read a file like //! `phase1radix2m2` from the current directory. You need to grab //! that from the [Powers of Tau](https://lists.z.cash.foundation/pipermail/zapps-wg/2018/000362.html). //! //! These parameters are not safe to use; false proofs can be //! created for them. Let's contribute some randomness to these //! parameters. //! //! ```compile_fail,no_run //! // Contribute randomness to the parameters. Remember this hash, //! // it's how we know our contribution is in the parameters! //! let hash = params.contribute(rng); //! ``` //! //! These parameters are now secure to use, so long as you weren't //! malicious. That may not be convincing to others, so let them //! contribute randomness too! `params` can be serialized and sent //! elsewhere, where they can do the same thing and send new //! parameters back to you. Only one person needs to be honest for //! the final parameters to be secure. //! //! Once you're done setting up the parameters, you can verify the //! parameters: //! //! ```compile_fail,no_run //! let contributions = params.verify(CubeRoot { //! cube_root: None //! }).expect("parameters should be valid!"); //! //! // We need to check the `contributions` to see if our `hash` //! // is in it (see above, when we first contributed) //! assert!(crate::contains_contribution(&contributions, &hash)); //! ``` //! //! Great, now if you're happy, grab the Groth16 `Parameters` with //! `params.params()`, so that you can interact with the bellman APIs //! just as before. #![deny(clippy::all, clippy::perf, clippy::correctness, rust_2018_idioms)] pub mod small; use std::{ fmt::{self, Debug, Formatter}, fs::File, io::{self, BufReader, Read, Write}, sync::Arc, }; use bellperson::bls::{ Bls12, Engine, Fr, G1Affine, G1Projective, G1Uncompressed, G2Affine, G2Projective, G2Uncompressed, PairingCurveAffine, }; use bellperson::{ groth16::{Parameters, VerifyingKey}, multicore::Worker, Circuit, ConstraintSystem, Index, LinearCombination, SynthesisError, Variable, }; use blake2b_simd::State as Blake2b; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use fff::{Field, PrimeField}; use groupy::{CurveAffine, CurveProjective, EncodedPoint, Wnaf}; use log::{error, info}; use rand::{Rng, SeedableRng}; use rand_chacha::ChaChaRng; use rayon::prelude::*; use crate::small::MPCSmall; /// This is our assembly structure that we'll use to synthesize the /// circuit into a QAP. struct KeypairAssembly<E: Engine> { num_inputs: usize, num_aux: usize, num_constraints: usize, at_inputs: Vec<Vec<(E::Fr, usize)>>, bt_inputs: Vec<Vec<(E::Fr, usize)>>, ct_inputs: Vec<Vec<(E::Fr, usize)>>, at_aux: Vec<Vec<(E::Fr, usize)>>, bt_aux: Vec<Vec<(E::Fr, usize)>>, ct_aux: Vec<Vec<(E::Fr, usize)>>, } impl<E: Engine> KeypairAssembly<E> { /// Returns the size (stack plus heap) of the `KeypairAssembly` in bytes. fn size(&self) -> usize { use std::mem::{size_of, size_of_val}; let mut size = 3 * size_of::<usize>(); size += 6 * size_of::<Vec<Vec<(E::Fr, usize)>>>(); size += size_of_val::<[Vec<(E::Fr, usize)>]>(&self.at_inputs); size += size_of_val::<[Vec<(E::Fr, usize)>]>(&self.bt_inputs); size += size_of_val::<[Vec<(E::Fr, usize)>]>(&self.ct_inputs); size += size_of_val::<[Vec<(E::Fr, usize)>]>(&self.at_aux); size += size_of_val::<[Vec<(E::Fr, usize)>]>(&self.bt_aux); size += size_of_val::<[Vec<(E::Fr, usize)>]>(&self.ct_aux); for el in self.at_inputs.iter() { size += size_of_val::<[(E::Fr, usize)]>(el); } for el in self.bt_inputs.iter() { size += size_of_val::<[(E::Fr, usize)]>(el); } for el in self.ct_inputs.iter() { size += size_of_val::<[(E::Fr, usize)]>(el); } for el in self.at_aux.iter() { size += size_of_val::<[(E::Fr, usize)]>(el); } for el in self.bt_aux.iter() { size += size_of_val::<[(E::Fr, usize)]>(el); } for el in self.ct_aux.iter() { size += size_of_val::<[(E::Fr, usize)]>(el); } size } } impl<E: Engine> ConstraintSystem<E> for KeypairAssembly<E> { type Root = Self; fn alloc<F, A, AR>(&mut self, _: A, _: F) -> Result<Variable, SynthesisError> where F: FnOnce() -> Result<E::Fr, SynthesisError>, A: FnOnce() -> AR, AR: Into<String>, { // There is no assignment, so we don't even invoke the // function for obtaining one. let index = self.num_aux; self.num_aux += 1; self.at_aux.push(vec![]); self.bt_aux.push(vec![]); self.ct_aux.push(vec![]); Ok(Variable::new_unchecked(Index::Aux(index))) } fn alloc_input<F, A, AR>(&mut self, _: A, _: F) -> Result<Variable, SynthesisError> where F: FnOnce() -> Result<E::Fr, SynthesisError>, A: FnOnce() -> AR, AR: Into<String>, { // There is no assignment, so we don't even invoke the // function for obtaining one. let index = self.num_inputs; self.num_inputs += 1; self.at_inputs.push(vec![]); self.bt_inputs.push(vec![]); self.ct_inputs.push(vec![]); Ok(Variable::new_unchecked(Index::Input(index))) } fn enforce<A, AR, LA, LB, LC>(&mut self, _: A, a: LA, b: LB, c: LC) where A: FnOnce() -> AR, AR: Into<String>, LA: FnOnce(LinearCombination<E>) -> LinearCombination<E>, LB: FnOnce(LinearCombination<E>) -> LinearCombination<E>, LC: FnOnce(LinearCombination<E>) -> LinearCombination<E>, { fn eval<E: Engine>( l: LinearCombination<E>, inputs: &mut [Vec<(E::Fr, usize)>], aux: &mut [Vec<(E::Fr, usize)>], this_constraint: usize, ) { for (&var, &coeff) in l.iter() { match var.get_unchecked() { Index::Input(id) => inputs[id].push((coeff, this_constraint)), Index::Aux(id) => aux[id].push((coeff, this_constraint)), } } } eval( a(LinearCombination::zero()), &mut self.at_inputs, &mut self.at_aux, self.num_constraints, ); eval( b(LinearCombination::zero()), &mut self.bt_inputs, &mut self.bt_aux, self.num_constraints, ); eval( c(LinearCombination::zero()), &mut self.ct_inputs, &mut self.ct_aux, self.num_constraints, ); self.num_constraints += 1; } fn push_namespace<NR, N>(&mut self, _: N) where NR: Into<String>, N: FnOnce() -> NR, { // Do nothing; we don't care about namespaces in this context. } fn pop_namespace(&mut self) { // Do nothing; we don't care about namespaces in this context. } fn get_root(&mut self) -> &mut Self::Root { self } } /// MPC parameters are just like bellman `Parameters` except, when serialized, /// they contain a transcript of contributions at the end, which can be verified. #[derive(Clone)] pub struct MPCParameters { params: Parameters<Bls12>, cs_hash: [u8; 64], contributions: Vec<PublicKey>, } // Required by `assert_eq!()`. impl Debug for MPCParameters { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("MPCParameters") .field("params", &"<bellman::groth16::Parameters>") .field("cs_hash", &self.cs_hash.to_vec()) .field("contributions", &self.contributions.to_vec()) .finish() } } impl PartialEq for MPCParameters { fn eq(&self, other: &MPCParameters) -> bool { self.params == other.params && self.cs_hash[..] == other.cs_hash[..] && self.contributions == other.contributions } } impl MPCParameters { /// Create new Groth16 parameters (compatible with bellman) for a /// given circuit. The resulting parameters are unsafe to use /// until there are contributions (see `contribute()`). pub fn new<C>(circuit: C) -> Result<MPCParameters, SynthesisError> where C: Circuit<Bls12>, { let mut assembly = KeypairAssembly { num_inputs: 0, num_aux: 0, num_constraints: 0, at_inputs: vec![], bt_inputs: vec![], ct_inputs: vec![], at_aux: vec![], bt_aux: vec![], ct_aux: vec![], }; // Allocate the "one" input variable assembly.alloc_input(|| "", || Ok(Fr::one()))?; // Synthesize the circuit. circuit.synthesize(&mut assembly)?; // Input constraints to ensure full density of IC query // x * 0 = 0 for i in 0..assembly.num_inputs { assembly.enforce( || "", |lc| lc + Variable::new_unchecked(Index::Input(i)), |lc| lc, |lc| lc, ); } info!( "phase2::MPCParameters::new() Constraint System: n_constraints={}, n_inputs={}, n_aux={}, memsize={}b", assembly.num_constraints, assembly.num_inputs, assembly.num_aux, assembly.size() ); // Compute the size of our evaluation domain, `m = 2^exp`. let mut m = 1; let mut exp = 0; while m < assembly.num_constraints { m *= 2; exp += 1; // Powers of Tau ceremony can't support more than 2^30 if exp > 30 { return Err(SynthesisError::PolynomialDegreeTooLarge); } } // Try to load "phase1radix2m{}" info!( "phase2::MPCParameters::new() phase1.5_file=phase1radix2m{}", exp ); let f = match File::open(format!("phase1radix2m{}", exp)) { Ok(f) => f, Err(e) => { panic!("Couldn't load phase1radix2m{}: {:?}", exp, e); } }; let f = &mut BufReader::with_capacity(1024 * 1024, f); let read_g1 = |reader: &mut BufReader<File>| -> io::Result<G1Affine> { let mut repr = G1Uncompressed::empty(); reader.read_exact(repr.as_mut())?; repr.into_affine_unchecked() .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) .and_then(|e| { if e.is_zero() { Err(io::Error::new( io::ErrorKind::InvalidData, "point at infinity", )) } else { Ok(e) } }) }; let read_g2 = |reader: &mut BufReader<File>| -> io::Result<G2Affine> { let mut repr = G2Uncompressed::empty(); reader.read_exact(repr.as_mut())?; repr.into_affine_unchecked() .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) .and_then(|e| { if e.is_zero() { Err(io::Error::new( io::ErrorKind::InvalidData, "point at infinity", )) } else { Ok(e) } }) }; let alpha = read_g1(f)?; let beta_g1 = read_g1(f)?; let beta_g2 = read_g2(f)?; info!("phase2::MPCParameters::new() reading coeffs_g1 from phase1.5 file"); let mut coeffs_g1 = Vec::with_capacity(m); for _ in 0..m { coeffs_g1.push(read_g1(f)?); } info!("phase2::MPCParameters::new() reading coeffs_g2 from phase1.5 file"); let mut coeffs_g2 = Vec::with_capacity(m); for _ in 0..m { coeffs_g2.push(read_g2(f)?); } info!("phase2::MPCParameters::new() reading alpha_coeffs_g1 from phase1.5 file"); let mut alpha_coeffs_g1 = Vec::with_capacity(m); for _ in 0..m { alpha_coeffs_g1.push(read_g1(f)?); } info!("phase2::MPCParameters::new() reading beta_coeffs_g1 from phase1.5 file"); let mut beta_coeffs_g1 = Vec::with_capacity(m); for _ in 0..m { beta_coeffs_g1.push(read_g1(f)?); } // These are `Arc` so that later it'll be easier // to use multiexp during QAP evaluation (which // requires a futures-based API) let coeffs_g1 = Arc::new(coeffs_g1); let coeffs_g2 = Arc::new(coeffs_g2); let alpha_coeffs_g1 = Arc::new(alpha_coeffs_g1); let beta_coeffs_g1 = Arc::new(beta_coeffs_g1); let mut ic = vec![G1Projective::zero(); assembly.num_inputs]; info!("phase2::MPCParameters::new() initialized ic vector"); let mut l = vec![G1Projective::zero(); assembly.num_aux]; info!("phase2::MPCParameters::new() initialized l vector"); let mut a_g1 = vec![G1Projective::zero(); assembly.num_inputs + assembly.num_aux]; info!("phase2::MPCParameters::new() initialized a_g1 vector"); let mut b_g1 = vec![G1Projective::zero(); assembly.num_inputs + assembly.num_aux]; info!("phase2::MPCParameters::new() initialized b_g1 vector"); let mut b_g2 = vec![G2Projective::zero(); assembly.num_inputs + assembly.num_aux]; info!("phase2::MPCParameters::new() initialized b_g2 vector"); #[allow(clippy::too_many_arguments)] fn eval( // Lagrange coefficients for tau coeffs_g1: Arc<Vec<G1Affine>>, coeffs_g2: Arc<Vec<G2Affine>>, alpha_coeffs_g1: Arc<Vec<G1Affine>>, beta_coeffs_g1: Arc<Vec<G1Affine>>, // QAP polynomials at: &[Vec<(Fr, usize)>], bt: &[Vec<(Fr, usize)>], ct: &[Vec<(Fr, usize)>], // Resulting evaluated QAP polynomials a_g1: &mut [G1Projective], b_g1: &mut [G1Projective], b_g2: &mut [G2Projective], ext: &mut [G1Projective], // Worker worker: &Worker, ) { // Sanity check assert_eq!(a_g1.len(), at.len()); assert_eq!(a_g1.len(), bt.len()); assert_eq!(a_g1.len(), ct.len()); assert_eq!(a_g1.len(), b_g1.len()); assert_eq!(a_g1.len(), b_g2.len()); assert_eq!(a_g1.len(), ext.len()); // Evaluate polynomials in multiple threads worker.scope(a_g1.len(), |scope, chunk| { for ((((((a_g1, b_g1), b_g2), ext), at), bt), ct) in a_g1 .chunks_mut(chunk) .zip(b_g1.chunks_mut(chunk)) .zip(b_g2.chunks_mut(chunk)) .zip(ext.chunks_mut(chunk)) .zip(at.chunks(chunk)) .zip(bt.chunks(chunk)) .zip(ct.chunks(chunk)) { let coeffs_g1 = coeffs_g1.clone(); let coeffs_g2 = coeffs_g2.clone(); let alpha_coeffs_g1 = alpha_coeffs_g1.clone(); let beta_coeffs_g1 = beta_coeffs_g1.clone(); scope.spawn(move |_| { for ((((((a_g1, b_g1), b_g2), ext), at), bt), ct) in a_g1 .iter_mut() .zip(b_g1.iter_mut()) .zip(b_g2.iter_mut()) .zip(ext.iter_mut()) .zip(at.iter()) .zip(bt.iter()) .zip(ct.iter()) { for &(coeff, lag) in at { a_g1.add_assign(&coeffs_g1[lag].mul(coeff)); ext.add_assign(&beta_coeffs_g1[lag].mul(coeff)); } for &(coeff, lag) in bt { b_g1.add_assign(&coeffs_g1[lag].mul(coeff)); b_g2.add_assign(&coeffs_g2[lag].mul(coeff)); ext.add_assign(&alpha_coeffs_g1[lag].mul(coeff)); } for &(coeff, lag) in ct { ext.add_assign(&coeffs_g1[lag].mul(coeff)); } } // Batch normalize G1Projective::batch_normalization(a_g1); G1Projective::batch_normalization(b_g1); G2Projective::batch_normalization(b_g2); G1Projective::batch_normalization(ext); }); } }); } let worker = Worker::new(); // Evaluate for inputs. info!("phase2::MPCParameters::new() evaluating polynomials for inputs"); eval( coeffs_g1.clone(), coeffs_g2.clone(), alpha_coeffs_g1.clone(), beta_coeffs_g1.clone(), &assembly.at_inputs, &assembly.bt_inputs, &assembly.ct_inputs, &mut a_g1[0..assembly.num_inputs], &mut b_g1[0..assembly.num_inputs], &mut b_g2[0..assembly.num_inputs], &mut ic, &worker, ); // Evaluate for auxillary variables. info!("phase2::MPCParameters::new() evaluating polynomials for auxillary variables"); eval( coeffs_g1.clone(), coeffs_g2.clone(), alpha_coeffs_g1.clone(), beta_coeffs_g1.clone(), &assembly.at_aux, &assembly.bt_aux, &assembly.ct_aux, &mut a_g1[assembly.num_inputs..], &mut b_g1[assembly.num_inputs..], &mut b_g2[assembly.num_inputs..], &mut l, &worker, ); // Don't allow any elements be unconstrained, so that // the L query is always fully dense. for e in l.iter() { if e.is_zero() { return Err(SynthesisError::UnconstrainedVariable); } } let vk = VerifyingKey { alpha_g1: alpha, beta_g1, beta_g2, gamma_g2: G2Affine::one(), delta_g1: G1Affine::one(), delta_g2: G2Affine::one(), ic: ic.into_par_iter().map(|e| e.into_affine()).collect(), }; // Reclaim the memory used by these vectors prior to reading in `h`. drop(coeffs_g1); drop(coeffs_g2); drop(alpha_coeffs_g1); drop(beta_coeffs_g1); info!("phase2::MPCParameters::new() reading h from phase1.5 file"); let mut h = Vec::with_capacity(m - 1); for _ in 0..(m - 1) { h.push(read_g1(f)?); } let params = Parameters { vk, h: Arc::new(h), l: Arc::new(l.into_par_iter().map(|e| e.into_affine()).collect()), // Filter points at infinity away from A/B queries a: Arc::new( a_g1.into_par_iter() .filter(|e| !e.is_zero()) .map(|e| e.into_affine()) .collect(), ), b_g1: Arc::new( b_g1.into_par_iter() .filter(|e| !e.is_zero()) .map(|e| e.into_affine()) .collect(), ), b_g2: Arc::new( b_g2.into_par_iter() .filter(|e| !e.is_zero()) .map(|e| e.into_affine()) .collect(), ), }; info!( "phase2::MPCParameters::new() vector lengths: ic={}, h={}, l={}, a={}, b_g1={}, b_g2={}", params.vk.ic.len(), params.h.len(), params.l.len(), params.a.len(), params.b_g1.len(), params.b_g2.len() ); let cs_hash = { let sink = io::sink(); let mut sink = HashWriter::new(sink); params.write(&mut sink).unwrap(); sink.into_hash() }; Ok(MPCParameters { params, cs_hash, contributions: vec![], }) } /// Get the underlying Groth16 `Parameters` pub fn get_params(&self) -> &Parameters<Bls12> { &self.params } pub fn n_contributions(&self) -> usize { self.contributions.len() } /// Contributes some randomness to the parameters. Only one /// contributor needs to be honest for the parameters to be /// secure. /// /// This function returns a "hash" that is bound to the /// contribution. Contributors can use this hash to make /// sure their contribution is in the final parameters, by /// checking to see if it appears in the output of /// `MPCParameters::verify`. pub fn contribute<R: Rng>(&mut self, rng: &mut R) -> [u8; 64] { // Generate a keypair let (pubkey, privkey) = keypair(rng, self); fn batch_exp<C: CurveAffine>(bases: &mut [C], coeff: C::Scalar) { let coeff = coeff.into_repr(); let mut projective = vec![C::Projective::zero(); bases.len()]; let cpus = num_cpus::get(); let chunk_size = if bases.len() < cpus { 1 } else { bases.len() / cpus }; // Perform wNAF over multiple cores, placing results into `projective`. crossbeam::thread::scope(|scope| { for (bases, projective) in bases .chunks_mut(chunk_size) .zip(projective.chunks_mut(chunk_size)) { scope.spawn(move |_| { let mut wnaf = Wnaf::new(); for (base, projective) in bases.iter_mut().zip(projective.iter_mut()) { *projective = wnaf.base(base.into_projective(), 1).scalar(coeff); } C::Projective::batch_normalization(projective); projective .iter() .zip(bases.iter_mut()) .for_each(|(projective, affine)| { *affine = projective.into_affine(); }); }); } }) .unwrap(); } let delta_inv = privkey.delta.inverse().expect("nonzero"); info!("phase2::MPCParameters::contribute() copying l"); let mut l = (&self.params.l[..]).to_vec(); info!("phase2::MPCParameters::contribute() copying h"); let mut h = (&self.params.h[..]).to_vec(); info!("phase2::MPCParameters::contribute() performing batch exponentiation of l"); batch_exp(&mut l, delta_inv); info!("phase2::MPCParameters::contribute() performing batch exponentiation of h"); batch_exp(&mut h, delta_inv); info!("phase2::MPCParameters::contribute() finished batch exponentiations"); self.params.l = Arc::new(l); self.params.h = Arc::new(h); self.params.vk.delta_g1 = self.params.vk.delta_g1.mul(privkey.delta).into_affine(); self.params.vk.delta_g2 = self.params.vk.delta_g2.mul(privkey.delta).into_affine(); self.contributions.push(pubkey.clone()); // Calculate the hash of the public key and return it { let sink = io::sink(); let mut sink = HashWriter::new(sink); pubkey.write(&mut sink).unwrap(); sink.into_hash() } } /// Verify the correctness of the parameters, given a circuit /// instance. This will return all of the hashes that /// contributors obtained when they ran /// `MPCParameters::contribute`, for ensuring that contributions /// exist in the final parameters. pub fn verify<C: Circuit<Bls12>>(&self, circuit: C) -> Result<Vec<[u8; 64]>, ()> { let initial_params = MPCParameters::new(circuit).map_err(|_| ())?; // H/L will change, but should have same length if initial_params.params.h.len() != self.params.h.len() { error!("phase2::MPCParameters::verify() h's length has changed"); return Err(()); } if initial_params.params.l.len() != self.params.l.len() { error!("phase2::MPCParameters::verify() l's length has changed"); return Err(()); } // A/B_G1/B_G2 doesn't change at all if initial_params.params.a != self.params.a { error!("phase2::MPCParameters::verify() evaluated QAP a polynomial has changed"); return Err(()); } if initial_params.params.b_g1 != self.params.b_g1 { error!("phase2::MPCParameters::verify() evaluated QAP b_g1 polynomial has changed"); return Err(()); } if initial_params.params.b_g2 != self.params.b_g2 { error!("phase2::MPCParameters::verify() evaluated QAP b_g2 polynomial has changed"); return Err(()); } // alpha/beta/gamma don't change if initial_params.params.vk.alpha_g1 != self.params.vk.alpha_g1 { error!("phase2::MPCParameters::verify() vk's alpha has changed"); return Err(()); } if initial_params.params.vk.beta_g1 != self.params.vk.beta_g1 { error!("phase2::MPCParameters::verify() vk's beta_g1 has changed"); return Err(()); } if initial_params.params.vk.beta_g2 != self.params.vk.beta_g2 { error!("phase2::MPCParameters::verify() vk's beta_g2 has changed"); return Err(()); } if initial_params.params.vk.gamma_g2 != self.params.vk.gamma_g2 { error!("phase2::MPCParameters::verify() vk's gamma has changed"); return Err(()); } // IC shouldn't change, as gamma doesn't change if initial_params.params.vk.ic != self.params.vk.ic { error!("phase2::MPCParameters::verify() vk's ic has changed"); return Err(()); } // cs_hash should be the same if initial_params.cs_hash[..] != self.cs_hash[..] { error!("phase2::MPCParameters::verify() cs_hash has changed"); return Err(()); } let sink = io::sink(); let mut sink = HashWriter::new(sink); sink.write_all(&initial_params.cs_hash[..]).unwrap(); let mut current_delta = G1Affine::one(); let mut result = vec![]; for pubkey in &self.contributions { let mut our_sink = sink.clone(); our_sink .write_all(pubkey.s.into_uncompressed().as_ref()) .unwrap(); our_sink .write_all(pubkey.s_delta.into_uncompressed().as_ref()) .unwrap(); pubkey.write(&mut sink).unwrap(); let h = our_sink.into_hash(); // The transcript must be consistent if &pubkey.transcript[..] != h.as_ref() { error!("phase2::MPCParameters::verify() transcripts differ"); return Err(()); } let r = hash_to_g2(h.as_ref()).into_affine(); // Check the signature of knowledge if !same_ratio((r, pubkey.r_delta), (pubkey.s, pubkey.s_delta)) { error!("phase2::MPCParameters::verify() pubkey's r and s were shifted by different deltas"); return Err(()); } // Check the change from the old delta is consistent if !same_ratio((current_delta, pubkey.delta_after), (r, pubkey.r_delta)) { error!("phase2::MPCParameters::verify() contribution's delta and r where shifted differently"); return Err(()); } current_delta = pubkey.delta_after; { let sink = io::sink(); let mut sink = HashWriter::new(sink); pubkey.write(&mut sink).unwrap(); result.push(sink.into_hash()); } } // Current parameters should have consistent delta in G1 if current_delta != self.params.vk.delta_g1 { error!("phase2::MPCParameters::verify() vk's delta_g1 differs from calculated delta"); return Err(()); } // Current parameters should have consistent delta in G2 if !same_ratio( (G1Affine::one(), current_delta), (G2Affine::one(), self.params.vk.delta_g2), ) { error!("phase2::MPCParameters::verify() shift in vk's delta_g2 is inconsistent with calculated delta"); return Err(()); } // H and L queries should be updated with delta^-1 if !same_ratio( merge_pairs(&initial_params.params.h, &self.params.h), (self.params.vk.delta_g2, G2Affine::one()), // reversed for inverse ) { error!("phase2::MPCParameters::verify() h queries have not shifted by delta^-1"); return Err(()); } if !same_ratio( merge_pairs(&initial_params.params.l, &self.params.l), (self.params.vk.delta_g2, G2Affine::one()), // reversed for inverse ) { error!("phase2::MPCParameters::verify() l queries have not shifted by delta^-1"); return Err(()); } Ok(result) } /// Serialize these parameters. The serialized parameters /// can be read by bellman as Groth16 `Parameters`. pub fn write<W: Write>(&self, mut writer: W) -> io::Result<()> { self.params.write(&mut writer)?; writer.write_all(&self.cs_hash)?; writer.write_u32::<BigEndian>(self.contributions.len() as u32)?; for pubkey in &self.contributions { pubkey.write(&mut writer)?; } Ok(()) } /// Serializes these parameters as `MPCSmall`. pub fn write_small<W: Write>(&self, mut writer: W) -> io::Result<()> { writer.write_all(self.params.vk.delta_g1.into_uncompressed().as_ref())?; writer.write_all(self.params.vk.delta_g2.into_uncompressed().as_ref())?; writer.write_u32::<BigEndian>(self.params.h.len() as u32)?; for h in &*self.params.h { writer.write_all(h.into_uncompressed().as_ref())?; } writer.write_u32::<BigEndian>(self.params.l.len() as u32)?; for l in &*self.params.l { writer.write_all(l.into_uncompressed().as_ref())?; } writer.write_all(&self.cs_hash)?; writer.write_u32::<BigEndian>(self.contributions.len() as u32)?; for pubkey in &self.contributions { pubkey.write(&mut writer)?; } Ok(()) } /// Deserialize these parameters. If `checked` is false, /// we won't perform curve validity and group order /// checks. pub fn read<R: Read>(mut reader: R, checked: bool) -> io::Result<MPCParameters> { let params = Parameters::read(&mut reader, checked)?; let mut cs_hash = [0u8; 64]; reader.read_exact(&mut cs_hash)?; let contributions_len = reader.read_u32::<BigEndian>()? as usize; let mut contributions = vec![]; for _ in 0..contributions_len { contributions.push(PublicKey::read(&mut reader)?); } info!( "phase2::MPCParameters::read() vector lengths: ic={}, h={}, l={}, a={}, b_g1={}, \ b_g2={}, contributions={}", params.vk.ic.len(), params.h.len(), params.l.len(), params.a.len(), params.b_g1.len(), params.b_g2.len(), contributions.len(), ); Ok(MPCParameters { params, cs_hash, contributions, }) } // memcpy's the potentially large vectors behind Arc's (duplicates the arrays on the stack, // does not increment ref-counts in `self`). pub fn copy(&self) -> Self { let mut params = self.clone(); params.params.h = Arc::new((*self.params.h).clone()); params.params.l = Arc::new((*self.params.l).clone()); params.params.a = Arc::new((*self.params.a).clone()); params.params.b_g1 = Arc::new((*self.params.b_g1).clone()); params.params.b_g2 = Arc::new((*self.params.b_g2).clone()); params } // memcpy's the potentially large h and l vectors behind Arc's into a new `MPCSmall` (duplicates // the h and l arrays on the stack, does not increment ref-counts for the h and l Arc's in `self`). pub fn copy_small(&self) -> MPCSmall { MPCSmall { delta_g1: self.params.vk.delta_g1, delta_g2: self.params.vk.delta_g2, h: (*self.params.h).clone(), l: (*self.params.l).clone(), cs_hash: self.cs_hash, contributions: self.contributions.clone(), } } // Updates `self` with a contribution (or contributions) that is in the `MPCSmall` params form. // `MPCSmall` must contain at least one new contribution. This decrements the strong ref-counts // by one for any Arc clones that were made from `self.h` and `self.l`. If either of `self`'s h // and l Arc's have ref-count 1, then they will be dropped. pub fn add_contrib(&mut self, contrib: MPCSmall) { assert_eq!( self.cs_hash[..], contrib.cs_hash[..], "large and small params have different cs_hash" ); assert_eq!( self.params.h.len(), contrib.h.len(), "large and small params have different h length" ); assert_eq!( self.params.l.len(), contrib.l.len(), "large and small params have different l length" ); assert!( self.contributions.len() < contrib.contributions.len(), "small params do not contain additional contributions" ); assert_eq!( &self.contributions[..], &contrib.contributions[..self.contributions.len()], "small params cannot change prior contributions in large params" ); // Unwrapping here is safe because we have already asserted that `contrib` contains at least // one (new) contribution. assert_eq!( contrib.delta_g1, contrib.contributions.last().unwrap().delta_after, "small params are internally inconsistent wrt. G1 deltas" ); let MPCSmall { delta_g1, delta_g2, h, l, contributions, .. } = contrib; self.params.vk.delta_g1 = delta_g1; self.params.vk.delta_g2 = delta_g2; self.params.h = Arc::new(h); self.params.l = Arc::new(l); self.contributions = contributions; } // Returns true if a pair of large and small MPC params contain equal values. It is not required // that `self`'s h and l Arc's point to the same memory locations as `small`'s non-Arc h and l // vectors. pub fn has_last_contrib(&self, small: &MPCSmall) -> bool { self.params.vk.delta_g1 == small.delta_g1 && self.params.vk.delta_g2 == small.delta_g2 && *self.params.h == small.h && *self.params.l == small.l && self.cs_hash[..] == small.cs_hash[..] && self.contributions == small.contributions } } /// This allows others to verify that you contributed. The hash produced /// by `MPCParameters::contribute` is just a BLAKE2b hash of this object. #[derive(Clone)] struct PublicKey { /// This is the delta (in G1) after the transformation, kept so that we /// can check correctness of the public keys without having the entire /// interstitial parameters for each contribution. delta_after: G1Affine, /// Random element chosen by the contributor. s: G1Affine, /// That element, taken to the contributor's secret delta. s_delta: G1Affine, /// r is H(last_pubkey | s | s_delta), r_delta proves knowledge of delta r_delta: G2Affine, /// Hash of the transcript (used for mapping to r) transcript: [u8; 64], } // Required by `assert_eq!()`. impl Debug for PublicKey { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("PublicKey") .field("delta_after", &self.delta_after) .field("s", &self.s) .field("s_delta", &self.s_delta) .field("r_delta", &self.r_delta) .field("transcript", &self.transcript.to_vec()) .finish() } } impl PublicKey { fn write<W: Write>(&self, mut writer: W) -> io::Result<()> { writer.write_all(self.delta_after.into_uncompressed().as_ref())?; writer.write_all(self.s.into_uncompressed().as_ref())?; writer.write_all(self.s_delta.into_uncompressed().as_ref())?; writer.write_all(self.r_delta.into_uncompressed().as_ref())?; writer.write_all(&self.transcript)?; Ok(()) } fn read<R: Read>(mut reader: R) -> io::Result<PublicKey> { let mut g1_repr = G1Uncompressed::empty(); let mut g2_repr = G2Uncompressed::empty(); reader.read_exact(g1_repr.as_mut())?; let delta_after = g1_repr .into_affine() .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; if delta_after.is_zero() { return Err(io::Error::new( io::ErrorKind::InvalidData, "point at infinity", )); } reader.read_exact(g1_repr.as_mut())?; let s = g1_repr .into_affine() .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; if s.is_zero() { return Err(io::Error::new( io::ErrorKind::InvalidData, "point at infinity", )); } reader.read_exact(g1_repr.as_mut())?; let s_delta = g1_repr .into_affine() .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; if s_delta.is_zero() { return Err(io::Error::new( io::ErrorKind::InvalidData, "point at infinity", )); } reader.read_exact(g2_repr.as_mut())?; let r_delta = g2_repr .into_affine() .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; if r_delta.is_zero() { return Err(io::Error::new( io::ErrorKind::InvalidData, "point at infinity", )); } let mut transcript = [0u8; 64]; reader.read_exact(&mut transcript)?; Ok(PublicKey { delta_after, s, s_delta, r_delta, transcript, }) } } impl PartialEq for PublicKey { fn eq(&self, other: &PublicKey) -> bool { self.delta_after == other.delta_after && self.s == other.s && self.s_delta == other.s_delta && self.r_delta == other.r_delta && self.transcript[..] == other.transcript[..] } } /// Verify a contribution, given the old parameters and /// the new parameters. Returns the hash of the contribution. pub fn verify_contribution(before: &MPCParameters, after: &MPCParameters) -> Result<[u8; 64], ()> { if after.contributions.len() != (before.contributions.len() + 1) { error!( "phase2::verify_contribution() 'after' params do not contain exactly one more \ contribution than the 'before' params: n_contributions_before={}, \ n_contributions_after={}", before.contributions.len(), after.contributions.len() ); return Err(()); } // None of the previous transformations should change if before.contributions[..] != after.contributions[0..before.contributions.len()] { error!("phase2::verify_contribution() 'after' params contributions differ from 'before' params contributions"); return Err(()); } // H/L will change, but should have same length if before.params.h.len() != after.params.h.len() { error!("phase2::verify_contribution() length of h has changed"); return Err(()); } if before.params.l.len() != after.params.l.len() { error!("phase2::verify_contribution() length of l has changed"); return Err(()); } // A/B_G1/B_G2 doesn't change at all if before.params.a != after.params.a { error!("phase2::verify_contribution() evaluated QAP a polynomial has changed"); return Err(()); } if before.params.b_g1 != after.params.b_g1 { error!("phase2::verify_contribution() evaluated QAP b_g1 polynomial has changed"); return Err(()); } if before.params.b_g2 != after.params.b_g2 { error!("phase2::verify_contribution() evaluated QAP b_g2 polynomial has changed"); return Err(()); } // alpha/beta/gamma don't change if before.params.vk.alpha_g1 != after.params.vk.alpha_g1 { error!("phase2::verify_contribution() vk's alpha_g1 hash changed"); return Err(()); } if before.params.vk.beta_g1 != after.params.vk.beta_g1 { error!("phase2::verify_contribution() vk's beta_g1 has changed"); return Err(()); } if before.params.vk.beta_g2 != after.params.vk.beta_g2 { error!("phase2::verify_contribution() vk's beta_g2 changed"); return Err(()); } if before.params.vk.gamma_g2 != after.params.vk.gamma_g2 { error!("phase2::verify_contribution() vk's gamma_g2 has changed"); return Err(()); } // IC shouldn't change, as gamma doesn't change if before.params.vk.ic != after.params.vk.ic { error!("phase2::verify_contribution() vk's ic has changed"); return Err(()); } // cs_hash should be the same if before.cs_hash[..] != after.cs_hash[..] { error!("phase2::verify_contribution() cs_hash has changed"); return Err(()); } let sink = io::sink(); let mut sink = HashWriter::new(sink); sink.write_all(&before.cs_hash[..]).unwrap(); for pubkey in &before.contributions { pubkey.write(&mut sink).unwrap(); } let pubkey = after.contributions.last().unwrap(); sink.write_all(pubkey.s.into_uncompressed().as_ref()) .unwrap(); sink.write_all(pubkey.s_delta.into_uncompressed().as_ref()) .unwrap(); let h = sink.into_hash(); // The transcript must be consistent if &pubkey.transcript[..] != h.as_ref() { error!("phase2::verify_contribution() inconsistent transcript"); return Err(()); } let r = hash_to_g2(h.as_ref()).into_affine(); // Check the signature of knowledge if !same_ratio((r, pubkey.r_delta), (pubkey.s, pubkey.s_delta)) { error!("phase2::verify_contribution() contribution's r and s were shifted with different deltas"); return Err(()); } // Check the change from the old delta is consistent if !same_ratio( (before.params.vk.delta_g1, pubkey.delta_after), (r, pubkey.r_delta), ) { error!("phase2::verify_contribution() contribution's delta and r where shifted with different delta"); return Err(()); } // Current parameters should have consistent delta in G1 if pubkey.delta_after != after.params.vk.delta_g1 { error!( "phase2::verify_contribution() contribution's delta in G1 differs from vk's delta_g1" ); return Err(()); } // Current parameters should have consistent delta in G2 if !same_ratio( (G1Affine::one(), pubkey.delta_after), (G2Affine::one(), after.params.vk.delta_g2), ) { error!("phase2::verify_contribution() contribution's shift in delta (G1) is inconsistent with vk's shift in delta (G2)"); return Err(()); } // H and L queries should be updated with delta^-1 if !same_ratio( merge_pairs(&before.params.h, &after.params.h), (after.params.vk.delta_g2, before.params.vk.delta_g2), // reversed for inverse ) { error!("phase2::verify_contribution() h was not updated by delta^-1"); return Err(()); } if !same_ratio( merge_pairs(&before.params.l, &after.params.l), (after.params.vk.delta_g2, before.params.vk.delta_g2), // reversed for inverse ) { error!("phase2::verify_contribution() l was not updated by delta^-1"); return Err(()); } let sink = io::sink(); let mut sink = HashWriter::new(sink); pubkey.write(&mut sink).unwrap(); Ok(sink.into_hash()) } /// Checks if pairs have the same ratio. pub(crate) fn same_ratio<G1: PairingCurveAffine>(g1: (G1, G1), g2: (G1::Pair, G1::Pair)) -> bool { g1.0.pairing_with(&g2.1) == g1.1.pairing_with(&g2.0) } /// Computes a random linear combination over v1/v2. /// /// Checking that many pairs of elements are exponentiated by /// the same `x` can be achieved (with high probability) with /// the following technique: /// /// Given v1 = [a, b, c] and v2 = [as, bs, cs], compute /// (a*r1 + b*r2 + c*r3, (as)*r1 + (bs)*r2 + (cs)*r3) for some /// random r1, r2, r3. Given (g, g^s)... /// /// e(g, (as)*r1 + (bs)*r2 + (cs)*r3) = e(g^s, a*r1 + b*r2 + c*r3) /// /// ... with high probability. pub(crate) fn merge_pairs<G: CurveAffine>(v1: &[G], v2: &[G]) -> (G, G) { use rand::thread_rng; use std::sync::Mutex; assert_eq!(v1.len(), v2.len()); let chunk = (v1.len() / num_cpus::get()) + 1; let s = Arc::new(Mutex::new(G::Projective::zero())); let sx = Arc::new(Mutex::new(G::Projective::zero())); crossbeam::thread::scope(|scope| { for (v1, v2) in v1.chunks(chunk).zip(v2.chunks(chunk)) { let s = s.clone(); let sx = sx.clone(); scope.spawn(move |_| { // We do not need to be overly cautious of the RNG // used for this check. let rng = &mut thread_rng(); let mut wnaf = Wnaf::new(); let mut local_s = G::Projective::zero(); let mut local_sx = G::Projective::zero(); for (v1, v2) in v1.iter().zip(v2.iter()) { let rho = G::Scalar::random(rng); let mut wnaf = wnaf.scalar(rho.into_repr()); let v1 = wnaf.base(v1.into_projective()); let v2 = wnaf.base(v2.into_projective()); local_s.add_assign(&v1); local_sx.add_assign(&v2); } s.lock().unwrap().add_assign(&local_s); sx.lock().unwrap().add_assign(&local_sx); }); } }) .unwrap(); let s = s.lock().unwrap().into_affine(); let sx = sx.lock().unwrap().into_affine(); (s, sx) } /// This needs to be destroyed by at least one participant /// for the final parameters to be secure. struct PrivateKey { delta: Fr, } /// Compute a keypair, given the current parameters. Keypairs /// cannot be reused for multiple contributions or contributions /// in different parameters. fn keypair<R: Rng>(rng: &mut R, current: &MPCParameters) -> (PublicKey, PrivateKey) { // Sample random delta let delta: Fr = Fr::random(rng); // Compute delta s-pair in G1 let s = G1Projective::random(rng).into_affine(); let s_delta = s.mul(delta).into_affine(); // H(cs_hash | <previous pubkeys> | s | s_delta) let h = { let sink = io::sink(); let mut sink = HashWriter::new(sink); sink.write_all(&current.cs_hash[..]).unwrap(); for pubkey in &current.contributions { pubkey.write(&mut sink).unwrap(); } sink.write_all(s.into_uncompressed().as_ref()).unwrap(); sink.write_all(s_delta.into_uncompressed().as_ref()) .unwrap(); sink.into_hash() }; // This avoids making a weird assumption about the hash into the // group. let transcript = h; // Compute delta s-pair in G2 let r = hash_to_g2(&h).into_affine(); let r_delta = r.mul(delta).into_affine(); ( PublicKey { delta_after: current.params.vk.delta_g1.mul(delta).into_affine(), s, s_delta, r_delta, transcript, }, PrivateKey { delta }, ) } /// Hashes to G2 using the first 32 bytes of `digest`. Panics if `digest` is less /// than 32 bytes. pub(crate) fn hash_to_g2(digest: &[u8]) -> G2Projective { assert!(digest.len() >= 32); let mut seed = [0u8; 32]; seed.copy_from_slice(&digest[..32]); G2Projective::random(&mut ChaChaRng::from_seed(seed)) } /// Abstraction over a writer which hashes the data being written. pub(crate) struct HashWriter<W: Write> { writer: W, hasher: Blake2b, } impl Clone for HashWriter<io::Sink> { fn clone(&self) -> HashWriter<io::Sink> { HashWriter { writer: io::sink(), hasher: self.hasher.clone(), } } } impl<W: Write> HashWriter<W> { /// Construct a new `HashWriter` given an existing `writer` by value. pub fn new(writer: W) -> Self { HashWriter { writer, hasher: Blake2b::new(), } } /// Destroy this writer and return the hash of what was written. pub fn into_hash(self) -> [u8; 64] { let mut tmp = [0u8; 64]; tmp.copy_from_slice(self.hasher.finalize().as_ref()); tmp } } impl<W: Write> Write for HashWriter<W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let bytes = self.writer.write(buf)?; if bytes > 0 { self.hasher.update(&buf[0..bytes]); } Ok(bytes) } fn flush(&mut self) -> io::Result<()> { self.writer.flush() } } /// This is a cheap helper utility that exists purely /// because Rust still doesn't have type-level integers /// and so doesn't implement `PartialEq` for `[T; 64]` pub fn contains_contribution(contributions: &[[u8; 64]], my_contribution: &[u8; 64]) -> bool { for contrib in contributions { if contrib[..] == my_contribution[..] { return true; } } false }
#[doc = "Register `ADC_SQR4` reader"] pub type R = crate::R<ADC_SQR4_SPEC>; #[doc = "Register `ADC_SQR4` writer"] pub type W = crate::W<ADC_SQR4_SPEC>; #[doc = "Field `SQ15` reader - SQ15"] pub type SQ15_R = crate::FieldReader; #[doc = "Field `SQ15` writer - SQ15"] pub type SQ15_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O>; #[doc = "Field `SQ16` reader - SQ16"] pub type SQ16_R = crate::FieldReader; #[doc = "Field `SQ16` writer - SQ16"] pub type SQ16_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O>; impl R { #[doc = "Bits 0:4 - SQ15"] #[inline(always)] pub fn sq15(&self) -> SQ15_R { SQ15_R::new((self.bits & 0x1f) as u8) } #[doc = "Bits 6:10 - SQ16"] #[inline(always)] pub fn sq16(&self) -> SQ16_R { SQ16_R::new(((self.bits >> 6) & 0x1f) as u8) } } impl W { #[doc = "Bits 0:4 - SQ15"] #[inline(always)] #[must_use] pub fn sq15(&mut self) -> SQ15_W<ADC_SQR4_SPEC, 0> { SQ15_W::new(self) } #[doc = "Bits 6:10 - SQ16"] #[inline(always)] #[must_use] pub fn sq16(&mut self) -> SQ16_W<ADC_SQR4_SPEC, 6> { SQ16_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 = "ADC regular sequence register 4\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`adc_sqr4::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 [`adc_sqr4::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct ADC_SQR4_SPEC; impl crate::RegisterSpec for ADC_SQR4_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`adc_sqr4::R`](R) reader structure"] impl crate::Readable for ADC_SQR4_SPEC {} #[doc = "`write(|w| ..)` method takes [`adc_sqr4::W`](W) writer structure"] impl crate::Writable for ADC_SQR4_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets ADC_SQR4 to value 0"] impl crate::Resettable for ADC_SQR4_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[doc = "Register `GICD_PIDR3` reader"] pub type R = crate::R<GICD_PIDR3_SPEC>; #[doc = "Field `PIDR3` reader - PIDR3"] pub type PIDR3_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - PIDR3"] #[inline(always)] pub fn pidr3(&self) -> PIDR3_R { PIDR3_R::new(self.bits) } } #[doc = "GICD peripheral ID3 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicd_pidr3::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct GICD_PIDR3_SPEC; impl crate::RegisterSpec for GICD_PIDR3_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`gicd_pidr3::R`](R) reader structure"] impl crate::Readable for GICD_PIDR3_SPEC {} #[doc = "`reset()` method sets GICD_PIDR3 to value 0"] impl crate::Resettable for GICD_PIDR3_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[macro_use] extern crate cpython; use cpython::{PyResult, Python}; // add bindings to the generated python module // N.B: names: "librust2py" must be the name of // the `.so` or `.pyd` file py_module_initializer!(librust2py, initlibrust2py, PyInit_librust2py, |py, m| { m.add(py, "__doc__", "This module is implemented in Rust.")?; m.add(py, "sum_as_string", py_fn!(py, sum_as_string_py(a: i64, b:i64)))?; Ok(()) }); // logic implemented as a normal rust function fn sum_as_string(a:i64, b:i64) -> String { format!("{}", a + b).to_string() } // rust-cpython aware function. All of our python // interface could be declared in a separate module. // Note that the py_fn!() macro automatically converts // the arguments from Python objects to Rust values; // and the Rust return value back into a Python object. fn sum_as_string_py(_: Python, a:i64, b:i64) -> PyResult<String> { let out = sum_as_string(a, b); Ok(out) }
//! # HTTP Client //! //! This module contains the HTTP client through which actors consume //! the currently bound `wascap:http_client` capability provider use wapc_guest::host_call; use wascc_codec::{deserialize, http::*, serialize}; use crate::HandlerResult; const CAPID_HTTPCLIENT: &str = "wascc:http_client"; /// An abstraction around a host runtime capability for an HTTP client pub struct HttpClientHostBinding { binding: String, } impl Default for HttpClientHostBinding { fn default() -> Self { HttpClientHostBinding { binding: "default".to_string(), } } } /// Creates a named host binding for the HTTP client capability pub fn host(binding: &str) -> HttpClientHostBinding { HttpClientHostBinding { binding: binding.to_string(), } } /// Creates the default host binding for the key-value store capability pub fn default() -> HttpClientHostBinding { HttpClientHostBinding::default() } impl HttpClientHostBinding { pub fn request(&self, request: Request) -> HandlerResult<Response> { host_call( &self.binding, CAPID_HTTPCLIENT, OP_PERFORM_REQUEST, &serialize(request)?, ) .map(|r| deserialize::<Response>(r.as_ref()).unwrap()) .map_err(|e| e.into()) } }
use crate::{ import::*, WsErr, WsStream }; /// A wrapper around WsStream that converts errors into io::Error so that it can be /// used for io (like `AsyncRead`/`AsyncWrite`). /// /// You shouldn't need to use this manually. It is passed to [`IoStream`] when calling /// [`WsStream::into_io`]. // #[ derive(Debug) ] // pub struct WsStreamIo { inner: WsStream } impl WsStreamIo { /// Create a new WsStreamIo. // pub fn new( inner: WsStream ) -> Self { Self { inner } } } impl Stream for WsStreamIo { type Item = Result< Vec<u8>, io::Error >; fn poll_next( mut self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll<Option< Self::Item >> { Pin::new( &mut self.inner ).poll_next( cx ) .map( |opt| opt.map( |msg| Ok( msg.into() ) ) ) } } impl Sink< Vec<u8> > for WsStreamIo { type Error = io::Error; fn poll_ready( mut self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll<Result<(), Self::Error>> { Pin::new( &mut self.inner ).poll_ready( cx ).map( convert_res_tuple ) } fn start_send( mut self: Pin<&mut Self>, item: Vec<u8> ) -> Result<(), Self::Error> { Pin::new( &mut self.inner ).start_send( item.into() ).map_err( convert_err ) } fn poll_flush( mut self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll<Result<(), Self::Error>> { Pin::new( &mut self.inner ).poll_flush( cx ).map( convert_res_tuple ) } fn poll_close( mut self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll<Result<(), Self::Error>> { Pin::new( &mut self.inner ).poll_close( cx ).map( convert_res_tuple ) } } fn convert_res_tuple( res: Result< (), WsErr> ) -> Result< (), io::Error > { res.map_err( convert_err ) } fn convert_err( err: WsErr ) -> io::Error { match err { WsErr::ConnectionNotOpen => return io::Error::from( io::ErrorKind::NotConnected ) , // This shouldn't happen, so panic for early detection. // _ => unreachable!(), } }
use bellman::gadgets::multipack; use bellman::groth16; use blake2s_simd::Params as Blake2sParams; use bls12_381::Bls12; use ff::Field; use group::{Curve, Group, GroupEncoding}; use sapvi::crypto::{ create_mint_proof, load_params, save_params, setup_mint_prover, verify_mint_proof, }; fn main() { use rand::rngs::OsRng; use std::time::Instant; let public = jubjub::SubgroupPoint::random(&mut OsRng); let value = 110; let randomness_value: jubjub::Fr = jubjub::Fr::random(&mut OsRng); let serial: jubjub::Fr = jubjub::Fr::random(&mut OsRng); let randomness_coin: jubjub::Fr = jubjub::Fr::random(&mut OsRng); { let params = setup_mint_prover(); save_params("mint.params", &params); } let (params, pvk) = load_params("mint.params").expect("params should load"); let (proof, revealed) = create_mint_proof( &params, value, randomness_value, serial, randomness_coin, public, ); assert!(verify_mint_proof(&pvk, &proof, &revealed)); }
pub mod connection; pub mod content_length; pub mod expect; pub mod transfer_encoding; mod encoding; mod parse; pub use self::connection::Connection; pub use self::content_length::ContentLength; pub use self::encoding::Encoding; pub use self::expect::Expect; pub use self::transfer_encoding::TransferEncoding;
pub fn adler32(input: &str ) -> u32 { let bytes = input.as_bytes(); let mut a: u32 = 1; let mut b: u32 = 0; let mut c: u32; for byte in bytes { let byte_val: u32 = *byte as u32; c = a; a = (a.wrapping_add(byte_val)) % 65521; b = (b.wrapping_add(byte_val.wrapping_add(c))) % 65521; } let hash = (b << 16).wrapping_add(a); hash }
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ #![warn(missing_debug_implementations, missing_docs)] //! Parameters for disk index construction. use crate::common::{ANNResult, ANNError}; /// Cached nodes size in GB const SPACE_FOR_CACHED_NODES_IN_GB: f64 = 0.25; /// Threshold for caching in GB const THRESHOLD_FOR_CACHING_IN_GB: f64 = 1.0; /// Parameters specific for disk index construction. #[derive(Clone, Copy, PartialEq, Debug)] pub struct DiskIndexBuildParameters { /// Bound on the memory footprint of the index at search time in bytes. /// Once built, the index will use up only the specified RAM limit, the rest will reside on disk. /// This will dictate how aggressively we compress the data vectors to store in memory. /// Larger will yield better performance at search time. search_ram_limit: f64, /// Limit on the memory allowed for building the index in bytes. index_build_ram_limit: f64, } impl DiskIndexBuildParameters { /// Create DiskIndexBuildParameters instance pub fn new(search_ram_limit_gb: f64, index_build_ram_limit_gb: f64) -> ANNResult<Self> { let param = Self { search_ram_limit: Self::get_memory_budget(search_ram_limit_gb), index_build_ram_limit: index_build_ram_limit_gb * 1024_f64 * 1024_f64 * 1024_f64, }; if param.search_ram_limit <= 0f64 { return Err(ANNError::log_index_config_error("search_ram_limit".to_string(), "RAM budget should be > 0".to_string())) } if param.index_build_ram_limit <= 0f64 { return Err(ANNError::log_index_config_error("index_build_ram_limit".to_string(), "RAM budget should be > 0".to_string())) } Ok(param) } /// Get search_ram_limit pub fn search_ram_limit(&self) -> f64 { self.search_ram_limit } /// Get index_build_ram_limit pub fn index_build_ram_limit(&self) -> f64 { self.index_build_ram_limit } fn get_memory_budget(mut index_ram_limit_gb: f64) -> f64 { if index_ram_limit_gb - SPACE_FOR_CACHED_NODES_IN_GB > THRESHOLD_FOR_CACHING_IN_GB { // slack for space used by cached nodes index_ram_limit_gb -= SPACE_FOR_CACHED_NODES_IN_GB; } index_ram_limit_gb * 1024_f64 * 1024_f64 * 1024_f64 } } #[cfg(test)] mod dataset_test { use super::*; #[test] fn sufficient_ram_for_caching() { let param = DiskIndexBuildParameters::new(1.26_f64, 1.0_f64).unwrap(); assert_eq!(param.search_ram_limit, 1.01_f64 * 1024_f64 * 1024_f64 * 1024_f64); } #[test] fn insufficient_ram_for_caching() { let param = DiskIndexBuildParameters::new(0.03_f64, 1.0_f64).unwrap(); assert_eq!(param.search_ram_limit, 0.03_f64 * 1024_f64 * 1024_f64 * 1024_f64); } }
use bytes::{ Bytes, Buf, BytesMut, BufMut }; #[derive(Debug, PartialEq, Clone)] pub struct SendDataRequestChip { pub callback_id: u8, pub status: u8, } impl SendDataRequestChip { pub fn encode(&self, dst: &mut BytesMut) { dst.put_u8(self.callback_id); dst.put_u8(self.status); } pub fn decode(src: &mut Bytes) -> SendDataRequestChip { let callback_id = src.get_u8(); let status = src.get_u8(); // TODO Metrics return SendDataRequestChip { callback_id, status } } }
use std::{collections::BTreeMap, fmt::Write}; use eyre::Report; use hashbrown::HashMap; use rosu_v2::prelude::{Beatmap, User}; use crate::{ custom_client::SnipeScore, embeds::{osu, Author, Footer}, pp::PpCalculator, util::{ constants::OSU_BASE, datetime::how_long_ago_dynamic, numbers::{round, with_comma_int}, }, core::Context, }; pub struct PlayerSnipeListEmbed { author: Author, description: String, footer: Footer, thumbnail: String, } impl PlayerSnipeListEmbed { pub async fn new( user: &User, scores: &BTreeMap<usize, SnipeScore>, maps: &HashMap<u32, Beatmap>, total: usize, ctx: &Context, pages: (usize, usize), ) -> Self { if scores.is_empty() { return Self { author: author!(user), thumbnail: user.avatar_url.to_owned(), footer: Footer::new("Page 1/1 ~ Total #1 scores: 0"), description: "No scores were found".to_owned(), }; } let index = (pages.0 - 1) * 5; let entries = scores.range(index..index + 5); let mut description = String::with_capacity(1024); for (idx, score) in entries { let map = maps .get(&score.beatmap_id) .expect("missing beatmap for psl embed"); let max_pp = match PpCalculator::new(ctx, map.map_id).await { Ok(mut calc) => Some(calc.mods(score.mods).max_pp() as f32), Err(err) => { warn!("{:?}", Report::new(err)); None } }; let pp = osu::get_pp(score.pp, max_pp); let n300 = map.count_objects() - score.count_100 - score.count_50 - score.count_miss; let _ = writeln!( description, "**{idx}. [{title} [{version}]]({OSU_BASE}b/{id}) {mods}** [{stars}]\n\ {pp} ~ ({acc}%) ~ {score}\n{{{n300}/{n100}/{n50}/{nmiss}}} ~ {ago}", idx = idx + 1, title = map.mapset.as_ref().unwrap().title, version = map.version, id = score.beatmap_id, mods = osu::get_mods(score.mods), stars = osu::get_stars(score.stars), acc = round(score.accuracy), score = with_comma_int(score.score), n100 = score.count_100, n50 = score.count_50, nmiss = score.count_miss, ago = how_long_ago_dynamic(&score.score_date) ); } let footer = Footer::new(format!( "Page {}/{} ~ Total scores: {total}", pages.0, pages.1 )); Self { author: author!(user), description, footer, thumbnail: user.avatar_url.to_owned(), } } } impl_builder!(PlayerSnipeListEmbed { author, description, footer, thumbnail, });
use std::collections::{BTreeMap, VecDeque}; use std::error::Error; use std::fmt; use std::io::{self, Read}; use std::result; use std::usize; type Result<T> = result::Result<T, Box<dyn Error>>; #[derive(Clone, PartialEq)] enum Tile { Wall, Open, Unit, } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] enum UnitKind { Goblin, Elf, } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] struct Unit { hp: u32, attack: u32, kind: UnitKind, id: usize, } #[derive(Clone)] struct Board { tiles: Vec<Tile>, units: BTreeMap<usize, Unit>, width: usize, elf_attack: u32, elf_casualty: bool, } impl Board { fn from_bytes(bytes: io::Bytes<io::Stdin>) -> Result<Board> { let mut tiles = Vec::new(); let mut units = BTreeMap::new(); let mut width = 0; for byte in bytes { let byte = byte?; if byte == b'\n' { if width == 0 { width = tiles.len(); } else if tiles.len() % width != 0 { return Err("non-rectangular input".into()); } continue; } let tile = match byte { b'#' => Tile::Wall, b'.' => Tile::Open, b'E' | b'G' => { units.insert( tiles.len(), Unit { hp: 200, attack: 3, kind: match byte { b'E' => UnitKind::Elf, b'G' | _ => UnitKind::Goblin, }, id: units.len(), }, ); Tile::Unit } _ => return Err("invalid byte".into()), }; tiles.push(tile); } Ok(Board { tiles, units, width, elf_attack: 3, elf_casualty: false, }) } fn neighbors(&self, pos: usize) -> impl Iterator<Item = usize> { // Assumes board bordered by walls. vec![pos - self.width, pos - 1, pos + 1, pos + self.width].into_iter() } fn open_neighbors(&self, pos: usize) -> impl Iterator<Item = usize> { self.neighbors(pos) .filter(|&pos| self.tiles[pos] == Tile::Open) .collect::<Vec<_>>() .into_iter() } fn enemy_neighbors(&self, pos: usize, kind: UnitKind) -> impl Iterator<Item = usize> { self.neighbors(pos) .filter(|pos| match self.units.get(pos) { Some(unit) => unit.kind != kind, None => false, }) .collect::<Vec<_>>() .into_iter() } fn bfs_step(&self, src: usize, dst: Vec<usize>) -> Option<usize> { let mut distances = vec![usize::MAX; self.tiles.len()]; let mut max_distance = usize::MAX; let mut horizon = VecDeque::new(); horizon.push_back((0, src)); while let Some((distance, pos)) = horizon.pop_front() { if distance > max_distance { break; } if distance >= distances[pos] { continue; } else { distances[pos] = distance; } if dst.contains(&pos) { max_distance = distance; } for neighbor in self.open_neighbors(pos) { horizon.push_back((distance + 1, neighbor)); } } let position = dst .into_iter() .filter(|&d| distances[d] == max_distance) .min() .unwrap(); let mut positions = vec![position]; let mut distance = max_distance; if distance == usize::MAX { return None; } while distance > 1 { distance -= 1; positions = positions .into_iter() .flat_map(|p| self.open_neighbors(p)) .filter(|&p| distances[p] == distance) .collect(); positions.sort(); positions.dedup(); } Some(positions[0]) } fn attack_for(&self, unit: &Unit) -> u32 { match unit.kind { UnitKind::Goblin => 3, UnitKind::Elf => self.elf_attack, } } fn next_round(&mut self) -> bool { let units: Vec<_> = self.units.keys().cloned().map(|p| (p, self.units[&p].id)).collect(); for (mut pos, id) in units { let unit = self.units.get(&pos); if unit.map(|u| u.id != id).unwrap_or(true) { continue; } let unit = unit.unwrap(); let targets: Vec<_> = self .units .iter() .filter(|(_, target)| target.kind != unit.kind) .collect(); if targets.is_empty() { return false; } let mut targets: Vec<_> = targets .iter() .flat_map(|&(&pos, _)| self.neighbors(pos)) .filter(|&pos| self.tiles[pos] == Tile::Open) .collect(); targets.sort(); targets.dedup(); if let None = self.enemy_neighbors(pos, unit.kind).next() { if targets.is_empty() { continue; } if let Some(next_pos) = self.bfs_step(pos, targets) { self.tiles.swap(pos, next_pos); let unit = self.units.remove(&pos).unwrap(); self.units.insert(next_pos, unit); pos = next_pos; } } let unit = &self.units[&pos]; let enemy = self .enemy_neighbors(pos, unit.kind) .map(|pos| (&self.units[&pos], pos)) .min(); if let Some((enemy, enemy_pos)) = enemy { let attack = self.attack_for(unit); if enemy.hp <= attack { if enemy.kind == UnitKind::Elf { self.elf_casualty = true; } self.tiles[enemy_pos] = Tile::Open; self.units.remove(&enemy_pos); } else { self.units.get_mut(&enemy_pos).unwrap().hp -= attack; } } } true } fn remaining_hp(&self) -> u32 { self.units.values().map(|unit| unit.hp).sum() } } impl fmt::Display for Board { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut units = Vec::new(); for (i, tile) in self.tiles.iter().enumerate() { let c = match tile { Tile::Wall => '#', Tile::Open => '.', Tile::Unit => { let Unit { kind, hp, .. } = &self.units[&i]; let c = match kind { UnitKind::Goblin => 'G', UnitKind::Elf => 'E', }; units.push((c, hp)); c } }; write!(f, "{}", c)?; if (i + 1) % self.width == 0 { if !units.is_empty() { let units_str = units .iter() .map(|(c, hp)| format!("{}({})", c, hp)) .collect::<Vec<_>>() .join(", "); write!(f, " {}", units_str)?; units.clear(); } writeln!(f)?; } } Ok(()) } } fn main() -> Result<()> { let orig_board = Board::from_bytes(io::stdin().bytes())?; let mut board = orig_board.clone(); let mut i = 0; while board.next_round() { i += 1; } println!("{}", i * board.remaining_hp()); 'outer: for attack in 4.. { let mut board = orig_board.clone(); board.elf_attack = attack; let mut i = 0; while board.next_round() { if board.elf_casualty { continue 'outer; } i += 1; } println!("{}", i * board.remaining_hp()); break; } Ok(()) }
use rand::Rng; use rand::XorShiftRng; use std::ops::{Add, Index, IndexMut}; use treap::implicit_tree; use treap::node::ImplicitNode; /// A list implemented using an implicit treap. /// /// A treap is a tree that satisfies both the binary search tree property and a heap property. Each /// node has a key, a value, and a priority. The key of any node is greater than all keys in its /// left subtree and less than all keys occuring in its right subtree. The priority of a node is /// greater than the priority of all nodes in its subtrees. By randomly generating priorities, the /// expected height of the tree is proportional to the logarithm of the number of keys. /// /// An implicit treap is a treap where the key of a node is implicitly determined by the size of /// its left subtree. This property allows the list to get, remove, and insert at an arbitrary index /// in `O(log N)` time. /// /// # Examples /// ``` /// use extended_collections::treap::TreapList; /// /// let mut list = TreapList::new(); /// list.insert(0, 1); /// list.push_back(2); /// list.push_front(3); /// /// assert_eq!(list.get(0), Some(&3)); /// assert_eq!(list.get(3), None); /// assert_eq!(list.len(), 3); /// /// *list.get_mut(0).unwrap() += 1; /// assert_eq!(list.pop_front(), 4); /// assert_eq!(list.pop_back(), 2); /// ``` pub struct TreapList<T> { tree: implicit_tree::Tree<T>, rng: XorShiftRng, } impl<T> TreapList<T> { /// Constructs a new, empty `TreapList<T>`. /// /// # Examples /// ``` /// use extended_collections::treap::TreapList; /// /// let list: TreapList<u32> = TreapList::new(); /// ``` pub fn new() -> Self { TreapList { tree: None, rng: XorShiftRng::new_unseeded(), } } /// Inserts a value into the list at a particular index, shifting elements one position to the /// right if needed. /// /// # Examples /// ``` /// use extended_collections::treap::TreapList; /// /// let mut list = TreapList::new(); /// list.insert(0, 1); /// list.insert(0, 2); /// assert_eq!(list.get(0), Some(&2)); /// assert_eq!(list.get(1), Some(&1)); /// ``` pub fn insert(&mut self, index: usize, value: T) { let TreapList { ref mut tree, ref mut rng } = self; implicit_tree::insert(tree, index + 1, ImplicitNode::new(value, rng.next_u32())); } /// Removes a value at a particular index from the list. Returns the value at the index. /// /// # Examples /// ``` /// use extended_collections::treap::TreapList; /// /// let mut list = TreapList::new(); /// list.insert(0, 1); /// assert_eq!(list.remove(0), 1); /// ``` pub fn remove(&mut self, index: usize) -> T { implicit_tree::remove(&mut self.tree, index + 1) } /// Inserts a value at the front of the list. /// /// # Examples /// ``` /// use extended_collections::treap::TreapList; /// /// let mut list = TreapList::new(); /// list.push_front(1); /// list.push_front(2); /// assert_eq!(list.get(0), Some(&2)); /// ``` pub fn push_front(&mut self, value: T) { self.insert(0, value); } /// Inserts a value at the back of the list. /// /// # Examples /// ``` /// use extended_collections::treap::TreapList; /// /// let mut list = TreapList::new(); /// list.push_back(1); /// list.push_back(2); /// assert_eq!(list.get(0), Some(&1)); /// ``` pub fn push_back(&mut self, value: T) { let index = self.len(); self.insert(index, value); } /// Removes a value at the front of the list. /// /// # Panics /// Panics if list is empty. /// /// # Examples /// ``` /// use extended_collections::treap::TreapList; /// /// let mut list = TreapList::new(); /// list.push_back(1); /// list.push_back(2); /// assert_eq!(list.pop_front(), 1); /// ``` pub fn pop_front(&mut self) -> T { self.remove(0) } /// Removes a value at the back of the list. /// /// # Panics /// Panics if list is empty. /// /// # Examples /// ``` /// use extended_collections::treap::TreapList; /// /// let mut list = TreapList::new(); /// list.push_back(1); /// list.push_back(2); /// assert_eq!(list.pop_back(), 2); /// ``` pub fn pop_back(&mut self) -> T { let index = self.len() - 1; self.remove(index) } /// Returns an immutable reference to the value at a particular index. Returns `None` if the /// index is out of bounds. /// /// # Examples /// ``` /// use extended_collections::treap::TreapList; /// /// let mut list = TreapList::new(); /// list.insert(0, 1); /// assert_eq!(list.get(0), Some(&1)); /// assert_eq!(list.get(1), None); /// ``` pub fn get(&self, index: usize) -> Option<&T> { implicit_tree::get(&self.tree, index + 1) } /// Returns a mutable reference to the value at a particular index. Returns `None` if the /// index is out of bounds. /// /// # Examples /// ``` /// use extended_collections::treap::TreapList; /// /// let mut list = TreapList::new(); /// list.insert(0, 1); /// *list.get_mut(0).unwrap() = 2; /// assert_eq!(list.get(0), Some(&2)); /// ``` pub fn get_mut(&mut self, index: usize) -> Option<&mut T> { implicit_tree::get_mut(&mut self.tree, index + 1) } /// Returns the number of elements in the list. /// /// # Examples /// ``` /// use extended_collections::treap::TreapList; /// /// let mut list = TreapList::new(); /// list.insert(0, 1); /// assert_eq!(list.len(), 1); /// ``` pub fn len(&self) -> usize { implicit_tree::len(&self.tree) } /// Returns `true` if the list is empty. /// /// # Examples /// ``` /// use extended_collections::treap::TreapList; /// /// let list: TreapList<u32> = TreapList::new(); /// assert!(list.is_empty()); /// ``` pub fn is_empty(&self) -> bool { self.tree.is_none() } /// Clears the list, removing all values. /// /// # Examples /// ``` /// use extended_collections::treap::TreapList; /// /// let mut list = TreapList::new(); /// list.insert(0, 1); /// list.insert(1, 2); /// list.clear(); /// assert_eq!(list.is_empty(), true); /// ``` pub fn clear(&mut self) { self.tree = None; } /// Returns an iterator over the list. /// /// # Examples /// ``` /// use extended_collections::treap::TreapList; /// /// let mut list = TreapList::new(); /// list.insert(0, 1); /// list.insert(1, 2); /// /// let mut iterator = list.iter(); /// assert_eq!(iterator.next(), Some(&1)); /// assert_eq!(iterator.next(), Some(&2)); /// assert_eq!(iterator.next(), None); /// ``` pub fn iter(&self) -> TreapListIter<T> { TreapListIter { current: &self.tree, stack: Vec::new(), } } /// Returns a mutable iterator over the list. /// /// # Examples /// ``` /// use extended_collections::treap::TreapList; /// /// let mut list = TreapList::new(); /// list.insert(0, 1); /// list.insert(1, 2); /// /// for value in &mut list { /// *value += 1; /// } /// /// let mut iterator = list.iter(); /// assert_eq!(iterator.next(), Some(&2)); /// assert_eq!(iterator.next(), Some(&3)); /// assert_eq!(iterator.next(), None); /// ``` pub fn iter_mut(&mut self) -> TreapListIterMut<T> { TreapListIterMut { current: self.tree.as_mut().map(|node| &mut **node), stack: Vec::new(), } } } impl<T> IntoIterator for TreapList<T> { type Item = T; type IntoIter = TreapListIntoIter<T>; fn into_iter(self) -> Self::IntoIter { Self::IntoIter { current: self.tree, stack: Vec::new(), } } } impl<'a, T> IntoIterator for &'a TreapList<T> where T: 'a, { type Item = &'a T; type IntoIter = TreapListIter<'a, T>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl<'a, T> IntoIterator for &'a mut TreapList<T> where T: 'a, { type Item = &'a mut T; type IntoIter = TreapListIterMut<'a, T>; fn into_iter(self) -> Self::IntoIter { self.iter_mut() } } /// An owning iterator for `TreapList<T>`. /// /// This iterator traverses the elements of the list and yields owned entries. pub struct TreapListIntoIter<T> { current: implicit_tree::Tree<T>, stack: Vec<ImplicitNode<T>>, } impl<T> Iterator for TreapListIntoIter<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { while let Some(mut node) = self.current.take() { self.current = node.left.take(); self.stack.push(*node); } self.stack.pop().map(|node| { let ImplicitNode { value, right, .. } = node; self.current = right; value }) } } /// An iterator for `TreapList<T>`. /// /// This iterator traverses the elements of the list in-order and yields immutable references. pub struct TreapListIter<'a, T> where T: 'a, { current: &'a implicit_tree::Tree<T>, stack: Vec<&'a ImplicitNode<T>>, } impl<'a, T> Iterator for TreapListIter<'a, T> where T: 'a, { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { while let Some(ref node) = self.current { self.current = &node.left; self.stack.push(node); } self.stack.pop().map(|node| { let ImplicitNode { ref value, ref right, .. } = node; self.current = right; value }) } } type BorrowedTreeMut<'a, T> = Option<&'a mut ImplicitNode<T>>; /// A mutable iterator for `TreapList<T>`. /// /// This iterator traverses the elements of the list in-order and yields mutable references. pub struct TreapListIterMut<'a, T> where T: 'a, { current: Option<&'a mut ImplicitNode<T>>, stack: Vec<Option<(&'a mut T, BorrowedTreeMut<'a, T>)>>, } impl<'a, T> Iterator for TreapListIterMut<'a, T> where T: 'a, { type Item = &'a mut T; fn next(&mut self) -> Option<Self::Item> { let TreapListIterMut { current, stack } = self; while current.is_some() { stack.push(current.take().map(|node| { *current = node.left.as_mut().map(|node| &mut **node); (&mut node.value, node.right.as_mut().map(|node| &mut **node)) })); } stack.pop().and_then(|pair_opt| { match pair_opt { Some(pair) => { let (value, right) = pair; *current = right; Some(value) }, None => None, } }) } } impl<T> Default for TreapList<T> { fn default() -> Self { Self::new() } } impl<T> Add for TreapList<T> { type Output = TreapList<T>; fn add(mut self, other: TreapList<T>) -> TreapList<T> { implicit_tree::merge(&mut self.tree, other.tree); TreapList { tree: self.tree.take(), rng: self.rng, } } } impl<T> Index<usize> for TreapList<T> { type Output = T; fn index(&self, index: usize) -> &Self::Output { self.get(index).expect("Index out of bounds.") } } impl<T> IndexMut<usize> for TreapList<T> { fn index_mut(&mut self, index: usize) -> &mut Self::Output { self.get_mut(index).expect("Index out of bounds.") } } #[cfg(test)] mod tests { use super::TreapList; #[test] fn test_len_empty() { let list: TreapList<u32> = TreapList::new(); assert_eq!(list.len(), 0); } #[test] fn test_is_empty() { let list: TreapList<u32> = TreapList::new(); assert!(list.is_empty()); } #[test] fn test_insert() { let mut list = TreapList::new(); list.insert(0, 1); assert_eq!(list.get(0), Some(&1)); } #[test] fn test_remove() { let mut list = TreapList::new(); list.insert(0, 1); let ret = list.remove(0); assert_eq!(list.get(0), None); assert_eq!(ret, 1); } #[test] fn test_get_mut() { let mut list = TreapList::new(); list.insert(0, 1); { let value = list.get_mut(0); *value.unwrap() = 3; } assert_eq!(list.get(0), Some(&3)); } #[test] fn test_push_front() { let mut list = TreapList::new(); list.insert(0, 1); list.push_front(2); assert_eq!(list.get(0), Some(&2)); } #[test] fn test_push_back() { let mut list = TreapList::new(); list.insert(0, 1); list.push_back(2); assert_eq!(list.get(1), Some(&2)); } #[test] fn test_pop_front() { let mut list = TreapList::new(); list.insert(0, 1); list.insert(1, 2); assert_eq!(list.pop_front(), 1); } #[test] fn test_pop_back() { let mut list = TreapList::new(); list.insert(0, 1); list.insert(1, 2); assert_eq!(list.pop_back(), 2); } #[test] fn test_add() { let mut n = TreapList::new(); n.insert(0, 1); n.insert(0, 2); n.insert(1, 3); let mut m = TreapList::new(); m.insert(0, 4); m.insert(0, 5); m.insert(1, 6); let res = n + m; assert_eq!( res.iter().collect::<Vec<&u32>>(), vec![&2, &3, &1, &5, &6, &4], ); assert_eq!(res.len(), 6); } #[test] fn test_into_iter() { let mut list = TreapList::new(); list.insert(0, 1); list.insert(0, 2); list.insert(1, 3); assert_eq!( list.into_iter().collect::<Vec<u32>>(), vec![2, 3, 1], ); } #[test] fn test_iter() { let mut list = TreapList::new(); list.insert(0, 1); list.insert(0, 2); list.insert(1, 3); assert_eq!( list.iter().collect::<Vec<&u32>>(), vec![&2, &3, &1], ); } #[test] fn test_iter_mut() { let mut list = TreapList::new(); list.insert(0, 1); list.insert(0, 2); list.insert(1, 3); for value in &mut list { *value += 1; } assert_eq!( list.iter().collect::<Vec<&u32>>(), vec![&3, &4, &2], ); } }
#![cfg_attr(feature = "nightly", feature(external_doc))] /*! [`RangeMap`] and [`RangeInclusiveMap`] are map data structures whose keys are stored as ranges. Contiguous and overlapping ranges that map to the same value are coalesced into a single range. Corresponding [`RangeSet`] and [`RangeInclusiveSet`] structures are also provided. # Different kinds of ranges `RangeMap` and `RangeInclusiveMap` correspond to the [`Range`] and [`RangeInclusive`] types from the standard library respectively. For some applications the choice of range type may be obvious, or even be dictated by pre-existing design decisions. For other applications the choice may seem arbitrary, and be guided instead by convenience or aesthetic preference. If the choice is not obvious in your case, consider these differences: - If your key type `K` represents points on a continuum (e.g. `f64`), and the choice of which of two adjacent ranges "owns" the value where they touch is largely arbitrary, then it may be more natural to work with half-open `Range`s like `0.0..1.0` and `1.0..2.0`. If you were to use closed `RangeInclusive`s here instead, then to represent two such adjacent ranges you would need to subtract some infinitesimal (which may depend, as it does in the case of `f64`, on the specific value of `K`) from the end of the earlier range. (See the last point below for more on this problem.) - If you need to represent ranges that _include_ the maximum value in the key domain (e.g. `255u8`) then you will probably want to use `RangeInclusive`s like `128u8..=255u8`. Sometimes it may be possible to instead work around this by using a wider key type than the values you are actually trying to represent (`K=u16` even though you are only trying to represent ranges covering `u8`) but in these cases the key domain often represents discrete objects rather than points on a continuum, and so `RangeInclusive` may be a more natural way to express these ranges anyway. - If you are using `RangeInclusive`, then it must be possible to define _successor_ and _predecessor_ functions for your key type `K`, because adjacent ranges can not be detected (and thereby coalesced) simply by testing their ends for equality. For key types that represent points on a continuum, defining these functions may be awkward and error-prone. For key types that represent discrete objects, this is usually much more straightforward. # Example: use with Chrono ```rust use chrono::offset::TimeZone; use chrono::{Duration, Utc}; use rangemap::RangeMap; let people = ["Alice", "Bob", "Carol"]; let mut roster = RangeMap::new(); // Set up initial roster. let start_of_roster = Utc.ymd(2019, 1, 7); let mut week_start = start_of_roster; for _ in 0..3 { for person in &people { let next_week = week_start + Duration::weeks(1); roster.insert(week_start..next_week, person); week_start = next_week; } } // Bob is covering Alice's second shift (the fourth shift overall). let fourth_shift_start = start_of_roster + Duration::weeks(3); let fourth_shift_end = fourth_shift_start + Duration::weeks(1); roster.insert(fourth_shift_start..fourth_shift_end, &"Bob"); for (range, person) in roster.iter() { println!("{} ({}): {}", range.start, range.end - range.start, person); } // Output: // 2019-01-07UTC (P7D): Alice // 2019-01-14UTC (P7D): Bob // 2019-01-21UTC (P7D): Carol // 2019-01-28UTC (P14D): Bob // 2019-02-11UTC (P7D): Carol // 2019-02-18UTC (P7D): Alice // 2019-02-25UTC (P7D): Bob // 2019-03-04UTC (P7D): Carol ``` [`RangeMap`]: crate::RangeMap [`RangeInclusiveMap`]: crate::RangeInclusiveMap [`RangeSet`]: crate::RangeSet [`RangeInclusiveSet`]: crate::RangeInclusiveSet [`Range`]: std::ops::Range [`RangeInclusive`]: std::ops::RangeInclusive */ mod inclusive_map; mod inclusive_set; mod map; mod range_wrapper; mod set; mod std_ext; #[cfg(test)] mod stupid_range_map; pub use inclusive_map::RangeInclusiveMap; pub use inclusive_set::RangeInclusiveSet; pub use map::RangeMap; pub use set::RangeSet; pub use std_ext::{StepFns, StepLite}; // Doc tests for README. #[cfg(feature = "nightly")] #[doc(include = "../README.md")] struct _Readme {}
//! A simple implementation of the Y Combinator: //! λf.(λx.xx)(λx.f(xx)) //! <=> λf.(λx.f(xx))(λx.f(xx)) /// A function type that takes its own type as an input is an infinite recursive type. /// We introduce the "Apply" trait, which will allow us to have an input with the same type as self, and break the recursion. /// The input is going to be a trait object that implements the desired function in the interface. trait Apply<T, R> { fn apply(&self, f: &dyn Apply<T, R>, t: T) -> R; } /// If we were to pass in self as f, we get: /// λf.λt.sft /// => λs.λt.sst [s/f] /// => λs.ss impl<T, R, F> Apply<T, R> for F where F: Fn(&dyn Apply<T, R>, T) -> R { fn apply(&self, f: &dyn Apply<T, R>, t: T) -> R { self(f, t) } } /// (λt(λx.(λy.xxy))(λx.(λy.f(λz.xxz)y)))t /// => (λx.xx)(λx.f(xx)) /// => Yf fn y<T, R>(f: impl Fn(&dyn Fn(T) -> R, T) -> R) -> impl Fn(T) -> R { move |t| (&|x: &dyn Apply<T, R>, y| x.apply(x, y)) (&|x: &dyn Apply<T, R>, y| f(&|z| x.apply(x, z), y), t) } /// Factorial of n. fn fac(n: usize) -> usize { let almost_fac = |f: &dyn Fn(usize) -> usize, x| if x == 0 { 1 } else { x * f(x - 1) }; y(almost_fac)(n) } /// nth Fibonacci number. fn fib(n: usize) -> usize { let almost_fib = |f: &dyn Fn((usize, usize, usize)) -> usize, (a0, a1, x)| match x { 0 => a0, 1 => a1, _ => f((a1, a0 + a1, x - 1)), }; y(almost_fib)((1, 1, n)) } /// Driver function. fn main() { let n = 10; println!("fac({}) = {}", n, fac(n)); println!("fib({}) = {}", n, fib(n)); }
#![allow(non_snake_case)] #![allow(unused_must_use)] use std::net; use std::time; use std::thread; use std::sync::mpsc; use std::error::Error; use std::io::prelude::*; use crate::encoder::Encoder; use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6, Ipv4Addr, Ipv6Addr, ToSocketAddrs, TcpStream}; #[allow(unused_imports)] use log::{trace, debug, info, warn, error, Level}; //pub fn handle_connection(&self, client_stream:net::TcpStream, encoder:Encoder) { pub fn handle_connection(rx: mpsc::Receiver<(TcpStream, Encoder)>, BUFFER_SIZE: usize){ for (client_stream, encoder) in rx { thread::spawn( move || do_handle_connection(client_stream, encoder, BUFFER_SIZE)); } } pub fn do_handle_connection(client_stream: TcpStream, encoder: Encoder, BUFFER_SIZE: usize) { let _encoder = encoder.clone(); let _client_stream = client_stream.try_clone().unwrap(); let upstream = match proxy_handshake(_client_stream, _encoder){ Ok(stream) => stream, Err(_) => {client_stream.shutdown(net::Shutdown::Both); return;} }; upstream.set_nodelay(true); upstream.set_read_timeout(Some(time::Duration::from_secs(18000))); // timeout 5 hours client_stream.set_nodelay(true); client_stream.set_read_timeout(Some(time::Duration::from_secs(18000))); // timeout 5 hours let mut upstream_read = upstream.try_clone().unwrap(); let mut upstream_write = upstream.try_clone().unwrap(); let mut client_stream_read = client_stream.try_clone().unwrap(); let mut client_stream_write = client_stream.try_clone().unwrap(); let decoder = encoder.clone(); // download stream let _download = thread::spawn(move || { let mut index: usize; let mut buf = vec![0u8; BUFFER_SIZE]; loop { index = match upstream_read.read(&mut buf[..BUFFER_SIZE-60]) { Ok(read_size) if read_size > 0 => read_size, _ => break }; index = encoder.encode(&mut buf, index); match client_stream_write.write(&buf[..index]) { Ok(_) => (), Err(_) => break }; } upstream_read.shutdown(net::Shutdown::Both); client_stream_write.shutdown(net::Shutdown::Both); trace!("Download stream exited..."); }); // upload stream let _upload = thread::spawn(move || { let mut index: usize = 0; let mut offset: i32; let mut last_offset: i32 = 0; let mut buf = vec![0u8; BUFFER_SIZE]; loop { // from docs, size = 0 means EOF, // maybe we don't need to worry about TCP Keepalive here. index += match client_stream_read.read(&mut buf[index..]) { Ok(read_size) if read_size > 0 => read_size, _ => break, }; offset = 0; loop { let (data_len, _offset) = decoder.decode(&mut buf[offset as usize..index]); if data_len > 0 { offset += _offset; match upstream_write.write(&buf[offset as usize - data_len .. offset as usize]) { Ok(_) => (), Err(_) => { offset = -2; break; } }; if (index - offset as usize) < (1 + 12 + 2 + 16) { break; // definitely not enough data to decode } } else if data_len == 0 && _offset == -1 { if last_offset == -1 { offset = -2; } else { offset = -1; } break; } else { break; } // decrypted_size == 0 && offset != -1: not enough data to decode } if offset > 0 { buf.copy_within(offset as usize .. index, 0); index = index - (offset as usize); last_offset = 0; } else if offset == -1 { last_offset = -1; } else if offset == -2 { // if decryption failed continuously, then we kill the stream error!("Packet decode error from: [{}]", client_stream_read.peer_addr().unwrap()); break; } } client_stream_read.shutdown(net::Shutdown::Both); upstream_write.shutdown(net::Shutdown::Both); trace!("Upload stream exited..."); }); } pub fn proxy_handshake(mut stream: TcpStream, encoder: Encoder) -> Result<TcpStream, Box<dyn Error>>{ let mut buf = [0u8; 4096]; let mut buf_toss = [0u8; 4096]; let _len = stream.peek(&mut buf)?; // TTCONNECT may send data packet right after handshake packet. // thus we have to peek here, then use read() to // consume proper length of data let (data_len, offset) = encoder.decode(&mut buf[.._len]); let index = offset as usize - data_len; // TT CONNECT (for tt client > 0.12.1) if &buf[index .. index + 9] == "TTCONNECT".as_bytes() { // toss away decrypted data stream.read(&mut buf_toss[ .. offset as usize])?; let addr: Vec<SocketAddr> = { let domain = String::from_utf8_lossy(&buf[index + 9 .. offset as usize]); debug!("[TTCONNECT] {} => {}", stream.peer_addr().unwrap(), domain); domain.to_socket_addrs()?.collect() }; match TcpStream::connect(&addr[..]){ Ok(upstream) => return Ok(upstream), Err(_) => return Err("upstream connect failed".into()) } } else{ // if not TTCONNECT, toss away the data from socket queue stream.read(&mut buf_toss[.._len])?; } // SOCKS5 (for tt client <= 0.12.1) if (data_len == 2 + buf[index+1] as usize) && buf[index] == 0x05 { buf[..2].copy_from_slice(&[0x05, 0x00]); let data_len = encoder.encode(&mut buf, 2); stream.write(&buf[..data_len])?; stream.read(&mut buf)?; let (data_len, offset) = encoder.decode(&mut buf); if data_len == 0 || buf[offset as usize - data_len + 1] != 0x01 { return Err("not CONNECT".into()); // not CONNECT } let _buf = &buf[offset as usize - data_len .. offset as usize]; let port:u16 = ((_buf[data_len-2] as u16) << 8) | _buf[data_len-1] as u16; let (addr, domain) = match _buf[3] { 0x01 => { // ipv4 address ( vec![SocketAddr::from( SocketAddrV4::new(Ipv4Addr::new(_buf[4], _buf[5], _buf[6], _buf[7]), port) )], None ) }, 0x03 => { // domain name let length = _buf[4] as usize; let mut domain = String::from_utf8_lossy(&_buf[5..length+5]).to_string(); domain.push_str(&":"); domain.push_str(&port.to_string()); (domain.to_socket_addrs()?.collect(), Some(domain)) }, 0x04 => { // ipv6 address let buf = (2..10).map(|x| { (u16::from(_buf[(x * 2)]) << 8) | u16::from(_buf[(x * 2) + 1]) }).collect::<Vec<u16>>(); ( vec![ SocketAddr::from( SocketAddrV6::new( Ipv6Addr::new( buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]), port, 0, 0) )], None ) }, _ => return Err("failed to parse address".into()), }; match domain { Some(value) => debug!("[SOCKS5] CONNECT: {} => {}", stream.peer_addr().unwrap(), value), None => debug!("[SOCKS5] CONNECT: {} => {}", stream.peer_addr().unwrap(), addr[0]) } match TcpStream::connect(&addr[..]){ Ok(upstream) => { buf[..10].copy_from_slice(&[0x5, 0x0, 0x0, 0x1, 0x7f, 0x0, 0x0, 0x1, 0x0, 0x0]); let data_len = encoder.encode(&mut buf, 10); match stream.write(&buf[..data_len]) { Ok(_) => return Ok(upstream), Err(_) => { upstream.shutdown(net::Shutdown::Both); return Err("client write failed".into()); } }; }, Err(_) => { buf[..2].copy_from_slice(&[0x05, 0x01]); let data_len = encoder.encode(&mut buf, 2); stream.write(&buf[..data_len])?; return Err("upstream connect failed".into()); } } } // HTTP CONNECT (for tt client <= 0.12.1) else if &buf[index .. index + 7] == "CONNECT".as_bytes() { let addr: Vec<SocketAddr> = { let domain = String::from_utf8_lossy(&buf[index..offset as usize]).split_whitespace().collect::<Vec<&str>>()[1].to_string(); debug!("[HTTP] CONNECT: {} => {}", stream.peer_addr().unwrap(), domain); domain.to_socket_addrs()?.collect() }; match TcpStream::connect(&addr[..]){ Ok(upstream) => { buf[..39].copy_from_slice("HTTP/1.0 200 Connection established\r\n\r\n".as_bytes()); let data_len = encoder.encode(&mut buf, 39); match stream.write(&buf[..data_len]) { Ok(_) => return Ok(upstream), Err(_) => { upstream.shutdown(net::Shutdown::Both); return Err("client write failed".into()); } }; }, Err(_) => { buf[..31].copy_from_slice("HTTP/1.0 500 CONNECT Failed\r\n\r\n".as_bytes()); let data_len = encoder.encode(&mut buf, 31); stream.write(&buf[..data_len])?; return Err("upstream connect failed".into()); } } } // HTTP Plain (for tt client <= 0.12.1) else { let addr: Vec<SocketAddr> = { let domain = String::from_utf8_lossy(&buf[index..offset as usize]).split_whitespace().collect::<Vec<&str>>()[1].to_string(); debug!("[HTTP] Proxy: {} => {}", stream.peer_addr().unwrap(), domain); //let mut domain = domain.split("//").collect::<Vec<&str>>()[1].trim_end_matches('/').split("/").collect::<Vec<&str>>()[0].to_string(); let domain = domain.split("//").collect::<Vec<&str>>(); let mut domain = match domain.len() { 1 => return Err("Handshake failed at HTTP Proxy, invalid request".into()), _ => domain[1].trim_end_matches('/').split("/").collect::<Vec<&str>>()[0].to_string(), }; if !domain.contains(":") { domain.push_str(":80") } domain.to_socket_addrs()?.collect() }; match TcpStream::connect(&addr[..]){ Ok(mut upstream) => { match upstream.write(&buf[index .. offset as usize]) { Ok(_) => return Ok(upstream), Err(_) => { upstream.shutdown(net::Shutdown::Both); return Err("client write failed".into()); } }; }, Err(_) => { buf[..28].copy_from_slice("HTTP/1.0 500 HTTP Failed\r\n\r\n".as_bytes()); let data_len = encoder.encode(&mut buf, 28); stream.write(&buf[..data_len])?; return Err("upstream connect failed".into()); } } } }
use std::fmt::Display; use std::fmt::Formatter; use core::fmt; #[derive(Debug)] enum FizzBuzz { Fizz, Buzz, FizzBuzz, Other(u32), } impl From<u32> for FizzBuzz { fn from(item: u32) -> Self { match (item % 3 == 0, item % 5 == 0) { (false, false) => FizzBuzz::Other(item), (true, false) => FizzBuzz::Fizz, (false, true) => FizzBuzz::Buzz, (true, true) => FizzBuzz::FizzBuzz, } } } impl Display for FizzBuzz { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { FizzBuzz::Other(n) => write!(f, "{}", n), _ => write!(f, "{:?}", self), } } } #[cfg(test)] mod tests { use super::*; #[test] fn from(){ for i in 1..=100 { println!("{:?}", FizzBuzz::from(i)); } } #[test] fn into(){ for i in 1..=100 { let fizzbuzz : FizzBuzz = i.into(); println!("{:?}", fizzbuzz); } } #[test] fn display() { for i in 1..=100 { println!("{}", FizzBuzz::from(i)); } } }
use crate::grammar::ast::{BinaryOp, Expression}; use crate::grammar::model::WrightInput; use crate::grammar::parsers::expression::binary_expression::primary::parser_left; use crate::grammar::parsers::expression::binary_expression::primary::relational::{ relational, relational_primary, }; use crate::grammar::tracing::parsers::alt; use crate::grammar::tracing::trace_result; use nom::IResult; pub fn equality_primary<I: WrightInput>(input: I) -> IResult<I, Expression<I>> { let trace = "BinaryExpr::equality_primary"; trace_result( trace, alt((relational, relational_primary))(input.trace_start_clone(trace)), ) } /// Parse equality expression. pub fn equality<I: WrightInput>(input: I) -> IResult<I, Expression<I>> { let trace = "BinaryExpr::equality"; trace_result( trace, parser_left(equality_primary, BinaryOp::parse_equality_operator)( input.trace_start_clone(trace), ), ) }
// This file is part of Substrate. // Copyright (C) 2017-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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. //! Genesis config definition. use super::super::{DeclStorageDefExt, StorageLineTypeDef}; use frame_support_procedural_tools::syn_ext as ext; use proc_macro2::TokenStream; use quote::quote; use syn::{parse_quote, spanned::Spanned}; pub struct GenesisConfigFieldDef { pub name: syn::Ident, pub typ: syn::Type, pub attrs: Vec<syn::Meta>, pub default: TokenStream, } pub struct GenesisConfigDef { pub is_generic: bool, pub fields: Vec<GenesisConfigFieldDef>, /// For example: `<T: Trait<I>, I: Instance=DefaultInstance>`. pub genesis_struct_decl: TokenStream, /// For example: `<T, I>`. pub genesis_struct: TokenStream, /// For example: `<T: Trait<I>, I: Instance>`. pub genesis_impl: TokenStream, /// The where clause to use to constrain generics if genesis config is generic. pub genesis_where_clause: Option<syn::WhereClause>, } impl GenesisConfigDef { pub fn from_def(def: &DeclStorageDefExt) -> syn::Result<Self> { let fields = Self::get_genesis_config_field_defs(def)?; let is_generic = fields .iter() .any(|field| ext::type_contains_ident(&field.typ, &def.module_runtime_generic)); let (genesis_struct_decl, genesis_impl, genesis_struct, genesis_where_clause) = if is_generic { let runtime_generic = &def.module_runtime_generic; let runtime_trait = &def.module_runtime_trait; let optional_instance = &def.optional_instance; let optional_instance_bound = &def.optional_instance_bound; let optional_instance_bound_optional_default = &def.optional_instance_bound_optional_default; let where_clause = &def.where_clause; ( quote!(<#runtime_generic: #runtime_trait, #optional_instance_bound_optional_default>), quote!(<#runtime_generic: #runtime_trait, #optional_instance_bound>), quote!(<#runtime_generic, #optional_instance>), where_clause.clone(), ) } else { (quote!(), quote!(), quote!(), None) }; Ok(Self { is_generic, fields, genesis_struct_decl, genesis_struct, genesis_impl, genesis_where_clause, }) } fn get_genesis_config_field_defs( def: &DeclStorageDefExt, ) -> syn::Result<Vec<GenesisConfigFieldDef>> { let mut config_field_defs = Vec::new(); for (config_field, line) in def.storage_lines.iter().filter_map(|line| { line.config.as_ref().map(|config_field| (config_field.clone(), line)) }) { let value_type = &line.value_type; let typ = match &line.storage_type { StorageLineTypeDef::Simple(_) => (*value_type).clone(), StorageLineTypeDef::Map(map) => { let key = &map.key; parse_quote!( Vec<(#key, #value_type)> ) }, StorageLineTypeDef::DoubleMap(map) => { let key1 = &map.key1; let key2 = &map.key2; parse_quote!( Vec<(#key1, #key2, #value_type)> ) }, }; let default = line.default_value .as_ref() .map(|d| { if line.is_option { quote!( #d.unwrap_or_default() ) } else { quote!( #d ) } }) .unwrap_or_else(|| quote!(Default::default())); config_field_defs.push(GenesisConfigFieldDef { name: config_field, typ, attrs: line.doc_attrs.clone(), default, }); } for line in &def.extra_genesis_config_lines { let attrs = line .attrs .iter() .map(|attr| { let meta = attr.parse_meta()?; if meta.path().is_ident("cfg") { return Err(syn::Error::new( meta.span(), "extra genesis config items do not support `cfg` attribute", )) } Ok(meta) }) .collect::<syn::Result<_>>()?; let default = line .default .as_ref() .map(|e| quote!( #e )) .unwrap_or_else(|| quote!(Default::default())); config_field_defs.push(GenesisConfigFieldDef { name: line.name.clone(), typ: line.typ.clone(), attrs, default, }); } Ok(config_field_defs) } }
use crate::{chunked_encoder::ChunkedEncoder, http_types::Body}; use futures_lite::io::AsyncRead; use pin_project::pin_project; use std::{ io, pin::Pin, task::{Context, Poll}, }; #[pin_project(project=BodyEncoderProjection)] #[derive(Debug)] /// A http encoder for [`http_types::Body`]. You probably don't want /// to interact with this directly. pub enum BodyEncoder { /// a chunked body Chunked(#[pin] ChunkedEncoder<Body>), /// a fixed-length body Fixed(#[pin] Body), } impl BodyEncoder { /// builds a body encoder for the provided [`http_types::Body`] pub fn new(body: Body) -> Self { match body.len() { Some(_) => Self::Fixed(body), None => Self::Chunked(ChunkedEncoder::new(body)), } } } impl AsyncRead for BodyEncoder { fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<usize>> { match self.project() { BodyEncoderProjection::Chunked(encoder) => encoder.poll_read(cx, buf), BodyEncoderProjection::Fixed(body) => body.poll_read(cx, buf), } } }
/// An enum to represent all characters in the CJKCompatibilityIdeographs block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum CJKCompatibilityIdeographs { /// \u{f900}: '豈' CjkCompatibilityIdeographDashF900, /// \u{f901}: '更' CjkCompatibilityIdeographDashF901, /// \u{f902}: '車' CjkCompatibilityIdeographDashF902, /// \u{f903}: '賈' CjkCompatibilityIdeographDashF903, /// \u{f904}: '滑' CjkCompatibilityIdeographDashF904, /// \u{f905}: '串' CjkCompatibilityIdeographDashF905, /// \u{f906}: '句' CjkCompatibilityIdeographDashF906, /// \u{f907}: '龜' CjkCompatibilityIdeographDashF907, /// \u{f908}: '龜' CjkCompatibilityIdeographDashF908, /// \u{f909}: '契' CjkCompatibilityIdeographDashF909, /// \u{f90a}: '金' CjkCompatibilityIdeographDashF90a, /// \u{f90b}: '喇' CjkCompatibilityIdeographDashF90b, /// \u{f90c}: '奈' CjkCompatibilityIdeographDashF90c, /// \u{f90d}: '懶' CjkCompatibilityIdeographDashF90d, /// \u{f90e}: '癩' CjkCompatibilityIdeographDashF90e, /// \u{f90f}: '羅' CjkCompatibilityIdeographDashF90f, /// \u{f910}: '蘿' CjkCompatibilityIdeographDashF910, /// \u{f911}: '螺' CjkCompatibilityIdeographDashF911, /// \u{f912}: '裸' CjkCompatibilityIdeographDashF912, /// \u{f913}: '邏' CjkCompatibilityIdeographDashF913, /// \u{f914}: '樂' CjkCompatibilityIdeographDashF914, /// \u{f915}: '洛' CjkCompatibilityIdeographDashF915, /// \u{f916}: '烙' CjkCompatibilityIdeographDashF916, /// \u{f917}: '珞' CjkCompatibilityIdeographDashF917, /// \u{f918}: '落' CjkCompatibilityIdeographDashF918, /// \u{f919}: '酪' CjkCompatibilityIdeographDashF919, /// \u{f91a}: '駱' CjkCompatibilityIdeographDashF91a, /// \u{f91b}: '亂' CjkCompatibilityIdeographDashF91b, /// \u{f91c}: '卵' CjkCompatibilityIdeographDashF91c, /// \u{f91d}: '欄' CjkCompatibilityIdeographDashF91d, /// \u{f91e}: '爛' CjkCompatibilityIdeographDashF91e, /// \u{f91f}: '蘭' CjkCompatibilityIdeographDashF91f, /// \u{f920}: '鸞' CjkCompatibilityIdeographDashF920, /// \u{f921}: '嵐' CjkCompatibilityIdeographDashF921, /// \u{f922}: '濫' CjkCompatibilityIdeographDashF922, /// \u{f923}: '藍' CjkCompatibilityIdeographDashF923, /// \u{f924}: '襤' CjkCompatibilityIdeographDashF924, /// \u{f925}: '拉' CjkCompatibilityIdeographDashF925, /// \u{f926}: '臘' CjkCompatibilityIdeographDashF926, /// \u{f927}: '蠟' CjkCompatibilityIdeographDashF927, /// \u{f928}: '廊' CjkCompatibilityIdeographDashF928, /// \u{f929}: '朗' CjkCompatibilityIdeographDashF929, /// \u{f92a}: '浪' CjkCompatibilityIdeographDashF92a, /// \u{f92b}: '狼' CjkCompatibilityIdeographDashF92b, /// \u{f92c}: '郎' CjkCompatibilityIdeographDashF92c, /// \u{f92d}: '來' CjkCompatibilityIdeographDashF92d, /// \u{f92e}: '冷' CjkCompatibilityIdeographDashF92e, /// \u{f92f}: '勞' CjkCompatibilityIdeographDashF92f, /// \u{f930}: '擄' CjkCompatibilityIdeographDashF930, /// \u{f931}: '櫓' CjkCompatibilityIdeographDashF931, /// \u{f932}: '爐' CjkCompatibilityIdeographDashF932, /// \u{f933}: '盧' CjkCompatibilityIdeographDashF933, /// \u{f934}: '老' CjkCompatibilityIdeographDashF934, /// \u{f935}: '蘆' CjkCompatibilityIdeographDashF935, /// \u{f936}: '虜' CjkCompatibilityIdeographDashF936, /// \u{f937}: '路' CjkCompatibilityIdeographDashF937, /// \u{f938}: '露' CjkCompatibilityIdeographDashF938, /// \u{f939}: '魯' CjkCompatibilityIdeographDashF939, /// \u{f93a}: '鷺' CjkCompatibilityIdeographDashF93a, /// \u{f93b}: '碌' CjkCompatibilityIdeographDashF93b, /// \u{f93c}: '祿' CjkCompatibilityIdeographDashF93c, /// \u{f93d}: '綠' CjkCompatibilityIdeographDashF93d, /// \u{f93e}: '菉' CjkCompatibilityIdeographDashF93e, /// \u{f93f}: '錄' CjkCompatibilityIdeographDashF93f, /// \u{f940}: '鹿' CjkCompatibilityIdeographDashF940, /// \u{f941}: '論' CjkCompatibilityIdeographDashF941, /// \u{f942}: '壟' CjkCompatibilityIdeographDashF942, /// \u{f943}: '弄' CjkCompatibilityIdeographDashF943, /// \u{f944}: '籠' CjkCompatibilityIdeographDashF944, /// \u{f945}: '聾' CjkCompatibilityIdeographDashF945, /// \u{f946}: '牢' CjkCompatibilityIdeographDashF946, /// \u{f947}: '磊' CjkCompatibilityIdeographDashF947, /// \u{f948}: '賂' CjkCompatibilityIdeographDashF948, /// \u{f949}: '雷' CjkCompatibilityIdeographDashF949, /// \u{f94a}: '壘' CjkCompatibilityIdeographDashF94a, /// \u{f94b}: '屢' CjkCompatibilityIdeographDashF94b, /// \u{f94c}: '樓' CjkCompatibilityIdeographDashF94c, /// \u{f94d}: '淚' CjkCompatibilityIdeographDashF94d, /// \u{f94e}: '漏' CjkCompatibilityIdeographDashF94e, /// \u{f94f}: '累' CjkCompatibilityIdeographDashF94f, /// \u{f950}: '縷' CjkCompatibilityIdeographDashF950, /// \u{f951}: '陋' CjkCompatibilityIdeographDashF951, /// \u{f952}: '勒' CjkCompatibilityIdeographDashF952, /// \u{f953}: '肋' CjkCompatibilityIdeographDashF953, /// \u{f954}: '凜' CjkCompatibilityIdeographDashF954, /// \u{f955}: '凌' CjkCompatibilityIdeographDashF955, /// \u{f956}: '稜' CjkCompatibilityIdeographDashF956, /// \u{f957}: '綾' CjkCompatibilityIdeographDashF957, /// \u{f958}: '菱' CjkCompatibilityIdeographDashF958, /// \u{f959}: '陵' CjkCompatibilityIdeographDashF959, /// \u{f95a}: '讀' CjkCompatibilityIdeographDashF95a, /// \u{f95b}: '拏' CjkCompatibilityIdeographDashF95b, /// \u{f95c}: '樂' CjkCompatibilityIdeographDashF95c, /// \u{f95d}: '諾' CjkCompatibilityIdeographDashF95d, /// \u{f95e}: '丹' CjkCompatibilityIdeographDashF95e, /// \u{f95f}: '寧' CjkCompatibilityIdeographDashF95f, /// \u{f960}: '怒' CjkCompatibilityIdeographDashF960, /// \u{f961}: '率' CjkCompatibilityIdeographDashF961, /// \u{f962}: '異' CjkCompatibilityIdeographDashF962, /// \u{f963}: '北' CjkCompatibilityIdeographDashF963, /// \u{f964}: '磻' CjkCompatibilityIdeographDashF964, /// \u{f965}: '便' CjkCompatibilityIdeographDashF965, /// \u{f966}: '復' CjkCompatibilityIdeographDashF966, /// \u{f967}: '不' CjkCompatibilityIdeographDashF967, /// \u{f968}: '泌' CjkCompatibilityIdeographDashF968, /// \u{f969}: '數' CjkCompatibilityIdeographDashF969, /// \u{f96a}: '索' CjkCompatibilityIdeographDashF96a, /// \u{f96b}: '參' CjkCompatibilityIdeographDashF96b, /// \u{f96c}: '塞' CjkCompatibilityIdeographDashF96c, /// \u{f96d}: '省' CjkCompatibilityIdeographDashF96d, /// \u{f96e}: '葉' CjkCompatibilityIdeographDashF96e, /// \u{f96f}: '說' CjkCompatibilityIdeographDashF96f, /// \u{f970}: '殺' CjkCompatibilityIdeographDashF970, /// \u{f971}: '辰' CjkCompatibilityIdeographDashF971, /// \u{f972}: '沈' CjkCompatibilityIdeographDashF972, /// \u{f973}: '拾' CjkCompatibilityIdeographDashF973, /// \u{f974}: '若' CjkCompatibilityIdeographDashF974, /// \u{f975}: '掠' CjkCompatibilityIdeographDashF975, /// \u{f976}: '略' CjkCompatibilityIdeographDashF976, /// \u{f977}: '亮' CjkCompatibilityIdeographDashF977, /// \u{f978}: '兩' CjkCompatibilityIdeographDashF978, /// \u{f979}: '凉' CjkCompatibilityIdeographDashF979, /// \u{f97a}: '梁' CjkCompatibilityIdeographDashF97a, /// \u{f97b}: '糧' CjkCompatibilityIdeographDashF97b, /// \u{f97c}: '良' CjkCompatibilityIdeographDashF97c, /// \u{f97d}: '諒' CjkCompatibilityIdeographDashF97d, /// \u{f97e}: '量' CjkCompatibilityIdeographDashF97e, /// \u{f97f}: '勵' CjkCompatibilityIdeographDashF97f, /// \u{f980}: '呂' CjkCompatibilityIdeographDashF980, /// \u{f981}: '女' CjkCompatibilityIdeographDashF981, /// \u{f982}: '廬' CjkCompatibilityIdeographDashF982, /// \u{f983}: '旅' CjkCompatibilityIdeographDashF983, /// \u{f984}: '濾' CjkCompatibilityIdeographDashF984, /// \u{f985}: '礪' CjkCompatibilityIdeographDashF985, /// \u{f986}: '閭' CjkCompatibilityIdeographDashF986, /// \u{f987}: '驪' CjkCompatibilityIdeographDashF987, /// \u{f988}: '麗' CjkCompatibilityIdeographDashF988, /// \u{f989}: '黎' CjkCompatibilityIdeographDashF989, /// \u{f98a}: '力' CjkCompatibilityIdeographDashF98a, /// \u{f98b}: '曆' CjkCompatibilityIdeographDashF98b, /// \u{f98c}: '歷' CjkCompatibilityIdeographDashF98c, /// \u{f98d}: '轢' CjkCompatibilityIdeographDashF98d, /// \u{f98e}: '年' CjkCompatibilityIdeographDashF98e, /// \u{f98f}: '憐' CjkCompatibilityIdeographDashF98f, /// \u{f990}: '戀' CjkCompatibilityIdeographDashF990, /// \u{f991}: '撚' CjkCompatibilityIdeographDashF991, /// \u{f992}: '漣' CjkCompatibilityIdeographDashF992, /// \u{f993}: '煉' CjkCompatibilityIdeographDashF993, /// \u{f994}: '璉' CjkCompatibilityIdeographDashF994, /// \u{f995}: '秊' CjkCompatibilityIdeographDashF995, /// \u{f996}: '練' CjkCompatibilityIdeographDashF996, /// \u{f997}: '聯' CjkCompatibilityIdeographDashF997, /// \u{f998}: '輦' CjkCompatibilityIdeographDashF998, /// \u{f999}: '蓮' CjkCompatibilityIdeographDashF999, /// \u{f99a}: '連' CjkCompatibilityIdeographDashF99a, /// \u{f99b}: '鍊' CjkCompatibilityIdeographDashF99b, /// \u{f99c}: '列' CjkCompatibilityIdeographDashF99c, /// \u{f99d}: '劣' CjkCompatibilityIdeographDashF99d, /// \u{f99e}: '咽' CjkCompatibilityIdeographDashF99e, /// \u{f99f}: '烈' CjkCompatibilityIdeographDashF99f, /// \u{f9a0}: '裂' CjkCompatibilityIdeographDashF9a0, /// \u{f9a1}: '說' CjkCompatibilityIdeographDashF9a1, /// \u{f9a2}: '廉' CjkCompatibilityIdeographDashF9a2, /// \u{f9a3}: '念' CjkCompatibilityIdeographDashF9a3, /// \u{f9a4}: '捻' CjkCompatibilityIdeographDashF9a4, /// \u{f9a5}: '殮' CjkCompatibilityIdeographDashF9a5, /// \u{f9a6}: '簾' CjkCompatibilityIdeographDashF9a6, /// \u{f9a7}: '獵' CjkCompatibilityIdeographDashF9a7, /// \u{f9a8}: '令' CjkCompatibilityIdeographDashF9a8, /// \u{f9a9}: '囹' CjkCompatibilityIdeographDashF9a9, /// \u{f9aa}: '寧' CjkCompatibilityIdeographDashF9aa, /// \u{f9ab}: '嶺' CjkCompatibilityIdeographDashF9ab, /// \u{f9ac}: '怜' CjkCompatibilityIdeographDashF9ac, /// \u{f9ad}: '玲' CjkCompatibilityIdeographDashF9ad, /// \u{f9ae}: '瑩' CjkCompatibilityIdeographDashF9ae, /// \u{f9af}: '羚' CjkCompatibilityIdeographDashF9af, /// \u{f9b0}: '聆' CjkCompatibilityIdeographDashF9b0, /// \u{f9b1}: '鈴' CjkCompatibilityIdeographDashF9b1, /// \u{f9b2}: '零' CjkCompatibilityIdeographDashF9b2, /// \u{f9b3}: '靈' CjkCompatibilityIdeographDashF9b3, /// \u{f9b4}: '領' CjkCompatibilityIdeographDashF9b4, /// \u{f9b5}: '例' CjkCompatibilityIdeographDashF9b5, /// \u{f9b6}: '禮' CjkCompatibilityIdeographDashF9b6, /// \u{f9b7}: '醴' CjkCompatibilityIdeographDashF9b7, /// \u{f9b8}: '隸' CjkCompatibilityIdeographDashF9b8, /// \u{f9b9}: '惡' CjkCompatibilityIdeographDashF9b9, /// \u{f9ba}: '了' CjkCompatibilityIdeographDashF9ba, /// \u{f9bb}: '僚' CjkCompatibilityIdeographDashF9bb, /// \u{f9bc}: '寮' CjkCompatibilityIdeographDashF9bc, /// \u{f9bd}: '尿' CjkCompatibilityIdeographDashF9bd, /// \u{f9be}: '料' CjkCompatibilityIdeographDashF9be, /// \u{f9bf}: '樂' CjkCompatibilityIdeographDashF9bf, /// \u{f9c0}: '燎' CjkCompatibilityIdeographDashF9c0, /// \u{f9c1}: '療' CjkCompatibilityIdeographDashF9c1, /// \u{f9c2}: '蓼' CjkCompatibilityIdeographDashF9c2, /// \u{f9c3}: '遼' CjkCompatibilityIdeographDashF9c3, /// \u{f9c4}: '龍' CjkCompatibilityIdeographDashF9c4, /// \u{f9c5}: '暈' CjkCompatibilityIdeographDashF9c5, /// \u{f9c6}: '阮' CjkCompatibilityIdeographDashF9c6, /// \u{f9c7}: '劉' CjkCompatibilityIdeographDashF9c7, /// \u{f9c8}: '杻' CjkCompatibilityIdeographDashF9c8, /// \u{f9c9}: '柳' CjkCompatibilityIdeographDashF9c9, /// \u{f9ca}: '流' CjkCompatibilityIdeographDashF9ca, /// \u{f9cb}: '溜' CjkCompatibilityIdeographDashF9cb, /// \u{f9cc}: '琉' CjkCompatibilityIdeographDashF9cc, /// \u{f9cd}: '留' CjkCompatibilityIdeographDashF9cd, /// \u{f9ce}: '硫' CjkCompatibilityIdeographDashF9ce, /// \u{f9cf}: '紐' CjkCompatibilityIdeographDashF9cf, /// \u{f9d0}: '類' CjkCompatibilityIdeographDashF9d0, /// \u{f9d1}: '六' CjkCompatibilityIdeographDashF9d1, /// \u{f9d2}: '戮' CjkCompatibilityIdeographDashF9d2, /// \u{f9d3}: '陸' CjkCompatibilityIdeographDashF9d3, /// \u{f9d4}: '倫' CjkCompatibilityIdeographDashF9d4, /// \u{f9d5}: '崙' CjkCompatibilityIdeographDashF9d5, /// \u{f9d6}: '淪' CjkCompatibilityIdeographDashF9d6, /// \u{f9d7}: '輪' CjkCompatibilityIdeographDashF9d7, /// \u{f9d8}: '律' CjkCompatibilityIdeographDashF9d8, /// \u{f9d9}: '慄' CjkCompatibilityIdeographDashF9d9, /// \u{f9da}: '栗' CjkCompatibilityIdeographDashF9da, /// \u{f9db}: '率' CjkCompatibilityIdeographDashF9db, /// \u{f9dc}: '隆' CjkCompatibilityIdeographDashF9dc, /// \u{f9dd}: '利' CjkCompatibilityIdeographDashF9dd, /// \u{f9de}: '吏' CjkCompatibilityIdeographDashF9de, /// \u{f9df}: '履' CjkCompatibilityIdeographDashF9df, /// \u{f9e0}: '易' CjkCompatibilityIdeographDashF9e0, /// \u{f9e1}: '李' CjkCompatibilityIdeographDashF9e1, /// \u{f9e2}: '梨' CjkCompatibilityIdeographDashF9e2, /// \u{f9e3}: '泥' CjkCompatibilityIdeographDashF9e3, /// \u{f9e4}: '理' CjkCompatibilityIdeographDashF9e4, /// \u{f9e5}: '痢' CjkCompatibilityIdeographDashF9e5, /// \u{f9e6}: '罹' CjkCompatibilityIdeographDashF9e6, /// \u{f9e7}: '裏' CjkCompatibilityIdeographDashF9e7, /// \u{f9e8}: '裡' CjkCompatibilityIdeographDashF9e8, /// \u{f9e9}: '里' CjkCompatibilityIdeographDashF9e9, /// \u{f9ea}: '離' CjkCompatibilityIdeographDashF9ea, /// \u{f9eb}: '匿' CjkCompatibilityIdeographDashF9eb, /// \u{f9ec}: '溺' CjkCompatibilityIdeographDashF9ec, /// \u{f9ed}: '吝' CjkCompatibilityIdeographDashF9ed, /// \u{f9ee}: '燐' CjkCompatibilityIdeographDashF9ee, /// \u{f9ef}: '璘' CjkCompatibilityIdeographDashF9ef, /// \u{f9f0}: '藺' CjkCompatibilityIdeographDashF9f0, /// \u{f9f1}: '隣' CjkCompatibilityIdeographDashF9f1, /// \u{f9f2}: '鱗' CjkCompatibilityIdeographDashF9f2, /// \u{f9f3}: '麟' CjkCompatibilityIdeographDashF9f3, /// \u{f9f4}: '林' CjkCompatibilityIdeographDashF9f4, /// \u{f9f5}: '淋' CjkCompatibilityIdeographDashF9f5, /// \u{f9f6}: '臨' CjkCompatibilityIdeographDashF9f6, /// \u{f9f7}: '立' CjkCompatibilityIdeographDashF9f7, /// \u{f9f8}: '笠' CjkCompatibilityIdeographDashF9f8, /// \u{f9f9}: '粒' CjkCompatibilityIdeographDashF9f9, /// \u{f9fa}: '狀' CjkCompatibilityIdeographDashF9fa, /// \u{f9fb}: '炙' CjkCompatibilityIdeographDashF9fb, /// \u{f9fc}: '識' CjkCompatibilityIdeographDashF9fc, /// \u{f9fd}: '什' CjkCompatibilityIdeographDashF9fd, /// \u{f9fe}: '茶' CjkCompatibilityIdeographDashF9fe, /// \u{f9ff}: '刺' CjkCompatibilityIdeographDashF9ff, /// \u{fa00}: '切' CjkCompatibilityIdeographDashFa00, /// \u{fa01}: '度' CjkCompatibilityIdeographDashFa01, /// \u{fa02}: '拓' CjkCompatibilityIdeographDashFa02, /// \u{fa03}: '糖' CjkCompatibilityIdeographDashFa03, /// \u{fa04}: '宅' CjkCompatibilityIdeographDashFa04, /// \u{fa05}: '洞' CjkCompatibilityIdeographDashFa05, /// \u{fa06}: '暴' CjkCompatibilityIdeographDashFa06, /// \u{fa07}: '輻' CjkCompatibilityIdeographDashFa07, /// \u{fa08}: '行' CjkCompatibilityIdeographDashFa08, /// \u{fa09}: '降' CjkCompatibilityIdeographDashFa09, /// \u{fa0a}: '見' CjkCompatibilityIdeographDashFa0a, /// \u{fa0b}: '廓' CjkCompatibilityIdeographDashFa0b, /// \u{fa0c}: '兀' CjkCompatibilityIdeographDashFa0c, /// \u{fa0d}: '嗀' CjkCompatibilityIdeographDashFa0d, /// \u{fa0e}: '﨎' CjkCompatibilityIdeographDashFa0e, /// \u{fa0f}: '﨏' CjkCompatibilityIdeographDashFa0f, /// \u{fa10}: '塚' CjkCompatibilityIdeographDashFa10, /// \u{fa11}: '﨑' CjkCompatibilityIdeographDashFa11, /// \u{fa12}: '晴' CjkCompatibilityIdeographDashFa12, /// \u{fa13}: '﨓' CjkCompatibilityIdeographDashFa13, /// \u{fa14}: '﨔' CjkCompatibilityIdeographDashFa14, /// \u{fa15}: '凞' CjkCompatibilityIdeographDashFa15, /// \u{fa16}: '猪' CjkCompatibilityIdeographDashFa16, /// \u{fa17}: '益' CjkCompatibilityIdeographDashFa17, /// \u{fa18}: '礼' CjkCompatibilityIdeographDashFa18, /// \u{fa19}: '神' CjkCompatibilityIdeographDashFa19, /// \u{fa1a}: '祥' CjkCompatibilityIdeographDashFa1a, /// \u{fa1b}: '福' CjkCompatibilityIdeographDashFa1b, /// \u{fa1c}: '靖' CjkCompatibilityIdeographDashFa1c, /// \u{fa1d}: '精' CjkCompatibilityIdeographDashFa1d, /// \u{fa1e}: '羽' CjkCompatibilityIdeographDashFa1e, /// \u{fa1f}: '﨟' CjkCompatibilityIdeographDashFa1f, /// \u{fa20}: '蘒' CjkCompatibilityIdeographDashFa20, /// \u{fa21}: '﨡' CjkCompatibilityIdeographDashFa21, /// \u{fa22}: '諸' CjkCompatibilityIdeographDashFa22, /// \u{fa23}: '﨣' CjkCompatibilityIdeographDashFa23, /// \u{fa24}: '﨤' CjkCompatibilityIdeographDashFa24, /// \u{fa25}: '逸' CjkCompatibilityIdeographDashFa25, /// \u{fa26}: '都' CjkCompatibilityIdeographDashFa26, /// \u{fa27}: '﨧' CjkCompatibilityIdeographDashFa27, /// \u{fa28}: '﨨' CjkCompatibilityIdeographDashFa28, /// \u{fa29}: '﨩' CjkCompatibilityIdeographDashFa29, /// \u{fa2a}: '飯' CjkCompatibilityIdeographDashFa2a, /// \u{fa2b}: '飼' CjkCompatibilityIdeographDashFa2b, /// \u{fa2c}: '館' CjkCompatibilityIdeographDashFa2c, /// \u{fa2d}: '鶴' CjkCompatibilityIdeographDashFa2d, /// \u{fa2e}: '郞' CjkCompatibilityIdeographDashFa2e, /// \u{fa2f}: '隷' CjkCompatibilityIdeographDashFa2f, /// \u{fa30}: '侮' CjkCompatibilityIdeographDashFa30, /// \u{fa31}: '僧' CjkCompatibilityIdeographDashFa31, /// \u{fa32}: '免' CjkCompatibilityIdeographDashFa32, /// \u{fa33}: '勉' CjkCompatibilityIdeographDashFa33, /// \u{fa34}: '勤' CjkCompatibilityIdeographDashFa34, /// \u{fa35}: '卑' CjkCompatibilityIdeographDashFa35, /// \u{fa36}: '喝' CjkCompatibilityIdeographDashFa36, /// \u{fa37}: '嘆' CjkCompatibilityIdeographDashFa37, /// \u{fa38}: '器' CjkCompatibilityIdeographDashFa38, /// \u{fa39}: '塀' CjkCompatibilityIdeographDashFa39, /// \u{fa3a}: '墨' CjkCompatibilityIdeographDashFa3a, /// \u{fa3b}: '層' CjkCompatibilityIdeographDashFa3b, /// \u{fa3c}: '屮' CjkCompatibilityIdeographDashFa3c, /// \u{fa3d}: '悔' CjkCompatibilityIdeographDashFa3d, /// \u{fa3e}: '慨' CjkCompatibilityIdeographDashFa3e, /// \u{fa3f}: '憎' CjkCompatibilityIdeographDashFa3f, /// \u{fa40}: '懲' CjkCompatibilityIdeographDashFa40, /// \u{fa41}: '敏' CjkCompatibilityIdeographDashFa41, /// \u{fa42}: '既' CjkCompatibilityIdeographDashFa42, /// \u{fa43}: '暑' CjkCompatibilityIdeographDashFa43, /// \u{fa44}: '梅' CjkCompatibilityIdeographDashFa44, /// \u{fa45}: '海' CjkCompatibilityIdeographDashFa45, /// \u{fa46}: '渚' CjkCompatibilityIdeographDashFa46, /// \u{fa47}: '漢' CjkCompatibilityIdeographDashFa47, /// \u{fa48}: '煮' CjkCompatibilityIdeographDashFa48, /// \u{fa49}: '爫' CjkCompatibilityIdeographDashFa49, /// \u{fa4a}: '琢' CjkCompatibilityIdeographDashFa4a, /// \u{fa4b}: '碑' CjkCompatibilityIdeographDashFa4b, /// \u{fa4c}: '社' CjkCompatibilityIdeographDashFa4c, /// \u{fa4d}: '祉' CjkCompatibilityIdeographDashFa4d, /// \u{fa4e}: '祈' CjkCompatibilityIdeographDashFa4e, /// \u{fa4f}: '祐' CjkCompatibilityIdeographDashFa4f, /// \u{fa50}: '祖' CjkCompatibilityIdeographDashFa50, /// \u{fa51}: '祝' CjkCompatibilityIdeographDashFa51, /// \u{fa52}: '禍' CjkCompatibilityIdeographDashFa52, /// \u{fa53}: '禎' CjkCompatibilityIdeographDashFa53, /// \u{fa54}: '穀' CjkCompatibilityIdeographDashFa54, /// \u{fa55}: '突' CjkCompatibilityIdeographDashFa55, /// \u{fa56}: '節' CjkCompatibilityIdeographDashFa56, /// \u{fa57}: '練' CjkCompatibilityIdeographDashFa57, /// \u{fa58}: '縉' CjkCompatibilityIdeographDashFa58, /// \u{fa59}: '繁' CjkCompatibilityIdeographDashFa59, /// \u{fa5a}: '署' CjkCompatibilityIdeographDashFa5a, /// \u{fa5b}: '者' CjkCompatibilityIdeographDashFa5b, /// \u{fa5c}: '臭' CjkCompatibilityIdeographDashFa5c, /// \u{fa5d}: '艹' CjkCompatibilityIdeographDashFa5d, /// \u{fa5e}: '艹' CjkCompatibilityIdeographDashFa5e, /// \u{fa5f}: '著' CjkCompatibilityIdeographDashFa5f, /// \u{fa60}: '褐' CjkCompatibilityIdeographDashFa60, /// \u{fa61}: '視' CjkCompatibilityIdeographDashFa61, /// \u{fa62}: '謁' CjkCompatibilityIdeographDashFa62, /// \u{fa63}: '謹' CjkCompatibilityIdeographDashFa63, /// \u{fa64}: '賓' CjkCompatibilityIdeographDashFa64, /// \u{fa65}: '贈' CjkCompatibilityIdeographDashFa65, /// \u{fa66}: '辶' CjkCompatibilityIdeographDashFa66, /// \u{fa67}: '逸' CjkCompatibilityIdeographDashFa67, /// \u{fa68}: '難' CjkCompatibilityIdeographDashFa68, /// \u{fa69}: '響' CjkCompatibilityIdeographDashFa69, /// \u{fa6a}: '頻' CjkCompatibilityIdeographDashFa6a, /// \u{fa6b}: '恵' CjkCompatibilityIdeographDashFa6b, /// \u{fa6c}: '𤋮' CjkCompatibilityIdeographDashFa6c, /// \u{fa6d}: '舘' CjkCompatibilityIdeographDashFa6d, /// \u{fa70}: '並' CjkCompatibilityIdeographDashFa70, /// \u{fa71}: '况' CjkCompatibilityIdeographDashFa71, /// \u{fa72}: '全' CjkCompatibilityIdeographDashFa72, /// \u{fa73}: '侀' CjkCompatibilityIdeographDashFa73, /// \u{fa74}: '充' CjkCompatibilityIdeographDashFa74, /// \u{fa75}: '冀' CjkCompatibilityIdeographDashFa75, /// \u{fa76}: '勇' CjkCompatibilityIdeographDashFa76, /// \u{fa77}: '勺' CjkCompatibilityIdeographDashFa77, /// \u{fa78}: '喝' CjkCompatibilityIdeographDashFa78, /// \u{fa79}: '啕' CjkCompatibilityIdeographDashFa79, /// \u{fa7a}: '喙' CjkCompatibilityIdeographDashFa7a, /// \u{fa7b}: '嗢' CjkCompatibilityIdeographDashFa7b, /// \u{fa7c}: '塚' CjkCompatibilityIdeographDashFa7c, /// \u{fa7d}: '墳' CjkCompatibilityIdeographDashFa7d, /// \u{fa7e}: '奄' CjkCompatibilityIdeographDashFa7e, /// \u{fa7f}: '奔' CjkCompatibilityIdeographDashFa7f, /// \u{fa80}: '婢' CjkCompatibilityIdeographDashFa80, /// \u{fa81}: '嬨' CjkCompatibilityIdeographDashFa81, /// \u{fa82}: '廒' CjkCompatibilityIdeographDashFa82, /// \u{fa83}: '廙' CjkCompatibilityIdeographDashFa83, /// \u{fa84}: '彩' CjkCompatibilityIdeographDashFa84, /// \u{fa85}: '徭' CjkCompatibilityIdeographDashFa85, /// \u{fa86}: '惘' CjkCompatibilityIdeographDashFa86, /// \u{fa87}: '慎' CjkCompatibilityIdeographDashFa87, /// \u{fa88}: '愈' CjkCompatibilityIdeographDashFa88, /// \u{fa89}: '憎' CjkCompatibilityIdeographDashFa89, /// \u{fa8a}: '慠' CjkCompatibilityIdeographDashFa8a, /// \u{fa8b}: '懲' CjkCompatibilityIdeographDashFa8b, /// \u{fa8c}: '戴' CjkCompatibilityIdeographDashFa8c, /// \u{fa8d}: '揄' CjkCompatibilityIdeographDashFa8d, /// \u{fa8e}: '搜' CjkCompatibilityIdeographDashFa8e, /// \u{fa8f}: '摒' CjkCompatibilityIdeographDashFa8f, /// \u{fa90}: '敖' CjkCompatibilityIdeographDashFa90, /// \u{fa91}: '晴' CjkCompatibilityIdeographDashFa91, /// \u{fa92}: '朗' CjkCompatibilityIdeographDashFa92, /// \u{fa93}: '望' CjkCompatibilityIdeographDashFa93, /// \u{fa94}: '杖' CjkCompatibilityIdeographDashFa94, /// \u{fa95}: '歹' CjkCompatibilityIdeographDashFa95, /// \u{fa96}: '殺' CjkCompatibilityIdeographDashFa96, /// \u{fa97}: '流' CjkCompatibilityIdeographDashFa97, /// \u{fa98}: '滛' CjkCompatibilityIdeographDashFa98, /// \u{fa99}: '滋' CjkCompatibilityIdeographDashFa99, /// \u{fa9a}: '漢' CjkCompatibilityIdeographDashFa9a, /// \u{fa9b}: '瀞' CjkCompatibilityIdeographDashFa9b, /// \u{fa9c}: '煮' CjkCompatibilityIdeographDashFa9c, /// \u{fa9d}: '瞧' CjkCompatibilityIdeographDashFa9d, /// \u{fa9e}: '爵' CjkCompatibilityIdeographDashFa9e, /// \u{fa9f}: '犯' CjkCompatibilityIdeographDashFa9f, /// \u{faa0}: '猪' CjkCompatibilityIdeographDashFaa0, /// \u{faa1}: '瑱' CjkCompatibilityIdeographDashFaa1, /// \u{faa2}: '甆' CjkCompatibilityIdeographDashFaa2, /// \u{faa3}: '画' CjkCompatibilityIdeographDashFaa3, /// \u{faa4}: '瘝' CjkCompatibilityIdeographDashFaa4, /// \u{faa5}: '瘟' CjkCompatibilityIdeographDashFaa5, /// \u{faa6}: '益' CjkCompatibilityIdeographDashFaa6, /// \u{faa7}: '盛' CjkCompatibilityIdeographDashFaa7, /// \u{faa8}: '直' CjkCompatibilityIdeographDashFaa8, /// \u{faa9}: '睊' CjkCompatibilityIdeographDashFaa9, /// \u{faaa}: '着' CjkCompatibilityIdeographDashFaaa, /// \u{faab}: '磌' CjkCompatibilityIdeographDashFaab, /// \u{faac}: '窱' CjkCompatibilityIdeographDashFaac, /// \u{faad}: '節' CjkCompatibilityIdeographDashFaad, /// \u{faae}: '类' CjkCompatibilityIdeographDashFaae, /// \u{faaf}: '絛' CjkCompatibilityIdeographDashFaaf, /// \u{fab0}: '練' CjkCompatibilityIdeographDashFab0, /// \u{fab1}: '缾' CjkCompatibilityIdeographDashFab1, /// \u{fab2}: '者' CjkCompatibilityIdeographDashFab2, /// \u{fab3}: '荒' CjkCompatibilityIdeographDashFab3, /// \u{fab4}: '華' CjkCompatibilityIdeographDashFab4, /// \u{fab5}: '蝹' CjkCompatibilityIdeographDashFab5, /// \u{fab6}: '襁' CjkCompatibilityIdeographDashFab6, /// \u{fab7}: '覆' CjkCompatibilityIdeographDashFab7, /// \u{fab8}: '視' CjkCompatibilityIdeographDashFab8, /// \u{fab9}: '調' CjkCompatibilityIdeographDashFab9, /// \u{faba}: '諸' CjkCompatibilityIdeographDashFaba, /// \u{fabb}: '請' CjkCompatibilityIdeographDashFabb, /// \u{fabc}: '謁' CjkCompatibilityIdeographDashFabc, /// \u{fabd}: '諾' CjkCompatibilityIdeographDashFabd, /// \u{fabe}: '諭' CjkCompatibilityIdeographDashFabe, /// \u{fabf}: '謹' CjkCompatibilityIdeographDashFabf, /// \u{fac0}: '變' CjkCompatibilityIdeographDashFac0, /// \u{fac1}: '贈' CjkCompatibilityIdeographDashFac1, /// \u{fac2}: '輸' CjkCompatibilityIdeographDashFac2, /// \u{fac3}: '遲' CjkCompatibilityIdeographDashFac3, /// \u{fac4}: '醙' CjkCompatibilityIdeographDashFac4, /// \u{fac5}: '鉶' CjkCompatibilityIdeographDashFac5, /// \u{fac6}: '陼' CjkCompatibilityIdeographDashFac6, /// \u{fac7}: '難' CjkCompatibilityIdeographDashFac7, /// \u{fac8}: '靖' CjkCompatibilityIdeographDashFac8, /// \u{fac9}: '韛' CjkCompatibilityIdeographDashFac9, /// \u{faca}: '響' CjkCompatibilityIdeographDashFaca, /// \u{facb}: '頋' CjkCompatibilityIdeographDashFacb, /// \u{facc}: '頻' CjkCompatibilityIdeographDashFacc, /// \u{facd}: '鬒' CjkCompatibilityIdeographDashFacd, /// \u{face}: '龜' CjkCompatibilityIdeographDashFace, /// \u{facf}: '𢡊' CjkCompatibilityIdeographDashFacf, /// \u{fad0}: '𢡄' CjkCompatibilityIdeographDashFad0, /// \u{fad1}: '𣏕' CjkCompatibilityIdeographDashFad1, /// \u{fad2}: '㮝' CjkCompatibilityIdeographDashFad2, /// \u{fad3}: '䀘' CjkCompatibilityIdeographDashFad3, /// \u{fad4}: '䀹' CjkCompatibilityIdeographDashFad4, /// \u{fad5}: '𥉉' CjkCompatibilityIdeographDashFad5, /// \u{fad6}: '𥳐' CjkCompatibilityIdeographDashFad6, /// \u{fad7}: '𧻓' CjkCompatibilityIdeographDashFad7, /// \u{fad8}: '齃' CjkCompatibilityIdeographDashFad8, /// \u{fad9}: '龎' CjkCompatibilityIdeographDashFad9, } impl Into<char> for CJKCompatibilityIdeographs { fn into(self) -> char { match self { CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF900 => '豈', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF901 => '更', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF902 => '車', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF903 => '賈', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF904 => '滑', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF905 => '串', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF906 => '句', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF907 => '龜', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF908 => '龜', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF909 => '契', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF90a => '金', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF90b => '喇', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF90c => '奈', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF90d => '懶', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF90e => '癩', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF90f => '羅', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF910 => '蘿', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF911 => '螺', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF912 => '裸', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF913 => '邏', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF914 => '樂', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF915 => '洛', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF916 => '烙', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF917 => '珞', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF918 => '落', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF919 => '酪', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF91a => '駱', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF91b => '亂', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF91c => '卵', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF91d => '欄', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF91e => '爛', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF91f => '蘭', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF920 => '鸞', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF921 => '嵐', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF922 => '濫', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF923 => '藍', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF924 => '襤', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF925 => '拉', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF926 => '臘', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF927 => '蠟', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF928 => '廊', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF929 => '朗', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF92a => '浪', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF92b => '狼', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF92c => '郎', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF92d => '來', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF92e => '冷', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF92f => '勞', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF930 => '擄', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF931 => '櫓', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF932 => '爐', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF933 => '盧', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF934 => '老', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF935 => '蘆', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF936 => '虜', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF937 => '路', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF938 => '露', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF939 => '魯', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF93a => '鷺', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF93b => '碌', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF93c => '祿', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF93d => '綠', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF93e => '菉', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF93f => '錄', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF940 => '鹿', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF941 => '論', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF942 => '壟', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF943 => '弄', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF944 => '籠', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF945 => '聾', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF946 => '牢', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF947 => '磊', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF948 => '賂', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF949 => '雷', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF94a => '壘', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF94b => '屢', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF94c => '樓', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF94d => '淚', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF94e => '漏', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF94f => '累', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF950 => '縷', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF951 => '陋', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF952 => '勒', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF953 => '肋', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF954 => '凜', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF955 => '凌', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF956 => '稜', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF957 => '綾', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF958 => '菱', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF959 => '陵', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF95a => '讀', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF95b => '拏', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF95c => '樂', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF95d => '諾', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF95e => '丹', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF95f => '寧', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF960 => '怒', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF961 => '率', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF962 => '異', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF963 => '北', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF964 => '磻', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF965 => '便', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF966 => '復', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF967 => '不', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF968 => '泌', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF969 => '數', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF96a => '索', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF96b => '參', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF96c => '塞', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF96d => '省', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF96e => '葉', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF96f => '說', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF970 => '殺', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF971 => '辰', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF972 => '沈', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF973 => '拾', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF974 => '若', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF975 => '掠', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF976 => '略', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF977 => '亮', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF978 => '兩', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF979 => '凉', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF97a => '梁', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF97b => '糧', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF97c => '良', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF97d => '諒', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF97e => '量', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF97f => '勵', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF980 => '呂', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF981 => '女', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF982 => '廬', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF983 => '旅', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF984 => '濾', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF985 => '礪', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF986 => '閭', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF987 => '驪', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF988 => '麗', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF989 => '黎', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF98a => '力', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF98b => '曆', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF98c => '歷', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF98d => '轢', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF98e => '年', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF98f => '憐', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF990 => '戀', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF991 => '撚', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF992 => '漣', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF993 => '煉', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF994 => '璉', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF995 => '秊', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF996 => '練', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF997 => '聯', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF998 => '輦', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF999 => '蓮', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF99a => '連', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF99b => '鍊', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF99c => '列', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF99d => '劣', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF99e => '咽', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF99f => '烈', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a0 => '裂', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a1 => '說', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a2 => '廉', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a3 => '念', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a4 => '捻', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a5 => '殮', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a6 => '簾', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a7 => '獵', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a8 => '令', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a9 => '囹', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9aa => '寧', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ab => '嶺', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ac => '怜', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ad => '玲', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ae => '瑩', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9af => '羚', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b0 => '聆', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b1 => '鈴', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b2 => '零', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b3 => '靈', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b4 => '領', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b5 => '例', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b6 => '禮', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b7 => '醴', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b8 => '隸', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b9 => '惡', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ba => '了', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9bb => '僚', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9bc => '寮', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9bd => '尿', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9be => '料', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9bf => '樂', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c0 => '燎', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c1 => '療', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c2 => '蓼', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c3 => '遼', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c4 => '龍', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c5 => '暈', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c6 => '阮', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c7 => '劉', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c8 => '杻', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c9 => '柳', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ca => '流', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9cb => '溜', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9cc => '琉', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9cd => '留', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ce => '硫', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9cf => '紐', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d0 => '類', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d1 => '六', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d2 => '戮', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d3 => '陸', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d4 => '倫', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d5 => '崙', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d6 => '淪', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d7 => '輪', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d8 => '律', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d9 => '慄', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9da => '栗', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9db => '率', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9dc => '隆', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9dd => '利', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9de => '吏', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9df => '履', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e0 => '易', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e1 => '李', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e2 => '梨', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e3 => '泥', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e4 => '理', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e5 => '痢', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e6 => '罹', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e7 => '裏', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e8 => '裡', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e9 => '里', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ea => '離', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9eb => '匿', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ec => '溺', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ed => '吝', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ee => '燐', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ef => '璘', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f0 => '藺', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f1 => '隣', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f2 => '鱗', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f3 => '麟', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f4 => '林', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f5 => '淋', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f6 => '臨', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f7 => '立', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f8 => '笠', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f9 => '粒', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9fa => '狀', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9fb => '炙', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9fc => '識', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9fd => '什', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9fe => '茶', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ff => '刺', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa00 => '切', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa01 => '度', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa02 => '拓', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa03 => '糖', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa04 => '宅', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa05 => '洞', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa06 => '暴', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa07 => '輻', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa08 => '行', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa09 => '降', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa0a => '見', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa0b => '廓', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa0c => '兀', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa0d => '嗀', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa0e => '﨎', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa0f => '﨏', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa10 => '塚', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa11 => '﨑', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa12 => '晴', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa13 => '﨓', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa14 => '﨔', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa15 => '凞', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa16 => '猪', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa17 => '益', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa18 => '礼', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa19 => '神', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa1a => '祥', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa1b => '福', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa1c => '靖', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa1d => '精', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa1e => '羽', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa1f => '﨟', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa20 => '蘒', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa21 => '﨡', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa22 => '諸', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa23 => '﨣', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa24 => '﨤', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa25 => '逸', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa26 => '都', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa27 => '﨧', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa28 => '﨨', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa29 => '﨩', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa2a => '飯', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa2b => '飼', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa2c => '館', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa2d => '鶴', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa2e => '郞', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa2f => '隷', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa30 => '侮', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa31 => '僧', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa32 => '免', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa33 => '勉', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa34 => '勤', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa35 => '卑', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa36 => '喝', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa37 => '嘆', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa38 => '器', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa39 => '塀', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa3a => '墨', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa3b => '層', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa3c => '屮', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa3d => '悔', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa3e => '慨', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa3f => '憎', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa40 => '懲', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa41 => '敏', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa42 => '既', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa43 => '暑', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa44 => '梅', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa45 => '海', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa46 => '渚', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa47 => '漢', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa48 => '煮', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa49 => '爫', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa4a => '琢', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa4b => '碑', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa4c => '社', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa4d => '祉', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa4e => '祈', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa4f => '祐', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa50 => '祖', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa51 => '祝', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa52 => '禍', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa53 => '禎', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa54 => '穀', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa55 => '突', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa56 => '節', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa57 => '練', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa58 => '縉', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa59 => '繁', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa5a => '署', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa5b => '者', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa5c => '臭', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa5d => '艹', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa5e => '艹', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa5f => '著', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa60 => '褐', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa61 => '視', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa62 => '謁', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa63 => '謹', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa64 => '賓', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa65 => '贈', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa66 => '辶', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa67 => '逸', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa68 => '難', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa69 => '響', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa6a => '頻', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa6b => '恵', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa6c => '𤋮', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa6d => '舘', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa70 => '並', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa71 => '况', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa72 => '全', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa73 => '侀', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa74 => '充', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa75 => '冀', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa76 => '勇', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa77 => '勺', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa78 => '喝', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa79 => '啕', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa7a => '喙', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa7b => '嗢', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa7c => '塚', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa7d => '墳', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa7e => '奄', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa7f => '奔', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa80 => '婢', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa81 => '嬨', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa82 => '廒', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa83 => '廙', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa84 => '彩', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa85 => '徭', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa86 => '惘', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa87 => '慎', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa88 => '愈', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa89 => '憎', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa8a => '慠', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa8b => '懲', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa8c => '戴', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa8d => '揄', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa8e => '搜', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa8f => '摒', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa90 => '敖', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa91 => '晴', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa92 => '朗', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa93 => '望', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa94 => '杖', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa95 => '歹', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa96 => '殺', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa97 => '流', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa98 => '滛', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa99 => '滋', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa9a => '漢', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa9b => '瀞', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa9c => '煮', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa9d => '瞧', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa9e => '爵', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa9f => '犯', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa0 => '猪', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa1 => '瑱', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa2 => '甆', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa3 => '画', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa4 => '瘝', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa5 => '瘟', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa6 => '益', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa7 => '盛', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa8 => '直', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa9 => '睊', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaaa => '着', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaab => '磌', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaac => '窱', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaad => '節', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaae => '类', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaaf => '絛', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab0 => '練', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab1 => '缾', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab2 => '者', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab3 => '荒', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab4 => '華', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab5 => '蝹', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab6 => '襁', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab7 => '覆', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab8 => '視', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab9 => '調', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaba => '諸', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFabb => '請', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFabc => '謁', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFabd => '諾', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFabe => '諭', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFabf => '謹', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac0 => '變', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac1 => '贈', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac2 => '輸', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac3 => '遲', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac4 => '醙', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac5 => '鉶', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac6 => '陼', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac7 => '難', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac8 => '靖', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac9 => '韛', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaca => '響', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFacb => '頋', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFacc => '頻', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFacd => '鬒', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFace => '龜', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFacf => '𢡊', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad0 => '𢡄', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad1 => '𣏕', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad2 => '㮝', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad3 => '䀘', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad4 => '䀹', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad5 => '𥉉', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad6 => '𥳐', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad7 => '𧻓', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad8 => '齃', CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad9 => '龎', } } } impl std::convert::TryFrom<char> for CJKCompatibilityIdeographs { type Error = (); fn try_from(c: char) -> Result<Self, Self::Error> { match c { '豈' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF900), '更' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF901), '車' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF902), '賈' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF903), '滑' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF904), '串' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF905), '句' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF906), '龜' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF907), '龜' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF908), '契' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF909), '金' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF90a), '喇' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF90b), '奈' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF90c), '懶' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF90d), '癩' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF90e), '羅' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF90f), '蘿' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF910), '螺' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF911), '裸' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF912), '邏' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF913), '樂' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF914), '洛' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF915), '烙' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF916), '珞' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF917), '落' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF918), '酪' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF919), '駱' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF91a), '亂' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF91b), '卵' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF91c), '欄' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF91d), '爛' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF91e), '蘭' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF91f), '鸞' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF920), '嵐' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF921), '濫' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF922), '藍' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF923), '襤' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF924), '拉' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF925), '臘' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF926), '蠟' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF927), '廊' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF928), '朗' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF929), '浪' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF92a), '狼' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF92b), '郎' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF92c), '來' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF92d), '冷' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF92e), '勞' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF92f), '擄' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF930), '櫓' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF931), '爐' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF932), '盧' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF933), '老' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF934), '蘆' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF935), '虜' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF936), '路' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF937), '露' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF938), '魯' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF939), '鷺' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF93a), '碌' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF93b), '祿' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF93c), '綠' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF93d), '菉' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF93e), '錄' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF93f), '鹿' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF940), '論' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF941), '壟' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF942), '弄' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF943), '籠' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF944), '聾' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF945), '牢' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF946), '磊' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF947), '賂' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF948), '雷' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF949), '壘' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF94a), '屢' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF94b), '樓' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF94c), '淚' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF94d), '漏' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF94e), '累' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF94f), '縷' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF950), '陋' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF951), '勒' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF952), '肋' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF953), '凜' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF954), '凌' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF955), '稜' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF956), '綾' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF957), '菱' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF958), '陵' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF959), '讀' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF95a), '拏' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF95b), '樂' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF95c), '諾' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF95d), '丹' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF95e), '寧' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF95f), '怒' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF960), '率' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF961), '異' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF962), '北' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF963), '磻' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF964), '便' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF965), '復' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF966), '不' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF967), '泌' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF968), '數' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF969), '索' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF96a), '參' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF96b), '塞' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF96c), '省' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF96d), '葉' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF96e), '說' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF96f), '殺' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF970), '辰' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF971), '沈' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF972), '拾' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF973), '若' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF974), '掠' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF975), '略' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF976), '亮' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF977), '兩' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF978), '凉' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF979), '梁' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF97a), '糧' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF97b), '良' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF97c), '諒' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF97d), '量' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF97e), '勵' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF97f), '呂' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF980), '女' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF981), '廬' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF982), '旅' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF983), '濾' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF984), '礪' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF985), '閭' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF986), '驪' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF987), '麗' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF988), '黎' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF989), '力' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF98a), '曆' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF98b), '歷' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF98c), '轢' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF98d), '年' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF98e), '憐' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF98f), '戀' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF990), '撚' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF991), '漣' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF992), '煉' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF993), '璉' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF994), '秊' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF995), '練' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF996), '聯' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF997), '輦' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF998), '蓮' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF999), '連' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF99a), '鍊' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF99b), '列' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF99c), '劣' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF99d), '咽' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF99e), '烈' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF99f), '裂' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a0), '說' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a1), '廉' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a2), '念' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a3), '捻' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a4), '殮' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a5), '簾' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a6), '獵' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a7), '令' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a8), '囹' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9a9), '寧' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9aa), '嶺' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ab), '怜' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ac), '玲' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ad), '瑩' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ae), '羚' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9af), '聆' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b0), '鈴' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b1), '零' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b2), '靈' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b3), '領' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b4), '例' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b5), '禮' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b6), '醴' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b7), '隸' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b8), '惡' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9b9), '了' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ba), '僚' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9bb), '寮' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9bc), '尿' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9bd), '料' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9be), '樂' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9bf), '燎' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c0), '療' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c1), '蓼' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c2), '遼' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c3), '龍' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c4), '暈' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c5), '阮' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c6), '劉' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c7), '杻' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c8), '柳' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9c9), '流' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ca), '溜' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9cb), '琉' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9cc), '留' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9cd), '硫' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ce), '紐' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9cf), '類' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d0), '六' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d1), '戮' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d2), '陸' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d3), '倫' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d4), '崙' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d5), '淪' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d6), '輪' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d7), '律' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d8), '慄' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9d9), '栗' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9da), '率' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9db), '隆' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9dc), '利' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9dd), '吏' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9de), '履' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9df), '易' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e0), '李' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e1), '梨' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e2), '泥' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e3), '理' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e4), '痢' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e5), '罹' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e6), '裏' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e7), '裡' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e8), '里' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9e9), '離' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ea), '匿' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9eb), '溺' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ec), '吝' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ed), '燐' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ee), '璘' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ef), '藺' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f0), '隣' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f1), '鱗' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f2), '麟' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f3), '林' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f4), '淋' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f5), '臨' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f6), '立' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f7), '笠' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f8), '粒' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9f9), '狀' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9fa), '炙' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9fb), '識' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9fc), '什' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9fd), '茶' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9fe), '刺' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF9ff), '切' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa00), '度' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa01), '拓' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa02), '糖' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa03), '宅' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa04), '洞' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa05), '暴' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa06), '輻' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa07), '行' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa08), '降' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa09), '見' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa0a), '廓' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa0b), '兀' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa0c), '嗀' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa0d), '﨎' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa0e), '﨏' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa0f), '塚' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa10), '﨑' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa11), '晴' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa12), '﨓' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa13), '﨔' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa14), '凞' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa15), '猪' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa16), '益' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa17), '礼' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa18), '神' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa19), '祥' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa1a), '福' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa1b), '靖' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa1c), '精' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa1d), '羽' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa1e), '﨟' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa1f), '蘒' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa20), '﨡' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa21), '諸' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa22), '﨣' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa23), '﨤' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa24), '逸' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa25), '都' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa26), '﨧' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa27), '﨨' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa28), '﨩' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa29), '飯' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa2a), '飼' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa2b), '館' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa2c), '鶴' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa2d), '郞' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa2e), '隷' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa2f), '侮' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa30), '僧' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa31), '免' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa32), '勉' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa33), '勤' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa34), '卑' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa35), '喝' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa36), '嘆' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa37), '器' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa38), '塀' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa39), '墨' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa3a), '層' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa3b), '屮' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa3c), '悔' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa3d), '慨' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa3e), '憎' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa3f), '懲' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa40), '敏' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa41), '既' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa42), '暑' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa43), '梅' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa44), '海' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa45), '渚' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa46), '漢' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa47), '煮' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa48), '爫' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa49), '琢' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa4a), '碑' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa4b), '社' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa4c), '祉' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa4d), '祈' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa4e), '祐' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa4f), '祖' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa50), '祝' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa51), '禍' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa52), '禎' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa53), '穀' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa54), '突' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa55), '節' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa56), '練' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa57), '縉' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa58), '繁' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa59), '署' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa5a), '者' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa5b), '臭' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa5c), '艹' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa5d), '艹' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa5e), '著' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa5f), '褐' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa60), '視' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa61), '謁' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa62), '謹' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa63), '賓' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa64), '贈' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa65), '辶' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa66), '逸' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa67), '難' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa68), '響' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa69), '頻' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa6a), '恵' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa6b), '𤋮' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa6c), '舘' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa6d), '並' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa70), '况' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa71), '全' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa72), '侀' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa73), '充' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa74), '冀' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa75), '勇' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa76), '勺' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa77), '喝' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa78), '啕' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa79), '喙' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa7a), '嗢' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa7b), '塚' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa7c), '墳' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa7d), '奄' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa7e), '奔' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa7f), '婢' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa80), '嬨' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa81), '廒' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa82), '廙' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa83), '彩' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa84), '徭' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa85), '惘' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa86), '慎' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa87), '愈' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa88), '憎' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa89), '慠' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa8a), '懲' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa8b), '戴' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa8c), '揄' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa8d), '搜' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa8e), '摒' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa8f), '敖' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa90), '晴' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa91), '朗' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa92), '望' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa93), '杖' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa94), '歹' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa95), '殺' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa96), '流' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa97), '滛' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa98), '滋' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa99), '漢' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa9a), '瀞' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa9b), '煮' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa9c), '瞧' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa9d), '爵' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa9e), '犯' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFa9f), '猪' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa0), '瑱' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa1), '甆' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa2), '画' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa3), '瘝' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa4), '瘟' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa5), '益' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa6), '盛' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa7), '直' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa8), '睊' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaa9), '着' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaaa), '磌' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaab), '窱' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaac), '節' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaad), '类' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaae), '絛' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaaf), '練' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab0), '缾' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab1), '者' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab2), '荒' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab3), '華' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab4), '蝹' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab5), '襁' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab6), '覆' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab7), '視' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab8), '調' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFab9), '諸' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaba), '請' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFabb), '謁' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFabc), '諾' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFabd), '諭' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFabe), '謹' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFabf), '變' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac0), '贈' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac1), '輸' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac2), '遲' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac3), '醙' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac4), '鉶' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac5), '陼' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac6), '難' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac7), '靖' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac8), '韛' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFac9), '響' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFaca), '頋' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFacb), '頻' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFacc), '鬒' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFacd), '龜' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFace), '𢡊' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFacf), '𢡄' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad0), '𣏕' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad1), '㮝' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad2), '䀘' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad3), '䀹' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad4), '𥉉' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad5), '𥳐' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad6), '𧻓' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad7), '齃' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad8), '龎' => Ok(CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashFad9), _ => Err(()), } } } impl Into<u32> for CJKCompatibilityIdeographs { fn into(self) -> u32 { let c: char = self.into(); let hex = c .escape_unicode() .to_string() .replace("\\u{", "") .replace("}", ""); u32::from_str_radix(&hex, 16).unwrap() } } impl std::convert::TryFrom<u32> for CJKCompatibilityIdeographs { type Error = (); fn try_from(u: u32) -> Result<Self, Self::Error> { if let Ok(c) = char::try_from(u) { Self::try_from(c) } else { Err(()) } } } impl Iterator for CJKCompatibilityIdeographs { type Item = Self; fn next(&mut self) -> Option<Self> { let index: u32 = (*self).into(); use std::convert::TryFrom; Self::try_from(index + 1).ok() } } impl CJKCompatibilityIdeographs { /// The character with the lowest index in this unicode block pub fn new() -> Self { CJKCompatibilityIdeographs::CjkCompatibilityIdeographDashF900 } /// The character's name, in sentence case pub fn name(&self) -> String { let s = std::format!("CJKCompatibilityIdeographs{:#?}", self); string_morph::to_sentence_case(&s) } }
//! Test and font stuff, it will be cleaned up later. Don't look here, it won't help you. use std::borrow::Cow; use std::collections::HashMap; use std::io::Read; use rusttype::{Rect, Point}; use glium::backend::Facade; #[derive(Debug)] pub enum Error { /// A glyph for this character is not present in font. NoGlyph(char), } pub struct FontTexture { } #[derive(Copy, Clone, Debug)] pub struct CharacterInfos { pub(crate) tex_coords: (f32, f32), pub(crate) tex_size: (f32, f32), pub(crate) size: (f32, f32), pub(crate) height_over_line: f32, pub(crate) left_padding: f32, pub(crate) right_padding: f32, } pub(crate) struct TextureData { data: Vec<f32>, pub(crate) width: u32, pub(crate) height: u32, } impl<'a> glium::texture::Texture2dDataSource<'a> for &'a TextureData { type Data = f32; fn into_raw(self) -> glium::texture::RawImage2d<'a, f32> { glium::texture::RawImage2d { data: Cow::Borrowed(&self.data), width: self.width, height: self.height, format: glium::texture::ClientFormat::F32, } } } impl FontTexture { /// Vec<char> of complete ASCII range (from 0 to 255 bytes) pub fn ascii_character_list() -> Vec<char> { (0 .. 255).filter_map(|c| ::std::char::from_u32(c)).collect() } /// Creates a new texture representing a font stored in a `FontTexture`. /// This function is very expensive as it needs to rasterize font into a /// texture. Complexity grows as `font_size**2 * characters_list.len()`. /// **Avoid rasterizing everything at once as it will be slow and end up in /// out of memory abort.** pub fn new<R, F, I>(_facade: &F, font: R, font_size: u32, characters_list: I) -> Result<(glium::texture::RawImage2d<f32>, HashMap<char, CharacterInfos>), Error> where R: Read, F: Facade, I: IntoIterator<Item=char> { // building the freetype face object let font: Vec<u8> = font.bytes().map(|c| c.unwrap()).collect(); let collection = ::rusttype::FontCollection::from_bytes(&font[..]); let font = collection.into_font().unwrap(); // building the infos let (texture_data, chr_infos) = build_font_image(font, characters_list.into_iter(), font_size)?; // we load the texture in the displ //texture_data.data.iter().for_each(|x| if *x > 0.1 { println!("{}", x) }); Ok(( glium::texture::RawImage2d { data: Cow::Owned(texture_data.data), width: texture_data.width, height: texture_data.height, format: glium::texture::ClientFormat::F32, }, chr_infos )) } } fn build_font_image<I>(font: rusttype::Font, characters_list: I, font_size: u32) -> Result<(TextureData, HashMap<char, CharacterInfos>), Error> where I: Iterator<Item=char> { use std::iter; // a margin around each character to prevent artifacts const MARGIN: u32 = 10; // glyph size for characters not presented in font. let invalid_character_width = font_size / 2; let size_estimation = characters_list.size_hint().1.unwrap_or(0); // this variable will store the texture data // we set an arbitrary capacity that we think will match what we will need let mut texture_data: Vec<f32> = Vec::with_capacity( size_estimation * font_size as usize * font_size as usize ); // the width is chosen more or less arbitrarily, because we can store // everything as long as the texture is at least as wide as the widest // character we just try to estimate a width so that width ~= height let texture_width = get_nearest_po2(std::cmp::max(font_size * 2 as u32, ((((size_estimation as u32) * font_size * font_size) as f32).sqrt()) as u32)); // we store the position of the "cursor" in the destination texture // this cursor points to the top-left pixel of the next character to write on the texture let mut cursor_offset = (0u32, 0u32); // number of rows to skip at next carriage return let mut rows_to_skip = 0u32; // now looping through the list of characters, filling the texture and returning the informations let em_pixels = font_size as f32; let characters_infos = characters_list.map(|character| { struct Bitmap { rows : i32, width : i32, buffer : Vec<u8> } // loading wanted glyph in the font face // hope scale will set the right pixel size let scaled_glyph = font.glyph(character) .ok_or_else(|| Error::NoGlyph(character))? .scaled(::rusttype::Scale {x : font_size as f32, y : font_size as f32 }); let h_metrics = scaled_glyph.h_metrics(); let glyph = scaled_glyph .positioned(::rusttype::Point {x : 0.0, y : 0.0 }); let bb = glyph.pixel_bounding_box(); // if no bounding box - we suppose that its invalid character but want it to be draw as empty quad let bb = if let Some(bb) = bb { bb } else { Rect { min: Point {x: 0, y: 0}, max: Point {x: invalid_character_width as i32, y: 0} } }; let mut buffer = vec![0; (bb.height() * bb.width()) as usize]; glyph.draw(|x, y, v| { let x = x; let y = y; buffer[(y * bb.width() as u32 + x) as usize] = (v * 255.0) as u8; }); let bitmap : Bitmap = Bitmap { rows : bb.height(), width : bb.width(), buffer : buffer }; // adding a left margin before our character to prevent artifacts cursor_offset.0 += MARGIN; // carriage return our cursor if we don't have enough room to write the next caracter // we add a margin to prevent artifacts if cursor_offset.0 + (bitmap.width as u32) + MARGIN >= texture_width { assert!(bitmap.width as u32 <= texture_width); // if this fails, we should increase texture_width cursor_offset.0 = 0; cursor_offset.1 += rows_to_skip; rows_to_skip = 0; } // if the texture data buffer has not enough lines, adding some if rows_to_skip < MARGIN + bitmap.rows as u32 { let diff = MARGIN + (bitmap.rows as u32) - rows_to_skip; rows_to_skip = MARGIN + bitmap.rows as u32; texture_data.extend(iter::repeat(0.0).take((diff * texture_width) as usize)); } // copying the data to the texture let offset_x_before_copy = cursor_offset.0; if bitmap.rows >= 1 { let destination = &mut texture_data[(cursor_offset.0 + cursor_offset.1 * texture_width) as usize ..]; let source = &bitmap.buffer; //ylet source = std::slice::from_raw_parts(source, destination.len()); for y in 0 .. bitmap.rows as u32 { let source = &source[(y * bitmap.width as u32) as usize ..]; let destination = &mut destination[(y * texture_width) as usize ..]; for x in 0 .. bitmap.width { // the values in source are bytes between 0 and 255, but we want floats between 0 and 1 let val: u8 = *source.get(x as usize).unwrap(); let val = (val as f32) / (std::u8::MAX as f32); let dest = destination.get_mut(x as usize).unwrap(); *dest = val; } } cursor_offset.0 += bitmap.width as u32; debug_assert!(cursor_offset.0 <= texture_width); } // filling infos about that character // tex_size and tex_coords are in pixels for the moment ; they will be divided // by the texture dimensions later Ok((character, CharacterInfos { tex_size: (bitmap.width as f32, bitmap.rows as f32), tex_coords: (offset_x_before_copy as f32, cursor_offset.1 as f32), size: (bitmap.width as f32, bitmap.rows as f32), left_padding: h_metrics.left_side_bearing as f32, right_padding: (h_metrics.advance_width - bitmap.width as f32 - h_metrics.left_side_bearing as f32) as f32 / 64.0, height_over_line: -bb.min.y as f32, })) }).collect::<Result<Vec<_>, Error>>()?; // adding blank lines at the end until the height of the texture is a power of two { let current_height = texture_data.len() as u32 / texture_width; let requested_height = get_nearest_po2(current_height); texture_data.extend(iter::repeat(0.0).take((texture_width * (requested_height - current_height)) as usize)); } // now our texture is finished // we know its final dimensions, so we can divide all the pixels values into (0,1) range assert!((texture_data.len() as u32 % texture_width) == 0); let texture_height = (texture_data.len() as u32 / texture_width) as f32; let float_texture_width = texture_width as f32; let mut characters_infos = characters_infos.into_iter().map(|mut chr| { chr.1.tex_size.0 /= float_texture_width; chr.1.tex_size.1 /= texture_height; chr.1.tex_coords.0 /= float_texture_width; chr.1.tex_coords.1 /= texture_height; chr.1.size.0 /= em_pixels; chr.1.size.1 /= em_pixels; chr.1.left_padding /= em_pixels; chr.1.right_padding /= em_pixels; chr.1.height_over_line /= em_pixels; chr }).collect::<HashMap<_, _>>(); // this HashMap will not be used mutably any more and it makes sense to // compact it characters_infos.shrink_to_fit(); // returning Ok((TextureData { data: texture_data, width: texture_width, height: texture_height as u32, }, characters_infos)) } fn get_nearest_po2(mut x: u32) -> u32 { assert!(x > 0); x -= 1; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >> 16); x + 1 }
#[doc = "Register `DDRCTRL_SCHED` reader"] pub type R = crate::R<DDRCTRL_SCHED_SPEC>; #[doc = "Register `DDRCTRL_SCHED` writer"] pub type W = crate::W<DDRCTRL_SCHED_SPEC>; #[doc = "Field `FORCE_LOW_PRI_N` reader - FORCE_LOW_PRI_N"] pub type FORCE_LOW_PRI_N_R = crate::BitReader; #[doc = "Field `FORCE_LOW_PRI_N` writer - FORCE_LOW_PRI_N"] pub type FORCE_LOW_PRI_N_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PREFER_WRITE` reader - PREFER_WRITE"] pub type PREFER_WRITE_R = crate::BitReader; #[doc = "Field `PREFER_WRITE` writer - PREFER_WRITE"] pub type PREFER_WRITE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PAGECLOSE` reader - PAGECLOSE"] pub type PAGECLOSE_R = crate::BitReader; #[doc = "Field `PAGECLOSE` writer - PAGECLOSE"] pub type PAGECLOSE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPR_NUM_ENTRIES` reader - LPR_NUM_ENTRIES"] pub type LPR_NUM_ENTRIES_R = crate::FieldReader; #[doc = "Field `LPR_NUM_ENTRIES` writer - LPR_NUM_ENTRIES"] pub type LPR_NUM_ENTRIES_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `GO2CRITICAL_HYSTERESIS` reader - GO2CRITICAL_HYSTERESIS"] pub type GO2CRITICAL_HYSTERESIS_R = crate::FieldReader; #[doc = "Field `GO2CRITICAL_HYSTERESIS` writer - GO2CRITICAL_HYSTERESIS"] pub type GO2CRITICAL_HYSTERESIS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; #[doc = "Field `RDWR_IDLE_GAP` reader - RDWR_IDLE_GAP"] pub type RDWR_IDLE_GAP_R = crate::FieldReader; #[doc = "Field `RDWR_IDLE_GAP` writer - RDWR_IDLE_GAP"] pub type RDWR_IDLE_GAP_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 7, O>; impl R { #[doc = "Bit 0 - FORCE_LOW_PRI_N"] #[inline(always)] pub fn force_low_pri_n(&self) -> FORCE_LOW_PRI_N_R { FORCE_LOW_PRI_N_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - PREFER_WRITE"] #[inline(always)] pub fn prefer_write(&self) -> PREFER_WRITE_R { PREFER_WRITE_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - PAGECLOSE"] #[inline(always)] pub fn pageclose(&self) -> PAGECLOSE_R { PAGECLOSE_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bits 8:11 - LPR_NUM_ENTRIES"] #[inline(always)] pub fn lpr_num_entries(&self) -> LPR_NUM_ENTRIES_R { LPR_NUM_ENTRIES_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 16:23 - GO2CRITICAL_HYSTERESIS"] #[inline(always)] pub fn go2critical_hysteresis(&self) -> GO2CRITICAL_HYSTERESIS_R { GO2CRITICAL_HYSTERESIS_R::new(((self.bits >> 16) & 0xff) as u8) } #[doc = "Bits 24:30 - RDWR_IDLE_GAP"] #[inline(always)] pub fn rdwr_idle_gap(&self) -> RDWR_IDLE_GAP_R { RDWR_IDLE_GAP_R::new(((self.bits >> 24) & 0x7f) as u8) } } impl W { #[doc = "Bit 0 - FORCE_LOW_PRI_N"] #[inline(always)] #[must_use] pub fn force_low_pri_n(&mut self) -> FORCE_LOW_PRI_N_W<DDRCTRL_SCHED_SPEC, 0> { FORCE_LOW_PRI_N_W::new(self) } #[doc = "Bit 1 - PREFER_WRITE"] #[inline(always)] #[must_use] pub fn prefer_write(&mut self) -> PREFER_WRITE_W<DDRCTRL_SCHED_SPEC, 1> { PREFER_WRITE_W::new(self) } #[doc = "Bit 2 - PAGECLOSE"] #[inline(always)] #[must_use] pub fn pageclose(&mut self) -> PAGECLOSE_W<DDRCTRL_SCHED_SPEC, 2> { PAGECLOSE_W::new(self) } #[doc = "Bits 8:11 - LPR_NUM_ENTRIES"] #[inline(always)] #[must_use] pub fn lpr_num_entries(&mut self) -> LPR_NUM_ENTRIES_W<DDRCTRL_SCHED_SPEC, 8> { LPR_NUM_ENTRIES_W::new(self) } #[doc = "Bits 16:23 - GO2CRITICAL_HYSTERESIS"] #[inline(always)] #[must_use] pub fn go2critical_hysteresis(&mut self) -> GO2CRITICAL_HYSTERESIS_W<DDRCTRL_SCHED_SPEC, 16> { GO2CRITICAL_HYSTERESIS_W::new(self) } #[doc = "Bits 24:30 - RDWR_IDLE_GAP"] #[inline(always)] #[must_use] pub fn rdwr_idle_gap(&mut self) -> RDWR_IDLE_GAP_W<DDRCTRL_SCHED_SPEC, 24> { RDWR_IDLE_GAP_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 = "DDRCTRL scheduler control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ddrctrl_sched::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 [`ddrctrl_sched::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct DDRCTRL_SCHED_SPEC; impl crate::RegisterSpec for DDRCTRL_SCHED_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ddrctrl_sched::R`](R) reader structure"] impl crate::Readable for DDRCTRL_SCHED_SPEC {} #[doc = "`write(|w| ..)` method takes [`ddrctrl_sched::W`](W) writer structure"] impl crate::Writable for DDRCTRL_SCHED_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets DDRCTRL_SCHED to value 0x0805"] impl crate::Resettable for DDRCTRL_SCHED_SPEC { const RESET_VALUE: Self::Ux = 0x0805; }
use crate::{Glyph, GlyphIter, IntoGlyphId, LayoutIter, Point, Scale, VMetrics}; #[cfg(not(feature = "has-atomics"))] use alloc::rc::Rc as Arc; #[cfg(feature = "has-atomics")] use alloc::sync::Arc; #[cfg(not(feature = "std"))] use alloc::vec::Vec; use core::fmt; /// A single font. This may or may not own the font data. /// /// # Lifetime /// The lifetime reflects the font data lifetime. `Font<'static>` covers most /// cases ie both dynamically loaded owned data and for referenced compile time /// font data. /// /// # Example /// /// ``` /// # use rusttype::Font; /// # fn example() -> Option<()> { /// let font_data: &[u8] = include_bytes!("../dev/fonts/dejavu/DejaVuSansMono.ttf"); /// let font: Font<'static> = Font::try_from_bytes(font_data)?; /// /// let owned_font_data: Vec<u8> = font_data.to_vec(); /// let from_owned_font: Font<'static> = Font::try_from_vec(owned_font_data)?; /// # Some(()) /// # } /// ``` #[derive(Clone)] pub enum Font<'a> { Ref(Arc<owned_ttf_parser::Face<'a>>), Owned(Arc<owned_ttf_parser::OwnedFace>), } impl fmt::Debug for Font<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Font") } } impl Font<'_> { /// Creates a Font from byte-slice data. /// /// Returns `None` for invalid data. pub fn try_from_bytes(bytes: &[u8]) -> Option<Font<'_>> { Self::try_from_bytes_and_index(bytes, 0) } /// Creates a Font from byte-slice data & a font collection `index`. /// /// Returns `None` for invalid data. pub fn try_from_bytes_and_index(bytes: &[u8], index: u32) -> Option<Font<'_>> { let inner = Arc::new(owned_ttf_parser::Face::parse(bytes, index).ok()?); Some(Font::Ref(inner)) } /// Creates a Font from owned font data. /// /// Returns `None` for invalid data. pub fn try_from_vec(data: Vec<u8>) -> Option<Font<'static>> { Self::try_from_vec_and_index(data, 0) } /// Creates a Font from owned font data & a font collection `index`. /// /// Returns `None` for invalid data. pub fn try_from_vec_and_index(data: Vec<u8>, index: u32) -> Option<Font<'static>> { let inner = Arc::new(owned_ttf_parser::OwnedFace::from_vec(data, index).ok()?); Some(Font::Owned(inner)) } } impl<'font> Font<'font> { #[inline] pub(crate) fn inner(&self) -> &owned_ttf_parser::Face<'_> { use owned_ttf_parser::AsFaceRef; match self { Self::Ref(f) => f, Self::Owned(f) => f.as_face_ref(), } } /// The "vertical metrics" for this font at a given scale. These metrics are /// shared by all of the glyphs in the font. See `VMetrics` for more detail. pub fn v_metrics(&self, scale: Scale) -> VMetrics { self.v_metrics_unscaled() * self.scale_for_pixel_height(scale.y) } /// Get the unscaled VMetrics for this font, shared by all glyphs. /// See `VMetrics` for more detail. pub fn v_metrics_unscaled(&self) -> VMetrics { let font = self.inner(); VMetrics { ascent: font.ascender() as f32, descent: font.descender() as f32, line_gap: font.line_gap() as f32, } } /// Returns the units per EM square of this font pub fn units_per_em(&self) -> u16 { self.inner().units_per_em() } /// The number of glyphs present in this font. Glyph identifiers for this /// font will always be in the range `0..self.glyph_count()` pub fn glyph_count(&self) -> usize { self.inner().number_of_glyphs() as _ } /// Returns the corresponding glyph for a Unicode code point or a glyph id /// for this font. /// /// If `id` is a `GlyphId`, it must be valid for this font; otherwise, this /// function panics. `GlyphId`s should always be produced by looking up some /// other sort of designator (like a Unicode code point) in a font, and /// should only be used to index the font they were produced for. /// /// Note that code points without corresponding glyphs in this font map to /// the ".notdef" glyph, glyph 0. pub fn glyph<C: IntoGlyphId>(&self, id: C) -> Glyph<'font> { let gid = id.into_glyph_id(self); assert!((gid.0 as usize) < self.glyph_count()); // font clone either a reference clone, or arc clone Glyph { font: self.clone(), id: gid, } } /// A convenience function. /// /// Returns an iterator that produces the glyphs corresponding to the code /// points or glyph ids produced by the given iterator `itr`. /// /// This is equivalent in behaviour to `itr.map(|c| font.glyph(c))`. pub fn glyphs_for<'a, I: Iterator>(&'a self, itr: I) -> GlyphIter<'a, 'font, I> where I::Item: IntoGlyphId, { GlyphIter { font: self, itr } } /// A convenience function for laying out glyphs for a string horizontally. /// It does not take control characters like line breaks into account, as /// treatment of these is likely to depend on the application. /// /// Note that this function does not perform Unicode normalisation. /// Composite characters (such as ö constructed from two code points, ¨ and /// o), will not be normalised to single code points. So if a font does not /// contain a glyph for each separate code point, but does contain one for /// the normalised single code point (which is common), the desired glyph /// will not be produced, despite being present in the font. Deal with this /// by performing Unicode normalisation on the input string before passing /// it to `layout`. The crate /// [unicode-normalization](http://crates.io/crates/unicode-normalization) /// is perfect for this purpose. /// /// Calling this function is equivalent to a longer sequence of operations /// involving `glyphs_for`, e.g. /// /// ```no_run /// # use rusttype::*; /// # let (scale, start) = (Scale::uniform(0.0), point(0.0, 0.0)); /// # let font: Font = unimplemented!(); /// font.layout("Hello World!", scale, start) /// # ; /// ``` /// /// produces an iterator with behaviour equivalent to the following: /// /// ```no_run /// # use rusttype::*; /// # let (scale, start) = (Scale::uniform(0.0), point(0.0, 0.0)); /// # let font: Font = unimplemented!(); /// font.glyphs_for("Hello World!".chars()) /// .scan((None, 0.0), |(last, x), g| { /// let g = g.scaled(scale); /// if let Some(last) = last { /// *x += font.pair_kerning(scale, *last, g.id()); /// } /// let w = g.h_metrics().advance_width; /// let next = g.positioned(start + vector(*x, 0.0)); /// *last = Some(next.id()); /// *x += w; /// Some(next) /// }) /// # ; /// ``` pub fn layout<'a, 's>( &'a self, s: &'s str, scale: Scale, start: Point<f32>, ) -> LayoutIter<'a, 'font, 's> { LayoutIter { font: self, chars: s.chars(), caret: 0.0, scale, start, last_glyph: None, } } /// Returns additional kerning to apply as well as that given by HMetrics /// for a particular pair of glyphs. pub fn pair_kerning<A, B>(&self, scale: Scale, first: A, second: B) -> f32 where A: IntoGlyphId, B: IntoGlyphId, { let first_id = first.into_glyph_id(self).into(); let second_id = second.into_glyph_id(self).into(); let factor = { let hscale = self.scale_for_pixel_height(scale.y); hscale * (scale.x / scale.y) }; let kern = if let Some(kern) = self.inner().tables().kern { kern.subtables .into_iter() .filter(|st| st.horizontal && !st.variable) .find_map(|st| st.glyphs_kerning(first_id, second_id)) .unwrap_or(0) } else { 0 }; factor * f32::from(kern) } /// Computes a scale factor to produce a font whose "height" is 'pixels' /// tall. Height is measured as the distance from the highest ascender /// to the lowest descender; in other words, it's equivalent to calling /// GetFontVMetrics and computing: /// scale = pixels / (ascent - descent) /// so if you prefer to measure height by the ascent only, use a similar /// calculation. pub fn scale_for_pixel_height(&self, height: f32) -> f32 { let inner = self.inner(); let fheight = f32::from(inner.ascender()) - f32::from(inner.descender()); height / fheight } }
#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FileType { File, Directory, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Permissions { pub read: bool, pub write: bool, } impl Permissions { pub fn readonly(&self) -> bool { self.read && !self.write } pub fn writeonly(&self) -> bool { self.write && !self.read } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Stat { pub file_type: FileType, pub permissions: Permissions, pub size: usize, }
use serenity::model::id::MessageId; use command_error::CommandError; command!(purge(_ctx, msg, args) { // Get the number of messages to delete. let num = args.single::<u64>().unwrap(); let channel = msg.channel() .ok_or(CommandError::Generic("Could not get channel.".to_owned()))?; let channel = channel.guild() .ok_or(CommandError::Generic("Could not get guild channel.".to_owned()))?; let channel = channel.write(); let messages: Vec<MessageId> = channel.messages(|m| m.limit(num)) .unwrap() .into_iter() .map(|m| m.id) .collect(); channel.delete_messages(messages.into_iter())?; });
use crate::assembunny::*; use crate::prelude::*; pub fn pt(input: Vec<Instruction>) -> Result<i64> { let mut prog = Program::new(input)?; let mut start_idx = -1i64; let mut state: HashSet<(i64, Registers, bool)> = HashSet::new(); 'outer: loop { prog.instruction_ptr = 0; start_idx += 1; let mut expect_high = false; let mut regs = Registers::default(); regs[0] = start_idx; state.clear(); state.insert((prog.instruction_ptr, regs, expect_high)); let mut has_false_output = false; while prog.run_one(&mut regs, |value| { let is_correct = match value { 0 => !expect_high, 1 => expect_high, _ => false, }; if !is_correct { has_false_output = true; } expect_high = !expect_high; }) { if has_false_output { continue 'outer; } if !state.insert((prog.instruction_ptr, regs, expect_high)) { break 'outer Ok(start_idx); } } } } pub fn parse(s: &str) -> IResult<&str, Vec<Instruction>> { use parsers::*; map_res(parse_assembunny, |instrs| { for instr in &instrs { match instr { Instruction::Toggle(_) => return Err(()), _ => {} } } Ok(instrs) })(s) }
#[doc = "Register `CCER` reader"] pub type R = crate::R<CCER_SPEC>; #[doc = "Register `CCER` writer"] pub type W = crate::W<CCER_SPEC>; #[doc = "Field `CC1E` reader - CC1E"] pub type CC1E_R = crate::BitReader<CC1E_A>; #[doc = "CC1E\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CC1E_A { #[doc = "0: Capture disabled"] Disabled = 0, #[doc = "1: Capture enabled"] Enabled = 1, } impl From<CC1E_A> for bool { #[inline(always)] fn from(variant: CC1E_A) -> Self { variant as u8 != 0 } } impl CC1E_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CC1E_A { match self.bits { false => CC1E_A::Disabled, true => CC1E_A::Enabled, } } #[doc = "Capture disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == CC1E_A::Disabled } #[doc = "Capture enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == CC1E_A::Enabled } } #[doc = "Field `CC1E` writer - CC1E"] pub type CC1E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CC1E_A>; impl<'a, REG, const O: u8> CC1E_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Capture disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(CC1E_A::Disabled) } #[doc = "Capture enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(CC1E_A::Enabled) } } #[doc = "Field `CC1P` reader - CC1P"] pub type CC1P_R = crate::BitReader<CC1P_A>; #[doc = "CC1P\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CC1P_A { #[doc = "0: Noninverted/rising edge"] RisingEdge = 0, #[doc = "1: Inverted/falling edge"] FallingEdge = 1, } impl From<CC1P_A> for bool { #[inline(always)] fn from(variant: CC1P_A) -> Self { variant as u8 != 0 } } impl CC1P_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CC1P_A { match self.bits { false => CC1P_A::RisingEdge, true => CC1P_A::FallingEdge, } } #[doc = "Noninverted/rising edge"] #[inline(always)] pub fn is_rising_edge(&self) -> bool { *self == CC1P_A::RisingEdge } #[doc = "Inverted/falling edge"] #[inline(always)] pub fn is_falling_edge(&self) -> bool { *self == CC1P_A::FallingEdge } } #[doc = "Field `CC1P` writer - CC1P"] pub type CC1P_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CC1P_A>; impl<'a, REG, const O: u8> CC1P_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Noninverted/rising edge"] #[inline(always)] pub fn rising_edge(self) -> &'a mut crate::W<REG> { self.variant(CC1P_A::RisingEdge) } #[doc = "Inverted/falling edge"] #[inline(always)] pub fn falling_edge(self) -> &'a mut crate::W<REG> { self.variant(CC1P_A::FallingEdge) } } #[doc = "Field `CC1NE` reader - CC1NE"] pub type CC1NE_R = crate::BitReader<CC1NE_A>; #[doc = "CC1NE\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CC1NE_A { #[doc = "0: Complementary output disabled"] Disabled = 0, #[doc = "1: Complementary output enabled"] Enabled = 1, } impl From<CC1NE_A> for bool { #[inline(always)] fn from(variant: CC1NE_A) -> Self { variant as u8 != 0 } } impl CC1NE_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CC1NE_A { match self.bits { false => CC1NE_A::Disabled, true => CC1NE_A::Enabled, } } #[doc = "Complementary output disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == CC1NE_A::Disabled } #[doc = "Complementary output enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == CC1NE_A::Enabled } } #[doc = "Field `CC1NE` writer - CC1NE"] pub type CC1NE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CC1NE_A>; impl<'a, REG, const O: u8> CC1NE_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Complementary output disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(CC1NE_A::Disabled) } #[doc = "Complementary output enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(CC1NE_A::Enabled) } } #[doc = "Field `CC1NP` reader - CC1NP"] pub type CC1NP_R = crate::BitReader<CC1NP_A>; #[doc = "CC1NP\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CC1NP_A { #[doc = "0: OCxN active high"] ActiveHigh = 0, #[doc = "1: OCxN active low"] ActiveLow = 1, } impl From<CC1NP_A> for bool { #[inline(always)] fn from(variant: CC1NP_A) -> Self { variant as u8 != 0 } } impl CC1NP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CC1NP_A { match self.bits { false => CC1NP_A::ActiveHigh, true => CC1NP_A::ActiveLow, } } #[doc = "OCxN active high"] #[inline(always)] pub fn is_active_high(&self) -> bool { *self == CC1NP_A::ActiveHigh } #[doc = "OCxN active low"] #[inline(always)] pub fn is_active_low(&self) -> bool { *self == CC1NP_A::ActiveLow } } #[doc = "Field `CC1NP` writer - CC1NP"] pub type CC1NP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CC1NP_A>; impl<'a, REG, const O: u8> CC1NP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "OCxN active high"] #[inline(always)] pub fn active_high(self) -> &'a mut crate::W<REG> { self.variant(CC1NP_A::ActiveHigh) } #[doc = "OCxN active low"] #[inline(always)] pub fn active_low(self) -> &'a mut crate::W<REG> { self.variant(CC1NP_A::ActiveLow) } } #[doc = "Field `CC2E` reader - CC2E"] pub use CC1E_R as CC2E_R; #[doc = "Field `CC3E` reader - CC3E"] pub use CC1E_R as CC3E_R; #[doc = "Field `CC4E` reader - CC4E"] pub use CC1E_R as CC4E_R; #[doc = "Field `CC5E` reader - CC5E"] pub use CC1E_R as CC5E_R; #[doc = "Field `CC6E` reader - CC6E"] pub use CC1E_R as CC6E_R; #[doc = "Field `CC2E` writer - CC2E"] pub use CC1E_W as CC2E_W; #[doc = "Field `CC3E` writer - CC3E"] pub use CC1E_W as CC3E_W; #[doc = "Field `CC4E` writer - CC4E"] pub use CC1E_W as CC4E_W; #[doc = "Field `CC5E` writer - CC5E"] pub use CC1E_W as CC5E_W; #[doc = "Field `CC6E` writer - CC6E"] pub use CC1E_W as CC6E_W; #[doc = "Field `CC2NE` reader - CC2NE"] pub use CC1NE_R as CC2NE_R; #[doc = "Field `CC3NE` reader - CC3NE"] pub use CC1NE_R as CC3NE_R; #[doc = "Field `CC2NE` writer - CC2NE"] pub use CC1NE_W as CC2NE_W; #[doc = "Field `CC3NE` writer - CC3NE"] pub use CC1NE_W as CC3NE_W; #[doc = "Field `CC2NP` reader - CC2NP"] pub use CC1NP_R as CC2NP_R; #[doc = "Field `CC3NP` reader - CC3NP"] pub use CC1NP_R as CC3NP_R; #[doc = "Field `CC2NP` writer - CC2NP"] pub use CC1NP_W as CC2NP_W; #[doc = "Field `CC3NP` writer - CC3NP"] pub use CC1NP_W as CC3NP_W; #[doc = "Field `CC2P` reader - CC2P"] pub use CC1P_R as CC2P_R; #[doc = "Field `CC3P` reader - CC3P"] pub use CC1P_R as CC3P_R; #[doc = "Field `CC4P` reader - CC4P"] pub use CC1P_R as CC4P_R; #[doc = "Field `CC5P` reader - CC5P"] pub use CC1P_R as CC5P_R; #[doc = "Field `CC6P` reader - CC6P"] pub use CC1P_R as CC6P_R; #[doc = "Field `CC2P` writer - CC2P"] pub use CC1P_W as CC2P_W; #[doc = "Field `CC3P` writer - CC3P"] pub use CC1P_W as CC3P_W; #[doc = "Field `CC4P` writer - CC4P"] pub use CC1P_W as CC4P_W; #[doc = "Field `CC5P` writer - CC5P"] pub use CC1P_W as CC5P_W; #[doc = "Field `CC6P` writer - CC6P"] pub use CC1P_W as CC6P_W; impl R { #[doc = "Bit 0 - CC1E"] #[inline(always)] pub fn cc1e(&self) -> CC1E_R { CC1E_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - CC1P"] #[inline(always)] pub fn cc1p(&self) -> CC1P_R { CC1P_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - CC1NE"] #[inline(always)] pub fn cc1ne(&self) -> CC1NE_R { CC1NE_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - CC1NP"] #[inline(always)] pub fn cc1np(&self) -> CC1NP_R { CC1NP_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - CC2E"] #[inline(always)] pub fn cc2e(&self) -> CC2E_R { CC2E_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - CC2P"] #[inline(always)] pub fn cc2p(&self) -> CC2P_R { CC2P_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - CC2NE"] #[inline(always)] pub fn cc2ne(&self) -> CC2NE_R { CC2NE_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - CC2NP"] #[inline(always)] pub fn cc2np(&self) -> CC2NP_R { CC2NP_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - CC3E"] #[inline(always)] pub fn cc3e(&self) -> CC3E_R { CC3E_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - CC3P"] #[inline(always)] pub fn cc3p(&self) -> CC3P_R { CC3P_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - CC3NE"] #[inline(always)] pub fn cc3ne(&self) -> CC3NE_R { CC3NE_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - CC3NP"] #[inline(always)] pub fn cc3np(&self) -> CC3NP_R { CC3NP_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - CC4E"] #[inline(always)] pub fn cc4e(&self) -> CC4E_R { CC4E_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - CC4P"] #[inline(always)] pub fn cc4p(&self) -> CC4P_R { CC4P_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 16 - CC5E"] #[inline(always)] pub fn cc5e(&self) -> CC5E_R { CC5E_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - CC5P"] #[inline(always)] pub fn cc5p(&self) -> CC5P_R { CC5P_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 20 - CC6E"] #[inline(always)] pub fn cc6e(&self) -> CC6E_R { CC6E_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - CC6P"] #[inline(always)] pub fn cc6p(&self) -> CC6P_R { CC6P_R::new(((self.bits >> 21) & 1) != 0) } } impl W { #[doc = "Bit 0 - CC1E"] #[inline(always)] #[must_use] pub fn cc1e(&mut self) -> CC1E_W<CCER_SPEC, 0> { CC1E_W::new(self) } #[doc = "Bit 1 - CC1P"] #[inline(always)] #[must_use] pub fn cc1p(&mut self) -> CC1P_W<CCER_SPEC, 1> { CC1P_W::new(self) } #[doc = "Bit 2 - CC1NE"] #[inline(always)] #[must_use] pub fn cc1ne(&mut self) -> CC1NE_W<CCER_SPEC, 2> { CC1NE_W::new(self) } #[doc = "Bit 3 - CC1NP"] #[inline(always)] #[must_use] pub fn cc1np(&mut self) -> CC1NP_W<CCER_SPEC, 3> { CC1NP_W::new(self) } #[doc = "Bit 4 - CC2E"] #[inline(always)] #[must_use] pub fn cc2e(&mut self) -> CC2E_W<CCER_SPEC, 4> { CC2E_W::new(self) } #[doc = "Bit 5 - CC2P"] #[inline(always)] #[must_use] pub fn cc2p(&mut self) -> CC2P_W<CCER_SPEC, 5> { CC2P_W::new(self) } #[doc = "Bit 6 - CC2NE"] #[inline(always)] #[must_use] pub fn cc2ne(&mut self) -> CC2NE_W<CCER_SPEC, 6> { CC2NE_W::new(self) } #[doc = "Bit 7 - CC2NP"] #[inline(always)] #[must_use] pub fn cc2np(&mut self) -> CC2NP_W<CCER_SPEC, 7> { CC2NP_W::new(self) } #[doc = "Bit 8 - CC3E"] #[inline(always)] #[must_use] pub fn cc3e(&mut self) -> CC3E_W<CCER_SPEC, 8> { CC3E_W::new(self) } #[doc = "Bit 9 - CC3P"] #[inline(always)] #[must_use] pub fn cc3p(&mut self) -> CC3P_W<CCER_SPEC, 9> { CC3P_W::new(self) } #[doc = "Bit 10 - CC3NE"] #[inline(always)] #[must_use] pub fn cc3ne(&mut self) -> CC3NE_W<CCER_SPEC, 10> { CC3NE_W::new(self) } #[doc = "Bit 11 - CC3NP"] #[inline(always)] #[must_use] pub fn cc3np(&mut self) -> CC3NP_W<CCER_SPEC, 11> { CC3NP_W::new(self) } #[doc = "Bit 12 - CC4E"] #[inline(always)] #[must_use] pub fn cc4e(&mut self) -> CC4E_W<CCER_SPEC, 12> { CC4E_W::new(self) } #[doc = "Bit 13 - CC4P"] #[inline(always)] #[must_use] pub fn cc4p(&mut self) -> CC4P_W<CCER_SPEC, 13> { CC4P_W::new(self) } #[doc = "Bit 16 - CC5E"] #[inline(always)] #[must_use] pub fn cc5e(&mut self) -> CC5E_W<CCER_SPEC, 16> { CC5E_W::new(self) } #[doc = "Bit 17 - CC5P"] #[inline(always)] #[must_use] pub fn cc5p(&mut self) -> CC5P_W<CCER_SPEC, 17> { CC5P_W::new(self) } #[doc = "Bit 20 - CC6E"] #[inline(always)] #[must_use] pub fn cc6e(&mut self) -> CC6E_W<CCER_SPEC, 20> { CC6E_W::new(self) } #[doc = "Bit 21 - CC6P"] #[inline(always)] #[must_use] pub fn cc6p(&mut self) -> CC6P_W<CCER_SPEC, 21> { CC6P_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 = "capture/compare enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccer::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 [`ccer::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CCER_SPEC; impl crate::RegisterSpec for CCER_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ccer::R`](R) reader structure"] impl crate::Readable for CCER_SPEC {} #[doc = "`write(|w| ..)` method takes [`ccer::W`](W) writer structure"] impl crate::Writable for CCER_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CCER to value 0"] impl crate::Resettable for CCER_SPEC { const RESET_VALUE: Self::Ux = 0; }
use actix_service::Service; use actix_session::CookieSession; use actix_web::{App, HttpServer}; use anyhow::Result; use futures::{FutureExt, TryFutureExt}; use rustimate_controllers::routes::add_routes; use rustimate_service::AppConfig; use std::time::SystemTime; pub(crate) async fn start_server(cfg: AppConfig, port_tx: std::sync::mpsc::Sender<u16>) -> Result<()> { let cfg = cfg.clone(); let data = cfg.clone(); let server = HttpServer::new(move || { App::new() .data(cfg.clone()) .wrap( CookieSession::signed(&[0; 32]) .http_only(true) .name(rustimate_core::APPNAME) .secure(false) ) .wrap(actix_web::middleware::Compress::default()) .wrap_fn(|req, srv| { let p = req.path().to_owned(); let start_time = SystemTime::now(); let cfg: AppConfig = match req.app_data::<AppConfig>() { Some(ad) => ad.get_ref().to_owned(), None => panic!("Missing AppConfig data reference!") }; let useful = !p.starts_with("/static"); if useful { slog::trace!(cfg.root_logger(), "Request received for path [{}]", p); } srv.call(req).map(move |res| { if useful { let elapsed_time = SystemTime::now() .duration_since(start_time) .ok() .map(|x| x.as_micros() as f64) .get_or_insert(0f64) .to_owned(); let ms = elapsed_time / 1000.0; // slog::debug!( // cfg.root_logger(), "{}", r.response().status(); // "path" => &p, "status" => format!("{}", r.response().status().as_u16()), "elapsed" => format!("{}", ms) // ); } res }) }) .configure(|s| add_routes(s)) }); match server.bind(format!("{}:{}", &data.address(), data.port())) { Ok(s) => { let port = s.addrs()[0].port(); let _ = port_tx.send(port); let msg = format!("[{}] started, open http://{}:{} to get going!", rustimate_core::APPNAME, data.address(), port); slog::info!(data.root_logger(), "{}", msg); s.run().map_err(|e| anyhow::anyhow!(format!("Error binding to port [{}]: {}", data.port(), e))).await } Err(e) => { let msg = format!("Error starting server on port [{}]: {}", data.port(), e); slog::info!(data.root_logger(), "{}", msg); Err(anyhow::anyhow!(format!("Cannot start server: {}", e))) } } }
use anyhow::{Context, Result}; use serde_state::DeserializeState; use necsim_core_bond::Partition; use necsim_partitioning_core::Partitioning; use super::{CommandArgs, ReplayArgs, SimulateArgs}; /// Transform the `command_args` into a RON `String` fn into_ron_args(command_args: CommandArgs) -> String { let mut ron_args = String::new(); for arg in command_args.args { ron_args.push_str(&arg); ron_args.push(' '); } let ron_args_trimmed = ron_args.trim(); let mut ron_args = String::from("#![enable(unwrap_newtypes)] #![enable(implicit_some)]"); ron_args.reserve(ron_args_trimmed.len()); if !ron_args_trimmed.starts_with('(') { ron_args.push('('); } ron_args.push_str(ron_args_trimmed); if !ron_args_trimmed.starts_with('(') { ron_args.push(')'); } ron_args } fn try_parse_subcommand_arguments<'de, A: DeserializeState<'de, Partition>, P: Partitioning>( subcommand: &str, ron_args: &'de str, partitioning: &P, ) -> Result<A> { let mut de_ron = ron::Deserializer::from_str(ron_args).context(format!( "Failed to create the {} subcommand argument parser.", subcommand ))?; let mut track = serde_path_to_error::Track::new(); let de = serde_path_to_error::Deserializer::new(&mut de_ron, &mut track); let mut partition = Partition::try_new( partitioning.get_rank(), partitioning.get_number_of_partitions(), ) .map_err(anyhow::Error::msg)?; let args = match A::deserialize_state(&mut partition, de) { Ok(args) => Ok(args), Err(err) => { let path = track.path(); Err(anyhow::Error::msg(format!( "{}{}{}{}: {}", subcommand, if path.iter().count() >= 1 { "." } else { "" }, path, if path.iter().count() >= 1 { "" } else { "*" }, err, ))) }, } .context(format!( "Failed to parse the {} subcommand arguments.", subcommand ))?; Ok(args) } impl SimulateArgs { pub fn try_parse<P: Partitioning>(command_args: CommandArgs, partitioning: &P) -> Result<Self> { // Parse and validate all command line arguments for a subcommand try_parse_subcommand_arguments("simulate", &into_ron_args(command_args), partitioning) } } impl ReplayArgs { pub fn try_parse<P: Partitioning>(command_args: CommandArgs, partitioning: &P) -> Result<Self> { // Parse and validate all command line arguments for a subcommand try_parse_subcommand_arguments("replay", &into_ron_args(command_args), partitioning) } }