text stringlengths 8 4.13M |
|---|
use crate::common::{self, *};
pub type Button = AMember<AControl<AButton<TestableButton>>>;
#[repr(C)]
pub struct TestableButton {
pub base: common::TestableControlBase<Button>,
label: String,
h_left_clicked: Option<callbacks::OnClick>,
}
impl<O: controls::Button> NewButtonInner<O> for TestableButton {
fn with_uninit(u: &mut mem::MaybeUninit<O>) -> Self {
TestableButton {
base: common::TestableControlBase::with_id(u),
h_left_clicked: None,
label: String::new(),
}
}
}
impl HasLabelInner for TestableButton {
fn label<'a>(&'a self, _: &MemberBase) -> Cow<'a, str> {
Cow::Borrowed(self.label.as_ref())
}
fn set_label(&mut self, _base: &mut MemberBase, label: Cow<str>) {
self.label = label.into();
self.base.invalidate();
}
}
impl ClickableInner for TestableButton {
fn on_click(&mut self, handle: Option<callbacks::OnClick>) {
self.h_left_clicked = handle;
}
fn click(&mut self, skip_callbacks: bool) {
if !skip_callbacks {
if let Some(ref mut h_left_clicked) = self.h_left_clicked {
(h_left_clicked.as_mut())(unsafe { &mut *(self.base.id as *mut Button) });
}
}
}
}
impl ButtonInner for TestableButton {
fn with_label<S: AsRef<str>>(label: S) -> Box<dyn controls::Button> {
let mut b: Box<mem::MaybeUninit<Button>> = Box::new_uninit();
let mut ab = AMember::with_inner(
AControl::with_inner(
AButton::with_inner(
<Self as NewButtonInner<Button>>::with_uninit(b.as_mut())
),
)
);
controls::HasLabel::set_label(&mut ab, label.as_ref().into());
unsafe {
b.as_mut_ptr().write(ab);
b.assume_init()
}
}
}
impl Spawnable for TestableButton {
fn spawn() -> Box<dyn controls::Control> {
<Self as ButtonInner>::with_label("").into_control()
}
}
impl ControlInner for TestableButton {
fn on_added_to_container(&mut self, _member: &mut MemberBase, _control: &mut ControlBase, parent: &dyn controls::Container, x: i32, y: i32, _pw: u16, _ph: u16) {
self.base.parent = Some(unsafe {parent.native_id() as InnerId});
self.base.position = (x, y);
}
fn on_removed_from_container(&mut self, _member: &mut MemberBase, _control: &mut ControlBase, _: &dyn controls::Container) {
self.base.parent = None;
}
fn parent(&self) -> Option<&dyn controls::Member> {
self.base.parent().map(|p| p.as_member())
}
fn parent_mut(&mut self) -> Option<&mut dyn controls::Member> {
self.base.parent_mut().map(|p| p.as_member_mut())
}
fn root(&self) -> Option<&dyn controls::Member> {
self.base.root().map(|p| p.as_member())
}
fn root_mut(&mut self) -> Option<&mut dyn controls::Member> {
self.base.root_mut().map(|p| p.as_member_mut())
}
#[cfg(feature = "markup")]
fn fill_from_markup(&mut self, member: &mut MemberBase, _control: &mut ControlBase, markup: &plygui_api::markup::Markup, registry: &mut plygui_api::markup::MarkupRegistry) {
use plygui_api::markup::MEMBER_TYPE_BUTTON;
fill_from_markup_base!(self, member, markup, registry, Button, [MEMBER_TYPE_BUTTON]);
fill_from_markup_label!(self, member, markup);
fill_from_markup_callbacks!(self, markup, registry, [on_click => plygui_api::callbacks::OnClick]);
}
}
impl HasLayoutInner for TestableButton {
fn on_layout_changed(&mut self, _base: &mut MemberBase) {
self.base.invalidate();
}
}
impl HasNativeIdInner for TestableButton {
type Id = common::TestableId;
fn native_id(&self) -> Self::Id {
self.base.id.into()
}
}
impl HasSizeInner for TestableButton {
fn on_size_set(&mut self, base: &mut MemberBase, (width, height): (u16, u16)) -> bool {
use plygui_api::controls::HasLayout;
let this = base.as_any_mut().downcast_mut::<Button>().unwrap();
this.set_layout_width(layout::Size::Exact(width));
this.set_layout_width(layout::Size::Exact(height));
self.base.invalidate();
unsafe { utils::base_to_impl_mut::<Button>(base) }.call_on_size::<Button>(width, height);
true
}
}
impl HasVisibilityInner for TestableButton {
fn on_visibility_set(&mut self, _base: &mut MemberBase, value: types::Visibility) -> bool {
self.base.on_set_visibility(value)
}
}
impl MemberInner for TestableButton {}
impl Drawable for TestableButton {
fn draw(&mut self, _member: &mut MemberBase, control: &mut ControlBase) {
self.base.draw(format!("Button '{}'", self.label).as_str(), control.coords, control.measured);
}
fn measure(&mut self, _member: &mut MemberBase, control: &mut ControlBase, parent_width: u16, parent_height: u16) -> (u16, u16, bool) {
let old_size = control.measured;
control.measured = match control.visibility {
types::Visibility::Gone => (0, 0),
_ => {
let label_size = (self.label.len(), 1);
let w = match control.layout.width {
layout::Size::MatchParent => parent_width as i32,
layout::Size::Exact(w) => w as i32,
layout::Size::WrapContent => {
label_size.0 as i32 + DEFAULT_PADDING + DEFAULT_PADDING
}
};
let h = match control.layout.height {
layout::Size::MatchParent => parent_height as i32,
layout::Size::Exact(h) => h as i32,
layout::Size::WrapContent => {
label_size.1 as i32 + DEFAULT_PADDING + DEFAULT_PADDING
}
};
(cmp::max(0, w) as u16, cmp::max(0, h) as u16)
}
};
(control.measured.0, control.measured.1, control.measured != old_size)
}
fn invalidate(&mut self, _member: &mut MemberBase, _control: &mut ControlBase) {
self.base.invalidate()
}
}
|
use std::fs::File;
use std::io::BufReader;
pub fn read_input_to_string(day: &str) -> String {
let path = format!("{}/input/{}", std::env!("CARGO_MANIFEST_DIR"), day);
match std::fs::read_to_string(&path) {
Ok(input) => input,
Err(e) => {
println!("Failed to read input from '{}' with following error", path);
println!("{}", e);
std::process::exit(1);
}
}
}
pub fn input_bufreader(day: &str) -> BufReader<File> {
let path = format!("{}/input/{}", std::env!("CARGO_MANIFEST_DIR"), day);
match File::open(&path) {
Ok(input) => BufReader::new(input),
Err(e) => {
println!("Failed to read input from '{}' with following error", path);
println!("{}", e);
std::process::exit(1);
}
}
}
|
/// this analyzer parses the Control Flow Guard function table.
/// it populates functions in the workspace.
/// the purpose of the table is to enumerate the functions that may be called indirectly.
///
/// references:
/// - https://docs.microsoft.com/en-us/windows/desktop/debug/pe-format#load-configuration-directory
/// - https://lucasg.github.io/2017/02/05/Control-Flow-Guard/
use log::{debug};
use goblin::{Object};
use failure::{Error};
use super::super::super::arch::{RVA, VA};
use super::super::super::loader::{Permissions};
use super::super::super::workspace::Workspace;
use super::super::{Analyzer};
pub struct CFGuardTableAnalyzer {}
impl CFGuardTableAnalyzer {
pub fn new() -> CFGuardTableAnalyzer {
CFGuardTableAnalyzer {}
}
}
const IMAGE_GUARD_CF_FUNCTION_TABLE_SIZE_MASK: u32 = 0xF0000000;
const IMAGE_GUARD_CF_FUNCTION_TABLE_SIZE_SHIFT: u32 = 28;
impl Analyzer for CFGuardTableAnalyzer {
fn get_name(&self) -> String {
"CF Guard Table analyzer".to_string()
}
/// ```
/// use lancelot::rsrc::*;
/// use lancelot::arch::*;
/// use lancelot::analysis::Analyzer;
/// use lancelot::workspace::Workspace;
/// use lancelot::analysis::pe::CFGuardTableAnalyzer;
///
/// let mut ws = Workspace::from_bytes("k32.dll", &get_buf(Rsrc::K32))
/// .disable_analysis()
/// .load().unwrap();
/// CFGuardTableAnalyzer::new().analyze(&mut ws);
///
/// // export: RtlVirtualUnwind
/// assert!(ws.get_functions().find(|&&rva| rva == RVA(0x1010)).is_some());
///
/// // __guard_check_icall
/// assert!(ws.get_functions().find(|&&rva| rva == RVA(0x21960)).is_some());
///
/// // __guard_dispatch_icall
/// assert!(ws.get_functions().find(|&&rva| rva == RVA(0x21B40)).is_some());
/// ```
fn analyze(&self, ws: &mut Workspace) -> Result<(), Error> {
let (load_config_directory, is_64) = {
let pe = match Object::parse(&ws.buf) {
Ok(Object::PE(pe)) => pe,
_ => panic!("can't analyze unexpected format"),
};
let opt_header = match pe.header.optional_header {
Some(opt_header) => opt_header,
_ => return Ok(()),
};
let load_config_directory = match opt_header.data_directories.get_load_config_table() {
Some(load_config_directory) => load_config_directory,
_ => return Ok(()),
};
(RVA::from(load_config_directory.virtual_address as i64), pe.is_64)
};
debug!("load config directory: {}", load_config_directory);
// offsets defined here:
// https://docs.microsoft.com/en-us/windows/desktop/debug/pe-format#load-configuration-directory
let cfg_flags = match is_64 {
true => ws.read_u32(load_config_directory + 144)?,
false => ws.read_u32(load_config_directory + 88)?,
};
let stride = (cfg_flags & IMAGE_GUARD_CF_FUNCTION_TABLE_SIZE_MASK) >> IMAGE_GUARD_CF_FUNCTION_TABLE_SIZE_SHIFT;
let cfg_table_va = match is_64 {
true => ws.read_va(load_config_directory + 128)?,
false => ws.read_va(load_config_directory + 80)?,
};
let cfg_table_count = match is_64 {
true => ws.read_u32(load_config_directory + 136)?,
false => ws.read_u32(load_config_directory + 84)?,
};
if cfg_table_va == VA(0x0) {
debug!("CF guard table empty");
return Ok(())
};
let cfg_table_rva = ws.rva(cfg_table_va).unwrap();
debug!("CF guard table: {}", cfg_table_rva);
let mut offset = cfg_table_rva;
for _ in 0..cfg_table_count {
let function = RVA::from(ws.read_i32(offset)?);
debug!("CF guard function: {}", function);
ws.make_function(function)?;
ws.analyze()?;
// 4 == sizeof(32-bit RVA)
offset = offset + (4 + stride as usize);
}
// add function pointed to by GuardCFCheckFunctionPointer
let guard_check_icall_fptr = match is_64 {
true => ws.rva(ws.read_va(load_config_directory + 112)?).unwrap(),
false => ws.rva(ws.read_va(load_config_directory + 72)?).unwrap(),
};
if ws.probe(guard_check_icall_fptr, 8, Permissions::R) {
let guard_check_icall = ws.rva(ws.read_va(guard_check_icall_fptr)?).unwrap();
if ws.probe(guard_check_icall, 1, Permissions::X) {
debug!("CF guard check function: {:#x}", guard_check_icall);
ws.make_function(guard_check_icall)?;
ws.analyze()?;
}
};
// add function pointed to by GuardCFDispatchFunctionPointer
let guard_dispatch_icall_fptr = match is_64 {
true => ws.rva(ws.read_va(load_config_directory + 120)?).unwrap(),
false => ws.rva(ws.read_va(load_config_directory + 76)?).unwrap(),
};
if ws.probe(guard_dispatch_icall_fptr, 8, Permissions::R) {
let guard_dispatch_icall = ws.rva(ws.read_va(guard_dispatch_icall_fptr)?).unwrap();
if ws.probe(guard_dispatch_icall, 1, Permissions::X) {
debug!("CF guard dispatch function: {:#x}", guard_dispatch_icall);
ws.make_function(guard_dispatch_icall)?;
ws.analyze()?;
}
};
Ok(())
}
}
|
use super::atom::btn::{self, Btn};
use super::atom::fa;
use isaribi::{
style,
styled::{Style, Styled},
};
use kagura::component::Cmd;
use kagura::prelude::*;
use nusa::prelude::*;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use wasm_bindgen::{prelude::*, JsCast};
pub struct Props {
pub direction: Direction,
pub variant: btn::Variant,
pub toggle_type: ToggleType,
}
impl Default for Props {
fn default() -> Self {
Self {
direction: Direction::BottomLeft,
toggle_type: ToggleType::Click,
variant: btn::Variant::Primary,
}
}
}
pub enum Direction {
Bottom,
BottomLeft,
BottomRight,
RightBottom,
}
impl std::fmt::Display for Direction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Bottom => write!(f, "bottom"),
Self::BottomLeft => write!(f, "bottom-left"),
Self::BottomRight => write!(f, "bottom-right"),
Self::RightBottom => write!(f, "right-bottom"),
}
}
}
impl Direction {
fn caret(&self) -> Html {
match self {
Self::Bottom | Self::BottomLeft | Self::BottomRight => fa::fas_i("fa-caret-down"),
Self::RightBottom => fa::fas_i("fa-caret-right"),
}
}
}
#[derive(PartialEq, Clone, Copy)]
pub enum ToggleType {
Click,
Hover,
Manual(bool),
}
pub enum Msg {
NoOp,
SetRoot(web_sys::Node),
ToggleTo(bool),
}
pub enum On {}
pub struct Dropdown {
direction: Direction,
variant: btn::Variant,
batch_state: Rc<RefCell<BatchState>>,
batch: js_sys::Function,
}
struct BatchState {
is_dropdowned: bool,
toggle_type: ToggleType,
root: Option<Rc<web_sys::Node>>,
handle: Option<Box<dyn FnMut(Cmd<Dropdown>)>>,
}
impl Component for Dropdown {
type Props = Props;
type Msg = Msg;
type Event = On;
}
impl HtmlComponent for Dropdown {}
impl Constructor for Dropdown {
fn constructor(props: Self::Props) -> Self {
let is_dropdowned = if let ToggleType::Manual(is_dropdowned) = &props.toggle_type {
*is_dropdowned
} else {
false
};
let batch_state = Rc::new(RefCell::new(BatchState {
is_dropdowned,
toggle_type: props.toggle_type,
root: None,
handle: None,
}));
let batch: js_sys::Function = Closure::wrap(Box::new({
let batch_state = Rc::clone(&batch_state);
move |e: web_sys::Event| {
let mut batch_state = batch_state.borrow_mut();
let batch_state: &mut BatchState = &mut batch_state;
if let (Some(root), Some(handle)) =
(batch_state.root.as_ref(), batch_state.handle.as_mut())
{
if batch_state.toggle_type == ToggleType::Click {
if batch_state.is_dropdowned {
handle(Cmd::chain(Msg::ToggleTo(false)));
} else if let Some(target) =
e.target().and_then(|t| t.dyn_into::<web_sys::Node>().ok())
{
if root.contains(Some(&target)) {
handle(Cmd::chain(Msg::ToggleTo(true)));
}
}
}
}
}
}) as Box<dyn FnMut(_)>)
.into_js_value()
.unchecked_into();
let _ = web_sys::window()
.unwrap()
.add_event_listener_with_callback("click", &batch);
Self {
direction: props.direction,
variant: props.variant,
batch_state,
batch,
}
}
}
impl Update for Dropdown {
fn on_assemble(self: Pin<&mut Self>) -> Cmd<Self> {
Cmd::batch(kagura::util::Batch::new({
let batch_state = Rc::clone(&self.batch_state);
move |handle| {
batch_state.borrow_mut().handle = Some(handle);
}
}))
}
fn on_load(mut self: Pin<&mut Self>, props: Self::Props) -> Cmd<Self> {
if let ToggleType::Manual(is_dropdowned) = &props.toggle_type {
self.batch_state.borrow_mut().is_dropdowned = *is_dropdowned;
}
self.direction = props.direction;
self.variant = props.variant;
self.batch_state.borrow_mut().toggle_type = props.toggle_type;
Cmd::none()
}
fn update(self: Pin<&mut Self>, msg: Msg) -> Cmd<Self> {
match msg {
Msg::NoOp => Cmd::none(),
Msg::SetRoot(root) => {
self.batch_state.borrow_mut().root = Some(Rc::new(root));
Cmd::none()
}
Msg::ToggleTo(is_dropdowned) => {
self.batch_state.borrow_mut().is_dropdowned = is_dropdowned;
Cmd::none()
}
}
}
}
impl Render<Html> for Dropdown {
type Children = (Vec<Html>, Vec<Html>);
fn render(&self, (text, children): Self::Children) -> Html {
Self::styled(match &self.batch_state.borrow().toggle_type {
ToggleType::Click => self.render_toggle_by_click(text, children),
ToggleType::Hover => self.render_toggle_by_hover(text, children),
ToggleType::Manual(_) => self.render_toggle_by_manual(text, children),
})
}
}
impl Dropdown {
fn base_class_option(&self) -> &str {
match &self.variant {
btn::Variant::Menu => "base-menu",
btn::Variant::MenuAsSecondary => "base-menu",
btn::Variant::DarkLikeMenu => "base-menu",
btn::Variant::SecondaryLikeMenu => "base-menu",
_ => "base-default",
}
}
fn render_toggle_by_click(&self, text: Vec<Html>, children: Vec<Html>) -> Html {
Html::div(
Attributes::new()
.class(Self::class("base"))
.class(Self::class(self.base_class_option())),
Events::new()
.refer(self, |root| Msg::SetRoot(root))
.on_mousedown(self, |e| {
e.stop_propagation();
Msg::NoOp
}),
vec![self.render_toggle_btn(text), self.render_toggled(children)],
)
}
fn render_toggle_by_hover(&self, text: Vec<Html>, children: Vec<Html>) -> Html {
Html::div(
Attributes::new()
.class(Self::class("base"))
.class(Self::class(self.base_class_option())),
Events::new()
.on("mouseenter", self, |_| Msg::ToggleTo(true))
.on("mouseleave", self, |_| Msg::ToggleTo(false)),
vec![self.render_toggle_btn(text), self.render_toggled(children)],
)
}
fn render_toggle_by_manual(&self, text: Vec<Html>, children: Vec<Html>) -> Html {
Html::div(
Attributes::new()
.class(Self::class("base"))
.class(Self::class(self.base_class_option())),
Events::new(),
vec![self.render_toggle_btn(text), self.render_toggled(children)],
)
}
fn render_toggle_btn(&self, text: Vec<Html>) -> Html {
Html::button(
Attributes::new()
.class("pure-button")
.class(Btn::class_name(&self.variant))
.class(Self::class("root-btn"))
.string(
"data-toggled",
self.batch_state.borrow().is_dropdowned.to_string(),
),
Events::new(),
vec![Html::div(
Attributes::new().class(Self::class("btn")),
Events::new(),
text,
)],
)
}
fn render_toggled(&self, children: Vec<Html>) -> Html {
Html::div(
Attributes::new()
.class(Self::class("content"))
.class(Self::class(&format!("content-{}", &self.direction)))
.string(
"data-toggled",
self.batch_state.borrow().is_dropdowned.to_string(),
),
Events::new(),
if self.batch_state.borrow().is_dropdowned {
children
} else {
vec![]
},
)
}
}
impl std::ops::Drop for Dropdown {
fn drop(&mut self) {
let _ = web_sys::window()
.unwrap()
.remove_event_listener_with_callback("click", &self.batch);
}
}
impl Styled for Dropdown {
fn style() -> Style {
style! {
".base" {
"position": "relative";
"overflow": "visible !important";
}
".base-menu" {
"justify-self": "stretch";
"display": "grid";
}
".base-default" {
"max-width": "max-content";
}
".root-btn" {
"height": "100%";
}
r#".root-btn[data-toggled="false"]"# {
"z-index": "auto";
}
r#".root-btn[data-toggled="true"]"# {
"z-index": format!("{}", super::constant::z_index::MASK + 1);
}
".btn" {
"display": "flex";
"align-items": "center";
}
".btn > *:not(:first-child)" {
"margin-right": "1ch";
}
".btn > *:not(:last-child)" {
"flex-gorw": "1";
}
".content" {
"position": "absolute";
"z-index": format!("{}", super::constant::z_index::MASK + 1);
"grid-auto-rows": "max-content";
"grid-auto-flow": "rows";
"row-gap": "0.05rem";
"padding-top": "0.05rem";
"padding-bottom": "0.05rem";
"justify-items": "stretch";
"background-color": crate::libs::color::color_system::gray(100, 0).to_string();
"border-radius": "2px";
"display": "grid";
}
r#".content[data-toggled="false"]"# {
"display": "none";
}
r#".content[data-toggled="true"]"# {
"display": "grid";
}
".content-bottom" {
"top": "100%";
"left": "0";
"right": "0";
"grid-template-columns": "1fr";
}
".content-bottom-left" {
"top": "100%";
"right": "0";
"grid-template-columns": "max-content";
}
".content-bottom-right" {
"top": "100%";
"left": "0";
"grid-template-columns": "max-content";
}
".content-right-bottom" {
"top": "0";
"left": "100%";
"grid-template-columns": "max-content";
}
".menu-heading" {
"padding": ".5em .5em";
"line-height": "1.5";
"align-items": "center";
"display": "grid";
"grid-template-columns": "1fr max-content 1fr";
"column-gap": ".25em";
}
".menu-heading:before, .menu-heading:after" {
"content": "''";
"height": ".15rem";
"background-color": crate::libs::color::Pallet::gray(1);
}
}
}
}
|
use std::io::{self, Read};
type Bridge = Vec<Pipe>;
#[derive(Debug, Clone)]
struct Pipe {
value: u32,
unused_ends: Vec<u32>,
}
impl Pipe {
fn has_end(&self, val: u32) -> bool {
self.unused_ends.contains(&val)
}
fn remove_end(&mut self, val: u32) {
let first_idx = self.unused_ends.iter().position(|&x| x == val).expect("No such end!");
self.unused_ends.swap_remove(first_idx);
}
}
fn main() {
let mut input = String::new();
io::stdin().read_to_string(&mut input).unwrap();
let pipes = parse(&input);
let bridges = create_all_bridges(pipes);
println!("the strongest bridge: {:?}", bridges.iter().map(|bridge| {
bridge.iter().map(|pipe| {
pipe.value
}).sum::<u32>()
}).max().unwrap());
//Part 2
let mut long_strong = vec![];
let mut strengh = 0;
for bridge in bridges {
if long_strong.len() < bridge.len() {
long_strong = bridge;
strengh = long_strong.iter().map(|pipe| pipe.value).sum();
} else if long_strong.len() == bridge.len() {
let strengh_new = bridge.iter().map(|pipe| pipe.value).sum();
if strengh < strengh_new {
strengh = strengh_new;
long_strong = bridge;
}
}
}
println!("the longest bridge that is strong: {}\nand {} long.", strengh, long_strong.len());
}
fn create_all_bridges(pipes: Vec<Pipe>) -> Vec<Bridge> {
let mut res: Vec<Vec<Pipe>> = vec![];
for (idx, start) in pipes.iter().enumerate().filter(|&(_, pipe)| pipe.has_end(0)) {
let mut start = start.clone();
start.remove_end(0);
let path = vec![];
let mut rest = pipes.clone();
rest.remove(idx);
let mut sol = create(start.clone(), rest.clone(), path);
res.append(&mut sol);
}
res
}
fn create(last: Pipe, to_consider: Vec<Pipe>, path: Bridge) -> Vec<Bridge> {
//this works because we removed the other end before the invocation
//so only one end is left
let number_used = last.unused_ends[0];
let mut path = path;
path.push(last);
//we have no more ends that could connect. Our path is complete
if to_consider.iter().all(|pipe| !pipe.has_end(number_used)) {
return vec![path];
}
let mut res = vec![];
for (idx, consider) in to_consider.iter().enumerate().filter(|&(_, pipe)| pipe.has_end(number_used)) {
//make a new list to consider with our pipe removed
let mut next_consider = to_consider.clone();
next_consider.swap_remove(idx);
//remove the pipe end we used
let mut consider = consider.clone();
consider.remove_end(number_used);
//all results from lower invokations get accumulated here
res.append(&mut create(consider, next_consider, path.clone()));
}
return res;
}
fn parse(inp: &str) -> Vec<Pipe> {
let lines = inp.trim().lines();
let mut res = vec![];
for line in lines {
let parts = line.split('/');
let unused = parts.map(|num| num.parse().unwrap()).collect::<Vec<_>>();
let pipe = Pipe {
value: unused.iter().sum(),
unused_ends: unused,
};
res.push(pipe);
}
res
} |
use std::cmp::Ordering;
fn count_signs(v: &Vec<i32>) -> Vec<i32> {
let mut negative_count = 0;
let mut neutral_count = 0;
let mut positive_count = 0;
for el in v.iter() {
match el.cmp(&0) {
Ordering::Less => negative_count += 1,
Ordering::Greater => positive_count += 1,
Ordering::Equal => neutral_count += 1,
}
}
let res = vec![negative_count, neutral_count, positive_count];
res
}
fn find_most_freq_sign(v: &Vec<i32>) -> char {
//Since function takes a vector of frequency of numbers with signs
//in a fixed format (neg, neutral, pos), we match indices
//to respective values.
let sign_count = count_signs(v);
if sign_count == [0,0,0] {
//If all frequencies equal zero, return '0' as the most frequent sign.
return '0'
}
println!("tmp: {:?}", sign_count);
match sign_count.iter().position(|&el| &el == sign_count.iter().max().unwrap()) {
Some(0) => '-',
Some(2) => '+',
_ => '0',
}
}
fn main() {
let a = vec![];
println!("Result: {:?}", find_most_freq_sign(&a));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case1() {
let a = vec![];
assert_eq!('0', find_most_freq_sign(&a));
}
#[test]
fn case2() {
let a = vec![1,2,3,4,5];
assert_eq!('+', find_most_freq_sign(&a));
}
#[test]
fn case3() {
let a = vec![-5,-4,-3,-2,-1];
assert_eq!('-', find_most_freq_sign(&a));
}
#[test]
#[should_panic]
fn case4() {
let a = vec![-1,1,-2,2,-3,3];
assert_ne!('-', find_most_freq_sign(&a));
}
} |
pub mod hosting;
mod serving; |
use euclid::default::Point2D;
#[derive(Copy, Clone)]
pub struct GlyphData {
id: u32,
advance: i32,
offset: Point2D<i32>,
}
impl GlyphData {
pub fn new(id: u32, advance: i32, offset_x:i32, offset_y: i32) -> Self {
GlyphData {
id,
advance,
offset: Point2D::new(offset_x, offset_y)
}
}
}
pub struct GlyphStore {
length: i32,
glyphs: Vec<GlyphData>,
}
impl GlyphStore {
pub fn new() -> Self {
GlyphStore {
length: 0,
glyphs: Vec::new(),
}
}
pub fn length(&self) -> i32 {
self.length
}
pub fn add_glyph(&mut self, data: GlyphData) {
self.length += data.advance;
self.glyphs.push(data);
}
} |
#![cfg_attr(not(feature = "std"), no_std)]
use liquid::storage;
use liquid_lang as liquid;
use liquid_lang::InOut;
use liquid_prelude::{string::String, vec::Vec};
#[derive(InOut)]
pub struct TableInfo {
key_column: String,
value_columns: Vec<String>,
}
#[liquid::interface(name = auto)]
mod table_manager {
use super::*;
extern "liquid" {
fn createKVTable(
&mut self,
table_name: String,
key: String,
value_fields: String,
) -> i32;
fn desc(&self, table_name: String) -> TableInfo;
}
}
#[liquid::interface(name = auto)]
mod kv_table {
extern "liquid" {
fn get(&self, key: String) -> (bool, String);
fn set(&mut self, key: String, value: String) -> i32;
}
}
#[liquid::contract]
mod kv_table_test {
use super::{kv_table::*, table_manager::*, *};
#[liquid(storage)]
struct KvTableTest {
table: storage::Value<KvTable>,
tm: storage::Value<TableManager>,
table_name: storage::Value<String>,
}
#[liquid(event)]
struct SetEvent {
count: i32,
}
#[liquid(methods)]
impl KvTableTest {
pub fn new(&mut self) {
self.table_name.initialize(String::from("t_kv_test"));
self.tm
.initialize(TableManager::at("/sys/table_manager".parse().unwrap()));
self.tm.createKVTable(
self.table_name.clone(),
String::from("id"),
String::from("item_name"),
);
self.table
.initialize(KvTable::at("/tables/t_kv_test".parse().unwrap()));
}
pub fn get(&self, id: String) -> (bool, String) {
if let Some((ok, value)) = (*self.table).get(id) {
return (ok, value);
}
return (false, Default::default());
}
pub fn set(&mut self, id: String, item_name: String) -> i32 {
let count = (*self.table).set(id, item_name).unwrap();
self.env().emit(SetEvent {
count: count.clone(),
});
count
}
pub fn desc(&self, table_name: String) -> (String, String) {
let ti = self.tm.desc(table_name).unwrap();
return (ti.key_column, ti.value_columns.get(0).unwrap().clone());
}
}
}
|
use amethyst::core::{Named, Parent};
use amethyst::ecs::prelude::*;
use amethyst_editor_sync::SerializableEntity;
pub use self::biped_entities::*;
pub use self::revolver_entities::*;
mod biped_entities;
mod revolver_entities;
/// Finds the first entity named `name` in the hierarchy starting with `entity`.
///
/// Performs a depth-first search starting with `entity` for a named entity whose name matches
/// `name`. The [`Named`] component is used for determining an entity's name.
///
/// Note that the search includes `entity`, so `entity` will always be returned if its name
/// matches.
pub fn find_named_child<'a>(
entity: Entity,
name: &str,
entities: &Entities<'a>,
names: &ReadStorage<'a, Named>,
parents: &ReadStorage<'a, Parent>,
) -> Option<Entity> {
trace!("Looking for entity named {:?} under {:?}", name, entity);
if let Some(named) = names.get(entity) {
if named.name == name {
trace!("Found name {:?} on {:?}", name, entity);
return Some(entity);
}
}
for (child, parent) in (&**entities, parents).join() {
if parent.entity == entity {
trace!("Descending search into child {:?}", child);
let maybe_result = find_named_child(child, name, entities, names, parents);
if maybe_result.is_some() { return maybe_result; }
}
}
None
}
/// Marker component indicating which entity represents the local player.
///
/// This is primarily used for logic that is specific to the local player, such as reading input,
/// local re-simulation, and updating the first-person camera. In all of these cases, we need
/// a way to identify which player components are associated with the local player. Using
/// `LocalPlayer`, we can join over any components we need and ensure we'll only be modifying
/// ones that are specific to the local player.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct LocalPlayer;
impl Component for LocalPlayer {
type Storage = VecStorage<Self>;
}
/// Component that tracks the entities for the player's head and gun.
///
/// This component will always be attached to the root entity for the player, so it does not
/// list the root entity explicitly.
#[derive(Debug, Clone, Serialize)]
pub struct PlayerEntities {
pub head: SerializableEntity,
pub gun: SerializableEntity,
}
impl Component for PlayerEntities {
type Storage = VecStorage<Self>;
}
/// Component attached to the player's head to indicate the current pitch of the player's
/// viewing angle.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct PlayerPitch {
pub pitch: f32,
}
impl Component for PlayerPitch {
type Storage = VecStorage<Self>;
}
|
use dex::Dex;
use memmap::Mmap;
pub struct DexFileStats {
pub class_count: usize,
pub defined_method_count: usize,
pub referenced_method_count: usize,
}
impl DexFileStats {
pub fn create(dex: Dex<Mmap>) -> DexFileStats {
let mut class_count = 0;
let mut defined_method_count = 0;
let mut referenced_method_count = 0;
for clz_result in dex.classes() {
class_count = class_count + 1;
match clz_result {
Ok(clz) => {
for _method in clz.methods() {
defined_method_count = defined_method_count + 1;
}
}
Err(_) => {}
}
}
for _x in dex.method_ids() {
referenced_method_count = referenced_method_count + 1;
}
DexFileStats {
class_count,
defined_method_count,
referenced_method_count,
}
}
}
|
pub mod stdio;
pub mod mem; |
pub mod assets;
|
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use crate::{
group::Group,
keypair::{KeyPair, SignalKeyPair, SizedBytes},
opaque::*,
rkr_encryption::{RKRCipher as _, RKRCiphertext},
};
use curve25519_dalek::ristretto::RistrettoPoint;
use chacha20poly1305::ChaCha20Poly1305;
use rand_core::{OsRng, RngCore};
use std::convert::TryFrom;
fn random_ristretto_point() -> RistrettoPoint {
let mut rng = OsRng;
let mut bits = [0u8; 64];
rng.fill_bytes(&mut bits);
RistrettoPoint::hash_from_bytes::<sha2::Sha512>(&bits)
}
#[test]
fn client_registration_roundtrip() {
let pw = b"hunter2";
let mut rng = OsRng;
let sc = <RistrettoPoint as Group>::random_scalar(&mut rng);
// serialization order: scalar, password
let mut bytes: Vec<u8> = vec![];
bytes.extend_from_slice(sc.as_bytes());
bytes.extend_from_slice(pw);
let reg = ClientRegistration::<ChaCha20Poly1305, RistrettoPoint>::try_from(&bytes[..]).unwrap();
let reg_bytes = reg.to_bytes();
assert_eq!(reg_bytes, bytes);
}
#[test]
fn server_registration_roundtrip() {
// If we don't have envelope and client_pk, the server registration just
// contains the prf key
let mut rng = OsRng;
let sc = <RistrettoPoint as Group>::random_scalar(&mut rng);
let mut oprf_bytes: Vec<u8> = vec![];
oprf_bytes.extend_from_slice(sc.as_bytes());
let reg = ServerRegistration::<ChaCha20Poly1305, RistrettoPoint, SignalKeyPair>::try_from(
&oprf_bytes[..],
)
.unwrap();
let reg_bytes = reg.to_bytes();
assert_eq!(reg_bytes, oprf_bytes);
// If we do have envelope and client pk, the server registration contains
// the whole kit
let rkr_size = RKRCiphertext::<ChaCha20Poly1305>::rkr_with_nonce_size();
let mut mock_rkr_bytes = vec![0u8; rkr_size];
rng.fill_bytes(&mut mock_rkr_bytes);
println!("{}", mock_rkr_bytes.len());
let mock_client_kp = SignalKeyPair::generate_random(&mut rng).unwrap();
// serialization order: scalar, public key, envelope
let mut bytes = Vec::<u8>::new();
bytes.extend_from_slice(sc.as_bytes());
bytes.extend_from_slice(&mock_client_kp.public().to_arr());
bytes.extend_from_slice(&mock_rkr_bytes);
let reg =
ServerRegistration::<ChaCha20Poly1305, RistrettoPoint, SignalKeyPair>::try_from(&bytes[..])
.unwrap();
let reg_bytes = reg.to_bytes();
assert_eq!(reg_bytes, bytes);
}
#[test]
fn register_first_message_roundtrip() {
let pt = random_ristretto_point();
let pt_bytes = pt.to_bytes();
let r1 = RegisterFirstMessage::<RistrettoPoint>::try_from(pt_bytes.as_slice()).unwrap();
let r1_bytes = r1.to_bytes();
assert_eq!(pt_bytes, r1_bytes);
}
#[test]
fn register_second_message_roundtrip() {
let pt = random_ristretto_point();
let pt_bytes = pt.to_bytes();
let message = pt_bytes.to_vec();
let r2 = RegisterSecondMessage::<RistrettoPoint>::try_from(&message[..]).unwrap();
let r2_bytes = r2.to_bytes();
assert_eq!(message, r2_bytes);
}
#[test]
fn register_third_message_roundtrip() {
let mut rng = OsRng;
let skp = SignalKeyPair::generate_random(&mut rng).unwrap();
let pubkey_bytes = skp.public().to_arr();
let mut encryption_key = [0u8; 32];
rng.fill_bytes(&mut encryption_key);
let mut hmac_key = [0u8; 32];
rng.fill_bytes(&mut hmac_key);
let mut msg = [0u8; 32];
rng.fill_bytes(&mut msg);
let ciphertext = RKRCiphertext::<ChaCha20Poly1305>::encrypt(
&encryption_key,
&hmac_key,
&msg,
&pubkey_bytes,
&mut rng,
)
.unwrap();
let mut message = Vec::new();
message.extend_from_slice(&ciphertext.to_bytes());
message.extend_from_slice(&pubkey_bytes);
let r3 =
RegisterThirdMessage::<ChaCha20Poly1305, SignalKeyPair>::try_from(&message[..]).unwrap();
let r3_bytes = r3.to_bytes();
assert_eq!(message, r3_bytes);
}
|
use std::collections::HashMap;
use std::hash::Hash;
use crate::swapping::{Swapper, SWAPPER_DEFAULT_CAPACITY};
use crate::utils::deque::{Deque, Node, NonNullLink};
pub struct LruSwapper<T> {
list: Deque<T>,
hash: HashMap<T, NonNullLink<T>>,
capacity: usize,
}
impl<T: Hash + Eq + Copy> Default for LruSwapper<T> {
fn default() -> Self {
Self {
list: Deque::new(),
hash: HashMap::new(),
capacity: SWAPPER_DEFAULT_CAPACITY,
}
}
}
impl<T: Hash + Eq + Copy> LruSwapper<T> {
pub fn new() -> Self {
Self::default()
}
}
impl<T: Hash + Eq + Copy> Swapper<T> for LruSwapper<T> {
fn reserve(&mut self, capacity: usize) {
self.capacity = capacity;
}
fn refer(&mut self, page: T) -> Result<(), Option<T>> {
if let Some(node) = self.hash.get(&page) {
self.list.remove_node(node.clone());
self.list.push_node_front(node.clone());
Ok(())
} else {
let mut swapped_page = None;
if self.list.size() == self.capacity {
if let Some(last) = self.list.pop_back() {
self.hash.remove(&last);
swapped_page = Some(last);
}
}
let node = Node::new(page);
self.hash.insert(page, node.clone());
self.list.push_node_front(node);
Err(swapped_page)
}
}
} |
use amethyst::{
{GameDataBuilder, Application},
utils::application_root_dir,
core::TransformBundle,
renderer::{RenderingBundle, RenderToWindow, RenderFlat2D, types::DefaultBackend},
};
use crate::bundle::GameBundle;
use crate::state::game::Game;
use crate::state::title::Title;
use amethyst::ui::{RenderUi, UiBundle};
use amethyst::input::StringBindings;
mod bundle;
mod asset;
mod input;
mod components;
mod state;
mod systems;
mod util;
fn main() -> amethyst::Result<()> {
amethyst::start_logger(Default::default());
let app_root = application_root_dir()?;
let display_config_path = app_root.join("config").join("display.ron");
let assets_dir = app_root.join("assets");
let game_data = GameDataBuilder::default()
.with_bundle(GameBundle)?
.with_bundle(TransformBundle::new())?
.with_bundle(input::bundle::create_input_bundle())?
.with_bundle(UiBundle::<StringBindings>::new())?
.with_bundle(RenderingBundle::<DefaultBackend>::new()
.with_plugin(
RenderToWindow::from_config_path(display_config_path)?.with_clear([0.,0.,0.,1.])
)
.with_plugin(RenderUi::default())
.with_plugin(RenderFlat2D::default())
)?;
Application::new(assets_dir, Title::default(), game_data)?.run();
Ok(())
}
|
use consts::SHUTDOWN;
use specs::*;
use types::*;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use protocol::server::ServerMessage;
use protocol::ServerMessageType;
use protocol::{to_bytes, ServerPacket};
use websocket::OwnedMessage;
use std::process;
#[derive(Default)]
pub struct SignalHandler {
time: Option<Instant>,
}
impl<'a> System<'a> for SignalHandler {
type SystemData = Read<'a, Connections>;
fn run(&mut self, data: Self::SystemData) {
if SHUTDOWN.swap(false, Ordering::Relaxed) {
if self.time.is_none() {
self.time = Some(Instant::now());
let msg = ServerMessage {
duration: 15000,
ty: ServerMessageType::ShutdownMessage,
text: "Server shutting down in 30 seconds!".to_string(),
};
data.send_to_all(OwnedMessage::Binary(
to_bytes(&ServerPacket::ServerMessage(msg)).unwrap(),
));
info!(
target:"server",
"Received interrupt, shutting down in 30s"
);
} else {
info!("Received second interrupt, server shutting down NOW!");
process::exit(0);
}
} else if self.time.is_some() {
let t = self.time.unwrap();
if Instant::now() - t > Duration::from_secs(30) {
process::exit(0);
}
}
}
}
use dispatch::SystemInfo;
impl SystemInfo for SignalHandler {
type Dependencies = ();
fn new() -> Self {
Self::default()
}
fn name() -> &'static str {
concat!(module_path!(), "::", line!())
}
}
|
#[doc = "Reader of register INTR_MASKED"]
pub type R = crate::R<u32, super::INTR_MASKED>;
#[doc = "Reader of field `TIMER_EXPIRED`"]
pub type TIMER_EXPIRED_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Logical and of corresponding request and mask fields."]
#[inline(always)]
pub fn timer_expired(&self) -> TIMER_EXPIRED_R {
TIMER_EXPIRED_R::new((self.bits & 0x01) != 0)
}
}
|
use std::collections::HashMap;
pub fn arith_series_sum(lower_limit: usize, upper_limit: usize, step: usize) -> usize {
let first_element = lower_limit + (step - (lower_limit % step));
let last_element = (upper_limit - 1) - ((upper_limit - 1) % step);
let number_of_elements = ((last_element - first_element) / step) + 1;
number_of_elements * (first_element + last_element) / 2
}
pub fn get_next_fib(fib_n: usize, fibos: &mut Vec<usize>) -> usize {
fibos[fib_n - 1] + fibos[fib_n - 2]
}
pub fn generate_primes(primes: &mut Vec<usize>, n: usize) {
let mut p = vec![true;n];
p[0] = false;
p[1] = false;
for i in 2..n {
let mut j = i * i;
while j < n {
p[j] = false;
j += i;
}
}
for (i, v) in p.iter().enumerate() {
if *v {
primes.push(i);
}
}
}
pub fn is_palindrom(st: &Vec<u8>) -> bool {
let len = st.len();
for v in 0..len / 2 {
if st[v] != st[len - v - 1] {
return false;
}
}
return true;
}
pub fn prime_factorize(temp: usize, primes: &Vec<usize>) -> HashMap<usize, usize> {
let mut n = temp;
let mut freq: HashMap<usize, usize> = HashMap::new();
for i in primes.iter() {
if (*i) * (*i) > temp {
break;
}
if n % *i == 0 {
let mut f = 0_usize;
while n % *i == 0 {
freq.insert(*i, f);
f += 1;
n /= *i;
}
freq.insert(*i, f);
}
}
freq
}
pub fn squares_sum(n: usize) -> usize {
n * (n + 1) * (2 * n + 1) / 6
}
pub fn number_of_divisors(n: usize, primes: &Vec<usize>) -> usize {
let prime_factors = prime_factorize(n, &primes);
let mut nof = 1;
for (_, value) in prime_factors.iter() {
nof *= (*value) + 1;
}
nof
}
|
use crate::mode::Mode;
use crate::PageSpec;
use observer::prelude::*;
use serde::ser::{Serialize, SerializeStructVariant, Serializer};
pub enum Response {
Http(http::response::Response<Vec<u8>>),
Page(PageSpec),
}
#[observed(with_result, namespace = "realm__response")]
pub fn json<T, UD>(in_: &crate::base::In<UD>, data: &T) -> Result<crate::Response, failure::Error>
where
T: serde::Serialize,
UD: crate::UserData,
{
Ok(Response::Http(in_.ctx.response(
serde_json::to_vec_pretty(&json!({
"success": true,
"result": data,
}))?,
)?))
}
#[observed(with_result, namespace = "realm__response")]
pub fn json_with_context<T1, T2, UD>(
in_: &crate::base::In<UD>,
data: &T1,
key: &str,
value: &T2,
) -> Result<crate::Response, failure::Error>
where
T1: serde::Serialize,
T2: serde::Serialize,
UD: crate::UserData,
{
let context = if crate::base::is_test() {
json!({
"key": key,
"value": value
})
} else {
serde_json::Value::Null
};
Ok(Response::Http(in_.ctx.response(
serde_json::to_vec_pretty(&json!({
"success": true,
"result": data,
"context": context
}))?,
)?))
}
impl Response {
pub fn with_url(self, url: String) -> Response {
match self {
Response::Http(r) => Response::Http(r),
Response::Page(s) => Response::Page(s.with_url(url)),
}
}
pub fn with_replace(self, url: String) -> Response {
match self {
Response::Http(r) => Response::Http(r),
Response::Page(s) => Response::Page(s.with_replace(url)),
}
}
pub fn with_default_url(self, url: String) -> Response {
match self {
Response::Http(r) => Response::Http(r),
Response::Page(s) => Response::Page(s.with_default_url(url)),
}
}
pub fn render(
self,
ctx: &crate::Context,
mode: &Mode,
url: &str,
) -> std::result::Result<http::Response<Vec<u8>>, failure::Error> {
if let Response::Http(r) = self {
return Ok(r);
};
let r = self.with_default_url(url.to_string());
match &r {
Response::Page(spec) => {
ctx.header(http::header::CONTENT_TYPE, mode.content_type());
Ok(ctx.response(match mode {
Mode::API => serde_json::to_string_pretty(&spec.config)?.into(),
Mode::HTML => spec.render(ctx.is_crawler())?,
Mode::HTMLExplicit => spec.render(false)?,
Mode::SSR => spec.render(true)?,
Mode::Layout => serde_json::to_string_pretty(&spec)?.into(),
Mode::Submit => serde_json::to_string_pretty(&json!({
"success": true,
"result": {
"kind": "navigate",
"data": spec,
}
}))?
.into(),
})?)
}
Response::Http(_) => unreachable!(),
}
}
pub fn err<T, UD>(
in_: &crate::base::In<UD>,
message: T,
) -> Result<crate::Response, failure::Error>
where
T: Into<String>,
UD: crate::UserData,
{
Ok(Response::Http(in_.ctx.response(
serde_json::to_vec_pretty(&json!({
"success": false,
"error": message.into(),
}))?,
)?))
}
pub fn plain(
ctx: &crate::Context,
resp: String,
status: http::StatusCode,
) -> Result<crate::Response, failure::Error> {
ctx.status(status);
Ok(Response::Http(ctx.response(resp.into_bytes())?))
}
pub fn redirect<T, UD>(
in_: &crate::base::In<UD>,
next: T,
) -> Result<crate::Response, failure::Error>
where
T: Into<String>,
UD: crate::UserData,
{
use http::header;
match in_.get_mode() {
Mode::Layout => Ok(Response::Page(PageSpec {
id: "".to_owned(),
config: json!({}),
title: "".to_owned(),
url: None,
replace: None,
redirect: Some(next.into()),
rendered: "".to_string(),
})),
_ => {
in_.ctx.header(header::LOCATION, next.into());
in_.ctx.status(http::StatusCode::TEMPORARY_REDIRECT);
Ok(Response::Http(in_.ctx.response("".into())?))
}
}
}
pub fn redirect_with<T, UD>(
in_: &crate::base::In<UD>,
next: T,
status: http::StatusCode,
) -> Result<crate::Response, failure::Error>
where
T: Into<String>,
UD: crate::UserData,
{
use http::header;
match in_.get_mode() {
Mode::Layout => Ok(Response::Page(PageSpec {
id: "".to_owned(),
config: json!({}),
title: "".to_owned(),
url: None,
replace: None,
redirect: Some(next.into()),
rendered: "".to_string(),
})),
_ => {
in_.ctx.header(header::LOCATION, next.into());
in_.ctx.status(status);
Ok(Response::Http(in_.ctx.response("".into())?))
}
}
}
}
impl Serialize for Response {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match *self {
Response::Http(ref s) => {
let mut resp = serializer.serialize_struct_variant("Response", 0, "Http", 0)?;
resp.serialize_field("status", &s.status().as_u16())?;
// TODO: headers
let body = std::str::from_utf8(s.body())
.map(|v| v.to_string())
.unwrap_or_else(|_| format!("{:?}", s.body()));
resp.serialize_field("body", &body)?;
resp.end()
}
Response::Page(ref p) => {
serializer.serialize_newtype_variant("Response", 1, "PageSpec", p)
}
}
}
}
#[cfg(test)]
mod tests {
use crate::PageSpec;
use http::Response as HttpResponse;
use serde_json::Value::Null;
#[test]
fn test_http_resp_default() {
let http_resp = HttpResponse::default();
let r = super::Response::Http(http_resp);
assert_eq!(
serde_json::to_value(r).unwrap(),
json!({
"Http": {
"body": "",
"status": 200
}
})
);
}
#[test]
fn test_http_resp_with_body() {
let http_resp = HttpResponse::new("hello world".into());
let r = super::Response::Http(http_resp);
assert_eq!(
serde_json::to_value(r).unwrap(),
json!({
"Http": {
"body": "hello world",
"status": 200
}
})
);
}
#[test]
fn test_page_spec() {
let page_spec = PageSpec {
id: "test-id".into(),
config: json!({}),
title: "test-title".into(),
url: None,
replace: None,
redirect: None,
rendered: "empty.html".to_string(),
};
let r = super::Response::Page(page_spec);
assert_eq!(
serde_json::to_value(r).unwrap(),
json!({
"PageSpec": {
"id": "test-id",
"config": json!({}),
"title": "test-title",
"url": Null,
"replace": Null,
"redirect": Null
}
})
);
}
}
|
#[doc = "Reader of register TIMx_AF1"]
pub type R = crate::R<u32, super::TIMX_AF1>;
#[doc = "Writer for register TIMx_AF1"]
pub type W = crate::W<u32, super::TIMX_AF1>;
#[doc = "Register TIMx_AF1 `reset()`'s with value 0x01"]
impl crate::ResetValue for super::TIMX_AF1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x01
}
}
#[doc = "Reader of field `BKINE`"]
pub type BKINE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BKINE`"]
pub struct BKINE_W<'a> {
w: &'a mut W,
}
impl<'a> BKINE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `BKDF1BK2E`"]
pub type BKDF1BK2E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BKDF1BK2E`"]
pub struct BKDF1BK2E_W<'a> {
w: &'a mut W,
}
impl<'a> BKDF1BK2E_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 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `BKINP`"]
pub type BKINP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BKINP`"]
pub struct BKINP_W<'a> {
w: &'a mut W,
}
impl<'a> BKINP_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 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
impl R {
#[doc = "Bit 0 - BKINE"]
#[inline(always)]
pub fn bkine(&self) -> BKINE_R {
BKINE_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 8 - BKDF1BK2E"]
#[inline(always)]
pub fn bkdf1bk2e(&self) -> BKDF1BK2E_R {
BKDF1BK2E_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - BKINP"]
#[inline(always)]
pub fn bkinp(&self) -> BKINP_R {
BKINP_R::new(((self.bits >> 9) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - BKINE"]
#[inline(always)]
pub fn bkine(&mut self) -> BKINE_W {
BKINE_W { w: self }
}
#[doc = "Bit 8 - BKDF1BK2E"]
#[inline(always)]
pub fn bkdf1bk2e(&mut self) -> BKDF1BK2E_W {
BKDF1BK2E_W { w: self }
}
#[doc = "Bit 9 - BKINP"]
#[inline(always)]
pub fn bkinp(&mut self) -> BKINP_W {
BKINP_W { w: self }
}
}
|
mod sender;
use actix_web::HttpResponse;
use drogue_client::{registry, Translator};
use drogue_cloud_endpoint_common::{
error::HttpEndpointError,
sender::{Publish, PublishOptions, Publisher, UpstreamSender},
sink::Sink,
};
use serde::Deserialize;
#[derive(Deserialize)]
pub struct CommandOptions {
pub application: String,
pub device: String,
pub command: String,
}
pub async fn process_command<S>(
application: registry::v1::Application,
device: registry::v1::Device,
gateways: Vec<registry::v1::Device>,
sender: &UpstreamSender<S>,
client: reqwest::Client,
content_type: Option<String>,
opts: CommandOptions,
body: bytes::Bytes,
) -> Result<HttpResponse, HttpEndpointError>
where
S: Sink,
{
if !device.attribute::<registry::v1::DeviceEnabled>() {
return Ok(HttpResponse::NotAcceptable().finish());
}
for gateway in gateways {
if !gateway.attribute::<registry::v1::DeviceEnabled>() {
continue;
}
if let Some(command) = gateway.attribute::<registry::v1::Commands>().pop() {
return match command {
registry::v1::Command::External(endpoint) => {
log::debug!("Sending to external command endpoint {:?}", endpoint);
let ctx = sender::Context {
device_id: device.metadata.name,
client,
};
match sender::send_to_external(ctx, endpoint, opts, body).await {
Ok(_) => Ok(HttpResponse::Ok().finish()),
Err(err) => {
log::info!("Failed to process external command: {}", err);
Ok(HttpResponse::NotAcceptable().finish())
}
}
}
};
}
}
// no hits so far
sender
.publish_http_default(
Publish {
channel: opts.command,
application: &application,
device_id: opts.device,
options: PublishOptions {
topic: None,
content_type,
..Default::default()
},
},
body,
)
.await
}
|
use crate::{fragment::Bounds, util, Cell, Point};
use nalgebra::Point2;
use parry2d::shape::{ConvexPolygon, Polyline};
use std::{
cmp::Ordering,
fmt,
hash::{Hash, Hasher},
};
use sauron::{
html::attributes::*,
svg::{attributes::*, *},
Node,
};
/// TODO: Add an is_broken field when there is a presence of `~` or `!` in the span
#[derive(Debug, Clone)]
pub struct Circle {
pub radius: f32,
pub center: Point,
pub is_filled: bool,
}
impl Hash for Circle {
fn hash<H: Hasher>(&self, state: &mut H) {
((self.radius * 2.0) as i32).hash(state);
}
}
impl Circle {
pub(crate) fn new(center: Point, radius: f32, is_filled: bool) -> Self {
Circle {
center,
radius,
is_filled,
}
}
/// the top most point of this circle for sorting.
/// center.y - radius
fn top_left_bound(&self) -> Point {
Point::new(self.center.x - self.radius, self.center.y - self.radius)
}
fn top_right_bound(&self) -> Point {
Point::new(self.center.x + self.radius, self.center.y - self.radius)
}
fn bottom_right_bound(&self) -> Point {
Point::new(self.center.x + self.radius, self.center.y + self.radius)
}
fn bottom_left_bound(&self) -> Point {
Point::new(self.center.x - self.radius, self.center.y + self.radius)
}
/// offset the circles parameter from the arg cell
pub(crate) fn absolute_position(&self, cell: Cell) -> Self {
Circle {
center: cell.absolute_position(self.center),
..*self
}
}
pub fn scale(&self, scale: f32) -> Self {
Circle {
center: self.center.scale(scale),
radius: self.radius * scale,
..*self
}
}
}
impl Bounds for Circle {
fn bounds(&self) -> (Point, Point) {
(self.top_left_bound(), self.bottom_right_bound())
}
}
impl fmt::Display for Circle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "C {} {}", self.center, self.radius)
}
}
impl<MSG> From<Circle> for Node<MSG> {
fn from(c: Circle) -> Node<MSG> {
circle(
[
cx(c.center.x),
cy(c.center.y),
r(c.radius),
classes_flag([
("filled", c.is_filled),
("nofill", !c.is_filled),
]),
],
[],
)
}
}
impl Eq for Circle {}
///This is needed since circle contains radius which is an f32 which rust doesn't provide trait
///implementation for Eq
impl Ord for Circle {
fn cmp(&self, other: &Self) -> Ordering {
self.mins()
.cmp(&other.mins())
.then(self.maxs().cmp(&other.maxs()))
.then(util::ord(self.radius, other.radius))
.then(self.is_filled.cmp(&other.is_filled))
}
}
impl PartialOrd for Circle {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Circle {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl From<Circle> for Polyline {
fn from(c: Circle) -> Polyline {
let points: Vec<Point2<f32>> = extract_circle_points(c.radius, 64)
.into_iter()
.map(|p| Point2::new(p.x + c.center.x, p.y + c.center.y))
.collect();
Polyline::new(points, None)
}
}
impl From<Circle> for ConvexPolygon {
fn from(c: Circle) -> ConvexPolygon {
let points: Vec<Point2<f32>> = extract_circle_points(c.radius, 64)
.into_iter()
.map(|p| Point2::new(p.x + c.center.x, p.y + c.center.y))
.collect();
ConvexPolygon::from_convex_polyline(points)
.expect("must create a convex polygon")
}
}
fn extract_circle_points(radius: f32, nsubdivs: u32) -> Vec<Point> {
let two_pi = std::f32::consts::TAU;
let dtheta = two_pi / nsubdivs as f32;
push_xy_arc(radius, nsubdivs, dtheta)
}
/// Pushes a discretized counterclockwise circle to a buffer.
/// The circle is contained on the plane spanned by the `x` and `y` axis.
fn push_xy_arc(radius: f32, nsubdiv: u32, dtheta: f32) -> Vec<Point> {
let mut out: Vec<Point> = vec![];
let mut curr_theta: f32 = 0.0;
for _ in 0..nsubdiv {
let x = curr_theta.cos() * radius;
let y = curr_theta.sin() * radius;
out.push(Point::new(x, y));
curr_theta += dtheta;
}
out
}
|
use failure::Fail;
#[derive(Debug, Fail)]
pub enum Ja3Error {
#[fail(display = "Not a TLS handshake packet")]
NotHandshake,
#[fail(display = "Parsing error")]
ParseError,
}
|
mod encoded;
mod hdrval;
pub use self::encoded::Encoded;
pub use self::hdrval::HdrVal;
|
#![allow(non_snake_case)]
#![allow(dead_code)]
//! Module for Board and BoardBuilder structs
//!
//! Use [BoardBuilder](struct.BoardBuilder.html) struct to initialize the [Board](struct.Board.html) struct,
//! and use [Board](struct.Board.html) struct to manipulate GPIO Pins.
use crate::mailbox;
use libc;
use std::ptr;
use std::mem::size_of;
use std::ffi::CString;
use core::ffi::c_void;
use std::thread::sleep;
use std::time::Duration;
use std::io::{Error, ErrorKind};
use std::fs;
use volatile_register::RW;
/// = 32. The highest gpio we can address.
pub const MAX_CHANNELS: usize = 32;
/// = 9. Default number of channels.
pub const DEFAULT_NUM_CHANNELS: usize = 9;
/// [4, 17, 18, 27, 21, 22, 23, 24, 25]. 9 default GPIO pins on pi.
pub static DEFAULT_PINS: [u8; MAX_CHANNELS] = [
4, // P1-7
17, // P1-11
18, // P1-12
27, // P1-13
21, // P1-40
22, // P1-15
23, // P1-16
24, // P1-18
25, // P1-22
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 //empty possible channels
];
/// [6, 28, 29, 30, 31, 40, 45, 46, 47, 48, 49, 50, 51, 52, 53]. List of reserved GPIO pins
pub static BANNED_PINS: [u8; 15] = [
6, // On Model B, it is in use for the Ethernet function
28, // board ID and are connected to resistors R3 to R10 (only on Rev1.0 boards).
29, // board ID and are connected to resistors R3 to R10 (only on Rev1.0 boards).
30, // board ID and are connected to resistors R3 to R10 (only on Rev1.0 boards).
31, // board ID and are connected to resistors R3 to R10 (only on Rev1.0 boards).
40, // used by analogue audio
45, // used by analogue audio
46, // HDMI hotplug detect
47, // 47 to 53 are used by the SD card interface.
48,
49,
50,
51,
52,
53,
];
const DEVFILE_MBOX: &str = "/dev/pi_gpio_mbox";
const DEVFILE_VCIO: &str = "/dev/vcio";
const PAGE_SIZE: usize = 4096;
const PAGE_SHIFT: usize = 12;
/// = 2000. Default period of the PWM signal.
pub const DEFAULT_CYCLE_TIME: usize = 2000;
/// = 10. Pulse width increment granularity.
///
/// Setting SAMPLE_DELAY too low will likely cause problems as the DMA controller
/// will use too much memory bandwidth.
/// 10 is a good value, though you might be ok setting it as low as 2.
pub const DEFAULT_SAMPLE_DELAY: usize = 10;
/// = 500. Default value for pwm div.
///
/// PWM runs at the frequency of 500 MHz.
/// So setting this as 500 will give us 500MHz/500 = 1 MHz.
/// You can change this configuration with [BoardBuilder::divide_pwm(mut self, divisor)](struct.BoardBuilder.html#method.divide_pwm: usize)
pub const DEFAULT_PWM_DIVISOR: usize = 500;
/// = DEFAULT_CYCLE_TIME/DEFAULT_SAMPLE_DELAY = 200. Number of samples.
pub const NUM_SAMPLES: usize = DEFAULT_CYCLE_TIME as usize/DEFAULT_SAMPLE_DELAY;
/// = NUM_SAMPLES * 2 = 400. Number of Control Blocks.
///
/// This is how much memory that will be allocated for control blocks.
/// Setting a different number for cycle time ([BoardBuilder::set_cycle_time](struct.BoardBuilder.html#method.set_cycle_time))
/// and setting a different number of sample delay ([BoardBuilder::set_sample_delay](struct.BoardBuilder.html#method.set_sample_delay))
/// will still allocate memory for 400 control blocks, but will only initialize (cycle_time/sample_delay) control blocks.
pub const NUM_CBS: usize = NUM_SAMPLES*2;
const DMA_NO_WIDE_BURSTS: usize = 1<<26;
const DMA_WAIT_RESP: usize = 1<<3;
const DMA_D_DREQ: usize = 1<<6;
fn DMA_PER_MAP(x: usize) -> usize{
x << 16
}
const DMA_END: usize = 1<<1;
const DMA_RESET: usize = 1<<31;
const DMA_INT: usize = 1<<2;
const DMA_CS: usize = 0x00/4;
const DMA_CONBLK_AD: usize = 0x04/4;
const DMA_DEBUG: usize = 0x20/4;
const GPIO_FSEL0: usize = 0x00/4;
const GPIO_SET0: usize = 0x1c/4;
const GPIO_CLR0: usize = 0x28/4;
const GPIO_LEV0: usize = 0x34/4;
const GPIO_PULLEN: usize = 0x94/4;
const GPIO_PULLCLK: usize = 0x98/4;
const GPIO_MODE_IN: usize = 0;
const GPIO_MODE_OUT: usize = 1;
const PWM_CTL: usize = 0x00/4;
const PWM_DMAC: usize = 0x08/4;
const PWM_RNG1: usize = 0x10/4;
const PWM_FIFO: usize = 0x18/4;
const PWMCLK_CNTL: usize = 40;
const PWMCLK_DIV: usize = 41;
const PWMCTL_MODE1: usize = 1<<1;
const PWMCTL_PWEN1: usize = 1<<0;
const PWMCTL_CLRF: usize = 1<<6;
const PWMCTL_USEF1: usize = 1<<5;
const PWMDMAC_ENAB: usize = 1<<31;
const PWMDMAC_THRSHLD: usize = (15<<8)|(15<<0);
const PCM_CS_A: usize = 0x00/4;
const PCM_FIFO_A: usize = 0x04/4;
const PCM_MODE_A: usize = 0x08/4;
const PCM_RXC_A: usize = 0x0c/4;
const PCM_TXC_A: usize = 0x10/4;
const PCM_DREQ_A: usize = 0x14/4;
const PCM_INTEN_A: usize = 0x18/4;
const PCM_INT_STC_A: usize = 0x1c/4;
const PCM_GRAY: usize = 0x20/4;
const PCMCLK_CNTL: usize = 38;
const PCMCLK_DIV: usize = 39;
/// Indicates using PWM
pub const DELAY_VIA_PWM: u8 = 0;
/// Indicates using PCM
pub const DELAY_VIA_PCM: u8 = 1;
/* New Board Revision format:
SRRR MMMM PPPP TTTT TTTT VVVV
S scheme (0=old, 1=new)
R RAM (0=256, 1=512, 2=1024)
M manufacturer (0='SONY',1='EGOMAN',2='EMBEST',3='UNKNOWN',4='EMBEST')
P processor (0=2835, 1=2836)
T type (0='A', 1='B', 2='A+', 3='B+', 4='Pi 2 B', 5='Alpha', 6='Compute Module')
V revision (0-15)
*/
const BOARD_REVISION_SCHEME_MASK: usize = 0x1 << 23;
const BOARD_REVISION_SCHEME_OLD: usize = 0x0 << 23;
const BOARD_REVISION_SCHEME_NEW: usize = 0x1 << 23;
const BOARD_REVISION_RAM_MASK: usize = 0x7 << 20;
const BOARD_REVISION_MANUFACTURER_MASK: usize = 0xF << 16;
const BOARD_REVISION_MANUFACTURER_SONY: usize = 0 << 16;
const BOARD_REVISION_MANUFACTURER_EGOMAN: usize = 1 << 16;
const BOARD_REVISION_MANUFACTURER_EMBEST: usize = 2 << 16;
const BOARD_REVISION_MANUFACTURER_UNKNOWN: usize = 3 << 16;
const BOARD_REVISION_MANUFACTURER_EMBEST2: usize = 4 << 16;
const BOARD_REVISION_PROCESSOR_MASK: usize = 0xF << 12;
const BOARD_REVISION_PROCESSOR_2835: usize = 0 << 12;
const BOARD_REVISION_PROCESSOR_2836: usize = 1 << 12;
const BOARD_REVISION_TYPE_MASK: usize = 0xFF << 4;
const BOARD_REVISION_TYPE_PI1_A: usize = 0 << 4;
const BOARD_REVISION_TYPE_PI1_B: usize = 1 << 4;
const BOARD_REVISION_TYPE_PI1_A_PLUS: usize = 2 << 4;
const BOARD_REVISION_TYPE_PI1_B_PLUS: usize = 3 << 4;
const BOARD_REVISION_TYPE_PI2_B: usize = 4 << 4;
const BOARD_REVISION_TYPE_ALPHA: usize = 5 << 4;
const BOARD_REVISION_TYPE_PI3_B: usize = 8 << 4;
const BOARD_REVISION_TYPE_PI3_BP: usize = 0xD << 4;
const BOARD_REVISION_TYPE_CM: usize = 6 << 4;
const BOARD_REVISION_TYPE_CM3: usize = 10 << 4;
const BOARD_REVISION_REV_MASK: usize = 0xF;
fn BUS_TO_PHYS(x: usize) -> usize {
x & (!0xC0000000)
}
const DMA_CHAN_SIZE: usize = 0x100; /* size of register space for a single DMA channel */
const DMA_CHAN_MAX: usize = 14; // number of DMA Channels we have... actually, there are 15... but channel fifteen is mapped at a different DMA_BASE, so we leave that one alone
const DMA_CHAN_NUM: usize = 14; // the DMA Channel we are using, NOTE: DMA Ch 0 seems to be used by X... better not use it ;)
const PWM_BASE_OFFSET: usize = 0x0020c000;
const PWM_LEN: usize = 0x28;
const CLK_BASE_OFFSET: usize = 0x00101000;
const CLK_LEN: usize = 0xA8;
const GPIO_BASE_OFFSET: usize = 0x00200000;
const GPIO_LEN: usize = 0x100;
const PCM_BASE_OFFSET: usize = 0x00203000;
const PCM_LEN: usize = 0x24;
// DMA Control Block
struct DmaCbT {
info: RW<usize>,
src: RW<usize>,
dst: RW<usize>,
length: RW<usize>,
stride: RW<usize>,
next: RW<usize>,
_pad: [usize; 2],
}
// DMA Controller
struct Ctl {
sample: [RW<usize>; NUM_SAMPLES],
cb: [DmaCbT; NUM_CBS],
}
// MailBox
struct Mbox {
handle: i32, // from mbox_open()
mem_ref: usize, // from mem_allox()
bus_addr: usize, // from mem_lock()
virt_addr: *mut c_void // from mapmem()
}
impl Mbox {
fn new(handle: i32, mem_ref: usize, bus_addr: usize, virt_addr: *mut c_void) -> Self {
Mbox{handle, mem_ref, bus_addr, virt_addr}
}
}
/// Struct for initialzing [Board](struct.Board.html) and configuring the settings.
///
/// BoardBuilder is the only way to initialize Board struct.
/// You can configure different settings for DMA and PWM using this struct.
///
/// # Examples
/// ## Building with default settings
///
/// ```no_run
/// use dma_gpio::pi::BoardBuilder;
///
/// fn main() {
/// let mut board = BoardBuilder::new().build().unwrap();
///
/// ...
///
/// }
///
/// ```
///
/// This example will enable 9 pins (4, 17, 18, 27, 21, 22, 23, 24, 25) for use.
///
/// PWM clock will run at 500MHz/500 = 1 MHz.
///
/// Each cycle will be 2000/1MHz = 2000 us.
///
/// Sample Delay will be 10/1MHz = 10 us.
///
/// This will create 2000/10 = 200 samples, and 200*2 = 400 Control Blocks.
///
/// This means that PWM can have 0.005 (0.5 %) increment from 0.00 (0 %) to 1.00 (100 %),
/// with each delay taking 10 us per sample.
///
/// Overall GPIO frequency will be 1/2000us = 500 Hz
///
/// ## Building with custom settings
///
/// ```no_run
/// use dma_gpio::pi::BoardBuilder;
///
/// fn main() {
/// let mut board = BoardBuilder::new()
/// .divide_pwm(50)
/// .set_cycle_time(400)
/// .set_sample_delay(2)
/// .build_with_pins(vec![21, 22]).unwrap();
///
/// ...
///
/// }
///
/// ```
///
/// This example will enable 2 pins (21, 22) for use.
///
/// PWM clock will run at 500MHz/50 = 10 MHz.
///
/// Each cycle will be 400/10MHz = 40 us.
///
/// Sample Delay will be 2/10MHz = 0.2 us.
///
/// This will create 400/2 = 200 samples, and 200*2 = 400 Control Blocks.
///
/// This means that PWM can have 0.005 (5 %) increment from 0.00 (0 %) to 1.00 (100 %),
/// with each delay taking 0.2 us per sample.
///
/// Theoratical GPIO frequency will be 1/40us = 25 KHz.
///
/// However, because the limiting speed of DMA is around ~1.6 MHz,
///
/// the actual frequency will be around 8 KHz with PWM (1.6 MHz/200 Samples).
pub struct BoardBuilder {
known_pins: [u8; MAX_CHANNELS],
num_channels: usize,
delay_hw: u8,
pwm_divisor: usize,
cycle_time: usize,
sample_delay: usize,
}
impl BoardBuilder {
/// Creates new instance of BoardBuilder.
pub fn new() -> Self {
BoardBuilder{
delay_hw: DELAY_VIA_PWM,
known_pins: DEFAULT_PINS,
num_channels: DEFAULT_NUM_CHANNELS,
pwm_divisor: DEFAULT_PWM_DIVISOR,
cycle_time: DEFAULT_CYCLE_TIME,
sample_delay: DEFAULT_SAMPLE_DELAY,
}
}
/// Builds and returns Result<[Board](struct.Board.html)>.
///
/// ## Example
/// ```no_run
/// ...
///
/// fn main() {
/// let mut board = BoardBuilder::new().build().unwrap();
///
/// ...
///
/// }
/// ```
pub fn build(&self) -> Result<Board, Error> {
Board::new(self.delay_hw, self.known_pins, self.num_channels, self.pwm_divisor, self.cycle_time, self.sample_delay)
}
/// Builds and returns Result<[Board](struct.Board.html)> with specific pins.
///
/// Be sure to look out for banned pins: [6, 28, 29, 30, 31, 40, 45, 46, 47, 48, 49, 50, 51, 52, 53]
///
/// ## Example
/// ```no_run
/// ...
///
/// fn main() {
/// let mut board = BoardBuilder::new().build_with_pins(vec![21, 22]).unwrap();
///
/// ...
///
/// }
/// ```
pub fn build_with_pins(mut self, pins: Vec<u8>) -> Result<Board, Error> {
let pins: Vec<u8> = pins.iter().filter(|&&pin| pin > 0).map(|&pin| pin).collect();
let pins_len = pins.len();
let mut temp_pins = [0; MAX_CHANNELS];
if pins_len <= MAX_CHANNELS {
for i in 0..pins_len {
if pins[i] >= MAX_CHANNELS as u8 {
let error = format!("ERROR: {:} is an invalid gpio\n", pins[i]);
error!("{}", error);
return Err(Error::new(ErrorKind::Other, error))
}else if is_banned_pin(pins[i]){
let error = format!("ERROR: {:} is a banned gpio\nBanned pins: {:?}", pins[i], BANNED_PINS);
error!("{}", error);
return Err(Error::new(ErrorKind::Other, error))
}else{
temp_pins[i] = pins[i];
}
}
}else {
let error = format!("ERROR: number of pins {} exceeds max number of channels: {}\n", pins_len, MAX_CHANNELS);
error!("{}", error);
return Err(Error::new(ErrorKind::Other, error))
}
self.num_channels = pins_len;
self.known_pins = temp_pins;
self.build()
}
/// Use pcm instead of pwm for dma scheduling
///
/// ## Example
/// ```no_run
/// ...
///
/// fn main() {
/// let mut board = BoardBuilder::new().use_pcm().build().unwrap();
///
/// ...
///
/// }
/// ```
pub fn use_pcm(mut self) -> Self {
self.delay_hw = DELAY_VIA_PCM;
self
}
/// Set value for PWM DIV.
///
/// See this [example](struct.BoardBuilder.html#building-with-custom-settings) for more details on how it works.
/// ## Example
/// value of 50 will give 500MHz/50 = 10 MHz frequency of PWM clock.
/// ```no_run
/// ...
///
/// fn main() {
/// let mut board = BoardBuilder::new().divide_pwm(50).build().unwrap();
///
/// ...
///
/// }
/// ```
///
pub fn divide_pwm(mut self, divisor: usize) -> Self {
if divisor > 1000 {
self.pwm_divisor = 1000;
}else {
self.pwm_divisor = divisor;
}
self
}
/// Set cycle time.
///
/// See this [example](struct.BoardBuilder.html#building-with-custom-settings) for more details on how it works.
///
/// ## Example
/// ```no_run
/// ...
///
/// fn main() {
/// let mut board = BoardBuilder::new()
/// .set_cycle_time(400)
/// .set_sample_delay(20)
/// .build().unwrap();
///
/// ...
///
/// }
/// ```
pub fn set_cycle_time(mut self, units: usize) -> Self {
if units < 200{
self.cycle_time = 200;
}else if units > 1000 {
self.cycle_time = 1000;
}else {
self.cycle_time = units;
}
self
}
/// Set sample delay.
///
/// See this [example](struct.BoardBuilder.html#building-with-custom-settings) for more details on how it works.
///
/// ## Example
/// ```no_run
/// ...
///
/// fn main() {
/// let mut board = BoardBuilder::new()
/// .set_cycle_time(400)
/// .set_sample_delay(20)
/// .build().unwrap();
///
/// ...
///
/// }
/// ```
pub fn set_sample_delay(mut self, units: usize) -> Self {
if units == 0 {
self.sample_delay = 1;
}else if units > 100{
self.sample_delay = 100;
}else {
self.sample_delay = units;
}
self
}
}
/// Struct for dealing with GPIO Pins.
///
/// Board is initialized through [BoardBuilder](struct.BoardBuilder.html).
///
/// Note that you can only manipulate pins that are set from BoardBuilder,
///
/// so if the pin you want to access is not one of the default pins: [4, 17, 18, 27, 21, 22, 23, 24, 25], make sure to set it with [BoardBuilder::build_with_pins](struct.BoardBuilder.html#method.build_with_pins).
///
/// ## Example
/// This example uses pins [21, 22, 23],
///
/// sets pin 21 to 25%, pin 22 to 50%, and pin 23 to 75%,
///
/// then, after 1 second, releases pin 22,
///
/// then, after 1 second, release all pins.
///
/// ```no_run
/// use std::thread::sleep;
/// use std::time::Duration;
/// use dma_gpio::pi::BoardBuilder;
///
/// fn main() {
/// let mut board = BoardBuilder::new().build_with_pins(vec![21, 22, 23]).unwrap();
/// board.print_info();
///
/// board.set_pwm(21, 0.25).unwrap();
/// board.set_pwm(22, 0.50).unwrap();
/// board.set_pwm(23, 0.75).unwrap();
///
/// let sec = Duration::from_millis(1000);
/// sleep(millis);
///
/// board.release_pwm(22).unwrap();
///
/// sleep(millis);
///
/// board.release_all_pwm().unwrap();
///
/// }
///
/// ```
pub struct Board {
pwm_divisor: usize,
cycle_time: usize,
sample_delay: usize,
num_pages: usize,
num_samples: usize,
// pi version specific addresses
dma_base: usize,
_pwm_base: usize,
pwm_phys_base: usize,
_clk_base: usize,
_gpio_base: usize,
gpio_phys_base: usize,
_pcm_base: usize,
pcm_phys_base: usize,
_dma_virt_base: *const [RW<usize>;DMA_CHAN_SIZE/4], // base address of all DMA Channels
dma_reg: *const [RW<usize>; DMA_CHAN_SIZE/4], // pointer to the DMA Channel registers we are using
pwm_reg: *const [RW<usize>; PWM_LEN/4],
pcm_reg: *const [RW<usize>; PCM_LEN/4],
clk_reg: *const [RW<usize>; CLK_LEN/4],
gpio_reg: *const [RW<usize>; GPIO_LEN/4],
known_pins: [u8; MAX_CHANNELS],
num_channels: usize,
channel_pwm: [f32; MAX_CHANNELS],
// pin2gpio array is not setup as empty to avoid locking all GPIO
// inputs as PWM, they are set on the fly by the pin param passed.
pin2gpio: [u8;MAX_CHANNELS],
mbox: Mbox,
delay_hw: u8,
invert_mode: bool,
}
impl Drop for Board {
fn drop(&mut self) {
self.terminate();
}
}
impl Board {
// open a char device file used for communicating with kernel mbox driver
fn mbox_open() -> Result<i32, Error> {
// try to use /dev/vcio first (kernel 4.1+)
let dev_vcio = CString::new(DEVFILE_VCIO).unwrap().into_bytes_with_nul();
match unsafe { libc::open(dev_vcio.as_ptr() as *const u8, 0) }{
fd if fd < 0 => {
// initialize mbox
let dev_mbox = CString::new(DEVFILE_MBOX).unwrap().into_bytes_with_nul();
let mbox_ptr = dev_mbox.as_ptr();
match fs::remove_file(DEVFILE_MBOX){
Ok(_) => (),
Err(e) => return Err(e),
}
if unsafe { libc::mknod(mbox_ptr, libc::S_IFCHR | 0600, libc::makedev(mailbox::MAJOR_NUM as u32, 0)) } < 0 {
error!("failed to create mailbox device");
return Err(Error::new(ErrorKind::Other, "failed to create mailbox device"))
}
match unsafe{ libc::open(mbox_ptr, 0) }{
fdd if fdd < 0 => {
error!("can't open device file: {:?}", DEVFILE_MBOX);
Err(Error::new(ErrorKind::Other, format!("can't open device file: {:?}", DEVFILE_MBOX)))
},
fdd => Ok(fdd)
}
},
fd => Ok(fd)
}
}
fn mbox_close(file_desc: i32) -> Result<(), Error> {
match unsafe {libc::close(file_desc) }{
0 => Ok(()),
_ => {
error!("closing mbox failed.");
Err(Error::new(ErrorKind::Other, "closing mbox failed."))
},
}
}
// determine which pi model we're running on
fn get_model(mbox_board_rev: usize) -> Result<(usize, usize, usize), Error> {
let board_model = if (mbox_board_rev & BOARD_REVISION_SCHEME_MASK) == BOARD_REVISION_SCHEME_NEW {
match mbox_board_rev & BOARD_REVISION_TYPE_MASK {
BOARD_REVISION_TYPE_PI2_B => 2,
BOARD_REVISION_TYPE_PI3_B | BOARD_REVISION_TYPE_PI3_BP | BOARD_REVISION_TYPE_CM3 => 3,
_ => 1,
}
}else {
1
};
#[cfg(feature = "debug")]
{
trace!("This is Pi-{}", board_model);
}
return match board_model {
1 => {
let periph_virt_base = 0x20000000;
let periph_phys_base = 0x7e000000;
let mem_flag = mailbox::MEM_FLAG_L1_NONALLOCATING | mailbox::MEM_FLAG_ZERO;
Ok((periph_virt_base, periph_phys_base, mem_flag))
},
2 | 3 => {
let periph_virt_base = 0x3f000000;
let periph_phys_base = 0x7e000000;
let mem_flag = mailbox::MEM_FLAG_L1_NONALLOCATING | mailbox::MEM_FLAG_ZERO;
Ok((periph_virt_base, periph_phys_base, mem_flag))
},
_ => {
Err(Error::new(ErrorKind::Other, format!("Unable to detect Board Model from board revision: {:?}", mbox_board_rev)))
},
}
}
fn map_peripheral(base: usize, len: usize) -> Result<*mut c_void, Error> {
let dev_mem = CString::new("/dev/mem").unwrap().into_bytes_with_nul();
let dmem_ptr = dev_mem.as_ptr();
match unsafe { libc::open(dmem_ptr as *const u8, libc::O_RDWR | libc::O_SYNC)}{
fd if fd < 0 => {
let error = format!("dma_gpio: failed to open /dev/mem.");
Err(Error::new(ErrorKind::Other, error))
},
#[cfg(target_arch = "aarch64")]
fd => match unsafe{ libc::mmap(ptr::null_mut(), len, libc::PROT_READ | libc::PROT_WRITE, libc::MAP_SHARED, fd, base as i64) } {
libc::MAP_FAILED => {
let error = format!("pi_gpio: Failed to map peripheral at {:#010x}.", base);
Err(Error::new(ErrorKind::Other, error))
},
vaddr => {
unsafe{ libc::close(fd)};
Ok(vaddr)
}
}
#[cfg(target_arch = "arm")]
fd => match unsafe{ libc::mmap(ptr::null_mut(), len, libc::PROT_READ | libc::PROT_WRITE, libc::MAP_SHARED, fd, base as i32) } {
libc::MAP_FAILED => {
let error = format!("pi_gpio: Failed to map peripheral at {:#010x}.", base);
Err(Error::new(ErrorKind::Other, error))
},
vaddr => {
unsafe{ libc::close(fd)};
Ok(vaddr)
}
}
}
}
fn new(delay_hw: u8, known_pins: [u8;MAX_CHANNELS], num_channels: usize, pwm_divisor: usize, cycle_time: usize, sample_delay: usize) -> Result<Self, Error> {
let mut mbox_handle: i32 = match Board::mbox_open(){
Ok(fd) => fd,
Err(e) => {
return Err(e)
}
};
#[cfg(feature = "debug")]
{
trace!("mbox_handle: {:?}", mbox_handle);
}
let mbox_board_rev = match mailbox::get_board_revision(mbox_handle){
Ok(rev) => rev,
Err(e) => {
return Err(Error::new(ErrorKind::Other, format!("could not get board revision: {:?}", e)))
}
};
#[cfg(feature = "debug")]
{
trace!("MBox Board Revision: {:#010x}", mbox_board_rev);
}
let num_samples = cycle_time as usize/sample_delay;
let num_pages: usize = (NUM_CBS * size_of::<DmaCbT>() as usize + NUM_SAMPLES * 4 + PAGE_SIZE - 1)>>PAGE_SHIFT;
let (periph_virt_base, periph_phys_base, mem_flag) = match Board::get_model(mbox_board_rev){
Ok(res) => res,
Err(e) => {
let error = format!("could not get the pi model: {:?}", e);
return Err(Error::new(ErrorKind::Other, error))
}
};
let dma_base = 0x00007000 + periph_virt_base;
let _pwm_base = PWM_BASE_OFFSET + periph_virt_base;
let pwm_phys_base = PWM_BASE_OFFSET + periph_phys_base;
let _clk_base = CLK_BASE_OFFSET + periph_virt_base;
let _gpio_base: usize = GPIO_BASE_OFFSET + periph_virt_base;
let gpio_phys_base: usize = GPIO_BASE_OFFSET + periph_phys_base;
let _pcm_base: usize = PCM_BASE_OFFSET + periph_virt_base;
let pcm_phys_base: usize = PCM_BASE_OFFSET + periph_phys_base;
#[cfg(feature = "debug")]
{
match mailbox::get_dma_channels(mbox_handle){
Ok(channels) => {
trace!("DMA Channels Info: {:#010x}, using DMA Channel: {}\n", channels, DMA_CHAN_NUM);
},
Err(e) => return Err(e)
};
}
/* map the registers for all DMA Channels */
let _dma_virt_base = match Board::map_peripheral(dma_base, DMA_CHAN_SIZE * (DMA_CHAN_MAX + 1)){
Ok(ptr) => ptr as *const [RW<usize>;DMA_CHAN_SIZE/4],
Err(e) => return Err(e)
};
#[cfg(feature = "debug")]
{
trace!("dma_virt_base: {:?}", _dma_virt_base);
}
/* set dma_reg to point to the DMA Channel we are using */
let dma_reg = (_dma_virt_base as usize + DMA_CHAN_NUM * DMA_CHAN_SIZE) as *const [RW<usize>;DMA_CHAN_SIZE/4];
#[cfg(feature = "debug")]
{
trace!("dma_reg_ptr: {:?}", dma_reg);
}
// let dma_reg = unsafe{ *dma_reg_ptr };
let pwm_reg = match Board::map_peripheral(_pwm_base, PWM_LEN){
Ok(ptr) => ptr as *const [RW<usize>;PWM_LEN/4],
Err(e) => return Err(e)
};
#[cfg(feature = "debug")]
{
trace!("pwm_reg: {:?}", pwm_reg);
}
let pcm_reg = match Board::map_peripheral(_pcm_base, PCM_LEN){
Ok(ptr) => ptr as *const [RW<usize>;PCM_LEN/4],
Err(e) => return Err(e)
};
#[cfg(feature = "debug")]
{
trace!("pcm_reg: {:?}", pcm_reg);
}
let clk_reg = match Board::map_peripheral(_clk_base, CLK_LEN){
Ok(ptr) => ptr as *const [RW<usize>;CLK_LEN/4],
Err(e) => return Err(e)
};
#[cfg(feature = "debug")]
{
trace!("clk_reg: {:?}", clk_reg);
}
let gpio_reg = match Board::map_peripheral(_gpio_base, GPIO_LEN){
Ok(ptr) => ptr as *const [RW<usize>;GPIO_LEN/4],
Err(e) => return Err(e)
};
#[cfg(feature = "debug")]
{
trace!("gpio_reg: {:?}", gpio_reg);
}
/* Use the mailbox interface to the VC to ask for physical memory */
let mbox_mem_ref = match mailbox::mem_alloc(mbox_handle, num_pages * PAGE_SIZE, PAGE_SIZE, mem_flag) {
Ok(ret) => ret,
Err(e) => return Err(e)
};
// TODO: How do we know that succeeded?
#[cfg(feature = "debug")]
{
trace!("mem_ref: {:#010x}", mbox_mem_ref);
}
let mbox_bus_addr = match mailbox::mem_lock(mbox_handle, mbox_mem_ref) {
Ok(ret) => ret,
Err(e) => return Err(e)
};
#[cfg(feature = "debug")]
{
trace!("bus_addr: {:#010x}", mbox_bus_addr);
}
let mbox_virt_addr = match mailbox::mapmem(BUS_TO_PHYS(mbox_bus_addr), num_pages * PAGE_SIZE){
Ok(ret) => ret,
Err(e) => return Err(e)
};
#[cfg(feature = "debug")]
{
trace!("virt_addr: {:#010x}\n", mbox_virt_addr);
}
if (mbox_virt_addr & (PAGE_SIZE - 1)) > 0 {
return Err(Error::new(ErrorKind::Other, "pi-gpio: Virtual address is not page aligned."))
}
// we're done with mbox now
match Board::mbox_close(mbox_handle){
Ok(()) => (),
Err(e) => return Err(e)
}
mbox_handle = -1;
let mbox = Mbox::new(mbox_handle, mbox_mem_ref, mbox_bus_addr, mbox_virt_addr as *mut c_void);
let mut board = Board{
pwm_divisor,
cycle_time,
sample_delay,
num_pages,
num_samples,
dma_base,
_pwm_base,
pwm_phys_base,
_clk_base,
_gpio_base,
gpio_phys_base,
_pcm_base,
pcm_phys_base,
_dma_virt_base,
dma_reg,
pwm_reg,
pcm_reg,
clk_reg,
gpio_reg,
known_pins,
num_channels,
pin2gpio: [0; MAX_CHANNELS],
channel_pwm: [0.0; MAX_CHANNELS],
mbox,
delay_hw,
invert_mode: false,
};
board.init_ctrl_data();
board.init_hardware(pwm_divisor, sample_delay);
board.init_pwm();
Ok(board)
}
fn mem_virt_to_phys(&self, virt: *const usize) -> usize {
let offset = virt as usize - self.mbox.virt_addr as usize;
offset + self.mbox.bus_addr
}
// bus address of the ram is 0x40000000. With this binary-or, writes to the returned address will bypass the CPU (L1) cache, but not the L2 cache. 0xc0000000 should be the base address if L2 must also be bypassed. However, the DMA engine is aware of L2 cache - just not the L1 cache (source: http://en.wikibooks.org/wiki/Aros/Platforms/Arm_Raspberry_Pi_support#Framebuffer )
fn virt_to_uncached_phys(&self, virt: *const usize) -> usize {
self.mem_virt_to_phys(virt) | 0x40000000
}
fn init_ctrl_data(&self) {
#[cfg(feature = "debug")]
{
trace!("Initializing DMA...\n");
}
let ctl_ptr = self.mbox.virt_addr as *const Ctl;
let phys_gpclr0 = self.gpio_phys_base + 0x28;
let phys_gpset0 = self.gpio_phys_base + 0x1c;
let phys_fifo_addr = if self.delay_hw == DELAY_VIA_PWM {
self.pwm_phys_base + 0x18
}else {
self.pcm_phys_base + 0x04
};
unsafe{
let sample_ptr = &((*ctl_ptr).sample) as *const [RW<usize>; NUM_SAMPLES];
libc::memset(sample_ptr as *mut c_void, 0, size_of::<[usize;NUM_SAMPLES]>());
}
// calculate a mask to turn off all the servos
let mut mask = 0;
for i in 0..self.num_channels {
mask |= 1 << self.known_pins[i];
}
#[cfg(feature = "debug")]
{
trace!("mask: {:#010x}", mask);
}
unsafe{
for i in 0..self.num_samples {
(*ctl_ptr).sample[i].write(mask);
}
}
/* Initialize all the DMA commands. They come in pairs.
* - 1st command copies a value from the sample memory to a destination
* address which can be either the gpclr0 register or the gpset0 register
* - 2nd command waits for a trigger from an external source (PWM or PCM)
*/
let mut j = 0;
let mut cbp;
let cb_size = size_of::<DmaCbT>();
unsafe{
for i in 0..self.num_samples {
// first DMA command
cbp = &(*ctl_ptr).cb[j];
cbp.info.write(DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP);
cbp.src.write(self.virt_to_uncached_phys((&((*ctl_ptr).sample[i]) as *const RW<usize>) as *const usize));
cbp.dst.write(if self.invert_mode {
phys_gpset0
}else {
phys_gpclr0
});
cbp.length.write(4);
cbp.stride.write(0);
cbp.next.write(self.virt_to_uncached_phys((cbp as *const DmaCbT as usize + cb_size) as *const usize));
j += 1;
cbp = &(*ctl_ptr).cb[j];
cbp.info.write(if self.delay_hw == DELAY_VIA_PWM {
DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP | DMA_D_DREQ | DMA_PER_MAP(5)
}else {
DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP | DMA_D_DREQ | DMA_PER_MAP(2)
});
cbp.src.write(self.virt_to_uncached_phys(ctl_ptr as *const usize)); // any data will do
cbp.dst.write(phys_fifo_addr);
cbp.length.write(4);
cbp.stride.write(0);
cbp.next.write(self.virt_to_uncached_phys((cbp as *const DmaCbT as usize + cb_size) as *const usize));
j += 1;
}
(*ctl_ptr).cb[j - 1].next.write(self.virt_to_uncached_phys(&(*ctl_ptr).cb as *const DmaCbT as *const usize));
}
}
fn init_hardware(&self, pwm_divisor: usize, sample_delay: usize) {
#[cfg(feature = "debug")]
{
trace!("Initializing PWM/PCM HW...\n");
}
let ctl_ptr = self.mbox.virt_addr as *mut Ctl;
unsafe {
if self.delay_hw == DELAY_VIA_PWM {
// Initialize PWM
(*self.pwm_reg)[PWM_CTL].write(0);
udelay(10);
(*self.clk_reg)[PWMCLK_CNTL].write(0x5A000006); // Source=PLLD (500 MHz)
udelay(100);
(*self.clk_reg)[PWMCLK_DIV].write(0x5A000000 | (pwm_divisor << 12)); // set pwm div to 500, giving 1MHz
udelay(100);
(*self.clk_reg)[PWMCLK_CNTL].write(0x5A000016); // Source = PLLD and enable
udelay(100);
(*self.pwm_reg)[PWM_RNG1].write(sample_delay as usize);
udelay(10);
(*self.pwm_reg)[PWM_DMAC].write((PWMDMAC_ENAB | PWMDMAC_THRSHLD) as usize);
udelay(10);
(*self.pwm_reg)[PWM_CTL].write(PWMCTL_CLRF);
udelay(10);
(*self.pwm_reg)[PWM_CTL].write(PWMCTL_USEF1 | PWMCTL_PWEN1);
udelay(10);
}else {
// Initialize PCM
(*self.pcm_reg)[PCM_CS_A].write(1); // Disable Rx+Tx, Enable PCM block
udelay(100);
(*self.clk_reg)[PCMCLK_CNTL].write(0x5A000006); // Source=PLLD (500 MHz)
udelay(100);
(*self.clk_reg)[PCMCLK_DIV].write(0x5A000000 | (pwm_divisor << 12)); // set pcm div to 500, giving 1MHz
udelay(100);
(*self.clk_reg)[PCMCLK_CNTL].write(0x5A000016); // Source = PLLD and enable
udelay(100);
(*self.pcm_reg)[PCM_TXC_A].write(0<<31 | 1<<30 | 0<<20 | 0<<16); // 1 channel, 8 bits
udelay(100);
(*self.pcm_reg)[PCM_MODE_A].write((sample_delay - 1) << 10);
udelay(100);
(*self.pcm_reg)[PCM_CS_A].modify(|val| val | 1<<4 | 1<<3); // Clear FIFOs
udelay(100);
(*self.pcm_reg)[PCM_DREQ_A].write(64<<24 | 64<<8); // DMA Req when one slot is free?
udelay(100);
(*self.pcm_reg)[PCM_CS_A].modify(|val| val | 1<<9); // Enable DMA
udelay(100);
}
// Initialize the DMA
(*self.dma_reg)[DMA_CS].write(DMA_RESET);
udelay(10);
(*self.dma_reg)[DMA_CS].write(DMA_INT | DMA_END);
(*self.dma_reg)[DMA_CONBLK_AD].write(self.virt_to_uncached_phys(&(*ctl_ptr).cb as *const DmaCbT as *const usize));
(*self.dma_reg)[DMA_DEBUG].write(7); // clear debug error flags
(*self.dma_reg)[DMA_CS].write(0x10880001); // go, mid priority, wait for outstanding writes
}
if self.delay_hw == DELAY_VIA_PCM {
unsafe {
(*self.pcm_reg)[PCM_CS_A].modify(|val| val | 1<<2)
}; // Enable Tx
}
}
fn init_pwm(&mut self) {
#[cfg(feature = "debug")]
{
trace!("Initializing PWM...\n");
}
self.update_pwm();
}
}
impl Board {
fn gpio_set(&mut self, pin: u8) {
unsafe {
if self.invert_mode {
(*self.gpio_reg)[GPIO_SET0].write(1 << pin);
}else{
(*self.gpio_reg)[GPIO_CLR0].write(1 << pin);
}
}
}
fn gpio_set_mode(&mut self, pin: usize, mode: usize) {
let i = GPIO_FSEL0 + pin/10;
unsafe {
let mut fsel: usize = (*self.gpio_reg)[i].read();
fsel &= !(7 << ((pin % 10) * 3));
fsel |= mode << ((pin % 10) * 3);
(*self.gpio_reg)[i].write(fsel);
}
}
// Set the pin to a pin2gpio element so pi_gpio can write to it,
// and set the width of the PWM pulse to the element with the same index
// in channel_pwm array.
fn set_pin2gpio(&mut self, pin: u8, width: f32) -> Result<(), Error> {
if width >= 0.0 || width <= 1.0 {
for i in 0..self.num_channels {
if self.pin2gpio[i] == pin {
self.channel_pwm[i] = width;
return Ok(())
}else if self.pin2gpio[i] == 0 {
self.pin2gpio[i] = pin;
self.gpio_set(pin);
self.gpio_set_mode(pin as usize, GPIO_MODE_OUT);
self.channel_pwm[i] = width;
return Ok(())
}
}
Err(Error::new(ErrorKind::Other, format!("Pin {} is not one of the known pins", pin)))
}else {
Err(Error::new(ErrorKind::Other, format!("Width {} out of range.", width)))
}
}
// Set each provided pin to one in pin2gpio
fn set_pin(&mut self, pin: u8, width: f32) -> Result<(), Error> {
if self.is_known_pin(pin) {
self.set_pin2gpio(pin, width)
}else{
let err = format!("GPIO {:?} is not enabled for dma-gpio module", pin);
Err(Error::new(ErrorKind::Other, err))
}
}
/// Set GPIO pin's pwm width.
pub fn set_pwm(&mut self, pin: u8, width: f32) -> Result<(), Error> {
match self.set_pin(pin, width) {
Ok(()) => self.update_pwm(),
Err(e) => return Err(e)
}
Ok(())
}
/// Set all known GPIO pins' pwm width.
pub fn set_all_pwm(&mut self, width: f32) -> Result<(), Error> {
for i in 0..self.num_channels {
match self.set_pin(self.known_pins[i], width) {
Ok(()) => (),
Err(e) => return Err(e)
}
}
self.update_pwm();
Ok(())
}
/// Invert all known GPIO pins' outputs.
pub fn set_invert_mode(&mut self, mode: bool) {
self.invert_mode = mode;
self.update_pwm();
}
// To avoid storing the same pin 2 times after one pin has been released
// we compact the pin2gpio array so all ON PWM pins are at the begining.
fn compact_pin2gpio(&mut self) {
let mut j = 0;
let mut tmp_pin2gpio: [u8; MAX_CHANNELS] = [0; MAX_CHANNELS];
let mut tmp_channel_pwm: [f32; MAX_CHANNELS] = [0.0; MAX_CHANNELS];
for i in 0..self.num_channels {
if self.pin2gpio[i] != 0 {
tmp_pin2gpio[j] = self.pin2gpio[i];
tmp_channel_pwm[j] = self.channel_pwm[i];
j += 1;
}
}
// Set the remaining slots in the arrays to 0, to disable them
for i in 0..self.num_channels {
self.pin2gpio[i] = tmp_pin2gpio[i];
self.channel_pwm[i] = tmp_channel_pwm[i];
}
self.num_channels = j;
}
// Pins can be relesead after being setup as PWM pins by writing the release <pin>
// command to the /dev/pi_gpio file. We make sure to compact the pin2gpio array
// that contains currently working pwm pins.
fn release_pin2gpio(&mut self, pin: u8) -> Result<(), Error> {
for i in 0..self.num_channels {
if self.pin2gpio[i] == pin {
self.channel_pwm[i] = 0.0;
self.pin2gpio[i] = 0;
return Ok(())
}
}
self.compact_pin2gpio();
Err(Error::new(ErrorKind::Other, format!("Pin {} is not one of the known pins", pin)))
}
// Function make sure the pin we want to release is a valid pin, if it is
// then calls release_pin2gpio to delete it from currently ON pins.
fn release_pin(&mut self, pin: u8) -> Result<(), Error> {
if self.is_known_pin(pin) {
self.release_pin2gpio(pin)
}else{
let err = format!("GPIO {:?} is not enabled for dma-gpio module", pin);
Err(Error::new(ErrorKind::Other, err))
}
}
/// Releases GPIO pin.
pub fn release_pwm(&mut self, pin: u8) -> Result<(), Error> {
match self.release_pin(pin) {
Ok(()) => self.update_pwm(),
Err(e) => return Err(e)
}
Ok(())
}
/// Releases all GPIO pins.
pub fn release_all_pwm(&mut self) -> Result<(), Error> {
self.channel_pwm = [0.0; MAX_CHANNELS];
self.update_pwm();
self.num_channels = 0;
self.pin2gpio = [0; MAX_CHANNELS];
Ok(())
}
/*
What we need to do here is:
First DMA command turns on the pins that are >0
All the other packets turn off the pins that are not used
For the cpb packets (The DMA control packet)
-> cbp[0]->dst = gpset0: set the pwms that are active
-> cbp[]->dst = gpclr0: clear when the sample has a value
For the samples (The value that is written by the DMA command to cbp[n]->dst)
-> dp[0] = mask of the pwms that are active
-> dp[n] = mask of the pwm to stop at time n
We dont really need to reset the cb->dst each time but I believe it helps a lot
in code readability in case someone wants to generate more complex signals.
*/
fn update_pwm(&self) {
let phys_gpclr0: usize = self.gpio_phys_base + 0x28;
let phys_gpset0: usize = self.gpio_phys_base + 0x1c;
let ctl_ptr = self.mbox.virt_addr as *const Ctl;
// first we turn on the channels that need to be on
// take the first DMA Packet and set its target to start pulse
unsafe {
(*ctl_ptr).cb[0].dst.write(
if self.invert_mode {
phys_gpclr0
}else {
phys_gpset0
});
}
// now create a mask of all the pins that should be on
let mut mask = 0;
for i in 0..self.num_channels {
// check the pin2gpio pin has been set to avoid locking all of them as PWM.
if (self.channel_pwm[i] > 0.0) && (self.pin2gpio[i] > 0) {
mask |= 1 << self.pin2gpio[i];
}
}
// and give that to the DMA controller to write
unsafe {
(*ctl_ptr).sample[0].write(mask);
}
// now we go through all the samples and turn the pins off when needed
unsafe {
for j in 1..self.num_samples {
(*ctl_ptr).cb[j*2].dst.write(
if self.invert_mode {
phys_gpset0
}else {
phys_gpclr0
});
mask = 0;
for i in 0..self.num_channels {
// check the pin2gpio pin has been set to avoid locking all of them as PWM.
if self.pin2gpio[i] > 0 && (j as f32/self.num_samples as f32 > self.channel_pwm[i]) {
mask |= 1 << self.pin2gpio[i];
}
}
(*ctl_ptr).sample[j].write(mask);
}
}
}
/// Check if the pin provided is found in the list of known pins set with [BoardBuilder::build_with_pins](struct.BoardBuilder.html#method.build_with_pins).
pub fn is_known_pin(&self, pin: u8) -> bool {
for i in 0..MAX_CHANNELS {
if self.known_pins[i] == pin {
return true
}
}
false
}
/// Check if the pin provided is found in the list of BANNED pins.
pub fn is_banned_pin(&self, pin: u8) -> bool {
for i in 0..BANNED_PINS.len() {
if BANNED_PINS[i] == pin {
return true
}
}
false
}
/// Sets all GPIO pins' pwm width to 0.0, and frees the memory used for the process.
///
/// Board already implements Drop trait that calls this method,
/// so you won't ever have to call this method.
pub fn terminate(&mut self) {
let mut has_error = false;
#[cfg(feature = "debug")]
{
trace!("Resetting DMA...");
}
if (self.dma_reg as usize > 0) && (self.mbox.virt_addr as usize > 0) {
for i in 0..self.num_channels {
self.channel_pwm[i] = 0.0;
}
self.update_pwm();
udelay(DEFAULT_CYCLE_TIME as u64);
unsafe {(*self.dma_reg)[DMA_CS].write(DMA_RESET)};
udelay(10);
}
#[cfg(feature = "debug")]
{
trace!("Freeing mbox memory...");
}
if !self.mbox.virt_addr.is_null() {
match mailbox::unmapmem(self.mbox.virt_addr, self.num_pages * PAGE_SIZE){
Ok(_) => (),
Err(e) => {
error!("{:?}", e);
has_error = true;
},
}
if self.mbox.handle <= 2 {
match Board::mbox_open(){
Ok(mbox_handle) => {
match mailbox::mem_unlock(mbox_handle, self.mbox.mem_ref){
Ok(_) => (),
Err(e) => {
error!("{:?}", e);
has_error = true;
}
}
match mailbox::mem_free(mbox_handle, self.mbox.mem_ref) {
Ok(_) => (),
Err(e) => {
error!("{:?}", e);
has_error = true;
}
}
match Board::mbox_close(mbox_handle) {
Ok(()) => (),
Err(_) => {
error!("file close error");
has_error = true
}
}
},
Err(e) => {
error!("{:?}", e);
has_error = true;
},
}
}
}
if has_error {
println!("unsuccessfully terminated.");
}else{
println!("dma_gpio stopped.");
}
}
/// print info about the hardware: PWM or PCM, Number of channels, Pins being used, PWM Frequency, PWM steps, Maximum Period, Minimum Period, and DMA Base Address.
pub fn print_info(&self) {
println!("Using hardware:\t\t\t{:}", if self.delay_hw == DELAY_VIA_PWM {"PWM"} else{"PCM"});
println!("Number of channels:\t\t{}", self.num_channels);
#[allow(array_into_iter)]
let print_pins: Vec<&u8> = self.known_pins.into_iter().filter(|&&pin| pin > 0).collect();
println!("Pins:\t\t\t\t{:?}", print_pins);
println!("PWM frequency:\t\t\t{} Hz", 500000000.0/(self.pwm_divisor * self.cycle_time) as f64);
println!("PWM steps:\t\t\t{}", self.num_samples);
println!("Maximum period (100 %):\t{} us", ((self.cycle_time * self.pwm_divisor) as f64/500.0));
println!("Minimum period ({:3} %):\t{} us", 100.0*self.sample_delay as f64 / self.cycle_time as f64, (self.sample_delay * self.pwm_divisor) as f64/500.0);
println!("DMA Base:\t\t\t{:#010x}", self.dma_base);
}
/// This method is only available when 'debug' feature is on.
///
/// Print out all informations about the control blocks, PWM, Clock, GPIO and DMA.
#[cfg(feature = "debug")]
pub fn debug_dump_hw(&self) {
trace!("\n");
trace!("pwm_reg: {:?}\n", self.pwm_reg);
let ctl_ptr = self.mbox.virt_addr as *const Ctl;
let mut cbp;
for i in 0..self.num_samples {
unsafe{
cbp = &(*ctl_ptr).cb[i];
}
trace!("DMA Control Block: #{} @{:?}", i, cbp as *const DmaCbT);
trace!("info:\t{:#010x}", cbp.info.read());
trace!("src:\t{:#010x}", cbp.src.read());
trace!("dst:\t{:#010x}", cbp.dst.read());
trace!("length:\t{:#010x}", cbp.length.read());
trace!("stride:\t{:#010x}", cbp.stride.read());
trace!("next:\t{:#010x}\n", cbp.next.read());
}
trace!("PWM_BASE:\t{:#010x}", self._pwm_base);
trace!("PWM_REG:\t{:?}", self.pwm_reg);
unsafe {
for i in 0..(PWM_LEN/4) {
trace!("{:#04X}: {:#010x} {:#010x}", i, self.pwm_reg as usize + 4*i, (*self.pwm_reg)[i].read());
}
}
trace!("\n");
trace!("CLK_BASE: {:#010x}", self._clk_base);
trace!("PWMCLK_CNTL: {:#010x}", PWMCLK_CNTL);
trace!("clk_reg[PWMCLK_CNTL]: {:#010x}", self.clk_reg as usize + 4*PWMCLK_CNTL);
trace!("PWMCLK_DIV: {:#010x}", PWMCLK_DIV);
trace!("clk_reg: {:?}", self.clk_reg);
trace!("virt_to_phys(clk_reg): {:#010x}", self.virt_to_uncached_phys(self.clk_reg as *const usize));
unsafe {
for i in 0..(CLK_LEN/4) {
trace!("{:#04X}: {:#010x} {:#010x}", i, self.clk_reg as usize + 4*i, (*self.clk_reg)[i].read());
}
}
trace!("\n");
trace!("DMA_BASE: {:#010x}", self.dma_base);
trace!("dma_virt_base: {:?}", self._dma_virt_base);
trace!("dma_reg: {:?}", self.dma_reg);
trace!("virt_to_phys(dma_reg): {:#010x}", self.virt_to_uncached_phys(self.dma_reg as *const usize));
unsafe {
for i in 0..(DMA_CHAN_SIZE/4) {
trace!("{:#04X}: {:#010x} {:#010x}", i, self.dma_reg as usize + i*4, (*self.dma_reg)[i].read());
}
}
trace!("\n");
trace!("GPIO_BASE: {:#010x}", self._gpio_base);
trace!("gpio_reg: {:?}", self.gpio_reg);
trace!("virt_to_phys(gpio_reg): {:#010x}", self.virt_to_uncached_phys(self.gpio_reg as *const usize));
unsafe {
for i in 0..(GPIO_LEN/4) {
trace!("{:#04X}: {:#010x} {:#010x}", i, self.gpio_reg as usize + i*4, (*self.gpio_reg)[i].read());
}
}
}
/// This method is only available when 'debug' feature is on.
///
/// Print out info about samples' outputs.
#[cfg(feature = "debug")]
pub fn debug_dump_samples(&self) {
let ctl_ptr = self.mbox.virt_addr as *const Ctl;
unsafe{
for i in 0..self.num_samples {
trace!("#{} @{:#010x}", i, (*ctl_ptr).sample[i].read());
}
}
}
}
/// delay for # us seconds.
pub fn udelay(us: u64) {
let nanos = Duration::from_nanos(us*1000);
sleep(nanos);
}
/// Check if the pin provided is found in the list of BANNED pins.
pub fn is_banned_pin(pin: u8) -> bool {
for i in 0..BANNED_PINS.len() {
if BANNED_PINS[i] == pin {
return true
}
}
false
}
|
// Problem 22 - Names scores
//
// Using "../resources/p022_names.txt", a 46K text file containing over
// five-thousand first names, begin by sorting it into alphabetical order.
// Then working out the alphabetical value for each name, multiply this value by
// its alphabetical position in the list to obtain a name score.
//
// For example, when the list is sorted into alphabetical order, COLIN, which is
// worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would
// obtain a score of 938 × 53 = 49714.
//
// What is the total of all the name scores in the file?
use std::io::BufReader;
use std::io::prelude::*;
use std::fs::File;
fn main() {
println!("{}", solution());
}
fn solution() -> u32 {
let file = match File::open("../resources/p022_names.txt") {
Ok(f) => BufReader::new(f),
Err(_) => panic!("Error opening file"),
};
let mut names = file.split(b',')
.map(|res| get_name(res.unwrap()))
.collect::<Vec<_>>();
names.sort();
names.iter()
.enumerate()
.map(|(ix, name)| (ix as u32 + 1)*value(name))
.fold(0, |sum, score| sum + score)
}
fn get_name(vstr: Vec<u8>) -> String {
String::from_utf8(vstr).unwrap().trim_matches('"').to_string()
}
fn value(s: &str) -> u32 {
let zero = b'A' - 1;
s.bytes().fold(0, |sum, c| { sum + (c - zero) as u32 })
}
|
use super::SelectionPhase::{Exploitation, Exploration, Initial};
use super::*;
use crate::helpers::models::domain::*;
use crate::utils::Timer;
fn create_rosomaxa(rebalance_memory: usize) -> Rosomaxa {
let mut config = RosomaxaConfig::new_with_defaults(4);
config.rebalance_memory = rebalance_memory;
Rosomaxa::new(create_empty_problem(), Arc::new(Environment::default()), config).unwrap()
}
fn create_statistics(termination_estimate: f64, generation: usize) -> Statistics {
let mut statistics = Statistics::default();
statistics.termination_estimate = termination_estimate;
statistics.generation = generation;
statistics.improvement_1000_ratio = 0.5;
statistics
}
fn get_network(rosomaxa: &Rosomaxa) -> &IndividualNetwork {
match &rosomaxa.phase {
RosomaxaPhases::Exploration { network, .. } => network,
_ => unreachable!(),
}
}
#[test]
fn can_switch_phases() {
let mut rosomaxa = create_rosomaxa(10);
(0..4).for_each(|_| {
assert_eq!(rosomaxa.selection_phase(), Initial);
rosomaxa.add_all(vec![create_empty_insertion_context()]);
rosomaxa.update_phase(&create_statistics(0., 0))
});
rosomaxa.add(create_empty_insertion_context());
assert_eq!(rosomaxa.selection_phase(), Exploration);
for (idx, (termination_estimate, phase)) in (&[(0.7, Exploration), (0.9, Exploitation)]).iter().enumerate() {
rosomaxa.update_phase(&create_statistics(*termination_estimate, idx));
assert_eq!(rosomaxa.selection_phase(), *phase);
}
}
#[test]
fn can_select_individuals_in_different_phases() {
let mut rosomaxa = create_rosomaxa(10);
(0..10).for_each(|idx| {
rosomaxa.add_all(vec![create_empty_insertion_context()]);
rosomaxa.update_phase(&create_statistics(0.75, idx))
});
let individuals = rosomaxa.select();
assert_eq!(individuals.count(), 4);
assert_eq!(rosomaxa.selection_phase(), SelectionPhase::Exploration);
rosomaxa.update_phase(&create_statistics(0.95, 10));
let individuals = rosomaxa.select();
assert_eq!(individuals.count(), 4);
assert_eq!(rosomaxa.selection_phase(), SelectionPhase::Exploitation);
}
#[test]
fn can_optimize_network() {
let termination_estimate = 0.75;
let mut rosomaxa = create_rosomaxa(2);
(0..10).for_each(|idx| {
rosomaxa.add_all(vec![create_simple_insertion_ctx(idx as f64, idx)]);
rosomaxa.update_phase(&create_statistics(termination_estimate, idx))
});
rosomaxa.add(create_empty_insertion_context());
rosomaxa.update_phase(&create_statistics(termination_estimate, 10));
assert_eq!(get_network(&rosomaxa).get_nodes().count(), 1);
}
#[test]
fn can_format_network() {
let mut rosomaxa = create_rosomaxa(4);
rosomaxa.add_all(vec![create_empty_insertion_context()]);
let str = format!("{}", rosomaxa);
assert_eq!(str, "[[0.0000000,0.0000000,0.0000000],]");
}
#[test]
fn can_handle_empty_population() {
let mut rosomaxa = create_rosomaxa(10);
for (phase, estimate) in vec![(Initial, None), (Initial, Some(0.7)), (Initial, Some(0.95))] {
if let Some(estimate) = estimate {
rosomaxa.update_phase(&create_statistics(estimate, 10));
}
assert!(rosomaxa.select().next().is_none());
assert_eq!(rosomaxa.selection_phase(), phase)
}
}
#[test]
fn can_get_population_shuffle_amount() {
let high_improvement = |termination_estimate: f64| Statistics {
generation: 1,
time: Timer::start(),
improvement_all_ratio: 0.99,
improvement_1000_ratio: 0.99,
termination_estimate,
};
assert_eq!(Rosomaxa::get_shuffle_amount(&high_improvement(0.), 100), 50);
assert_eq!(Rosomaxa::get_shuffle_amount(&high_improvement(0.20), 100), 48);
assert_eq!(Rosomaxa::get_shuffle_amount(&high_improvement(0.25), 100), 46);
assert_eq!(Rosomaxa::get_shuffle_amount(&high_improvement(0.5), 100), 25);
assert_eq!(Rosomaxa::get_shuffle_amount(&high_improvement(0.55), 100), 19);
assert_eq!(Rosomaxa::get_shuffle_amount(&high_improvement(0.65), 100), 10);
assert_eq!(Rosomaxa::get_shuffle_amount(&high_improvement(0.75), 100), 10);
assert_eq!(Rosomaxa::get_shuffle_amount(&high_improvement(1.), 100), 10);
let some_improvement = |ratio: f64, termination_estimate: f64| Statistics {
generation: 1,
time: Timer::start(),
improvement_all_ratio: ratio,
improvement_1000_ratio: ratio,
termination_estimate,
};
assert_eq!(Rosomaxa::get_shuffle_amount(&some_improvement(0.3, 0.55), 100), 50);
assert_eq!(Rosomaxa::get_shuffle_amount(&some_improvement(0.1, 0.55), 100), 100);
}
|
/// An enum to represent all characters in the TangutComponents block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum TangutComponents {
/// \u{18800}: '𘠀'
TangutComponentDash001,
/// \u{18801}: '𘠁'
TangutComponentDash002,
/// \u{18802}: '𘠂'
TangutComponentDash003,
/// \u{18803}: '𘠃'
TangutComponentDash004,
/// \u{18804}: '𘠄'
TangutComponentDash005,
/// \u{18805}: '𘠅'
TangutComponentDash006,
/// \u{18806}: '𘠆'
TangutComponentDash007,
/// \u{18807}: '𘠇'
TangutComponentDash008,
/// \u{18808}: '𘠈'
TangutComponentDash009,
/// \u{18809}: '𘠉'
TangutComponentDash010,
/// \u{1880a}: '𘠊'
TangutComponentDash011,
/// \u{1880b}: '𘠋'
TangutComponentDash012,
/// \u{1880c}: '𘠌'
TangutComponentDash013,
/// \u{1880d}: '𘠍'
TangutComponentDash014,
/// \u{1880e}: '𘠎'
TangutComponentDash015,
/// \u{1880f}: '𘠏'
TangutComponentDash016,
/// \u{18810}: '𘠐'
TangutComponentDash017,
/// \u{18811}: '𘠑'
TangutComponentDash018,
/// \u{18812}: '𘠒'
TangutComponentDash019,
/// \u{18813}: '𘠓'
TangutComponentDash020,
/// \u{18814}: '𘠔'
TangutComponentDash021,
/// \u{18815}: '𘠕'
TangutComponentDash022,
/// \u{18816}: '𘠖'
TangutComponentDash023,
/// \u{18817}: '𘠗'
TangutComponentDash024,
/// \u{18818}: '𘠘'
TangutComponentDash025,
/// \u{18819}: '𘠙'
TangutComponentDash026,
/// \u{1881a}: '𘠚'
TangutComponentDash027,
/// \u{1881b}: '𘠛'
TangutComponentDash028,
/// \u{1881c}: '𘠜'
TangutComponentDash029,
/// \u{1881d}: '𘠝'
TangutComponentDash030,
/// \u{1881e}: '𘠞'
TangutComponentDash031,
/// \u{1881f}: '𘠟'
TangutComponentDash032,
/// \u{18820}: '𘠠'
TangutComponentDash033,
/// \u{18821}: '𘠡'
TangutComponentDash034,
/// \u{18822}: '𘠢'
TangutComponentDash035,
/// \u{18823}: '𘠣'
TangutComponentDash036,
/// \u{18824}: '𘠤'
TangutComponentDash037,
/// \u{18825}: '𘠥'
TangutComponentDash038,
/// \u{18826}: '𘠦'
TangutComponentDash039,
/// \u{18827}: '𘠧'
TangutComponentDash040,
/// \u{18828}: '𘠨'
TangutComponentDash041,
/// \u{18829}: '𘠩'
TangutComponentDash042,
/// \u{1882a}: '𘠪'
TangutComponentDash043,
/// \u{1882b}: '𘠫'
TangutComponentDash044,
/// \u{1882c}: '𘠬'
TangutComponentDash045,
/// \u{1882d}: '𘠭'
TangutComponentDash046,
/// \u{1882e}: '𘠮'
TangutComponentDash047,
/// \u{1882f}: '𘠯'
TangutComponentDash048,
/// \u{18830}: '𘠰'
TangutComponentDash049,
/// \u{18831}: '𘠱'
TangutComponentDash050,
/// \u{18832}: '𘠲'
TangutComponentDash051,
/// \u{18833}: '𘠳'
TangutComponentDash052,
/// \u{18834}: '𘠴'
TangutComponentDash053,
/// \u{18835}: '𘠵'
TangutComponentDash054,
/// \u{18836}: '𘠶'
TangutComponentDash055,
/// \u{18837}: '𘠷'
TangutComponentDash056,
/// \u{18838}: '𘠸'
TangutComponentDash057,
/// \u{18839}: '𘠹'
TangutComponentDash058,
/// \u{1883a}: '𘠺'
TangutComponentDash059,
/// \u{1883b}: '𘠻'
TangutComponentDash060,
/// \u{1883c}: '𘠼'
TangutComponentDash061,
/// \u{1883d}: '𘠽'
TangutComponentDash062,
/// \u{1883e}: '𘠾'
TangutComponentDash063,
/// \u{1883f}: '𘠿'
TangutComponentDash064,
/// \u{18840}: '𘡀'
TangutComponentDash065,
/// \u{18841}: '𘡁'
TangutComponentDash066,
/// \u{18842}: '𘡂'
TangutComponentDash067,
/// \u{18843}: '𘡃'
TangutComponentDash068,
/// \u{18844}: '𘡄'
TangutComponentDash069,
/// \u{18845}: '𘡅'
TangutComponentDash070,
/// \u{18846}: '𘡆'
TangutComponentDash071,
/// \u{18847}: '𘡇'
TangutComponentDash072,
/// \u{18848}: '𘡈'
TangutComponentDash073,
/// \u{18849}: '𘡉'
TangutComponentDash074,
/// \u{1884a}: '𘡊'
TangutComponentDash075,
/// \u{1884b}: '𘡋'
TangutComponentDash076,
/// \u{1884c}: '𘡌'
TangutComponentDash077,
/// \u{1884d}: '𘡍'
TangutComponentDash078,
/// \u{1884e}: '𘡎'
TangutComponentDash079,
/// \u{1884f}: '𘡏'
TangutComponentDash080,
/// \u{18850}: '𘡐'
TangutComponentDash081,
/// \u{18851}: '𘡑'
TangutComponentDash082,
/// \u{18852}: '𘡒'
TangutComponentDash083,
/// \u{18853}: '𘡓'
TangutComponentDash084,
/// \u{18854}: '𘡔'
TangutComponentDash085,
/// \u{18855}: '𘡕'
TangutComponentDash086,
/// \u{18856}: '𘡖'
TangutComponentDash087,
/// \u{18857}: '𘡗'
TangutComponentDash088,
/// \u{18858}: '𘡘'
TangutComponentDash089,
/// \u{18859}: '𘡙'
TangutComponentDash090,
/// \u{1885a}: '𘡚'
TangutComponentDash091,
/// \u{1885b}: '𘡛'
TangutComponentDash092,
/// \u{1885c}: '𘡜'
TangutComponentDash093,
/// \u{1885d}: '𘡝'
TangutComponentDash094,
/// \u{1885e}: '𘡞'
TangutComponentDash095,
/// \u{1885f}: '𘡟'
TangutComponentDash096,
/// \u{18860}: '𘡠'
TangutComponentDash097,
/// \u{18861}: '𘡡'
TangutComponentDash098,
/// \u{18862}: '𘡢'
TangutComponentDash099,
/// \u{18863}: '𘡣'
TangutComponentDash100,
/// \u{18864}: '𘡤'
TangutComponentDash101,
/// \u{18865}: '𘡥'
TangutComponentDash102,
/// \u{18866}: '𘡦'
TangutComponentDash103,
/// \u{18867}: '𘡧'
TangutComponentDash104,
/// \u{18868}: '𘡨'
TangutComponentDash105,
/// \u{18869}: '𘡩'
TangutComponentDash106,
/// \u{1886a}: '𘡪'
TangutComponentDash107,
/// \u{1886b}: '𘡫'
TangutComponentDash108,
/// \u{1886c}: '𘡬'
TangutComponentDash109,
/// \u{1886d}: '𘡭'
TangutComponentDash110,
/// \u{1886e}: '𘡮'
TangutComponentDash111,
/// \u{1886f}: '𘡯'
TangutComponentDash112,
/// \u{18870}: '𘡰'
TangutComponentDash113,
/// \u{18871}: '𘡱'
TangutComponentDash114,
/// \u{18872}: '𘡲'
TangutComponentDash115,
/// \u{18873}: '𘡳'
TangutComponentDash116,
/// \u{18874}: '𘡴'
TangutComponentDash117,
/// \u{18875}: '𘡵'
TangutComponentDash118,
/// \u{18876}: '𘡶'
TangutComponentDash119,
/// \u{18877}: '𘡷'
TangutComponentDash120,
/// \u{18878}: '𘡸'
TangutComponentDash121,
/// \u{18879}: '𘡹'
TangutComponentDash122,
/// \u{1887a}: '𘡺'
TangutComponentDash123,
/// \u{1887b}: '𘡻'
TangutComponentDash124,
/// \u{1887c}: '𘡼'
TangutComponentDash125,
/// \u{1887d}: '𘡽'
TangutComponentDash126,
/// \u{1887e}: '𘡾'
TangutComponentDash127,
/// \u{1887f}: '𘡿'
TangutComponentDash128,
/// \u{18880}: '𘢀'
TangutComponentDash129,
/// \u{18881}: '𘢁'
TangutComponentDash130,
/// \u{18882}: '𘢂'
TangutComponentDash131,
/// \u{18883}: '𘢃'
TangutComponentDash132,
/// \u{18884}: '𘢄'
TangutComponentDash133,
/// \u{18885}: '𘢅'
TangutComponentDash134,
/// \u{18886}: '𘢆'
TangutComponentDash135,
/// \u{18887}: '𘢇'
TangutComponentDash136,
/// \u{18888}: '𘢈'
TangutComponentDash137,
/// \u{18889}: '𘢉'
TangutComponentDash138,
/// \u{1888a}: '𘢊'
TangutComponentDash139,
/// \u{1888b}: '𘢋'
TangutComponentDash140,
/// \u{1888c}: '𘢌'
TangutComponentDash141,
/// \u{1888d}: '𘢍'
TangutComponentDash142,
/// \u{1888e}: '𘢎'
TangutComponentDash143,
/// \u{1888f}: '𘢏'
TangutComponentDash144,
/// \u{18890}: '𘢐'
TangutComponentDash145,
/// \u{18891}: '𘢑'
TangutComponentDash146,
/// \u{18892}: '𘢒'
TangutComponentDash147,
/// \u{18893}: '𘢓'
TangutComponentDash148,
/// \u{18894}: '𘢔'
TangutComponentDash149,
/// \u{18895}: '𘢕'
TangutComponentDash150,
/// \u{18896}: '𘢖'
TangutComponentDash151,
/// \u{18897}: '𘢗'
TangutComponentDash152,
/// \u{18898}: '𘢘'
TangutComponentDash153,
/// \u{18899}: '𘢙'
TangutComponentDash154,
/// \u{1889a}: '𘢚'
TangutComponentDash155,
/// \u{1889b}: '𘢛'
TangutComponentDash156,
/// \u{1889c}: '𘢜'
TangutComponentDash157,
/// \u{1889d}: '𘢝'
TangutComponentDash158,
/// \u{1889e}: '𘢞'
TangutComponentDash159,
/// \u{1889f}: '𘢟'
TangutComponentDash160,
/// \u{188a0}: '𘢠'
TangutComponentDash161,
/// \u{188a1}: '𘢡'
TangutComponentDash162,
/// \u{188a2}: '𘢢'
TangutComponentDash163,
/// \u{188a3}: '𘢣'
TangutComponentDash164,
/// \u{188a4}: '𘢤'
TangutComponentDash165,
/// \u{188a5}: '𘢥'
TangutComponentDash166,
/// \u{188a6}: '𘢦'
TangutComponentDash167,
/// \u{188a7}: '𘢧'
TangutComponentDash168,
/// \u{188a8}: '𘢨'
TangutComponentDash169,
/// \u{188a9}: '𘢩'
TangutComponentDash170,
/// \u{188aa}: '𘢪'
TangutComponentDash171,
/// \u{188ab}: '𘢫'
TangutComponentDash172,
/// \u{188ac}: '𘢬'
TangutComponentDash173,
/// \u{188ad}: '𘢭'
TangutComponentDash174,
/// \u{188ae}: '𘢮'
TangutComponentDash175,
/// \u{188af}: '𘢯'
TangutComponentDash176,
/// \u{188b0}: '𘢰'
TangutComponentDash177,
/// \u{188b1}: '𘢱'
TangutComponentDash178,
/// \u{188b2}: '𘢲'
TangutComponentDash179,
/// \u{188b3}: '𘢳'
TangutComponentDash180,
/// \u{188b4}: '𘢴'
TangutComponentDash181,
/// \u{188b5}: '𘢵'
TangutComponentDash182,
/// \u{188b6}: '𘢶'
TangutComponentDash183,
/// \u{188b7}: '𘢷'
TangutComponentDash184,
/// \u{188b8}: '𘢸'
TangutComponentDash185,
/// \u{188b9}: '𘢹'
TangutComponentDash186,
/// \u{188ba}: '𘢺'
TangutComponentDash187,
/// \u{188bb}: '𘢻'
TangutComponentDash188,
/// \u{188bc}: '𘢼'
TangutComponentDash189,
/// \u{188bd}: '𘢽'
TangutComponentDash190,
/// \u{188be}: '𘢾'
TangutComponentDash191,
/// \u{188bf}: '𘢿'
TangutComponentDash192,
/// \u{188c0}: '𘣀'
TangutComponentDash193,
/// \u{188c1}: '𘣁'
TangutComponentDash194,
/// \u{188c2}: '𘣂'
TangutComponentDash195,
/// \u{188c3}: '𘣃'
TangutComponentDash196,
/// \u{188c4}: '𘣄'
TangutComponentDash197,
/// \u{188c5}: '𘣅'
TangutComponentDash198,
/// \u{188c6}: '𘣆'
TangutComponentDash199,
/// \u{188c7}: '𘣇'
TangutComponentDash200,
/// \u{188c8}: '𘣈'
TangutComponentDash201,
/// \u{188c9}: '𘣉'
TangutComponentDash202,
/// \u{188ca}: '𘣊'
TangutComponentDash203,
/// \u{188cb}: '𘣋'
TangutComponentDash204,
/// \u{188cc}: '𘣌'
TangutComponentDash205,
/// \u{188cd}: '𘣍'
TangutComponentDash206,
/// \u{188ce}: '𘣎'
TangutComponentDash207,
/// \u{188cf}: '𘣏'
TangutComponentDash208,
/// \u{188d0}: '𘣐'
TangutComponentDash209,
/// \u{188d1}: '𘣑'
TangutComponentDash210,
/// \u{188d2}: '𘣒'
TangutComponentDash211,
/// \u{188d3}: '𘣓'
TangutComponentDash212,
/// \u{188d4}: '𘣔'
TangutComponentDash213,
/// \u{188d5}: '𘣕'
TangutComponentDash214,
/// \u{188d6}: '𘣖'
TangutComponentDash215,
/// \u{188d7}: '𘣗'
TangutComponentDash216,
/// \u{188d8}: '𘣘'
TangutComponentDash217,
/// \u{188d9}: '𘣙'
TangutComponentDash218,
/// \u{188da}: '𘣚'
TangutComponentDash219,
/// \u{188db}: '𘣛'
TangutComponentDash220,
/// \u{188dc}: '𘣜'
TangutComponentDash221,
/// \u{188dd}: '𘣝'
TangutComponentDash222,
/// \u{188de}: '𘣞'
TangutComponentDash223,
/// \u{188df}: '𘣟'
TangutComponentDash224,
/// \u{188e0}: '𘣠'
TangutComponentDash225,
/// \u{188e1}: '𘣡'
TangutComponentDash226,
/// \u{188e2}: '𘣢'
TangutComponentDash227,
/// \u{188e3}: '𘣣'
TangutComponentDash228,
/// \u{188e4}: '𘣤'
TangutComponentDash229,
/// \u{188e5}: '𘣥'
TangutComponentDash230,
/// \u{188e6}: '𘣦'
TangutComponentDash231,
/// \u{188e7}: '𘣧'
TangutComponentDash232,
/// \u{188e8}: '𘣨'
TangutComponentDash233,
/// \u{188e9}: '𘣩'
TangutComponentDash234,
/// \u{188ea}: '𘣪'
TangutComponentDash235,
/// \u{188eb}: '𘣫'
TangutComponentDash236,
/// \u{188ec}: '𘣬'
TangutComponentDash237,
/// \u{188ed}: '𘣭'
TangutComponentDash238,
/// \u{188ee}: '𘣮'
TangutComponentDash239,
/// \u{188ef}: '𘣯'
TangutComponentDash240,
/// \u{188f0}: '𘣰'
TangutComponentDash241,
/// \u{188f1}: '𘣱'
TangutComponentDash242,
/// \u{188f2}: '𘣲'
TangutComponentDash243,
/// \u{188f3}: '𘣳'
TangutComponentDash244,
/// \u{188f4}: '𘣴'
TangutComponentDash245,
/// \u{188f5}: '𘣵'
TangutComponentDash246,
/// \u{188f6}: '𘣶'
TangutComponentDash247,
/// \u{188f7}: '𘣷'
TangutComponentDash248,
/// \u{188f8}: '𘣸'
TangutComponentDash249,
/// \u{188f9}: '𘣹'
TangutComponentDash250,
/// \u{188fa}: '𘣺'
TangutComponentDash251,
/// \u{188fb}: '𘣻'
TangutComponentDash252,
/// \u{188fc}: '𘣼'
TangutComponentDash253,
/// \u{188fd}: '𘣽'
TangutComponentDash254,
/// \u{188fe}: '𘣾'
TangutComponentDash255,
/// \u{188ff}: '𘣿'
TangutComponentDash256,
/// \u{18900}: '𘤀'
TangutComponentDash257,
/// \u{18901}: '𘤁'
TangutComponentDash258,
/// \u{18902}: '𘤂'
TangutComponentDash259,
/// \u{18903}: '𘤃'
TangutComponentDash260,
/// \u{18904}: '𘤄'
TangutComponentDash261,
/// \u{18905}: '𘤅'
TangutComponentDash262,
/// \u{18906}: '𘤆'
TangutComponentDash263,
/// \u{18907}: '𘤇'
TangutComponentDash264,
/// \u{18908}: '𘤈'
TangutComponentDash265,
/// \u{18909}: '𘤉'
TangutComponentDash266,
/// \u{1890a}: '𘤊'
TangutComponentDash267,
/// \u{1890b}: '𘤋'
TangutComponentDash268,
/// \u{1890c}: '𘤌'
TangutComponentDash269,
/// \u{1890d}: '𘤍'
TangutComponentDash270,
/// \u{1890e}: '𘤎'
TangutComponentDash271,
/// \u{1890f}: '𘤏'
TangutComponentDash272,
/// \u{18910}: '𘤐'
TangutComponentDash273,
/// \u{18911}: '𘤑'
TangutComponentDash274,
/// \u{18912}: '𘤒'
TangutComponentDash275,
/// \u{18913}: '𘤓'
TangutComponentDash276,
/// \u{18914}: '𘤔'
TangutComponentDash277,
/// \u{18915}: '𘤕'
TangutComponentDash278,
/// \u{18916}: '𘤖'
TangutComponentDash279,
/// \u{18917}: '𘤗'
TangutComponentDash280,
/// \u{18918}: '𘤘'
TangutComponentDash281,
/// \u{18919}: '𘤙'
TangutComponentDash282,
/// \u{1891a}: '𘤚'
TangutComponentDash283,
/// \u{1891b}: '𘤛'
TangutComponentDash284,
/// \u{1891c}: '𘤜'
TangutComponentDash285,
/// \u{1891d}: '𘤝'
TangutComponentDash286,
/// \u{1891e}: '𘤞'
TangutComponentDash287,
/// \u{1891f}: '𘤟'
TangutComponentDash288,
/// \u{18920}: '𘤠'
TangutComponentDash289,
/// \u{18921}: '𘤡'
TangutComponentDash290,
/// \u{18922}: '𘤢'
TangutComponentDash291,
/// \u{18923}: '𘤣'
TangutComponentDash292,
/// \u{18924}: '𘤤'
TangutComponentDash293,
/// \u{18925}: '𘤥'
TangutComponentDash294,
/// \u{18926}: '𘤦'
TangutComponentDash295,
/// \u{18927}: '𘤧'
TangutComponentDash296,
/// \u{18928}: '𘤨'
TangutComponentDash297,
/// \u{18929}: '𘤩'
TangutComponentDash298,
/// \u{1892a}: '𘤪'
TangutComponentDash299,
/// \u{1892b}: '𘤫'
TangutComponentDash300,
/// \u{1892c}: '𘤬'
TangutComponentDash301,
/// \u{1892d}: '𘤭'
TangutComponentDash302,
/// \u{1892e}: '𘤮'
TangutComponentDash303,
/// \u{1892f}: '𘤯'
TangutComponentDash304,
/// \u{18930}: '𘤰'
TangutComponentDash305,
/// \u{18931}: '𘤱'
TangutComponentDash306,
/// \u{18932}: '𘤲'
TangutComponentDash307,
/// \u{18933}: '𘤳'
TangutComponentDash308,
/// \u{18934}: '𘤴'
TangutComponentDash309,
/// \u{18935}: '𘤵'
TangutComponentDash310,
/// \u{18936}: '𘤶'
TangutComponentDash311,
/// \u{18937}: '𘤷'
TangutComponentDash312,
/// \u{18938}: '𘤸'
TangutComponentDash313,
/// \u{18939}: '𘤹'
TangutComponentDash314,
/// \u{1893a}: '𘤺'
TangutComponentDash315,
/// \u{1893b}: '𘤻'
TangutComponentDash316,
/// \u{1893c}: '𘤼'
TangutComponentDash317,
/// \u{1893d}: '𘤽'
TangutComponentDash318,
/// \u{1893e}: '𘤾'
TangutComponentDash319,
/// \u{1893f}: '𘤿'
TangutComponentDash320,
/// \u{18940}: '𘥀'
TangutComponentDash321,
/// \u{18941}: '𘥁'
TangutComponentDash322,
/// \u{18942}: '𘥂'
TangutComponentDash323,
/// \u{18943}: '𘥃'
TangutComponentDash324,
/// \u{18944}: '𘥄'
TangutComponentDash325,
/// \u{18945}: '𘥅'
TangutComponentDash326,
/// \u{18946}: '𘥆'
TangutComponentDash327,
/// \u{18947}: '𘥇'
TangutComponentDash328,
/// \u{18948}: '𘥈'
TangutComponentDash329,
/// \u{18949}: '𘥉'
TangutComponentDash330,
/// \u{1894a}: '𘥊'
TangutComponentDash331,
/// \u{1894b}: '𘥋'
TangutComponentDash332,
/// \u{1894c}: '𘥌'
TangutComponentDash333,
/// \u{1894d}: '𘥍'
TangutComponentDash334,
/// \u{1894e}: '𘥎'
TangutComponentDash335,
/// \u{1894f}: '𘥏'
TangutComponentDash336,
/// \u{18950}: '𘥐'
TangutComponentDash337,
/// \u{18951}: '𘥑'
TangutComponentDash338,
/// \u{18952}: '𘥒'
TangutComponentDash339,
/// \u{18953}: '𘥓'
TangutComponentDash340,
/// \u{18954}: '𘥔'
TangutComponentDash341,
/// \u{18955}: '𘥕'
TangutComponentDash342,
/// \u{18956}: '𘥖'
TangutComponentDash343,
/// \u{18957}: '𘥗'
TangutComponentDash344,
/// \u{18958}: '𘥘'
TangutComponentDash345,
/// \u{18959}: '𘥙'
TangutComponentDash346,
/// \u{1895a}: '𘥚'
TangutComponentDash347,
/// \u{1895b}: '𘥛'
TangutComponentDash348,
/// \u{1895c}: '𘥜'
TangutComponentDash349,
/// \u{1895d}: '𘥝'
TangutComponentDash350,
/// \u{1895e}: '𘥞'
TangutComponentDash351,
/// \u{1895f}: '𘥟'
TangutComponentDash352,
/// \u{18960}: '𘥠'
TangutComponentDash353,
/// \u{18961}: '𘥡'
TangutComponentDash354,
/// \u{18962}: '𘥢'
TangutComponentDash355,
/// \u{18963}: '𘥣'
TangutComponentDash356,
/// \u{18964}: '𘥤'
TangutComponentDash357,
/// \u{18965}: '𘥥'
TangutComponentDash358,
/// \u{18966}: '𘥦'
TangutComponentDash359,
/// \u{18967}: '𘥧'
TangutComponentDash360,
/// \u{18968}: '𘥨'
TangutComponentDash361,
/// \u{18969}: '𘥩'
TangutComponentDash362,
/// \u{1896a}: '𘥪'
TangutComponentDash363,
/// \u{1896b}: '𘥫'
TangutComponentDash364,
/// \u{1896c}: '𘥬'
TangutComponentDash365,
/// \u{1896d}: '𘥭'
TangutComponentDash366,
/// \u{1896e}: '𘥮'
TangutComponentDash367,
/// \u{1896f}: '𘥯'
TangutComponentDash368,
/// \u{18970}: '𘥰'
TangutComponentDash369,
/// \u{18971}: '𘥱'
TangutComponentDash370,
/// \u{18972}: '𘥲'
TangutComponentDash371,
/// \u{18973}: '𘥳'
TangutComponentDash372,
/// \u{18974}: '𘥴'
TangutComponentDash373,
/// \u{18975}: '𘥵'
TangutComponentDash374,
/// \u{18976}: '𘥶'
TangutComponentDash375,
/// \u{18977}: '𘥷'
TangutComponentDash376,
/// \u{18978}: '𘥸'
TangutComponentDash377,
/// \u{18979}: '𘥹'
TangutComponentDash378,
/// \u{1897a}: '𘥺'
TangutComponentDash379,
/// \u{1897b}: '𘥻'
TangutComponentDash380,
/// \u{1897c}: '𘥼'
TangutComponentDash381,
/// \u{1897d}: '𘥽'
TangutComponentDash382,
/// \u{1897e}: '𘥾'
TangutComponentDash383,
/// \u{1897f}: '𘥿'
TangutComponentDash384,
/// \u{18980}: '𘦀'
TangutComponentDash385,
/// \u{18981}: '𘦁'
TangutComponentDash386,
/// \u{18982}: '𘦂'
TangutComponentDash387,
/// \u{18983}: '𘦃'
TangutComponentDash388,
/// \u{18984}: '𘦄'
TangutComponentDash389,
/// \u{18985}: '𘦅'
TangutComponentDash390,
/// \u{18986}: '𘦆'
TangutComponentDash391,
/// \u{18987}: '𘦇'
TangutComponentDash392,
/// \u{18988}: '𘦈'
TangutComponentDash393,
/// \u{18989}: '𘦉'
TangutComponentDash394,
/// \u{1898a}: '𘦊'
TangutComponentDash395,
/// \u{1898b}: '𘦋'
TangutComponentDash396,
/// \u{1898c}: '𘦌'
TangutComponentDash397,
/// \u{1898d}: '𘦍'
TangutComponentDash398,
/// \u{1898e}: '𘦎'
TangutComponentDash399,
/// \u{1898f}: '𘦏'
TangutComponentDash400,
/// \u{18990}: '𘦐'
TangutComponentDash401,
/// \u{18991}: '𘦑'
TangutComponentDash402,
/// \u{18992}: '𘦒'
TangutComponentDash403,
/// \u{18993}: '𘦓'
TangutComponentDash404,
/// \u{18994}: '𘦔'
TangutComponentDash405,
/// \u{18995}: '𘦕'
TangutComponentDash406,
/// \u{18996}: '𘦖'
TangutComponentDash407,
/// \u{18997}: '𘦗'
TangutComponentDash408,
/// \u{18998}: '𘦘'
TangutComponentDash409,
/// \u{18999}: '𘦙'
TangutComponentDash410,
/// \u{1899a}: '𘦚'
TangutComponentDash411,
/// \u{1899b}: '𘦛'
TangutComponentDash412,
/// \u{1899c}: '𘦜'
TangutComponentDash413,
/// \u{1899d}: '𘦝'
TangutComponentDash414,
/// \u{1899e}: '𘦞'
TangutComponentDash415,
/// \u{1899f}: '𘦟'
TangutComponentDash416,
/// \u{189a0}: '𘦠'
TangutComponentDash417,
/// \u{189a1}: '𘦡'
TangutComponentDash418,
/// \u{189a2}: '𘦢'
TangutComponentDash419,
/// \u{189a3}: '𘦣'
TangutComponentDash420,
/// \u{189a4}: '𘦤'
TangutComponentDash421,
/// \u{189a5}: '𘦥'
TangutComponentDash422,
/// \u{189a6}: '𘦦'
TangutComponentDash423,
/// \u{189a7}: '𘦧'
TangutComponentDash424,
/// \u{189a8}: '𘦨'
TangutComponentDash425,
/// \u{189a9}: '𘦩'
TangutComponentDash426,
/// \u{189aa}: '𘦪'
TangutComponentDash427,
/// \u{189ab}: '𘦫'
TangutComponentDash428,
/// \u{189ac}: '𘦬'
TangutComponentDash429,
/// \u{189ad}: '𘦭'
TangutComponentDash430,
/// \u{189ae}: '𘦮'
TangutComponentDash431,
/// \u{189af}: '𘦯'
TangutComponentDash432,
/// \u{189b0}: '𘦰'
TangutComponentDash433,
/// \u{189b1}: '𘦱'
TangutComponentDash434,
/// \u{189b2}: '𘦲'
TangutComponentDash435,
/// \u{189b3}: '𘦳'
TangutComponentDash436,
/// \u{189b4}: '𘦴'
TangutComponentDash437,
/// \u{189b5}: '𘦵'
TangutComponentDash438,
/// \u{189b6}: '𘦶'
TangutComponentDash439,
/// \u{189b7}: '𘦷'
TangutComponentDash440,
/// \u{189b8}: '𘦸'
TangutComponentDash441,
/// \u{189b9}: '𘦹'
TangutComponentDash442,
/// \u{189ba}: '𘦺'
TangutComponentDash443,
/// \u{189bb}: '𘦻'
TangutComponentDash444,
/// \u{189bc}: '𘦼'
TangutComponentDash445,
/// \u{189bd}: '𘦽'
TangutComponentDash446,
/// \u{189be}: '𘦾'
TangutComponentDash447,
/// \u{189bf}: '𘦿'
TangutComponentDash448,
/// \u{189c0}: '𘧀'
TangutComponentDash449,
/// \u{189c1}: '𘧁'
TangutComponentDash450,
/// \u{189c2}: '𘧂'
TangutComponentDash451,
/// \u{189c3}: '𘧃'
TangutComponentDash452,
/// \u{189c4}: '𘧄'
TangutComponentDash453,
/// \u{189c5}: '𘧅'
TangutComponentDash454,
/// \u{189c6}: '𘧆'
TangutComponentDash455,
/// \u{189c7}: '𘧇'
TangutComponentDash456,
/// \u{189c8}: '𘧈'
TangutComponentDash457,
/// \u{189c9}: '𘧉'
TangutComponentDash458,
/// \u{189ca}: '𘧊'
TangutComponentDash459,
/// \u{189cb}: '𘧋'
TangutComponentDash460,
/// \u{189cc}: '𘧌'
TangutComponentDash461,
/// \u{189cd}: '𘧍'
TangutComponentDash462,
/// \u{189ce}: '𘧎'
TangutComponentDash463,
/// \u{189cf}: '𘧏'
TangutComponentDash464,
/// \u{189d0}: '𘧐'
TangutComponentDash465,
/// \u{189d1}: '𘧑'
TangutComponentDash466,
/// \u{189d2}: '𘧒'
TangutComponentDash467,
/// \u{189d3}: '𘧓'
TangutComponentDash468,
/// \u{189d4}: '𘧔'
TangutComponentDash469,
/// \u{189d5}: '𘧕'
TangutComponentDash470,
/// \u{189d6}: '𘧖'
TangutComponentDash471,
/// \u{189d7}: '𘧗'
TangutComponentDash472,
/// \u{189d8}: '𘧘'
TangutComponentDash473,
/// \u{189d9}: '𘧙'
TangutComponentDash474,
/// \u{189da}: '𘧚'
TangutComponentDash475,
/// \u{189db}: '𘧛'
TangutComponentDash476,
/// \u{189dc}: '𘧜'
TangutComponentDash477,
/// \u{189dd}: '𘧝'
TangutComponentDash478,
/// \u{189de}: '𘧞'
TangutComponentDash479,
/// \u{189df}: '𘧟'
TangutComponentDash480,
/// \u{189e0}: '𘧠'
TangutComponentDash481,
/// \u{189e1}: '𘧡'
TangutComponentDash482,
/// \u{189e2}: '𘧢'
TangutComponentDash483,
/// \u{189e3}: '𘧣'
TangutComponentDash484,
/// \u{189e4}: '𘧤'
TangutComponentDash485,
/// \u{189e5}: '𘧥'
TangutComponentDash486,
/// \u{189e6}: '𘧦'
TangutComponentDash487,
/// \u{189e7}: '𘧧'
TangutComponentDash488,
/// \u{189e8}: '𘧨'
TangutComponentDash489,
/// \u{189e9}: '𘧩'
TangutComponentDash490,
/// \u{189ea}: '𘧪'
TangutComponentDash491,
/// \u{189eb}: '𘧫'
TangutComponentDash492,
/// \u{189ec}: '𘧬'
TangutComponentDash493,
/// \u{189ed}: '𘧭'
TangutComponentDash494,
/// \u{189ee}: '𘧮'
TangutComponentDash495,
/// \u{189ef}: '𘧯'
TangutComponentDash496,
/// \u{189f0}: '𘧰'
TangutComponentDash497,
/// \u{189f1}: '𘧱'
TangutComponentDash498,
/// \u{189f2}: '𘧲'
TangutComponentDash499,
/// \u{189f3}: '𘧳'
TangutComponentDash500,
/// \u{189f4}: '𘧴'
TangutComponentDash501,
/// \u{189f5}: '𘧵'
TangutComponentDash502,
/// \u{189f6}: '𘧶'
TangutComponentDash503,
/// \u{189f7}: '𘧷'
TangutComponentDash504,
/// \u{189f8}: '𘧸'
TangutComponentDash505,
/// \u{189f9}: '𘧹'
TangutComponentDash506,
/// \u{189fa}: '𘧺'
TangutComponentDash507,
/// \u{189fb}: '𘧻'
TangutComponentDash508,
/// \u{189fc}: '𘧼'
TangutComponentDash509,
/// \u{189fd}: '𘧽'
TangutComponentDash510,
/// \u{189fe}: '𘧾'
TangutComponentDash511,
/// \u{189ff}: '𘧿'
TangutComponentDash512,
/// \u{18a00}: '𘨀'
TangutComponentDash513,
/// \u{18a01}: '𘨁'
TangutComponentDash514,
/// \u{18a02}: '𘨂'
TangutComponentDash515,
/// \u{18a03}: '𘨃'
TangutComponentDash516,
/// \u{18a04}: '𘨄'
TangutComponentDash517,
/// \u{18a05}: '𘨅'
TangutComponentDash518,
/// \u{18a06}: '𘨆'
TangutComponentDash519,
/// \u{18a07}: '𘨇'
TangutComponentDash520,
/// \u{18a08}: '𘨈'
TangutComponentDash521,
/// \u{18a09}: '𘨉'
TangutComponentDash522,
/// \u{18a0a}: '𘨊'
TangutComponentDash523,
/// \u{18a0b}: '𘨋'
TangutComponentDash524,
/// \u{18a0c}: '𘨌'
TangutComponentDash525,
/// \u{18a0d}: '𘨍'
TangutComponentDash526,
/// \u{18a0e}: '𘨎'
TangutComponentDash527,
/// \u{18a0f}: '𘨏'
TangutComponentDash528,
/// \u{18a10}: '𘨐'
TangutComponentDash529,
/// \u{18a11}: '𘨑'
TangutComponentDash530,
/// \u{18a12}: '𘨒'
TangutComponentDash531,
/// \u{18a13}: '𘨓'
TangutComponentDash532,
/// \u{18a14}: '𘨔'
TangutComponentDash533,
/// \u{18a15}: '𘨕'
TangutComponentDash534,
/// \u{18a16}: '𘨖'
TangutComponentDash535,
/// \u{18a17}: '𘨗'
TangutComponentDash536,
/// \u{18a18}: '𘨘'
TangutComponentDash537,
/// \u{18a19}: '𘨙'
TangutComponentDash538,
/// \u{18a1a}: '𘨚'
TangutComponentDash539,
/// \u{18a1b}: '𘨛'
TangutComponentDash540,
/// \u{18a1c}: '𘨜'
TangutComponentDash541,
/// \u{18a1d}: '𘨝'
TangutComponentDash542,
/// \u{18a1e}: '𘨞'
TangutComponentDash543,
/// \u{18a1f}: '𘨟'
TangutComponentDash544,
/// \u{18a20}: '𘨠'
TangutComponentDash545,
/// \u{18a21}: '𘨡'
TangutComponentDash546,
/// \u{18a22}: '𘨢'
TangutComponentDash547,
/// \u{18a23}: '𘨣'
TangutComponentDash548,
/// \u{18a24}: '𘨤'
TangutComponentDash549,
/// \u{18a25}: '𘨥'
TangutComponentDash550,
/// \u{18a26}: '𘨦'
TangutComponentDash551,
/// \u{18a27}: '𘨧'
TangutComponentDash552,
/// \u{18a28}: '𘨨'
TangutComponentDash553,
/// \u{18a29}: '𘨩'
TangutComponentDash554,
/// \u{18a2a}: '𘨪'
TangutComponentDash555,
/// \u{18a2b}: '𘨫'
TangutComponentDash556,
/// \u{18a2c}: '𘨬'
TangutComponentDash557,
/// \u{18a2d}: '𘨭'
TangutComponentDash558,
/// \u{18a2e}: '𘨮'
TangutComponentDash559,
/// \u{18a2f}: '𘨯'
TangutComponentDash560,
/// \u{18a30}: '𘨰'
TangutComponentDash561,
/// \u{18a31}: '𘨱'
TangutComponentDash562,
/// \u{18a32}: '𘨲'
TangutComponentDash563,
/// \u{18a33}: '𘨳'
TangutComponentDash564,
/// \u{18a34}: '𘨴'
TangutComponentDash565,
/// \u{18a35}: '𘨵'
TangutComponentDash566,
/// \u{18a36}: '𘨶'
TangutComponentDash567,
/// \u{18a37}: '𘨷'
TangutComponentDash568,
/// \u{18a38}: '𘨸'
TangutComponentDash569,
/// \u{18a39}: '𘨹'
TangutComponentDash570,
/// \u{18a3a}: '𘨺'
TangutComponentDash571,
/// \u{18a3b}: '𘨻'
TangutComponentDash572,
/// \u{18a3c}: '𘨼'
TangutComponentDash573,
/// \u{18a3d}: '𘨽'
TangutComponentDash574,
/// \u{18a3e}: '𘨾'
TangutComponentDash575,
/// \u{18a3f}: '𘨿'
TangutComponentDash576,
/// \u{18a40}: '𘩀'
TangutComponentDash577,
/// \u{18a41}: '𘩁'
TangutComponentDash578,
/// \u{18a42}: '𘩂'
TangutComponentDash579,
/// \u{18a43}: '𘩃'
TangutComponentDash580,
/// \u{18a44}: '𘩄'
TangutComponentDash581,
/// \u{18a45}: '𘩅'
TangutComponentDash582,
/// \u{18a46}: '𘩆'
TangutComponentDash583,
/// \u{18a47}: '𘩇'
TangutComponentDash584,
/// \u{18a48}: '𘩈'
TangutComponentDash585,
/// \u{18a49}: '𘩉'
TangutComponentDash586,
/// \u{18a4a}: '𘩊'
TangutComponentDash587,
/// \u{18a4b}: '𘩋'
TangutComponentDash588,
/// \u{18a4c}: '𘩌'
TangutComponentDash589,
/// \u{18a4d}: '𘩍'
TangutComponentDash590,
/// \u{18a4e}: '𘩎'
TangutComponentDash591,
/// \u{18a4f}: '𘩏'
TangutComponentDash592,
/// \u{18a50}: '𘩐'
TangutComponentDash593,
/// \u{18a51}: '𘩑'
TangutComponentDash594,
/// \u{18a52}: '𘩒'
TangutComponentDash595,
/// \u{18a53}: '𘩓'
TangutComponentDash596,
/// \u{18a54}: '𘩔'
TangutComponentDash597,
/// \u{18a55}: '𘩕'
TangutComponentDash598,
/// \u{18a56}: '𘩖'
TangutComponentDash599,
/// \u{18a57}: '𘩗'
TangutComponentDash600,
/// \u{18a58}: '𘩘'
TangutComponentDash601,
/// \u{18a59}: '𘩙'
TangutComponentDash602,
/// \u{18a5a}: '𘩚'
TangutComponentDash603,
/// \u{18a5b}: '𘩛'
TangutComponentDash604,
/// \u{18a5c}: '𘩜'
TangutComponentDash605,
/// \u{18a5d}: '𘩝'
TangutComponentDash606,
/// \u{18a5e}: '𘩞'
TangutComponentDash607,
/// \u{18a5f}: '𘩟'
TangutComponentDash608,
/// \u{18a60}: '𘩠'
TangutComponentDash609,
/// \u{18a61}: '𘩡'
TangutComponentDash610,
/// \u{18a62}: '𘩢'
TangutComponentDash611,
/// \u{18a63}: '𘩣'
TangutComponentDash612,
/// \u{18a64}: '𘩤'
TangutComponentDash613,
/// \u{18a65}: '𘩥'
TangutComponentDash614,
/// \u{18a66}: '𘩦'
TangutComponentDash615,
/// \u{18a67}: '𘩧'
TangutComponentDash616,
/// \u{18a68}: '𘩨'
TangutComponentDash617,
/// \u{18a69}: '𘩩'
TangutComponentDash618,
/// \u{18a6a}: '𘩪'
TangutComponentDash619,
/// \u{18a6b}: '𘩫'
TangutComponentDash620,
/// \u{18a6c}: '𘩬'
TangutComponentDash621,
/// \u{18a6d}: '𘩭'
TangutComponentDash622,
/// \u{18a6e}: '𘩮'
TangutComponentDash623,
/// \u{18a6f}: '𘩯'
TangutComponentDash624,
/// \u{18a70}: '𘩰'
TangutComponentDash625,
/// \u{18a71}: '𘩱'
TangutComponentDash626,
/// \u{18a72}: '𘩲'
TangutComponentDash627,
/// \u{18a73}: '𘩳'
TangutComponentDash628,
/// \u{18a74}: '𘩴'
TangutComponentDash629,
/// \u{18a75}: '𘩵'
TangutComponentDash630,
/// \u{18a76}: '𘩶'
TangutComponentDash631,
/// \u{18a77}: '𘩷'
TangutComponentDash632,
/// \u{18a78}: '𘩸'
TangutComponentDash633,
/// \u{18a79}: '𘩹'
TangutComponentDash634,
/// \u{18a7a}: '𘩺'
TangutComponentDash635,
/// \u{18a7b}: '𘩻'
TangutComponentDash636,
/// \u{18a7c}: '𘩼'
TangutComponentDash637,
/// \u{18a7d}: '𘩽'
TangutComponentDash638,
/// \u{18a7e}: '𘩾'
TangutComponentDash639,
/// \u{18a7f}: '𘩿'
TangutComponentDash640,
/// \u{18a80}: '𘪀'
TangutComponentDash641,
/// \u{18a81}: '𘪁'
TangutComponentDash642,
/// \u{18a82}: '𘪂'
TangutComponentDash643,
/// \u{18a83}: '𘪃'
TangutComponentDash644,
/// \u{18a84}: '𘪄'
TangutComponentDash645,
/// \u{18a85}: '𘪅'
TangutComponentDash646,
/// \u{18a86}: '𘪆'
TangutComponentDash647,
/// \u{18a87}: '𘪇'
TangutComponentDash648,
/// \u{18a88}: '𘪈'
TangutComponentDash649,
/// \u{18a89}: '𘪉'
TangutComponentDash650,
/// \u{18a8a}: '𘪊'
TangutComponentDash651,
/// \u{18a8b}: '𘪋'
TangutComponentDash652,
/// \u{18a8c}: '𘪌'
TangutComponentDash653,
/// \u{18a8d}: '𘪍'
TangutComponentDash654,
/// \u{18a8e}: '𘪎'
TangutComponentDash655,
/// \u{18a8f}: '𘪏'
TangutComponentDash656,
/// \u{18a90}: '𘪐'
TangutComponentDash657,
/// \u{18a91}: '𘪑'
TangutComponentDash658,
/// \u{18a92}: '𘪒'
TangutComponentDash659,
/// \u{18a93}: '𘪓'
TangutComponentDash660,
/// \u{18a94}: '𘪔'
TangutComponentDash661,
/// \u{18a95}: '𘪕'
TangutComponentDash662,
/// \u{18a96}: '𘪖'
TangutComponentDash663,
/// \u{18a97}: '𘪗'
TangutComponentDash664,
/// \u{18a98}: '𘪘'
TangutComponentDash665,
/// \u{18a99}: '𘪙'
TangutComponentDash666,
/// \u{18a9a}: '𘪚'
TangutComponentDash667,
/// \u{18a9b}: '𘪛'
TangutComponentDash668,
/// \u{18a9c}: '𘪜'
TangutComponentDash669,
/// \u{18a9d}: '𘪝'
TangutComponentDash670,
/// \u{18a9e}: '𘪞'
TangutComponentDash671,
/// \u{18a9f}: '𘪟'
TangutComponentDash672,
/// \u{18aa0}: '𘪠'
TangutComponentDash673,
/// \u{18aa1}: '𘪡'
TangutComponentDash674,
/// \u{18aa2}: '𘪢'
TangutComponentDash675,
/// \u{18aa3}: '𘪣'
TangutComponentDash676,
/// \u{18aa4}: '𘪤'
TangutComponentDash677,
/// \u{18aa5}: '𘪥'
TangutComponentDash678,
/// \u{18aa6}: '𘪦'
TangutComponentDash679,
/// \u{18aa7}: '𘪧'
TangutComponentDash680,
/// \u{18aa8}: '𘪨'
TangutComponentDash681,
/// \u{18aa9}: '𘪩'
TangutComponentDash682,
/// \u{18aaa}: '𘪪'
TangutComponentDash683,
/// \u{18aab}: '𘪫'
TangutComponentDash684,
/// \u{18aac}: '𘪬'
TangutComponentDash685,
/// \u{18aad}: '𘪭'
TangutComponentDash686,
/// \u{18aae}: '𘪮'
TangutComponentDash687,
/// \u{18aaf}: '𘪯'
TangutComponentDash688,
/// \u{18ab0}: '𘪰'
TangutComponentDash689,
/// \u{18ab1}: '𘪱'
TangutComponentDash690,
/// \u{18ab2}: '𘪲'
TangutComponentDash691,
/// \u{18ab3}: '𘪳'
TangutComponentDash692,
/// \u{18ab4}: '𘪴'
TangutComponentDash693,
/// \u{18ab5}: '𘪵'
TangutComponentDash694,
/// \u{18ab6}: '𘪶'
TangutComponentDash695,
/// \u{18ab7}: '𘪷'
TangutComponentDash696,
/// \u{18ab8}: '𘪸'
TangutComponentDash697,
/// \u{18ab9}: '𘪹'
TangutComponentDash698,
/// \u{18aba}: '𘪺'
TangutComponentDash699,
/// \u{18abb}: '𘪻'
TangutComponentDash700,
/// \u{18abc}: '𘪼'
TangutComponentDash701,
/// \u{18abd}: '𘪽'
TangutComponentDash702,
/// \u{18abe}: '𘪾'
TangutComponentDash703,
/// \u{18abf}: '𘪿'
TangutComponentDash704,
/// \u{18ac0}: '𘫀'
TangutComponentDash705,
/// \u{18ac1}: '𘫁'
TangutComponentDash706,
/// \u{18ac2}: '𘫂'
TangutComponentDash707,
/// \u{18ac3}: '𘫃'
TangutComponentDash708,
/// \u{18ac4}: '𘫄'
TangutComponentDash709,
/// \u{18ac5}: '𘫅'
TangutComponentDash710,
/// \u{18ac6}: '𘫆'
TangutComponentDash711,
/// \u{18ac7}: '𘫇'
TangutComponentDash712,
/// \u{18ac8}: '𘫈'
TangutComponentDash713,
/// \u{18ac9}: '𘫉'
TangutComponentDash714,
/// \u{18aca}: '𘫊'
TangutComponentDash715,
/// \u{18acb}: '𘫋'
TangutComponentDash716,
/// \u{18acc}: '𘫌'
TangutComponentDash717,
/// \u{18acd}: '𘫍'
TangutComponentDash718,
/// \u{18ace}: '𘫎'
TangutComponentDash719,
/// \u{18acf}: '𘫏'
TangutComponentDash720,
/// \u{18ad0}: '𘫐'
TangutComponentDash721,
/// \u{18ad1}: '𘫑'
TangutComponentDash722,
/// \u{18ad2}: '𘫒'
TangutComponentDash723,
/// \u{18ad3}: '𘫓'
TangutComponentDash724,
/// \u{18ad4}: '𘫔'
TangutComponentDash725,
/// \u{18ad5}: '𘫕'
TangutComponentDash726,
/// \u{18ad6}: '𘫖'
TangutComponentDash727,
/// \u{18ad7}: '𘫗'
TangutComponentDash728,
/// \u{18ad8}: '𘫘'
TangutComponentDash729,
/// \u{18ad9}: '𘫙'
TangutComponentDash730,
/// \u{18ada}: '𘫚'
TangutComponentDash731,
/// \u{18adb}: '𘫛'
TangutComponentDash732,
/// \u{18adc}: '𘫜'
TangutComponentDash733,
/// \u{18add}: '𘫝'
TangutComponentDash734,
/// \u{18ade}: '𘫞'
TangutComponentDash735,
/// \u{18adf}: '𘫟'
TangutComponentDash736,
/// \u{18ae0}: '𘫠'
TangutComponentDash737,
/// \u{18ae1}: '𘫡'
TangutComponentDash738,
/// \u{18ae2}: '𘫢'
TangutComponentDash739,
/// \u{18ae3}: '𘫣'
TangutComponentDash740,
/// \u{18ae4}: '𘫤'
TangutComponentDash741,
/// \u{18ae5}: '𘫥'
TangutComponentDash742,
/// \u{18ae6}: '𘫦'
TangutComponentDash743,
/// \u{18ae7}: '𘫧'
TangutComponentDash744,
/// \u{18ae8}: '𘫨'
TangutComponentDash745,
/// \u{18ae9}: '𘫩'
TangutComponentDash746,
/// \u{18aea}: '𘫪'
TangutComponentDash747,
/// \u{18aeb}: '𘫫'
TangutComponentDash748,
/// \u{18aec}: '𘫬'
TangutComponentDash749,
/// \u{18aed}: '𘫭'
TangutComponentDash750,
/// \u{18aee}: '𘫮'
TangutComponentDash751,
/// \u{18aef}: '𘫯'
TangutComponentDash752,
/// \u{18af0}: '𘫰'
TangutComponentDash753,
/// \u{18af1}: '𘫱'
TangutComponentDash754,
/// \u{18af2}: '𘫲'
TangutComponentDash755,
}
impl Into<char> for TangutComponents {
fn into(self) -> char {
match self {
TangutComponents::TangutComponentDash001 => '𘠀',
TangutComponents::TangutComponentDash002 => '𘠁',
TangutComponents::TangutComponentDash003 => '𘠂',
TangutComponents::TangutComponentDash004 => '𘠃',
TangutComponents::TangutComponentDash005 => '𘠄',
TangutComponents::TangutComponentDash006 => '𘠅',
TangutComponents::TangutComponentDash007 => '𘠆',
TangutComponents::TangutComponentDash008 => '𘠇',
TangutComponents::TangutComponentDash009 => '𘠈',
TangutComponents::TangutComponentDash010 => '𘠉',
TangutComponents::TangutComponentDash011 => '𘠊',
TangutComponents::TangutComponentDash012 => '𘠋',
TangutComponents::TangutComponentDash013 => '𘠌',
TangutComponents::TangutComponentDash014 => '𘠍',
TangutComponents::TangutComponentDash015 => '𘠎',
TangutComponents::TangutComponentDash016 => '𘠏',
TangutComponents::TangutComponentDash017 => '𘠐',
TangutComponents::TangutComponentDash018 => '𘠑',
TangutComponents::TangutComponentDash019 => '𘠒',
TangutComponents::TangutComponentDash020 => '𘠓',
TangutComponents::TangutComponentDash021 => '𘠔',
TangutComponents::TangutComponentDash022 => '𘠕',
TangutComponents::TangutComponentDash023 => '𘠖',
TangutComponents::TangutComponentDash024 => '𘠗',
TangutComponents::TangutComponentDash025 => '𘠘',
TangutComponents::TangutComponentDash026 => '𘠙',
TangutComponents::TangutComponentDash027 => '𘠚',
TangutComponents::TangutComponentDash028 => '𘠛',
TangutComponents::TangutComponentDash029 => '𘠜',
TangutComponents::TangutComponentDash030 => '𘠝',
TangutComponents::TangutComponentDash031 => '𘠞',
TangutComponents::TangutComponentDash032 => '𘠟',
TangutComponents::TangutComponentDash033 => '𘠠',
TangutComponents::TangutComponentDash034 => '𘠡',
TangutComponents::TangutComponentDash035 => '𘠢',
TangutComponents::TangutComponentDash036 => '𘠣',
TangutComponents::TangutComponentDash037 => '𘠤',
TangutComponents::TangutComponentDash038 => '𘠥',
TangutComponents::TangutComponentDash039 => '𘠦',
TangutComponents::TangutComponentDash040 => '𘠧',
TangutComponents::TangutComponentDash041 => '𘠨',
TangutComponents::TangutComponentDash042 => '𘠩',
TangutComponents::TangutComponentDash043 => '𘠪',
TangutComponents::TangutComponentDash044 => '𘠫',
TangutComponents::TangutComponentDash045 => '𘠬',
TangutComponents::TangutComponentDash046 => '𘠭',
TangutComponents::TangutComponentDash047 => '𘠮',
TangutComponents::TangutComponentDash048 => '𘠯',
TangutComponents::TangutComponentDash049 => '𘠰',
TangutComponents::TangutComponentDash050 => '𘠱',
TangutComponents::TangutComponentDash051 => '𘠲',
TangutComponents::TangutComponentDash052 => '𘠳',
TangutComponents::TangutComponentDash053 => '𘠴',
TangutComponents::TangutComponentDash054 => '𘠵',
TangutComponents::TangutComponentDash055 => '𘠶',
TangutComponents::TangutComponentDash056 => '𘠷',
TangutComponents::TangutComponentDash057 => '𘠸',
TangutComponents::TangutComponentDash058 => '𘠹',
TangutComponents::TangutComponentDash059 => '𘠺',
TangutComponents::TangutComponentDash060 => '𘠻',
TangutComponents::TangutComponentDash061 => '𘠼',
TangutComponents::TangutComponentDash062 => '𘠽',
TangutComponents::TangutComponentDash063 => '𘠾',
TangutComponents::TangutComponentDash064 => '𘠿',
TangutComponents::TangutComponentDash065 => '𘡀',
TangutComponents::TangutComponentDash066 => '𘡁',
TangutComponents::TangutComponentDash067 => '𘡂',
TangutComponents::TangutComponentDash068 => '𘡃',
TangutComponents::TangutComponentDash069 => '𘡄',
TangutComponents::TangutComponentDash070 => '𘡅',
TangutComponents::TangutComponentDash071 => '𘡆',
TangutComponents::TangutComponentDash072 => '𘡇',
TangutComponents::TangutComponentDash073 => '𘡈',
TangutComponents::TangutComponentDash074 => '𘡉',
TangutComponents::TangutComponentDash075 => '𘡊',
TangutComponents::TangutComponentDash076 => '𘡋',
TangutComponents::TangutComponentDash077 => '𘡌',
TangutComponents::TangutComponentDash078 => '𘡍',
TangutComponents::TangutComponentDash079 => '𘡎',
TangutComponents::TangutComponentDash080 => '𘡏',
TangutComponents::TangutComponentDash081 => '𘡐',
TangutComponents::TangutComponentDash082 => '𘡑',
TangutComponents::TangutComponentDash083 => '𘡒',
TangutComponents::TangutComponentDash084 => '𘡓',
TangutComponents::TangutComponentDash085 => '𘡔',
TangutComponents::TangutComponentDash086 => '𘡕',
TangutComponents::TangutComponentDash087 => '𘡖',
TangutComponents::TangutComponentDash088 => '𘡗',
TangutComponents::TangutComponentDash089 => '𘡘',
TangutComponents::TangutComponentDash090 => '𘡙',
TangutComponents::TangutComponentDash091 => '𘡚',
TangutComponents::TangutComponentDash092 => '𘡛',
TangutComponents::TangutComponentDash093 => '𘡜',
TangutComponents::TangutComponentDash094 => '𘡝',
TangutComponents::TangutComponentDash095 => '𘡞',
TangutComponents::TangutComponentDash096 => '𘡟',
TangutComponents::TangutComponentDash097 => '𘡠',
TangutComponents::TangutComponentDash098 => '𘡡',
TangutComponents::TangutComponentDash099 => '𘡢',
TangutComponents::TangutComponentDash100 => '𘡣',
TangutComponents::TangutComponentDash101 => '𘡤',
TangutComponents::TangutComponentDash102 => '𘡥',
TangutComponents::TangutComponentDash103 => '𘡦',
TangutComponents::TangutComponentDash104 => '𘡧',
TangutComponents::TangutComponentDash105 => '𘡨',
TangutComponents::TangutComponentDash106 => '𘡩',
TangutComponents::TangutComponentDash107 => '𘡪',
TangutComponents::TangutComponentDash108 => '𘡫',
TangutComponents::TangutComponentDash109 => '𘡬',
TangutComponents::TangutComponentDash110 => '𘡭',
TangutComponents::TangutComponentDash111 => '𘡮',
TangutComponents::TangutComponentDash112 => '𘡯',
TangutComponents::TangutComponentDash113 => '𘡰',
TangutComponents::TangutComponentDash114 => '𘡱',
TangutComponents::TangutComponentDash115 => '𘡲',
TangutComponents::TangutComponentDash116 => '𘡳',
TangutComponents::TangutComponentDash117 => '𘡴',
TangutComponents::TangutComponentDash118 => '𘡵',
TangutComponents::TangutComponentDash119 => '𘡶',
TangutComponents::TangutComponentDash120 => '𘡷',
TangutComponents::TangutComponentDash121 => '𘡸',
TangutComponents::TangutComponentDash122 => '𘡹',
TangutComponents::TangutComponentDash123 => '𘡺',
TangutComponents::TangutComponentDash124 => '𘡻',
TangutComponents::TangutComponentDash125 => '𘡼',
TangutComponents::TangutComponentDash126 => '𘡽',
TangutComponents::TangutComponentDash127 => '𘡾',
TangutComponents::TangutComponentDash128 => '𘡿',
TangutComponents::TangutComponentDash129 => '𘢀',
TangutComponents::TangutComponentDash130 => '𘢁',
TangutComponents::TangutComponentDash131 => '𘢂',
TangutComponents::TangutComponentDash132 => '𘢃',
TangutComponents::TangutComponentDash133 => '𘢄',
TangutComponents::TangutComponentDash134 => '𘢅',
TangutComponents::TangutComponentDash135 => '𘢆',
TangutComponents::TangutComponentDash136 => '𘢇',
TangutComponents::TangutComponentDash137 => '𘢈',
TangutComponents::TangutComponentDash138 => '𘢉',
TangutComponents::TangutComponentDash139 => '𘢊',
TangutComponents::TangutComponentDash140 => '𘢋',
TangutComponents::TangutComponentDash141 => '𘢌',
TangutComponents::TangutComponentDash142 => '𘢍',
TangutComponents::TangutComponentDash143 => '𘢎',
TangutComponents::TangutComponentDash144 => '𘢏',
TangutComponents::TangutComponentDash145 => '𘢐',
TangutComponents::TangutComponentDash146 => '𘢑',
TangutComponents::TangutComponentDash147 => '𘢒',
TangutComponents::TangutComponentDash148 => '𘢓',
TangutComponents::TangutComponentDash149 => '𘢔',
TangutComponents::TangutComponentDash150 => '𘢕',
TangutComponents::TangutComponentDash151 => '𘢖',
TangutComponents::TangutComponentDash152 => '𘢗',
TangutComponents::TangutComponentDash153 => '𘢘',
TangutComponents::TangutComponentDash154 => '𘢙',
TangutComponents::TangutComponentDash155 => '𘢚',
TangutComponents::TangutComponentDash156 => '𘢛',
TangutComponents::TangutComponentDash157 => '𘢜',
TangutComponents::TangutComponentDash158 => '𘢝',
TangutComponents::TangutComponentDash159 => '𘢞',
TangutComponents::TangutComponentDash160 => '𘢟',
TangutComponents::TangutComponentDash161 => '𘢠',
TangutComponents::TangutComponentDash162 => '𘢡',
TangutComponents::TangutComponentDash163 => '𘢢',
TangutComponents::TangutComponentDash164 => '𘢣',
TangutComponents::TangutComponentDash165 => '𘢤',
TangutComponents::TangutComponentDash166 => '𘢥',
TangutComponents::TangutComponentDash167 => '𘢦',
TangutComponents::TangutComponentDash168 => '𘢧',
TangutComponents::TangutComponentDash169 => '𘢨',
TangutComponents::TangutComponentDash170 => '𘢩',
TangutComponents::TangutComponentDash171 => '𘢪',
TangutComponents::TangutComponentDash172 => '𘢫',
TangutComponents::TangutComponentDash173 => '𘢬',
TangutComponents::TangutComponentDash174 => '𘢭',
TangutComponents::TangutComponentDash175 => '𘢮',
TangutComponents::TangutComponentDash176 => '𘢯',
TangutComponents::TangutComponentDash177 => '𘢰',
TangutComponents::TangutComponentDash178 => '𘢱',
TangutComponents::TangutComponentDash179 => '𘢲',
TangutComponents::TangutComponentDash180 => '𘢳',
TangutComponents::TangutComponentDash181 => '𘢴',
TangutComponents::TangutComponentDash182 => '𘢵',
TangutComponents::TangutComponentDash183 => '𘢶',
TangutComponents::TangutComponentDash184 => '𘢷',
TangutComponents::TangutComponentDash185 => '𘢸',
TangutComponents::TangutComponentDash186 => '𘢹',
TangutComponents::TangutComponentDash187 => '𘢺',
TangutComponents::TangutComponentDash188 => '𘢻',
TangutComponents::TangutComponentDash189 => '𘢼',
TangutComponents::TangutComponentDash190 => '𘢽',
TangutComponents::TangutComponentDash191 => '𘢾',
TangutComponents::TangutComponentDash192 => '𘢿',
TangutComponents::TangutComponentDash193 => '𘣀',
TangutComponents::TangutComponentDash194 => '𘣁',
TangutComponents::TangutComponentDash195 => '𘣂',
TangutComponents::TangutComponentDash196 => '𘣃',
TangutComponents::TangutComponentDash197 => '𘣄',
TangutComponents::TangutComponentDash198 => '𘣅',
TangutComponents::TangutComponentDash199 => '𘣆',
TangutComponents::TangutComponentDash200 => '𘣇',
TangutComponents::TangutComponentDash201 => '𘣈',
TangutComponents::TangutComponentDash202 => '𘣉',
TangutComponents::TangutComponentDash203 => '𘣊',
TangutComponents::TangutComponentDash204 => '𘣋',
TangutComponents::TangutComponentDash205 => '𘣌',
TangutComponents::TangutComponentDash206 => '𘣍',
TangutComponents::TangutComponentDash207 => '𘣎',
TangutComponents::TangutComponentDash208 => '𘣏',
TangutComponents::TangutComponentDash209 => '𘣐',
TangutComponents::TangutComponentDash210 => '𘣑',
TangutComponents::TangutComponentDash211 => '𘣒',
TangutComponents::TangutComponentDash212 => '𘣓',
TangutComponents::TangutComponentDash213 => '𘣔',
TangutComponents::TangutComponentDash214 => '𘣕',
TangutComponents::TangutComponentDash215 => '𘣖',
TangutComponents::TangutComponentDash216 => '𘣗',
TangutComponents::TangutComponentDash217 => '𘣘',
TangutComponents::TangutComponentDash218 => '𘣙',
TangutComponents::TangutComponentDash219 => '𘣚',
TangutComponents::TangutComponentDash220 => '𘣛',
TangutComponents::TangutComponentDash221 => '𘣜',
TangutComponents::TangutComponentDash222 => '𘣝',
TangutComponents::TangutComponentDash223 => '𘣞',
TangutComponents::TangutComponentDash224 => '𘣟',
TangutComponents::TangutComponentDash225 => '𘣠',
TangutComponents::TangutComponentDash226 => '𘣡',
TangutComponents::TangutComponentDash227 => '𘣢',
TangutComponents::TangutComponentDash228 => '𘣣',
TangutComponents::TangutComponentDash229 => '𘣤',
TangutComponents::TangutComponentDash230 => '𘣥',
TangutComponents::TangutComponentDash231 => '𘣦',
TangutComponents::TangutComponentDash232 => '𘣧',
TangutComponents::TangutComponentDash233 => '𘣨',
TangutComponents::TangutComponentDash234 => '𘣩',
TangutComponents::TangutComponentDash235 => '𘣪',
TangutComponents::TangutComponentDash236 => '𘣫',
TangutComponents::TangutComponentDash237 => '𘣬',
TangutComponents::TangutComponentDash238 => '𘣭',
TangutComponents::TangutComponentDash239 => '𘣮',
TangutComponents::TangutComponentDash240 => '𘣯',
TangutComponents::TangutComponentDash241 => '𘣰',
TangutComponents::TangutComponentDash242 => '𘣱',
TangutComponents::TangutComponentDash243 => '𘣲',
TangutComponents::TangutComponentDash244 => '𘣳',
TangutComponents::TangutComponentDash245 => '𘣴',
TangutComponents::TangutComponentDash246 => '𘣵',
TangutComponents::TangutComponentDash247 => '𘣶',
TangutComponents::TangutComponentDash248 => '𘣷',
TangutComponents::TangutComponentDash249 => '𘣸',
TangutComponents::TangutComponentDash250 => '𘣹',
TangutComponents::TangutComponentDash251 => '𘣺',
TangutComponents::TangutComponentDash252 => '𘣻',
TangutComponents::TangutComponentDash253 => '𘣼',
TangutComponents::TangutComponentDash254 => '𘣽',
TangutComponents::TangutComponentDash255 => '𘣾',
TangutComponents::TangutComponentDash256 => '𘣿',
TangutComponents::TangutComponentDash257 => '𘤀',
TangutComponents::TangutComponentDash258 => '𘤁',
TangutComponents::TangutComponentDash259 => '𘤂',
TangutComponents::TangutComponentDash260 => '𘤃',
TangutComponents::TangutComponentDash261 => '𘤄',
TangutComponents::TangutComponentDash262 => '𘤅',
TangutComponents::TangutComponentDash263 => '𘤆',
TangutComponents::TangutComponentDash264 => '𘤇',
TangutComponents::TangutComponentDash265 => '𘤈',
TangutComponents::TangutComponentDash266 => '𘤉',
TangutComponents::TangutComponentDash267 => '𘤊',
TangutComponents::TangutComponentDash268 => '𘤋',
TangutComponents::TangutComponentDash269 => '𘤌',
TangutComponents::TangutComponentDash270 => '𘤍',
TangutComponents::TangutComponentDash271 => '𘤎',
TangutComponents::TangutComponentDash272 => '𘤏',
TangutComponents::TangutComponentDash273 => '𘤐',
TangutComponents::TangutComponentDash274 => '𘤑',
TangutComponents::TangutComponentDash275 => '𘤒',
TangutComponents::TangutComponentDash276 => '𘤓',
TangutComponents::TangutComponentDash277 => '𘤔',
TangutComponents::TangutComponentDash278 => '𘤕',
TangutComponents::TangutComponentDash279 => '𘤖',
TangutComponents::TangutComponentDash280 => '𘤗',
TangutComponents::TangutComponentDash281 => '𘤘',
TangutComponents::TangutComponentDash282 => '𘤙',
TangutComponents::TangutComponentDash283 => '𘤚',
TangutComponents::TangutComponentDash284 => '𘤛',
TangutComponents::TangutComponentDash285 => '𘤜',
TangutComponents::TangutComponentDash286 => '𘤝',
TangutComponents::TangutComponentDash287 => '𘤞',
TangutComponents::TangutComponentDash288 => '𘤟',
TangutComponents::TangutComponentDash289 => '𘤠',
TangutComponents::TangutComponentDash290 => '𘤡',
TangutComponents::TangutComponentDash291 => '𘤢',
TangutComponents::TangutComponentDash292 => '𘤣',
TangutComponents::TangutComponentDash293 => '𘤤',
TangutComponents::TangutComponentDash294 => '𘤥',
TangutComponents::TangutComponentDash295 => '𘤦',
TangutComponents::TangutComponentDash296 => '𘤧',
TangutComponents::TangutComponentDash297 => '𘤨',
TangutComponents::TangutComponentDash298 => '𘤩',
TangutComponents::TangutComponentDash299 => '𘤪',
TangutComponents::TangutComponentDash300 => '𘤫',
TangutComponents::TangutComponentDash301 => '𘤬',
TangutComponents::TangutComponentDash302 => '𘤭',
TangutComponents::TangutComponentDash303 => '𘤮',
TangutComponents::TangutComponentDash304 => '𘤯',
TangutComponents::TangutComponentDash305 => '𘤰',
TangutComponents::TangutComponentDash306 => '𘤱',
TangutComponents::TangutComponentDash307 => '𘤲',
TangutComponents::TangutComponentDash308 => '𘤳',
TangutComponents::TangutComponentDash309 => '𘤴',
TangutComponents::TangutComponentDash310 => '𘤵',
TangutComponents::TangutComponentDash311 => '𘤶',
TangutComponents::TangutComponentDash312 => '𘤷',
TangutComponents::TangutComponentDash313 => '𘤸',
TangutComponents::TangutComponentDash314 => '𘤹',
TangutComponents::TangutComponentDash315 => '𘤺',
TangutComponents::TangutComponentDash316 => '𘤻',
TangutComponents::TangutComponentDash317 => '𘤼',
TangutComponents::TangutComponentDash318 => '𘤽',
TangutComponents::TangutComponentDash319 => '𘤾',
TangutComponents::TangutComponentDash320 => '𘤿',
TangutComponents::TangutComponentDash321 => '𘥀',
TangutComponents::TangutComponentDash322 => '𘥁',
TangutComponents::TangutComponentDash323 => '𘥂',
TangutComponents::TangutComponentDash324 => '𘥃',
TangutComponents::TangutComponentDash325 => '𘥄',
TangutComponents::TangutComponentDash326 => '𘥅',
TangutComponents::TangutComponentDash327 => '𘥆',
TangutComponents::TangutComponentDash328 => '𘥇',
TangutComponents::TangutComponentDash329 => '𘥈',
TangutComponents::TangutComponentDash330 => '𘥉',
TangutComponents::TangutComponentDash331 => '𘥊',
TangutComponents::TangutComponentDash332 => '𘥋',
TangutComponents::TangutComponentDash333 => '𘥌',
TangutComponents::TangutComponentDash334 => '𘥍',
TangutComponents::TangutComponentDash335 => '𘥎',
TangutComponents::TangutComponentDash336 => '𘥏',
TangutComponents::TangutComponentDash337 => '𘥐',
TangutComponents::TangutComponentDash338 => '𘥑',
TangutComponents::TangutComponentDash339 => '𘥒',
TangutComponents::TangutComponentDash340 => '𘥓',
TangutComponents::TangutComponentDash341 => '𘥔',
TangutComponents::TangutComponentDash342 => '𘥕',
TangutComponents::TangutComponentDash343 => '𘥖',
TangutComponents::TangutComponentDash344 => '𘥗',
TangutComponents::TangutComponentDash345 => '𘥘',
TangutComponents::TangutComponentDash346 => '𘥙',
TangutComponents::TangutComponentDash347 => '𘥚',
TangutComponents::TangutComponentDash348 => '𘥛',
TangutComponents::TangutComponentDash349 => '𘥜',
TangutComponents::TangutComponentDash350 => '𘥝',
TangutComponents::TangutComponentDash351 => '𘥞',
TangutComponents::TangutComponentDash352 => '𘥟',
TangutComponents::TangutComponentDash353 => '𘥠',
TangutComponents::TangutComponentDash354 => '𘥡',
TangutComponents::TangutComponentDash355 => '𘥢',
TangutComponents::TangutComponentDash356 => '𘥣',
TangutComponents::TangutComponentDash357 => '𘥤',
TangutComponents::TangutComponentDash358 => '𘥥',
TangutComponents::TangutComponentDash359 => '𘥦',
TangutComponents::TangutComponentDash360 => '𘥧',
TangutComponents::TangutComponentDash361 => '𘥨',
TangutComponents::TangutComponentDash362 => '𘥩',
TangutComponents::TangutComponentDash363 => '𘥪',
TangutComponents::TangutComponentDash364 => '𘥫',
TangutComponents::TangutComponentDash365 => '𘥬',
TangutComponents::TangutComponentDash366 => '𘥭',
TangutComponents::TangutComponentDash367 => '𘥮',
TangutComponents::TangutComponentDash368 => '𘥯',
TangutComponents::TangutComponentDash369 => '𘥰',
TangutComponents::TangutComponentDash370 => '𘥱',
TangutComponents::TangutComponentDash371 => '𘥲',
TangutComponents::TangutComponentDash372 => '𘥳',
TangutComponents::TangutComponentDash373 => '𘥴',
TangutComponents::TangutComponentDash374 => '𘥵',
TangutComponents::TangutComponentDash375 => '𘥶',
TangutComponents::TangutComponentDash376 => '𘥷',
TangutComponents::TangutComponentDash377 => '𘥸',
TangutComponents::TangutComponentDash378 => '𘥹',
TangutComponents::TangutComponentDash379 => '𘥺',
TangutComponents::TangutComponentDash380 => '𘥻',
TangutComponents::TangutComponentDash381 => '𘥼',
TangutComponents::TangutComponentDash382 => '𘥽',
TangutComponents::TangutComponentDash383 => '𘥾',
TangutComponents::TangutComponentDash384 => '𘥿',
TangutComponents::TangutComponentDash385 => '𘦀',
TangutComponents::TangutComponentDash386 => '𘦁',
TangutComponents::TangutComponentDash387 => '𘦂',
TangutComponents::TangutComponentDash388 => '𘦃',
TangutComponents::TangutComponentDash389 => '𘦄',
TangutComponents::TangutComponentDash390 => '𘦅',
TangutComponents::TangutComponentDash391 => '𘦆',
TangutComponents::TangutComponentDash392 => '𘦇',
TangutComponents::TangutComponentDash393 => '𘦈',
TangutComponents::TangutComponentDash394 => '𘦉',
TangutComponents::TangutComponentDash395 => '𘦊',
TangutComponents::TangutComponentDash396 => '𘦋',
TangutComponents::TangutComponentDash397 => '𘦌',
TangutComponents::TangutComponentDash398 => '𘦍',
TangutComponents::TangutComponentDash399 => '𘦎',
TangutComponents::TangutComponentDash400 => '𘦏',
TangutComponents::TangutComponentDash401 => '𘦐',
TangutComponents::TangutComponentDash402 => '𘦑',
TangutComponents::TangutComponentDash403 => '𘦒',
TangutComponents::TangutComponentDash404 => '𘦓',
TangutComponents::TangutComponentDash405 => '𘦔',
TangutComponents::TangutComponentDash406 => '𘦕',
TangutComponents::TangutComponentDash407 => '𘦖',
TangutComponents::TangutComponentDash408 => '𘦗',
TangutComponents::TangutComponentDash409 => '𘦘',
TangutComponents::TangutComponentDash410 => '𘦙',
TangutComponents::TangutComponentDash411 => '𘦚',
TangutComponents::TangutComponentDash412 => '𘦛',
TangutComponents::TangutComponentDash413 => '𘦜',
TangutComponents::TangutComponentDash414 => '𘦝',
TangutComponents::TangutComponentDash415 => '𘦞',
TangutComponents::TangutComponentDash416 => '𘦟',
TangutComponents::TangutComponentDash417 => '𘦠',
TangutComponents::TangutComponentDash418 => '𘦡',
TangutComponents::TangutComponentDash419 => '𘦢',
TangutComponents::TangutComponentDash420 => '𘦣',
TangutComponents::TangutComponentDash421 => '𘦤',
TangutComponents::TangutComponentDash422 => '𘦥',
TangutComponents::TangutComponentDash423 => '𘦦',
TangutComponents::TangutComponentDash424 => '𘦧',
TangutComponents::TangutComponentDash425 => '𘦨',
TangutComponents::TangutComponentDash426 => '𘦩',
TangutComponents::TangutComponentDash427 => '𘦪',
TangutComponents::TangutComponentDash428 => '𘦫',
TangutComponents::TangutComponentDash429 => '𘦬',
TangutComponents::TangutComponentDash430 => '𘦭',
TangutComponents::TangutComponentDash431 => '𘦮',
TangutComponents::TangutComponentDash432 => '𘦯',
TangutComponents::TangutComponentDash433 => '𘦰',
TangutComponents::TangutComponentDash434 => '𘦱',
TangutComponents::TangutComponentDash435 => '𘦲',
TangutComponents::TangutComponentDash436 => '𘦳',
TangutComponents::TangutComponentDash437 => '𘦴',
TangutComponents::TangutComponentDash438 => '𘦵',
TangutComponents::TangutComponentDash439 => '𘦶',
TangutComponents::TangutComponentDash440 => '𘦷',
TangutComponents::TangutComponentDash441 => '𘦸',
TangutComponents::TangutComponentDash442 => '𘦹',
TangutComponents::TangutComponentDash443 => '𘦺',
TangutComponents::TangutComponentDash444 => '𘦻',
TangutComponents::TangutComponentDash445 => '𘦼',
TangutComponents::TangutComponentDash446 => '𘦽',
TangutComponents::TangutComponentDash447 => '𘦾',
TangutComponents::TangutComponentDash448 => '𘦿',
TangutComponents::TangutComponentDash449 => '𘧀',
TangutComponents::TangutComponentDash450 => '𘧁',
TangutComponents::TangutComponentDash451 => '𘧂',
TangutComponents::TangutComponentDash452 => '𘧃',
TangutComponents::TangutComponentDash453 => '𘧄',
TangutComponents::TangutComponentDash454 => '𘧅',
TangutComponents::TangutComponentDash455 => '𘧆',
TangutComponents::TangutComponentDash456 => '𘧇',
TangutComponents::TangutComponentDash457 => '𘧈',
TangutComponents::TangutComponentDash458 => '𘧉',
TangutComponents::TangutComponentDash459 => '𘧊',
TangutComponents::TangutComponentDash460 => '𘧋',
TangutComponents::TangutComponentDash461 => '𘧌',
TangutComponents::TangutComponentDash462 => '𘧍',
TangutComponents::TangutComponentDash463 => '𘧎',
TangutComponents::TangutComponentDash464 => '𘧏',
TangutComponents::TangutComponentDash465 => '𘧐',
TangutComponents::TangutComponentDash466 => '𘧑',
TangutComponents::TangutComponentDash467 => '𘧒',
TangutComponents::TangutComponentDash468 => '𘧓',
TangutComponents::TangutComponentDash469 => '𘧔',
TangutComponents::TangutComponentDash470 => '𘧕',
TangutComponents::TangutComponentDash471 => '𘧖',
TangutComponents::TangutComponentDash472 => '𘧗',
TangutComponents::TangutComponentDash473 => '𘧘',
TangutComponents::TangutComponentDash474 => '𘧙',
TangutComponents::TangutComponentDash475 => '𘧚',
TangutComponents::TangutComponentDash476 => '𘧛',
TangutComponents::TangutComponentDash477 => '𘧜',
TangutComponents::TangutComponentDash478 => '𘧝',
TangutComponents::TangutComponentDash479 => '𘧞',
TangutComponents::TangutComponentDash480 => '𘧟',
TangutComponents::TangutComponentDash481 => '𘧠',
TangutComponents::TangutComponentDash482 => '𘧡',
TangutComponents::TangutComponentDash483 => '𘧢',
TangutComponents::TangutComponentDash484 => '𘧣',
TangutComponents::TangutComponentDash485 => '𘧤',
TangutComponents::TangutComponentDash486 => '𘧥',
TangutComponents::TangutComponentDash487 => '𘧦',
TangutComponents::TangutComponentDash488 => '𘧧',
TangutComponents::TangutComponentDash489 => '𘧨',
TangutComponents::TangutComponentDash490 => '𘧩',
TangutComponents::TangutComponentDash491 => '𘧪',
TangutComponents::TangutComponentDash492 => '𘧫',
TangutComponents::TangutComponentDash493 => '𘧬',
TangutComponents::TangutComponentDash494 => '𘧭',
TangutComponents::TangutComponentDash495 => '𘧮',
TangutComponents::TangutComponentDash496 => '𘧯',
TangutComponents::TangutComponentDash497 => '𘧰',
TangutComponents::TangutComponentDash498 => '𘧱',
TangutComponents::TangutComponentDash499 => '𘧲',
TangutComponents::TangutComponentDash500 => '𘧳',
TangutComponents::TangutComponentDash501 => '𘧴',
TangutComponents::TangutComponentDash502 => '𘧵',
TangutComponents::TangutComponentDash503 => '𘧶',
TangutComponents::TangutComponentDash504 => '𘧷',
TangutComponents::TangutComponentDash505 => '𘧸',
TangutComponents::TangutComponentDash506 => '𘧹',
TangutComponents::TangutComponentDash507 => '𘧺',
TangutComponents::TangutComponentDash508 => '𘧻',
TangutComponents::TangutComponentDash509 => '𘧼',
TangutComponents::TangutComponentDash510 => '𘧽',
TangutComponents::TangutComponentDash511 => '𘧾',
TangutComponents::TangutComponentDash512 => '𘧿',
TangutComponents::TangutComponentDash513 => '𘨀',
TangutComponents::TangutComponentDash514 => '𘨁',
TangutComponents::TangutComponentDash515 => '𘨂',
TangutComponents::TangutComponentDash516 => '𘨃',
TangutComponents::TangutComponentDash517 => '𘨄',
TangutComponents::TangutComponentDash518 => '𘨅',
TangutComponents::TangutComponentDash519 => '𘨆',
TangutComponents::TangutComponentDash520 => '𘨇',
TangutComponents::TangutComponentDash521 => '𘨈',
TangutComponents::TangutComponentDash522 => '𘨉',
TangutComponents::TangutComponentDash523 => '𘨊',
TangutComponents::TangutComponentDash524 => '𘨋',
TangutComponents::TangutComponentDash525 => '𘨌',
TangutComponents::TangutComponentDash526 => '𘨍',
TangutComponents::TangutComponentDash527 => '𘨎',
TangutComponents::TangutComponentDash528 => '𘨏',
TangutComponents::TangutComponentDash529 => '𘨐',
TangutComponents::TangutComponentDash530 => '𘨑',
TangutComponents::TangutComponentDash531 => '𘨒',
TangutComponents::TangutComponentDash532 => '𘨓',
TangutComponents::TangutComponentDash533 => '𘨔',
TangutComponents::TangutComponentDash534 => '𘨕',
TangutComponents::TangutComponentDash535 => '𘨖',
TangutComponents::TangutComponentDash536 => '𘨗',
TangutComponents::TangutComponentDash537 => '𘨘',
TangutComponents::TangutComponentDash538 => '𘨙',
TangutComponents::TangutComponentDash539 => '𘨚',
TangutComponents::TangutComponentDash540 => '𘨛',
TangutComponents::TangutComponentDash541 => '𘨜',
TangutComponents::TangutComponentDash542 => '𘨝',
TangutComponents::TangutComponentDash543 => '𘨞',
TangutComponents::TangutComponentDash544 => '𘨟',
TangutComponents::TangutComponentDash545 => '𘨠',
TangutComponents::TangutComponentDash546 => '𘨡',
TangutComponents::TangutComponentDash547 => '𘨢',
TangutComponents::TangutComponentDash548 => '𘨣',
TangutComponents::TangutComponentDash549 => '𘨤',
TangutComponents::TangutComponentDash550 => '𘨥',
TangutComponents::TangutComponentDash551 => '𘨦',
TangutComponents::TangutComponentDash552 => '𘨧',
TangutComponents::TangutComponentDash553 => '𘨨',
TangutComponents::TangutComponentDash554 => '𘨩',
TangutComponents::TangutComponentDash555 => '𘨪',
TangutComponents::TangutComponentDash556 => '𘨫',
TangutComponents::TangutComponentDash557 => '𘨬',
TangutComponents::TangutComponentDash558 => '𘨭',
TangutComponents::TangutComponentDash559 => '𘨮',
TangutComponents::TangutComponentDash560 => '𘨯',
TangutComponents::TangutComponentDash561 => '𘨰',
TangutComponents::TangutComponentDash562 => '𘨱',
TangutComponents::TangutComponentDash563 => '𘨲',
TangutComponents::TangutComponentDash564 => '𘨳',
TangutComponents::TangutComponentDash565 => '𘨴',
TangutComponents::TangutComponentDash566 => '𘨵',
TangutComponents::TangutComponentDash567 => '𘨶',
TangutComponents::TangutComponentDash568 => '𘨷',
TangutComponents::TangutComponentDash569 => '𘨸',
TangutComponents::TangutComponentDash570 => '𘨹',
TangutComponents::TangutComponentDash571 => '𘨺',
TangutComponents::TangutComponentDash572 => '𘨻',
TangutComponents::TangutComponentDash573 => '𘨼',
TangutComponents::TangutComponentDash574 => '𘨽',
TangutComponents::TangutComponentDash575 => '𘨾',
TangutComponents::TangutComponentDash576 => '𘨿',
TangutComponents::TangutComponentDash577 => '𘩀',
TangutComponents::TangutComponentDash578 => '𘩁',
TangutComponents::TangutComponentDash579 => '𘩂',
TangutComponents::TangutComponentDash580 => '𘩃',
TangutComponents::TangutComponentDash581 => '𘩄',
TangutComponents::TangutComponentDash582 => '𘩅',
TangutComponents::TangutComponentDash583 => '𘩆',
TangutComponents::TangutComponentDash584 => '𘩇',
TangutComponents::TangutComponentDash585 => '𘩈',
TangutComponents::TangutComponentDash586 => '𘩉',
TangutComponents::TangutComponentDash587 => '𘩊',
TangutComponents::TangutComponentDash588 => '𘩋',
TangutComponents::TangutComponentDash589 => '𘩌',
TangutComponents::TangutComponentDash590 => '𘩍',
TangutComponents::TangutComponentDash591 => '𘩎',
TangutComponents::TangutComponentDash592 => '𘩏',
TangutComponents::TangutComponentDash593 => '𘩐',
TangutComponents::TangutComponentDash594 => '𘩑',
TangutComponents::TangutComponentDash595 => '𘩒',
TangutComponents::TangutComponentDash596 => '𘩓',
TangutComponents::TangutComponentDash597 => '𘩔',
TangutComponents::TangutComponentDash598 => '𘩕',
TangutComponents::TangutComponentDash599 => '𘩖',
TangutComponents::TangutComponentDash600 => '𘩗',
TangutComponents::TangutComponentDash601 => '𘩘',
TangutComponents::TangutComponentDash602 => '𘩙',
TangutComponents::TangutComponentDash603 => '𘩚',
TangutComponents::TangutComponentDash604 => '𘩛',
TangutComponents::TangutComponentDash605 => '𘩜',
TangutComponents::TangutComponentDash606 => '𘩝',
TangutComponents::TangutComponentDash607 => '𘩞',
TangutComponents::TangutComponentDash608 => '𘩟',
TangutComponents::TangutComponentDash609 => '𘩠',
TangutComponents::TangutComponentDash610 => '𘩡',
TangutComponents::TangutComponentDash611 => '𘩢',
TangutComponents::TangutComponentDash612 => '𘩣',
TangutComponents::TangutComponentDash613 => '𘩤',
TangutComponents::TangutComponentDash614 => '𘩥',
TangutComponents::TangutComponentDash615 => '𘩦',
TangutComponents::TangutComponentDash616 => '𘩧',
TangutComponents::TangutComponentDash617 => '𘩨',
TangutComponents::TangutComponentDash618 => '𘩩',
TangutComponents::TangutComponentDash619 => '𘩪',
TangutComponents::TangutComponentDash620 => '𘩫',
TangutComponents::TangutComponentDash621 => '𘩬',
TangutComponents::TangutComponentDash622 => '𘩭',
TangutComponents::TangutComponentDash623 => '𘩮',
TangutComponents::TangutComponentDash624 => '𘩯',
TangutComponents::TangutComponentDash625 => '𘩰',
TangutComponents::TangutComponentDash626 => '𘩱',
TangutComponents::TangutComponentDash627 => '𘩲',
TangutComponents::TangutComponentDash628 => '𘩳',
TangutComponents::TangutComponentDash629 => '𘩴',
TangutComponents::TangutComponentDash630 => '𘩵',
TangutComponents::TangutComponentDash631 => '𘩶',
TangutComponents::TangutComponentDash632 => '𘩷',
TangutComponents::TangutComponentDash633 => '𘩸',
TangutComponents::TangutComponentDash634 => '𘩹',
TangutComponents::TangutComponentDash635 => '𘩺',
TangutComponents::TangutComponentDash636 => '𘩻',
TangutComponents::TangutComponentDash637 => '𘩼',
TangutComponents::TangutComponentDash638 => '𘩽',
TangutComponents::TangutComponentDash639 => '𘩾',
TangutComponents::TangutComponentDash640 => '𘩿',
TangutComponents::TangutComponentDash641 => '𘪀',
TangutComponents::TangutComponentDash642 => '𘪁',
TangutComponents::TangutComponentDash643 => '𘪂',
TangutComponents::TangutComponentDash644 => '𘪃',
TangutComponents::TangutComponentDash645 => '𘪄',
TangutComponents::TangutComponentDash646 => '𘪅',
TangutComponents::TangutComponentDash647 => '𘪆',
TangutComponents::TangutComponentDash648 => '𘪇',
TangutComponents::TangutComponentDash649 => '𘪈',
TangutComponents::TangutComponentDash650 => '𘪉',
TangutComponents::TangutComponentDash651 => '𘪊',
TangutComponents::TangutComponentDash652 => '𘪋',
TangutComponents::TangutComponentDash653 => '𘪌',
TangutComponents::TangutComponentDash654 => '𘪍',
TangutComponents::TangutComponentDash655 => '𘪎',
TangutComponents::TangutComponentDash656 => '𘪏',
TangutComponents::TangutComponentDash657 => '𘪐',
TangutComponents::TangutComponentDash658 => '𘪑',
TangutComponents::TangutComponentDash659 => '𘪒',
TangutComponents::TangutComponentDash660 => '𘪓',
TangutComponents::TangutComponentDash661 => '𘪔',
TangutComponents::TangutComponentDash662 => '𘪕',
TangutComponents::TangutComponentDash663 => '𘪖',
TangutComponents::TangutComponentDash664 => '𘪗',
TangutComponents::TangutComponentDash665 => '𘪘',
TangutComponents::TangutComponentDash666 => '𘪙',
TangutComponents::TangutComponentDash667 => '𘪚',
TangutComponents::TangutComponentDash668 => '𘪛',
TangutComponents::TangutComponentDash669 => '𘪜',
TangutComponents::TangutComponentDash670 => '𘪝',
TangutComponents::TangutComponentDash671 => '𘪞',
TangutComponents::TangutComponentDash672 => '𘪟',
TangutComponents::TangutComponentDash673 => '𘪠',
TangutComponents::TangutComponentDash674 => '𘪡',
TangutComponents::TangutComponentDash675 => '𘪢',
TangutComponents::TangutComponentDash676 => '𘪣',
TangutComponents::TangutComponentDash677 => '𘪤',
TangutComponents::TangutComponentDash678 => '𘪥',
TangutComponents::TangutComponentDash679 => '𘪦',
TangutComponents::TangutComponentDash680 => '𘪧',
TangutComponents::TangutComponentDash681 => '𘪨',
TangutComponents::TangutComponentDash682 => '𘪩',
TangutComponents::TangutComponentDash683 => '𘪪',
TangutComponents::TangutComponentDash684 => '𘪫',
TangutComponents::TangutComponentDash685 => '𘪬',
TangutComponents::TangutComponentDash686 => '𘪭',
TangutComponents::TangutComponentDash687 => '𘪮',
TangutComponents::TangutComponentDash688 => '𘪯',
TangutComponents::TangutComponentDash689 => '𘪰',
TangutComponents::TangutComponentDash690 => '𘪱',
TangutComponents::TangutComponentDash691 => '𘪲',
TangutComponents::TangutComponentDash692 => '𘪳',
TangutComponents::TangutComponentDash693 => '𘪴',
TangutComponents::TangutComponentDash694 => '𘪵',
TangutComponents::TangutComponentDash695 => '𘪶',
TangutComponents::TangutComponentDash696 => '𘪷',
TangutComponents::TangutComponentDash697 => '𘪸',
TangutComponents::TangutComponentDash698 => '𘪹',
TangutComponents::TangutComponentDash699 => '𘪺',
TangutComponents::TangutComponentDash700 => '𘪻',
TangutComponents::TangutComponentDash701 => '𘪼',
TangutComponents::TangutComponentDash702 => '𘪽',
TangutComponents::TangutComponentDash703 => '𘪾',
TangutComponents::TangutComponentDash704 => '𘪿',
TangutComponents::TangutComponentDash705 => '𘫀',
TangutComponents::TangutComponentDash706 => '𘫁',
TangutComponents::TangutComponentDash707 => '𘫂',
TangutComponents::TangutComponentDash708 => '𘫃',
TangutComponents::TangutComponentDash709 => '𘫄',
TangutComponents::TangutComponentDash710 => '𘫅',
TangutComponents::TangutComponentDash711 => '𘫆',
TangutComponents::TangutComponentDash712 => '𘫇',
TangutComponents::TangutComponentDash713 => '𘫈',
TangutComponents::TangutComponentDash714 => '𘫉',
TangutComponents::TangutComponentDash715 => '𘫊',
TangutComponents::TangutComponentDash716 => '𘫋',
TangutComponents::TangutComponentDash717 => '𘫌',
TangutComponents::TangutComponentDash718 => '𘫍',
TangutComponents::TangutComponentDash719 => '𘫎',
TangutComponents::TangutComponentDash720 => '𘫏',
TangutComponents::TangutComponentDash721 => '𘫐',
TangutComponents::TangutComponentDash722 => '𘫑',
TangutComponents::TangutComponentDash723 => '𘫒',
TangutComponents::TangutComponentDash724 => '𘫓',
TangutComponents::TangutComponentDash725 => '𘫔',
TangutComponents::TangutComponentDash726 => '𘫕',
TangutComponents::TangutComponentDash727 => '𘫖',
TangutComponents::TangutComponentDash728 => '𘫗',
TangutComponents::TangutComponentDash729 => '𘫘',
TangutComponents::TangutComponentDash730 => '𘫙',
TangutComponents::TangutComponentDash731 => '𘫚',
TangutComponents::TangutComponentDash732 => '𘫛',
TangutComponents::TangutComponentDash733 => '𘫜',
TangutComponents::TangutComponentDash734 => '𘫝',
TangutComponents::TangutComponentDash735 => '𘫞',
TangutComponents::TangutComponentDash736 => '𘫟',
TangutComponents::TangutComponentDash737 => '𘫠',
TangutComponents::TangutComponentDash738 => '𘫡',
TangutComponents::TangutComponentDash739 => '𘫢',
TangutComponents::TangutComponentDash740 => '𘫣',
TangutComponents::TangutComponentDash741 => '𘫤',
TangutComponents::TangutComponentDash742 => '𘫥',
TangutComponents::TangutComponentDash743 => '𘫦',
TangutComponents::TangutComponentDash744 => '𘫧',
TangutComponents::TangutComponentDash745 => '𘫨',
TangutComponents::TangutComponentDash746 => '𘫩',
TangutComponents::TangutComponentDash747 => '𘫪',
TangutComponents::TangutComponentDash748 => '𘫫',
TangutComponents::TangutComponentDash749 => '𘫬',
TangutComponents::TangutComponentDash750 => '𘫭',
TangutComponents::TangutComponentDash751 => '𘫮',
TangutComponents::TangutComponentDash752 => '𘫯',
TangutComponents::TangutComponentDash753 => '𘫰',
TangutComponents::TangutComponentDash754 => '𘫱',
TangutComponents::TangutComponentDash755 => '𘫲',
}
}
}
impl std::convert::TryFrom<char> for TangutComponents {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'𘠀' => Ok(TangutComponents::TangutComponentDash001),
'𘠁' => Ok(TangutComponents::TangutComponentDash002),
'𘠂' => Ok(TangutComponents::TangutComponentDash003),
'𘠃' => Ok(TangutComponents::TangutComponentDash004),
'𘠄' => Ok(TangutComponents::TangutComponentDash005),
'𘠅' => Ok(TangutComponents::TangutComponentDash006),
'𘠆' => Ok(TangutComponents::TangutComponentDash007),
'𘠇' => Ok(TangutComponents::TangutComponentDash008),
'𘠈' => Ok(TangutComponents::TangutComponentDash009),
'𘠉' => Ok(TangutComponents::TangutComponentDash010),
'𘠊' => Ok(TangutComponents::TangutComponentDash011),
'𘠋' => Ok(TangutComponents::TangutComponentDash012),
'𘠌' => Ok(TangutComponents::TangutComponentDash013),
'𘠍' => Ok(TangutComponents::TangutComponentDash014),
'𘠎' => Ok(TangutComponents::TangutComponentDash015),
'𘠏' => Ok(TangutComponents::TangutComponentDash016),
'𘠐' => Ok(TangutComponents::TangutComponentDash017),
'𘠑' => Ok(TangutComponents::TangutComponentDash018),
'𘠒' => Ok(TangutComponents::TangutComponentDash019),
'𘠓' => Ok(TangutComponents::TangutComponentDash020),
'𘠔' => Ok(TangutComponents::TangutComponentDash021),
'𘠕' => Ok(TangutComponents::TangutComponentDash022),
'𘠖' => Ok(TangutComponents::TangutComponentDash023),
'𘠗' => Ok(TangutComponents::TangutComponentDash024),
'𘠘' => Ok(TangutComponents::TangutComponentDash025),
'𘠙' => Ok(TangutComponents::TangutComponentDash026),
'𘠚' => Ok(TangutComponents::TangutComponentDash027),
'𘠛' => Ok(TangutComponents::TangutComponentDash028),
'𘠜' => Ok(TangutComponents::TangutComponentDash029),
'𘠝' => Ok(TangutComponents::TangutComponentDash030),
'𘠞' => Ok(TangutComponents::TangutComponentDash031),
'𘠟' => Ok(TangutComponents::TangutComponentDash032),
'𘠠' => Ok(TangutComponents::TangutComponentDash033),
'𘠡' => Ok(TangutComponents::TangutComponentDash034),
'𘠢' => Ok(TangutComponents::TangutComponentDash035),
'𘠣' => Ok(TangutComponents::TangutComponentDash036),
'𘠤' => Ok(TangutComponents::TangutComponentDash037),
'𘠥' => Ok(TangutComponents::TangutComponentDash038),
'𘠦' => Ok(TangutComponents::TangutComponentDash039),
'𘠧' => Ok(TangutComponents::TangutComponentDash040),
'𘠨' => Ok(TangutComponents::TangutComponentDash041),
'𘠩' => Ok(TangutComponents::TangutComponentDash042),
'𘠪' => Ok(TangutComponents::TangutComponentDash043),
'𘠫' => Ok(TangutComponents::TangutComponentDash044),
'𘠬' => Ok(TangutComponents::TangutComponentDash045),
'𘠭' => Ok(TangutComponents::TangutComponentDash046),
'𘠮' => Ok(TangutComponents::TangutComponentDash047),
'𘠯' => Ok(TangutComponents::TangutComponentDash048),
'𘠰' => Ok(TangutComponents::TangutComponentDash049),
'𘠱' => Ok(TangutComponents::TangutComponentDash050),
'𘠲' => Ok(TangutComponents::TangutComponentDash051),
'𘠳' => Ok(TangutComponents::TangutComponentDash052),
'𘠴' => Ok(TangutComponents::TangutComponentDash053),
'𘠵' => Ok(TangutComponents::TangutComponentDash054),
'𘠶' => Ok(TangutComponents::TangutComponentDash055),
'𘠷' => Ok(TangutComponents::TangutComponentDash056),
'𘠸' => Ok(TangutComponents::TangutComponentDash057),
'𘠹' => Ok(TangutComponents::TangutComponentDash058),
'𘠺' => Ok(TangutComponents::TangutComponentDash059),
'𘠻' => Ok(TangutComponents::TangutComponentDash060),
'𘠼' => Ok(TangutComponents::TangutComponentDash061),
'𘠽' => Ok(TangutComponents::TangutComponentDash062),
'𘠾' => Ok(TangutComponents::TangutComponentDash063),
'𘠿' => Ok(TangutComponents::TangutComponentDash064),
'𘡀' => Ok(TangutComponents::TangutComponentDash065),
'𘡁' => Ok(TangutComponents::TangutComponentDash066),
'𘡂' => Ok(TangutComponents::TangutComponentDash067),
'𘡃' => Ok(TangutComponents::TangutComponentDash068),
'𘡄' => Ok(TangutComponents::TangutComponentDash069),
'𘡅' => Ok(TangutComponents::TangutComponentDash070),
'𘡆' => Ok(TangutComponents::TangutComponentDash071),
'𘡇' => Ok(TangutComponents::TangutComponentDash072),
'𘡈' => Ok(TangutComponents::TangutComponentDash073),
'𘡉' => Ok(TangutComponents::TangutComponentDash074),
'𘡊' => Ok(TangutComponents::TangutComponentDash075),
'𘡋' => Ok(TangutComponents::TangutComponentDash076),
'𘡌' => Ok(TangutComponents::TangutComponentDash077),
'𘡍' => Ok(TangutComponents::TangutComponentDash078),
'𘡎' => Ok(TangutComponents::TangutComponentDash079),
'𘡏' => Ok(TangutComponents::TangutComponentDash080),
'𘡐' => Ok(TangutComponents::TangutComponentDash081),
'𘡑' => Ok(TangutComponents::TangutComponentDash082),
'𘡒' => Ok(TangutComponents::TangutComponentDash083),
'𘡓' => Ok(TangutComponents::TangutComponentDash084),
'𘡔' => Ok(TangutComponents::TangutComponentDash085),
'𘡕' => Ok(TangutComponents::TangutComponentDash086),
'𘡖' => Ok(TangutComponents::TangutComponentDash087),
'𘡗' => Ok(TangutComponents::TangutComponentDash088),
'𘡘' => Ok(TangutComponents::TangutComponentDash089),
'𘡙' => Ok(TangutComponents::TangutComponentDash090),
'𘡚' => Ok(TangutComponents::TangutComponentDash091),
'𘡛' => Ok(TangutComponents::TangutComponentDash092),
'𘡜' => Ok(TangutComponents::TangutComponentDash093),
'𘡝' => Ok(TangutComponents::TangutComponentDash094),
'𘡞' => Ok(TangutComponents::TangutComponentDash095),
'𘡟' => Ok(TangutComponents::TangutComponentDash096),
'𘡠' => Ok(TangutComponents::TangutComponentDash097),
'𘡡' => Ok(TangutComponents::TangutComponentDash098),
'𘡢' => Ok(TangutComponents::TangutComponentDash099),
'𘡣' => Ok(TangutComponents::TangutComponentDash100),
'𘡤' => Ok(TangutComponents::TangutComponentDash101),
'𘡥' => Ok(TangutComponents::TangutComponentDash102),
'𘡦' => Ok(TangutComponents::TangutComponentDash103),
'𘡧' => Ok(TangutComponents::TangutComponentDash104),
'𘡨' => Ok(TangutComponents::TangutComponentDash105),
'𘡩' => Ok(TangutComponents::TangutComponentDash106),
'𘡪' => Ok(TangutComponents::TangutComponentDash107),
'𘡫' => Ok(TangutComponents::TangutComponentDash108),
'𘡬' => Ok(TangutComponents::TangutComponentDash109),
'𘡭' => Ok(TangutComponents::TangutComponentDash110),
'𘡮' => Ok(TangutComponents::TangutComponentDash111),
'𘡯' => Ok(TangutComponents::TangutComponentDash112),
'𘡰' => Ok(TangutComponents::TangutComponentDash113),
'𘡱' => Ok(TangutComponents::TangutComponentDash114),
'𘡲' => Ok(TangutComponents::TangutComponentDash115),
'𘡳' => Ok(TangutComponents::TangutComponentDash116),
'𘡴' => Ok(TangutComponents::TangutComponentDash117),
'𘡵' => Ok(TangutComponents::TangutComponentDash118),
'𘡶' => Ok(TangutComponents::TangutComponentDash119),
'𘡷' => Ok(TangutComponents::TangutComponentDash120),
'𘡸' => Ok(TangutComponents::TangutComponentDash121),
'𘡹' => Ok(TangutComponents::TangutComponentDash122),
'𘡺' => Ok(TangutComponents::TangutComponentDash123),
'𘡻' => Ok(TangutComponents::TangutComponentDash124),
'𘡼' => Ok(TangutComponents::TangutComponentDash125),
'𘡽' => Ok(TangutComponents::TangutComponentDash126),
'𘡾' => Ok(TangutComponents::TangutComponentDash127),
'𘡿' => Ok(TangutComponents::TangutComponentDash128),
'𘢀' => Ok(TangutComponents::TangutComponentDash129),
'𘢁' => Ok(TangutComponents::TangutComponentDash130),
'𘢂' => Ok(TangutComponents::TangutComponentDash131),
'𘢃' => Ok(TangutComponents::TangutComponentDash132),
'𘢄' => Ok(TangutComponents::TangutComponentDash133),
'𘢅' => Ok(TangutComponents::TangutComponentDash134),
'𘢆' => Ok(TangutComponents::TangutComponentDash135),
'𘢇' => Ok(TangutComponents::TangutComponentDash136),
'𘢈' => Ok(TangutComponents::TangutComponentDash137),
'𘢉' => Ok(TangutComponents::TangutComponentDash138),
'𘢊' => Ok(TangutComponents::TangutComponentDash139),
'𘢋' => Ok(TangutComponents::TangutComponentDash140),
'𘢌' => Ok(TangutComponents::TangutComponentDash141),
'𘢍' => Ok(TangutComponents::TangutComponentDash142),
'𘢎' => Ok(TangutComponents::TangutComponentDash143),
'𘢏' => Ok(TangutComponents::TangutComponentDash144),
'𘢐' => Ok(TangutComponents::TangutComponentDash145),
'𘢑' => Ok(TangutComponents::TangutComponentDash146),
'𘢒' => Ok(TangutComponents::TangutComponentDash147),
'𘢓' => Ok(TangutComponents::TangutComponentDash148),
'𘢔' => Ok(TangutComponents::TangutComponentDash149),
'𘢕' => Ok(TangutComponents::TangutComponentDash150),
'𘢖' => Ok(TangutComponents::TangutComponentDash151),
'𘢗' => Ok(TangutComponents::TangutComponentDash152),
'𘢘' => Ok(TangutComponents::TangutComponentDash153),
'𘢙' => Ok(TangutComponents::TangutComponentDash154),
'𘢚' => Ok(TangutComponents::TangutComponentDash155),
'𘢛' => Ok(TangutComponents::TangutComponentDash156),
'𘢜' => Ok(TangutComponents::TangutComponentDash157),
'𘢝' => Ok(TangutComponents::TangutComponentDash158),
'𘢞' => Ok(TangutComponents::TangutComponentDash159),
'𘢟' => Ok(TangutComponents::TangutComponentDash160),
'𘢠' => Ok(TangutComponents::TangutComponentDash161),
'𘢡' => Ok(TangutComponents::TangutComponentDash162),
'𘢢' => Ok(TangutComponents::TangutComponentDash163),
'𘢣' => Ok(TangutComponents::TangutComponentDash164),
'𘢤' => Ok(TangutComponents::TangutComponentDash165),
'𘢥' => Ok(TangutComponents::TangutComponentDash166),
'𘢦' => Ok(TangutComponents::TangutComponentDash167),
'𘢧' => Ok(TangutComponents::TangutComponentDash168),
'𘢨' => Ok(TangutComponents::TangutComponentDash169),
'𘢩' => Ok(TangutComponents::TangutComponentDash170),
'𘢪' => Ok(TangutComponents::TangutComponentDash171),
'𘢫' => Ok(TangutComponents::TangutComponentDash172),
'𘢬' => Ok(TangutComponents::TangutComponentDash173),
'𘢭' => Ok(TangutComponents::TangutComponentDash174),
'𘢮' => Ok(TangutComponents::TangutComponentDash175),
'𘢯' => Ok(TangutComponents::TangutComponentDash176),
'𘢰' => Ok(TangutComponents::TangutComponentDash177),
'𘢱' => Ok(TangutComponents::TangutComponentDash178),
'𘢲' => Ok(TangutComponents::TangutComponentDash179),
'𘢳' => Ok(TangutComponents::TangutComponentDash180),
'𘢴' => Ok(TangutComponents::TangutComponentDash181),
'𘢵' => Ok(TangutComponents::TangutComponentDash182),
'𘢶' => Ok(TangutComponents::TangutComponentDash183),
'𘢷' => Ok(TangutComponents::TangutComponentDash184),
'𘢸' => Ok(TangutComponents::TangutComponentDash185),
'𘢹' => Ok(TangutComponents::TangutComponentDash186),
'𘢺' => Ok(TangutComponents::TangutComponentDash187),
'𘢻' => Ok(TangutComponents::TangutComponentDash188),
'𘢼' => Ok(TangutComponents::TangutComponentDash189),
'𘢽' => Ok(TangutComponents::TangutComponentDash190),
'𘢾' => Ok(TangutComponents::TangutComponentDash191),
'𘢿' => Ok(TangutComponents::TangutComponentDash192),
'𘣀' => Ok(TangutComponents::TangutComponentDash193),
'𘣁' => Ok(TangutComponents::TangutComponentDash194),
'𘣂' => Ok(TangutComponents::TangutComponentDash195),
'𘣃' => Ok(TangutComponents::TangutComponentDash196),
'𘣄' => Ok(TangutComponents::TangutComponentDash197),
'𘣅' => Ok(TangutComponents::TangutComponentDash198),
'𘣆' => Ok(TangutComponents::TangutComponentDash199),
'𘣇' => Ok(TangutComponents::TangutComponentDash200),
'𘣈' => Ok(TangutComponents::TangutComponentDash201),
'𘣉' => Ok(TangutComponents::TangutComponentDash202),
'𘣊' => Ok(TangutComponents::TangutComponentDash203),
'𘣋' => Ok(TangutComponents::TangutComponentDash204),
'𘣌' => Ok(TangutComponents::TangutComponentDash205),
'𘣍' => Ok(TangutComponents::TangutComponentDash206),
'𘣎' => Ok(TangutComponents::TangutComponentDash207),
'𘣏' => Ok(TangutComponents::TangutComponentDash208),
'𘣐' => Ok(TangutComponents::TangutComponentDash209),
'𘣑' => Ok(TangutComponents::TangutComponentDash210),
'𘣒' => Ok(TangutComponents::TangutComponentDash211),
'𘣓' => Ok(TangutComponents::TangutComponentDash212),
'𘣔' => Ok(TangutComponents::TangutComponentDash213),
'𘣕' => Ok(TangutComponents::TangutComponentDash214),
'𘣖' => Ok(TangutComponents::TangutComponentDash215),
'𘣗' => Ok(TangutComponents::TangutComponentDash216),
'𘣘' => Ok(TangutComponents::TangutComponentDash217),
'𘣙' => Ok(TangutComponents::TangutComponentDash218),
'𘣚' => Ok(TangutComponents::TangutComponentDash219),
'𘣛' => Ok(TangutComponents::TangutComponentDash220),
'𘣜' => Ok(TangutComponents::TangutComponentDash221),
'𘣝' => Ok(TangutComponents::TangutComponentDash222),
'𘣞' => Ok(TangutComponents::TangutComponentDash223),
'𘣟' => Ok(TangutComponents::TangutComponentDash224),
'𘣠' => Ok(TangutComponents::TangutComponentDash225),
'𘣡' => Ok(TangutComponents::TangutComponentDash226),
'𘣢' => Ok(TangutComponents::TangutComponentDash227),
'𘣣' => Ok(TangutComponents::TangutComponentDash228),
'𘣤' => Ok(TangutComponents::TangutComponentDash229),
'𘣥' => Ok(TangutComponents::TangutComponentDash230),
'𘣦' => Ok(TangutComponents::TangutComponentDash231),
'𘣧' => Ok(TangutComponents::TangutComponentDash232),
'𘣨' => Ok(TangutComponents::TangutComponentDash233),
'𘣩' => Ok(TangutComponents::TangutComponentDash234),
'𘣪' => Ok(TangutComponents::TangutComponentDash235),
'𘣫' => Ok(TangutComponents::TangutComponentDash236),
'𘣬' => Ok(TangutComponents::TangutComponentDash237),
'𘣭' => Ok(TangutComponents::TangutComponentDash238),
'𘣮' => Ok(TangutComponents::TangutComponentDash239),
'𘣯' => Ok(TangutComponents::TangutComponentDash240),
'𘣰' => Ok(TangutComponents::TangutComponentDash241),
'𘣱' => Ok(TangutComponents::TangutComponentDash242),
'𘣲' => Ok(TangutComponents::TangutComponentDash243),
'𘣳' => Ok(TangutComponents::TangutComponentDash244),
'𘣴' => Ok(TangutComponents::TangutComponentDash245),
'𘣵' => Ok(TangutComponents::TangutComponentDash246),
'𘣶' => Ok(TangutComponents::TangutComponentDash247),
'𘣷' => Ok(TangutComponents::TangutComponentDash248),
'𘣸' => Ok(TangutComponents::TangutComponentDash249),
'𘣹' => Ok(TangutComponents::TangutComponentDash250),
'𘣺' => Ok(TangutComponents::TangutComponentDash251),
'𘣻' => Ok(TangutComponents::TangutComponentDash252),
'𘣼' => Ok(TangutComponents::TangutComponentDash253),
'𘣽' => Ok(TangutComponents::TangutComponentDash254),
'𘣾' => Ok(TangutComponents::TangutComponentDash255),
'𘣿' => Ok(TangutComponents::TangutComponentDash256),
'𘤀' => Ok(TangutComponents::TangutComponentDash257),
'𘤁' => Ok(TangutComponents::TangutComponentDash258),
'𘤂' => Ok(TangutComponents::TangutComponentDash259),
'𘤃' => Ok(TangutComponents::TangutComponentDash260),
'𘤄' => Ok(TangutComponents::TangutComponentDash261),
'𘤅' => Ok(TangutComponents::TangutComponentDash262),
'𘤆' => Ok(TangutComponents::TangutComponentDash263),
'𘤇' => Ok(TangutComponents::TangutComponentDash264),
'𘤈' => Ok(TangutComponents::TangutComponentDash265),
'𘤉' => Ok(TangutComponents::TangutComponentDash266),
'𘤊' => Ok(TangutComponents::TangutComponentDash267),
'𘤋' => Ok(TangutComponents::TangutComponentDash268),
'𘤌' => Ok(TangutComponents::TangutComponentDash269),
'𘤍' => Ok(TangutComponents::TangutComponentDash270),
'𘤎' => Ok(TangutComponents::TangutComponentDash271),
'𘤏' => Ok(TangutComponents::TangutComponentDash272),
'𘤐' => Ok(TangutComponents::TangutComponentDash273),
'𘤑' => Ok(TangutComponents::TangutComponentDash274),
'𘤒' => Ok(TangutComponents::TangutComponentDash275),
'𘤓' => Ok(TangutComponents::TangutComponentDash276),
'𘤔' => Ok(TangutComponents::TangutComponentDash277),
'𘤕' => Ok(TangutComponents::TangutComponentDash278),
'𘤖' => Ok(TangutComponents::TangutComponentDash279),
'𘤗' => Ok(TangutComponents::TangutComponentDash280),
'𘤘' => Ok(TangutComponents::TangutComponentDash281),
'𘤙' => Ok(TangutComponents::TangutComponentDash282),
'𘤚' => Ok(TangutComponents::TangutComponentDash283),
'𘤛' => Ok(TangutComponents::TangutComponentDash284),
'𘤜' => Ok(TangutComponents::TangutComponentDash285),
'𘤝' => Ok(TangutComponents::TangutComponentDash286),
'𘤞' => Ok(TangutComponents::TangutComponentDash287),
'𘤟' => Ok(TangutComponents::TangutComponentDash288),
'𘤠' => Ok(TangutComponents::TangutComponentDash289),
'𘤡' => Ok(TangutComponents::TangutComponentDash290),
'𘤢' => Ok(TangutComponents::TangutComponentDash291),
'𘤣' => Ok(TangutComponents::TangutComponentDash292),
'𘤤' => Ok(TangutComponents::TangutComponentDash293),
'𘤥' => Ok(TangutComponents::TangutComponentDash294),
'𘤦' => Ok(TangutComponents::TangutComponentDash295),
'𘤧' => Ok(TangutComponents::TangutComponentDash296),
'𘤨' => Ok(TangutComponents::TangutComponentDash297),
'𘤩' => Ok(TangutComponents::TangutComponentDash298),
'𘤪' => Ok(TangutComponents::TangutComponentDash299),
'𘤫' => Ok(TangutComponents::TangutComponentDash300),
'𘤬' => Ok(TangutComponents::TangutComponentDash301),
'𘤭' => Ok(TangutComponents::TangutComponentDash302),
'𘤮' => Ok(TangutComponents::TangutComponentDash303),
'𘤯' => Ok(TangutComponents::TangutComponentDash304),
'𘤰' => Ok(TangutComponents::TangutComponentDash305),
'𘤱' => Ok(TangutComponents::TangutComponentDash306),
'𘤲' => Ok(TangutComponents::TangutComponentDash307),
'𘤳' => Ok(TangutComponents::TangutComponentDash308),
'𘤴' => Ok(TangutComponents::TangutComponentDash309),
'𘤵' => Ok(TangutComponents::TangutComponentDash310),
'𘤶' => Ok(TangutComponents::TangutComponentDash311),
'𘤷' => Ok(TangutComponents::TangutComponentDash312),
'𘤸' => Ok(TangutComponents::TangutComponentDash313),
'𘤹' => Ok(TangutComponents::TangutComponentDash314),
'𘤺' => Ok(TangutComponents::TangutComponentDash315),
'𘤻' => Ok(TangutComponents::TangutComponentDash316),
'𘤼' => Ok(TangutComponents::TangutComponentDash317),
'𘤽' => Ok(TangutComponents::TangutComponentDash318),
'𘤾' => Ok(TangutComponents::TangutComponentDash319),
'𘤿' => Ok(TangutComponents::TangutComponentDash320),
'𘥀' => Ok(TangutComponents::TangutComponentDash321),
'𘥁' => Ok(TangutComponents::TangutComponentDash322),
'𘥂' => Ok(TangutComponents::TangutComponentDash323),
'𘥃' => Ok(TangutComponents::TangutComponentDash324),
'𘥄' => Ok(TangutComponents::TangutComponentDash325),
'𘥅' => Ok(TangutComponents::TangutComponentDash326),
'𘥆' => Ok(TangutComponents::TangutComponentDash327),
'𘥇' => Ok(TangutComponents::TangutComponentDash328),
'𘥈' => Ok(TangutComponents::TangutComponentDash329),
'𘥉' => Ok(TangutComponents::TangutComponentDash330),
'𘥊' => Ok(TangutComponents::TangutComponentDash331),
'𘥋' => Ok(TangutComponents::TangutComponentDash332),
'𘥌' => Ok(TangutComponents::TangutComponentDash333),
'𘥍' => Ok(TangutComponents::TangutComponentDash334),
'𘥎' => Ok(TangutComponents::TangutComponentDash335),
'𘥏' => Ok(TangutComponents::TangutComponentDash336),
'𘥐' => Ok(TangutComponents::TangutComponentDash337),
'𘥑' => Ok(TangutComponents::TangutComponentDash338),
'𘥒' => Ok(TangutComponents::TangutComponentDash339),
'𘥓' => Ok(TangutComponents::TangutComponentDash340),
'𘥔' => Ok(TangutComponents::TangutComponentDash341),
'𘥕' => Ok(TangutComponents::TangutComponentDash342),
'𘥖' => Ok(TangutComponents::TangutComponentDash343),
'𘥗' => Ok(TangutComponents::TangutComponentDash344),
'𘥘' => Ok(TangutComponents::TangutComponentDash345),
'𘥙' => Ok(TangutComponents::TangutComponentDash346),
'𘥚' => Ok(TangutComponents::TangutComponentDash347),
'𘥛' => Ok(TangutComponents::TangutComponentDash348),
'𘥜' => Ok(TangutComponents::TangutComponentDash349),
'𘥝' => Ok(TangutComponents::TangutComponentDash350),
'𘥞' => Ok(TangutComponents::TangutComponentDash351),
'𘥟' => Ok(TangutComponents::TangutComponentDash352),
'𘥠' => Ok(TangutComponents::TangutComponentDash353),
'𘥡' => Ok(TangutComponents::TangutComponentDash354),
'𘥢' => Ok(TangutComponents::TangutComponentDash355),
'𘥣' => Ok(TangutComponents::TangutComponentDash356),
'𘥤' => Ok(TangutComponents::TangutComponentDash357),
'𘥥' => Ok(TangutComponents::TangutComponentDash358),
'𘥦' => Ok(TangutComponents::TangutComponentDash359),
'𘥧' => Ok(TangutComponents::TangutComponentDash360),
'𘥨' => Ok(TangutComponents::TangutComponentDash361),
'𘥩' => Ok(TangutComponents::TangutComponentDash362),
'𘥪' => Ok(TangutComponents::TangutComponentDash363),
'𘥫' => Ok(TangutComponents::TangutComponentDash364),
'𘥬' => Ok(TangutComponents::TangutComponentDash365),
'𘥭' => Ok(TangutComponents::TangutComponentDash366),
'𘥮' => Ok(TangutComponents::TangutComponentDash367),
'𘥯' => Ok(TangutComponents::TangutComponentDash368),
'𘥰' => Ok(TangutComponents::TangutComponentDash369),
'𘥱' => Ok(TangutComponents::TangutComponentDash370),
'𘥲' => Ok(TangutComponents::TangutComponentDash371),
'𘥳' => Ok(TangutComponents::TangutComponentDash372),
'𘥴' => Ok(TangutComponents::TangutComponentDash373),
'𘥵' => Ok(TangutComponents::TangutComponentDash374),
'𘥶' => Ok(TangutComponents::TangutComponentDash375),
'𘥷' => Ok(TangutComponents::TangutComponentDash376),
'𘥸' => Ok(TangutComponents::TangutComponentDash377),
'𘥹' => Ok(TangutComponents::TangutComponentDash378),
'𘥺' => Ok(TangutComponents::TangutComponentDash379),
'𘥻' => Ok(TangutComponents::TangutComponentDash380),
'𘥼' => Ok(TangutComponents::TangutComponentDash381),
'𘥽' => Ok(TangutComponents::TangutComponentDash382),
'𘥾' => Ok(TangutComponents::TangutComponentDash383),
'𘥿' => Ok(TangutComponents::TangutComponentDash384),
'𘦀' => Ok(TangutComponents::TangutComponentDash385),
'𘦁' => Ok(TangutComponents::TangutComponentDash386),
'𘦂' => Ok(TangutComponents::TangutComponentDash387),
'𘦃' => Ok(TangutComponents::TangutComponentDash388),
'𘦄' => Ok(TangutComponents::TangutComponentDash389),
'𘦅' => Ok(TangutComponents::TangutComponentDash390),
'𘦆' => Ok(TangutComponents::TangutComponentDash391),
'𘦇' => Ok(TangutComponents::TangutComponentDash392),
'𘦈' => Ok(TangutComponents::TangutComponentDash393),
'𘦉' => Ok(TangutComponents::TangutComponentDash394),
'𘦊' => Ok(TangutComponents::TangutComponentDash395),
'𘦋' => Ok(TangutComponents::TangutComponentDash396),
'𘦌' => Ok(TangutComponents::TangutComponentDash397),
'𘦍' => Ok(TangutComponents::TangutComponentDash398),
'𘦎' => Ok(TangutComponents::TangutComponentDash399),
'𘦏' => Ok(TangutComponents::TangutComponentDash400),
'𘦐' => Ok(TangutComponents::TangutComponentDash401),
'𘦑' => Ok(TangutComponents::TangutComponentDash402),
'𘦒' => Ok(TangutComponents::TangutComponentDash403),
'𘦓' => Ok(TangutComponents::TangutComponentDash404),
'𘦔' => Ok(TangutComponents::TangutComponentDash405),
'𘦕' => Ok(TangutComponents::TangutComponentDash406),
'𘦖' => Ok(TangutComponents::TangutComponentDash407),
'𘦗' => Ok(TangutComponents::TangutComponentDash408),
'𘦘' => Ok(TangutComponents::TangutComponentDash409),
'𘦙' => Ok(TangutComponents::TangutComponentDash410),
'𘦚' => Ok(TangutComponents::TangutComponentDash411),
'𘦛' => Ok(TangutComponents::TangutComponentDash412),
'𘦜' => Ok(TangutComponents::TangutComponentDash413),
'𘦝' => Ok(TangutComponents::TangutComponentDash414),
'𘦞' => Ok(TangutComponents::TangutComponentDash415),
'𘦟' => Ok(TangutComponents::TangutComponentDash416),
'𘦠' => Ok(TangutComponents::TangutComponentDash417),
'𘦡' => Ok(TangutComponents::TangutComponentDash418),
'𘦢' => Ok(TangutComponents::TangutComponentDash419),
'𘦣' => Ok(TangutComponents::TangutComponentDash420),
'𘦤' => Ok(TangutComponents::TangutComponentDash421),
'𘦥' => Ok(TangutComponents::TangutComponentDash422),
'𘦦' => Ok(TangutComponents::TangutComponentDash423),
'𘦧' => Ok(TangutComponents::TangutComponentDash424),
'𘦨' => Ok(TangutComponents::TangutComponentDash425),
'𘦩' => Ok(TangutComponents::TangutComponentDash426),
'𘦪' => Ok(TangutComponents::TangutComponentDash427),
'𘦫' => Ok(TangutComponents::TangutComponentDash428),
'𘦬' => Ok(TangutComponents::TangutComponentDash429),
'𘦭' => Ok(TangutComponents::TangutComponentDash430),
'𘦮' => Ok(TangutComponents::TangutComponentDash431),
'𘦯' => Ok(TangutComponents::TangutComponentDash432),
'𘦰' => Ok(TangutComponents::TangutComponentDash433),
'𘦱' => Ok(TangutComponents::TangutComponentDash434),
'𘦲' => Ok(TangutComponents::TangutComponentDash435),
'𘦳' => Ok(TangutComponents::TangutComponentDash436),
'𘦴' => Ok(TangutComponents::TangutComponentDash437),
'𘦵' => Ok(TangutComponents::TangutComponentDash438),
'𘦶' => Ok(TangutComponents::TangutComponentDash439),
'𘦷' => Ok(TangutComponents::TangutComponentDash440),
'𘦸' => Ok(TangutComponents::TangutComponentDash441),
'𘦹' => Ok(TangutComponents::TangutComponentDash442),
'𘦺' => Ok(TangutComponents::TangutComponentDash443),
'𘦻' => Ok(TangutComponents::TangutComponentDash444),
'𘦼' => Ok(TangutComponents::TangutComponentDash445),
'𘦽' => Ok(TangutComponents::TangutComponentDash446),
'𘦾' => Ok(TangutComponents::TangutComponentDash447),
'𘦿' => Ok(TangutComponents::TangutComponentDash448),
'𘧀' => Ok(TangutComponents::TangutComponentDash449),
'𘧁' => Ok(TangutComponents::TangutComponentDash450),
'𘧂' => Ok(TangutComponents::TangutComponentDash451),
'𘧃' => Ok(TangutComponents::TangutComponentDash452),
'𘧄' => Ok(TangutComponents::TangutComponentDash453),
'𘧅' => Ok(TangutComponents::TangutComponentDash454),
'𘧆' => Ok(TangutComponents::TangutComponentDash455),
'𘧇' => Ok(TangutComponents::TangutComponentDash456),
'𘧈' => Ok(TangutComponents::TangutComponentDash457),
'𘧉' => Ok(TangutComponents::TangutComponentDash458),
'𘧊' => Ok(TangutComponents::TangutComponentDash459),
'𘧋' => Ok(TangutComponents::TangutComponentDash460),
'𘧌' => Ok(TangutComponents::TangutComponentDash461),
'𘧍' => Ok(TangutComponents::TangutComponentDash462),
'𘧎' => Ok(TangutComponents::TangutComponentDash463),
'𘧏' => Ok(TangutComponents::TangutComponentDash464),
'𘧐' => Ok(TangutComponents::TangutComponentDash465),
'𘧑' => Ok(TangutComponents::TangutComponentDash466),
'𘧒' => Ok(TangutComponents::TangutComponentDash467),
'𘧓' => Ok(TangutComponents::TangutComponentDash468),
'𘧔' => Ok(TangutComponents::TangutComponentDash469),
'𘧕' => Ok(TangutComponents::TangutComponentDash470),
'𘧖' => Ok(TangutComponents::TangutComponentDash471),
'𘧗' => Ok(TangutComponents::TangutComponentDash472),
'𘧘' => Ok(TangutComponents::TangutComponentDash473),
'𘧙' => Ok(TangutComponents::TangutComponentDash474),
'𘧚' => Ok(TangutComponents::TangutComponentDash475),
'𘧛' => Ok(TangutComponents::TangutComponentDash476),
'𘧜' => Ok(TangutComponents::TangutComponentDash477),
'𘧝' => Ok(TangutComponents::TangutComponentDash478),
'𘧞' => Ok(TangutComponents::TangutComponentDash479),
'𘧟' => Ok(TangutComponents::TangutComponentDash480),
'𘧠' => Ok(TangutComponents::TangutComponentDash481),
'𘧡' => Ok(TangutComponents::TangutComponentDash482),
'𘧢' => Ok(TangutComponents::TangutComponentDash483),
'𘧣' => Ok(TangutComponents::TangutComponentDash484),
'𘧤' => Ok(TangutComponents::TangutComponentDash485),
'𘧥' => Ok(TangutComponents::TangutComponentDash486),
'𘧦' => Ok(TangutComponents::TangutComponentDash487),
'𘧧' => Ok(TangutComponents::TangutComponentDash488),
'𘧨' => Ok(TangutComponents::TangutComponentDash489),
'𘧩' => Ok(TangutComponents::TangutComponentDash490),
'𘧪' => Ok(TangutComponents::TangutComponentDash491),
'𘧫' => Ok(TangutComponents::TangutComponentDash492),
'𘧬' => Ok(TangutComponents::TangutComponentDash493),
'𘧭' => Ok(TangutComponents::TangutComponentDash494),
'𘧮' => Ok(TangutComponents::TangutComponentDash495),
'𘧯' => Ok(TangutComponents::TangutComponentDash496),
'𘧰' => Ok(TangutComponents::TangutComponentDash497),
'𘧱' => Ok(TangutComponents::TangutComponentDash498),
'𘧲' => Ok(TangutComponents::TangutComponentDash499),
'𘧳' => Ok(TangutComponents::TangutComponentDash500),
'𘧴' => Ok(TangutComponents::TangutComponentDash501),
'𘧵' => Ok(TangutComponents::TangutComponentDash502),
'𘧶' => Ok(TangutComponents::TangutComponentDash503),
'𘧷' => Ok(TangutComponents::TangutComponentDash504),
'𘧸' => Ok(TangutComponents::TangutComponentDash505),
'𘧹' => Ok(TangutComponents::TangutComponentDash506),
'𘧺' => Ok(TangutComponents::TangutComponentDash507),
'𘧻' => Ok(TangutComponents::TangutComponentDash508),
'𘧼' => Ok(TangutComponents::TangutComponentDash509),
'𘧽' => Ok(TangutComponents::TangutComponentDash510),
'𘧾' => Ok(TangutComponents::TangutComponentDash511),
'𘧿' => Ok(TangutComponents::TangutComponentDash512),
'𘨀' => Ok(TangutComponents::TangutComponentDash513),
'𘨁' => Ok(TangutComponents::TangutComponentDash514),
'𘨂' => Ok(TangutComponents::TangutComponentDash515),
'𘨃' => Ok(TangutComponents::TangutComponentDash516),
'𘨄' => Ok(TangutComponents::TangutComponentDash517),
'𘨅' => Ok(TangutComponents::TangutComponentDash518),
'𘨆' => Ok(TangutComponents::TangutComponentDash519),
'𘨇' => Ok(TangutComponents::TangutComponentDash520),
'𘨈' => Ok(TangutComponents::TangutComponentDash521),
'𘨉' => Ok(TangutComponents::TangutComponentDash522),
'𘨊' => Ok(TangutComponents::TangutComponentDash523),
'𘨋' => Ok(TangutComponents::TangutComponentDash524),
'𘨌' => Ok(TangutComponents::TangutComponentDash525),
'𘨍' => Ok(TangutComponents::TangutComponentDash526),
'𘨎' => Ok(TangutComponents::TangutComponentDash527),
'𘨏' => Ok(TangutComponents::TangutComponentDash528),
'𘨐' => Ok(TangutComponents::TangutComponentDash529),
'𘨑' => Ok(TangutComponents::TangutComponentDash530),
'𘨒' => Ok(TangutComponents::TangutComponentDash531),
'𘨓' => Ok(TangutComponents::TangutComponentDash532),
'𘨔' => Ok(TangutComponents::TangutComponentDash533),
'𘨕' => Ok(TangutComponents::TangutComponentDash534),
'𘨖' => Ok(TangutComponents::TangutComponentDash535),
'𘨗' => Ok(TangutComponents::TangutComponentDash536),
'𘨘' => Ok(TangutComponents::TangutComponentDash537),
'𘨙' => Ok(TangutComponents::TangutComponentDash538),
'𘨚' => Ok(TangutComponents::TangutComponentDash539),
'𘨛' => Ok(TangutComponents::TangutComponentDash540),
'𘨜' => Ok(TangutComponents::TangutComponentDash541),
'𘨝' => Ok(TangutComponents::TangutComponentDash542),
'𘨞' => Ok(TangutComponents::TangutComponentDash543),
'𘨟' => Ok(TangutComponents::TangutComponentDash544),
'𘨠' => Ok(TangutComponents::TangutComponentDash545),
'𘨡' => Ok(TangutComponents::TangutComponentDash546),
'𘨢' => Ok(TangutComponents::TangutComponentDash547),
'𘨣' => Ok(TangutComponents::TangutComponentDash548),
'𘨤' => Ok(TangutComponents::TangutComponentDash549),
'𘨥' => Ok(TangutComponents::TangutComponentDash550),
'𘨦' => Ok(TangutComponents::TangutComponentDash551),
'𘨧' => Ok(TangutComponents::TangutComponentDash552),
'𘨨' => Ok(TangutComponents::TangutComponentDash553),
'𘨩' => Ok(TangutComponents::TangutComponentDash554),
'𘨪' => Ok(TangutComponents::TangutComponentDash555),
'𘨫' => Ok(TangutComponents::TangutComponentDash556),
'𘨬' => Ok(TangutComponents::TangutComponentDash557),
'𘨭' => Ok(TangutComponents::TangutComponentDash558),
'𘨮' => Ok(TangutComponents::TangutComponentDash559),
'𘨯' => Ok(TangutComponents::TangutComponentDash560),
'𘨰' => Ok(TangutComponents::TangutComponentDash561),
'𘨱' => Ok(TangutComponents::TangutComponentDash562),
'𘨲' => Ok(TangutComponents::TangutComponentDash563),
'𘨳' => Ok(TangutComponents::TangutComponentDash564),
'𘨴' => Ok(TangutComponents::TangutComponentDash565),
'𘨵' => Ok(TangutComponents::TangutComponentDash566),
'𘨶' => Ok(TangutComponents::TangutComponentDash567),
'𘨷' => Ok(TangutComponents::TangutComponentDash568),
'𘨸' => Ok(TangutComponents::TangutComponentDash569),
'𘨹' => Ok(TangutComponents::TangutComponentDash570),
'𘨺' => Ok(TangutComponents::TangutComponentDash571),
'𘨻' => Ok(TangutComponents::TangutComponentDash572),
'𘨼' => Ok(TangutComponents::TangutComponentDash573),
'𘨽' => Ok(TangutComponents::TangutComponentDash574),
'𘨾' => Ok(TangutComponents::TangutComponentDash575),
'𘨿' => Ok(TangutComponents::TangutComponentDash576),
'𘩀' => Ok(TangutComponents::TangutComponentDash577),
'𘩁' => Ok(TangutComponents::TangutComponentDash578),
'𘩂' => Ok(TangutComponents::TangutComponentDash579),
'𘩃' => Ok(TangutComponents::TangutComponentDash580),
'𘩄' => Ok(TangutComponents::TangutComponentDash581),
'𘩅' => Ok(TangutComponents::TangutComponentDash582),
'𘩆' => Ok(TangutComponents::TangutComponentDash583),
'𘩇' => Ok(TangutComponents::TangutComponentDash584),
'𘩈' => Ok(TangutComponents::TangutComponentDash585),
'𘩉' => Ok(TangutComponents::TangutComponentDash586),
'𘩊' => Ok(TangutComponents::TangutComponentDash587),
'𘩋' => Ok(TangutComponents::TangutComponentDash588),
'𘩌' => Ok(TangutComponents::TangutComponentDash589),
'𘩍' => Ok(TangutComponents::TangutComponentDash590),
'𘩎' => Ok(TangutComponents::TangutComponentDash591),
'𘩏' => Ok(TangutComponents::TangutComponentDash592),
'𘩐' => Ok(TangutComponents::TangutComponentDash593),
'𘩑' => Ok(TangutComponents::TangutComponentDash594),
'𘩒' => Ok(TangutComponents::TangutComponentDash595),
'𘩓' => Ok(TangutComponents::TangutComponentDash596),
'𘩔' => Ok(TangutComponents::TangutComponentDash597),
'𘩕' => Ok(TangutComponents::TangutComponentDash598),
'𘩖' => Ok(TangutComponents::TangutComponentDash599),
'𘩗' => Ok(TangutComponents::TangutComponentDash600),
'𘩘' => Ok(TangutComponents::TangutComponentDash601),
'𘩙' => Ok(TangutComponents::TangutComponentDash602),
'𘩚' => Ok(TangutComponents::TangutComponentDash603),
'𘩛' => Ok(TangutComponents::TangutComponentDash604),
'𘩜' => Ok(TangutComponents::TangutComponentDash605),
'𘩝' => Ok(TangutComponents::TangutComponentDash606),
'𘩞' => Ok(TangutComponents::TangutComponentDash607),
'𘩟' => Ok(TangutComponents::TangutComponentDash608),
'𘩠' => Ok(TangutComponents::TangutComponentDash609),
'𘩡' => Ok(TangutComponents::TangutComponentDash610),
'𘩢' => Ok(TangutComponents::TangutComponentDash611),
'𘩣' => Ok(TangutComponents::TangutComponentDash612),
'𘩤' => Ok(TangutComponents::TangutComponentDash613),
'𘩥' => Ok(TangutComponents::TangutComponentDash614),
'𘩦' => Ok(TangutComponents::TangutComponentDash615),
'𘩧' => Ok(TangutComponents::TangutComponentDash616),
'𘩨' => Ok(TangutComponents::TangutComponentDash617),
'𘩩' => Ok(TangutComponents::TangutComponentDash618),
'𘩪' => Ok(TangutComponents::TangutComponentDash619),
'𘩫' => Ok(TangutComponents::TangutComponentDash620),
'𘩬' => Ok(TangutComponents::TangutComponentDash621),
'𘩭' => Ok(TangutComponents::TangutComponentDash622),
'𘩮' => Ok(TangutComponents::TangutComponentDash623),
'𘩯' => Ok(TangutComponents::TangutComponentDash624),
'𘩰' => Ok(TangutComponents::TangutComponentDash625),
'𘩱' => Ok(TangutComponents::TangutComponentDash626),
'𘩲' => Ok(TangutComponents::TangutComponentDash627),
'𘩳' => Ok(TangutComponents::TangutComponentDash628),
'𘩴' => Ok(TangutComponents::TangutComponentDash629),
'𘩵' => Ok(TangutComponents::TangutComponentDash630),
'𘩶' => Ok(TangutComponents::TangutComponentDash631),
'𘩷' => Ok(TangutComponents::TangutComponentDash632),
'𘩸' => Ok(TangutComponents::TangutComponentDash633),
'𘩹' => Ok(TangutComponents::TangutComponentDash634),
'𘩺' => Ok(TangutComponents::TangutComponentDash635),
'𘩻' => Ok(TangutComponents::TangutComponentDash636),
'𘩼' => Ok(TangutComponents::TangutComponentDash637),
'𘩽' => Ok(TangutComponents::TangutComponentDash638),
'𘩾' => Ok(TangutComponents::TangutComponentDash639),
'𘩿' => Ok(TangutComponents::TangutComponentDash640),
'𘪀' => Ok(TangutComponents::TangutComponentDash641),
'𘪁' => Ok(TangutComponents::TangutComponentDash642),
'𘪂' => Ok(TangutComponents::TangutComponentDash643),
'𘪃' => Ok(TangutComponents::TangutComponentDash644),
'𘪄' => Ok(TangutComponents::TangutComponentDash645),
'𘪅' => Ok(TangutComponents::TangutComponentDash646),
'𘪆' => Ok(TangutComponents::TangutComponentDash647),
'𘪇' => Ok(TangutComponents::TangutComponentDash648),
'𘪈' => Ok(TangutComponents::TangutComponentDash649),
'𘪉' => Ok(TangutComponents::TangutComponentDash650),
'𘪊' => Ok(TangutComponents::TangutComponentDash651),
'𘪋' => Ok(TangutComponents::TangutComponentDash652),
'𘪌' => Ok(TangutComponents::TangutComponentDash653),
'𘪍' => Ok(TangutComponents::TangutComponentDash654),
'𘪎' => Ok(TangutComponents::TangutComponentDash655),
'𘪏' => Ok(TangutComponents::TangutComponentDash656),
'𘪐' => Ok(TangutComponents::TangutComponentDash657),
'𘪑' => Ok(TangutComponents::TangutComponentDash658),
'𘪒' => Ok(TangutComponents::TangutComponentDash659),
'𘪓' => Ok(TangutComponents::TangutComponentDash660),
'𘪔' => Ok(TangutComponents::TangutComponentDash661),
'𘪕' => Ok(TangutComponents::TangutComponentDash662),
'𘪖' => Ok(TangutComponents::TangutComponentDash663),
'𘪗' => Ok(TangutComponents::TangutComponentDash664),
'𘪘' => Ok(TangutComponents::TangutComponentDash665),
'𘪙' => Ok(TangutComponents::TangutComponentDash666),
'𘪚' => Ok(TangutComponents::TangutComponentDash667),
'𘪛' => Ok(TangutComponents::TangutComponentDash668),
'𘪜' => Ok(TangutComponents::TangutComponentDash669),
'𘪝' => Ok(TangutComponents::TangutComponentDash670),
'𘪞' => Ok(TangutComponents::TangutComponentDash671),
'𘪟' => Ok(TangutComponents::TangutComponentDash672),
'𘪠' => Ok(TangutComponents::TangutComponentDash673),
'𘪡' => Ok(TangutComponents::TangutComponentDash674),
'𘪢' => Ok(TangutComponents::TangutComponentDash675),
'𘪣' => Ok(TangutComponents::TangutComponentDash676),
'𘪤' => Ok(TangutComponents::TangutComponentDash677),
'𘪥' => Ok(TangutComponents::TangutComponentDash678),
'𘪦' => Ok(TangutComponents::TangutComponentDash679),
'𘪧' => Ok(TangutComponents::TangutComponentDash680),
'𘪨' => Ok(TangutComponents::TangutComponentDash681),
'𘪩' => Ok(TangutComponents::TangutComponentDash682),
'𘪪' => Ok(TangutComponents::TangutComponentDash683),
'𘪫' => Ok(TangutComponents::TangutComponentDash684),
'𘪬' => Ok(TangutComponents::TangutComponentDash685),
'𘪭' => Ok(TangutComponents::TangutComponentDash686),
'𘪮' => Ok(TangutComponents::TangutComponentDash687),
'𘪯' => Ok(TangutComponents::TangutComponentDash688),
'𘪰' => Ok(TangutComponents::TangutComponentDash689),
'𘪱' => Ok(TangutComponents::TangutComponentDash690),
'𘪲' => Ok(TangutComponents::TangutComponentDash691),
'𘪳' => Ok(TangutComponents::TangutComponentDash692),
'𘪴' => Ok(TangutComponents::TangutComponentDash693),
'𘪵' => Ok(TangutComponents::TangutComponentDash694),
'𘪶' => Ok(TangutComponents::TangutComponentDash695),
'𘪷' => Ok(TangutComponents::TangutComponentDash696),
'𘪸' => Ok(TangutComponents::TangutComponentDash697),
'𘪹' => Ok(TangutComponents::TangutComponentDash698),
'𘪺' => Ok(TangutComponents::TangutComponentDash699),
'𘪻' => Ok(TangutComponents::TangutComponentDash700),
'𘪼' => Ok(TangutComponents::TangutComponentDash701),
'𘪽' => Ok(TangutComponents::TangutComponentDash702),
'𘪾' => Ok(TangutComponents::TangutComponentDash703),
'𘪿' => Ok(TangutComponents::TangutComponentDash704),
'𘫀' => Ok(TangutComponents::TangutComponentDash705),
'𘫁' => Ok(TangutComponents::TangutComponentDash706),
'𘫂' => Ok(TangutComponents::TangutComponentDash707),
'𘫃' => Ok(TangutComponents::TangutComponentDash708),
'𘫄' => Ok(TangutComponents::TangutComponentDash709),
'𘫅' => Ok(TangutComponents::TangutComponentDash710),
'𘫆' => Ok(TangutComponents::TangutComponentDash711),
'𘫇' => Ok(TangutComponents::TangutComponentDash712),
'𘫈' => Ok(TangutComponents::TangutComponentDash713),
'𘫉' => Ok(TangutComponents::TangutComponentDash714),
'𘫊' => Ok(TangutComponents::TangutComponentDash715),
'𘫋' => Ok(TangutComponents::TangutComponentDash716),
'𘫌' => Ok(TangutComponents::TangutComponentDash717),
'𘫍' => Ok(TangutComponents::TangutComponentDash718),
'𘫎' => Ok(TangutComponents::TangutComponentDash719),
'𘫏' => Ok(TangutComponents::TangutComponentDash720),
'𘫐' => Ok(TangutComponents::TangutComponentDash721),
'𘫑' => Ok(TangutComponents::TangutComponentDash722),
'𘫒' => Ok(TangutComponents::TangutComponentDash723),
'𘫓' => Ok(TangutComponents::TangutComponentDash724),
'𘫔' => Ok(TangutComponents::TangutComponentDash725),
'𘫕' => Ok(TangutComponents::TangutComponentDash726),
'𘫖' => Ok(TangutComponents::TangutComponentDash727),
'𘫗' => Ok(TangutComponents::TangutComponentDash728),
'𘫘' => Ok(TangutComponents::TangutComponentDash729),
'𘫙' => Ok(TangutComponents::TangutComponentDash730),
'𘫚' => Ok(TangutComponents::TangutComponentDash731),
'𘫛' => Ok(TangutComponents::TangutComponentDash732),
'𘫜' => Ok(TangutComponents::TangutComponentDash733),
'𘫝' => Ok(TangutComponents::TangutComponentDash734),
'𘫞' => Ok(TangutComponents::TangutComponentDash735),
'𘫟' => Ok(TangutComponents::TangutComponentDash736),
'𘫠' => Ok(TangutComponents::TangutComponentDash737),
'𘫡' => Ok(TangutComponents::TangutComponentDash738),
'𘫢' => Ok(TangutComponents::TangutComponentDash739),
'𘫣' => Ok(TangutComponents::TangutComponentDash740),
'𘫤' => Ok(TangutComponents::TangutComponentDash741),
'𘫥' => Ok(TangutComponents::TangutComponentDash742),
'𘫦' => Ok(TangutComponents::TangutComponentDash743),
'𘫧' => Ok(TangutComponents::TangutComponentDash744),
'𘫨' => Ok(TangutComponents::TangutComponentDash745),
'𘫩' => Ok(TangutComponents::TangutComponentDash746),
'𘫪' => Ok(TangutComponents::TangutComponentDash747),
'𘫫' => Ok(TangutComponents::TangutComponentDash748),
'𘫬' => Ok(TangutComponents::TangutComponentDash749),
'𘫭' => Ok(TangutComponents::TangutComponentDash750),
'𘫮' => Ok(TangutComponents::TangutComponentDash751),
'𘫯' => Ok(TangutComponents::TangutComponentDash752),
'𘫰' => Ok(TangutComponents::TangutComponentDash753),
'𘫱' => Ok(TangutComponents::TangutComponentDash754),
'𘫲' => Ok(TangutComponents::TangutComponentDash755),
_ => Err(()),
}
}
}
impl Into<u32> for TangutComponents {
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 TangutComponents {
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 TangutComponents {
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 TangutComponents {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
TangutComponents::TangutComponentDash001
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("TangutComponents{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
use std::mem;
use wasmer_runtime_core::{
types::{Type, WasmExternType},
vm::Ctx,
};
#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct VarArgs {
pub pointer: u32, // assuming 32bit wasm
}
impl VarArgs {
pub fn get<T: Sized>(&mut self, ctx: &mut Ctx) -> T {
let ptr = emscripten_memory_pointer!(ctx.memory(0), self.pointer);
self.pointer += mem::size_of::<T>() as u32;
unsafe { (ptr as *const T).read() }
}
}
unsafe impl WasmExternType for VarArgs {
const TYPE: Type = Type::I32;
fn to_bits(self) -> u64 {
self.pointer as u64
}
fn from_bits(n: u64) -> Self {
Self { pointer: n as u32 }
}
}
|
// My first rustlang project
// Rustlang primitive types
// boolean -- bool -- true, false
// numbers -- ix, -- x = 8, 16, 32, 64 (integers) [ux for unsigned]
// floating numbers -- fx -- x = 32, 64
// arrays -- [T;nbr] -- nbr is a compile time constant
// slices -- &[T] -- &a[..] --> a slice containing all the elements of the array
// &a[1..5] --> from index 1 to index 4, 5 is exclusive
// slices need to work on borrowed references of the arrays
// tuples : (x, y, z)
// functions : fn name(params) -> return type {}
// fn foo(x: i32) -> i32 { x }
// let x: fn(i32) -> i32 = foo;
// x is a ‘function pointer’ to a function that takes an i32 and returns an i32
// Testing out enums and structs and tuples
fn main() {
// a normal struct
// added the debug trait for allowing println!
#[derive(Debug)]
struct AnyStruct {
elem1: i32,
elem2: String,
elem3: Vec<String>,
};
// a struct containing mutable references to some values
// needs a mandatory lifetime declaration, so that the
// structure doesn't outlive it's borrowed elements
struct MutStruct<'a> {
mut_ref1: &'a mut Vec<i32>,
ref2: &'a i32,
};
// a tuple struct that has anonymous field names
// adding the #[derive(Debug)] trait just for printing
#[derive(Debug)]
struct TupleStruct(i32, String, i32, String);
// empty struct
// struct EmptyDefStruct {};
// emptry struct
// struct EmptyStruct;
// enum
#[derive(Debug)]
enum MyFirstEnum {
// just one case without any parameters
Option1,
// case looking like a tuplestruct
Option2(i32, String, u64),
// a case representing something like a struct def
// formatted by rustfmt
Option3 { x: i32, y: i64, z: String, k: f32 },
// looks like a function
Option4(String),
};
// field accesses for structs, tuples and enums
// tuple
let tuple1: (i32, i32) = (5, 6);
// tuples have 0 based indexes and are accessed like
// members rather than subscripts
let tuple_index1: i32 = tuple1.0;
let tuple_index2: i32 = tuple1.1;
println!("tuple: 0: {index0}, 1: {index1}",
index1 = tuple_index2,
index0 = tuple_index1);
// field accesses for structs
// Note: The binding of the structs can be mut, not the individual
// fields of the struct
// Note: `String` != `str`
// String is a struct built using the `str` - builtin string type
// so "String" is of `str` type, while "String".to_string() is of `String` type
let struct_instance: AnyStruct = AnyStruct {
elem1: 1,
elem2: "String type".to_string(),
elem3: vec!["String vec1".to_string()],
};
println!("AnyStruct = {:?}", struct_instance);
// declaring a mutable vector for passing the reference to mut_struct_instance
let mut vec_instance: Vec<i32> = vec![5, 6, 7];
let ref2: i32 = 5;
let mut_struct_instance: MutStruct = MutStruct {
mut_ref1: &mut vec_instance,
ref2: &ref2,
};
println!("mut_struct_instance : mut_ref1 = {:?}, ref2 = {}",
mut_struct_instance.mut_ref1,
mut_struct_instance.ref2);
// tuple struct instance
// initialization is different from a normal struct
// they are initialized like calling a function
let tuple_struct_inst: TupleStruct = TupleStruct(1, "2".to_string(), 4, "5".to_string());
// needed to add #[derive(Debug)] on the TupleStruct definition for gettign
// print formatting ability
// else would have to define the method for it
println!("TupleStruct : {:?}", tuple_struct_inst);
// Enum access
// enum access using `::` operator or a match statement
let enum_option1: MyFirstEnum = MyFirstEnum::Option1;
let enum_option2: MyFirstEnum = MyFirstEnum::Option2(1, "1".to_string(), 2);
let enum_option3: MyFirstEnum = MyFirstEnum::Option3 {
x: 1,
y: 34,
z: "Abc".to_string(),
k: 2.34,
};
let enum_option4: MyFirstEnum = MyFirstEnum::Option4("String type".to_string());
// A match is basically like a switch-case but more powerful, since it matches
// patterns
let enum_option: MyFirstEnum = match enum_option3 {
MyFirstEnum::Option1 => {
println!("Option1");
enum_option1
}
MyFirstEnum::Option2(_, _, _) => {
println!("Option2");
enum_option2
}
// used a variable struct content
// A struct can include .. to indicate that you want to use
// a copy of some other struct for some of the values.
MyFirstEnum::Option3 { .. } => {
println!("Option3");
enum_option3
}
MyFirstEnum::Option4(_) => {
println!("Option4");
enum_option4
}
};
println!("value of enum_option = {:?}", enum_option);
// The below line is now invalid since the ownership of enum_option3 has transferred
// to the match body and the match body has ended
// VERY POWERFUL CONCEPT
// println!("enum_option3 = {:?}", enum_option3);
// "stting".to_string() is the same as String::from("strign")
let string_from: String = String::from("Hellp String");
println!("String = {:?}", string_from);
// str is an unsized type, so when we declare a string literal
// it has a type of &'static str
// it is a borrowed slice with static lifetime (lifetime of the entire program)
// so it doesn't get destroyed even after it goes out of scope
// although it is not accessible though
// str is basically a string slice
{
let test_string: &'static str = "String";
println!("test_string={}", test_string);
}
// need turbofish `::<T>` operator for this type of
// bindings
let vector = Vec::<bool>::new();
// else go with
let vector: Vec<bool> = Vec::new();
}
// The Guessing game!
// the way to include external libraries as dependencies
// here rand is the external library
// extern crate rand;
// use is the analogy for import, to add to the namespace
// std is the main module, io is a submodule, and stdin is a method defined inside io and so on.
// The prelude is the list of things that Rust automatically imports into every Rust program.
// prelude is kept at min
//use std::io;
//use std::cmp::Ordering;
//use rand::Rng;
//**
//A structure called Point
//it has the following members x and y each of i32 type
//*/
//struct Point {
// x: i32,
// y: i32,
//}
//
//
//
//fn main() {
//
// //! The main()
//
// // the entire structure is to be mutable, not the individual members
// let mut b = Point { x: 5, y: 6 };
//
// // when passing to println macro, the objects are passed as lifetime by
// // default, it is the same as passing then as function<'a, 'b>(...)
// // format.
// println!("Point: x{}, y{}", b.x, b.y);
//
// // b still in main scope, hence is still owned by main scope
// // and since b is a mutable instance, we can modify the value
// b.x = 4;
// b.y = 8;
//
// // this will print Point: x4, y8
// println!("Point: x{}, y{}", b.x, b.y);
//
// // passing a mutable reference to the function mod_point
// // this way, I'm not handing over the ownership of the point b
// mod_point(&mut b);
//
// println!("Point: x{}, y{}", b.x, b.y);
//
// let k: i32;
// let kk: &i32;
// {
// k = 5;
// kk = pikapika(&k);
//
// println!("inside kk={}", kk);
// }
//
// println!("outside : k={} and kk={}", k, kk);
//}
/*
// Every reference(borrowed) in rustlang has a lifetime associated with it.
// In the function pikapika I declare a lifetime named `'a` since that is the syntax,
// now, each function has a input lifetime and output lifetime.
// Input lifetime:
// k: &'a i32
// Output lifetime:
// &'a i32
An input lifetime is a lifetime associated with a parameter of a function,
and an output lifetime is a lifetime associated with the return value of a function.
Lifetimes are only used for borrowed values/references, not for ownership transfers.
Lifetime 3 rules for elision/ automatic lifetime inference by rustlang compiler
Here are the three rules:
* Each elided lifetime in a function’s arguments becomes a distinct lifetime parameter.
* If there is exactly one input lifetime, elided or not, that lifetime is assigned to all
elided lifetimes in the return values of that function.
* If there are multiple input lifetimes, but one of them is &self or &mut self,
the lifetime of self is assigned to all elided output lifetimes.
Otherwise, it is an error to elide an output lifetime.
*/
//fn pikapika<'a>(k: &'a i32) -> &'a i32 {
//
// /// This function <'a> means that, the return value will have the same lifetime as the input value
// /// lifetime being the same scope (lifetime is just the alternate name for named scopes)
// return k;
//}
// mod_point<'b>(b: &'b mut Point) -> () {...}
// This function takes a mutable lifetime reference of point.
// This way, b maintains lifetime even after the program's control returns from the function mod_point
//fn mod_point<'b>(b: &'b mut Point) {
//
// b.x = 90;
// b.y = 90;
//
// println!("Point: x{}, y{}", &b.x, &b.y);
//}
//fn main() {
//
// let mut x: String = String::new();
//
// std::io::stdin().read_line(&mut x).expect("Hey there this is wrong");
//
// println!("String readIn = {}", x);
//
//}
//fn main() {
//
// // generate a random number between 0 -100 (0 <= secret < 100)
// let secret: u32 = rand::thread_rng().gen_range(0, 100);
//
// println!("Hey there, enter your name:");
//
// // By default, all the instances in Rust are immutable
// // need to explicitly say `mut` to make the value mutable
// // need to make the String mutable in order to update it with the value
// // from the stdin.
// let mut name = String::new();
//
// io::stdin()
// .read_line(&mut name)
// .expect("PLease enter a valid name lol!");
//
// if name.contains("Si") {
//
// println!("So your name is {}?", &name);
// } else {
//
// println!("Nice name you got there!");
// }
//
// println!("{}, enter a number [0, 100):", name);
//
// loop {
//
// let mut number: String = String::new();
//
// io::stdin()
// .read_line(&mut number)
// .expect("Please enter a valid whole number");
//
// let number: u32 = match number.trim().parse() {
//
// Ok(number) => number,
// Err(_) => continue,
// };
//
// match number.cmp(&secret) {
// Ordering::Equal => {
// println!("Well done, {}. You won!", &name);
// break;
// }
// Ordering::Less => println!("Guess higher, {}", &name),
// Ordering::Greater => println!("Guess lower, {}", &name),
// };
// }
//
//}
|
use airhobot::prelude::*;
use cv::gui::*;
use env_logger::{Builder, Env};
use log::*;
use std::{
env, error,
net::UdpSocket,
sync::{Arc, Mutex},
time::Duration,
};
fn main() -> std::result::Result<(), Box<dyn error::Error>> {
Builder::from_env(Env::default().default_filter_or("info")).init();
let win_name = "AirHoBot - test";
let gui = cv::GUI::new(win_name);
let mut offset = (50, 50, 50);
let pusher_range = cv::HSVRange::new(0..=50, 200..=255, 80..=180)?;
// let socket = UdpSocket::bind("192.168.1.220:6789")?;
let mut start_p = None;
let mut end_p = None;
let mut send_done = false;
let mouse_events = gui.mouse_events();
// let mut cam = Source::cam(2)?;
let mut cam = Source::image(asset_path("airhockey.png"))?;
// board bounds
let mut points = Vec::new();
let mut frame = cam.next().unwrap();
while points.len() < 4 {
match mouse_events.try_recv() {
Ok(MouseEvent::LeftBtnDown(p)) => {
points.push(p.clone());
println!("point: {:?}", p);
frame.draw_circle(&p, 5, cv::RGB::red(), 5);
}
_ => (),
};
gui.show_for(&frame, Duration::from_millis(10));
}
let field = Field::new(points.clone());
loop {
let mut frame = cam.next().unwrap();
frame.blur(5);
let mut hsv_frame = frame.to_hsv()?;
// draw board bounds
field.draw(&mut frame);
// puck abfragen
match mouse_events.try_recv() {
Ok(MouseEvent::LeftBtnDown(p)) => {
println!("point set");
frame.draw_circle(&p, 5, cv::RGB::green(), 5);
if start_p.is_none() {
start_p = Some(p);
} else if end_p.is_none() {
end_p = Some(p);
} else {
start_p = None;
end_p = None;
}
}
_ => (),
};
// gui.show_for(&frame, Duration::from_millis(10));
if let Some(pusher) = find(&hsv_frame, &pusher_range, 600.0, 3000.0)?.iter().next() {
let pusher_c = pusher.center();
frame.draw_rect(&pusher.bounding_rect(), cv::RGB::new(255, 165, 0), 2);
if let Some(start_p) = start_p {
frame.draw_circle(&start_p, 5, cv::RGB::red(), 2);
if let Some(end_p) = end_p {
frame.draw_circle(&end_p, 5, cv::RGB::red(), 5);
frame.draw_line(&start_p, &end_p, cv::RGB::red(), 2);
let m = -(points[2].y() - points[3].y()) as f32 / (points[2].x() - points[3].x()) as f32;
let b = points[2].y() as f32 - points[3].x() as f32 * m;
let y = dbg!((m * ((points[2].x() + points[3].x()) / 2) as f32 + b) as i32 - 15);
let x = if end_p.x() != start_p.x() {
let m = (end_p.y() - start_p.y()) as f32 / (end_p.x() - start_p.x()) as f32;
((y - end_p.y()) as f32 / m + end_p.x() as f32) as i32
} else {
end_p.x()
};
frame.draw_line(&end_p, &cv::Point::new(x, y), cv::RGB::green(), 2);
let (einschlag, bounce) = predict(&start_p, &end_p, y, &field);
frame.draw_circle(&einschlag, 8, cv::RGB::green(), 5);
if let Some(b) = bounce {
frame.draw_circle(&b, 8, cv::RGB::red(), 5);
}
// if false { // !send_done {
// let m1 = (x + y) as f32 * 2.22;
// let m2 = (x - y) as f32 * 2.22;
// let tx = (m1 - ((pusher_c.x() + pusher_c.y()) as f32 * 2.22)) as i32;
// let ty = (m2 - ((pusher_c.x() - pusher_c.y()) as f32 * 2.22)) as i32;
// let payload = format!("{}:{}", tx, ty);
// socket
// .send_to(payload.as_bytes(), "192.168.1.100:6789")
// .expect("couldn't send data");
// send_done = true;
// }
// } else {
// send_done = false;
// }
}
}
gui.show_for(&frame, Duration::from_millis(10));
}
}
}
struct Field {
lt: cv::Point,
rt: cv::Point,
lb: cv::Point,
rb: cv::Point,
}
impl Field {
pub fn new(vec: Vec<cv::Point>) -> Self {
Field {
lt: vec[0],
rt: vec[1],
rb: vec[2],
lb: vec[3],
}
}
pub fn draw<T>(&self, frame: &mut cv::Mat<T>) -> std::result::Result<(), Box<dyn error::Error>> {
frame.draw_line(&self.lt, &self.rt, cv::RGB::red(), 2);
frame.draw_line(&self.rt, &self.rb, cv::RGB::red(), 2);
frame.draw_line(&self.rb, &self.lb, cv::RGB::red(), 2);
frame.draw_line(&self.lb, &self.lt, cv::RGB::red(), 2);
Ok(())
}
pub fn puck_bounces_side(&self, puck_pos: &cv::Point) -> Option<(cv::Point, cv::Point)> {
if puck_pos.x() < self.lt.x() {
Some((self.lt, self.lb))
} else if puck_pos.x() > self.rb.x() {
Some((self.rt, self.rb))
} else {
None
}
}
}
fn predict(s: &cv::Point, e: &cv::Point, y: i32, field: &Field) -> (cv::Point, Option<cv::Point>) {
if e.x() == s.x() {
return (cv::Point::new(e.x(), y), None);
}
let m = (e.y() - s.y()) as f32 / (e.x() - s.x()) as f32;
let x = ((y - e.y()) as f32 / m + e.x() as f32) as i32;
let point = cv::Point::new(x, y);
if let Some((l_start, l_end)) = field.puck_bounces_side(&point) {
let m1 = (e.y() - s.y()) as f32 / (e.x() - s.x()) as f32;
let m2 = (l_end.y() - l_start.y()) as f32 / (l_end.x() - l_start.x()) as f32;
let b1 = s.y() as f32 - s.x() as f32 * m1;
let b2 = l_start.y() as f32 - l_start.x() as f32 * m2;
let x = (b2 - b1) / (m1 - m2);
let y_ = (m1 * x + b1) as i32;
let bp = cv::Point::new(x as i32, y_ as i32);
let point = cv::Point::new(((y - bp.y()) as f32 / (-m) + bp.x() as f32) as i32, y);
(point, Some(bp))
} else {
(point, None)
}
}
pub fn find(frame: &cv::Mat<cv::HSV>, hsv_range: &cv::HSVRange, area_min: f64, area_max: f64) -> Result<cv::Contours> {
let mut masked = frame.in_range(hsv_range);
let contours = masked.find_contours();
Ok(contours
.iter()
.filter(|c| {
let area = c.area();
area > area_min && area < area_max
})
.collect())
}
|
use crate::hittable::{HitRecord, Hittable};
use crate::material::Material;
use crate::ray::Ray;
use crate::vec3::Point3;
use crate::Num;
use std::ops::Range;
#[derive(Clone, Copy)]
pub struct Sphere {
center: Point3,
radius: Num,
mat: Material,
}
impl Sphere {
pub(crate) fn new(center: Point3, radius: Num, mat: Material) -> Self {
Self {
center,
radius,
mat,
}
}
}
impl Hittable for Sphere {
fn hit(&self, ray: Ray, range: Range<Num>) -> Option<HitRecord> {
let oc = ray.origin - self.center;
let a = ray.direction.length_squared();
let half_b = oc.dot(ray.direction);
let c = oc.length_squared() - self.radius * self.radius;
let discriminant = half_b * half_b - a * c;
if discriminant < 0. {
return None;
}
let sqrt_disc = discriminant.sqrt();
let mut root = (-half_b - sqrt_disc) / a;
if !range.contains(&root) {
root = (-half_b + sqrt_disc) / a;
if !range.contains(&root) {
return None;
}
}
let p = ray.at(root);
let outward_normal = (p - self.center) / self.radius;
Some(HitRecord::new(ray, outward_normal, p, root, self.mat))
}
}
|
use crate::renderer::Ray;
use glam::{Vec3, Vec3A};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Sphere {
pub position: Vec3,
pub radius: f32,
pub diffuse: Vec3,
pub specular: Vec3,
pub ambient: Vec3,
pub mirror: bool,
}
#[derive(Debug, Deserialize)]
pub struct Quad {
pub positions: [Vec3; 3],
pub diffuse: Vec3,
pub specular: Vec3,
pub ambient: Vec3,
pub is_diffuse: bool,
}
pub trait Renderable {
fn get_diffuse(&self) -> Vec3;
fn get_ambient(&self) -> Vec3;
fn get_specular(&self) -> Vec3;
fn get_mirrored(&self) -> bool;
fn intersect(&self, ray: &Ray) -> Option<(f32, Vec3A)>;
}
impl Renderable for Sphere {
fn get_diffuse(&self) -> Vec3 {
self.diffuse
}
fn get_ambient(&self) -> Vec3 {
self.ambient
}
fn get_specular(&self) -> Vec3 {
self.specular
}
fn get_mirrored(&self) -> bool {
true
}
// Returns t and surface normal
fn intersect(&self, ray: &Ray) -> Option<(f32, Vec3A)> {
debug_assert!(ray.dir.is_normalized());
let p: Vec3A = self.position.into();
let m: Vec3A = ray.origin - p;
let b = m.dot(ray.dir);
let c = m.dot(m) - self.radius * self.radius;
if c > 0.0 && b > 0.0 {
return None;
}
let discr = b * b - c;
if discr < 0.0 {
return None;
}
let t = -b - discr.sqrt();
let t = t.max(0.0);
let hitpoint = ray.origin + t * ray.dir;
let normal = (hitpoint - p).normalize();
Some((t, normal))
}
}
impl Renderable for Quad {
fn get_diffuse(&self) -> Vec3 {
self.diffuse
}
fn get_ambient(&self) -> Vec3 {
self.ambient
}
fn get_specular(&self) -> Vec3 {
self.specular
}
fn get_mirrored(&self) -> bool {
false
}
fn intersect(&self, ray: &Ray) -> Option<(f32, Vec3A)> {
debug_assert!(ray.dir.is_normalized());
let a: Vec3A = self.positions[0].into();
let b: Vec3A = self.positions[1].into();
let c: Vec3A = self.positions[2].into();
let p = b - a;
let q = c - a;
let tmp1 = ray.dir.cross(q);
let dot1 = tmp1.dot(p);
if dot1.abs() < 0.00001 {
return None;
}
let f = 1.0 / dot1;
let s = ray.origin - a;
let u = f * s.dot(tmp1);
if u < 0.0 || u > 1.0 {
return None; // outside
}
let tmp2 = s.cross(p);
let v = f * ray.dir.dot(tmp2);
if v < 0.0 || v > 1.0 {
return None; // outsize
}
let t = f * q.dot(tmp2);
let normal = p.cross(q).normalize();
return Some((t, normal));
}
}
|
use std::fs;
type InfiniteImg = (Vec<Vec<char>>, bool);
fn main() {
let filename = "input/input.txt";
let (enhancement_algorithm, img) = parse_input_file(filename);
let enhancement_algo_slice = enhancement_algorithm.as_slice();
// println!("enhancement_algorithm: {:?}", enhancement_algorithm);
// println!("img: {:?}", img);
// println!();
let mut inf_img: InfiniteImg = (img, false);
let num_enhance_times = 50;
for _ in 0..num_enhance_times {
inf_img = enhance(inf_img, enhancement_algo_slice);
}
// println!("inf_img: {:?}", inf_img);
pretty(&inf_img.0);
let num_lit_pixels: usize = inf_img
.0
.iter()
.map(|row| {
row.iter()
.map(|c| if *c == '#' { 1 } else { 0 })
.sum::<usize>()
})
.sum();
println!("num_lit_pixels: {}", num_lit_pixels);
}
fn pretty(img: &Vec<Vec<char>>) {
for row in img {
println!("{}", row.iter().collect::<String>());
}
println!();
}
fn enhance(
(img, out_of_bounds_is_set): InfiniteImg,
enhancement_algorithm: &[char],
) -> InfiniteImg {
let img_size = img.len();
let iimg_size: isize = img_size.try_into().unwrap();
let output_img_size = img_size + 2;
let ioutput_img_size = output_img_size.try_into().unwrap();
let is_in_bounds = |(x, y): (isize, isize)| x >= 0 && x < iimg_size && y >= 0 && y < iimg_size;
let to_input_img_idx = |(x, y): (isize, isize)| (x - 1, y - 1);
let output_img: Vec<Vec<char>> = (0..ioutput_img_size)
.map(|x: isize| {
(0..ioutput_img_size)
.map(|y: isize| {
let pixels_around = [
(x - 1, y - 1),
(x - 1, y),
(x - 1, y + 1),
(x, y - 1),
(x, y),
(x, y + 1),
(x + 1, y - 1),
(x + 1, y),
(x + 1, y + 1),
];
let serialized_pixels: String = pixels_around
.into_iter()
.map(to_input_img_idx)
.map(|input_img_idx| {
if !is_in_bounds(input_img_idx) {
match out_of_bounds_is_set {
true => '#',
false => '.',
}
} else {
let (ix, iy) = input_img_idx;
let ux: usize = ix.try_into().unwrap();
let uy: usize = iy.try_into().unwrap();
img[ux][uy]
}
})
.collect();
// println!("serialized_pixels: {:?}", serialized_pixels);
enhancement_algorithm[enhancement_algorithm_idx(&serialized_pixels)]
})
.collect()
})
.collect();
(
output_img,
(enhancement_algorithm[0] == '#') ^ out_of_bounds_is_set,
)
}
fn parse_input_file(filename: &str) -> (Vec<char>, Vec<Vec<char>>) {
let file_contents = fs::read_to_string(filename).unwrap();
let parts: Vec<String> = file_contents.split("\n\n").map(|s| s.to_string()).collect();
let enhancement_code = parts[0].chars().collect();
let img: Vec<Vec<char>> = parse_img_str(&parts[1]);
(enhancement_code, img)
}
fn parse_img_str(img_str: &str) -> Vec<Vec<char>> {
img_str.split('\n').map(|l| l.chars().collect()).collect()
}
fn enhancement_algorithm_idx(pixels: &str) -> usize {
let binary_string: String = pixels
.chars()
.map(|c| if c == '#' { '1' } else { '0' })
.collect();
usize::from_str_radix(binary_string.as_str(), 2).unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_image_enhancement_algorithm_idx() {
let idx = enhancement_algorithm_idx("...#...#.");
assert_eq!(idx, 34);
}
#[test]
fn test_enhance() {
let enhancement = "..#.#..#####.#.#.#.###.##.....###.##.#..###.####..#####..#....#..#..##..###..######.###...####..#..#####..##..#.#####...##.#.#..#.##..#.#......#.###.######.###.####...#.##.##..#..#..#####.....#.#....###..#.##......#.....#..#..#..##..#...##.######.####.####.#.#...#.......#..#.#.#...####.##.#......#..#...##.#.##..#...##.#.##..###.#......#.#.......#.#.#.####.###.##...#.....####.#..#..#.##.#....##..#.####....##...##..#...#......#.#.......#.......##..####..#...#.#.#...##..#.#..###..#####........#..####......#..#";
let input_str = "#..#.
#....
##..#
..#..
..###";
let expected_output_str = ".##.##.
#..#.#.
##.#..#
####..#
.#..##.
..##..#
...#.#.";
let input_img: InfiniteImg = (parse_img_str(input_str), false);
let expected_output_img: InfiniteImg = (parse_img_str(expected_output_str), false);
let actual_output_img = enhance(
input_img,
enhancement.chars().collect::<Vec<char>>().as_slice(),
);
assert_eq!(actual_output_img, expected_output_img);
}
}
|
//! provides access to general purpose registers (GPRs)
/// refers to a GPR
pub trait GeneralPurposeRegister {
const ID: u32;
}
macro_rules! define_gpr {
($name: ident, $id: expr, $doc_name: expr, $doc_id: expr) => {
#[allow(non_camel_case_types)]
#[doc = "register"]
#[doc = $doc_id]
#[doc = "("]
#[doc = $doc_name]
#[doc = ")"]
pub struct $name {}
impl GeneralPurposeRegister for $name {
const ID: u32 = $id;
}
};
// call itself recursively to generate correct documentation
($name: ident, $id: expr) => {
define_gpr!($name, $id, stringify!($name), stringify!($id));
};
}
define_gpr!(zero, 0);
define_gpr!(at, 1);
define_gpr!(v0, 2);
define_gpr!(v1, 3);
define_gpr!(a0, 4);
define_gpr!(a1, 5);
define_gpr!(a2, 6);
define_gpr!(a3, 7);
define_gpr!(t0, 8);
define_gpr!(t1, 9);
define_gpr!(t2, 10);
define_gpr!(t3, 11);
define_gpr!(t4, 12);
define_gpr!(t5, 13);
define_gpr!(t6, 14);
define_gpr!(t7, 15);
define_gpr!(s0, 16);
define_gpr!(s1, 17);
define_gpr!(s2, 18);
define_gpr!(s3, 19);
define_gpr!(s4, 20);
define_gpr!(s5, 21);
define_gpr!(s6, 22);
define_gpr!(s7, 23);
define_gpr!(t8, 24);
define_gpr!(t9, 25);
define_gpr!(k0, 26);
define_gpr!(k1, 27);
define_gpr!(gp, 28);
define_gpr!(sp, 29);
// s8 == fp
define_gpr!(s8, 30);
define_gpr!(fp, 30);
define_gpr!(ra, 31);
/// read from a GPR
/// ```rust
/// let value = read::<a0>();
/// ```
#[inline]
pub fn read<R>() -> u32
where
R: GeneralPurposeRegister,
{
let value: u32;
unsafe {
llvm_asm!("ori $0, $$$1, 0"
: "=r"(value)
: "i"(R::ID)
:: "volatile"
);
}
value
}
/// write to a GPR
/// ```rust
/// write::<s0>(42);
/// ```
#[inline]
pub fn write<R>(value: u32)
where
R: GeneralPurposeRegister,
{
unsafe {
llvm_asm!("ori $$$1, $0, 0"
:: "r"(value), "i"(R::ID)
:: "volatile"
);
}
}
|
#[macro_use]
extern crate trackable;
use clap::Parser;
use fibers_transport::UdpTransporter;
use futures::Future;
use rustun::channel::Channel;
use rustun::client::Client;
use rustun::message::Request;
use rustun::transport::StunUdpTransporter;
use rustun::Error;
use std::net::ToSocketAddrs;
use stun_codec::rfc5389;
use stun_codec::{MessageDecoder, MessageEncoder};
use trackable::error::Failed;
use trackable::error::MainError;
#[derive(Debug, Parser)]
struct Args {
host: String,
#[clap(short, long, default_value_t = 3478)]
port: usize,
}
fn main() -> Result<(), MainError> {
let args = Args::parse();
let peer_addr = track_assert_some!(
track_any_err!(format!("{}:{}", args.host, args.port).to_socket_addrs())?
.filter(|x| x.is_ipv4())
.nth(0),
Failed
);
let local_addr = "0.0.0.0:0".parse().unwrap();
let response = UdpTransporter::<MessageEncoder<_>, MessageDecoder<_>>::bind(local_addr)
.map_err(Error::from)
.map(StunUdpTransporter::new)
.map(Channel::new)
.and_then(move |channel| {
let client = Client::new(&fibers_global::handle(), channel);
let request = Request::<rfc5389::Attribute>::new(rfc5389::methods::BINDING);
client.call(peer_addr, request)
});
let response = track!(fibers_global::execute(response))?;
println!("{:?}", response);
Ok(())
}
|
mod block_relayer;
pub use block_relayer::BlockRelayer;
|
//! Tests auto-converted from "sass-spec/spec/libsass-closed-issues/issue_659"
#[allow(unused)]
use super::rsass;
// From "sass-spec/spec/libsass-closed-issues/issue_659/issue_659.hrx"
#[test]
fn issue_659() {
assert_eq!(
rsass(
"// libsass issue 659: never output empty blocks\
\n// https://github.com/sass/libsass/issues/659\
\n\
\n@function null() {\
\n @return null;\
\n}\
\n\
\n$foo: null;\
\n\
\n.test {\
\n out: null();\
\n out: $foo;\
\n}"
)
.unwrap(),
""
);
}
// From "sass-spec/spec/libsass-closed-issues/issue_659/sass-script.hrx"
#[test]
fn sass_script() {
assert_eq!(
rsass(
"$foo: null;\
\n\
\n@mixin bar() {\
\n bar: $foo;\
\n}\
\n\
\n@mixin baz() {\
\n baz: $foo !important;\
\n}\
\n\
\nfoo {\
\n baz: $foo;\
\n}\
\n\
\nbar {\
\n @include bar;\
\n}\
\n\
\nbaz {\
\n @include baz;\
\n}\
\n"
)
.unwrap(),
"baz {\
\n baz: !important;\
\n}\
\n"
);
}
// From "sass-spec/spec/libsass-closed-issues/issue_659/static.hrx"
#[test]
#[ignore] // wrong result
fn test_static() {
assert_eq!(
rsass(
"\
\n%bam { bam: null; }\
\n\
\n@mixin bar() {\
\n bar: null;\
\n}\
\n\
\n@mixin baz() {\
\n baz: null !important;\
\n}\
\n\
\nfoo {\
\n foo: null;\
\n}\
\n\
\nbar {\
\n @include bar;\
\n}\
\n\
\nbaz {\
\n @include baz;\
\n}\
\n\
\nbam {\
\n @extend %bam;\
\n}\
\n"
)
.unwrap(),
"baz {\
\n baz: !important;\
\n}\
\n"
);
}
|
mod moebius_instruction;
mod moebius_state;
use proc_macro::TokenStream;
use syn::parse_macro_input;
use crate::{moebius_instruction::MoebiusInstruction, moebius_state::MoebiusState};
#[proc_macro_attribute]
pub fn moebius_state(attr: TokenStream, item: TokenStream) -> TokenStream {
let _ = attr;
let state = parse_macro_input!(item as MoebiusState);
state.expand().into()
}
#[proc_macro_attribute]
pub fn moebius_instruction(attr: TokenStream, item: TokenStream) -> TokenStream {
let _ = attr;
let instruction = parse_macro_input!(item as MoebiusInstruction);
instruction.expand().into()
}
|
extern crate rand;
extern crate rmp_serde;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
use futures::channel::mpsc::unbounded;
use futures::future::{lazy, FutureExt, LocalBoxFuture};
use rand::seq::SliceRandom;
use super::genesis::{build_node_transaction_map, build_verifiers, PoolTransactions};
use super::networker::{
LocalNetworker, Networker, NetworkerEvent, NetworkerFactory, SharedNetworker,
};
use super::requests::{PoolRequest, PoolRequestImpl, RequestHandle};
use super::types::{PoolSetup, Verifiers};
use crate::common::error::prelude::*;
use crate::common::merkle_tree::MerkleTree;
use crate::config::PoolConfig;
use crate::ledger::RequestBuilder;
use crate::utils::base58::ToBase58;
pub trait Pool: Clone {
type Request: PoolRequest;
fn get_config(&self) -> &PoolConfig;
fn create_request<'a>(
&'a self,
req_id: String,
req_json: String,
) -> LocalBoxFuture<'a, VdrResult<Self::Request>>;
fn get_merkle_tree(&self) -> &MerkleTree;
fn get_node_aliases(&self) -> Vec<String>;
fn get_merkle_tree_root(&self) -> (String, usize) {
let tree = self.get_merkle_tree();
(tree.root_hash().to_base58(), tree.count())
}
fn get_request_builder(&self) -> RequestBuilder {
RequestBuilder::new(self.get_config().protocol_version)
}
fn get_transactions(&self) -> VdrResult<Vec<String>> {
PoolTransactions::from(self.get_merkle_tree()).encode_json()
}
}
#[derive(Clone)]
pub struct PoolImpl<S: AsRef<PoolSetup> + Clone, T: Networker + Clone> {
setup: S,
networker: T,
}
pub type LocalPool = PoolImpl<Rc<PoolSetup>, LocalNetworker>;
pub type SharedPool = PoolImpl<Arc<PoolSetup>, SharedNetworker>;
impl<S, T> PoolImpl<S, T>
where
S: AsRef<PoolSetup> + Clone + From<Box<PoolSetup>>,
T: Networker + Clone,
{
pub fn new(setup: S, networker: T) -> Self {
Self { setup, networker }
}
pub fn build<F>(
config: PoolConfig,
merkle_tree: MerkleTree,
networker_factory: F,
node_weights: Option<HashMap<String, f32>>,
) -> VdrResult<Self>
where
F: NetworkerFactory<Output = T>,
{
let txn_map = build_node_transaction_map(&merkle_tree, config.protocol_version)?;
let verifiers = build_verifiers(txn_map)?;
let networker = networker_factory.make_networker(config, &verifiers)?;
let setup = PoolSetup::new(config, merkle_tree, node_weights, verifiers);
Ok(Self::new(S::from(Box::new(setup)), networker))
}
}
impl<S, T> Pool for PoolImpl<S, T>
where
S: AsRef<PoolSetup> + Clone,
T: Networker + Clone,
{
type Request = PoolRequestImpl<S, T>;
fn create_request<'a>(
&'a self,
req_id: String,
req_json: String,
) -> LocalBoxFuture<'a, VdrResult<Self::Request>> {
let setup = self.setup.clone();
let networker = self.networker.clone();
lazy(move |_| {
let (tx, rx) = unbounded();
let handle = RequestHandle::next();
let setup_ref = setup.as_ref();
let node_order = choose_nodes(&setup_ref.verifiers, setup_ref.node_weights.clone());
debug!("New {}: reqId({})", handle, req_id);
networker.send(NetworkerEvent::NewRequest(handle, req_id, req_json, tx))?;
Ok(PoolRequestImpl::new(
handle, rx, setup, networker, node_order,
))
})
.boxed_local()
}
fn get_config(&self) -> &PoolConfig {
&self.setup.as_ref().config
}
fn get_merkle_tree(&self) -> &MerkleTree {
&self.setup.as_ref().merkle_tree
}
fn get_node_aliases(&self) -> Vec<String> {
self.setup.as_ref().verifiers.keys().cloned().collect()
}
}
pub fn choose_nodes(verifiers: &Verifiers, weights: Option<HashMap<String, f32>>) -> Vec<String> {
let mut weighted = verifiers
.keys()
.map(|name| {
(
weights
.as_ref()
.and_then(|w| w.get(name))
.cloned()
.unwrap_or(1.0),
name.as_str(),
)
})
.collect::<Vec<(f32, &str)>>();
let mut rng = rand::thread_rng();
let mut result = vec![];
for _ in 0..weighted.len() {
let found = weighted
.choose_weighted_mut(&mut rng, |item| item.0)
.unwrap();
found.0 = 0.0;
result.push(found.1.to_string());
}
result
}
/*
#[cfg(test)]
mod tests {
// use crate::services::pool::events::MockUpdateHandler;
use crate::services::pool::networker::MockNetworker;
use crate::services::pool::request_handler::tests::MockRequestHandler;
use crate::services::pool::types::{
next_command_handle, next_pool_handle, Message, Reply, ReplyResultV1, ReplyTxnV1, ReplyV1,
ResponseMetadata,
};
use crate::utils::test;
use crate::utils::test::test_pool_create_poolfile;
use super::*;
const TEST_POOL_CONFIG: PoolConfig = PoolConfig::default();
mod pool {
use super::*;
#[test]
pub fn pool_new_works() {
let _p: Pool<MockNetworker, MockRequestHandler> =
Pool::new(next_pool_handle(), &TEST_POOL_CONFIG);
}
#[test]
pub fn pool_get_id_works() {
let id = next_pool_handle();
let p: Pool<MockNetworker, MockRequestHandler> = Pool::new(id, &TEST_POOL_CONFIG);
assert_eq!(id, p.get_id());
}
}
mod pool_sm {
use std::io::Write;
use serde_json;
use super::*;
#[test]
pub fn pool_wrapper_new_inactive_works() {
let _p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
}
#[test]
pub fn pool_wrapper_check_cache_works() {
test::cleanup_storage("pool_wrapper_check_cache_works");
_write_genesis_txns("pool_wrapper_check_cache_works");
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
assert_match!(PoolState::GettingCatchupTarget(_), p.state);
test::cleanup_storage("pool_wrapper_check_cache_works");
}
#[test]
pub fn pool_wrapper_check_cache_works_for_no_pool_created() {
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
assert_match!(PoolState::Terminated(_), p.state);
}
#[test]
pub fn pool_wrapper_terminated_close_works() {
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::Close(cmd_id));
assert_match!(PoolState::Closed(_), p.state);
}
#[test]
pub fn pool_wrapper_terminated_refresh_works() {
test::cleanup_pool("pool_wrapper_terminated_refresh_works");
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
_write_genesis_txns("pool_wrapper_terminated_refresh_works");
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::Refresh(cmd_id));
assert_match!(PoolState::GettingCatchupTarget(_), p.state);
test::cleanup_pool("pool_wrapper_terminated_refresh_works");
}
#[test]
pub fn pool_wrapper_terminated_timeout_works() {
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM {
id: next_pool_handle(),
config: TEST_POOL_CONFIG,
state: PoolState::Terminated(TerminatedState {
networker: Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
}),
};
let p = p.handle_event(PoolEvent::Timeout("".to_string(), "".to_string()));
assert_match!(PoolState::Terminated(_), p.state);
match p.state {
PoolState::Terminated(state) => {
assert_eq!(state.networker.borrow().events.len(), 1);
let event = state.networker.borrow_mut().events.remove(0);
assert_match!(Some(NetworkerEvent::Timeout), event);
}
_ => assert!(false),
}
}
#[test]
pub fn pool_wrapper_close_works_from_inactive() {
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::Close(cmd_id));
assert_match!(PoolState::Closed(_), p.state);
}
#[test]
pub fn pool_wrapper_close_works_from_getting_catchup_target() {
test::cleanup_storage("pool_wrapper_close_works_from_getting_catchup_target");
_write_genesis_txns("pool_wrapper_close_works_from_getting_catchup_target");
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::Close(cmd_id));
assert_match!(PoolState::Closed(_), p.state);
test::cleanup_storage("pool_wrapper_close_works_from_getting_catchup_target");
}
#[test]
pub fn pool_wrapper_catchup_target_not_found_works() {
test::cleanup_storage("pool_wrapper_catchup_target_not_found_works");
_write_genesis_txns("pool_wrapper_catchup_target_not_found_works");
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
let p = p.handle_event(PoolEvent::CatchupTargetNotFound(err_msg(
VdrErrorKind::PoolTimeout,
"Pool timeout",
)));
assert_match!(PoolState::Terminated(_), p.state);
test::cleanup_storage("pool_wrapper_catchup_target_not_found_works");
}
#[test]
pub fn pool_wrapper_getting_catchup_target_synced_works() {
test::cleanup_storage("pool_wrapper_getting_catchup_target_synced_works");
_write_genesis_txns("pool_wrapper_getting_catchup_target_synced_works");
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
let p = p.handle_event(PoolEvent::Synced(MerkleTree::from_vec(vec![]).unwrap()));
assert_match!(PoolState::Active(_), p.state);
test::cleanup_storage("pool_wrapper_getting_catchup_target_synced_works");
}
/*
FIXME changes protocol version
#[test]
pub fn pool_wrapper_getting_catchup_target_synced_works_for_node_state_error() {
test::cleanup_storage(
"pool_wrapper_getting_catchup_target_synced_works_for_node_state_error",
);
ProtocolVersion::set(2);
_write_genesis_txns(
"pool_wrapper_getting_catchup_target_synced_works_for_node_state_error",
);
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
ProtocolVersion::set(1);
let p = p.handle_event(PoolEvent::Synced(
merkle_tree_factory::create(
"pool_wrapper_getting_catchup_target_synced_works_for_node_state_error",
)
.unwrap(),
));
assert_match!(PoolState::Terminated(_), p.state);
test::cleanup_storage(
"pool_wrapper_getting_catchup_target_synced_works_for_node_state_error",
);
}
*/
#[test]
pub fn pool_wrapper_getting_catchup_target_catchup_target_found_works() {
test::cleanup_storage("pool_wrapper_getting_catchup_target_catchup_target_found_works");
_write_genesis_txns("pool_wrapper_getting_catchup_target_catchup_target_found_works");
let mt = merkle_tree_factory::create(
"pool_wrapper_getting_catchup_target_catchup_target_found_works",
)
.unwrap();
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
let p = p.handle_event(PoolEvent::CatchupTargetFound(
mt.root_hash().to_vec(),
mt.count,
mt,
));
assert_match!(PoolState::SyncCatchup(_), p.state);
test::cleanup_storage("pool_wrapper_getting_catchup_target_catchup_target_found_works");
}
/*
FIXME changed protocol version
#[test]
pub fn pool_wrapper_getting_catchup_target_catchup_target_found_works_for_node_state_error()
{
test::cleanup_storage("pool_wrapper_getting_catchup_target_catchup_target_found_works_for_node_state_error");
ProtocolVersion::set(2);
_write_genesis_txns("pool_wrapper_getting_catchup_target_catchup_target_found_works_for_node_state_error");
let mt = merkle_tree_factory::create("pool_wrapper_getting_catchup_target_catchup_target_found_works_for_node_state_error").unwrap();
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
ProtocolVersion::set(1);
let p = p.handle_event(PoolEvent::CatchupTargetFound(
mt.root_hash().to_vec(),
mt.count,
mt,
));
assert_match!(PoolState::Terminated(_), p.state);
test::cleanup_storage("pool_wrapper_getting_catchup_target_catchup_target_found_works_for_node_state_error");
}
*/
#[test]
pub fn pool_wrapper_sync_catchup_close_works() {
test::cleanup_storage("pool_wrapper_sync_catchup_close_works");
_write_genesis_txns("pool_wrapper_sync_catchup_close_works");
let mt = merkle_tree_factory::create("pool_wrapper_sync_catchup_close_works").unwrap();
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
let p = p.handle_event(PoolEvent::CatchupTargetFound(
mt.root_hash().to_vec(),
mt.count,
mt,
));
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::Close(cmd_id));
assert_match!(PoolState::Closed(_), p.state);
test::cleanup_storage("pool_wrapper_sync_catchup_close_works");
}
#[test]
pub fn pool_wrapper_sync_catchup_synced_works() {
test::cleanup_storage("pool_wrapper_sync_catchup_synced_works");
_write_genesis_txns("pool_wrapper_sync_catchup_synced_works");
let mt = merkle_tree_factory::create("pool_wrapper_sync_catchup_synced_works").unwrap();
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
let p = p.handle_event(PoolEvent::CatchupTargetFound(
mt.root_hash().to_vec(),
mt.count,
mt,
));
let p = p.handle_event(PoolEvent::Synced(
merkle_tree_factory::create("pool_wrapper_sync_catchup_synced_works").unwrap(),
));
assert_match!(PoolState::Active(_), p.state);
test::cleanup_storage("pool_wrapper_sync_catchup_synced_works");
}
/*
FIXME changes protocol version
#[test]
pub fn pool_wrapper_sync_catchup_synced_works_for_node_state_error() {
test::cleanup_storage("pool_wrapper_sync_catchup_synced_works_for_node_state_error");
ProtocolVersion::set(2);
_write_genesis_txns("pool_wrapper_sync_catchup_synced_works_for_node_state_error");
let mt = merkle_tree_factory::create(
"pool_wrapper_sync_catchup_synced_works_for_node_state_error",
)
.unwrap();
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
let p = p.handle_event(PoolEvent::CatchupTargetFound(
mt.root_hash().to_vec(),
mt.count,
mt,
));
ProtocolVersion::set(1);
let p = p.handle_event(PoolEvent::Synced(
merkle_tree_factory::create(
"pool_wrapper_sync_catchup_synced_works_for_node_state_error",
)
.unwrap(),
));
assert_match!(PoolState::Terminated(_), p.state);
test::cleanup_storage("pool_wrapper_sync_catchup_synced_works_for_node_state_error");
}
*/
#[test]
pub fn pool_wrapper_active_send_request_works() {
test::cleanup_storage("pool_wrapper_active_send_request_works");
_write_genesis_txns("pool_wrapper_active_send_request_works");
let req = json!({
"reqId": 1,
"operation": {
"type": "1"
}
})
.to_string();
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
let p = p.handle_event(PoolEvent::Synced(MerkleTree::from_vec(vec![]).unwrap()));
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::SendRequest(cmd_id, req, None, None));
assert_match!(PoolState::Active(_), p.state);
match p.state {
PoolState::Active(state) => {
assert_eq!(state.request_handlers.len(), 1);
assert!(state.request_handlers.contains_key("1"));
}
_ => assert!(false),
};
test::cleanup_storage("pool_wrapper_active_send_request_works");
}
#[test]
pub fn pool_wrapper_active_send_request_works_for_no_req_id() {
test::cleanup_storage("pool_wrapper_active_send_request_works_for_no_req_id");
_write_genesis_txns("pool_wrapper_active_send_request_works_for_no_req_id");
let req = json!({
"operation": {
"type": "1"
}
})
.to_string();
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
let p = p.handle_event(PoolEvent::Synced(MerkleTree::from_vec(vec![]).unwrap()));
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::SendRequest(cmd_id, req, None, None));
assert_match!(PoolState::Active(_), p.state);
match p.state {
PoolState::Active(state) => {
assert_eq!(state.request_handlers.len(), 0);
}
_ => assert!(false),
};
test::cleanup_storage("pool_wrapper_active_send_request_works_for_no_req_id");
}
#[test]
pub fn pool_wrapper_active_node_reply_works() {
test::cleanup_storage("pool_wrapper_active_node_reply_works");
_write_genesis_txns("pool_wrapper_active_node_reply_works");
let req = json!({
"reqId": 1,
"operation": {
"type": "1"
}
})
.to_string();
let rep = Message::Reply(Reply::ReplyV1(ReplyV1 {
result: ReplyResultV1 {
txn: ReplyTxnV1 {
metadata: ResponseMetadata { req_id: 1 },
},
},
}));
let rep = serde_json::to_string(&rep).unwrap();
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
let p = p.handle_event(PoolEvent::Synced(MerkleTree::from_vec(vec![]).unwrap()));
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::SendRequest(cmd_id, req, None, None));
let p = p.handle_event(PoolEvent::NodeReply(rep, "node".to_string()));
assert_match!(PoolState::Active(_), p.state);
match p.state {
PoolState::Active(state) => {
assert_eq!(state.request_handlers.len(), 0);
}
_ => assert!(false),
};
test::cleanup_storage("pool_wrapper_active_node_reply_works");
}
#[test]
pub fn pool_wrapper_sends_requests_to_two_nodes() {
test::cleanup_storage("pool_wrapper_sends_requests_to_two_nodes");
_write_genesis_txns("pool_wrapper_sends_requests_to_two_nodes");
let req = json!({
"reqId": 1,
"operation": {
"type": "105"
}
})
.to_string();
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
let p = p.handle_event(PoolEvent::Synced(MerkleTree::from_vec(vec![]).unwrap()));
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::SendRequest(cmd_id, req, None, None));
assert_match!(PoolState::Active(_), p.state);
match p.state {
PoolState::Active(state) => {
assert_eq!(state.networker.borrow().events.len(), 2);
}
_ => assert!(false),
};
test::cleanup_storage("pool_wrapper_sends_requests_to_two_nodes");
}
#[test]
pub fn pool_wrapper_active_node_reply_works_for_no_request() {
test::cleanup_storage("pool_wrapper_active_node_reply_works_for_no_request");
_write_genesis_txns("pool_wrapper_active_node_reply_works_for_no_request");
let req = json!({
"reqId": 1,
"operation": {
"type": "1"
}
})
.to_string();
let rep = Message::Reply(Reply::ReplyV1(ReplyV1 {
result: ReplyResultV1 {
txn: ReplyTxnV1 {
metadata: ResponseMetadata { req_id: 2 },
},
},
}));
let rep = serde_json::to_string(&rep).unwrap();
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
let p = p.handle_event(PoolEvent::Synced(MerkleTree::from_vec(vec![]).unwrap()));
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::SendRequest(cmd_id, req, None, None));
let p = p.handle_event(PoolEvent::NodeReply(rep, "node".to_string()));
assert_match!(PoolState::Active(_), p.state);
match p.state {
PoolState::Active(state) => {
assert_eq!(state.request_handlers.len(), 1);
assert!(state.request_handlers.contains_key("1"));
}
_ => assert!(false),
};
test::cleanup_storage("pool_wrapper_active_node_reply_works_for_no_request");
}
#[test]
pub fn pool_wrapper_active_node_reply_works_for_invalid_reply() {
test::cleanup_storage("pool_wrapper_active_node_reply_works_for_invalid_reply");
_write_genesis_txns("pool_wrapper_active_node_reply_works_for_invalid_reply");
let req = json!({
"reqId": 1,
"operation": {
"type": "1"
}
})
.to_string();
let rep = r#"{}"#;
let p: PoolSM<MockNetworker, MockRequestHandler> = PoolSM::new(
next_pool_handle(),
&TEST_POOL_CONFIG,
Rc::new(RefCell::new(MockNetworker::new(0, 0, vec![]))),
);
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::CheckCache(cmd_id));
let p = p.handle_event(PoolEvent::Synced(MerkleTree::from_vec(vec![]).unwrap()));
let cmd_id: CommandHandle = next_command_handle();
let p = p.handle_event(PoolEvent::SendRequest(cmd_id, req, None, None));
let p = p.handle_event(PoolEvent::NodeReply(rep.to_string(), "node".to_string()));
assert_match!(PoolState::Active(_), p.state);
match p.state {
PoolState::Active(state) => {
assert_eq!(state.request_handlers.len(), 1);
}
_ => assert!(false),
};
test::cleanup_storage("pool_wrapper_active_node_reply_works_for_invalid_reply");
}
fn _write_genesis_txns(pool_name: &str) {
let txns = test::gen_txns().join("\n");
let mut f = test_pool_create_poolfile(pool_name);
f.write(txns.as_bytes()).unwrap();
f.flush().unwrap();
f.sync_all().unwrap();
}
}
mod other {
use super::*;
#[test]
fn get_f_works() {
test::cleanup_storage("get_f_works");
assert_eq!(_get_f(0), 0);
assert_eq!(_get_f(3), 0);
assert_eq!(_get_f(4), 1);
assert_eq!(_get_f(5), 1);
assert_eq!(_get_f(6), 1);
assert_eq!(_get_f(7), 2);
}
}
}
*/
|
pub mod ep0r {
pub mod ea {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40005C00u32 as *const u32) & 0xF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C00u32 as *const u32);
reg &= 0xFFFFFFF0u32;
reg |= val & 0xF;
core::ptr::write_volatile(0x40005C00u32 as *mut u32, reg);
}
}
}
pub mod stat_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C00u32 as *const u32) >> 4) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C00u32 as *const u32);
reg &= 0xFFFFFFCFu32;
reg |= (val & 0x3) << 4;
core::ptr::write_volatile(0x40005C00u32 as *mut u32, reg);
}
}
}
pub mod dtog_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C00u32 as *const u32) >> 6) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C00u32 as *const u32);
reg &= 0xFFFFFFBFu32;
reg |= (val & 0x1) << 6;
core::ptr::write_volatile(0x40005C00u32 as *mut u32, reg);
}
}
}
pub mod ctr_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C00u32 as *const u32) >> 7) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C00u32 as *const u32);
reg &= 0xFFFFFF7Fu32;
reg |= (val & 0x1) << 7;
core::ptr::write_volatile(0x40005C00u32 as *mut u32, reg);
}
}
}
pub mod ep_kind {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C00u32 as *const u32) >> 8) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C00u32 as *const u32);
reg &= 0xFFFFFEFFu32;
reg |= (val & 0x1) << 8;
core::ptr::write_volatile(0x40005C00u32 as *mut u32, reg);
}
}
}
pub mod ep_type {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C00u32 as *const u32) >> 9) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C00u32 as *const u32);
reg &= 0xFFFFF9FFu32;
reg |= (val & 0x3) << 9;
core::ptr::write_volatile(0x40005C00u32 as *mut u32, reg);
}
}
}
pub mod setup {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C00u32 as *const u32) >> 11) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C00u32 as *const u32);
reg &= 0xFFFFF7FFu32;
reg |= (val & 0x1) << 11;
core::ptr::write_volatile(0x40005C00u32 as *mut u32, reg);
}
}
}
pub mod stat_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C00u32 as *const u32) >> 12) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C00u32 as *const u32);
reg &= 0xFFFFCFFFu32;
reg |= (val & 0x3) << 12;
core::ptr::write_volatile(0x40005C00u32 as *mut u32, reg);
}
}
}
pub mod dtog_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C00u32 as *const u32) >> 14) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C00u32 as *const u32);
reg &= 0xFFFFBFFFu32;
reg |= (val & 0x1) << 14;
core::ptr::write_volatile(0x40005C00u32 as *mut u32, reg);
}
}
}
pub mod ctr_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C00u32 as *const u32) >> 15) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C00u32 as *const u32);
reg &= 0xFFFF7FFFu32;
reg |= (val & 0x1) << 15;
core::ptr::write_volatile(0x40005C00u32 as *mut u32, reg);
}
}
}
}
pub mod ep1r {
pub mod ea {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40005C04u32 as *const u32) & 0xF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C04u32 as *const u32);
reg &= 0xFFFFFFF0u32;
reg |= val & 0xF;
core::ptr::write_volatile(0x40005C04u32 as *mut u32, reg);
}
}
}
pub mod stat_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C04u32 as *const u32) >> 4) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C04u32 as *const u32);
reg &= 0xFFFFFFCFu32;
reg |= (val & 0x3) << 4;
core::ptr::write_volatile(0x40005C04u32 as *mut u32, reg);
}
}
}
pub mod dtog_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C04u32 as *const u32) >> 6) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C04u32 as *const u32);
reg &= 0xFFFFFFBFu32;
reg |= (val & 0x1) << 6;
core::ptr::write_volatile(0x40005C04u32 as *mut u32, reg);
}
}
}
pub mod ctr_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C04u32 as *const u32) >> 7) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C04u32 as *const u32);
reg &= 0xFFFFFF7Fu32;
reg |= (val & 0x1) << 7;
core::ptr::write_volatile(0x40005C04u32 as *mut u32, reg);
}
}
}
pub mod ep_kind {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C04u32 as *const u32) >> 8) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C04u32 as *const u32);
reg &= 0xFFFFFEFFu32;
reg |= (val & 0x1) << 8;
core::ptr::write_volatile(0x40005C04u32 as *mut u32, reg);
}
}
}
pub mod ep_type {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C04u32 as *const u32) >> 9) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C04u32 as *const u32);
reg &= 0xFFFFF9FFu32;
reg |= (val & 0x3) << 9;
core::ptr::write_volatile(0x40005C04u32 as *mut u32, reg);
}
}
}
pub mod setup {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C04u32 as *const u32) >> 11) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C04u32 as *const u32);
reg &= 0xFFFFF7FFu32;
reg |= (val & 0x1) << 11;
core::ptr::write_volatile(0x40005C04u32 as *mut u32, reg);
}
}
}
pub mod stat_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C04u32 as *const u32) >> 12) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C04u32 as *const u32);
reg &= 0xFFFFCFFFu32;
reg |= (val & 0x3) << 12;
core::ptr::write_volatile(0x40005C04u32 as *mut u32, reg);
}
}
}
pub mod dtog_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C04u32 as *const u32) >> 14) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C04u32 as *const u32);
reg &= 0xFFFFBFFFu32;
reg |= (val & 0x1) << 14;
core::ptr::write_volatile(0x40005C04u32 as *mut u32, reg);
}
}
}
pub mod ctr_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C04u32 as *const u32) >> 15) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C04u32 as *const u32);
reg &= 0xFFFF7FFFu32;
reg |= (val & 0x1) << 15;
core::ptr::write_volatile(0x40005C04u32 as *mut u32, reg);
}
}
}
}
pub mod ep2r {
pub mod ea {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40005C08u32 as *const u32) & 0xF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C08u32 as *const u32);
reg &= 0xFFFFFFF0u32;
reg |= val & 0xF;
core::ptr::write_volatile(0x40005C08u32 as *mut u32, reg);
}
}
}
pub mod stat_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C08u32 as *const u32) >> 4) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C08u32 as *const u32);
reg &= 0xFFFFFFCFu32;
reg |= (val & 0x3) << 4;
core::ptr::write_volatile(0x40005C08u32 as *mut u32, reg);
}
}
}
pub mod dtog_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C08u32 as *const u32) >> 6) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C08u32 as *const u32);
reg &= 0xFFFFFFBFu32;
reg |= (val & 0x1) << 6;
core::ptr::write_volatile(0x40005C08u32 as *mut u32, reg);
}
}
}
pub mod ctr_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C08u32 as *const u32) >> 7) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C08u32 as *const u32);
reg &= 0xFFFFFF7Fu32;
reg |= (val & 0x1) << 7;
core::ptr::write_volatile(0x40005C08u32 as *mut u32, reg);
}
}
}
pub mod ep_kind {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C08u32 as *const u32) >> 8) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C08u32 as *const u32);
reg &= 0xFFFFFEFFu32;
reg |= (val & 0x1) << 8;
core::ptr::write_volatile(0x40005C08u32 as *mut u32, reg);
}
}
}
pub mod ep_type {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C08u32 as *const u32) >> 9) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C08u32 as *const u32);
reg &= 0xFFFFF9FFu32;
reg |= (val & 0x3) << 9;
core::ptr::write_volatile(0x40005C08u32 as *mut u32, reg);
}
}
}
pub mod setup {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C08u32 as *const u32) >> 11) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C08u32 as *const u32);
reg &= 0xFFFFF7FFu32;
reg |= (val & 0x1) << 11;
core::ptr::write_volatile(0x40005C08u32 as *mut u32, reg);
}
}
}
pub mod stat_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C08u32 as *const u32) >> 12) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C08u32 as *const u32);
reg &= 0xFFFFCFFFu32;
reg |= (val & 0x3) << 12;
core::ptr::write_volatile(0x40005C08u32 as *mut u32, reg);
}
}
}
pub mod dtog_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C08u32 as *const u32) >> 14) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C08u32 as *const u32);
reg &= 0xFFFFBFFFu32;
reg |= (val & 0x1) << 14;
core::ptr::write_volatile(0x40005C08u32 as *mut u32, reg);
}
}
}
pub mod ctr_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C08u32 as *const u32) >> 15) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C08u32 as *const u32);
reg &= 0xFFFF7FFFu32;
reg |= (val & 0x1) << 15;
core::ptr::write_volatile(0x40005C08u32 as *mut u32, reg);
}
}
}
}
pub mod ep3r {
pub mod ea {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40005C0Cu32 as *const u32) & 0xF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C0Cu32 as *const u32);
reg &= 0xFFFFFFF0u32;
reg |= val & 0xF;
core::ptr::write_volatile(0x40005C0Cu32 as *mut u32, reg);
}
}
}
pub mod stat_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C0Cu32 as *const u32) >> 4) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C0Cu32 as *const u32);
reg &= 0xFFFFFFCFu32;
reg |= (val & 0x3) << 4;
core::ptr::write_volatile(0x40005C0Cu32 as *mut u32, reg);
}
}
}
pub mod dtog_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C0Cu32 as *const u32) >> 6) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C0Cu32 as *const u32);
reg &= 0xFFFFFFBFu32;
reg |= (val & 0x1) << 6;
core::ptr::write_volatile(0x40005C0Cu32 as *mut u32, reg);
}
}
}
pub mod ctr_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C0Cu32 as *const u32) >> 7) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C0Cu32 as *const u32);
reg &= 0xFFFFFF7Fu32;
reg |= (val & 0x1) << 7;
core::ptr::write_volatile(0x40005C0Cu32 as *mut u32, reg);
}
}
}
pub mod ep_kind {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C0Cu32 as *const u32) >> 8) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C0Cu32 as *const u32);
reg &= 0xFFFFFEFFu32;
reg |= (val & 0x1) << 8;
core::ptr::write_volatile(0x40005C0Cu32 as *mut u32, reg);
}
}
}
pub mod ep_type {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C0Cu32 as *const u32) >> 9) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C0Cu32 as *const u32);
reg &= 0xFFFFF9FFu32;
reg |= (val & 0x3) << 9;
core::ptr::write_volatile(0x40005C0Cu32 as *mut u32, reg);
}
}
}
pub mod setup {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C0Cu32 as *const u32) >> 11) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C0Cu32 as *const u32);
reg &= 0xFFFFF7FFu32;
reg |= (val & 0x1) << 11;
core::ptr::write_volatile(0x40005C0Cu32 as *mut u32, reg);
}
}
}
pub mod stat_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C0Cu32 as *const u32) >> 12) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C0Cu32 as *const u32);
reg &= 0xFFFFCFFFu32;
reg |= (val & 0x3) << 12;
core::ptr::write_volatile(0x40005C0Cu32 as *mut u32, reg);
}
}
}
pub mod dtog_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C0Cu32 as *const u32) >> 14) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C0Cu32 as *const u32);
reg &= 0xFFFFBFFFu32;
reg |= (val & 0x1) << 14;
core::ptr::write_volatile(0x40005C0Cu32 as *mut u32, reg);
}
}
}
pub mod ctr_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C0Cu32 as *const u32) >> 15) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C0Cu32 as *const u32);
reg &= 0xFFFF7FFFu32;
reg |= (val & 0x1) << 15;
core::ptr::write_volatile(0x40005C0Cu32 as *mut u32, reg);
}
}
}
}
pub mod ep4r {
pub mod ea {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40005C10u32 as *const u32) & 0xF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C10u32 as *const u32);
reg &= 0xFFFFFFF0u32;
reg |= val & 0xF;
core::ptr::write_volatile(0x40005C10u32 as *mut u32, reg);
}
}
}
pub mod stat_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C10u32 as *const u32) >> 4) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C10u32 as *const u32);
reg &= 0xFFFFFFCFu32;
reg |= (val & 0x3) << 4;
core::ptr::write_volatile(0x40005C10u32 as *mut u32, reg);
}
}
}
pub mod dtog_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C10u32 as *const u32) >> 6) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C10u32 as *const u32);
reg &= 0xFFFFFFBFu32;
reg |= (val & 0x1) << 6;
core::ptr::write_volatile(0x40005C10u32 as *mut u32, reg);
}
}
}
pub mod ctr_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C10u32 as *const u32) >> 7) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C10u32 as *const u32);
reg &= 0xFFFFFF7Fu32;
reg |= (val & 0x1) << 7;
core::ptr::write_volatile(0x40005C10u32 as *mut u32, reg);
}
}
}
pub mod ep_kind {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C10u32 as *const u32) >> 8) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C10u32 as *const u32);
reg &= 0xFFFFFEFFu32;
reg |= (val & 0x1) << 8;
core::ptr::write_volatile(0x40005C10u32 as *mut u32, reg);
}
}
}
pub mod ep_type {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C10u32 as *const u32) >> 9) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C10u32 as *const u32);
reg &= 0xFFFFF9FFu32;
reg |= (val & 0x3) << 9;
core::ptr::write_volatile(0x40005C10u32 as *mut u32, reg);
}
}
}
pub mod setup {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C10u32 as *const u32) >> 11) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C10u32 as *const u32);
reg &= 0xFFFFF7FFu32;
reg |= (val & 0x1) << 11;
core::ptr::write_volatile(0x40005C10u32 as *mut u32, reg);
}
}
}
pub mod stat_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C10u32 as *const u32) >> 12) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C10u32 as *const u32);
reg &= 0xFFFFCFFFu32;
reg |= (val & 0x3) << 12;
core::ptr::write_volatile(0x40005C10u32 as *mut u32, reg);
}
}
}
pub mod dtog_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C10u32 as *const u32) >> 14) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C10u32 as *const u32);
reg &= 0xFFFFBFFFu32;
reg |= (val & 0x1) << 14;
core::ptr::write_volatile(0x40005C10u32 as *mut u32, reg);
}
}
}
pub mod ctr_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C10u32 as *const u32) >> 15) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C10u32 as *const u32);
reg &= 0xFFFF7FFFu32;
reg |= (val & 0x1) << 15;
core::ptr::write_volatile(0x40005C10u32 as *mut u32, reg);
}
}
}
}
pub mod ep5r {
pub mod ea {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40005C14u32 as *const u32) & 0xF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C14u32 as *const u32);
reg &= 0xFFFFFFF0u32;
reg |= val & 0xF;
core::ptr::write_volatile(0x40005C14u32 as *mut u32, reg);
}
}
}
pub mod stat_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C14u32 as *const u32) >> 4) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C14u32 as *const u32);
reg &= 0xFFFFFFCFu32;
reg |= (val & 0x3) << 4;
core::ptr::write_volatile(0x40005C14u32 as *mut u32, reg);
}
}
}
pub mod dtog_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C14u32 as *const u32) >> 6) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C14u32 as *const u32);
reg &= 0xFFFFFFBFu32;
reg |= (val & 0x1) << 6;
core::ptr::write_volatile(0x40005C14u32 as *mut u32, reg);
}
}
}
pub mod ctr_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C14u32 as *const u32) >> 7) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C14u32 as *const u32);
reg &= 0xFFFFFF7Fu32;
reg |= (val & 0x1) << 7;
core::ptr::write_volatile(0x40005C14u32 as *mut u32, reg);
}
}
}
pub mod ep_kind {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C14u32 as *const u32) >> 8) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C14u32 as *const u32);
reg &= 0xFFFFFEFFu32;
reg |= (val & 0x1) << 8;
core::ptr::write_volatile(0x40005C14u32 as *mut u32, reg);
}
}
}
pub mod ep_type {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C14u32 as *const u32) >> 9) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C14u32 as *const u32);
reg &= 0xFFFFF9FFu32;
reg |= (val & 0x3) << 9;
core::ptr::write_volatile(0x40005C14u32 as *mut u32, reg);
}
}
}
pub mod setup {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C14u32 as *const u32) >> 11) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C14u32 as *const u32);
reg &= 0xFFFFF7FFu32;
reg |= (val & 0x1) << 11;
core::ptr::write_volatile(0x40005C14u32 as *mut u32, reg);
}
}
}
pub mod stat_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C14u32 as *const u32) >> 12) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C14u32 as *const u32);
reg &= 0xFFFFCFFFu32;
reg |= (val & 0x3) << 12;
core::ptr::write_volatile(0x40005C14u32 as *mut u32, reg);
}
}
}
pub mod dtog_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C14u32 as *const u32) >> 14) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C14u32 as *const u32);
reg &= 0xFFFFBFFFu32;
reg |= (val & 0x1) << 14;
core::ptr::write_volatile(0x40005C14u32 as *mut u32, reg);
}
}
}
pub mod ctr_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C14u32 as *const u32) >> 15) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C14u32 as *const u32);
reg &= 0xFFFF7FFFu32;
reg |= (val & 0x1) << 15;
core::ptr::write_volatile(0x40005C14u32 as *mut u32, reg);
}
}
}
}
pub mod ep6r {
pub mod ea {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40005C18u32 as *const u32) & 0xF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C18u32 as *const u32);
reg &= 0xFFFFFFF0u32;
reg |= val & 0xF;
core::ptr::write_volatile(0x40005C18u32 as *mut u32, reg);
}
}
}
pub mod stat_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C18u32 as *const u32) >> 4) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C18u32 as *const u32);
reg &= 0xFFFFFFCFu32;
reg |= (val & 0x3) << 4;
core::ptr::write_volatile(0x40005C18u32 as *mut u32, reg);
}
}
}
pub mod dtog_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C18u32 as *const u32) >> 6) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C18u32 as *const u32);
reg &= 0xFFFFFFBFu32;
reg |= (val & 0x1) << 6;
core::ptr::write_volatile(0x40005C18u32 as *mut u32, reg);
}
}
}
pub mod ctr_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C18u32 as *const u32) >> 7) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C18u32 as *const u32);
reg &= 0xFFFFFF7Fu32;
reg |= (val & 0x1) << 7;
core::ptr::write_volatile(0x40005C18u32 as *mut u32, reg);
}
}
}
pub mod ep_kind {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C18u32 as *const u32) >> 8) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C18u32 as *const u32);
reg &= 0xFFFFFEFFu32;
reg |= (val & 0x1) << 8;
core::ptr::write_volatile(0x40005C18u32 as *mut u32, reg);
}
}
}
pub mod ep_type {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C18u32 as *const u32) >> 9) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C18u32 as *const u32);
reg &= 0xFFFFF9FFu32;
reg |= (val & 0x3) << 9;
core::ptr::write_volatile(0x40005C18u32 as *mut u32, reg);
}
}
}
pub mod setup {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C18u32 as *const u32) >> 11) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C18u32 as *const u32);
reg &= 0xFFFFF7FFu32;
reg |= (val & 0x1) << 11;
core::ptr::write_volatile(0x40005C18u32 as *mut u32, reg);
}
}
}
pub mod stat_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C18u32 as *const u32) >> 12) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C18u32 as *const u32);
reg &= 0xFFFFCFFFu32;
reg |= (val & 0x3) << 12;
core::ptr::write_volatile(0x40005C18u32 as *mut u32, reg);
}
}
}
pub mod dtog_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C18u32 as *const u32) >> 14) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C18u32 as *const u32);
reg &= 0xFFFFBFFFu32;
reg |= (val & 0x1) << 14;
core::ptr::write_volatile(0x40005C18u32 as *mut u32, reg);
}
}
}
pub mod ctr_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C18u32 as *const u32) >> 15) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C18u32 as *const u32);
reg &= 0xFFFF7FFFu32;
reg |= (val & 0x1) << 15;
core::ptr::write_volatile(0x40005C18u32 as *mut u32, reg);
}
}
}
}
pub mod ep7r {
pub mod ea {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40005C1Cu32 as *const u32) & 0xF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C1Cu32 as *const u32);
reg &= 0xFFFFFFF0u32;
reg |= val & 0xF;
core::ptr::write_volatile(0x40005C1Cu32 as *mut u32, reg);
}
}
}
pub mod stat_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C1Cu32 as *const u32) >> 4) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C1Cu32 as *const u32);
reg &= 0xFFFFFFCFu32;
reg |= (val & 0x3) << 4;
core::ptr::write_volatile(0x40005C1Cu32 as *mut u32, reg);
}
}
}
pub mod dtog_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C1Cu32 as *const u32) >> 6) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C1Cu32 as *const u32);
reg &= 0xFFFFFFBFu32;
reg |= (val & 0x1) << 6;
core::ptr::write_volatile(0x40005C1Cu32 as *mut u32, reg);
}
}
}
pub mod ctr_tx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C1Cu32 as *const u32) >> 7) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C1Cu32 as *const u32);
reg &= 0xFFFFFF7Fu32;
reg |= (val & 0x1) << 7;
core::ptr::write_volatile(0x40005C1Cu32 as *mut u32, reg);
}
}
}
pub mod ep_kind {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C1Cu32 as *const u32) >> 8) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C1Cu32 as *const u32);
reg &= 0xFFFFFEFFu32;
reg |= (val & 0x1) << 8;
core::ptr::write_volatile(0x40005C1Cu32 as *mut u32, reg);
}
}
}
pub mod ep_type {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C1Cu32 as *const u32) >> 9) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C1Cu32 as *const u32);
reg &= 0xFFFFF9FFu32;
reg |= (val & 0x3) << 9;
core::ptr::write_volatile(0x40005C1Cu32 as *mut u32, reg);
}
}
}
pub mod setup {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C1Cu32 as *const u32) >> 11) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C1Cu32 as *const u32);
reg &= 0xFFFFF7FFu32;
reg |= (val & 0x1) << 11;
core::ptr::write_volatile(0x40005C1Cu32 as *mut u32, reg);
}
}
}
pub mod stat_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C1Cu32 as *const u32) >> 12) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C1Cu32 as *const u32);
reg &= 0xFFFFCFFFu32;
reg |= (val & 0x3) << 12;
core::ptr::write_volatile(0x40005C1Cu32 as *mut u32, reg);
}
}
}
pub mod dtog_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C1Cu32 as *const u32) >> 14) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C1Cu32 as *const u32);
reg &= 0xFFFFBFFFu32;
reg |= (val & 0x1) << 14;
core::ptr::write_volatile(0x40005C1Cu32 as *mut u32, reg);
}
}
}
pub mod ctr_rx {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C1Cu32 as *const u32) >> 15) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C1Cu32 as *const u32);
reg &= 0xFFFF7FFFu32;
reg |= (val & 0x1) << 15;
core::ptr::write_volatile(0x40005C1Cu32 as *mut u32, reg);
}
}
}
}
pub mod cntr {
pub mod fres {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40005C40u32 as *const u32) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C40u32 as *const u32);
reg &= 0xFFFFFFFEu32;
reg |= val & 0x1;
core::ptr::write_volatile(0x40005C40u32 as *mut u32, reg);
}
}
}
pub mod pdwn {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C40u32 as *const u32) >> 1) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C40u32 as *const u32);
reg &= 0xFFFFFFFDu32;
reg |= (val & 0x1) << 1;
core::ptr::write_volatile(0x40005C40u32 as *mut u32, reg);
}
}
}
pub mod lpmode {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C40u32 as *const u32) >> 2) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C40u32 as *const u32);
reg &= 0xFFFFFFFBu32;
reg |= (val & 0x1) << 2;
core::ptr::write_volatile(0x40005C40u32 as *mut u32, reg);
}
}
}
pub mod fsusp {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C40u32 as *const u32) >> 3) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C40u32 as *const u32);
reg &= 0xFFFFFFF7u32;
reg |= (val & 0x1) << 3;
core::ptr::write_volatile(0x40005C40u32 as *mut u32, reg);
}
}
}
pub mod resume {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C40u32 as *const u32) >> 4) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C40u32 as *const u32);
reg &= 0xFFFFFFEFu32;
reg |= (val & 0x1) << 4;
core::ptr::write_volatile(0x40005C40u32 as *mut u32, reg);
}
}
}
pub mod esofm {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C40u32 as *const u32) >> 8) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C40u32 as *const u32);
reg &= 0xFFFFFEFFu32;
reg |= (val & 0x1) << 8;
core::ptr::write_volatile(0x40005C40u32 as *mut u32, reg);
}
}
}
pub mod sofm {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C40u32 as *const u32) >> 9) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C40u32 as *const u32);
reg &= 0xFFFFFDFFu32;
reg |= (val & 0x1) << 9;
core::ptr::write_volatile(0x40005C40u32 as *mut u32, reg);
}
}
}
pub mod resetm {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C40u32 as *const u32) >> 10) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C40u32 as *const u32);
reg &= 0xFFFFFBFFu32;
reg |= (val & 0x1) << 10;
core::ptr::write_volatile(0x40005C40u32 as *mut u32, reg);
}
}
}
pub mod suspm {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C40u32 as *const u32) >> 11) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C40u32 as *const u32);
reg &= 0xFFFFF7FFu32;
reg |= (val & 0x1) << 11;
core::ptr::write_volatile(0x40005C40u32 as *mut u32, reg);
}
}
}
pub mod wkupm {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C40u32 as *const u32) >> 12) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C40u32 as *const u32);
reg &= 0xFFFFEFFFu32;
reg |= (val & 0x1) << 12;
core::ptr::write_volatile(0x40005C40u32 as *mut u32, reg);
}
}
}
pub mod errm {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C40u32 as *const u32) >> 13) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C40u32 as *const u32);
reg &= 0xFFFFDFFFu32;
reg |= (val & 0x1) << 13;
core::ptr::write_volatile(0x40005C40u32 as *mut u32, reg);
}
}
}
pub mod pmaovrm {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C40u32 as *const u32) >> 14) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C40u32 as *const u32);
reg &= 0xFFFFBFFFu32;
reg |= (val & 0x1) << 14;
core::ptr::write_volatile(0x40005C40u32 as *mut u32, reg);
}
}
}
pub mod ctrm {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C40u32 as *const u32) >> 15) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C40u32 as *const u32);
reg &= 0xFFFF7FFFu32;
reg |= (val & 0x1) << 15;
core::ptr::write_volatile(0x40005C40u32 as *mut u32, reg);
}
}
}
}
pub mod istr {
pub mod ep_id {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40005C44u32 as *const u32) & 0xF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C44u32 as *const u32);
reg &= 0xFFFFFFF0u32;
reg |= val & 0xF;
core::ptr::write_volatile(0x40005C44u32 as *mut u32, reg);
}
}
}
pub mod dir {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C44u32 as *const u32) >> 4) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C44u32 as *const u32);
reg &= 0xFFFFFFEFu32;
reg |= (val & 0x1) << 4;
core::ptr::write_volatile(0x40005C44u32 as *mut u32, reg);
}
}
}
pub mod esof {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C44u32 as *const u32) >> 8) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C44u32 as *const u32);
reg &= 0xFFFFFEFFu32;
reg |= (val & 0x1) << 8;
core::ptr::write_volatile(0x40005C44u32 as *mut u32, reg);
}
}
}
pub mod sof {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C44u32 as *const u32) >> 9) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C44u32 as *const u32);
reg &= 0xFFFFFDFFu32;
reg |= (val & 0x1) << 9;
core::ptr::write_volatile(0x40005C44u32 as *mut u32, reg);
}
}
}
pub mod reset {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C44u32 as *const u32) >> 10) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C44u32 as *const u32);
reg &= 0xFFFFFBFFu32;
reg |= (val & 0x1) << 10;
core::ptr::write_volatile(0x40005C44u32 as *mut u32, reg);
}
}
}
pub mod susp {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C44u32 as *const u32) >> 11) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C44u32 as *const u32);
reg &= 0xFFFFF7FFu32;
reg |= (val & 0x1) << 11;
core::ptr::write_volatile(0x40005C44u32 as *mut u32, reg);
}
}
}
pub mod wkup {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C44u32 as *const u32) >> 12) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C44u32 as *const u32);
reg &= 0xFFFFEFFFu32;
reg |= (val & 0x1) << 12;
core::ptr::write_volatile(0x40005C44u32 as *mut u32, reg);
}
}
}
pub mod err {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C44u32 as *const u32) >> 13) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C44u32 as *const u32);
reg &= 0xFFFFDFFFu32;
reg |= (val & 0x1) << 13;
core::ptr::write_volatile(0x40005C44u32 as *mut u32, reg);
}
}
}
pub mod pmaovr {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C44u32 as *const u32) >> 14) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C44u32 as *const u32);
reg &= 0xFFFFBFFFu32;
reg |= (val & 0x1) << 14;
core::ptr::write_volatile(0x40005C44u32 as *mut u32, reg);
}
}
}
pub mod ctr {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C44u32 as *const u32) >> 15) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C44u32 as *const u32);
reg &= 0xFFFF7FFFu32;
reg |= (val & 0x1) << 15;
core::ptr::write_volatile(0x40005C44u32 as *mut u32, reg);
}
}
}
}
pub mod fnr {
pub mod fn {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40005C48u32 as *const u32) & 0x7FF
}
}
}
pub mod lsof {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C48u32 as *const u32) >> 11) & 0x3
}
}
}
pub mod lck {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C48u32 as *const u32) >> 13) & 0x1
}
}
}
pub mod rxdm {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C48u32 as *const u32) >> 14) & 0x1
}
}
}
pub mod rxdp {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C48u32 as *const u32) >> 15) & 0x1
}
}
}
}
pub mod daddr {
pub mod add {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40005C4Cu32 as *const u32) & 0x7F
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C4Cu32 as *const u32);
reg &= 0xFFFFFF80u32;
reg |= val & 0x7F;
core::ptr::write_volatile(0x40005C4Cu32 as *mut u32, reg);
}
}
}
pub mod ef {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C4Cu32 as *const u32) >> 7) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C4Cu32 as *const u32);
reg &= 0xFFFFFF7Fu32;
reg |= (val & 0x1) << 7;
core::ptr::write_volatile(0x40005C4Cu32 as *mut u32, reg);
}
}
}
}
pub mod btable {
pub mod btable {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40005C50u32 as *const u32) >> 3) & 0x1FFF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40005C50u32 as *const u32);
reg &= 0xFFFF0007u32;
reg |= (val & 0x1FFF) << 3;
core::ptr::write_volatile(0x40005C50u32 as *mut u32, reg);
}
}
}
}
|
// Copyright (c) 2018, ilammy
//
// Licensed under the Apache License, Version 2.0 (see LICENSE in the
// root directory). This file may be copied, distributed, and modified
// only in accordance with the terms specified by the license.
extern crate exonum;
extern crate exonum_legislation as legislation;
#[macro_use]
extern crate exonum_testkit;
#[macro_use]
extern crate serde_json;
use exonum::{api, crypto};
use exonum_testkit::{ApiKind, TestKit, TestKitApi, TestKitBuilder};
use legislation::{
schema::{Act, ActId, Clause}, service::LegalService, transactions::TxCreateAct,
};
#[test]
fn test_create_act() {
let (mut testkit, api) = create_testkit();
// Issue API request
api.create_act(1, "Test Act 1 Please Ignore", vec![])
.expect("successful transaction");
// Process pending transactions
testkit.create_block();
// Make another request and verify that new act is there
let acts = api.get_acts().expect("successful acts");
assert_eq!(acts.len(), 1);
assert_eq!(acts[0].id(), 1);
assert_eq!(acts[0].name(), "Test Act 1 Please Ignore");
assert_eq!(acts[0].clauses().len(), 0);
}
struct LegalApi {
inner: TestKitApi,
}
impl LegalApi {
fn create_act(&self, id: ActId, name: &str, clauses: Vec<Clause>) -> Result<(), api::Error> {
let (_, key) = crypto::gen_keypair();
let tx = TxCreateAct::new(id, name, clauses, &key);
let tx_info: serde_json::Value = self.inner
.public(ApiKind::Service("legislation"))
.query(&tx)
.post("v1/acts")?;
Ok(())
}
fn get_acts(&self) -> Result<Vec<Act>, api::Error> {
self.inner
.public(ApiKind::Service("legislation"))
.get("v1/acts")
}
}
fn create_testkit() -> (TestKit, LegalApi) {
let testkit = TestKitBuilder::validator()
.with_service(LegalService)
.create();
let api = LegalApi {
inner: testkit.api(),
};
(testkit, api)
}
|
pub mod algorithm;
pub mod utils;
pub mod custom_ga; |
use crate::BoxedErrorResult;
use crate::constants;
use crate::filesystem;
use crate::globals;
use crate::heartbeat;
use crate::operation::*;
use std::collections::HashMap;
use std::future::Future;
use std::fs::{self, File, OpenOptions};
use std::io::{self, Write};
use std::net::{Ipv4Addr, UdpSocket};
use std::str::FromStr;
use std::sync::{mpsc};
use std::{thread, time};
// Types
type FrequencyInterval = Option<u64>;
pub type ComponentResult = BoxedErrorResult<()>;
pub type OperationSender = mpsc::Sender<SendableOperation>;
pub type OperationReceiver = mpsc::Receiver<SendableOperation>;
// Component Starters
pub fn start_sender(freq_interval: FrequencyInterval, receiver: OperationReceiver) {
thread::spawn(move || {
start_component(&mut sender, &receiver, freq_interval);
});
}
pub fn start_receiver(freq_interval: FrequencyInterval, sender: OperationSender) {
thread::spawn(move || {
start_component(&mut receiver, &sender, freq_interval);
});
}
pub fn start_maintainer(freq_interval: FrequencyInterval, sender: OperationSender) {
thread::spawn(move || {
start_component(&mut heartbeat::maintainer, &sender, freq_interval);
});
}
pub fn start_file_server(freq_interval: FrequencyInterval, sender: OperationSender) {
thread::spawn(move || {
start_async_component(&mut filesystem::file_server, &sender, freq_interval);
});
}
pub fn start_console(freq_interval: FrequencyInterval, sender: OperationSender) {
thread::spawn(move || {
start_component(&mut console, &sender, freq_interval);
});
}
// Utility Functions
pub async fn startup(udp_port: u16) -> BoxedErrorResult<()> {
startup_log_file(udp_port);
startup_data_dir();
let (udp_addr, tcp_addr) = get_socket_addrs(udp_port, udp_port+3)?;
// TODO: Have a better scheme for TCP port
globals::UDP_SOCKET.write(UdpSocket::bind(&udp_addr)?);
globals::IS_JOINED.write(false);
globals::MEMBERSHIP_LIST.write(Vec::new());
globals::SUCCESSOR_LIST.write(Vec::new());
globals::PREDECESSOR_LIST.write(Vec::new());
globals::PREDECESSOR_TIMESTAMPS.write(HashMap::new());
globals::MY_IP_ADDR.write(udp_addr.to_string());
globals::DEBUG.write(true);
globals::TCP_ADDR.write(tcp_addr.clone());
globals::SERVER_SOCKET.write(async_std::net::TcpListener::bind(tcp_addr).await?);
globals::UDP_TO_TCP_MAP.write(HashMap::new());
globals::ALL_FILE_OWNERS.write(HashMap::new());
Ok(())
}
fn startup_data_dir() -> BoxedErrorResult<()> {
if let Err(_) = fs::create_dir(constants::DATA_DIR) {}
Ok(())
}
fn startup_log_file(port: u16) -> BoxedErrorResult<()> {
if let Err(_) = fs::create_dir(constants::LOG_DIR) {}
let timestamp = heartbeat::get_timestamp()?;
let debug_file = format!("{}/port_{}_{:020}.txt", constants::LOG_DIR, port, timestamp);
globals::LOG_FILE.write(OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(debug_file)?);
Ok(())
}
fn start_component<T, A>(f: &mut dyn Fn(&A) -> BoxedErrorResult<T>, arg: &A, freq_interval: FrequencyInterval) {
let freq = parse_frequency(freq_interval);
loop {
run_component(f, &arg);
thread::sleep(time::Duration::from_millis(freq));
}
}
fn run_component<T, A>(f: &mut dyn Fn(&A) -> BoxedErrorResult<T>, arg: &A) {
let fres = f(arg);
// Separate ifs because the if let still experimental with another expression
if *globals::DEBUG.read() {
if let Err(e) = fres {
// TODO: Add some better error handling
println!("Error: {}", e);
}
}
}
fn start_async_component<'a, F, T, A>(f: &mut dyn Fn(&'a A) -> F, arg: &'a A, freq_interval: FrequencyInterval)
where F: Future<Output = BoxedErrorResult<T>> {
let freq = parse_frequency(freq_interval);
loop {
run_async_component(f, &arg);
thread::sleep(time::Duration::from_millis(freq));
}
// let fres = async_std::task::block_on(f(arg));
}
fn run_async_component<'a, F, T, A>(f: &mut dyn Fn(&'a A) -> F, arg: &'a A)
where F: Future<Output = BoxedErrorResult<T>> {
let fres = async_std::task::block_on(f(arg));
// Separate ifs because the if let still experimental with another expression
if *globals::DEBUG.read() {
if let Err(e) = fres {
// TODO: Add some better error handling
println!("Error: {}", e);
}
}
}
// Components
pub fn sender(receiver: &OperationReceiver) -> ComponentResult {
// Empty the queue by sending all outstanding operations
// Do this before heartbeating so that we can empty after a leave
let udp_socket = globals::UDP_SOCKET.read();
while let Ok(queue_item) = receiver.try_recv() {
queue_item.write_all_udp(&udp_socket)?;
}
// Send heartbeat packets
if is_joined() {
heartbeat::send_heartbeats();
}
Ok(())
}
pub fn receiver(sender: &OperationSender) -> ComponentResult {
let udp_socket = globals::UDP_SOCKET.read();
loop {
if is_joined() {
// let (operation, source) = read_operation(&*udp_socket)?;
let (operation, source) = udp_socket.try_read_operation()?;
let generated_operations = operation.execute(source)?;
for generated_operation in generated_operations {
sender.send(generated_operation)?;
}
} else {
// Drop the packet
udp_socket.recv_from(&mut vec![0])?;
}
}
}
pub fn console(sender: &OperationSender) -> ComponentResult {
let mut input = String::new();
io::stdin().read_line(&mut input)?;
let mut it = input.split_whitespace();
let cmd = it.next().ok_or("No command given")?;
let args: Vec<&str> = it.collect();
match cmd.trim() {
"join" => heartbeat::join(args, sender)?,
"leave" => heartbeat::leave(args, sender)?,
"print" => heartbeat::print(args, )?,
"get" => filesystem::get(args)?,
"put" => filesystem::put(args, sender)?,
"ls" => filesystem::ls(args)?,
"is_master" => println!("{}", heartbeat::is_master()),
_ => println!("Invalid command. (Maybe replace with a help func)")
}
Ok(())
}
// Helper Functions
pub fn is_joined() -> bool {
*globals::IS_JOINED.read()
}
pub fn check_joined() -> BoxedErrorResult<()> {
match is_joined() {
false => Err("Not joined yet".into()),
true => Ok(())
}
}
fn parse_frequency(freq_interval: FrequencyInterval) -> u64 {
match freq_interval {
Some(interval) => interval,
None => 0
}
}
// TODO: Eventually, change this to external IPs
fn get_socket_addrs(udp_port: u16, tcp_port: u16) -> BoxedErrorResult<(String, String)> {
let local_addr = get_local_addr()?;
let udp_addr = format!("{}:{}", local_addr, udp_port);
let tcp_addr = format!("{}:{}", local_addr, tcp_port);
Ok((udp_addr, tcp_addr))
}
fn get_local_addr() -> BoxedErrorResult<String> {
for iface in get_if_addrs::get_if_addrs().unwrap() {
if let get_if_addrs::IfAddr::V4(v4_addr) = iface.addr {
if v4_addr.netmask == Ipv4Addr::from_str("255.255.255.0").unwrap() {
return Ok(v4_addr.ip.to_string());
}
}
}
Err("Could not find valid local IPv4 address".to_string().into())
}
// TODO: Maybe find another place for this - Also: borrow or owned?
pub fn log(msg: String) -> BoxedErrorResult<()> {
writeln!(*globals::LOG_FILE.get_mut(), "{}", msg)?;
Ok(())
}
|
use super::{
create_array, extract_type_from_pointer, AnnotatedFunction, AnnotatedFunctionMap, BasicBlock,
CodegenError, CodegenResult, Compiler, Context, Function, FunctionType, LLVMInstruction,
Object, Scope, Token, Type,
};
use llvm_sys::core::*;
pub fn build_functions(
compiler: &mut Compiler,
functions: &AnnotatedFunctionMap,
) -> CodegenResult<()> {
// TODO: don't clone this. It's a waste
// to reallocate when the full map is available.
let function_map = functions.clone();
for (name, function_by_args) in functions {
for (_, function) in function_by_args {
if cfg!(feature = "debug") {
println!("building function {:?}", &function);
}
let function =
FunctionType::Disp(build_function(&function_map, compiler, name, function)?);
compiler.data.functions.insert(name.to_string(), function);
}
}
Ok(())
}
fn build_function(
function_map: &AnnotatedFunctionMap,
compiler: &mut Compiler,
name: &str,
source_function: &AnnotatedFunction,
) -> CodegenResult<Function> {
if cfg!(feature = "debug") {
println!("building function {}", name);
}
let mut function = Function::new(
name.to_owned(),
source_function.arg_types.clone(),
Some(source_function.return_type.clone()),
);
{
let mut scope = Scope::new(None);
let entry_block = function.create_block("entry".to_owned());
let mut context = Context::new(
function_map,
compiler,
&mut function,
&mut scope,
entry_block,
);
// load arguments into scope
for i in 0..source_function.arg_types.len() {
let param_value = context.allocate_without_type();
context.add_instruction(LLVMInstruction::GetParam {
arg_num: i as u32,
target: param_value,
});
let param = context.allocate(source_function.arg_types[i].clone());
let param_type = context
.compiler
.llvm
.types
.get(&source_function.arg_types[i]);
context.add_instruction(LLVMInstruction::BuildAlloca {
llvm_type: param_type,
target: param.index,
});
context.add_instruction(LLVMInstruction::BuildStore {
source: param_value,
target: param.index,
});
context
.scope
.locals
.insert(source_function.function.args[i].clone(), param.clone());
}
gen_token(&mut context, &source_function.function.body)?;
if !context.current_block().has_been_terminated() {
context.add_instruction(LLVMInstruction::BuildRetVoid {});
}
}
Ok(function)
}
pub fn gen_token(context: &mut Context, token: &Token) -> CodegenResult<Object> {
Ok(match token {
&Token::Boolean(b) => {
let object = context.allocate(Type::Bool);
context.add_instruction(LLVMInstruction::ConstBool {
value: b,
target: object.index,
});
object
}
&Token::Map(ref m) => {
let object = context.allocate(Type::Map(Box::new(Type::String), Box::new(Type::Int)));
context.add_instruction(LLVMInstruction::BuildCall {
name: String::from("create_map"),
args: vec![],
target: object.index,
});
object
}
&Token::None => Object::none(),
&Token::Bytes(ref s) => {
// extract the proper subtypalex chance pove
let global_string_pointer = context.allocate_without_type();
context.add_instruction(LLVMInstruction::BuildGlobalString {
value: *s.clone(),
target: global_string_pointer,
});
create_array(context, &Type::Byte, global_string_pointer, s.len() as i64)?
}
&Token::String(ref s) => {
let object = context.allocate(Type::String);
context.add_instruction(LLVMInstruction::BuildGlobalString {
value: *s.clone(),
target: object.index,
});
object
}
&Token::Symbol(ref s) => {
let value = match context.scope.get_local(&(*s.clone())) {
Some(s) => {
let object = context.allocate(s.object_type.clone());
context.add_instruction(LLVMInstruction::BuildLoad {
source: s.index,
target: object.index,
});
Some(object)
}
None => None,
};
match value {
Some(value) => value,
None => {
return Err(CodegenError::new(&format!("unable to find variable {}", s)));
}
}
}
&Token::Integer(i) => context.const_int(i),
&Token::Block(ref tl) => gen_block(context, tl)?,
&Token::List(ref tl) => gen_list(context, tl)?,
&Token::Expression(ref tl) => gen_expr(context, tl)?,
_ => Object::none(),
})
}
fn gen_block(context: &mut Context, args: &[Token]) -> CodegenResult<Object> {
let mut result = Ok(Object::none());
for t in args {
let result_to_add = gen_token(context, t)?;
result = Ok(result_to_add);
}
result
}
fn gen_list(context: &mut Context, args: &[Token]) -> CodegenResult<Object> {
let list_pointer = context.allocate_without_type();
let mut results = vec![];
for t in args {
results.push(gen_token(context, t)?);
}
unsafe {
let array_type = LLVMArrayType(
context.compiler.llvm.types.get(&results[0].object_type),
results.len() as u32,
);
context.add_instruction(LLVMInstruction::BuildAlloca {
llvm_type: array_type,
target: list_pointer,
});
}
let zero = context.const_int(0);
for i in 0..results.len() {
let field_pointer = context.allocate_without_type();
let index_as_llvm_int = context.const_int(i as i64);
context.add_instruction(LLVMInstruction::BuildGEP {
value: list_pointer,
indices: vec![zero.index, index_as_llvm_int.index],
target: field_pointer,
});
context.add_instruction(LLVMInstruction::BuildStore {
source: results[i].index,
target: field_pointer,
});
}
create_array(
context,
&results[0].object_type,
list_pointer,
args.len() as i64,
)
}
fn gen_expr(context: &mut Context, args: &[Token]) -> CodegenResult<Object> {
if let Some((func_token, args)) = args.split_first() {
match func_token {
&Token::Symbol(ref s) => compile_expr(context, s, args),
&Token::Comment(ref c) => Ok(Object::none()),
_ => Err(CodegenError::new(&format!(
"first token must be a symbol for expression, found {}",
func_token
))),
}
} else {
Err(CodegenError::new(&format!(
"no method found found {:?}",
args
)))
}
}
fn compile_expr<'a, 'b, 'c>(
context: &'a mut Context<'b, 'c>,
func_name: &'a str,
args: &'a [Token],
) -> CodegenResult<Object> {
let codegen_function = {
match context.compiler.data.builtin_expressions.get(func_name) {
Some(expression) => Some((*expression).codegen),
None => None,
}
};
if let Some(codegen) = codegen_function {
return codegen(context, args);
} else if let Some(function_by_arg_count) = context.function_map.get(func_name) {
let (argument_objects, argument_types) = {
let mut argument_objects = Vec::with_capacity(args.len());
let mut argument_types = Vec::with_capacity(args.len());
for arg in args {
let result = gen_token(context, arg)?;
argument_objects.push(result.index);
argument_types.push(result.object_type);
}
(argument_objects, argument_types)
};
if let Some(function) = function_by_arg_count.get(&argument_types) {
let object = context.allocate(function.return_type.clone());
context.add_instruction(LLVMInstruction::BuildCall {
name: func_name.to_owned(),
args: argument_objects,
target: object.index,
});
return Ok(object);
}
}
Ok(Object::none())
// match func_name {
// symbol => match context.scope.get_macro(symbol) {
// None => call_function(context, symbol, args),
// },
// }
}
|
use diesel::r2d2;
use diesel::pg::PgConnection;
use dotenv::dotenv;
use std::env;
use std::thread;
fn main() {
dotenv().ok();
let manager: r2d2::ConnectionManager<PgConnection> = r2d2::ConnectionManager::new(env::var("DATABASE_URL").unwrap());
let pool = r2d2::Pool::builder()
.max_size(15)
.build(manager)
.unwrap();
for _ in 0..20 {
let pool = pool.clone();
thread::spawn(move || {
let _conn = pool.get().unwrap();
// use the connection
// it will be returned to the pool when it falls out of scope.
});
}
}
|
use std::{collections::HashMap, env};
fn main() -> Result<(), std::io::Error> {
let mut abi = HashMap::new();
let contract_abi = <contract::__LIQUID_ABI_GEN as liquid_lang::GenerateAbi>::generate_abi();
let mut local_abi =
Vec::with_capacity(contract_abi.event_abis.len() + contract_abi.fn_abis.len() + 1);
local_abi.extend(
contract_abi
.event_abis
.iter()
.map(|event_abi| liquid_lang::AbiKind::Event(event_abi.clone())),
);
local_abi.push(liquid_lang::AbiKind::Constructor(
contract_abi.constructor_abi,
));
local_abi.extend(
contract_abi
.fn_abis
.iter()
.map(|fn_abi| liquid_lang::AbiKind::ExternalFn(fn_abi.clone())),
);
abi.insert(String::from("$local"), local_abi);
for (iface_name, fn_abis) in contract_abi.iface_abis {
let fn_abis = fn_abis
.iter()
.map(|fn_abi| liquid_lang::AbiKind::ExternalFn(fn_abi.clone()))
.collect::<Vec<liquid_lang::AbiKind>>();
abi.insert(iface_name, fn_abis);
}
let target_dir = env::var("CARGO_TARGET_DIR").unwrap_or("target".into());
std::fs::create_dir(&target_dir).ok();
std::fs::write("hello_world.abi", serde_json::to_string(&abi).unwrap())?;
Ok(())
}
|
fn prime(v: u64) -> bool {
!(2..).take_while(|x| x * x <= v).any(|x| v % x == 0)
}
fn digits_match(mut s: u64, mut b: u64) -> bool {
let sdigits = std::iter::from_fn(move || {
if s == 0 {
None
} else {
let digit = s % 10;
s = s / 10;
Some(digit)
}
});
let bdigits = std::iter::from_fn(move || {
if b == 0 {
None
} else {
let digit = b % 10;
b = b / 10;
Some(digit)
}
});
sdigits.zip(bdigits).all(|(a, b)| a == b)
}
fn get_s(p1: u64, p2: u64) -> u64 {
((1..)
.step_by(2)
.take_while(|m| !digits_match(p1, p2 * m))
.last()
.unwrap()
+ 2)
* p2
}
fn main() {
let extra_prime = (1000000..).filter(|&v| prime(v)).take(1);
let primes: Vec<u64> = (5..1000000)
.filter(|&v| prime(v))
.chain(extra_prime)
.collect();
let skipped_primes = primes.iter().skip(1);
let zipped = primes.iter().zip(skipped_primes);
let sum = zipped.fold(0, |acc, (&p1, &p2)| {
let v = get_s(p1, p2);
acc + v
});
println!("{}", sum);
}
#[test]
fn test_example() {
let p1 = 19;
let p2 = 23;
let s = get_s(p1, p2);
assert_eq!(s, 1219);
}
|
use crate::msg::adc_msg::AdcMsg;
use crate::msg::adc_msg::CtrlParam;
use crate::msg::adc_msg::XGbeIdParam;
use crate::msg::snap2_msg::AppParam;
use crate::msg::snap2_msg::Snap2Msg;
use crate::msg::snap2_msg::XGbePortOp;
use crate::msg::snap2_msg::XGbePortParam;
use crate::net::send_adc_msg;
use crate::net::send_udp_buffer;
use num_complex::Complex;
//use pcap::{Active, Capture};
use pnet::datalink::{DataLinkReceiver, DataLinkSender};
use serde_yaml::Value;
pub const BOARD_NUM: usize = 16;
pub const ADC_PER_BOARD: usize = 4;
macro_rules! fetch_uint_array {
($t: ty, $n: expr, $v:expr) => {{
let mut result = [0; $n];
$v.as_sequence()
.expect("aa")
.iter()
.enumerate()
.for_each(|(i, v)| {
result[i] = v.as_u64().expect("bb") as $t;
});
result
}};
}
#[derive(Clone, Debug)]
pub struct BoardCfg {
pub packet_gap: u16,
pub counter_sync: u8,
pub counter_wait: u16,
pub trig_out_delay: u8,
pub optical_delay: u8,
pub fft_shift: u16,
pub truncation: u32,
pub mac: [[u8; 6]; BOARD_NUM],
pub xgbeid: Vec<XGbeIdParam>,
pub io_delay: [[u8; ADC_PER_BOARD]; BOARD_NUM],
pub master_board_id: usize,
pub snap_mac: [u8; 6],
pub snap_ip: [u8; 4],
pub src_mac: [u8; 6],
pub src_ip: [u8; 4],
pub ctrl_src_port: u16,
pub ctrl_dst_port: u16,
pub snap_xgbe_params: [XGbePortParam; 9],
pub ch_beg: usize,
pub ch_end: usize,
pub snap_app_param: AppParam,
}
impl BoardCfg {
pub fn from_yaml(param: &Value) -> BoardCfg {
let ch_beg = param["ch_beg"].as_u64().expect("ch_beg err") as usize;
let ch_end = param["ch_end"].as_u64().expect("ch_end err") as usize;
assert!(ch_beg % 2 == 0 && ch_beg < ch_end, "CH Asseration failed");
assert!(ch_end % 2 == 0 && ch_end <= 2048, "CH Asseration failed");
let packet_gap = param["packet_gap"]
.as_u64()
.expect("Unable to get packet_gap") as u16;
let counter_wait = param["counter_wait"]
.as_u64()
.expect("Unable to get counter_wait") as u16;
let counter_sync = param["counter_sync"]
.as_u64()
.expect("Unable to get counter_sync") as u8;
let trig_out_delay = param["trig_out_delay"]
.as_u64()
.expect("Unable to get trig_out_delay") as u8;
let optical_delay = param["optical_delay"]
.as_u64()
.expect("Unable to get optical_delay") as u8;
let fft_shift = param["fft_shift"]
.as_u64()
.expect("Unable to get fft_shift") as u16;
let truncation = param["truncation"]
.as_u64()
.expect("Unable to get truncation") as u32;
let master_board_id = param["master_board_id"]
.as_u64()
.expect("cannot read master board id") as usize;
let mut mac = [[0_u8; 6]; BOARD_NUM];
param["mac"]
.as_sequence()
.expect("error, mac cannot be read")
.iter()
.enumerate()
.for_each(|(i, v)| {
v.as_sequence()
.expect("error mac cannot be read")
.iter()
.enumerate()
.for_each(|(j, v)| {
mac[i][j] = v.as_u64().expect("mac not u8") as u8;
})
});
let xgbeid: Vec<XGbeIdParam> = param["xgbeid"]
.as_sequence()
.expect("error, xgbeid cannot be read")
.iter()
.enumerate()
.map(|(i, v)| {
if i % 2 == 0 {
let mut mac1 = [0; 6];
let mut mac2 = [0; 6];
v["mac1"]
.as_sequence()
.expect("mac1 err")
.iter()
.enumerate()
.for_each(|(i, x)| mac1[i] = x.as_u64().expect("mac err") as u8);
v["mac2"]
.as_sequence()
.expect("mac2 err")
.iter()
.enumerate()
.for_each(|(i, x)| mac2[i] = x.as_u64().expect("mac err") as u8);
XGbeIdParam::Upper { mac1, mac2 }
} else {
let mut mac1 = [0; 6];
let mut mac2 = [0; 6];
let mut mac3 = [0; 6];
let mut mac4 = [0; 6];
v["mac1"]
.as_sequence()
.expect("mac1 err")
.iter()
.enumerate()
.for_each(|(i, x)| mac1[i] = x.as_u64().expect("mac err") as u8);
v["mac2"]
.as_sequence()
.expect("mac2 err")
.iter()
.enumerate()
.for_each(|(i, x)| mac2[i] = x.as_u64().expect("mac err") as u8);
v["mac3"]
.as_sequence()
.expect("mac3 err")
.iter()
.enumerate()
.for_each(|(i, x)| mac3[i] = x.as_u64().expect("mac err") as u8);
v["mac4"]
.as_sequence()
.expect("mac4 err")
.iter()
.enumerate()
.for_each(|(i, x)| mac4[i] = x.as_u64().expect("mac err") as u8);
let mut ip1 = [0; 4];
let mut ip2 = [0; 4];
v["ip1"]
.as_sequence()
.expect("ip1 err")
.iter()
.enumerate()
.for_each(|(i, x)| ip1[i] = x.as_u64().expect("ip err") as u8);
v["ip2"]
.as_sequence()
.expect("ip2 err")
.iter()
.enumerate()
.for_each(|(i, x)| ip2[i] = x.as_u64().expect("ip err") as u8);
let port1 = v["port1"].as_u64().expect("port1 err") as u16;
let port2 = v["port2"].as_u64().expect("port2 err") as u16;
XGbeIdParam::Lower {
mac1,
mac2,
mac3,
mac4,
ip1,
ip2,
port1,
port2,
}
}
}).collect();
let mut io_delay = [[0_u8; ADC_PER_BOARD]; BOARD_NUM];
param["io_delay"]
.as_sequence()
.expect("error, iodelay cannot be read")
.iter()
.enumerate()
.for_each(|(i, v)| {
v.as_sequence()
.expect("error iodelay1 cannot be read")
.iter()
.enumerate()
.for_each(|(j, v)| {
io_delay[i][j] = v.as_u64().expect("iodelay not u8") as u8;
})
});
let mut snap_mac = [0_u8; 6];
param["snap2"]["mac"]
.as_sequence()
.expect("missing snap mac")
.iter()
.enumerate()
.for_each(|(i, x)| snap_mac[i] = x.as_u64().expect("snap mac err") as u8);
let mut snap_ip = [0_u8; 4];
param["snap2"]["ip"]
.as_sequence()
.expect("missing snap ip")
.iter()
.enumerate()
.for_each(|(i, x)| snap_ip[i] = x.as_u64().expect("snap ip err") as u8);
let ctrl_src_port = param["snap2"]["ctrl_src_port"]
.as_u64()
.expect("ctrl src port missing") as u16;
let ctrl_dst_port = param["snap2"]["ctrl_dst_port"]
.as_u64()
.expect("ctrl dst port missing") as u16;
let mut snap_xgbe_params = [XGbePortParam::default(); 9];
param["snap2"]["xgbeparam"]
.as_sequence()
.expect("xgbeparam missing")
.iter()
.enumerate()
.for_each(|(i, v)| {
snap_xgbe_params[i] = XGbePortParam {
src_mac: fetch_uint_array!(u8, 6, v["src_mac"]),
src_ip: fetch_uint_array!(u8, 4, v["src_ip"]),
src_port: v["src_port"].as_u64().expect("port missing") as u16,
dst_mac: fetch_uint_array!(u8, 6, v["dst_mac"]),
dst_ip: fetch_uint_array!(u8, 4, v["dst_ip"]),
dst_port: v["dst_port"].as_u64().expect("port missing") as u16,
pkt_len: if i == 0 {
((ch_end - ch_beg) * (2 + 2) + 8) as u32
} else {
2048 * 4 + 8
},
}
});
let mode_sel = param["snap2"]["app_param"]["mode_sel"]
.as_u64()
.expect("mode sel missing") as u32;
let test_mode_streams =
fetch_uint_array!(u64, 8, param["snap2"]["app_param"]["test_mode_streams"]);
let num_of_streams_sel = param["snap2"]["app_param"]["num_of_streams_sel"]
.as_u64()
.expect("num streams sel err") as u32;
let first_ch = ch_beg as u32;
let last_ch = ch_end as u32 - 1;
let mut src_mac = [0_u8; 6];
param["src_mac"]
.as_sequence()
.expect("missing src mac")
.iter()
.enumerate()
.for_each(|(i, x)| src_mac[i] = x.as_u64().expect("snap src err") as u8);
let mut src_ip = [0_u8; 4];
param["src_ip"]
.as_sequence()
.expect("missing src ip")
.iter()
.enumerate()
.for_each(|(i, x)| src_ip[i] = x.as_u64().expect("src_ip err") as u8);
BoardCfg {
packet_gap,
counter_sync,
counter_wait,
trig_out_delay,
optical_delay,
master_board_id,
fft_shift,
truncation,
mac,
xgbeid,
io_delay,
snap_mac,
snap_ip,
src_mac,
src_ip,
ch_beg,
ch_end,
snap_xgbe_params,
ctrl_src_port,
ctrl_dst_port,
snap_app_param: AppParam {
mode_sel,
test_mode_streams,
num_of_streams_sel,
first_ch,
last_ch,
},
}
}
pub fn set_xgbeid(&self, tx: &mut DataLinkSender) {
for i in 0..BOARD_NUM {
println!("Initializing xgbeid of board {}", i);
let msg = AdcMsg::XGbeId(self.xgbeid[i]);
send_adc_msg(tx, &msg, self.mac[i], self.src_mac, 1500).expect("sent error");
}
}
pub fn set_fft_param(&self, tx: &mut DataLinkSender) {
for i in 0..BOARD_NUM {
println!("setting fft params of board {}", i);
let msg = AdcMsg::FftParam {
fft_shift: self.fft_shift,
truncation: self.truncation,
};
send_adc_msg(tx, &msg, self.mac[i], self.src_mac, 1500).expect("sent error");
}
}
pub fn update_phase_factor1(
&self,
tx: &mut DataLinkSender,
bid: usize,
value: Vec<Vec<Complex<i16>>>,
) {
let msg = AdcMsg::PhaseFactor { value };
send_adc_msg(tx, &msg, self.mac[bid], self.src_mac, 1500).expect("sent error");
}
pub fn update_phase_factor(&self, tx: &mut DataLinkSender, value: Vec<Vec<Vec<Complex<i16>>>>) {
//self.set_xgbeid(tx);
//self.set_fft_param(tx);
assert_eq!(value.len(), BOARD_NUM);
for (bid, pf) in value.into_iter().enumerate() {
println!("uploading phase factor to board {}", bid);
self.update_phase_factor1(tx, bid, pf);
}
for bid in 0..BOARD_NUM {
println!("flipping phase factor of board {}", bid);
let msg = AdcMsg::Ctrl(CtrlParam::SwitchPhaseFactor);
send_adc_msg(tx, &msg, self.mac[bid], self.src_mac, 1500).expect("sent error");
}
println!("enabling new phase factor");
//let msg = AdcMsg::MasterTrig;
//send_adc_msg(tx, &msg, self.mac[self.master_board_id], self.src_mac, 1500)
// .expect("sent error");
}
pub fn send_snap_msg(&self, tx: &mut DataLinkSender, msg: Snap2Msg) {
//let msg = Snap2Msg::XGbePortParams(self.snap_xgbe_params.clone()).get_raw_data();
send_udp_buffer(
tx,
&msg.get_raw_data(),
self.snap_mac,
self.src_mac,
self.snap_ip,
self.src_ip,
self.ctrl_dst_port,
self.ctrl_src_port,
).expect("sent error");
}
pub fn set_snap_xgbe_params(&self, tx: &mut DataLinkSender) {
println!("setting snap xgbe params");
self.send_snap_msg(tx, Snap2Msg::XGbePortParams(self.snap_xgbe_params));
}
pub fn set_snap_app_params(&self, tx: &mut DataLinkSender) {
println!("uploading snap app params");
self.send_snap_msg(tx, Snap2Msg::AppParam(self.snap_app_param));
}
pub fn turn_on_snap_xgbe(&self, tx: &mut DataLinkSender) {
println!("turnning on snap xgbe");
self.send_snap_msg(tx, Snap2Msg::XGbePortOp(XGbePortOp::TurnOn));
}
pub fn turn_off_snap_xgbe(&self, tx: &mut DataLinkSender) {
println!("turnning off snap xgbe");
self.send_snap_msg(tx, Snap2Msg::XGbePortOp(XGbePortOp::TurnOff));
}
pub fn reset_all(&self, tx: &mut DataLinkSender) {
for i in 0..BOARD_NUM {
println!("reseting board {}", i);
let msg = AdcMsg::Ctrl(CtrlParam::PreRst);
send_adc_msg(tx, &msg, self.mac[i], self.src_mac, 1500).expect("sent error");
}
println!(
"reseting master board, i.e., board {}",
self.master_board_id
);
send_adc_msg(
tx,
&AdcMsg::MasterRst,
self.mac[self.master_board_id],
self.src_mac,
1500,
).expect("sent error");
}
pub fn set_adc_params(&self, tx: &mut DataLinkSender) {
for i in 0..BOARD_NUM {
println!("setting adc param of board {}", i);
let msg = AdcMsg::Cfg {
io_delay: self.io_delay[i],
packet_gap: self.packet_gap,
counter_sync: self.counter_sync,
counter_wait: self.counter_wait,
trig_out_delay: self.trig_out_delay,
optical_delay: self.optical_delay,
};
send_adc_msg(tx, &msg, self.mac[i], self.src_mac, 1500).expect("sent error");
}
}
pub fn sync_adc(&self, tx: &mut DataLinkSender) {
println!("Syncing...");
for i in 0..BOARD_NUM {
println!("reseting iddr of board {}", i);
let msg = AdcMsg::Ctrl(CtrlParam::IddrRst);
send_adc_msg(tx, &msg, self.mac[i], self.src_mac, 1500).expect("sent error")
}
println!(
"reseting master board, i.e., board {}",
self.master_board_id
);
send_adc_msg(
tx,
&AdcMsg::MasterTrig,
self.mac[self.master_board_id],
self.src_mac,
1500,
).expect("sent error");
for i in 0..BOARD_NUM {
println!("sync board {}", i);
let msg = AdcMsg::Ctrl(CtrlParam::Synchronize);
send_adc_msg(tx, &msg, self.mac[i], self.src_mac, 1500).expect("sent error")
}
println!("sync master board, i.e., board {}", self.master_board_id);
send_adc_msg(
tx,
&AdcMsg::MasterSync,
self.mac[self.master_board_id],
self.src_mac,
1500,
).expect("sent error");
}
pub fn wait_for_trig(&self, tx: &mut DataLinkSender) {
for i in 0..BOARD_NUM {
println!("preparing board {} for trig", i);
let msg = AdcMsg::Ctrl(CtrlParam::StartFft);
send_adc_msg(tx, &msg, self.mac[i], self.src_mac, 1500).expect("sent error")
}
}
pub fn send_internal_trig(&self, tx: &mut DataLinkSender) {
println!(
"asking master board, i.e., board {} to send internal trig sig",
self.master_board_id
);
send_adc_msg(
tx,
&AdcMsg::MasterTrig,
self.mac[self.master_board_id],
self.src_mac,
1500,
).expect("sent error");
}
pub fn store_data(&self, tx: &mut DataLinkSender) {
for i in 0..BOARD_NUM {
//println!("prepare board {} to store data", i);
let msg = AdcMsg::Ctrl(CtrlParam::StoreData);
send_adc_msg(tx, &msg, self.mac[i], self.src_mac, 1500).expect("sent error")
}
println!(
"send trig from master board, i.e., board {}",
self.master_board_id
);
send_adc_msg(
tx,
&AdcMsg::MasterTrig,
self.mac[self.master_board_id],
self.src_mac,
1500,
).expect("sent error");
}
pub fn fetch_fft_data1(
&self,
bid: usize,
tx: &mut DataLinkSender,
rx: &mut DataLinkReceiver,
) -> Option<Vec<Vec<Complex<i32>>>> {
let mut result = vec![vec![Complex::<i32>::new(1, 1); 2048]; 8];
//println!("fetching data from board {}", bid);
send_adc_msg(tx, &AdcMsg::UploadFft, self.mac[bid], self.src_mac, 1500)
.expect("sent error");
let mut cnt = 0;
while let Ok(packet) = rx.next() {
if packet.len() != 1024 + 12 + 2 + 4 + 1 {
//println!("a");
continue;
}
let src_mac = &packet[6..13];
if src_mac
.iter()
.zip(self.mac[bid].iter())
.any(|(&i, &j)| i != j)
{
continue;
}
let data_order = (packet[18] - 1) as usize;
let data = &packet[19..];
let chip_id = (data_order / 16) as usize; //16 packet for one chip
let ch_chunk_id = (data_order - 16 * chip_id) as usize;
//println!("{} {} {} {}", data_order, data.len(), chip_id, ch_chunk_id);
let chunk_len = 2048 / 16;
let mut dst_data = unsafe {
std::slice::from_raw_parts_mut(
result[chip_id][ch_chunk_id * chunk_len..(ch_chunk_id + 1) * chunk_len].as_ptr()
as *mut u8,
1024,
)
};
dst_data.copy_from_slice(data);
cnt += 1;
}
if cnt == 128 {
result
.iter_mut()
.for_each(|s| s.iter_mut().for_each(|d| *d = Complex::new(d.im, d.re)));
Some(result)
} else {
None
}
}
pub fn fetch_fft_data(
&self,
tx: &mut DataLinkSender,
rx: &mut DataLinkReceiver,
) -> Option<Vec<Vec<Complex<i32>>>> {
let board_ids: Vec<usize> = (0..BOARD_NUM).collect();
let mut result = vec![Vec::<Complex<i32>>::new(); board_ids.len() * 8];
for (i, bid) in board_ids.into_iter().enumerate() {
if let Some(x) = self.fetch_fft_data1(bid, tx, rx) {
for (d, s) in result[i * 8..(i + 1) * 8].iter_mut().zip(x.into_iter()) {
*d = s;
}
} else {
println!("Error: no data fetched from board {}", bid);
return None;
}
}
Some(result)
}
}
|
// Copyright 2019 Steven Bosnick
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE-2.0 or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms
// Implements #TST-elfpreload.elflint
use elf_preload::{Input, LayoutStrategy};
use std::fs;
use std::path::Path;
use std::process::Command;
use tempfile;
static SMOKETEST_ELF: &'static [u8] = include_bytes!("../test_data/smoketest");
static KERNEL_ELF: &'static [u8] = include_bytes!("../test_data/kernel.elf");
#[test]
fn elf_preload_for_specfied_start_passes_lint() {
elf_lint_test(SMOKETEST_ELF, LayoutStrategy::SpecifiedStart(5000));
}
#[test]
fn elf_preload_for_from_input_passes_lint() {
elf_lint_test(KERNEL_ELF, LayoutStrategy::FromInput);
}
fn elf_lint_test(input: &[u8], strategy: LayoutStrategy) {
let out_dir = tempfile::tempdir().expect("Couldn't create temp dir.");
let out_file = out_dir.path().join("output.elf");
let output = run_preload(input, strategy);
fs::write(&out_file, output).expect("Unable to write output file");
run_elflint(&out_file);
}
fn run_preload(input: &[u8], strategy: LayoutStrategy) -> Vec<u8> {
let input = Input::new(input).expect("Unable to read input file");
let layout = input
.layout(strategy)
.expect("Unable to layout output file");
let mut output = vec![0xd0; layout.required_size()];
let mut writer = layout.output(&mut output).expect("Unable to create writer");
writer.write().expect("Unable to write output file");
output
}
fn run_elflint(filename: &Path) {
let status = Command::new("eu-elflint")
.arg("--strict")
.arg("--quiet")
.arg(filename)
.status()
.expect("Unable to run eu-elflint");
assert!(status.success(), "eu-elflint did not exit sucessfully");
}
|
use crate::utils::get_fl_name;
use proc_macro::TokenStream;
use quote::*;
use syn::*;
pub fn impl_menu_trait(ast: &DeriveInput) -> TokenStream {
let name = &ast.ident;
let name_str = get_fl_name(name.to_string());
let ptr_name = Ident::new(name_str.as_str(), name.span());
let add = Ident::new(format!("{}_{}", name_str, "add").as_str(), name.span());
let insert = Ident::new(format!("{}_{}", name_str, "insert").as_str(), name.span());
let remove = Ident::new(format!("{}_{}", name_str, "remove").as_str(), name.span());
let get_item = Ident::new(format!("{}_{}", name_str, "get_item").as_str(), name.span());
let set_item = Ident::new(format!("{}_{}", name_str, "set_item").as_str(), name.span());
let find_index = Ident::new(
format!("{}_{}", name_str, "find_index").as_str(),
name.span(),
);
let text_font = Ident::new(
format!("{}_{}", name_str, "text_font").as_str(),
name.span(),
);
let set_text_font = Ident::new(
format!("{}_{}", name_str, "set_text_font").as_str(),
name.span(),
);
let text_color = Ident::new(
format!("{}_{}", name_str, "text_color").as_str(),
name.span(),
);
let set_text_color = Ident::new(
format!("{}_{}", name_str, "set_text_color").as_str(),
name.span(),
);
let text_size = Ident::new(
format!("{}_{}", name_str, "text_size").as_str(),
name.span(),
);
let set_text_size = Ident::new(
format!("{}_{}", name_str, "set_text_size").as_str(),
name.span(),
);
let add_choice = Ident::new(
format!("{}_{}", name_str, "add_choice").as_str(),
name.span(),
);
let get_choice = Ident::new(
format!("{}_{}", name_str, "get_choice").as_str(),
name.span(),
);
let value = Ident::new(format!("{}_{}", name_str, "value").as_str(), name.span());
let set_value = Ident::new(
format!("{}_{}", name_str, "set_value").as_str(),
name.span(),
);
let clear = Ident::new(format!("{}_{}", name_str, "clear").as_str(), name.span());
let clear_submenu = Ident::new(
format!("{}_{}", name_str, "clear_submenu").as_str(),
name.span(),
);
let size = Ident::new(format!("{}_{}", name_str, "size").as_str(), name.span());
let text = Ident::new(format!("{}_{}", name_str, "text").as_str(), name.span());
let at = Ident::new(format!("{}_{}", name_str, "at").as_str(), name.span());
let mode = Ident::new(format!("{}_{}", name_str, "mode").as_str(), name.span());
let set_mode = Ident::new(format!("{}_{}", name_str, "set_mode").as_str(), name.span());
let down_box = Ident::new(format!("{}_{}", name_str, "down_box").as_str(), name.span());
let set_down_box = Ident::new(
format!("{}_{}", name_str, "set_down_box").as_str(),
name.span(),
);
let global = Ident::new(format!("{}_{}", name_str, "global").as_str(), name.span());
let gen = quote! {
impl IntoIterator for #name {
type Item = MenuItem;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
let mut v: Vec<MenuItem> = vec![];
for i in 0..self.size() {
v.push(self.at(i).unwrap());
}
v.into_iter()
}
}
unsafe impl MenuExt for #name {
fn add<F: FnMut(&mut Self) + 'static>(&mut self, name: &str, shortcut: Shortcut, flag: MenuFlag, mut cb: F) {
assert!(!self.was_deleted());
let temp = CString::safe_new(name);
unsafe {
unsafe extern "C" fn shim(wid: *mut Fl_Widget, data: *mut raw::c_void) {
let mut wid = crate::widget::Widget::from_widget_ptr(wid as *mut _);
let a: *mut Box<dyn FnMut(&mut crate::widget::Widget)> = data as *mut Box<dyn FnMut(&mut crate::widget::Widget)>;
let f: &mut (dyn FnMut(&mut crate::widget::Widget)) = &mut **a;
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(&mut wid)));
}
let a: *mut Box<dyn FnMut(&mut Self)> = Box::into_raw(Box::new(Box::new(cb)));
let data: *mut raw::c_void = a as *mut raw::c_void;
let callback: Fl_Callback = Some(shim);
#add(self.inner, temp.as_ptr(), shortcut.bits() as i32, callback, data, flag as i32);
}
}
fn insert<F: FnMut(&mut Self) + 'static>(&mut self, idx: i32, name: &str, shortcut: Shortcut, flag: MenuFlag, mut cb: F) {
assert!(!self.was_deleted());
let temp = CString::safe_new(name);
unsafe {
unsafe extern "C" fn shim(wid: *mut Fl_Widget, data: *mut raw::c_void) {
let mut wid = crate::widget::Widget::from_widget_ptr(wid as *mut _);
let a: *mut Box<dyn FnMut(&mut crate::widget::Widget)> = data as *mut Box<dyn FnMut(&mut crate::widget::Widget)>;
let f: &mut (dyn FnMut(&mut crate::widget::Widget)) = &mut **a;
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(&mut wid)));
}
let a: *mut Box<dyn FnMut(&mut Self)> = Box::into_raw(Box::new(Box::new(cb)));
let data: *mut raw::c_void = a as *mut raw::c_void;
let callback: Fl_Callback = Some(shim);
#insert(self.inner, idx as i32, temp.as_ptr(), shortcut.bits() as i32, callback, data, flag as i32);
}
}
fn add_emit<T: 'static + Clone + Send + Sync>(
&mut self,
label: &str,
shortcut: Shortcut,
flag: crate::menu::MenuFlag,
sender: crate::app::Sender<T>,
msg: T,
) {
self.add(label, shortcut, flag, move|_| sender.send(msg.clone()))
}
fn insert_emit<T: 'static + Clone + Send + Sync>(
&mut self,
idx: i32,
label: &str,
shortcut: Shortcut,
flag: crate::menu::MenuFlag,
sender: crate::app::Sender<T>,
msg: T,
) {
self.insert(idx, label, shortcut, flag, move|_| sender.send(msg.clone()))
}
fn remove(&mut self, idx: i32) {
assert!(!self.was_deleted());
let idx = if idx < self.size() { idx } else { self.size() - 1 };
unsafe {
#remove(self.inner, idx as i32)
}
}
fn find_item(&self, name: &str) -> Option<MenuItem> {
assert!(!self.was_deleted());
let name = CString::safe_new(name);
unsafe {
let menu_item = #get_item(
self.inner,
name.as_ptr());
if menu_item.is_null() {
None
} else {
Some(MenuItem {
inner: menu_item,
})
}
}
}
fn set_item(&mut self, item: &MenuItem) -> bool {
unsafe {
assert!(!self.was_deleted());
#set_item(
self.inner,
item.inner) != 0
}
}
fn find_index(&self, label: &str) -> i32 {
assert!(!self.was_deleted());
let label = CString::safe_new(label);
unsafe {
#find_index(self.inner, label.as_ptr()) as i32
}
}
fn text_font(&self) -> Font {
unsafe {
assert!(!self.was_deleted());
mem::transmute(#text_font(self.inner))
}
}
fn set_text_font(&mut self, c: Font) {
unsafe {
assert!(!self.was_deleted());
#set_text_font(self.inner, c.bits() as i32)
}
}
fn text_size(&self) -> i32 {
unsafe {
assert!(!self.was_deleted());
#text_size(self.inner) as i32
}
}
fn set_text_size(&mut self, c: i32) {
unsafe {
assert!(!self.was_deleted());
#set_text_size(self.inner, c as i32)
}
}
fn text_color(&self) -> Color {
unsafe {
assert!(!self.was_deleted());
mem::transmute(#text_color(self.inner))
}
}
fn set_text_color(&mut self, c: Color) {
unsafe {
assert!(!self.was_deleted());
#set_text_color(self.inner, c.bits() as u32)
}
}
fn add_choice(&mut self, text: &str) {
unsafe {
assert!(!self.was_deleted());
let arg2 = CString::safe_new(text);
#add_choice(self.inner, arg2.as_ptr() as *mut raw::c_char)
}
}
fn choice(&self) -> Option<String> {
unsafe {
assert!(!self.was_deleted());
let choice_ptr = #get_choice(self.inner);
if choice_ptr.is_null() {
None
} else {
Some(CStr::from_ptr(choice_ptr as *mut raw::c_char).to_string_lossy().to_string())
}
}
}
fn value(&self) -> i32 {
unsafe {
assert!(!self.was_deleted());
#value(self.inner)
}
}
fn set_value(&mut self,v:i32) -> bool {
unsafe {
assert!(!self.was_deleted());
#set_value(self.inner,v) != 0
}
}
fn clear(&mut self) {
unsafe {
assert!(!self.was_deleted());
#clear(self.inner);
}
}
unsafe fn unsafe_clear(&mut self) {
assert!(!self.was_deleted());
let sz = self.size();
if sz > 0 {
for i in 0..sz {
// Shouldn't fail
let mut c = self.at(i).unwrap();
let _ = c.user_data();
}
}
#clear(self.inner);
}
fn clear_submenu(&mut self, idx: i32) -> Result<(), FltkError> {
unsafe {
assert!(!self.was_deleted());
match #clear_submenu(self.inner, idx as i32) {
0 => Ok(()),
_ => Err(FltkError::Internal(FltkErrorKind::FailedOperation)),
}
}
}
unsafe fn unsafe_clear_submenu(&mut self, idx: i32) -> Result<(), FltkError> {
assert!(!self.was_deleted());
let x = self.at(idx);
if x.is_none() {
return Err(FltkError::Internal(FltkErrorKind::FailedOperation));
}
// Shouldn't fail
let x = x.unwrap();
if !x.is_submenu() {
return Err(FltkError::Internal(FltkErrorKind::FailedOperation));
}
let mut i = idx;
loop {
// Shouldn't fail
let mut item = self.at(i).unwrap();
if item.label().is_none() {
break;
}
let _ = item.user_data();
i += 1;
}
match #clear_submenu(self.inner, idx as i32) {
0 => Ok(()),
_ => Err(FltkError::Internal(FltkErrorKind::FailedOperation)),
}
}
fn size(&self) -> i32 {
assert!(!self.was_deleted());
unsafe {
#size(self.inner) as i32
}
}
fn text(&self, idx: i32) -> Option<String> {
assert!(!self.was_deleted());
unsafe {
let text = #text(self.inner, idx as i32);
if text.is_null() {
None
} else {
Some(CStr::from_ptr(text as *mut raw::c_char).to_string_lossy().to_string())
}
}
}
fn at(&self, idx: i32) -> Option<crate::menu::MenuItem> {
assert!(!self.was_deleted());
if idx >= self.size() || idx < 0 {
return None;
}
unsafe {
let ptr = #at(self.inner, idx as i32) as *mut Fl_Menu_Item;
if ptr.is_null() {
None
} else {
Some(MenuItem {
inner: ptr,
})
}
}
}
fn mode(&self, idx: i32) -> crate::menu::MenuFlag {
assert!(!self.was_deleted());
unsafe {
mem::transmute(#mode(self.inner, idx as i32))
}
}
fn set_mode(&mut self, idx: i32, flag: crate::menu::MenuFlag) {
assert!(!self.was_deleted());
unsafe {
#set_mode(self.inner, idx as i32, flag as i32)
}
}
fn end(&mut self) {
//
}
fn set_down_frame(&mut self, f: FrameType) {
assert!(!self.was_deleted());
unsafe {
#set_down_box(self.inner, f as i32)
}
}
fn down_frame(&self) -> FrameType {
assert!(!self.was_deleted());
unsafe {
mem::transmute(#down_box(self.inner))
}
}
fn global(&mut self) {
assert!(!self.was_deleted());
unsafe {
#global(self.inner)
}
}
}
};
gen.into()
}
|
use crate::utils::file2vec;
pub fn day12(filename: &String){
let contents = file2vec::<String>(filename);
let contents:Vec<String> = contents.iter().map(|x| x.to_owned().unwrap()).collect();
let mut pos = Position::start();
for act in &contents {
let action = Action::from_str(&act);
pos.take_action(&action);
}
let dist = pos.manhattan();
println!("part 1 ans: {}", dist);
pos = Position::start();
for act in &contents {
let action = Action::from_str(&act);
pos.take_action_with_waypoint(&action);
}
let dist = pos.manhattan();
println!("part 2 ans: {}", dist);
}
#[derive(Debug, Copy, Clone)]
struct Position {
n: i32,
e: i32,
s: i32,
w: i32,
direction: char,
waypoint: WayPoint
}
#[derive(Debug,Copy, Clone)]
struct WayPoint {
n: i32,
e: i32
}
#[derive(Debug, Copy, Clone)]
struct Action {
act: char,
val: i32
}
impl Action {
fn from_str(s:&str)-> Action{
let act = s.chars().next().unwrap();
let val = s[1..].to_string().parse::<i32>().unwrap();
Action { act, val }
}
}
impl Position {
fn start()->Position{
Position { n: 0, e: 0, s: 0, w: 0, direction: 'E', waypoint: WayPoint{ n:1, e: 10} }
}
fn take_action(&mut self, action: &Action){
match action.act {
'N' => {self.n += action.val;},
'S' => {self.s += action.val;},
'E' => {self.e += action.val;},
'W' => {self.w += action.val;},
'L' => {
let turns = (action.val / 90) % 4;
let directions = ['N','W','S','E'];
if let Some(idx) = directions.iter().
position(|ch| ch == &self.direction) {
self.direction = directions[(idx + turns as usize) % 4];
};
},
'R' => {
let turns = (action.val / 90) % 4;
let directions = ['N','E','S','W'];
if let Some(idx) = directions.iter().
position(|ch| ch == &self.direction) {
self.direction = directions[(idx + turns as usize) % 4];
};
},
'F' => {
let act = Action{act:self.direction, val: action.val};
self.take_action(&act);
},
_ => ()
}
}
fn take_action_with_waypoint(&mut self, action: &Action){
match action.act {
'N' => {self.waypoint.n += action.val;},
'S' => {self.waypoint.n -= action.val;},
'E' => {self.waypoint.e += action.val;},
'W' => {self.waypoint.e -= action.val;},
'L' => {
let turns = (action.val / 90) % 4;
for _ in 0..turns {
let tmp_n = self.waypoint.e;
self.waypoint.e = -self.waypoint.n;
self.waypoint.n = tmp_n;
};
},
'R' => {
let turns = (action.val / 90) % 4;
for _ in 0..turns {
let tmp_n = -self.waypoint.e;
self.waypoint.e = self.waypoint.n;
self.waypoint.n = tmp_n;
};
},
'F' => {
let n = self.waypoint.n * action.val;
let w = self.waypoint.e * action.val;
if n < 0 {self.s -= n} else {self.n += n};
if w < 0 {self.w -= w} else {self.e += w};
},
_ => ()
}
}
fn manhattan(&self)-> i32 {
(self.n - self.s).abs() + (self.e - self.w).abs()
}
}
|
use super::super::context::{Args, Context, ParentOrRoot, RootContext};
use super::super::error::{CrawlErrorKind, CrawlResult};
use super::super::utils::station_fn_ctx2;
use super::super::utils::{WorkArcWrapper, WorkBoxWrapper};
use super::super::work::{Work, WorkBox, WorkOutput, Worker};
use super::flow_description::*;
use super::utils::compile_steps;
use super::work_description::*;
use conveyor::{into_box, Chain};
use conveyor_work::package::Package;
use serde_json::Value;
use slog::{FnValue, Logger};
use std::sync::Arc;
use std::time::Instant;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TargetDescription {
pub name: String,
pub work: WorkTargetDescription,
pub flows: Vec<FlowDescription>,
}
// pub async fn run_target(
// logger: &Logger,
// target: TargetDescription,
// args: Args,
// ) -> CrawlResult<Vec<CrawlResult<Package>>> {
// let ctx = RootContext::new(logger, target, args);
// let c = ctx.clone();
// await!(c.target().work.run(ctx))
// }
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct WorkTargetDescription {
pub input: Value,
pub steps: Vec<WorkDescription>,
}
impl WorkTargetDescription {
pub async fn run(&self, mut parent: RootContext) -> CrawlResult<Vec<CrawlResult<Package>>> {
let mut ctx = Context::new(ParentOrRoot::Root(parent), None, None);
let work = self.build(&mut ctx)?;
let worker = Worker::new();
let ret = await!(worker.run(vec![work]));
Ok(ret)
}
pub fn build(&self, ctx: &mut Context) -> CrawlResult<Work<Package>> {
if self.steps.is_empty() {
return Err(CrawlErrorKind::NotFound("no steps defined".to_string()).into());
}
// let start = Instant::now();
// let name = &ctx.root().target().description().name.to_string();
// let mut ctx = ctx.child(
// &format!("Target({})", &name),
// Some(args! {
// "targetName" => name
// }),
// );
// info!(ctx.log(),"building target"; "steps" => self.steps.len());
// let mut work = self.steps[0].request_station(&mut ctx)?;
// if self.steps.len() > 1 {
// for w in self.steps.iter().skip(1) {
// let next = w.request_station(&mut ctx)?;
// work = into_box(WorkBoxWrapper::new(work).pipe(station_fn_ctx2(
// async move |pack: Vec<WorkOutput<Package>>, ctx: Arc<WorkBox<Package>>| {
// let work = Worker::new();
// let ret = await!(work.run_chain(pack, ctx.clone()));
// Ok(ret.into_iter().map(|m| WorkOutput::Result(m)).collect())
// },
// Arc::new(next),
// )));
// }
// }
// info!(ctx.log(), "built target"; "time" => FnValue(move |_| format!("{:?}",start.elapsed())));
let input = if self.input.is_string() {
Value::String(ctx.interpolate(self.input.as_str().unwrap()).unwrap())
} else {
self.input.clone()
};
let name = &ctx.root().target().description().name.to_string();
let mut ctx = ctx.child(
&format!("Target({})", &name),
Some(args! {
"targetName" => name
}),
);
let work = compile_steps(&self.steps, &mut ctx)?;
Ok(Work::new(
Package::new(&name, input),
WorkBoxWrapper::new(work),
// station_fn_ctx2(
// async move |pack: Package, ctx: Arc<(Context, WorkBox<Package>)>| {
// info!(ctx.0.log(), "target started");
// let now = Instant::now();
// let ret = await!(ctx.1.execute(pack));
// info!(ctx.0.log(), "target executed"; "time" => FnValue(move |_| format!("{:?}",now.elapsed())));
// ret
// },
// Arc::new((ctx.clone(), work)),
// ),
))
}
}
#[cfg(test)]
mod tests {
use super::super::super::prelude::*;
use super::super::super::utils::WorkBoxWrapper;
use super::super::super::work;
use super::*;
use conveyor::{into_box, station_fn, Station};
use conveyor_work::http::Method;
use conveyor_work::prelude::*;
use serde_json::Value;
use slog::*;
use tokio;
#[test]
fn test_target() {
// tokio::run_async(
// async {
// let logger = Logger::root(Discard.fuse(), o!());
// let desc = TargetDescription {
// name: "Loppen".to_string(),
// work: WorkTargetDescription {
// input: Value::String("https://loppen.dk".to_string()),
// steps: vec![WorkDescription {
// name: Some("description".to_string()),
// work: Box::new(worktypes::PassThrough {
// service: Some(Arc::new(into_box(station_fn(
// async move |package: Package| {
// Ok(vec![work::WorkOutput::Result(Ok(package))])
// },
// )))),
// }),
// then: None,
// }],
// },
// flows: vec![],
// };
// let out = await!(run_target(&logger, desc, Args::new())).unwrap();
// for o in out {
// println!("O {}", o.unwrap().name())
// }
// },
// );
}
}
|
#![warn(clippy::all)]
use std::io;
use std::io::Read;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::SocketAddr;
use tit::print_tcp_key;
use tit::start_nic;
use tit::Tcp;
use tit::TcpListener;
use tit::TitError;
const LISTEN_ON_IP: Ipv4Addr = Ipv4Addr::UNSPECIFIED;
// const LISTEN_ON_IP: Ipv4Addr = Ipv4Addr::new(10, 0, 0, 10);
const LISTEN_ON_PORT: u16 = 4433;
fn main() -> Result<(), TitError> {
// TODO: take CLI params to control active/passive open (similar to netcat)
print_tcp_key();
eprintln!();
let (tcp_impl, incoming_tcp_packets) = Tcp::new();
let outgoing_tcp_packets = start_nic(incoming_tcp_packets)?;
let send_cmd = tcp_impl.start(outgoing_tcp_packets);
{
let listening_socket = SocketAddr::new(IpAddr::from(LISTEN_ON_IP), LISTEN_ON_PORT);
let listener = TcpListener::bind(listening_socket, &send_cmd)?;
let (mut stream, _remote_socket) = listener.accept()?;
let mut read_buf = [0; 512];
let len = stream.read(&mut read_buf)?;
{
let stderr = io::stderr();
let _lock = stderr.lock();
eprintln!(
"Data: {:#?}",
std::str::from_utf8(&read_buf[..len])
.expect("non UTF-8 string in data")
);
eprintln!();
}
}
std::thread::sleep(std::time::Duration::from_secs(1000));
Ok(())
}
|
pub mod chip8;
#[cfg(target_arch = "wasm32")]
pub mod wasm_bindings;
|
pub fn longest_common_prefix(strs: Vec<&str>) -> String {
// for w in strs.windows(2) {
// w[0];
// w[1];
// }
strs.iter().skip(1).fold(strs[0].to_string(), |acc, el| {
acc.chars()
.zip(el.chars())
.take_while(|(a, b)| a == b)
.map(|(a, _)| a)
.collect()
})
}
fn main() {
assert_eq!(
"fl",
longest_common_prefix(vec!["flower", "flow", "flight"])
);
}
|
use nalgebra::{DMatrix, Dynamic, MatrixXx1, U1};
use rand::prelude::*;
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::path::Path;
struct MnistDataset {
records: Vec<MnistRecord>,
}
struct MnistRecord {
target: usize,
targets: Vec<f32>,
inputs: Vec<f32>,
}
fn load_mnist_data<P: AsRef<Path>>(path: P) -> Result<MnistDataset, String> {
println!("Loading data from {}...", path.as_ref().display());
let test_file = BufReader::new(File::open(path.as_ref()).map_err(|e| e.to_string())?);
let mut csv_reader = csv::Reader::from_reader(test_file);
let mut records = Vec::new();
for result in csv_reader.records() {
let record = result.map_err(|e| e.to_string())?;
let inputs: Vec<f32> = (0..784)
.into_iter()
.map(|i| record[i + 1].parse::<f32>().unwrap() / 255.0)
.collect();
let target = record[0].parse::<usize>().map_err(|e| e.to_string())?;
let mut targets = vec![0.; 10];
targets[target] = 1.;
records.push(MnistRecord {
target,
targets,
inputs,
});
}
Ok(MnistDataset { records })
}
#[derive(Debug, Serialize, Deserialize)]
struct Network {
input_size: usize,
hidden_size: usize,
output_size: usize,
hidden_weights: DMatrix<f32>,
output_weights: DMatrix<f32>,
learning_rate: f32,
}
impl Network {
fn new(input_size: usize, hidden_size: usize, output_size: usize, learning_rate: f32) -> Self {
let mut rng = thread_rng();
Self {
input_size,
hidden_size,
output_size,
learning_rate,
hidden_weights: DMatrix::from_distribution(
hidden_size,
input_size,
&rand::distributions::Uniform::new(
-1. / (input_size as f32).sqrt(),
1. / (input_size as f32).sqrt(),
),
&mut rng,
),
output_weights: DMatrix::from_distribution(
output_size,
hidden_size,
&rand::distributions::Uniform::new(
-1. / (hidden_size as f32).sqrt(),
1. / (hidden_size as f32).sqrt(),
),
&mut rng,
),
}
}
fn predict(&self, input_data: &[f32]) -> Result<MatrixXx1<f32>, String> {
if input_data.len() != self.input_size {
return Err(String::from("input_data length != inputs"));
}
let inputs = MatrixXx1::from_column_slice(input_data);
let sigmoid = |x: f32| 1. / (1. + (-1. * x).exp());
let mut hidden_outputs = &self.hidden_weights * inputs;
hidden_outputs.apply(sigmoid);
let mut final_outputs = &self.output_weights * hidden_outputs;
final_outputs.apply(sigmoid);
Ok(final_outputs.reshape_generic(Dynamic::new(self.output_size), U1))
}
fn train(&mut self, input_data: &[f32], target_data: &[f32]) -> Result<(), String> {
if input_data.len() != self.input_size {
return Err(String::from("input_data length != inputs"));
}
if target_data.len() != self.output_size {
return Err(String::from("targer_data length != outputs"));
}
let sigmoid = |x: f32| 1. / (1. + (-1. * x).exp());
let sigmoid_dx = |x: f32| x * (1. - x);
// Forward propagation
let inputs = MatrixXx1::from_column_slice(input_data);
let mut hidden_outputs = &self.hidden_weights * &inputs;
hidden_outputs.apply(sigmoid);
let mut final_outputs = &self.output_weights * &hidden_outputs;
final_outputs.apply(sigmoid);
// Errors
let targets = MatrixXx1::from_column_slice(target_data);
let output_errors = targets - &final_outputs;
let hidden_errors = &self.output_weights.transpose() * &output_errors;
// Backpropagation
self.output_weights = &self.output_weights
+ (output_errors.component_mul(&final_outputs.map(sigmoid_dx))
* &hidden_outputs.transpose())
.scale(self.learning_rate);
self.hidden_weights = &self.hidden_weights
+ (hidden_errors.component_mul(&hidden_outputs.map(sigmoid_dx)) * inputs.transpose())
.scale(self.learning_rate);
Ok(())
}
fn mnist_train(&mut self, epochs: usize) -> Result<(), String> {
let dataset = load_mnist_data("data/mnist_train.csv")?.records;
let start = std::time::Instant::now();
for epoch in 0..epochs {
println!("Epoch {}/{}...", epoch + 1, epochs);
for (
i,
MnistRecord {
targets, inputs, ..
},
) in dataset.iter().enumerate()
{
self.train(&*inputs, &*targets)?;
if i % (dataset.len() / 10) == 0 {
println!("{}%", i * 100 / dataset.len());
}
}
}
let elapsed = start.elapsed();
println!(
"Time taken to train: {}m {}s",
elapsed.as_secs() / 60,
(elapsed.as_millis() as f32 / 1000.) % 60.,
);
Ok(())
}
fn mnist_predict(&self) -> Result<(), String> {
let dataset = load_mnist_data("data/mnist_test.csv")?.records;
let start = std::time::Instant::now();
let mut correct = 0;
for MnistRecord { target, inputs, .. } in dataset.iter() {
let (best, _best_val) = self.predict(inputs)?.argmax();
if *target == best {
correct += 1;
}
}
let elapsed = start.elapsed();
println!(
"Time taken to predict: {}m {}s",
elapsed.as_secs() / 60,
(elapsed.as_millis() as f32 / 1000.) % 60.,
);
println!(
"Accuracy: {}% ({}/{})",
(correct as f32 / dataset.len() as f32) * 100.,
correct,
dataset.len()
);
Ok(())
}
fn save_file<P: AsRef<Path>>(&self, path: P) -> Result<(), String> {
println!("Saving to file...");
let network_file = BufWriter::new(File::create(path.as_ref()).map_err(|e| e.to_string())?);
serde_json::to_writer_pretty(network_file, &self).unwrap();
Ok(())
}
fn load_file<P: AsRef<Path>>(path: P) -> Result<Self, String> {
println!("Loading from file...");
let network_file = BufReader::new(File::open(path.as_ref()).map_err(|e| e.to_string())?);
let net: Self = serde_json::from_reader(network_file).map_err(|e| e.to_string())?;
println!("Loaded {}-{}-{}", net.input_size, net.hidden_size, net.output_size);
Ok(net)
}
}
fn main() -> Result<(), String> {
let mut n = Network::new(784, 200, 10, 0.05);
n.mnist_train(5)?;
n.save_file("data/network.model")?;
let model = Network::load_file("data/network.model")?;
model.mnist_predict()?;
Ok(())
}
|
//! Data shared between the state::server module files, but hidden to users of the module.
use std::sync::{ Arc, Mutex };
use std::sync::mpsc::{ Receiver, Sender };
use protocol;
/// Shorthand for the type of the UserList (a reference-counted mutex around some list.)
pub type UserList = Arc<Mutex<Vec<String>>>;
/// The transmission end of the channel on which client threads talk to the server thread.
pub type SayTx = Sender<protocol::Message>;
/// The receiving end of the channel on which client threads talk to the server thread.
pub type SayRx = Receiver<protocol::Message>;
/// The transmission end of a channel on which the server thread talks to a client thread.
pub type HearTx = Sender<protocol::Message>;
/// The receiving end of a channel on which the server thread talks to a client thread.
pub type HearRx = Receiver<protocol::Message>;
|
#[cfg(test)]
#[path = "../../../tests/unit/algorithms/gsom/network_test.rs"]
mod network_test;
use super::*;
use crate::utils::parallel_into_collect;
use hashbrown::HashMap;
use rand::prelude::SliceRandom;
use std::cmp::Ordering;
use std::ops::Deref;
use std::sync::{Arc, RwLock};
/// A customized Growing Self Organizing Map designed to store and retrieve trained input.
pub struct Network<I: Input, S: Storage<Item = I>> {
/// Data dimension.
dimension: usize,
/// Growth threshold.
growing_threshold: f64,
/// The factor of distribution (FD), used in error distribution stage, 0 < FD < 1
distribution_factor: f64,
/// Initial learning rate.
learning_rate: f64,
/// All nodes in the network.
nodes: HashMap<Coordinate, NodeLink<I, S>>,
/// Creates input storage for new nodes.
storage_factory: Box<dyn Fn() -> S + Send + Sync>,
/// A current time which is used to track node update statistics.
time: usize,
/// A rebalance memory.
rebalance_memory: usize,
}
/// GSOM network configuration.
pub struct NetworkConfig {
/// A spread factor.
pub spread_factor: f64,
/// The factor of distribution (FD), used in error distribution stage, 0 < FD < 1
pub distribution_factor: f64,
/// Initial learning rate.
pub learning_rate: f64,
/// A rebalance memory.
pub rebalance_memory: usize,
}
impl<I: Input, S: Storage<Item = I>> Network<I, S> {
/// Creates a new instance of `Network`.
pub fn new(roots: [I; 4], config: NetworkConfig, storage_factory: Box<dyn Fn() -> S + Send + Sync>) -> Self {
let dimension = roots[0].weights().len();
assert!(roots.iter().all(|r| r.weights().len() == dimension));
assert!(config.distribution_factor > 0. && config.distribution_factor < 1.);
Self {
dimension,
growing_threshold: -1. * dimension as f64 * config.spread_factor.log2(),
distribution_factor: config.distribution_factor,
learning_rate: config.learning_rate,
nodes: Self::create_initial_nodes(roots, 0, config.rebalance_memory, &storage_factory),
storage_factory,
time: 0,
rebalance_memory: config.rebalance_memory,
}
}
/// Stores input into the network.
pub fn store(&mut self, input: I, time: usize) {
debug_assert!(input.weights().len() == self.dimension);
self.time = time;
self.train(input, true)
}
/// Stores multiple inputs into the network.
pub fn store_batch<T: Sized + Send + Sync>(&mut self, item_data: Vec<T>, time: usize, map_func: fn(T) -> I) {
self.time = time;
self.train_batch(item_data, true, map_func);
}
/// Retrains the whole network.
pub fn retrain(&mut self, rebalance_count: usize, node_filter: &(dyn Fn(&NodeLink<I, S>) -> bool)) {
// NOTE compact before rebalancing to reduce network size to be rebalanced
self.compact(node_filter);
self.rebalance(rebalance_count);
self.compact(node_filter);
}
/// Returns node coordinates in arbitrary order.
pub fn get_coordinates(&'_ self) -> impl Iterator<Item = Coordinate> + '_ {
self.nodes.keys().cloned()
}
/// Return nodes in arbitrary order.
pub fn get_nodes<'a>(&'a self) -> impl Iterator<Item = &NodeLink<I, S>> + 'a {
self.nodes.values()
}
/// Returns a total amount of nodes.
pub fn size(&self) -> usize {
self.nodes.len()
}
/// Trains network on an input.
fn train(&mut self, input: I, is_new_input: bool) {
debug_assert!(input.weights().len() == self.dimension);
let bmu = self.find_bmu(&input);
let error = bmu.read().unwrap().distance(input.weights());
self.update(&bmu, &input, error, is_new_input);
bmu.write().unwrap().storage.add(input);
}
/// Trains network on inputs.
fn train_batch<T: Send + Sync>(&mut self, item_data: Vec<T>, is_new_input: bool, map_func: fn(T) -> I) {
let nodes_data = parallel_into_collect(item_data, |item| {
let input = map_func(item);
let bmu = self.find_bmu(&input);
let error = bmu.read().unwrap().distance(input.weights());
(bmu, error, input)
});
nodes_data.into_iter().for_each(|(bmu, error, input)| {
self.update(&bmu, &input, error, is_new_input);
bmu.write().unwrap().storage.add(input);
});
}
/// Finds the best matching unit within the map for the given input.
fn find_bmu(&self, input: &I) -> NodeLink<I, S> {
self.nodes
.iter()
.map(|(_, node)| (node.clone(), node.read().unwrap().distance(input.weights())))
.min_by(|(_, x), (_, y)| x.partial_cmp(y).unwrap_or(Ordering::Less))
.map(|(node, _)| node)
.expect("no nodes")
}
/// Updates network according to the error.
fn update(&mut self, node: &NodeLink<I, S>, input: &I, error: f64, is_new_input: bool) {
let (exceeds_ae, is_boundary) = {
let mut node = node.write().unwrap();
node.error += error;
// NOTE update usage statistics only for a new input
if is_new_input {
node.new_hit(self.time);
}
(node.error > self.growing_threshold, node.topology.is_boundary())
};
match (exceeds_ae, is_boundary) {
// error distribution
(true, false) => {
let distribute_error = |node: Option<&NodeLink<I, S>>| {
let mut node = node.unwrap().write().unwrap();
node.error += self.distribution_factor * node.error;
};
let mut node = node.write().unwrap();
node.error = 0.5 * self.growing_threshold;
distribute_error(node.topology.left.as_ref());
distribute_error(node.topology.right.as_ref());
distribute_error(node.topology.up.as_ref());
distribute_error(node.topology.down.as_ref());
}
// weight distribution
(true, true) => {
// NOTE clone to fight with borrow checker
let coordinate = node.read().unwrap().coordinate.clone();
let weights = node.read().unwrap().weights.clone();
let topology = node.read().unwrap().topology.clone();
let mut distribute_weight = |offset: (i32, i32), link: Option<&NodeLink<I, S>>| {
if link.is_none() {
let coordinate = Coordinate(coordinate.0 + offset.0, coordinate.1 + offset.1);
self.insert(coordinate, weights.as_slice());
}
};
distribute_weight((-1, 0), topology.left.as_ref());
distribute_weight((1, 0), topology.right.as_ref());
distribute_weight((0, 1), topology.up.as_ref());
distribute_weight((0, -1), topology.down.as_ref());
}
_ => {}
}
// weight adjustments
let mut node = node.write().unwrap();
let learning_rate = self.learning_rate * (1. - 3.8 / (self.nodes.len() as f64));
node.adjust(input.weights(), learning_rate);
(node.topology.neighbours().map(|n| n.write().unwrap())).for_each(|mut neighbor| {
neighbor.adjust(input.weights(), learning_rate);
});
}
/// Inserts new neighbors if necessary.
fn insert(&mut self, coordinate: Coordinate, weights: &[f64]) {
let new_node = Arc::new(RwLock::new(Node::new(
coordinate.clone(),
weights,
self.time,
self.rebalance_memory,
self.storage_factory.deref()(),
)));
{
let mut new_node_mut = new_node.write().unwrap();
let (new_x, new_y) = (coordinate.0, coordinate.1);
if let Some(node) = self.nodes.get(&Coordinate(new_x - 1, new_y)) {
new_node_mut.topology.left = Some(node.clone());
node.write().unwrap().topology.right = Some(new_node.clone());
}
if let Some(node) = self.nodes.get(&Coordinate(new_x + 1, new_y)) {
new_node_mut.topology.right = Some(node.clone());
node.write().unwrap().topology.left = Some(new_node.clone());
}
if let Some(node) = self.nodes.get(&Coordinate(new_x, new_y - 1)) {
new_node_mut.topology.down = Some(node.clone());
node.write().unwrap().topology.up = Some(new_node.clone());
}
if let Some(node) = self.nodes.get(&Coordinate(new_x, new_y + 1)) {
new_node_mut.topology.up = Some(node.clone());
node.write().unwrap().topology.down = Some(new_node.clone());
}
}
self.nodes.insert(coordinate, new_node);
}
/// Rebalances network.
fn rebalance(&mut self, rebalance_count: usize) {
let mut data = Vec::with_capacity(self.nodes.len());
(0..rebalance_count).for_each(|_| {
data.clear();
data.extend(self.nodes.iter_mut().flat_map(|(_, node)| node.write().unwrap().storage.drain(0..)));
data.shuffle(&mut rand::thread_rng());
data.drain(0..).for_each(|input| {
self.train(input, false);
});
});
}
fn compact(&mut self, node_filter: &(dyn Fn(&NodeLink<I, S>) -> bool)) {
let mut remove = vec![];
let mut remove_node = |coordinate: &Coordinate, node: &mut NodeLink<I, S>| {
let topology = &mut node.write().unwrap().topology;
topology.left.iter_mut().for_each(|link| link.write().unwrap().topology.right = None);
topology.right.iter_mut().for_each(|link| link.write().unwrap().topology.left = None);
topology.up.iter_mut().for_each(|link| link.write().unwrap().topology.down = None);
topology.down.iter_mut().for_each(|link| link.write().unwrap().topology.up = None);
remove.push(coordinate.clone());
};
// remove user defined nodes
self.nodes
.iter_mut()
.filter(|(_, node)| node_filter.deref()(node))
.for_each(|(coordinate, node)| remove_node(coordinate, node));
// remove empty nodes which are not at boundary
self.nodes
.iter_mut()
.filter(|(_, node)| {
let node = node.read().unwrap();
node.storage.size() == 0 && node.topology.is_boundary()
})
.for_each(|(coordinate, node)| remove_node(coordinate, node));
remove.iter().for_each(|coordinate| {
self.nodes.remove(coordinate);
});
}
/// Creates nodes for initial topology.
fn create_initial_nodes(
roots: [I; 4],
time: usize,
rebalance_memory: usize,
storage_factory: &(dyn Fn() -> S + Send + Sync),
) -> HashMap<Coordinate, NodeLink<I, S>> {
let create_node_link = |coordinate: Coordinate, input: I| {
let mut node =
Node::<I, S>::new(coordinate, input.weights(), time, rebalance_memory, storage_factory.deref()());
node.storage.add(input);
Arc::new(RwLock::new(node))
};
let [n00, n01, n11, n10] = roots;
let n00 = create_node_link(Coordinate(0, 0), n00);
let n01 = create_node_link(Coordinate(0, 1), n01);
let n11 = create_node_link(Coordinate(1, 1), n11);
let n10 = create_node_link(Coordinate(1, 0), n10);
n00.write().unwrap().topology.right = Some(n10.clone());
n00.write().unwrap().topology.up = Some(n01.clone());
n01.write().unwrap().topology.right = Some(n11.clone());
n01.write().unwrap().topology.down = Some(n00.clone());
n10.write().unwrap().topology.up = Some(n11.clone());
n10.write().unwrap().topology.left = Some(n00.clone());
n11.write().unwrap().topology.left = Some(n01.clone());
n11.write().unwrap().topology.down = Some(n10.clone());
[(Coordinate(0, 0), n00), (Coordinate(0, 1), n01), (Coordinate(1, 1), n11), (Coordinate(1, 0), n10)]
.iter()
.cloned()
.collect()
}
}
|
pub trait TerminalSymbol {
type SymbolLiteral: PartialEq;
fn contains(literal: Self::SymbolLiteral) -> bool;
fn from_literal(literal: Self::SymbolLiteral) -> Self;
fn to_literal(&self) -> Self::SymbolLiteral;
fn is_literal(&self, literal: Self::SymbolLiteral) -> bool {
self.to_literal() == literal
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum PrimitiveType {
Int,
Void,
}
impl PrimitiveType {
pub fn as_code(&self) -> String {
use PrimitiveType::*;
let s = match self {
Int => "i32",
Void => unimplemented!(),
};
String::from(s)
}
}
impl TerminalSymbol for PrimitiveType {
type SymbolLiteral = String;
fn contains(literal: String) -> bool {
match literal.as_str() {
"int" | "void" => true,
_ => false,
}
}
fn from_literal(literal: String) -> PrimitiveType {
use PrimitiveType::*;
match literal.as_str() {
"int" => Int,
"void" => Void,
_ => unreachable!(),
}
}
fn to_literal(&self) -> String {
use PrimitiveType::*;
let s = match self {
Int => "int",
Void => "void",
};
String::from(s)
}
}
#[derive(Debug, Clone)]
pub enum ReservedLiteral {
Return,
If,
Else,
While,
}
impl TerminalSymbol for ReservedLiteral {
type SymbolLiteral = String;
fn contains(literal: String) -> bool {
match literal.as_str() {
"return" | "if" | "else" | "while" => true,
_ => false,
}
}
fn from_literal(literal: String) -> ReservedLiteral {
match literal.as_str() {
"return" => ReservedLiteral::Return,
"if" => ReservedLiteral::If,
"else" => ReservedLiteral::Else,
"while" => ReservedLiteral::While,
_ => unreachable!(),
}
}
fn to_literal(&self) -> String {
let s = match self {
ReservedLiteral::Return => "return",
ReservedLiteral::If => "if",
ReservedLiteral::Else => "else",
ReservedLiteral::While => "while",
};
String::from(s)
}
}
#[derive(Debug, Clone)]
pub enum DelimiterKind {
Semicolon,
Comma,
}
impl TerminalSymbol for DelimiterKind {
type SymbolLiteral = char;
fn contains(literal: char) -> bool {
match literal {
';' | ',' => true,
_ => false,
}
}
fn from_literal(literal: char) -> DelimiterKind {
use DelimiterKind::*;
match literal {
';' => Semicolon,
',' => Comma,
_ => unreachable!(),
}
}
fn to_literal(&self) -> char {
use DelimiterKind::*;
match self {
Semicolon => ';',
Comma => ',',
}
}
}
#[derive(Debug, Clone)]
pub enum ParenKind {
NormalOpen,
NormalClose,
SquareOpen,
SquareClose,
CurlyOpen,
CurlyClose,
}
impl TerminalSymbol for ParenKind {
type SymbolLiteral = char;
fn contains(literal: char) -> bool {
match literal {
'(' | ')' | '[' | ']' | '{' | '}' => true,
_ => false,
}
}
fn from_literal(literal: char) -> ParenKind {
use ParenKind::*;
match literal {
'(' => NormalOpen,
')' => NormalClose,
'[' => SquareOpen,
']' => SquareClose,
'{' => CurlyOpen,
'}' => CurlyClose,
_ => unreachable!(),
}
}
fn to_literal(&self) -> char {
use ParenKind::*;
match self {
NormalOpen => '(',
NormalClose => ')',
SquareOpen => '[',
SquareClose => ']',
CurlyOpen => '{',
CurlyClose => '}',
}
}
}
pub enum OperatorPriority {
Addition,
Multiplication,
Equivalence,
Assignment,
}
impl OperatorPriority {
pub fn is_addition(&self) -> bool {
match self {
OperatorPriority::Addition => true,
_ => false,
}
}
pub fn is_multiplication(&self) -> bool {
match self {
OperatorPriority::Multiplication => true,
_ => false,
}
}
pub fn is_equivalence(&self) -> bool {
match self {
OperatorPriority::Equivalence => true,
_ => false,
}
}
}
#[derive(Debug, Clone)]
pub enum OperatorKind {
Plus,
Minus,
Times,
Devide,
Assign,
Equal,
NotEqual,
}
impl OperatorKind {
pub fn priority(&self) -> OperatorPriority {
use OperatorKind::*;
use OperatorPriority::*;
match self {
Plus | Minus => Addition,
Times | Devide => Multiplication,
Assign => Assignment,
Equal | NotEqual => Equivalence,
}
}
}
impl TerminalSymbol for OperatorKind {
type SymbolLiteral = String;
fn contains(literal: String) -> bool {
match literal.as_str() {
"+" | "-" | "*" | "/" | "=" | "!" | "==" | "!=" => true,
_ => false,
}
}
fn from_literal(literal: String) -> OperatorKind {
use OperatorKind::*;
match literal.as_str() {
"+" => Plus,
"-" => Minus,
"*" => Times,
"/" => Devide,
"=" => Assign,
"==" => Equal,
"!=" => NotEqual,
_ => unreachable!(),
}
}
fn to_literal(&self) -> String {
use OperatorKind::*;
let s = match self {
Plus => "+",
Minus => "-",
Times => "*",
Devide => "/",
Assign => "=",
Equal => "==",
NotEqual => "!=",
};
String::from(s)
}
}
|
use clap::App;
use clap::Arg;
use clap::ArgMatches;
use clap::SubCommand;
use crate::client::html_client::Client;
use crate::model::Id;
use crate::cli::HnCommand;
use crate::error::HnError;
pub struct Query;
impl HnCommand for Query {
const NAME: &'static str = "query";
fn parser<'a, 'b>() -> App<'a, 'b> {
SubCommand::with_name(Self::NAME).arg(
Arg::with_name("id")
.value_name("id")
.required(true)
.takes_value(true)
.min_values(1),
)
}
fn cmd(matches: &ArgMatches) -> Result<(), Box<HnError>> {
// SAFE: The clap App will guarantee required arguments are received
let id = matches.value_of("id")
.unwrap();
let id: Id = id.parse()
.map_err(|_| HnError::ArgumentError(Some("id argument not parseable as numeric")))?;
let client = Client::new();
let item = client.item(id)?;
println!("item = {:#?}", item);
Ok(())
}
}
|
use std::collections::HashSet;
/*
AOC 2018
Day 1 - Part 1 : 592
generator: 12.666µs,
runner: 34.021µs
Day 1 - Part 2 - set : 241
generator: 260ns,
runner: 27.686372ms
Day 1 - Part 2 - vec : 241
generator: 657ns,
runner: 2.242261429s
*/
#[aoc(day1, part1)]
pub fn part1(input: &str) -> i32 {
input.lines().map(|n| n.parse::<i32>().expect("Unable to parse number")).sum()
}
#[aoc(day1, part2, set)]
pub fn part2_set(input: &str) -> i32 {
let mut seen: HashSet<i32> = HashSet::new();
let mut freq: i32 = 0;
seen.insert(freq);
for line in input.lines().cycle() {
let curr_num = line.parse::<i32>().expect("Unable to parse number");
freq += curr_num;
if(seen.contains(&freq)) {
return freq;
}
seen.insert(freq);
}
panic!("Shouldn't reach here");
}
#[aoc(day1, part2, vec)]
pub fn part2_vec(input: &str) -> i32 {
let mut seen: Vec<i32> = Vec::new();
let mut freq: i32 = 0;
seen.push(0);
for line in input.lines().cycle() {
let curr_num = line.parse::<i32>().unwrap();
freq += curr_num;
if(seen.contains(&freq)) {
return freq;
}
seen.push(freq);
}
panic!("Shouldn't reach here");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test1() {
assert_eq!(part1("+1\n+1\n+1"), 3);
assert_eq!(part1("+1\n+1\n-2"), 0);
assert_eq!(part1("-1\n-2\n-3"), -6);
}
#[test]
fn test2_set() {
assert_eq!(part2_set("+1\n-1"), 0);
assert_eq!(part2_set("+3\n+3\n+4\n-2\n-4"), 10);
assert_eq!(part2_set("-6\n+3\n+8\n+5\n-6"), 5);
assert_eq!(part2_set("+7\n+7\n-2\n-7\n-4"), 14);
}
#[test]
fn test2_vec() {
assert_eq!(part2_vec("+1\n-1"), 0);
assert_eq!(part2_vec("+3\n+3\n+4\n-2\n-4"), 10);
assert_eq!(part2_vec("-6\n+3\n+8\n+5\n-6"), 5);
assert_eq!(part2_vec("+7\n+7\n-2\n-7\n-4"), 14);
}
}
|
use std::{collections::HashMap, sync::Mutex};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use tracing::{info, instrument, warn};
// funtranslations is very rate limited and slow so I've opted to use an in memory cache.
// In a production API I would buy an API key for funtranslations because even with a cache the rate limit is a serious issue.
type Cache = Lazy<Mutex<HashMap<String, String>>>;
static YODA_CACHE: Cache = Lazy::new(|| Mutex::new(HashMap::new()));
static SHAKESPEARE_CACHE: Cache = Lazy::new(|| Mutex::new(HashMap::new()));
#[instrument(level = "info")]
pub async fn yoda(text: &str) -> Option<String> {
translate(text, "yoda", &YODA_CACHE).await
}
#[instrument(level = "info")]
pub async fn shakespeare(text: &str) -> Option<String> {
translate(text, "shakespeare", &SHAKESPEARE_CACHE).await
}
async fn translate(text: &str, trans_type: &str, cache: &Cache) -> Option<String> {
let translation = || funtranslations(text, trans_type);
if let Ok(mut cache) = cache.lock() {
if let Some(translation) = cache.get(text) {
info!("Taking translation from cache");
return Some(translation.to_owned());
}
let translation = translation().await;
if let Some(ref translation) = translation {
cache.insert(text.to_owned(), translation.to_owned());
};
translation
} else {
warn!("Unable to get lock on cache");
translation().await
}
}
// Call the funtranslations api and return the translation
async fn funtranslations(text: &str, trans_type: &str) -> Option<String> {
#[derive(Serialize)]
struct PostBody<'a> {
text: &'a str,
}
#[derive(Deserialize)]
struct Response {
contents: Contents,
}
#[derive(Deserialize)]
struct Contents {
translated: String,
}
let client = awc::Client::default();
let response: Response = client
.post(format!(
"https://api.funtranslations.com/translate/{}.json",
trans_type,
))
.send_form(&PostBody { text })
.await
.map_err(|e| warn!("Failed to connect to funtranslations: {:?}", e))
.ok()?
.json()
.await
.map_err(|e| warn!("failed to parse json from funtranslations: {:?}", e))
.ok()?;
Some(response.contents.translated)
}
// Translation is not unit tested because without an API key for funtranslations the tests would be
// far too fragile.
// TODO test translation
|
use sdl2::image::InitFlag;
use sdl2::event::Event;
use sdl2::pixels::Color;
use sdl2::image::LoadTexture;
pub struct Display {
// Private field
event_pump: sdl2::EventPump,
// Accessible field
pub texture_creator: sdl2::render::TextureCreator<sdl2::video::WindowContext>,
pub canvas: sdl2::render::Canvas<sdl2::video::Window>,
pub should_close: bool
}
impl Display {
pub fn new(title: &str, width: u32, height: u32) -> Self {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let _image_context = sdl2::image::init(InitFlag::PNG | InitFlag::JPG);
let _win = video_subsystem
.window(title, width, height)
.position_centered()
.resizable()
.build()
.map_err(|e| e.to_string())
.unwrap();
let mut canvas = _win
.into_canvas()
.present_vsync()
.build()
.map_err(|e| e.to_string())
.unwrap();
canvas.set_draw_color(Color::RGBA(51, 51, 51, 255));
let event_pump = sdl_context
.event_pump()
.map_err(|e| e.to_string())
.unwrap();
let texture_creator = canvas.texture_creator();
return Display{event_pump, texture_creator, canvas, should_close: false};
}
// Poll events and clear screen
pub fn update(&mut self) {
for event in self.event_pump.poll_iter() {
match event {
Event::Quit { .. } => self.should_close = true,
_ => {}
}
}
self.canvas.clear();
}
// Show current frame to screen
pub fn present(&mut self) {
self.canvas.present();
}
// Load a texture
pub fn load_texture(&mut self, src: &str) -> sdl2::render::Texture {
self.texture_creator.load_texture(src).unwrap()
}
} |
extern crate arith;
use arith::{parse, eval};
fn main() {
let program = parse("if iszero pred succ 0 then succ succ pred 0 else false");
match program {
Ok(term) => {
println!("Source program: {}", term);
println!("Evaluated program: {}", eval(&term));
}
Err(e) => println!("Parse error: {:?}", e),
}
}
|
//! Functions used for encrypting and decrypting data using XOR.
use utils::data::Data;
/// XORs the given data with a repeating key.
pub fn xor(data: &Data, key: &Data) -> Data {
// Create a new vector to store the resulting bytes in.
let mut bytes = Vec::with_capacity(data.len());
// Repeatedly loop over the key and XOR the data bytes.
let mut it = data.bytes().iter();
'outer: loop {
for k_byte in key.bytes().iter() {
let e_byte = match it.next() {
None => break 'outer,
Some(d_byte) => *k_byte ^ *d_byte,
};
bytes.push(e_byte);
}
}
Data::from_bytes(bytes)
}
|
mod parser;
mod code_writer;
use parser::CommandType;
use crate::parser::Parser;
use crate::code_writer::CodeWriter;
fn main() {
let input_file_path = "../MemoryAccess/StaticTest/StaticTest.vm";
let output_file_path = "../MemoryAccess/StaticTest/StaticTest.asm";
// let input_file_path = "../StackArithmetic/StackTest/StackTest.vm";
// let output_file_path = "../StackArithmetic/StackTest/StackTest.asm";
let mut parser = Parser::new(input_file_path);
let mut code_writer = CodeWriter::new(output_file_path);
while parser.has_more_commands() {
let command = parser.command_type();
match &command {
CommandType::CArithmetic(_) => {code_writer.write_arithmetic(&command)}
CommandType::CPush(_, _) => {code_writer.write_push_pop(&command)},
CommandType::CPop(_, _) => {code_writer.write_push_pop(&command)},
CommandType::CLabel => {}
CommandType::CGoto => {}
CommandType::CIf => {}
CommandType::CFunction(_, _) => {}
CommandType::CReturn => {}
CommandType::CCall(_, _) => {}
CommandType::NotCommand => {}
}
println!("{:?}", command);
parser.advance();
}
code_writer.close();
}
|
extern crate libc;
use std;
use std::ffi::CString;
use self::libc::c_int;
use self::libc::c_char;
use self::libc::c_uint;
enum QtHandle {}
#[link(name="qt5rust")]
extern {
fn qapplication_new(argc: c_int, argv: *mut *mut c_char) -> *mut QtHandle;
fn qapplication_exec(this: *mut QtHandle) -> c_int;
fn qlabel_new(parent: *mut QtHandle) -> *mut QtHandle;
fn qlabel_resize(this: *mut QtHandle, width: c_int, height: c_int) -> ();
fn qlabel_show(this: *mut QtHandle) -> ();
fn qlabel_set_text(this: *mut QtHandle, utf8: *const c_char, length: c_uint) -> ();
}
pub struct QApplication {
this: *mut QtHandle,
}
impl QApplication {
pub fn new() -> QApplication {
let args = std::env::args().map(|arg| CString::new(arg).unwrap() ).collect::<Vec<CString>>();
let c_args = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<*const c_char>>();
unsafe {
return QApplication {
this: qapplication_new(c_args.len() as c_int, c_args.as_ptr() as *mut *mut c_char),
};
}
}
pub fn exec(&self) -> i32 {
unsafe {
return qapplication_exec(self.this);
}
}
}
pub struct QLabel {
this: *mut QtHandle,
}
impl QLabel {
pub fn new() -> QLabel {
unsafe {
return QLabel {
this: qlabel_new(std::ptr::null_mut()),
};
}
}
pub fn resize(&self, width: i32, height: i32) -> () {
unsafe {
return qlabel_resize(self.this, width, height);
}
}
pub fn show(&self) -> () {
unsafe {
return qlabel_show(self.this);
}
}
pub fn set_text(&self, string: &str) -> () {
let cs = CString::new(string).unwrap();
unsafe {
return qlabel_set_text(self.this, cs.as_ptr(), string.len() as u32);
}
}
}
|
mod common;
mod days;
mod points;
fn main() {
for day in days::all_numbers() {
if let Some(solver) = days::get_solver(day) {
let input = common::get_day_input(day).expect(&format!(
"Problem occured while getting input for day{:02}",
day
));
let (solution, time) = solver(&input);
println!(
"Solution for day{:02}: ({}, {}), took {:?}",
day, solution.0, solution.1, time
);
}
}
println!("DONE");
}
|
// Copyright 2019, 2020 Wingchain
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crypto::dsa::{Dsa, DsaImpl, KeyPair};
use node_consensus_primitives::CONSENSUS_POA;
use primitives::codec::{self, Decode, Encode};
use primitives::errors::{CommonError, CommonResult};
use primitives::{Hash, PublicKey, SecretKey, Signature};
use std::convert::TryFrom;
use std::sync::Arc;
#[derive(Encode, Decode)]
pub struct Proof {
pub public_key: PublicKey,
pub signature: Signature,
}
impl Proof {
pub fn new(block_hash: &Hash, secret_key: &SecretKey, dsa: Arc<DsaImpl>) -> CommonResult<Self> {
let keypair = dsa.key_pair_from_secret_key(&secret_key.0)?;
let (_, public_key_len, signature_len) = dsa.length().into();
let public_key = {
let mut out = vec![0u8; public_key_len];
keypair.public_key(&mut out);
PublicKey(out)
};
let signature = {
let mut out = vec![0u8; signature_len];
let message = codec::encode(&block_hash)?;
keypair.sign(&message, &mut out);
Signature(out)
};
Ok(Self {
public_key,
signature,
})
}
}
impl TryFrom<Proof> for primitives::Proof {
type Error = CommonError;
fn try_from(value: Proof) -> Result<Self, Self::Error> {
Ok(Self {
name: CONSENSUS_POA.to_string(),
data: codec::encode(&value)?,
})
}
}
|
// #![feature(bool_to_option)]
pub mod client;
#[macro_use]
mod macros;
pub mod models;
mod query_variables;
mod utils;
|
use std::collections::HashMap;
use rand::seq::SliceRandom;
use rand::Rng;
use crate::config;
use crate::neatns::network::genome::Genome;
use crate::neatns::network::link::Link;
use crate::neatns::network::node::{Node, NodeRef};
use crate::neatns::network::{activation, connection, order};
#[derive(Clone)]
pub struct AgentGenome {
pub inputs: HashMap<NodeRef, Node>,
pub hidden_nodes: HashMap<NodeRef, Node>,
pub outputs: HashMap<NodeRef, Node>,
pub links: HashMap<(NodeRef, NodeRef), Link>, // Links between nodes
pub order: order::Order<NodeRef>,
// Actions to perform when evaluating
pub connections: connection::Connections<NodeRef>, // Fast connection lookup
}
impl AgentGenome {
pub fn new(genome: Genome) -> AgentGenome {
AgentGenome {
inputs: genome.inputs.clone(),
hidden_nodes: genome.hidden_nodes.clone(),
outputs: genome.outputs.clone(),
links: genome.links.clone(),
order: genome.order.clone(),
connections: genome.connections.clone(),
}
}
fn split_link(&mut self, link: Link, new_node_id: u64) {
{
// Disable link
let link = self
.links
.get_mut(&(link.from, link.to))
.expect("Unable to split nonexistent link");
assert!(link.enabled);
link.enabled = false;
link.split = true;
}
let new_node_ref = NodeRef::Hidden(new_node_id);
// Might have inherited that the connection is not split, but also the nodes splitting it
if self.hidden_nodes.contains_key(&new_node_ref) {
return;
}
// Disable connection
self.connections.disable(link.from, link.to);
// Add and remove actions
self.order.split_link(link.from, link.to, new_node_ref);
self.hidden_nodes
.insert(new_node_ref, Node::new(NodeRef::Hidden(new_node_id)));
let link1 = Link::new(link.from, new_node_ref, 1.0, 0);
let link2 = Link::new(new_node_ref, link.to, link.weight, 0);
assert!(!self.links.contains_key(&(link1.from, link1.to)));
self.insert_link(link1, false);
assert!(!self.links.contains_key(&(link2.from, link2.to)));
self.insert_link(link2, false);
}
fn insert_link(&mut self, link: Link, add_action: bool) {
// Add link
self.links.insert((link.from, link.to), link);
// Add connections
self.connections.add(link.from, link.to, link.enabled);
// Add action
if link.enabled && add_action {
// When adding many links at the same time, it is faster to sort
// topologically at the end than adding every connection independently
// When 'add_action' is false, 'sort_topologically' must be called on
// self.actions when all links are inserted.
// Except when the link is added by split, then self.action should
// perform the split internally.
self.order.add_link(link.from, link.to, &self.connections);
}
}
pub fn mutate(&mut self) {
let mut rng = rand::thread_rng();
if rng.gen::<f64>() < config::AGENT.add_neuron {
self.mutation_add_node();
}
if rng.gen::<f64>() < config::AGENT.add_connection {
self.mutation_add_connection();
}
if rng.gen::<f64>() < config::AGENT.disable_connection {
self.mutation_disable_connection();
}
if rng.gen::<f64>() < config::AGENT.mutate_weight {
self.mutate_link_weight();
}
}
fn mutate_link_weight(&mut self) {
let mut rng = rand::thread_rng();
// Mutate single link
if !self.links.is_empty() {
let link_index = rng.gen_range(0, self.links.len());
if let Some(link) = self.links.values_mut().skip(link_index).next() {
link.weight +=
(rng.gen::<f64>() - 0.5) * 2.0 * config::NEAT.mutate_link_weight_size;
}
}
/*for link in self.links.values_mut() {
link.weight += (rng.gen::<f64>() - 0.5) * 2.0 * config::NEAT.mutate_link_weight_size;
}*/
}
fn mutation_add_node(&mut self) {
// Select random enabled link
if let Some(index) = self
.links
.iter()
.filter(|(_, link)| !link.split && link.enabled)
.map(|(i, _)| *i)
.collect::<Vec<(NodeRef, NodeRef)>>()
.choose(&mut rand::thread_rng())
{
if self.order.contains(&order::Action::Link(index.0, index.1)) {
if let Some(&link) = self.links.get(index) {
self.split_link(link, self.hidden_nodes.len() as u64);
}
}
/*assert!(self.order.contains(&order::Action::Link(index.0, index.1)));
if let Some(&link) = self.links.get(index) {
self.split_link(link, self.hidden_nodes.len() as u64);
}*/
}
}
// TODO: avoid retries
fn mutation_add_connection(&mut self) {
let mut rng = rand::thread_rng();
// Retry 50 times
for _ in 0..50 {
// Select random source and target nodes for new link
let from_index = rng.gen_range(0, self.inputs.len() + self.hidden_nodes.len());
let to_index = rng.gen_range(0, self.hidden_nodes.len() + self.outputs.len());
let from_option = if from_index < self.inputs.len() {
self.inputs.keys().skip(from_index).next()
} else {
self.hidden_nodes
.keys()
.skip(from_index - self.inputs.len())
.next()
};
let to_option = if to_index < self.outputs.len() {
self.outputs.keys().skip(to_index).next()
} else {
self.hidden_nodes
.keys()
.skip(to_index - self.outputs.len())
.next()
};
if let (Some(&from), Some(&to)) = (from_option, to_option) {
// If connection does not exist and its addition does not create cycle
if !self.links.contains_key(&(from, to))
&& !self.connections.creates_cycle(from, to)
{
self.insert_link(
Link::new(
from,
to,
(rng.gen::<f64>() - 0.5) * 2.0 * config::NEAT.initial_link_weight_size,
0,
),
true,
);
break;
}
} else {
break;
}
}
}
fn mutation_disable_connection(&mut self) {
if let Some(&connection_ref) = self
.links
.iter()
.filter(|(_, link)| link.enabled)
.map(|(i, _)| i)
.collect::<Vec<&(NodeRef, NodeRef)>>()
.choose(&mut rand::thread_rng())
{
let connection_ref = *connection_ref;
self.connections.disable(connection_ref.0, connection_ref.1);
self.order.remove_link(connection_ref.0, connection_ref.1);
if let Some(link) = self.links.get_mut(&connection_ref) {
link.enabled = false;
}
}
}
// Genetic distance between two genomes
pub fn distance(&self, other: &Self) -> f64 {
let mut link_differences: u64 = 0; // Number of links present in only one of the genomes
let mut link_distance: f64 = 0.0; // Total distance between links present in both genomes
let mut link_count = self.links.len() as u64; // Number of unique links between the two genomes
for link_ref in other.links.keys() {
if !self.links.contains_key(link_ref) {
link_differences += 1;
}
}
link_count += link_differences; // Count is number of links in A + links in B that are not in A
for (link_ref, link) in self.links.iter() {
if let Some(link2) = other.links.get(link_ref) {
link_distance += link.distance(link2); // Distance normalized between 0 and 1
} else {
link_differences += 1;
}
}
return if link_count == 0 {
0.0
} else {
((link_differences as f64) + link_distance) / (link_count as f64)
};
}
pub fn get_activation(&self, node_ref: &NodeRef) -> activation::Activation {
match node_ref {
NodeRef::Input(_) => self.inputs.get(node_ref).unwrap().activation,
NodeRef::Hidden(_) => self.hidden_nodes.get(node_ref).unwrap().activation,
NodeRef::Output(_) => self.outputs.get(node_ref).unwrap().activation,
}
}
pub fn get_bias(&self, node_ref: &NodeRef) -> f64 {
match node_ref {
NodeRef::Input(_) => self.inputs.get(node_ref).unwrap().bias,
NodeRef::Hidden(_) => self.hidden_nodes.get(node_ref).unwrap().bias,
NodeRef::Output(_) => self.outputs.get(node_ref).unwrap().bias,
}
}
}
|
use anyhow::Error;
use serde_derive::Deserialize;
use yew::{
format::{Json, Nothing},
html,
services::{
fetch::{FetchTask, Request, Response},
FetchService,
},
Component, ComponentLink, InputData,
};
#[derive(Deserialize)]
struct Cep {
cep: String,
logradouro: String,
complemento: String,
bairro: String,
localidade: String,
uf: String,
ibge: String,
gia: String,
ddd: String,
siafi: String,
}
impl Cep {
fn new() -> Self {
Self {
cep: "".to_string(),
logradouro: "".to_string(),
complemento: "".to_string(),
bairro: "".to_string(),
localidade: "".to_string(),
uf: "".to_string(),
ibge: "".to_string(),
gia: "".to_string(),
ddd: "".to_string(),
siafi: "".to_string(),
}
}
}
struct Model {
link: ComponentLink<Self>,
task: Option<FetchTask>,
text: String,
cep: Cep,
}
const URL: &str = "https://viacep.com.br/ws/";
enum Msg {
FetchData(String),
FetchReady(Cep),
FetchResourceFailed,
}
impl Component for Model {
type Message = Msg;
type Properties = ();
fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
text: "".to_string(),
task: None,
cep: Cep::new(),
}
}
fn update(&mut self, msg: Self::Message) -> yew::ShouldRender {
match msg {
Msg::FetchData(cep) => {
let request = Request::get(format!("{}/{}/json/", URL, cep))
.body(Nothing)
.expect("Couldn't create request");
let callback =
self.link
.callback(|response: Response<Json<Result<Cep, Error>>>| {
if let (meta, Json(Ok(data))) = response.into_parts() {
if meta.status.is_success() {
return Msg::FetchReady(data);
}
}
Msg::FetchResourceFailed
});
let task = FetchService::fetch(request, callback).expect("Failed to create task");
self.task = Some(task);
true
}
Msg::FetchReady(data) => {
self.text = "Valid cep".to_string();
self.cep = data;
true
}
Msg::FetchResourceFailed => {
self.text = "Invalid cep".to_string();
true
}
}
}
fn change(&mut self, _props: Self::Properties) -> yew::ShouldRender {
todo!()
}
fn view(&self) -> yew::Html {
html! {
<>
<nav>
<div class="header">
</div>
</nav>
<div class="container">
<h1>{ self.text.clone() }</h1>
<input oninput=self.link.callback(|cep: InputData| Msg::FetchData(cep.value)) />
<table class="table">
<tr>
<th scope="col">{"cep"}</th>
<th scope="col">{"logradouro"}</th>
<th scope="col">{"complemento"}</th>
<th scope="col">{"bairro"}</th>
<th scope="col">{"localidade"}</th>
<th scope="col">{"uf"}</th>
<th scope="col">{"ibge"}</th>
<th scope="col">{"gia"}</th>
<th scope="col">{"ddd"}</th>
<th scope="col">{"siafi"}</th>
</tr>
<tr>
<td>{self.cep.cep.clone()}</td>
<td>{self.cep.logradouro.clone()}</td>
<td>{self.cep.complemento.clone()}</td>
<td>{self.cep.bairro.clone()}</td>
<td>{self.cep.localidade.clone()}</td>
<td>{self.cep.uf.clone()}</td>
<td>{self.cep.ibge.clone()}</td>
<td>{self.cep.gia.clone()}</td>
<td>{self.cep.ddd.clone()}</td>
<td>{self.cep.siafi.clone()}</td>
</tr>
</table>
</div>
</>
}
}
}
fn main() {
yew::start_app::<Model>();
}
|
use simple_error::bail;
use evmap;
use evmap::{ReadHandle, WriteHandle};
use std::error;
use std::io;
use std::io::BufRead;
use std::sync::mpsc;
use std::thread;
use crate::day;
pub type BoxResult<T> = Result<T, Box<dyn error::Error>>;
struct Intcode {
p: Vec<i64>,
base: i64,
}
impl Intcode {
fn new(p: &[i64]) -> Self { Self { p: p.to_vec(), base: 0 } }
fn op(&self, c: i64) -> i64 { c % 100 }
fn get(&mut self, a: usize) -> i64 {
// eprintln!("get {}", a);
if a >= self.p.len() { self.p.resize(a + 1, 0); }
self.p[a]
}
fn put(&mut self, a: usize, v: i64) {
// eprintln!("put @{} {}", a, v);
if a >= self.p.len() { self.p.resize(a + 1, 0); }
self.p[a] = v;
}
fn addr(&mut self, ip: usize, i: usize) -> usize {
let a = self.get(ip + i);
let v = match self.get(ip) / vec![100, 1000, 10000][i - 1] % 10 {
0 => a as usize,
2 => (a + self.base) as usize,
_ => 0, // XXX
};
v
}
fn val(&mut self, ip: usize, i: usize) -> i64 {
let a = self.get(ip + i);
let v = match self.get(ip) / vec![100, 1000, 10000][i - 1] % 10 {
1 => a,
_ => {
let addr = self.addr(ip, i);
self.get(addr)
},
};
// eprintln!("{} {} {} {} {} {}", ip, self.get(ip), i, a, self.base, v);
v
}
fn run(&mut self, sender: &mpsc::Sender<i64>, receiver: &mpsc::Receiver<i64>,
request: &mpsc::Sender<()>, ack: &mpsc::Receiver<()>) -> BoxResult<i64> {
let mut ip = 0;
let mut o = None;
while { let op = self.get(ip); self.op(op) != 99 } {
// eprintln!("{}: {} {} {} {}", ip, self.p[ip], self.p[ip + 1], self.p[ip + 2], self.p[ip + 3]);
match self.op(self.p[ip]) {
1 => {
let a = self.val(ip, 1);
let b = self.val( ip, 2);
let c = self.addr(ip, 3);
self.put(c, a + b);
ip += 4;
},
2 => {
let a = self.val(ip, 1);
let b = self.val(ip, 2);
let c = self.addr(ip, 3);
self.put(c, a * b);
ip += 4;
},
3 => {
let a = self.addr(ip, 1);
// eprintln!(">recv {}", a);
request.send(())?;
self.put(a as usize, receiver.recv()?);
// eprintln!("<recv {}", self.get(a as usize));
ip += 2;
},
4 => {
let a = self.val(ip, 1);
o = Some(a);
// eprintln!(">send {}", a);
sender.send(a)?;
// eprintln!("<send");
ack.recv()?;
// eprintln!("<<send");
ip += 2;
},
5 => {
let a = self.val(ip, 1);
let b = self.val(ip, 2) as usize;
ip = if a != 0 { b } else { ip + 3 };
},
6 => {
let a = self.val(ip, 1);
let b = self.val(ip, 2) as usize;
ip = if a == 0 { b } else { ip + 3 };
},
7 => {
let a = self.val(ip, 1);
let b = self.val(ip, 2);
let c = self.addr(ip, 3);
self.put(c, if a < b { 1 } else { 0 });
ip += 4;
},
8 => {
let a = self.val(ip, 1);
let b = self.val(ip, 2);
let c = self.addr(ip,3);
self.put(c, if a == b { 1 } else { 0 });
ip += 4;
},
9 => {
self.base += self.val(ip, 1);
// eprintln!("<base {}", self.base);
ip += 2;
}
_ => bail!("unknown opcode {}: {}", ip, self.op(self.p[ip])),
};
}
if o.is_none() { bail!("no output"); }
Ok(o.unwrap())
}
#[allow(dead_code)]
fn arg(&self, ip: usize, offset: usize) -> String {
let a = self.p[ip + offset].to_string();
match self.p[ip] / vec![100, 1000, 10000][offset - 1] % 10 {
0 => format!("@{}", a),
1 => a,
2 => format!("+{}", a),
_ => String::from(""), // XXX
}
}
#[allow(dead_code)]
fn disassemble(&self) {
let mut ip = 0;
while ip < self.p.len() {
match self.op(self.p[ip]) {
1 => {
println!("{}: add {} {} {}", ip, self.arg(ip, 1), self.arg(ip, 2), self.arg(ip, 3));
ip += 4;
},
2 => {
println!("{}: mul {} {} {}", ip, self.arg(ip, 1), self.arg(ip, 2), self.arg(ip, 3));
ip += 4;
},
3 => {
println!("{}: in {}", ip, self.arg(ip, 1));
ip += 2;
},
4 => {
println!("{}: out {}", ip, self.arg(ip, 1));
ip += 2;
},
5 => {
println!("{}: jnz {} {}", ip, self.arg(ip, 1), self.arg(ip, 2));
ip += 3;
},
6 => {
println!("{}: jz {} {}", ip, self.arg(ip, 1), self.arg(ip, 2));
ip += 3;
},
7 => {
println!("{}: testlt {} {} {}", ip, self.arg(ip, 1), self.arg(ip, 2), self.arg(ip, 3));
ip += 4;
},
8 => {
println!("{}: testeq {} {} {}", ip, self.arg(ip, 1), self.arg(ip, 2), self.arg(ip, 3));
ip += 4;
},
9 => {
println!("{}: base {}", ip, self.arg(ip, 1));
ip += 2;
},
99 => {
println!("{}: halt", ip);
ip += 1;
},
_ => {
println!("{}: data ({})", ip, self.p[ip]);
ip += 1;
},
};
}
}
}
pub struct Day21 {}
impl day::Day for Day21 {
fn tag(&self) -> &str { "21" }
fn part1(&self, input: &dyn Fn() -> Box<dyn io::Read>) {
let reader = io::BufReader::new(input());
let p = reader.split(b',')
.map(|v| String::from_utf8(v.unwrap()).unwrap())
.map(|s| s.trim_end().parse::<i64>().unwrap())
.collect::<Vec<_>>();
println!("{:?}", self.part1_impl(p, "NOT A T\nNOT T T\nAND B T\nAND C T\nNOT T T\nAND D T\nNOT T T\nNOT T J\nWALK\n"));
}
fn part2(&self, input: &dyn Fn() -> Box<dyn io::Read>) {
let reader = io::BufReader::new(input());
let p = reader.split(b',')
.map(|v| String::from_utf8(v.unwrap()).unwrap())
.map(|s| s.trim_end().parse::<i64>().unwrap())
.collect::<Vec<_>>();
println!("{:?}", self.part1_impl(p, "NOT A J\nNOT B T\nAND D T\nAND H T\nOR T J\nNOT C T\nAND D T\nAND H T\nOR T J\nRUN\n"));
}
}
impl Day21 {
fn part1_impl(self: &Self, p: Vec<i64>, prog: &str)
-> BoxResult<i64> {
let (input_sender, input_receiver) = mpsc::channel::<i64>();
let (output_sender, output_receiver) = mpsc::channel::<i64>();
let (request_sender, request_receiver) = mpsc::channel::<()>();
let (ack_sender, ack_receiver) = mpsc::channel::<()>();
let (start_sender, start_receiver) = mpsc::channel::<()>();
let _cpu = thread::spawn(move || {
while start_receiver.recv().is_ok() {
let mut ic = Intcode::new(&p.clone());
ic.run(&output_sender, &input_receiver, &request_sender, &ack_receiver)
.unwrap_or(0);
// eprintln!("cpu stopped");
}
// eprintln!("really stopped");
});
let mut r = 0;
let mut stop = 99;
let mut line = String::new();
let mut i = 0;
let mut mode = 0;
start_sender.send(()).unwrap();
loop {
let o = output_receiver.recv().unwrap();
ack_sender.send(()).unwrap();
if o > 255 {
r = o;
break;
} else {
// eprint!("{}", o as u8 as char);
line += format!("{}", o as u8 as char).as_str();
if o == 10 {
if stop < 99 { eprint!("{}", line); };
line = String::new();
i += 1;
if i == stop { break; }
} else if o == 64 && i % 5 == 0 {
stop = i + 2;
}
}
if mode == 0 && o == 10 {
mode += 1;
prog.chars().into_iter().for_each(|c| {
request_receiver.recv().unwrap();
input_sender.send(c as u8 as i64).unwrap();
});
}
}
Ok(r)
}
}
|
#[no_mangle]
pub extern "C" fn what_have_we_here() -> i32 {
leaf::HOW_MANY * leaf::HOW_MANY
}
|
//! Parse OpenLibrary JSON.
use std::str::FromStr;
use log::*;
use serde::de;
use serde::Deserialize;
use thiserror::Error;
use crate::tsv::split_first;
/// Struct representing a row of the OpenLibrary dump file.
///
/// The row extracts the key and record, deserializing the record from JSON to the
/// appropriate type.
pub struct Row<T> {
pub key: String,
pub record: T,
}
/// Error type for parsing an OpenLibrary JSON row.
#[derive(Error, Debug)]
pub enum RowError {
#[error("line has insufficient fields, failed splitting {0}")]
FieldError(i32),
#[error("JSON parsing error: {0}")]
ParseError(#[from] serde_json::Error),
}
impl<T: de::DeserializeOwned> FromStr for Row<T> {
type Err = RowError;
fn from_str(s: &str) -> Result<Row<T>, RowError> {
// split row into columns
let (_, rest) = split_first(s).ok_or(RowError::FieldError(1))?;
let (key, rest) = split_first(rest).ok_or(RowError::FieldError(2))?;
let (_, rest) = split_first(rest).ok_or(RowError::FieldError(3))?;
let (_, data) = split_first(rest).ok_or(RowError::FieldError(4))?;
let record = serde_json::from_str(data).map_err(|e| {
error!("invalid JSON in record {}: {:?}", key, e);
let jsv: serde_json::Value = serde_json::from_str(data).expect("invalid JSON");
let jsp = serde_json::to_string_pretty(&jsv).expect("uhh");
info!("offending JSON: {}", jsp);
e
})?;
Ok(Row {
key: key.to_owned(),
record,
})
}
}
/// Struct representing an author link in OL.
///
/// There are several different formats in which we can find author references.
/// This enum encapsulates them, and Serde automatically deserializes it into the
/// appropraite variant. We then use the [Author::key] function to extract the key itself,
/// no matter the variant.
#[derive(Deserialize, Debug)]
#[serde(untagged)]
pub enum Author {
Object { key: String },
Nested { author: Keyed },
Key(String),
Empty {},
}
/// Keyed object reference
#[derive(Deserialize, Debug)]
pub struct Keyed {
pub key: String,
}
impl Author {
/// Get the key out of an author reference.
pub fn key<'a>(&'a self) -> Option<&'a str> {
match self {
Author::Object { key } => Some(key.as_ref()),
Author::Nested { author } => Some(author.key.as_ref()),
Author::Key(ref ks) => Some(ks.as_ref()),
Author::Empty {} => None,
}
}
}
/// An author record parsed from OpenLibrary JSON.
#[derive(Deserialize)]
pub struct OLAuthorSource {
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub personal_name: Option<String>,
#[serde(default)]
pub alternate_names: Vec<String>,
}
/// An edition record parsed from OpenLibrary JSON.
#[derive(Deserialize)]
pub struct OLEditionRecord {
#[serde(default)]
pub isbn_10: Vec<String>,
#[serde(default)]
pub isbn_13: Vec<String>,
#[serde(default)]
pub asin: Vec<String>,
#[serde(default)]
pub title: Option<String>,
#[serde(default)]
pub works: Vec<Keyed>,
#[serde(default)]
pub authors: Vec<Author>,
#[serde(default)]
pub subjects: Vec<String>,
}
/// An author record parsed from OpenLibrary JSON.
#[derive(Deserialize)]
pub struct OLWorkRecord {
#[serde(default)]
pub authors: Vec<Author>,
#[serde(default)]
pub title: Option<String>,
#[serde(default)]
pub subjects: Vec<String>,
}
|
// (Full example with detailed comments in examples/01a_quick_example.rs)
//
// This example demonstrates clap's "builder pattern" method of creating arguments
// which the most flexible, but also most verbose.
use clap::{Arg, App};
fn main() {
let matches = App::new("My Super Program")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")
.arg(Arg::new("config")
.short('c')
.long("config")
.value_name("FILE")
.about("Sets a custom config file")
.takes_value(true))
.arg(Arg::new("INPUT")
.about("Sets the input file to use")
.required(true)
.index(1))
.arg(Arg::new("v")
.short('v')
.multiple(true)
.about("Sets the level of verbosity"))
.subcommand(App::new("test")
.about("controls testing features")
.version("1.3")
.author("Someone E. <someone_else@other.com>")
.arg(Arg::new("debug")
.short('d')
.about("print debug information verbosely")))
.get_matches();
// Same as above examples...
} |
pub mod bitvec;
mod chunked_vec;
pub use crate::chunked_vec::ChunkedVecInt as ChunkedVecInt;
|
use super::auto::{HasInner, Spawnable, Abstract};
use super::clickable::{Clickable, ClickableInner};
use super::control::{AControl, Control, ControlInner};
use super::has_label::{HasLabel, HasLabelInner};
use super::member::{AMember, Member};
define! {
Button: Control + Clickable + HasLabel {
constructor: {
fn with_label<S: AsRef<str>>(label: S) -> Box<dyn Button>;
}
}
}
impl<II: ButtonInner, T: HasInner<I = II> + Abstract + 'static> ButtonInner for T {
fn with_label<S: AsRef<str>>(label: S) -> Box<dyn Button> {
<<Self as HasInner>::I as ButtonInner>::with_label(label)
}
}
impl<T: ButtonInner> Button for AMember<AControl<AButton<T>>> {
#[inline]
fn as_button(&self) -> &dyn Button {
self
}
#[inline]
fn as_button_mut(&mut self) -> &mut dyn Button {
self
}
#[inline]
fn into_button(self: Box<Self>) -> Box<dyn Button> {
self
}
}
impl<T: ButtonInner> NewButton for AMember<AControl<AButton<T>>> {
#[inline]
fn with_label<S: AsRef<str>>(label: S) -> Box<dyn Button> {
T::with_label(label)
}
}
impl<T: ButtonInner> Spawnable for AMember<AControl<AButton<T>>> {
fn spawn() -> Box<dyn Control> {
<T as Spawnable>::spawn()
}
}
|
#[cfg(test)]
mod tests {
use lib::get_max_range;
#[test]
fn test_get_max_range() {
let array: [i32; 7] = [-15, 110, 78, 32, -45, 120, -50];
assert_eq!(get_max_range(&array), 170);
let array: [i32; 7] = [0, 1, -2, 0, 3, 2, 5];
assert_eq!(get_max_range(&array), 7);
}
#[test]
fn test_get_max_range_only_signed() {
let array: [i32; 7] = [-15, -110, -78, -32, -45, -120, -50];
assert_eq!(get_max_range(&array), 105);
}
}
|
use super::float_eq;
use std::default::Default;
use std::fmt;
use std::ops;
use tuples::Tuple;
#[derive(Copy, Clone, Debug)]
pub struct Matrix2 {
pub rows: [[f32; 2]; 2],
}
impl PartialEq for Matrix2 {
fn eq(&self, other: &Matrix2) -> bool {
for row in 0..2 {
for col in 0..2 {
if !float_eq(self.rows[row][col], other.rows[row][col]) {
return false;
}
}
}
true
}
}
impl Matrix2 {
pub fn from_rows(rows: [[f32; 2]; 2]) -> Self {
Matrix2 { rows }
}
pub fn determinant(&self) -> f32 {
self.rows[0][0] * self.rows[1][1] - self.rows[0][1] * self.rows[1][0]
}
}
#[test]
fn test_a_2x2_matrix_should_be_representable() {
let matrix = Matrix2::from_rows([[-3.0, 5.0], [1.0, -2.0]]);
assert_eq!(matrix.rows[0][0], -3.0);
assert_eq!(matrix.rows[0][1], 5.0);
assert_eq!(matrix.rows[1][0], 1.0);
assert_eq!(matrix.rows[1][1], -2.0);
}
#[test]
fn test_calculating_the_determinant_of_a_2x2_matrix() {
let matrix = Matrix2::from_rows([[1.0, 5.0], [-3.0, 2.0]]);
assert_eq!(matrix.determinant(), 17.0);
}
#[derive(Copy, Clone, Debug)]
pub struct Matrix3 {
pub rows: [[f32; 3]; 3],
}
impl PartialEq for Matrix3 {
fn eq(&self, other: &Matrix3) -> bool {
for row in 0..3 {
for col in 0..3 {
if !float_eq(self.rows[row][col], other.rows[row][col]) {
return false;
}
}
}
true
}
}
impl Matrix3 {
pub fn from_rows(rows: [[f32; 3]; 3]) -> Self {
Matrix3 { rows }
}
pub fn submatrix(&self, del_row: usize, del_col: usize) -> Matrix2 {
let mut values = Vec::with_capacity(2 * 2);
for (rowi, row) in self.rows.iter().enumerate() {
for (coli, value) in row.iter().enumerate() {
if rowi != del_row && coli != del_col {
values.push(value.clone());
}
}
}
Matrix2::from_rows([[values[0], values[1]], [values[2], values[3]]])
}
pub fn minor(&self, row: usize, col: usize) -> f32 {
self.submatrix(row, col).determinant()
}
pub fn cofactor(&self, row: usize, col: usize) -> f32 {
let mut val = self.minor(row, col);
if (row + col) % 2 != 0 {
val = -val
}
val
}
pub fn determinant(&self) -> f32 {
self.rows[0][0] * self.cofactor(0, 0)
+ self.rows[0][1] * self.cofactor(0, 1)
+ self.rows[0][2] * self.cofactor(0, 2)
}
}
#[test]
fn test_a_3x3_matrix_should_be_representable() {
let matrix = Matrix3::from_rows([
[-3.0, 5.0, 0.0],
[1.0, -2.0, -7.0],
[0.0, 1.0, 1.0],
]);
assert_eq!(matrix.rows[0][0], -3.0);
assert_eq!(matrix.rows[1][1], -2.0);
assert_eq!(matrix.rows[2][2], 1.0);
}
#[test]
fn test_a_submatrix_of_a_3x3_matrix_is_a_2x2_matrix() {
let matrix = Matrix3::from_rows([
[1.0, 5.0, 0.0],
[-3.0, 2.0, 7.0],
[0.0, 6.0, -3.0],
]);
let expected = Matrix2::from_rows([[-3.0, 2.0], [0.0, 6.0]]);
assert_eq!(matrix.submatrix(0, 2), expected);
}
#[test]
fn test_calculating_a_minor_or_a_3x3_matrix() {
let matrix = Matrix3::from_rows([
[3.0, 5.0, 0.0],
[2.0, -1.0, -7.0],
[6.0, -1.0, 5.0],
]);
let submatrix = matrix.submatrix(1, 0);
assert_eq!(submatrix.determinant(), 25.0);
assert_eq!(matrix.minor(1, 0), 25.0);
}
#[test]
fn test_calculating_a_cofactor_of_a_3x3_matrix() {
let matrix = Matrix3::from_rows([
[3.0, 5.0, 0.0],
[2.0, -1.0, -7.0],
[6.0, -1.0, 5.0],
]);
assert_eq!(matrix.minor(0, 0), -12.0);
assert_eq!(matrix.cofactor(0, 0), -12.0);
assert_eq!(matrix.minor(1, 0), 25.0);
assert_eq!(matrix.cofactor(1, 0), -25.0);
}
#[test]
fn test_calculating_the_determinant_of_a_3x3_matrix() {
let matrix = Matrix3::from_rows([
[1.0, 2.0, 6.0],
[-5.0, 8.0, -4.0],
[2.0, 6.0, 4.0],
]);
assert_eq!(matrix.cofactor(0, 0), 56.0);
assert_eq!(matrix.cofactor(0, 1), 12.0);
assert_eq!(matrix.cofactor(0, 2), -46.0);
assert_eq!(matrix.determinant(), -196.0);
}
#[derive(Copy, Clone)]
pub struct Matrix4 {
pub rows: [[f32; 4]; 4],
}
impl PartialEq for Matrix4 {
fn eq(&self, other: &Matrix4) -> bool {
for row in 0..4 {
for col in 0..4 {
if !float_eq(self.rows[row][col], other.rows[row][col]) {
return false;
}
}
}
true
}
}
impl Eq for Matrix4 {}
impl fmt::Debug for Matrix4 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for row in 0..4 {
for col in 0..4 {
write!(f, " | {:3.5}", self.rows[row][col])?;
}
write!(f, " |")?;
write!(f, "\n")?;
}
Ok(())
}
}
impl ops::Mul<Matrix4> for Matrix4 {
type Output = Self;
fn mul(self, other: Matrix4) -> Self {
let mut rows = [[Default::default(); 4]; 4];
for row in 0..4 {
for col in 0..4 {
rows[row][col] = self.rows[row][0] * other.rows[0][col]
+ self.rows[row][1] * other.rows[1][col]
+ self.rows[row][2] * other.rows[2][col]
+ self.rows[row][3] * other.rows[3][col];
}
}
Matrix4::from_rows(rows)
}
}
#[test]
fn test_multiplying_two_matrices() {
let matrix_a = Matrix4::from_rows([
[1.0, 2.0, 3.0, 4.0],
[2.0, 3.0, 4.0, 5.0],
[3.0, 4.0, 5.0, 6.0],
[4.0, 5.0, 6.0, 7.0],
]);
let matrix_b = Matrix4::from_rows([
[0.0, 1.0, 2.0, 4.0],
[1.0, 2.0, 4.0, 8.0],
[2.0, 4.0, 8.0, 16.0],
[4.0, 8.0, 16.0, 32.0],
]);
let expected = Matrix4::from_rows([
[24.0, 49.0, 98.0, 196.0],
[31.0, 64.0, 128.0, 256.0],
[38.0, 79.0, 158.0, 316.0],
[45.0, 94.0, 188.0, 376.0],
]);
assert_eq!(matrix_a * matrix_b, expected);
}
#[test]
fn test_multiplying_a_matrix_by_the_identity() {
let matrix = Matrix4::from_rows([
[0.0, 1.0, 2.0, 4.0],
[1.0, 2.0, 4.0, 8.0],
[2.0, 4.0, 8.0, 16.0],
[4.0, 8.0, 16.0, 32.0],
]);
assert_eq!(matrix.clone() * IDENTITY_MATRIX4, matrix);
}
impl ops::Mul<Tuple> for Matrix4 {
type Output = Tuple;
fn mul(self, rhs: Tuple) -> Tuple {
Tuple::new(
self.rows[0][0] as f32 * rhs.x
+ self.rows[0][1] as f32 * rhs.y
+ self.rows[0][2] as f32 * rhs.z
+ self.rows[0][3] as f32 * rhs.w,
self.rows[1][0] as f32 * rhs.x
+ self.rows[1][1] as f32 * rhs.y
+ self.rows[1][2] as f32 * rhs.z
+ self.rows[1][3] as f32 * rhs.w,
self.rows[2][0] as f32 * rhs.x
+ self.rows[2][1] as f32 * rhs.y
+ self.rows[2][2] as f32 * rhs.z
+ self.rows[2][3] as f32 * rhs.w,
self.rows[3][0] as f32 * rhs.x
+ self.rows[3][1] as f32 * rhs.y
+ self.rows[3][2] as f32 * rhs.z
+ self.rows[3][3] as f32 * rhs.w,
)
}
}
#[test]
fn test_matrix_multiplied_by_a_tuple() {
let matrix = Matrix4::from_rows([
[1.0, 2.0, 3.0, 4.0],
[2.0, 4.0, 4.0, 2.0],
[8.0, 6.0, 4.0, 1.0],
[0.0, 0.0, 0.0, 1.0],
]);
let tuple = Tuple::new(1.0, 2.0, 3.0, 1.0);
assert_eq!(matrix * tuple, Tuple::new(18.0, 24.0, 33.0, 1.0));
}
#[test]
fn test_multiplying_identity_by_a_tuple() {
let tuple = Tuple::new(1.0, 2.0, 3.0, 4.0);
assert_eq!(IDENTITY_MATRIX4 * tuple, tuple);
}
impl ops::Div<f32> for Matrix4 {
type Output = Matrix4;
fn div(self, other: f32) -> Matrix4 {
Matrix4::from_rows([
[
self.rows[0][0] / other,
self.rows[0][1] / other,
self.rows[0][2] / other,
self.rows[0][3] / other,
],
[
self.rows[1][0] / other,
self.rows[1][1] / other,
self.rows[1][2] / other,
self.rows[1][3] / other,
],
[
self.rows[2][0] / other,
self.rows[2][1] / other,
self.rows[2][2] / other,
self.rows[2][3] / other,
],
[
self.rows[3][0] / other,
self.rows[3][1] / other,
self.rows[3][2] / other,
self.rows[3][3] / other,
],
])
}
}
impl Matrix4 {
pub fn from_rows(rows: [[f32; 4]; 4]) -> Self {
Matrix4 { rows }
}
pub fn translation(x: f32, y: f32, z: f32) -> Self {
let mut matrix = IDENTITY_MATRIX4;
matrix.rows[0][3] = x;
matrix.rows[1][3] = y;
matrix.rows[2][3] = z;
matrix
}
pub fn scaling(x: f32, y: f32, z: f32) -> Self {
let mut matrix = IDENTITY_MATRIX4;
matrix.rows[0][0] = x;
matrix.rows[1][1] = y;
matrix.rows[2][2] = z;
matrix
}
pub fn rotation_x(angle: f32) -> Self {
let mut matrix = IDENTITY_MATRIX4;
matrix.rows[1][1] = angle.cos();
matrix.rows[1][2] = -angle.sin();
matrix.rows[2][1] = angle.sin();
matrix.rows[2][2] = angle.cos();
matrix
}
pub fn rotation_y(angle: f32) -> Self {
let mut matrix = IDENTITY_MATRIX4;
matrix.rows[0][0] = angle.cos();
matrix.rows[0][2] = angle.sin();
matrix.rows[2][0] = -angle.sin();
matrix.rows[2][2] = angle.cos();
matrix
}
pub fn rotation_z(angle: f32) -> Self {
let mut matrix = IDENTITY_MATRIX4;
matrix.rows[0][0] = angle.cos();
matrix.rows[0][1] = -angle.sin();
matrix.rows[1][0] = angle.sin();
matrix.rows[1][1] = angle.cos();
matrix
}
pub fn shearing(
xy: f32,
xz: f32,
yx: f32,
yz: f32,
zx: f32,
zy: f32,
) -> Self {
let mut matrix = IDENTITY_MATRIX4;
matrix.rows[0][1] = xy;
matrix.rows[0][2] = xz;
matrix.rows[1][0] = yx;
matrix.rows[1][2] = yz;
matrix.rows[2][0] = zx;
matrix.rows[2][1] = zy;
matrix
}
pub fn transpose(&self) -> Self {
Matrix4::from_rows([
[
self.rows[0][0],
self.rows[1][0],
self.rows[2][0],
self.rows[3][0],
],
[
self.rows[0][1],
self.rows[1][1],
self.rows[2][1],
self.rows[3][1],
],
[
self.rows[0][2],
self.rows[1][2],
self.rows[2][2],
self.rows[3][2],
],
[
self.rows[0][3],
self.rows[1][3],
self.rows[2][3],
self.rows[3][3],
],
])
}
pub fn submatrix(&self, del_row: usize, del_col: usize) -> Matrix3 {
let mut values = Vec::with_capacity(3 * 3);
for (rowi, row) in self.rows.iter().enumerate() {
for (coli, value) in row.iter().enumerate() {
if rowi != del_row && coli != del_col {
values.push(value.clone());
}
}
}
Matrix3::from_rows([
[values[0], values[1], values[2]],
[values[3], values[4], values[5]],
[values[6], values[7], values[8]],
])
}
pub fn minor(&self, row: usize, col: usize) -> f32 {
self.submatrix(row, col).determinant()
}
pub fn cofactor(&self, row: usize, col: usize) -> f32 {
let mut val = self.minor(row, col);
if (row + col) % 2 != 0 {
val = -val
}
val
}
pub fn determinant(&self) -> f32 {
self.rows[0][0] * self.cofactor(0, 0)
+ self.rows[0][1] * self.cofactor(0, 1)
+ self.rows[0][2] * self.cofactor(0, 2)
+ self.rows[0][3] * self.cofactor(0, 3)
}
pub fn is_invertible(&self) -> bool {
self.determinant() != 0.0
}
pub fn inverse(&self) -> Self {
let mut cofactors = Vec::with_capacity(4 * 4);
for row in 0..4 {
for col in 0..4 {
cofactors.push(self.cofactor(row, col));
}
}
let cofactor_matrix = Matrix4::from_rows([
[cofactors[0], cofactors[1], cofactors[2], cofactors[3]],
[cofactors[4], cofactors[5], cofactors[6], cofactors[7]],
[cofactors[8], cofactors[9], cofactors[10], cofactors[11]],
[cofactors[12], cofactors[13], cofactors[14], cofactors[15]],
]);
let transposed = cofactor_matrix.transpose();
transposed / self.determinant()
}
}
const IDENTITY_MATRIX4: Matrix4 = Matrix4 {
rows: [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
],
};
#[test]
fn test_constructing_and_inspecting_a_4x4_matrix() {
let matrix = Matrix4::from_rows([
[1.0, 2.0, 3.0, 4.0],
[5.5, 6.5, 7.5, 8.5],
[9.0, 10.0, 11.0, 12.0],
[13.5, 14.5, 15.5, 16.5],
]);
assert_eq!(matrix.rows[0][0], 1.0);
assert_eq!(matrix.rows[0][3], 4.0);
assert_eq!(matrix.rows[1][0], 5.5);
assert_eq!(matrix.rows[1][2], 7.5);
assert_eq!(matrix.rows[2][2], 11.0);
assert_eq!(matrix.rows[3][0], 13.5);
assert_eq!(matrix.rows[3][2], 15.5);
}
#[test]
fn test_matrix_equality_with_identical_matrices() {
let matrix_a = Matrix4::from_rows([
[1.0, 2.0, 3.0, 4.0],
[2.0, 3.0, 4.0, 5.0],
[3.0, 4.0, 5.0, 6.0],
[4.0, 5.0, 6.0, 7.0],
]);
let matrix_b = Matrix4::from_rows([
[1.0, 2.0, 3.0, 4.0],
[2.0, 3.0, 4.0, 5.0],
[3.0, 4.0, 5.0, 6.0],
[4.0, 5.0, 6.0, 7.0],
]);
assert_eq!(matrix_a, matrix_b);
}
#[test]
fn test_matrix_equality_with_different_matrices() {
let matrix_a = Matrix4::from_rows([
[1.0, 2.0, 3.0, 4.0],
[2.0, 3.0, 4.0, 5.0],
[3.0, 4.0, 5.0, 6.0],
[4.0, 5.0, 6.0, 7.0],
]);
let matrix_b = Matrix4::from_rows([
[0.0, 2.0, 3.0, 4.0],
[2.0, 3.0, 4.0, 5.0],
[3.0, 4.0, 5.0, 6.0],
[4.0, 5.0, 6.0, 7.0],
]);
assert!(matrix_a != matrix_b);
}
#[test]
fn test_transposing_a_matrix() {
let matrix = Matrix4::from_rows([
[0.0, 9.0, 3.0, 0.0],
[9.0, 8.0, 0.0, 8.0],
[1.0, 8.0, 5.0, 3.0],
[0.0, 0.0, 5.0, 8.0],
]);
let expected = Matrix4::from_rows([
[0.0, 9.0, 1.0, 0.0],
[9.0, 8.0, 8.0, 0.0],
[3.0, 0.0, 5.0, 5.0],
[0.0, 8.0, 3.0, 8.0],
]);
assert_eq!(matrix.transpose(), expected);
}
#[test]
fn test_transposing_the_identity_matrix() {
assert_eq!(IDENTITY_MATRIX4.transpose(), IDENTITY_MATRIX4);
}
#[test]
fn test_a_submatrix_of_a_4x4_matrix_is_a_3x3_matrix() {
let matrix = Matrix4::from_rows([
[-6.0, 1.0, 1.0, 6.0],
[-8.0, 5.0, 8.0, 6.0],
[-1.0, 0.0, 8.0, 2.0],
[-7.0, 1.0, -1.0, 1.0],
]);
let expected = Matrix3::from_rows([
[-6.0, 1.0, 6.0],
[-8.0, 8.0, 6.0],
[-7.0, -1.0, 1.0],
]);
assert_eq!(matrix.submatrix(2, 1), expected);
}
#[test]
fn test_calculating_the_determinant_of_a_4x4_matrix() {
let matrix = Matrix4::from_rows([
[-2.0, -8.0, 3.0, 5.0],
[-3.0, 1.0, 7.0, 3.0],
[1.0, 2.0, -9.0, 6.0],
[-6.0, 7.0, 7.0, -9.0],
]);
assert_eq!(matrix.cofactor(0, 0), 690.0);
assert_eq!(matrix.cofactor(0, 1), 447.0);
assert_eq!(matrix.cofactor(0, 2), 210.0);
assert_eq!(matrix.cofactor(0, 3), 51.0);
assert_eq!(matrix.determinant(), -4071.0);
}
#[test]
fn test_testing_an_invertible_matrix_for_invertibility() {
let matrix = Matrix4::from_rows([
[6.0, 4.0, 4.0, 4.0],
[5.0, 5.0, 7.0, 6.0],
[4.0, -9.0, 3.0, -7.0],
[9.0, 1.0, 7.0, -6.0],
]);
assert_eq!(matrix.determinant(), -2120.0);
assert!(matrix.is_invertible());
}
#[test]
fn test_testing_a_non_invertible_matrix_for_invertibility() {
let matrix = Matrix4::from_rows([
[-4.0, 2.0, -2.0, -3.0],
[9.0, 6.0, 2.0, 6.0],
[0.0, -5.0, 1.0, -5.0],
[0.0, 0.0, 0.0, 0.0],
]);
assert_eq!(matrix.determinant(), 0.0);
assert!(!matrix.is_invertible());
}
#[test]
fn test_calculating_the_inverse_of_a_matrix() {
let matrix = Matrix4::from_rows([
[-5.0, 2.0, 6.0, -8.0],
[1.0, -5.0, 1.0, 8.0],
[7.0, 7.0, -6.0, -7.0],
[1.0, -3.0, 7.0, 4.0],
]);
let inverse = matrix.inverse();
assert_eq!(matrix.determinant(), 532.0);
assert_eq!(matrix.cofactor(2, 3), -160.0);
assert_eq!(inverse.rows[3][2], -160.0 / 532.0);
assert_eq!(matrix.cofactor(3, 2), 105.0);
assert_eq!(inverse.rows[2][3], 105.0 / 532.0);
let expected = Matrix4::from_rows([
[0.21805, 0.45113, 0.24060, -0.04511],
[-0.80827, -1.45677, -0.44361, 0.52068],
[-0.07895, -0.22368, -0.05263, 0.19737],
[-0.52256, -0.81391, -0.30075, 0.30639],
]);
assert_eq!(inverse, expected);
}
#[test]
fn test_calculating_the_inverse_of_another_matrix() {
let matrix = Matrix4::from_rows([
[8.0, -5.0, 9.0, 2.0],
[7.0, 5.0, 6.0, 1.0],
[-6.0, 0.0, 9.0, 6.0],
[-3.0, 0.0, -9.0, -4.0],
]);
let expected = Matrix4::from_rows([
[-0.15385, -0.15385, -0.28205, -0.53846],
[-0.07692, 0.12308, 0.02564, 0.03077],
[0.35897, 0.35897, 0.43590, 0.92308],
[-0.69231, -0.69231, -0.76923, -1.92308],
]);
assert_eq!(matrix.inverse(), expected);
}
#[test]
fn test_calculating_the_inverse_of_a_third_matrix() {
let matrix = Matrix4::from_rows([
[9.0, 3.0, 0.0, 9.0],
[-5.0, -2.0, -6.0, -3.0],
[-4.0, 9.0, 6.0, 4.0],
[-7.0, 6.0, 6.0, 2.0],
]);
let expected = Matrix4::from_rows([
[-0.04074, -0.07778, 0.14444, -0.22222],
[-0.07778, 0.03333, 0.36667, -0.33333],
[-0.02901, -0.14630, -0.10926, 0.12963],
[0.17778, 0.06667, -0.26667, 0.33333],
]);
assert_eq!(matrix.inverse(), expected);
}
#[test]
fn test_multiplying_a_product_by_its_inverse() {
let matrix_a = Matrix4::from_rows([
[3.0, -9.0, 7.0, 3.0],
[3.0, -8.0, 2.0, -9.0],
[-4.0, 4.0, 4.0, 1.0],
[-6.0, 5.0, -1.0, 1.0],
]);
let matrix_b = Matrix4::from_rows([
[8.0, 2.0, 2.0, 2.0],
[3.0, -1.0, 7.0, 0.0],
[7.0, 0.0, 5.0, 4.0],
[6.0, -2.0, 0.0, 5.0],
]);
let c = matrix_a * matrix_b;
assert_eq!(c * matrix_b.inverse(), matrix_a);
}
#[test]
fn test_multiplying_by_a_translation_matrix() {
let transform = Matrix4::translation(5.0, -3.0, 2.0);
let p = Tuple::point(-3.0, 4.0, 5.0);
assert_eq!(transform * p, Tuple::point(2.0, 1.0, 7.0));
}
#[test]
fn test_multiplying_by_the_inverse_of_a_translation_matrix() {
let transform = Matrix4::translation(5.0, -3.0, 2.0);
let inv = transform.inverse();
let p = Tuple::point(-3.0, 4.0, 5.0);
assert_eq!(inv * p, Tuple::point(-8.0, 7.0, 3.0));
}
#[test]
fn test_translation_does_not_affect_vectors() {
let transform = Matrix4::translation(5.0, -3.0, 2.0);
let v = Tuple::vector(-3.0, 4.0, 5.0);
assert_eq!(transform * v, v);
}
#[test]
fn test_scaling_matrix_applied_to_a_point() {
let transform = Matrix4::scaling(2.0, 3.0, 4.0);
let p = Tuple::point(-4.0, 6.0, 8.0);
assert_eq!(transform * p, Tuple::point(-8.0, 18.0, 32.0));
}
#[test]
fn test_a_scaling_matrix_applied_to_a_vector() {
let transform = Matrix4::scaling(2.0, 3.0, 4.0);
let v = Tuple::vector(-4.0, 6.0, 8.0);
assert_eq!(transform * v, Tuple::vector(-8.0, 18.0, 32.0));
}
#[test]
fn test_multiplying_by_the_inverse_of_a_scaling_matrix() {
let transform = Matrix4::scaling(2.0, 3.0, 4.0);
let inv = transform.inverse();
let v = Tuple::vector(-4.0, 6.0, 8.0);
assert_eq!(inv * v, Tuple::vector(-2.0, 2.0, 2.0));
}
#[test]
fn test_reflection_is_scaling_by_a_negative_value() {
let transform = Matrix4::scaling(-1.0, 1.0, 1.0);
let p = Tuple::point(2.0, 3.0, 4.0);
assert_eq!(transform * p, Tuple::point(-2.0, 3.0, 4.0));
}
#[test]
fn test_rotating_a_point_around_the_x_axis() {
use std::f32::consts::PI;
let p = Tuple::point(0.0, 1.0, 0.0);
let half_quarter = Matrix4::rotation_x(PI / 4.0);
let full_quarter = Matrix4::rotation_x(PI / 2.0);
assert_eq!(
half_quarter * p,
Tuple::point(0.0, 2f32.sqrt() / 2.0, 2f32.sqrt() / 2.0)
);
assert_eq!(full_quarter * p, Tuple::point(0.0, 0.0, 1.0));
}
#[test]
fn test_the_inverse_of_an_x_rotation_rotates_in_the_opposite_direction() {
use std::f32::consts::PI;
let v = Tuple::point(0.0, 1.0, 0.0);
let half_quarter = Matrix4::rotation_x(PI / 4.0);
let inv = half_quarter.inverse();
assert_eq!(
inv * v,
Tuple::point(0.0, 2f32.sqrt() / 2.0, -2f32.sqrt() / 2.0)
);
}
#[test]
fn test_rotating_a_point_around_the_y_axis() {
use std::f32::consts::PI;
let p = Tuple::point(0.0, 0.0, 1.0);
let half_quarter = Matrix4::rotation_y(PI / 4.0);
let full_quarter = Matrix4::rotation_y(PI / 2.0);
assert_eq!(
half_quarter * p,
Tuple::point(2f32.sqrt() / 2.0, 0.0, 2f32.sqrt() / 2.0)
);
assert_eq!(full_quarter * p, Tuple::point(1.0, 0.0, 0.0));
}
#[test]
fn test_rotating_a_point_around_the_z_axis() {
use std::f32::consts::PI;
let p = Tuple::point(0.0, 1.0, 0.0);
let half_quarter = Matrix4::rotation_z(PI / 4.0);
let full_quarter = Matrix4::rotation_z(PI / 2.0);
assert_eq!(
half_quarter * p,
Tuple::point(-2f32.sqrt() / 2.0, 2f32.sqrt() / 2.0, 0.0)
);
assert_eq!(full_quarter * p, Tuple::point(-1.0, 0.0, 0.0));
}
#[test]
fn test_shearing_transformation_moves_x_in_proportion_to_y() {
let transform = Matrix4::shearing(1.0, 0.0, 0.0, 0.0, 0.0, 0.0);
let p = Tuple::point(2.0, 3.0, 4.0);
assert_eq!(transform * p, Tuple::point(5.0, 3.0, 4.0));
}
#[test]
fn test_shearing_transformation_moves_x_in_proportion_to_z() {
let transform = Matrix4::shearing(0.0, 1.0, 0.0, 0.0, 0.0, 0.0);
let p = Tuple::point(2.0, 3.0, 4.0);
assert_eq!(transform * p, Tuple::point(6.0, 3.0, 4.0));
}
#[test]
fn test_shearing_transformation_moves_y_in_proportion_to_x() {
let transform = Matrix4::shearing(0.0, 0.0, 1.0, 0.0, 0.0, 0.0);
let p = Tuple::point(2.0, 3.0, 4.0);
assert_eq!(transform * p, Tuple::point(2.0, 5.0, 4.0));
}
#[test]
fn test_shearing_transformation_moves_y_in_proprtion_to_z() {
let transform = Matrix4::shearing(0.0, 0.0, 0.0, 1.0, 0.0, 0.0);
let p = Tuple::point(2.0, 3.0, 4.0);
assert_eq!(transform * p, Tuple::point(2.0, 7.0, 4.0));
}
#[test]
fn test_shearing_transformation_moves_z_in_proprtion_to_x() {
let transform = Matrix4::shearing(0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
let p = Tuple::point(2.0, 3.0, 4.0);
assert_eq!(transform * p, Tuple::point(2.0, 3.0, 6.0));
}
#[test]
fn test_shearing_transformation_moves_z_in_proprtion_to_y() {
let transform = Matrix4::shearing(0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
let p = Tuple::point(2.0, 3.0, 4.0);
assert_eq!(transform * p, Tuple::point(2.0, 3.0, 7.0));
}
#[test]
fn test_individual_transformations_are_applied_in_sequence() {
use std::f32::consts::PI;
let p = Tuple::point(1.0, 0.0, 1.0);
let a = Matrix4::rotation_x(PI / 2.0);
let b = Matrix4::scaling(5.0, 5.0, 5.0);
let c = Matrix4::translation(10.0, 5.0, 7.0);
let p2 = a * p;
assert_eq!(p2, Tuple::point(1.0, -1.0, 0.0));
let p3 = b * p2;
assert_eq!(p3, Tuple::point(5.0, -5.0, 0.0));
let p4 = c * p3;
assert_eq!(p4, Tuple::point(15.0, 0.0, 7.0));
}
#[test]
fn test_chained_transformations_must_be_applied_in_reverse_order() {
use std::f32::consts::PI;
let p = Tuple::point(1.0, 0.0, 1.0);
let a = Matrix4::rotation_x(PI / 2.0);
let b = Matrix4::scaling(5.0, 5.0, 5.0);
let c = Matrix4::translation(10.0, 5.0, 7.0);
let t = c * b * a;
assert_eq!(t * p, Tuple::point(15.0, 0.0, 7.0));
}
impl Default for Matrix4 {
fn default() -> Self {
IDENTITY_MATRIX4
}
}
#[test]
fn test_default_matrix4_is_identity() {
let default = Matrix4::default();
assert_eq!(default, IDENTITY_MATRIX4);
}
|
/// Random links on macro invocation
///
/// <https://github.com/rust-lang/rfcs/blob/master/text/0378-expr-macros.md>
/// discussion
/// <https://users.rust-lang.org/t/braces-square-brackets-and-parentheses-in-macro-call/9984/4>
///
#[macro_export]
macro_rules! vec {
// moo
( $( $x:expr ),* ) => {
{
let mut temp_vec = Vec::new();
$(
println!("moo { }", $x );
temp_vec.push($x);
)*
temp_vec
}
};
}
|
use std::fs;
use crate::wiifs;
pub mod read {
pub struct ReadInfo {
current_node: u32,
string_table: Option<String>
}
#[allow(dead_code)]
impl ReadInfo {
pub fn new() -> ReadInfo {
ReadInfo {
current_node: 1,
string_table: None
}
}
pub fn current_node(&self) -> u32 {self.current_node}
pub fn increment_node(&mut self) {self.current_node += 1}
pub fn string_table(&self) -> &Option<String> {&self.string_table}
pub fn init_string_table(&mut self, string_table: String) {self.string_table = Some(string_table)}
}
}
use read::*;
use std::io::Cursor;
use byteorder::{BigEndian, ReadBytesExt};
#[allow(dead_code)]
const IO_ERR_MSG: &str = "Something went wrong while reading the archive (I/O Error).";
#[allow(dead_code)]
const POPULATE_ERR_MSG: &str = concat!( "Something went wronte while reading data from the archive: archive data has not been read, ",
"therefore its value is None. Call the read() method to solve this error.");
#[allow(dead_code)]
const UTF8_ERR_MSG: &str = "Something went wrong while making an UTF-8 String from bytes (UTF8 Error).";
#[allow(dead_code)]
const FUNNY_ERR_MSG: &str = "God damn, are you serious? You managed to fuck it up. This is bad news, why not getting a social life instead of having a furry pfp and doing this crap all day.";
#[allow(dead_code)]
const WIIFS_FILE_ID: u32 = 0;
#[allow(dead_code)]
const WIIFS_DIR_ID: u32 = 1;
pub struct WiiArchive {
filename: String,
data: Option<Vec<u8>>,
root: wiifs::WiiFSObject,
read_info: ReadInfo
}
#[allow(dead_code)]
impl WiiArchive {
pub fn new(filename: String) -> WiiArchive {
WiiArchive {
filename,
data: None,
root: wiifs::objs::new_empty_root(),
read_info: ReadInfo::new()}
}
pub fn read(&mut self) {
self.data = Some(fs::read(self.filename.as_str()).expect(IO_ERR_MSG));
}
pub fn read_borrow(mut self) -> WiiArchive {
self.read();
self
}
pub fn populate_root(mut self) -> WiiArchive {
let file_data = match self.data {
Some(some_data) => some_data,
None => {
eprintln!("{}", POPULATE_ERR_MSG);
return self;
}
};
self.data = None;
//cursor for reading the data
let mut vec_read = Cursor::new(file_data);
//Read fst
vec_read.set_position(4);
let fst_start = vec_read.read_u32::<BigEndian>().unwrap();
let fst_size = vec_read.read_u32::<BigEndian>().unwrap();
let save_pos = fst_start + 12;
vec_read.set_position((save_pos - 4) as u64);
let last_child = vec_read.read_u32::<BigEndian>().unwrap();
//Read string table
let str_table_start = (save_pos + ((last_child - 1) * 12)) as usize;
let str_table_end = (save_pos + fst_size - 12) as usize;
//Init string table
self.read_info.init_string_table(String::from_utf8(vec_read.get_ref()
[str_table_start..str_table_end].to_vec())
.expect(UTF8_ERR_MSG));
//Read root directory
WiiArchive::read_dir(&mut self.root, &mut self.read_info, &mut vec_read, save_pos, last_child);
self
}
fn read_dir(dir: &mut wiifs::WiiFSObject, info: &mut ReadInfo, vec_read: &mut Cursor<Vec<u8>>,
mut data_pointer: u32, last_child: u32) {
while info.current_node() < last_child {
info.increment_node();
//Read current file data
vec_read.set_position(data_pointer as u64);
let value = vec_read.read_u32::<BigEndian>().unwrap();
let data_offset = vec_read.read_u32::<BigEndian>().unwrap() as usize;
let size = vec_read.read_u32::<BigEndian>().unwrap() as usize;
//get name
let mut new_obj_name = String::new();
for table_ch in info.string_table().as_ref()
.unwrap().chars().into_iter().skip((value & 0xFFFFFF) as usize) {
if table_ch == '\0' {break}
new_obj_name.push(table_ch);
}
//istantiate new wiifs object
let new_fs_obj = match value >> 24 {
WIIFS_FILE_ID => {
let mut new_obj_data: Vec<u8> = vec![];
let mut idx = 0;
for b in vec_read.get_ref().iter().skip(data_offset) {
if idx >= size {break}
new_obj_data.push(*b);
idx += 1;
}
data_pointer += 12;
wiifs::objs::new_file(new_obj_name, new_obj_data)
},
WIIFS_DIR_ID => {
let mut filled_dir = wiifs::objs::new_empty_dir(new_obj_name);
WiiArchive::read_dir(&mut filled_dir, info, vec_read, data_pointer, size as u32);
filled_dir
},
err_id => {
panic!(format!("Error with FS ID: {}. {}", err_id, FUNNY_ERR_MSG));
}
};
//finally push the object into the
dir.push_child(new_fs_obj);
}
}
pub fn get_root(&self) -> &wiifs::WiiFSObject {&self.root}
}
|
use std::fs::File;
use std::io::prelude::*;
extern crate protobuf;
use protobuf::Message;
mod protos;
use protos::payload::{CreateProgramAction,ProgramPayload, ProgramPayload_Action};
fn main() -> std::io::Result<()>{
let mut buffer = File::create("payload").unwrap();
let payload: ProgramPayload = create_program_payload();
let tnx_payload = payload.write_to_bytes()?;
buffer.write_all(&tnx_payload)?;
print!("written");
Ok(())
}
fn create_program_payload() -> ProgramPayload{
let mut create_program = CreateProgramAction::new();
create_program.set_gtin("00049000015966".to_string());
let mut payload = ProgramPayload::new();
payload.action = ProgramPayload_Action::CREATE_PROGRAM;
payload.set_create_program(create_program);
return payload;
} |
//! Console version of picross.
#![deny(missing_docs)]
use crate::cell::SimpleCell;
use itertools::Itertools;
use pancurses::{
curs_set, endwin, init_pair, initscr, noecho, start_color, Input, COLOR_BLACK, COLOR_GREEN, COLOR_PAIR, COLOR_WHITE,
};
use picore::{constraints, Cell, Picross, Puzzle};
use std::collections::HashMap;
pub mod cell;
fn demo_puzzle() -> Puzzle<SimpleCell> {
// # #
// # #
//
// # #
// ###
Puzzle::new(
constraints![
[1, SimpleCell; 1, SimpleCell]
[1, SimpleCell; 1, SimpleCell]
[]
[1, SimpleCell; 1, SimpleCell]
[3, SimpleCell]
],
constraints! {
[1, SimpleCell]
[2, SimpleCell; 1, SimpleCell]
[1, SimpleCell]
[2, SimpleCell; 1, SimpleCell]
[1, SimpleCell]
},
)
}
const COLOR_SOLVED: i16 = 1;
const COLOR_SELECTION: i16 = 2;
const COLOR_SELECTION_SOLVED: i16 = 3;
fn main() {
let mut picross = Picross::new(demo_puzzle());
let window = initscr();
curs_set(0);
noecho();
start_color();
init_pair(COLOR_SOLVED, COLOR_GREEN, COLOR_BLACK);
init_pair(COLOR_SELECTION, COLOR_BLACK, COLOR_WHITE);
init_pair(COLOR_SELECTION_SOLVED, COLOR_BLACK, COLOR_GREEN);
window.keypad(true);
let mut row_sizes = vec![0; picross.row_constraints().iter().map(|c| c.len()).max().unwrap_or(0)];
let mut col_sizes = vec![0; picross.column_constraints().len()];
for rc in picross.row_constraints() {
for (i, entry) in rc.iter().enumerate() {
let text_size = ((entry.size as f32).log10() as usize) + 1;
if text_size > row_sizes[i] {
row_sizes[i] = text_size;
}
}
}
for (i, cc) in picross.column_constraints().iter().enumerate() {
for entry in cc {
let text_size = ((entry.size as f32).log10() as usize) + 1;
if text_size > col_sizes[i] {
col_sizes[i] = text_size;
}
}
}
let row_label_len = (row_sizes.iter().sum::<usize>() + row_sizes.len()) as i32;
let col_label_len = picross.column_constraints().iter().map(|c| c.len()).max().unwrap_or(0) as i32;
let board_base = (col_label_len + 1, row_label_len + 1);
let mut board_pos = HashMap::new();
for r in 0..picross.height() {
let mut col_offset = 0;
for c in 0..picross.width() {
board_pos.insert((r, c), (r as i32, col_offset as i32));
col_offset += col_sizes[c] + 1;
}
}
let mut pos = (0, 0);
let mut solved = false;
loop {
window.clear();
window.mvprintw(1, window.get_max_x() - 20, format!("{:?}", pos));
{
let (row_status, column_status) = picross.status();
window.mvprintw(
2,
window.get_max_x() - 23,
format!("r: {}", row_status.iter().map(|s| if *s { "1" } else { "0" }).join("")),
);
window.mvprintw(
3,
window.get_max_x() - 23,
format!(
"c: {}",
column_status.iter().map(|s| if *s { "1" } else { "0" }).join("")
),
);
}
for (i, constraint) in picross.row_constraints().iter().enumerate() {
let mut offset = 0;
for (j, entry) in constraint.iter().enumerate() {
window.mvprintw(
board_base.0 + i as i32,
board_base.1 - row_label_len + offset,
format!("{:width$}", entry.size, width = row_sizes[j]),
);
offset += row_sizes[j] as i32 + 1;
}
}
let mut offset = 0;
for (i, constraint) in picross.column_constraints().iter().enumerate() {
for (j, entry) in constraint.iter().enumerate() {
window.mvprintw(
board_base.0 - col_label_len + j as i32,
board_base.1 + offset,
format!("{:width$}", entry.size, width = col_sizes[i]),
);
}
offset += col_sizes[i] as i32 + 1;
}
for (r, c, cell) in picross.cells() {
if solved {
window.attron(COLOR_PAIR(COLOR_SOLVED as _));
}
if r == pos.0 && c == pos.1 {
window.attron(COLOR_PAIR(if solved {
COLOR_SELECTION_SOLVED
} else {
COLOR_SELECTION
} as _));
}
window.mvaddch(
board_base.0 + board_pos[&(r, c)].0,
board_base.1 + board_pos[&(r, c)].1,
SimpleCell::char_repr(cell),
);
if solved {
window.attroff(COLOR_PAIR(COLOR_SOLVED as _));
}
if r == pos.0 && c == pos.1 {
window.attroff(COLOR_PAIR(if solved {
COLOR_SELECTION_SOLVED
} else {
COLOR_SELECTION
} as _));
}
}
match window.getch() {
Some(Input::KeyDC) => break,
Some(Input::KeyLeft) => pos.1 = (pos.1 + picross.width() - 1) % picross.width(),
Some(Input::KeyRight) => pos.1 = (pos.1 + picross.width() + 1) % picross.width(),
Some(Input::KeyUp) => pos.0 = (pos.0 + picross.height() - 1) % picross.height(),
Some(Input::KeyDown) => pos.0 = (pos.0 + picross.height() + 1) % picross.height(),
Some(Input::Character('c')) => {
solved = match picross.get(pos.0, pos.1) {
Cell::Empty | Cell::Filled(_) => picross.cross_out(pos.0, pos.1),
Cell::CrossedOut => picross.clear_at(pos.0, pos.1),
}
}
Some(Input::Character(' ')) => {
solved = match picross.get(pos.0, pos.1) {
Cell::Empty | Cell::CrossedOut => picross.place_at(SimpleCell, pos.0, pos.1),
Cell::Filled(_) => picross.clear_at(pos.0, pos.1),
}
}
_ => {}
};
}
endwin();
}
|
extern crate rocksdb;
mod aggregates;
mod error;
mod filters;
pub mod index;
mod json_shred;
pub mod json_value;
mod key_builder;
mod parser;
pub mod query;
pub mod repl;
mod returnable;
mod snapshot;
mod stems;
|
fn main() {
let digits: u32 = 8;
gen(digits);
}
// fn read_from_file() -> u32 {
// let mut file = File::open("output.txt").expect("Unable to open file");
// let buffer = BufReader::new(file);
// let mut res: u32 = 0;
// for line in buffer.lines() {
// let num: u32 = line.unwrap().trim().parse().unwrap();
// if num % 5 == 3 {
// res += 1;
// println!("num: {}", num);
// }
// }
// res
// }
fn gen_rec(n: u32, lvl: u32, nr_of_digits: u32, buffer: &mut BufWriter<std::fs::File>) {
let mut n = n;
let mut lvl = lvl;
let is_odd = nr_of_digits % 2 == 1;
if lvl == 0 {
// most inner level
let temp = nr_of_digits / 2;
let add = if is_odd {
10u32.pow(temp)
} else {
11 * 10u32.pow(temp - 1)
};
// special case when the num_of_digits is equals to 2
let i = if nr_of_digits == 2 { 1 } else { 0 };
for _ in i..=9 {
writeln!(buffer, "{}", n).expect("Unable to writeln!");
// println!("{}", n);
n += add;
}
} else if lvl == (nr_of_digits - 1) / 2 {
//most outter level
let add = 10u32.pow(nr_of_digits - 1) + 1;
for _ in 1..=9 {
gen_rec(n, lvl - 1, nr_of_digits, buffer);
n += add;
}
} else {
// other inner levels
let tmp = nr_of_digits / 2;
let add = if is_odd {
10u32.pow(tmp + lvl) + 10u32.pow(tmp - lvl)
} else {
10u32.pow(tmp + lvl) + 10u32.pow(tmp - lvl - 1)
};
println!("***********{}", add);
for _ in 0..=9 {
gen_rec(n, lvl - 1, nr_of_digits, buffer);
n += add;
}
}
}
use std::fs::File;
use std::io::prelude::*;
use std::io::{BufRead, BufReader, BufWriter};
fn gen(nr_of_digits: u32) {
let outer_lvl = (nr_of_digits - 1) / 2;
let init = if nr_of_digits == 1 {
0
} else {
10u32.pow(nr_of_digits - 1) + 1
};
let mut file = File::create("output.txt").expect("Unable to create file");
let mut buffer = BufWriter::new(file);
gen_rec(init, outer_lvl, nr_of_digits, &mut buffer);
}
// fn gen_rec_odd(n: u32, lvl: u32, nr_of_digits: u32, buffer: &mut BufWriter<std::fs::File>) {
// let mut n = n;
// let mut lvl = lvl;
// if lvl == 0 {
// // most inner level
// // match nr_of_digits{
// // 1=> { add = 1},
// // 3=> { add = 010},
// // 5=> { add = 00100},
// // ...
// // }
// let add = 10u32.pow(nr_of_digits / 2);
// for _ in 0..=9 {
// writeln!(buffer, "{}", n).expect("Unable to writeln!");
// println!("{}", n);
// n += add;
// }
// } else if lvl == (nr_of_digits - 1) / 2 {
// //most outter level
// // match nr_of_digits{
// // 3=> { add = 101},
// // 5=> { add = 10001},
// // 7=> { add = 1000001},
// // ...
// // }
// let add = 10u32.pow(nr_of_digits - 1) + 1;
// for _ in 1..=9 {
// gen_rec_odd(n, lvl - 1, nr_of_digits, buffer);
// n += add;
// }
// } else {
// // other inner levels
// // match nr_of_digits{
// // 5=> { add = 1010 },
// // 7=> { add = 10100 or 100010 },
// // 9=> { add = 101000 or 1000100 or 10000010 },
// // ...
// // }
// let tmp = nr_of_digits / 2;
// let add = 10u32.pow(tmp + lvl) + 10u32.pow(tmp - lvl);
// println!("***********{}", add);
// for _ in 0..=9 {
// gen_rec_odd(n, lvl - 1, nr_of_digits, buffer);
// n += add;
// }
// }
// }
// fn gen_rec_even(n: u32, lvl: u32, nr_of_digits: u32, buffer: &mut BufWriter<std::fs::File>) {
// let mut n = n;
// let mut lvl = lvl;
// if lvl == 0 {
// // most inner level
// // match nr_of_digits{
// // 2=> { add = 11},
// // 4=> { add = 110},
// // 6=> { add = 1100},
// // ...
// // }
// let temp = (nr_of_digits - 1) / 2;
// let add = 11 * 10u32.pow(temp);
// for _ in 0..=9 {
// writeln!(buffer, "{}", n).expect("Unable to writeln!");
// println!("{}", n);
// n += add;
// }
// } else if lvl == (nr_of_digits - 1) / 2 {
// //most outter level
// // match nr_of_digits{
// // 4=> { add = 1001},
// // 6=> { add = 100001},
// // 8=> { add = 10000001},
// // ...
// // }
// let add = 10u32.pow(nr_of_digits - 1) + 1;
// for _ in 1..=9 {
// gen_rec_even(n, lvl - 1, nr_of_digits, buffer);
// n += add;
// }
// } else {
// // other inner levels
// // match nr_of_digits{
// // 6=> { add = 10010},
// // 8=> { add = 100100 or 1000010},
// // 10=> { add = 1001000 or 10000100 or 100000010 },
// // ...
// // }
// let tmp = nr_of_digits / 2;
// let add = 10u32.pow(tmp + lvl) + 10u32.pow(tmp - lvl - 1);
// println!("***********{}", add);
// for _ in 0..=9 {
// gen_rec_even(n, lvl - 1, nr_of_digits, buffer);
// n += add;
// }
// }
// }
|
use std::fmt;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use base64::encode;
#[derive(Debug, Clone)]
pub enum ChasmError {
InvalidCommitRequest,
InvalidCommitJSON,
FilenameMissing,
PostfolderMissing,
ImageDataMissing,
RepoMissing,
AccessTokenMissing,
}
impl fmt::Display for ChasmError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ChasmError::InvalidCommitRequest => write!(f, "Invalid Commit Request"),
ChasmError::InvalidCommitJSON => write!(f, "Invalid Commit JSON"),
ChasmError::FilenameMissing => write!(f, "Filename missing"),
ChasmError::PostfolderMissing => write!(f, "Postfolder missing"),
ChasmError::ImageDataMissing => write!(f, "Image Data Missing"),
ChasmError::RepoMissing => write!(f, "Repo Missng"),
ChasmError::AccessTokenMissing => write!(f, "Access Token Missing"),
}
}
}
#[derive(Deserialize, Serialize)]
pub struct CommitContent {
pub message: String,
pub content: String,
pub path: String,
}
impl CommitContent {
pub fn new(message: String, content: String, path: String) -> CommitContent {
CommitContent {
message: message,
content: encode(content),
path: path,
}
}
pub fn new_from_image(message: String, content: Vec<u8>, path: String) -> CommitContent {
CommitContent {
message: message,
content: encode(content),
path: path,
}
}
}
#[derive(Deserialize, Serialize)]
pub struct PostContent {
pub date: DateTime<Utc>,
pub postfolder: String,
pub title: Option<String>,
pub content: Vec<ContentPart>,
pub location: ContentLocation,
}
#[derive(Deserialize, Serialize)]
#[serde(tag = "type")]
pub enum ContentPart {
Header {text: String},
Paragraph {text: String},
Image {filename: String},
Link {title: String, url: String},
}
#[derive(Deserialize, Serialize)]
pub struct CommitResponse {
pub content: CommitResponseContent,
}
#[derive(Deserialize, Serialize)]
pub struct CommitResponseContent {
pub download_url: String,
}
#[derive(Deserialize, Serialize)]
pub struct ImageUploadResponse {
pub commit_response: Option<CommitResponse>,
pub filename: String
}
#[derive(Deserialize, Serialize)]
#[serde(tag = "type")]
pub enum ContentLocation {
Github { repo: String, access_token: String },
Local { path: String }
} |
#[macro_use]
extern crate rbatis;
pub mod model;
use crate::model::{init_db, BizActivity};
use rbatis::rbdc::datetime::FastDateTime;
use rbatis::sql::page::PageRequest;
use rbs::Value;
//crud!(BizActivity {},"biz_activity");//custom table name
//impl_select!(BizActivity{select_all_by_id(table_name:&str,id:&str) => "`where id = #{id}`"}); //custom table name
crud!(BizActivity {});
impl_select!(BizActivity{select_all_by_id(id:&str,name:&str) => "`where id = #{id} and name = #{name}`"});
impl_select!(BizActivity{select_by_id(id:&str) -> Option => "`where id = #{id} limit 1`"});
impl_update!(BizActivity{update_by_name(name:&str) => "`where id = '2'`"});
impl_delete!(BizActivity {delete_by_name(name:&str) => "`where name= '2'`"});
impl_select_page!(BizActivity{select_page() =>"
if !sql.contains('count'):
`order by create_time desc`"});
impl_select_page!(BizActivity{select_page_by_name(name:&str) =>"
if name != null && name != '':
`where name != #{name}`
if name == '':
`where name != ''`"});
// sql() method write in rbatis::sql::methods.rs
use rbatis::sql::IntoSql;
use rbs::value::map::ValueMap;
impl_select!(BizActivity{select_by_method(ids:&[&str],logic:ValueMap) -> Option => "`where ${logic.sql()} and id in ${ids.sql()} limit 1`"});
#[tokio::main]
pub async fn main() {
fast_log::init(
fast_log::Config::new()
.console()
.level(log::LevelFilter::Debug),
)
.expect("rbatis init fail");
let mut rb = init_db().await;
let t = BizActivity {
id: Some("2".into()),
name: Some("2".into()),
pc_link: Some("2".into()),
h5_link: Some("2".into()),
pc_banner_img: None,
h5_banner_img: None,
sort: Some("2".to_string()),
status: Some(2),
remark: Some("2".into()),
create_time: Some(FastDateTime::now()),
version: Some(1),
delete_flag: Some(1),
};
let tables = [t.clone(), {
let mut t3 = t.clone();
t3.id = "3".to_string().into();
t3
}];
let data = BizActivity::insert(&mut rb, &t).await;
println!("insert = {:?}", data);
let _data = BizActivity::delete_by_name(&mut rb, "2").await;
let _data = BizActivity::delete_by_name(&mut rb, "3").await;
let data = BizActivity::insert_batch(&mut rb, &tables, 10).await;
println!("insert_batch = {:?}", data);
let data = BizActivity::update_by_column_batch(&mut rb, &tables, "id").await;
println!("update_by_column_batch = {:?}", data);
let data = BizActivity::select_all_by_id(&mut rb, "1", "1").await;
println!("select_all_by_id = {:?}", data);
let data = BizActivity::select_by_id(&mut rb, "1").await;
println!("select_by_id = {:?}", data);
let data = BizActivity::update_by_column(&mut rb, &t, "id").await;
println!("update_by_column = {:?}", data);
let data = BizActivity::update_by_name(&mut rb, &t, "test").await;
println!("update_by_name = {:?}", data);
let data = BizActivity::select_page(&mut rb, &PageRequest::new(1, 10)).await;
println!("select_page = {:?}", data);
let data = BizActivity::select_page_by_name(&mut rb, &PageRequest::new(1, 10), "").await;
println!("select_page_by_name = {:?}", data);
let data = BizActivity::delete_by_column(&mut rb, "id", "2").await;
println!("delete_by_column = {:?}", data);
let data = BizActivity::delete_by_name(&mut rb, "2").await;
println!("delete_by_column = {:?}", data);
let data = BizActivity::select_in_column(&mut rb, "id", &["1", "2", "3"]).await;
println!("select_in_column = {:?}", data);
let mut logic = ValueMap::new();
logic.insert("id = ".into(), Value::I32(1));
logic.insert("and id != ".into(), Value::I32(2));
let data = BizActivity::select_by_method(&mut rb, &["1", "2"], logic).await;
println!("select_by_method = {:?}", data);
let data = BizActivity::delete_in_column(&mut rb, "id", &["1", "2", "3"]).await;
println!("delete_in_column = {:?}", data);
}
|
use std::fmt;
#[derive(Default, Debug, PartialEq)]
pub struct Filter {
pub name: Option<String>,
pub domain: Option<String>,
pub stype: Option<String>,
pub protocol: Option<String>,
pub port: Option<u16>,
}
impl Filter {
pub fn new() -> Filter {
Filter {
..Default::default()
}
}
pub fn kind(&self) -> Option<String> {
// Prefix stype and protocol with underscores
if let Some(stype) = &self.stype {
if let Some(protocol) = &self.protocol {
return Some(format!("_{}._{}", stype, protocol));
}
}
return None;
}
}
impl fmt::Display for Filter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut result: Vec<String> = Vec::new();
let kind = self.kind();
if let Some(name) = &self.name {
result.push(format!("name=\"{}\"", name.to_owned()));
}
if let Some(domain) = &self.domain {
result.push(format!("domain=\"{}\"", domain.to_owned()));
}
if let Some(kind) = kind {
result.push(format!("kind=\"{}\"", kind));
}
if let Some(port) = self.port {
result.push(format!("port=\"{}\"", port.to_string()));
}
let result = result.join(" ");
write!(f, "{}", result)
}
}
#[cfg(test)]
mod tests {
use super::Filter;
#[test]
fn test_kind() {
let f = Filter {
stype: Some("rust".to_string()),
protocol: Some("tcp".to_string()),
..Default::default()
};
assert_eq!(Some("_rust._tcp".to_string()), f.kind())
}
#[test]
fn test_fmt() {
let f = Filter {
stype: Some("rust".to_string()),
protocol: Some("tcp".to_string()),
..Default::default()
};
assert_eq!(format!("{}", f), "kind=\"_rust._tcp\"");
}
}
|
use std::net::SocketAddr;
use std::default::Default;
use std::convert::{TryFrom, TryInto};
use url::{Url, ParseError};
#[derive(Debug, PartialEq, Clone)]
pub struct Credential {
name: String,
password: String
}
#[derive(Debug, PartialEq, Clone)]
pub struct Host {
target: SocketAddr,
vhost: String,
secure: bool
}
// pub type Resource = (Credential, Host);
// impl TryFrom<Url> for Resource {
// type Error = ParseError;
// fn try_from(value: Url) -> Result<Self, Self::Error> {
// let vhost = value.path_segments().unwrap_or_else(vec![]).first();
// let secure = match value.scheme() {
// "amqp" => false,
// "amqps" => true
// };
// let target = value.host_str().unwrap_or("127.0.0.1");
// let username = value.username();
// let password = value.password().unwrap_or("guest");
// Ok((
// Credential {
// username: username, password: password
// },
// Host {
// target: target, vhost: vhost, secure: secure
// }
// ))
// }
// }
#[derive(Debug, PartialEq, Clone)]
pub struct Limit {
pub channel: u16,
pub frame: u32
}
impl Default for Credential {
fn default() -> Credential {
Credential {
name: String::from("guest"),
password: String::from("guest")
}
}
}
/// we don't support tls yet
impl Default for Host {
fn default() -> Host {
Host {
target: "127.0.0.1:5673".parse().unwrap(),
secure: false,
vhost: String::from("/")
}
}
}
impl Default for Limit {
fn default() -> Limit {
Limit {
channel: 65535,
frame: 131072
}
}
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
pub fn derive_any_lifetime(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as DeriveInput);
// We can deal with exactly:
// Foo<'v> OR Foo
// So see which case we have and abort otherwise
if input.generics.const_params().count() > 0
|| input.generics.type_params().count() > 0
|| input.generics.lifetimes().count() > 1
{
return syn::Error::new_spanned(
input.generics,
"Can't derive AnyLifetime for types with type parameters or more than one lifetime",
)
.into_compile_error()
.into();
}
let has_lifetime = input.generics.lifetimes().count() == 1;
let name = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let gen = if has_lifetime {
quote! {
unsafe impl #impl_generics gazebo::any::AnyLifetime #impl_generics for #name #ty_generics #where_clause {
fn static_type_id() -> std::any::TypeId {
std::any::TypeId::of::<#name<'static>>()
}
fn static_type_of(&self) -> std::any::TypeId {
Self::static_type_id()
}
}
}
} else {
quote! {
unsafe impl<'a> gazebo::any::AnyLifetime<'a> for #name #ty_generics #where_clause {
fn static_type_id() -> std::any::TypeId {
std::any::TypeId::of::<#name>()
}
fn static_type_of(&self) -> std::any::TypeId {
Self::static_type_id()
}
}
}
};
gen.into()
}
|
/*
* Copyright Stalwart Labs Ltd. See the COPYING
* file at the top-level directory of this distribution.
*
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
* https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
*/
use crate::{
core::{
request::ResultReference,
set::{from_timestamp, SetError},
RequestParams,
},
Error,
};
use ahash::AHashMap;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use super::{Email, Property};
#[derive(Debug, Clone, Serialize)]
pub struct EmailImportRequest {
#[serde(rename = "accountId")]
account_id: String,
#[serde(rename = "ifInState")]
#[serde(skip_serializing_if = "Option::is_none")]
if_in_state: Option<String>,
emails: AHashMap<String, EmailImport>,
}
#[derive(Debug, Clone, Serialize)]
pub struct EmailImport {
#[serde(skip)]
create_id: usize,
#[serde(rename = "blobId")]
blob_id: String,
#[serde(rename = "mailboxIds")]
#[serde(skip_serializing_if = "Option::is_none")]
mailbox_ids: Option<AHashMap<String, bool>>,
#[serde(rename = "#mailboxIds")]
#[serde(skip_deserializing)]
#[serde(skip_serializing_if = "Option::is_none")]
mailbox_ids_ref: Option<ResultReference>,
#[serde(rename = "keywords")]
keywords: AHashMap<String, bool>,
#[serde(rename = "receivedAt")]
#[serde(skip_serializing_if = "Option::is_none")]
received_at: Option<DateTime<Utc>>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct EmailImportResponse {
#[serde(rename = "accountId")]
account_id: String,
#[serde(rename = "oldState")]
old_state: Option<String>,
#[serde(rename = "newState")]
new_state: String,
#[serde(rename = "created")]
created: Option<AHashMap<String, Email>>,
#[serde(rename = "notCreated")]
not_created: Option<AHashMap<String, SetError<Property>>>,
}
impl EmailImportRequest {
pub fn new(params: RequestParams) -> Self {
EmailImportRequest {
account_id: params.account_id,
if_in_state: None,
emails: AHashMap::new(),
}
}
pub fn account_id(&mut self, account_id: impl Into<String>) -> &mut Self {
self.account_id = account_id.into();
self
}
pub fn if_in_state(&mut self, if_in_state: impl Into<String>) -> &mut Self {
self.if_in_state = Some(if_in_state.into());
self
}
pub fn email(&mut self, blob_id: impl Into<String>) -> &mut EmailImport {
let create_id = self.emails.len();
let create_id_str = format!("i{}", create_id);
self.emails.insert(
create_id_str.clone(),
EmailImport::new(blob_id.into(), create_id),
);
self.emails.get_mut(&create_id_str).unwrap()
}
}
impl EmailImport {
fn new(blob_id: String, create_id: usize) -> Self {
EmailImport {
create_id,
blob_id,
mailbox_ids: None,
mailbox_ids_ref: None,
keywords: AHashMap::new(),
received_at: None,
}
}
pub fn mailbox_ids<T, U>(&mut self, mailbox_ids: T) -> &mut Self
where
T: IntoIterator<Item = U>,
U: Into<String>,
{
self.mailbox_ids = Some(mailbox_ids.into_iter().map(|s| (s.into(), true)).collect());
self.mailbox_ids_ref = None;
self
}
pub fn mailbox_ids_ref(&mut self, reference: ResultReference) -> &mut Self {
self.mailbox_ids_ref = reference.into();
self.mailbox_ids = None;
self
}
pub fn keywords<T, U>(&mut self, keywords: T) -> &mut Self
where
T: IntoIterator<Item = U>,
U: Into<String>,
{
self.keywords = keywords.into_iter().map(|s| (s.into(), true)).collect();
self
}
pub fn received_at(&mut self, received_at: i64) -> &mut Self {
self.received_at = Some(from_timestamp(received_at));
self
}
pub fn create_id(&self) -> String {
format!("i{}", self.create_id)
}
}
impl EmailImportResponse {
pub fn account_id(&self) -> &str {
&self.account_id
}
pub fn old_state(&self) -> Option<&str> {
self.old_state.as_deref()
}
pub fn new_state(&self) -> &str {
&self.new_state
}
pub fn take_new_state(&mut self) -> String {
std::mem::take(&mut self.new_state)
}
pub fn created(&mut self, id: &str) -> crate::Result<Email> {
if let Some(result) = self.created.as_mut().and_then(|r| r.remove(id)) {
Ok(result)
} else if let Some(error) = self.not_created.as_mut().and_then(|r| r.remove(id)) {
Err(error.to_string_error().into())
} else {
Err(Error::Internal(format!("Id {} not found.", id)))
}
}
pub fn created_ids(&self) -> Option<impl Iterator<Item = &String>> {
self.created.as_ref().map(|map| map.keys())
}
pub fn not_created_ids(&self) -> Option<impl Iterator<Item = &String>> {
self.not_created.as_ref().map(|map| map.keys())
}
}
|
// This crate implements ECVRF based on the Edwards25519 elliptic curve. The
// code is based on section 5 of draft-irtf-cfrg-vrf-15 (version 15):
// https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
//
// The cipher suite is ECVRF-EDWARDS25519-SHA512-ELL2 (4), but the method for
// ciphersuite ECVRF-EDWARDS25519-SHA512-TAI (3) is present as well, and can be
// uncommented. ELL2 uses the edwards25519-hash crate to convert arbitrary
// strings to elliptic curve points, and TAI simply uses SHA512 directly and
// attempts to decompress it to an elliptic curve point. If it fails it simply
// increments a counter to get a new hash value and tries again.
// The step comments refer to the corresponding steps in the IETF pseudocode for
// comparison with hacspec
use hacspec_lib::*;
use hacspec_edwards25519::*;
use hacspec_sha512::*;
use hacspec_edwards25519_hash::*;
#[derive(Debug)]
enum Errorec {
FailedVerify,
MessageTooLarge,
InvalidProof,
InvalidPublicKey,
FailedDecompression,
FailedE2C,
}
pub type ByteSeqResult = Result<ByteSeq, Errorec>;
type ProofResult = Result<(EdPoint, Scalar, Scalar), Errorec>;
type EdPointResult = Result<EdPoint, Errorec>;
public_nat_mod!(
type_name: LargeMod,
type_of_canvas: LargeModCanvas,
bit_size_of_field: 256,
modulo_value: "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
);
array!(ArrLargeMod, 4, U64);
const Q: ArrLargeMod = ArrLargeMod(secret_array!(
U64,
[
0x7fffffffffffffffu64,
0xffffffffffffffffu64,
0xffffffffffffffffu64,
0xffffffffffffffedu64
]
));
const C_LEN: usize = 16usize;
const PT_LEN: usize = 32usize;
const Q_LEN: usize = 32usize;
bytes!(IntByte, 1);
#[rustfmt::skip]
const ZERO: IntByte = IntByte(secret_array!(U8, [0x00u8]));
#[rustfmt::skip]
const ONE: IntByte = IntByte(secret_array!(U8, [0x01u8]));
#[rustfmt::skip]
const TWO: IntByte = IntByte(secret_array!(U8, [0x02u8]));
#[rustfmt::skip]
const THREE: IntByte = IntByte(secret_array!(U8, [0x03u8]));
#[rustfmt::skip]
const FOUR: IntByte = IntByte(secret_array!(U8, [0x04u8]));
// Change to THREE to use encode_to_curve_try_and_increment
// const SUITE_STRING: IntByte = THREE;
const SUITE_STRING: IntByte = FOUR;
bytes!(DST, 39);
#[rustfmt::skip]
// "ECVRF_edwards25519_XMD:SHA-512_ELL2_NU_"
const H2C_SUITE_ID_STRING: DST = DST(secret_array!(
U8,
[
0x45u8, 0x43u8, 0x56u8, 0x52u8, 0x46u8, 0x5fu8,
0x65u8, 0x64u8, 0x77u8, 0x61u8, 0x72u8, 0x64u8, 0x73u8, 0x32u8,
0x35u8, 0x35u8, 0x31u8, 0x39u8, 0x5fu8, 0x58u8, 0x4du8, 0x44u8,
0x3au8, 0x53u8, 0x48u8, 0x41u8, 0x2du8, 0x35u8, 0x31u8, 0x32u8,
0x5fu8, 0x45u8, 0x4cu8, 0x4cu8, 0x32u8, 0x5fu8, 0x4eu8, 0x55u8 ,
0x5fu8
]
));
// See section 5.4.1.1 (ciphersuite 3) for the TAI method:
// https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
// Note that this should not be used when alpha should remain secret.
// Fails with very low probability if unsuccessful after 256 attempts.
// Attempts to convert an arbitrary string to an elliptic curve element by
// iteratively using sha512 and trying to decompress the output to an elliptic
// curve point
fn ecvrf_encode_to_curve_try_and_increment(
encode_to_curve_salt: &ByteSeq, alpha: &ByteSeq
) -> EdPointResult {
let mut h: Option<EdPoint> = Option::<EdPoint>::None;
let mut x = Ed25519FieldElement::ZERO();
for _ctr in 1..256 {
if h.clone() == Option::<EdPoint>::None {
let ctr_string = x.to_byte_seq_be().slice(31,1);
let hash_string = sha512(&SUITE_STRING
.concat(&ONE)
.concat(encode_to_curve_salt)
.concat(alpha)
.concat(&ctr_string)
.concat(&ZERO));
h = decompress(CompressedEdPoint::from_slice(&hash_string, 0, 32));
x = x + Ed25519FieldElement::ONE();
}
}
let h = h.ok_or(Errorec::FailedE2C)?;
Ok(point_mul_by_cofactor(h))
}
// See section 5.4.1.2 (ciphersuite 4) for the ELL2 method:
// https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
// Uses the edwards25519-hash crate to convert an arbitrary string to an
// elliptic curve point
fn ecvrf_encode_to_curve_h2c_suite(
encode_to_curve_salt: &ByteSeq, alpha: &ByteSeq
) -> EdPointResult {
let string_to_be_hashed = encode_to_curve_salt.concat(alpha);
let dst = H2C_SUITE_ID_STRING.concat(&SUITE_STRING);
let h = ed_encode_to_curve(&string_to_be_hashed, &dst);
let h = h.ok().ok_or(Errorec::FailedE2C)?;
Ok(h)
}
// See section 5.4.2 for nonce generation:
// https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
// This implements section 5.4.2.2 that is also based on RFC8032
fn ecvrf_nonce_generation(
sk: SecretKey, h_string: &ByteSeq
) -> Scalar {
let hashed_sk_string = sha512(&sk.to_le_bytes());
let truncated_hashed_sk_string = hashed_sk_string.slice(32,32);
let k_string = sha512(&truncated_hashed_sk_string.concat(h_string));
let nonce = BigScalar::from_byte_seq_le(k_string);
let nonceseq = nonce.to_byte_seq_le().slice(0, 32);
Scalar::from_byte_seq_le(nonceseq)
}
// See section 5.4.3 for challenge generation
// https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
fn ecvrf_challenge_generation(
p1: EdPoint, p2: EdPoint, p3: EdPoint, p4: EdPoint, p5: EdPoint
) -> Scalar {
let string = SUITE_STRING
.concat(&TWO)
.concat(&encode(p1))
.concat(&encode(p2))
.concat(&encode(p3))
.concat(&encode(p4))
.concat(&encode(p5))
.concat(&ZERO);
let c_string = sha512(&string);
let truncated_c_string= c_string.slice(0, C_LEN).concat(&ByteSeq::new(16));
Scalar::from_byte_seq_le(truncated_c_string)
}
// See section 5.4.4 for decode proof
// https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
fn ecvrf_decode_proof(pi: &ByteSeq) -> ProofResult {
let gamma_string = pi.slice(0, PT_LEN);
let c_string = pi.slice(PT_LEN, C_LEN);
let s_string = pi.slice(PT_LEN + C_LEN, Q_LEN);
let gamma = decompress(CompressedEdPoint::from_slice(&gamma_string, 0, 32))
.ok_or(Errorec::InvalidProof)?;
let c = Scalar::from_byte_seq_le(c_string.concat(&ByteSeq::new(16)));
let s = Scalar::from_byte_seq_le(s_string.clone());
let s_test = LargeMod::from_byte_seq_le(s_string);
let q = LargeMod::from_byte_seq_be(&Q.to_be_bytes());
if s_test >= q {
ProofResult::Err(Errorec::InvalidProof)
} else {
ProofResult::Ok((gamma, c, s))
}
}
// See section 5.4.5 validate key
// https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
fn ecvrf_validate_key(y: PublicKey) -> Result<(), Errorec> {
let y = decompress(y).ok_or(Errorec::InvalidPublicKey)?;
let y_prime = point_mul_by_cofactor(y);
if y_prime == point_identity() {
Err(Errorec::InvalidPublicKey)
} else {
Ok(())
}
}
// This function is to construct a proof based on alpha. See section 5.1:
// https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
// Currently the code uses the ELL2 method, but this can be swapped by calling
// the TAI method instead. Proofs constructed with one of the methods can only
// be verified by a verify algorithm that uses the same method.
pub fn ecvrf_prove(
sk: SecretKey, alpha: &ByteSeq
) -> ByteSeqResult {
let b = decompress(BASE).ok_or(Errorec::FailedDecompression)?;
// STEP 1
let (x, _) = secret_expand(sk);
let x = Scalar::from_byte_seq_le(x);
let y = point_mul(x, b);
let pk = compress(y);
// STEP 2
let encode_to_curve_salt = pk.slice(0,32);
// Swap lines to use encode_to_curve_try_and_increment
let h = ecvrf_encode_to_curve_h2c_suite(&encode_to_curve_salt, alpha)?;
// let h = ecvrf_encode_to_curve_try_and_increment(&encode_to_curve_salt, alpha)?;
// STEP 3
let h_string = encode(h);
// STEP 4
let gamma = point_mul(x, h);
// STEP 5
let k = ecvrf_nonce_generation(sk, &h_string);
// STEP 6
let u = point_mul(k, b);
let v = point_mul(k, h);
let c = ecvrf_challenge_generation(y, h, gamma, u, v);
// STEP 7
let s = k + (c * x);
// STEP 8 and 9
ByteSeqResult::Ok(encode(gamma)
.concat(&Scalar::to_byte_seq_le(c).slice(0, C_LEN))
.concat(&Scalar::to_byte_seq_le(s).slice(0, Q_LEN))
.slice(0, C_LEN + Q_LEN + PT_LEN))
}
// This function simply computes the hash of a proof. See section 5.2:
// https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
pub fn ecvrf_proof_to_hash(pi: &ByteSeq) -> ByteSeqResult {
// STEP 1, 2 and 3
let (gamma, _, _) = ecvrf_decode_proof(pi)?;
// STEP 4 + 5 + 6
ByteSeqResult::Ok(sha512(&SUITE_STRING
.concat(&THREE)
.concat(&encode(point_mul_by_cofactor(gamma)))
.concat(&ZERO)).slice(0,64))
}
// This function is to verify a proof pi that is based on alpha. See section 5.3:
// https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
// Currently the code uses the ELL2 method, but this can be swapped by calling
// the TAI method instead. Proofs constructed with one of the methods can only
// be verified by a verify algorithm that uses the same method.
pub fn ecvrf_verify(
pk: PublicKey, alpha: &ByteSeq, pi: &ByteSeq, validate_key: bool
) -> ByteSeqResult {
let b = decompress(BASE).ok_or(Errorec::FailedDecompression)?;
// STEP 1 and 2
let y = decompress(pk).ok_or(Errorec::InvalidPublicKey)?;
// STEP 3
if validate_key {
ecvrf_validate_key(pk)?;
}
// STEP 4, 5 and 6
let (gamma, c, s) = ecvrf_decode_proof(pi)?;
// STEP 7
let encode_to_curve_salt = pk.slice(0,32);
// Swap lines to use encode_to_curve_try_and_increment
let h = ecvrf_encode_to_curve_h2c_suite(&encode_to_curve_salt, alpha)?;
// let h = ecvrf_encode_to_curve_try_and_increment(&encode_to_curve_salt, alpha)?;
// STEP 8
let u = point_add(point_mul(s, b), point_neg(point_mul(c, y)));
// STEP 9
let v = point_add(point_mul(s, h), point_neg(point_mul(c, gamma)));
// STEP 10
let c_prime = ecvrf_challenge_generation(y, h, gamma, u, v);
// STEP 11
if c == c_prime {
ecvrf_proof_to_hash(pi)
} else {
ByteSeqResult::Err(Errorec::FailedVerify)
}
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck::*;
#[derive(Clone, Copy, Debug)]
struct Keyp {sk: SecretKey, pk: PublicKey}
#[derive(Clone, Copy, Debug)]
struct Wrapper(Ed25519FieldElement);
impl Arbitrary for Wrapper {
fn arbitrary(g: &mut Gen) -> Wrapper {
const NUM_BYTES: u32 = 32;
let mut a: [u8; NUM_BYTES as usize] = [0; NUM_BYTES as usize];
for i in 0..NUM_BYTES as usize {
a[i] = u8::arbitrary(g);
}
Wrapper(Ed25519FieldElement::from_byte_seq_be(
&Seq::<U8>::from_public_slice(&a)))
}
}
public_nat_mod!(
type_name: KeyInt,
type_of_canvas: KeyCanvas,
bit_size_of_field: 256,
modulo_value: "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
);
impl Arbitrary for Keyp {
fn arbitrary(g: &mut Gen) -> Keyp {
const NUM_BYTES: u32 = 32;
let mut a: [u8; NUM_BYTES as usize] = [0; NUM_BYTES as usize];
for i in 0..NUM_BYTES as usize {
a[i] = u8::arbitrary(g);
}
let bs = KeyInt::from_byte_seq_be(
&Seq::<U8>::from_public_slice(&a));
let bss = bs.to_byte_seq_be();
let sk = SerializedScalar::from_slice(&bss, 0, 32);
let pk = secret_to_public(sk);
Keyp {sk, pk}
}
}
// quickcheck tests
const NUM_TESTS: u64 = 5;
#[test]
fn test_ecvrf() {
fn ecvrf(kp: Keyp, alpha: Wrapper) -> bool {
let alpha = alpha.0.to_byte_seq_be();
let pi = ecvrf_prove(kp.sk, &alpha).unwrap();
let beta = ecvrf_proof_to_hash(&pi).unwrap();
let beta_prime = ecvrf_verify(kp.pk, &alpha, &pi, true).unwrap();
beta_prime == beta
}
QuickCheck::new().tests(NUM_TESTS)
.quickcheck(ecvrf as fn(Keyp, Wrapper) -> bool);
}
#[test]
fn test_neg_ecvrf() {
fn neg_ecvrf(kp: Keyp, fake: Keyp, alpha: Wrapper) -> bool {
let alpha = alpha.0.to_byte_seq_be();
let pi = ecvrf_prove(kp.sk, &alpha).unwrap();
match ecvrf_verify(fake.pk, &alpha, &pi, true) {
Ok(_beta_prime) => false,
Err(e) => matches!(e, Errorec::FailedVerify),
}
}
QuickCheck::new().tests(NUM_TESTS)
.quickcheck(neg_ecvrf as fn(Keyp, Keyp, Wrapper) -> bool);
}
#[test]
fn test_neg_alpha_ecvrf() {
fn neg_alpha_ecvrf(kp: Keyp, alpha: Wrapper, fake_alpha: Wrapper) -> bool {
let alpha = alpha.0.to_byte_seq_be();
let fake_alpha = fake_alpha.0.to_byte_seq_be();
let pi = ecvrf_prove(kp.sk, &alpha).unwrap();
match ecvrf_verify(kp.pk, &fake_alpha, &pi, true) {
Ok(_beta_prime) => false,
Err(e) => matches!(e, Errorec::FailedVerify),
}
}
QuickCheck::new().tests(NUM_TESTS)
.quickcheck(neg_alpha_ecvrf as fn(Keyp, Wrapper, Wrapper) -> bool);
}
#[test]
fn unit_ecvrf_ell2() {
let alpha = ByteSeq::from_public_slice(b"");
let secret = ByteSeq::from_hex("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60");
let public = ByteSeq::from_hex("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a");
let pitest = ByteSeq::from_hex("7d9c633ffeee27349264cf5c667579fc583b4bda63ab71d001f89c10003ab46f14adf9a3cd8b8412d9038531e865c341cafa73589b023d14311c331a9ad15ff2fb37831e00f0acaa6d73bc9997b06501");
let betatest = ByteSeq::from_hex("9d574bf9b8302ec0fc1e21c3ec5368269527b87b462ce36dab2d14ccf80c53cccf6758f058c5b1c856b116388152bbe509ee3b9ecfe63d93c3b4346c1fbc6c54");
let sk = SerializedScalar::from_slice(&secret, 0, 32);
let pk = secret_to_public(sk);
let pkstr = encode(decompress(secret_to_public(sk)).unwrap());
assert_eq!(public, pkstr);
let pi = ecvrf_prove(sk, &alpha).unwrap();
assert_eq!(pi, pitest);
let beta = ecvrf_proof_to_hash(&pi).unwrap();
assert_eq!(beta, betatest);
let beta_prime = ecvrf_verify(pk, &alpha, &pi, true).unwrap();
assert_eq!(beta_prime, beta);
}
// Uncomment to test once all places in code have been swapped to use
// encode_to_curve_try_and_increment
// #[test]
// fn unit_ecvrf_tai() {
// let alpha = ByteSeq::from_public_slice(b"");
// let secret = ByteSeq::from_hex("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60");
// let public = ByteSeq::from_hex("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a");
// let pitest = ByteSeq::from_hex("8657106690b5526245a92b003bb079ccd1a92130477671f6fc01ad16f26f723f26f8a57ccaed74ee1b190bed1f479d9727d2d0f9b005a6e456a35d4fb0daab1268a1b0db10836d9826a528ca76567805");
// let betatest = ByteSeq::from_hex("90cf1df3b703cce59e2a35b925d411164068269d7b2d29f3301c03dd757876ff66b71dda49d2de59d03450451af026798e8f81cd2e333de5cdf4f3e140fdd8ae");
// let sk = SerializedScalar::from_slice(&secret, 0, 32);
// let pk = secret_to_public(sk);
// let pkstr = encode(decompress(secret_to_public(sk)).unwrap());
// assert_eq!(public, pkstr);
// let pi = ecvrf_prove(sk, &alpha).unwrap();
// assert_eq!(pi, pitest);
// let beta = ecvrf_proof_to_hash(&pi).unwrap();
// assert_eq!(beta, betatest);
// let beta_prime = ecvrf_verify(pk, &alpha, &pi, true).unwrap();
// assert_eq!(beta_prime, beta);
// }
}
|
#[cfg(test)]
pub fn runner(tests: &[&dyn Fn()]) {
use crate::*;
println!("Running Tests");
for test in tests {
test();
println!("... Ok");
}
}
|
#[doc = "Reader of register BUILD_CONFIG"]
pub type R = crate::R<u32, super::BUILD_CONFIG>;
#[doc = "Writer for register BUILD_CONFIG"]
pub type W = crate::W<u32, super::BUILD_CONFIG>;
#[doc = "Register BUILD_CONFIG `reset()`'s with value 0x0100_1f08"]
impl crate::ResetValue for super::BUILD_CONFIG {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x0100_1f08
}
}
#[doc = "Reader of field `NO_OF_REGIONS`"]
pub type NO_OF_REGIONS_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `NO_OF_REGIONS`"]
pub struct NO_OF_REGIONS_W<'a> {
w: &'a mut W,
}
impl<'a> NO_OF_REGIONS_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x1f) | ((value as u32) & 0x1f);
self.w
}
}
#[doc = "Reader of field `ADDRESS_WIDTH`"]
pub type ADDRESS_WIDTH_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `ADDRESS_WIDTH`"]
pub struct ADDRESS_WIDTH_W<'a> {
w: &'a mut W,
}
impl<'a> ADDRESS_WIDTH_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 & !(0x3f << 8)) | (((value as u32) & 0x3f) << 8);
self.w
}
}
#[doc = "Reader of field `NO_OF_FILTERS`"]
pub type NO_OF_FILTERS_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `NO_OF_FILTERS`"]
pub struct NO_OF_FILTERS_W<'a> {
w: &'a mut W,
}
impl<'a> NO_OF_FILTERS_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 24)) | (((value as u32) & 0x03) << 24);
self.w
}
}
impl R {
#[doc = "Bits 0:4 - Number fo regions"]
#[inline(always)]
pub fn no_of_regions(&self) -> NO_OF_REGIONS_R {
NO_OF_REGIONS_R::new((self.bits & 0x1f) as u8)
}
#[doc = "Bits 8:13 - ADDRESS WIDTH"]
#[inline(always)]
pub fn address_width(&self) -> ADDRESS_WIDTH_R {
ADDRESS_WIDTH_R::new(((self.bits >> 8) & 0x3f) as u8)
}
#[doc = "Bits 24:25 - Number of filters"]
#[inline(always)]
pub fn no_of_filters(&self) -> NO_OF_FILTERS_R {
NO_OF_FILTERS_R::new(((self.bits >> 24) & 0x03) as u8)
}
}
impl W {
#[doc = "Bits 0:4 - Number fo regions"]
#[inline(always)]
pub fn no_of_regions(&mut self) -> NO_OF_REGIONS_W {
NO_OF_REGIONS_W { w: self }
}
#[doc = "Bits 8:13 - ADDRESS WIDTH"]
#[inline(always)]
pub fn address_width(&mut self) -> ADDRESS_WIDTH_W {
ADDRESS_WIDTH_W { w: self }
}
#[doc = "Bits 24:25 - Number of filters"]
#[inline(always)]
pub fn no_of_filters(&mut self) -> NO_OF_FILTERS_W {
NO_OF_FILTERS_W { w: self }
}
}
|
use std::path::PathBuf;
use cli_integration_test::IntegrationTestEnvironment;
use predicates::prelude::Predicate;
use predicates::str::contains;
use short::cli::terminal::emoji::RIGHT_POINTER;
use short::BIN_NAME;
use test_utils::init;
use test_utils::{
HOME_CFG_FILE, PRIVATE_ENV_DEV_FILE, PRIVATE_ENV_DIR, PROJECT_CFG_FILE, PROJECT_ENV_DIR,
};
mod test_utils;
#[test]
fn cmd_ls_settings() {
let e = IntegrationTestEnvironment::new("cmd_ls_settings");
let mut command = e.command(BIN_NAME).unwrap();
let r = command
.env("RUST_LOG", "debug")
.arg("ls")
.assert()
.to_string();
assert!(contains("fail to load cfg").eval(&r));
}
#[test]
fn cmd_ls() {
let mut e = init("cmd_ls_settings");
e.add_file("template.yaml", "");
e.add_file(
PathBuf::from(PROJECT_ENV_DIR).join(".example1"),
"VAR1=VALUE1",
);
e.add_file(
PathBuf::from(PROJECT_ENV_DIR).join(".example2"),
"VAR1=VALUE1",
);
e.add_file(PathBuf::from(PRIVATE_ENV_DEV_FILE), "VAR1=VALUE1");
e.add_file(
PROJECT_CFG_FILE,
r"#---
setups:
setup_1:
file: test.sh
array_vars: {}
setup_2:
file: test.sh
array_vars: {}
public_env_dir: env/
#",
);
e.add_file(
HOME_CFG_FILE,
format!(
r"
projects:
- file: {file}
setups:
setup_1:
private_env_dir: {private_env_dir}
",
file = e.path().unwrap().join(PROJECT_CFG_FILE).to_string_lossy(),
private_env_dir = e.path().unwrap().join(PRIVATE_ENV_DIR).to_string_lossy()
),
);
e.setup();
let mut command = e.command(BIN_NAME).unwrap();
let r = command
.env("RUST_LOG", "debug")
.arg("ls")
.assert()
.to_string();
assert!(contains("setup_1 (test.sh)").count(1).eval(&r));
assert!(contains(format!(
"dev ({})",
e.path()
.unwrap()
.join(PRIVATE_ENV_DEV_FILE)
.to_string_lossy()
))
.count(1)
.eval(&r));
assert!(contains("setup_2 (test.sh)").count(1).eval(&r));
assert!(contains("example1 (env/.example1)").count(1).eval(&r));
assert!(contains("example2 (env/.example2)").count(1).eval(&r));
let mut command = e.command(BIN_NAME).unwrap();
let r = command
.env("RUST_LOG", "debug")
.arg("ls")
.args(&["-s", "setup_1"])
.assert()
.to_string();
assert!(contains(format!("{} setup_1", RIGHT_POINTER))
.count(1)
.eval(&r));
let mut command = e.command(BIN_NAME).unwrap();
let r = command
.env("RUST_LOG", "debug")
.arg("ls")
.args(&["-s", "setup_2"])
.args(&["-e", "example2"])
.assert()
.to_string();
assert!(contains(format!("{} example2", RIGHT_POINTER))
.count(1)
.eval(&r));
}
|
use wasm_bindgen::prelude::*;
use wasm_bindgen::convert::{OptionIntoWasmAbi, IntoWasmAbi, FromWasmAbi};
use crate::bigint_256::{self, WasmBigInteger256};
use algebra::biginteger::BigInteger256;
use algebra::{ToBytes, FromBytes};
use mina_curves::pasta::fp::{Fp, FpParameters as Fp_params};
use algebra::{
fields::{Field, FpParameters, PrimeField, SquareRootField},
FftField, One, UniformRand, Zero,
};
use ff_fft::{EvaluationDomain, Radix2EvaluationDomain as Domain};
use num_bigint::BigUint;
use rand::rngs::StdRng;
use std::cmp::Ordering::{Equal, Greater, Less};
pub struct WasmPastaFp(pub Fp);
impl wasm_bindgen::describe::WasmDescribe for WasmPastaFp {
fn describe() { <Vec<u8> as wasm_bindgen::describe::WasmDescribe>::describe() }
}
impl FromWasmAbi for WasmPastaFp {
type Abi = <Vec<u8> as FromWasmAbi>::Abi;
unsafe fn from_abi(js: Self::Abi) -> Self {
let bytes: Vec<u8> = FromWasmAbi::from_abi(js);
WasmPastaFp(FromBytes::read(bytes.as_slice()).unwrap())
}
}
impl IntoWasmAbi for WasmPastaFp {
type Abi = <Vec<u8> as FromWasmAbi>::Abi;
fn into_abi(self) -> Self::Abi {
let mut bytes: Vec<u8> = vec![];
self.0.write(&mut bytes);
bytes.into_abi()
}
}
impl OptionIntoWasmAbi for WasmPastaFp {
fn none() -> Self::Abi {
let max_bigint = WasmBigInteger256(BigInteger256([u64::MAX, u64::MAX, u64::MAX, u64::MAX]));
max_bigint.into_abi()
}
}
#[wasm_bindgen]
pub fn caml_pasta_fp_size_in_bits() -> isize {
Fp_params::MODULUS_BITS as isize
}
#[wasm_bindgen]
pub fn caml_pasta_fp_size() -> WasmBigInteger256 {
WasmBigInteger256(Fp_params::MODULUS)
}
#[wasm_bindgen]
pub fn caml_pasta_fp_add(x: WasmPastaFp, y: WasmPastaFp) -> WasmPastaFp {
WasmPastaFp(x.0 + y.0)
}
#[wasm_bindgen]
pub fn caml_pasta_fp_sub(x: WasmPastaFp, y: WasmPastaFp) -> WasmPastaFp {
WasmPastaFp(x.0 - y.0)
}
#[wasm_bindgen]
pub fn caml_pasta_fp_negate(x: WasmPastaFp) -> WasmPastaFp {
WasmPastaFp(-x.0)
}
#[wasm_bindgen]
pub fn caml_pasta_fp_mul(x: WasmPastaFp, y: WasmPastaFp) -> WasmPastaFp {
WasmPastaFp(x.0 * y.0)
}
#[wasm_bindgen]
pub fn caml_pasta_fp_div(x: WasmPastaFp, y: WasmPastaFp) -> WasmPastaFp {
WasmPastaFp(x.0 / y.0)
}
#[wasm_bindgen]
pub fn caml_pasta_fp_inv(x: WasmPastaFp) -> Option<WasmPastaFp> {
x.0.inverse().map(|x| { WasmPastaFp(x) })
}
#[wasm_bindgen]
pub fn caml_pasta_fp_square(x: WasmPastaFp) -> WasmPastaFp {
WasmPastaFp(x.0.square())
}
#[wasm_bindgen]
pub fn caml_pasta_fp_is_square(x: WasmPastaFp) -> bool {
let s = x.0.pow(Fp_params::MODULUS_MINUS_ONE_DIV_TWO);
s.is_zero() || s.is_one()
}
#[wasm_bindgen]
pub fn caml_pasta_fp_sqrt(x: WasmPastaFp) -> Option<WasmPastaFp> {
x.0.sqrt().map(|x| { WasmPastaFp(x) })
}
#[wasm_bindgen]
pub fn caml_pasta_fp_of_int(i: i32) -> WasmPastaFp {
WasmPastaFp(Fp::from(i as u64))
}
#[wasm_bindgen]
pub fn caml_pasta_fp_to_string(x: WasmPastaFp) -> String {
bigint_256::to_biguint(&x.0.into_repr()).to_string()
}
#[wasm_bindgen]
pub fn caml_pasta_fp_of_string(s: String) -> WasmPastaFp {
match BigUint::parse_bytes(&s.into_bytes(), 10) {
Some(data) => WasmPastaFp(Fp::from_repr(bigint_256::of_biguint(&data))),
None => panic!("caml_pasta_fp_of_string"),
}
}
#[wasm_bindgen]
pub fn caml_pasta_fp_print(x: WasmPastaFp) {
println!("{}", bigint_256::to_biguint(&(x.0.into_repr())));
}
#[wasm_bindgen]
pub fn caml_pasta_fp_compare(x: WasmPastaFp, y: WasmPastaFp) -> i32 {
match x.0.cmp(&y.0) {
Less => -1,
Equal => 0,
Greater => 1,
}
}
#[wasm_bindgen]
pub fn caml_pasta_fp_equal(x: WasmPastaFp, y: WasmPastaFp) -> bool {
x.0 == y.0
}
#[wasm_bindgen]
pub fn caml_pasta_fp_random() -> WasmPastaFp {
WasmPastaFp(UniformRand::rand(&mut rand::thread_rng()))
}
#[wasm_bindgen]
pub fn caml_pasta_fp_rng(i: i32) -> WasmPastaFp {
// We only care about entropy here, so we force a conversion i32 -> u32.
let i: u64 = (i as u32).into();
let mut rng: StdRng = rand::SeedableRng::seed_from_u64(i);
WasmPastaFp(UniformRand::rand(&mut rng))
}
#[wasm_bindgen]
pub fn caml_pasta_fp_to_bigint(x: WasmPastaFp) -> WasmBigInteger256 {
WasmBigInteger256(x.0.into_repr())
}
#[wasm_bindgen]
pub fn caml_pasta_fp_of_bigint(x: WasmBigInteger256) -> WasmPastaFp {
WasmPastaFp(Fp::from_repr(x.0))
}
#[wasm_bindgen]
pub fn caml_pasta_fp_two_adic_root_of_unity() -> WasmPastaFp {
WasmPastaFp(FftField::two_adic_root_of_unity())
}
#[wasm_bindgen]
pub fn caml_pasta_fp_domain_generator(log2_size: i32) -> WasmPastaFp {
match Domain::new(1 << log2_size) {
Some(x) => WasmPastaFp(x.group_gen),
None => panic!("caml_pasta_fp_domain_generator"),
}
}
#[wasm_bindgen]
pub fn caml_pasta_fp_to_bytes(x: WasmPastaFp) -> Vec<u8> {
let len = std::mem::size_of::<Fp>();
let mut str: Vec<u8> = Vec::with_capacity(len);
str.resize(len, 0);
let str_as_fp : *mut Fp = str.as_mut_ptr().cast::<Fp>();
unsafe {
*str_as_fp = x.0;
}
str
}
#[wasm_bindgen]
pub fn caml_pasta_fp_of_bytes(x: &[u8]) -> WasmPastaFp {
let len = std::mem::size_of::<Fp>();
if x.len() != len {
panic!("caml_pasta_fp_of_bytes");
};
let x = unsafe { *(x.as_ptr() as *const Fp) };
WasmPastaFp(x)
}
#[wasm_bindgen]
pub fn caml_pasta_fp_deep_copy(x: WasmPastaFp) -> WasmPastaFp {
x
}
|
#[doc = "Register `ETH_DMAA4TxACR` reader"]
pub type R = crate::R<ETH_DMAA4TX_ACR_SPEC>;
#[doc = "Register `ETH_DMAA4TxACR` writer"]
pub type W = crate::W<ETH_DMAA4TX_ACR_SPEC>;
#[doc = "Field `TDRC` reader - TDRC"]
pub type TDRC_R = crate::FieldReader;
#[doc = "Field `TDRC` writer - TDRC"]
pub type TDRC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>;
#[doc = "Field `TEC` reader - TEC"]
pub type TEC_R = crate::FieldReader;
#[doc = "Field `TEC` writer - TEC"]
pub type TEC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>;
#[doc = "Field `THC` reader - THC"]
pub type THC_R = crate::FieldReader;
#[doc = "Field `THC` writer - THC"]
pub type THC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>;
impl R {
#[doc = "Bits 0:3 - TDRC"]
#[inline(always)]
pub fn tdrc(&self) -> TDRC_R {
TDRC_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 8:11 - TEC"]
#[inline(always)]
pub fn tec(&self) -> TEC_R {
TEC_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bits 16:19 - THC"]
#[inline(always)]
pub fn thc(&self) -> THC_R {
THC_R::new(((self.bits >> 16) & 0x0f) as u8)
}
}
impl W {
#[doc = "Bits 0:3 - TDRC"]
#[inline(always)]
#[must_use]
pub fn tdrc(&mut self) -> TDRC_W<ETH_DMAA4TX_ACR_SPEC, 0> {
TDRC_W::new(self)
}
#[doc = "Bits 8:11 - TEC"]
#[inline(always)]
#[must_use]
pub fn tec(&mut self) -> TEC_W<ETH_DMAA4TX_ACR_SPEC, 8> {
TEC_W::new(self)
}
#[doc = "Bits 16:19 - THC"]
#[inline(always)]
#[must_use]
pub fn thc(&mut self) -> THC_W<ETH_DMAA4TX_ACR_SPEC, 16> {
THC_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 = "AXI4 transmit channel ACE control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmaa4tx_acr::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 [`eth_dmaa4tx_acr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct ETH_DMAA4TX_ACR_SPEC;
impl crate::RegisterSpec for ETH_DMAA4TX_ACR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`eth_dmaa4tx_acr::R`](R) reader structure"]
impl crate::Readable for ETH_DMAA4TX_ACR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`eth_dmaa4tx_acr::W`](W) writer structure"]
impl crate::Writable for ETH_DMAA4TX_ACR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets ETH_DMAA4TxACR to value 0"]
impl crate::Resettable for ETH_DMAA4TX_ACR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.