text stringlengths 8 4.13M |
|---|
#[doc = "Reader of register STAT1"]
pub type R = crate::R<u32, super::STAT1>;
#[doc = "Writer for register STAT1"]
pub type W = crate::W<u32, super::STAT1>;
#[doc = "Register STAT1 `reset()`'s with value 0xc0"]
impl crate::ResetValue for super::STAT1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0xc0
}
}
#[doc = "Reader of field `BSY`"]
pub type BSY_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EBF`"]
pub struct EBF_W<'a> {
w: &'a mut W,
}
impl<'a> EBF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Write proxy for field `RTF`"]
pub struct RTF_W<'a> {
w: &'a mut W,
}
impl<'a> RTF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
impl R {
#[doc = "Bit 16 - Busy flag"]
#[inline(always)]
pub fn bsy(&self) -> BSY_R {
BSY_R::new(((self.bits >> 16) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 12 - End of block flag"]
#[inline(always)]
pub fn ebf(&mut self) -> EBF_W {
EBF_W { w: self }
}
#[doc = "Bit 11 - Receiver timeout flag"]
#[inline(always)]
pub fn rtf(&mut self) -> RTF_W {
RTF_W { w: self }
}
}
|
use codespan::Location;
use std::io;
use termcolor::WriteColor;
use crate::term::Config;
/// The 'location focus' of a source code snippet.
///
/// This is displayed in a way that other tools can understand, for
/// example when command+clicking in iTerm.
///
/// ```text
/// test:2:9
/// ```
pub struct Locus<'a> {
file_name: &'a str,
location: Location,
}
impl<'a> Locus<'a> {
pub fn new(file_name: &'a str, location: Location) -> Locus<'a> {
Locus {
file_name,
location,
}
}
pub fn emit(&self, writer: &mut (impl WriteColor + ?Sized), _config: &Config) -> io::Result<()> {
write!(
writer,
"{file}:{line}:{column}",
file = self.file_name,
line = self.location.line.number(),
column = self.location.column.number(),
)
}
}
|
use amethyst::{GameData, SimpleState, StateData, StateEvent, SimpleTrans, Trans};
use amethyst::assets::Loader;
use amethyst::core::Transform;
use amethyst::ecs::{Builder, World};
use amethyst::input::{VirtualKeyCode, is_key_down};
use amethyst::renderer::Camera;
use amethyst::ui::{Anchor, LineMode, TtfFormat, UiText, UiTransform};
use amethyst::prelude::WorldExt;
use crate::config::BlobsConfig;
use crate::components::Init;
use crate::map::{Generator, Map};
use crate::utils::prefab;
use crate::ui;
use crate::utils::sprite::{SpriteHandler, SpriteSheets};
#[derive(Default)]
pub struct GameplayState;
impl SimpleState for GameplayState {
fn on_start(&mut self, data: StateData<'_, GameData<'_, '_>>) {
let the_world = data.world;
let mut sprite_handler = SpriteHandler::default();
sprite_handler.add_sprite_sheet(the_world, SpriteSheets::Character,
"sprites.png", "sprites.ron");
sprite_handler.add_sprite_sheet(the_world, SpriteSheets::Dungeon,
"dungeon.png", "dungeon.ron");
sprite_handler.add_sprite_sheet(the_world, SpriteSheets::Mobs,
"mobs.png", "mobs.ron");
the_world.insert(sprite_handler);
the_world.create_entity().with(Init).build();
let (player_x, player_y) = init_map(the_world);
prefab::create_player(the_world, player_x, player_y);
init_camera(the_world);
init_ui(the_world);
}
fn handle_event(&mut self, _data: StateData<'_, GameData<'_, '_>>,
event: StateEvent) -> SimpleTrans {
if let StateEvent::Window(event) = &event {
if is_key_down(&event, VirtualKeyCode::Escape) {
return Trans::Quit
}
}
Trans::None
}
}
fn init_map(the_world: &mut World) -> (usize, usize) {
let (mut generator, map) = {
let config = &the_world.read_resource::<BlobsConfig>();
let generator = Generator::new(&config.map);
let map = Map::new(&config.map);
(generator, map)
};
the_world.insert(map);
let rooms = generator.generate();
for y in 0..generator.height() {
for x in 0..generator.width() {
let tile = prefab::create_tile(the_world, x, y, generator.tile(x, y));
let mut map = the_world.write_resource::<Map>();
map.add_tile(tile);
}
}
for room in rooms.iter().skip(1) {
let c = room.center();
prefab::create_mob(the_world, c.0, c.1);
}
rooms[0].center()
}
fn init_camera(the_world: &mut World) {
let (transform, camera) = {
let mut transform = Transform::default();
let config = the_world.read_resource::<BlobsConfig>();
let screen_width = (config.map.width + config.panel.right) as f32;
let screen_height = (config.map.height + config.panel.bottom) as f32;
transform.set_translation_xyz(
screen_width / 2.0 - 0.5,
screen_height / 2.0 - config.panel.bottom as f32 - 0.5,
10.0);
let camera = Camera::standard_2d(screen_width, screen_height as f32);
(transform, camera)
};
the_world.create_entity()
.with(camera)
.with(transform)
.build();
}
fn init_ui(the_world: &mut World) {
let (log_height, log_lines, font_size) = {
let config = the_world.read_resource::<BlobsConfig>();
(config.panel.bottom as f32 * config.map.tile_size as f32,
config.panel.bottom_lines, config.panel.font_size as f32)
};
let font = the_world.read_resource::<Loader>().load(
"font.ttf",
TtfFormat,
(),
&the_world.read_resource()
);
let transform = UiTransform::new(
"hp".to_string(),
Anchor::TopLeft,
Anchor::Middle,
260., -20., 5.,
500., 50.);
let text = UiText::new(
font.clone(),
"HP:".to_string(),
[1., 1., 1., 1.],
font_size,
LineMode::Single,
Anchor::MiddleLeft);
let label = the_world.create_entity()
.with(transform)
.with(text)
.build();
let hp = ui::Hp::new(label);
the_world.insert(hp);
let transform = UiTransform::new(
"log".to_string(),
Anchor::BottomLeft,
Anchor::Middle,
410., log_height / 2., 5.,
800., log_height);
let text = UiText::new(
font.clone(),
"".to_string(),
[1., 1., 1., 1.],
font_size,
LineMode::Wrap,
Anchor::TopLeft);
let label = the_world.create_entity()
.with(transform)
.with(text)
.build();
let message_log = ui::MessageLog::new(label, log_lines);
the_world.insert(message_log);
}
|
//! This crate provides a non-invasive implementation of a **disjoint-set tree** data structure.
//!
//! # Disjoint-Set Tree
//!
//! **[Disjoint sets] data structure**, or **DSU**, or **union-find data structure**, or **merge-
//! find set**, is a data structure that stores a collection of disjoint sets. It provides
//! operations for adding new sets, merging sets (equivalent to replacing the sets with the union
//! of them) and finding the representative member of a set. DSU is very useful in implementing
//! algorithms like [minimum spanning tree] and more.
//!
//! DSU can be implemented with its extreme efficiency by using **disjoint-set trees**. Disjoint-set
//! trees are actually a forest in which each node represents a set and each tree represents the
//! union of sets that are merged together. The three DSU operations can be implemented as follows:
//! - Adding new sets: Easy. Just add new nodes to the forest and it's done. The new nodes are
//! themselves a tree in the forest to indicate that they have not been merged with other sets.
//! - Merging sets: To merge two sets whose corresponding nodes are `A` and `B`, respectively, we
//! just change the parent node of `A` to `B` and it's done. In real implementations, some corner
//! cases need to be considered, such as merging a set into itself.
//! - Finding the representative member of a set: Each tree within the disjoint-set trees represents
//! a set. The representative member of a set can be chosen to be the representative member of the
//! set corresponding to the root node of the tree.
//!
//! # `dsu-tree`
//!
//! Rather than implementing a disjoint-set data structure, this crate provides the implementation
//! of the underlying disjoint-set tree data structure.
//!
//! [`DsuRoot`] is provided to access the disjoint-set trees. It is a smart pointer that can be
//! thought as "always" points to the root node of a tree within the disjoint-set trees.
//!
//! To create a new disjoint-set tree node, call the [`DsuRoot::new`] function. To merge two
//! disjoint-set trees, call the [`DsuRoot::merge_into`] function. To test whether two disjoint-set
//! trees are actually the same tree, call the [`DsuRoot::same`] function.
//!
//! # `#![no_std]`
//!
//! This crate is `#![no_std]`.
//!
//! [Disjoint sets]: https://en.wikipedia.org/wiki/Disjoint-set_data_structure
//! [minimum spanning tree]: https://en.wikipedia.org/wiki/Minimum_spanning_tree
//!
//! [`DsuRoot`]: struct.DsuRoot.html
//! [`DsuRoot::new`]: struct.DsuRoot.html#method.new
//! [`DsuRoot::merge_into`]: struct.DsuRoot.html#method.merge_into
//! [`DsuRoot::same`]: struct.DsuRoot.html#method.same
//!
#![no_std]
extern crate alloc;
use alloc::rc::Rc;
use core::cell::RefCell;
/// An owning smart pointer that always points to the root of a DSU tree.
///
/// One can logically consider that `DsuRoot` smart pointers refer to a standalone DSU tree. When
/// merging two DSU trees by calling the [`merge_into`] function, the two DSU trees are given
/// through two `DsuRoot` smart pointers that logically refer to the two trees.
///
/// [`merge_into`]: #method.merge_into
#[derive(Clone, Debug)]
pub struct DsuRoot<T> {
node: Rc<DsuNode<T>>,
}
impl<T> DsuRoot<T> {
/// Create a new DSU tree node and attach a `DsuRoot` smart pointer to the new node.
///
/// The new DSU tree node contains the given value.
pub fn new(value: T) -> Self {
Self {
node: Rc::new(DsuNode::new(value)),
}
}
/// Determine whether the two `DsuRoot` smart pointers refer to the same tree.
///
/// ```
/// use dsu_tree::DsuRoot;
///
/// let mut dsu_1 = DsuRoot::new(10);
/// let mut dsu_2 = DsuRoot::new(20);
/// assert!(!DsuRoot::same(&mut dsu_1, &mut dsu_2));
///
/// dsu_1.merge_into(&mut dsu_2);
/// assert!(DsuRoot::same(&mut dsu_1, &mut dsu_2));
/// ```
pub fn same(lhs: &mut Self, rhs: &mut Self) -> bool {
lhs.move_to_root();
rhs.move_to_root();
Rc::ptr_eq(&lhs.node, &rhs.node)
}
/// Get the value contained in the DSU tree node pointed to by this `DsuRoot` smart pointer.
///
/// This function requires `&mut self` since the `DsuRoot` smart pointer may move around over
/// the DSU tree so that it eventually points to the root node.
pub fn value(&mut self) -> &T {
self.move_to_root();
&self.node.value
}
/// Merge two DSU trees into one.
///
/// The first DSU tree is given through `self`. The second DSU tree is given through `another`.
///
/// If initially, the two trees are the same tree, then this function does nothing. Otherwise,
/// the parent node of the root node of the tree specified through `self` is set to the root
/// node of the tree specified through `another`.
pub fn merge_into(&mut self, another: &mut Self) {
if Self::same(self, another) {
return;
}
// After calling `same`, `self` and `another` should both point to the root of their DSU
// tree.
debug_assert!(self.node.is_root());
debug_assert!(another.node.is_root());
self.node.set_parent(another.node.clone())
}
/// Move this smart pointer to make it point to the root node of the referring DSU tree.
fn move_to_root(&mut self) {
self.node.compress_path();
if !self.node.is_root() {
self.node = self.node.parent().unwrap();
}
debug_assert!(self.node.is_root());
}
}
/// The DSU tree node.
#[derive(Debug)]
struct DsuNode<T> {
parent: RefCell<Option<Rc<DsuNode<T>>>>,
value: T,
}
impl<T> DsuNode<T> {
/// Create a new DSU tree node that contains the given value.
fn new(value: T) -> Self {
Self {
parent: RefCell::new(None),
value,
}
}
/// Determine whether this node is the root node.
fn is_root(&self) -> bool {
self.parent.borrow().is_none()
}
/// Get the parent node wrapped in an [`Option`].
///
/// If this node is the root node, this function returns [`None`].
///
/// [`Option`]: https://doc.rust-lang.org/core/option/enum.Option.html
/// [`None`]: https://doc.rust-lang.org/core/option/enum.Option.html#variant.None
fn parent(&self) -> Option<Rc<DsuNode<T>>> {
(*self.parent.borrow()).clone()
}
/// Set the parent node.
//noinspection ALL
fn set_parent(&self, parent: Rc<DsuNode<T>>) {
*self.parent.borrow_mut() = Some(parent);
}
/// Compress the path from this node to the root node of the tree.
///
/// After path compression, the number of nodes along the path from this node to the root node
/// cannot be greater than 2. That is, after path compression, one of the two conditions holds:
/// * This node is initially the root node, and so it keeps to be the root node after path
/// compression;
/// * This node is not the root node initially, and after path compression, the parent node
/// becomes the root node.
fn compress_path(&self) {
// Quick check to bail the trivial situations out in which:
// * `self` is itself a root node;
// * The parent node of `self` is a root node.
//
// In any of the two cases above, we don't have to do anything.
let trivial = {
let parent_borrow = self.parent.borrow();
match &*parent_borrow {
Some(parent) => parent.is_root(),
None => true,
}
};
if trivial {
return;
}
// Do the path compression.
let mut parent_borrow = self.parent.borrow_mut();
// First, compress the path from the parent to the root. After this step, the parent of the
// parent node should be the root.
let parent_node = parent_borrow.as_ref().unwrap();
parent_node.compress_path();
// Then, simply update the parent pointer.
*parent_borrow = Some(parent_node.parent().unwrap());
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec::Vec;
fn create_link_tree() -> Vec<Rc<DsuNode<i32>>> {
let mut nodes = Vec::with_capacity(10);
let root = Rc::new(DsuNode::new(0));
nodes.push(root.clone());
for i in 1..10usize {
let mut node = DsuNode::new(i as i32);
node.parent = RefCell::new(Some(nodes[i - 1].clone()));
nodes.push(Rc::new(node));
}
nodes
}
fn assert_path_compressed(nodes: &[Rc<DsuNode<i32>>]) {
let root = nodes[0].clone();
for i in 1..nodes.len() {
let parent = nodes[i].parent();
assert!(parent.is_some());
assert!(Rc::ptr_eq(parent.as_ref().unwrap(), &root));
}
}
mod dsu_node_tests {
use super::*;
#[test]
fn test_new() {
let node = DsuNode::new(10);
assert!(node.parent.borrow().is_none());
assert_eq!(node.value, 10);
}
#[test]
fn test_is_root_true() {
let node = DsuNode::new(10);
assert!(node.is_root());
}
#[test]
fn test_is_root_false() {
let mut node = DsuNode::new(10);
node.parent = RefCell::new(Some(Rc::new(DsuNode::new(20))));
assert!(!node.is_root());
}
#[test]
fn test_parent_root() {
let node = DsuNode::new(10);
assert!(node.parent().is_none());
}
#[test]
fn test_parent_non_root() {
let mut node = DsuNode::new(10);
let root = Rc::new(DsuNode::new(20));
node.parent = RefCell::new(Some(root.clone()));
let node_parent = node.parent();
assert!(node_parent.is_some());
assert!(Rc::ptr_eq(node_parent.as_ref().unwrap(), &root));
}
#[test]
fn test_set_parent() {
let node = DsuNode::new(10);
let parent = Rc::new(DsuNode::new(20));
node.set_parent(parent.clone());
assert!(node.parent.borrow().is_some());
assert!(Rc::ptr_eq(node.parent.borrow().as_ref().unwrap(), &parent));
}
#[test]
fn test_compress_path_root() {
let node = DsuNode::new(10);
node.compress_path();
assert!(node.parent.borrow().is_none());
}
#[test]
fn test_compress_path_root_child() {
let mut node = DsuNode::new(10);
let root = Rc::new(DsuNode::new(20));
node.parent = RefCell::new(Some(root.clone()));
node.compress_path();
assert!(node.parent.borrow().is_some());
assert!(Rc::ptr_eq(node.parent.borrow().as_ref().unwrap(), &root));
}
#[test]
fn test_compress_path_deep() {
let nodes = create_link_tree();
nodes.last().unwrap().compress_path();
assert_path_compressed(&nodes);
}
}
mod dsu_root_tests {
use super::*;
#[test]
fn test_new() {
let ptr = DsuRoot::new(10);
assert!(ptr.node.is_root());
assert_eq!(ptr.node.value, 10);
}
#[test]
fn test_same() {
let mut ptr_1 = DsuRoot::new(10);
let mut ptr_2 = DsuRoot::new(20);
assert!(!DsuRoot::same(&mut ptr_1, &mut ptr_2));
ptr_1.node.set_parent(ptr_2.node.clone());
assert!(DsuRoot::same(&mut ptr_1, &mut ptr_2));
}
#[test]
fn test_value_basic() {
let mut ptr = DsuRoot::new(10);
assert_eq!(*ptr.value(), 10);
}
#[test]
fn test_value_merged() {
let mut ptr = DsuRoot::new(10);
ptr.node.set_parent(Rc::new(DsuNode::new(20)));
assert_eq!(*ptr.value(), 20);
}
#[test]
fn test_merge_into_basic() {
let mut ptr = DsuRoot::new(10);
let mut root = DsuRoot::new(20);
ptr.merge_into(&mut root);
assert!(DsuRoot::same(&mut ptr, &mut root));
assert_eq!(*ptr.value(), 20);
}
#[test]
fn test_merge_into_root() {
let mut ptr = DsuRoot::new(10);
let mut root = DsuRoot::new(20);
ptr.node.set_parent(root.node.clone());
ptr.merge_into(&mut root);
assert_eq!(*ptr.value(), 20);
}
#[test]
fn test_merge_into_child() {
let mut ptr = DsuRoot::new(10);
let mut root = DsuRoot::new(20);
ptr.node.set_parent(root.node.clone());
root.merge_into(&mut ptr);
assert_eq!(*root.value(), 20);
}
#[test]
fn test_move_to_root() {
let nodes = create_link_tree();
let root = nodes[0].clone();
let mut ptr = DsuRoot {
node: nodes.last().unwrap().clone(),
};
ptr.move_to_root();
assert!(Rc::ptr_eq(&ptr.node, &root));
assert_path_compressed(&nodes);
}
}
}
|
use crate::deferred::DeferredValue::{Initialized, WaitingForValue};
use std::ops::Deref;
use std::sync::Mutex;
pub struct Deferred<T> {
value: Mutex<DeferredValue<T>>,
}
pub enum DeferredValue<T> {
Initialized(T),
WaitingForValue,
}
impl<T> Deferred<T> {
pub fn new() -> Self {
Self {
value: Mutex::new(WaitingForValue),
}
}
pub fn init(&self, value: T) {
*self.value.lock().unwrap() = Initialized(value);
}
}
impl<T> Deref for Deferred<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe {
if let Initialized(value) = &*(self.value.lock().unwrap().deref() as *const DeferredValue<T>) {
value
} else {
panic!("Deferred value must be initialized before the first usage")
}
}
}
}
#[cfg(test)]
mod tests {
use crate::Deferred;
#[test]
fn deref_after_init() {
let deferred = Deferred::<&str>::new();
deferred.init("Initialized");
assert_eq!("Initialized", *deferred);
}
#[test]
#[should_panic]
fn deref_before_init() {
let deferred = Deferred::<&str>::new();
assert_eq!("Initialized", *deferred);
}
}
|
fn longest(a1: &str, a2: &str) -> String {
let mut chars: Vec<char> = a1.to_string().chars().collect();
let chars2: Vec<char> = a2.to_string().chars().collect();
chars.extend(chars2); chars.sort(); chars.dedup();
chars.into_iter().collect()
}
#[test]
fn test0() {
assert_eq!( longest("aretheyhere", "yestheyarehere"), "aehrsty");
}
#[test]
fn test1() {
assert_eq!( longest("loopingisfunbutdangerous", "lessdangerousthancoding"), "abcdefghilnoprstu");
}
#[test]
fn test2() {
assert_eq!( longest("abc", "def"), "abcdef");
}
#[test]
fn test3() {
assert_eq!( longest("aabbcc", "ddeeff"), "abcdef");
}
#[test]
fn test4() {
assert_eq!( longest("cba", "fed"), "abcdef");
}
#[test]
fn test5() {
assert_eq!( longest("aeaaaaaaeaaaaaabeebbeebbbebebebbbbebcddddeddedddedddd", "f"), "abcdef");
}
#[test]
fn test6() {
assert_eq!( longest("a", "b"), "ab");
}
#[test]
fn test7() {
assert_eq!( longest("bbbbbbbbbbb", "aaaaaaaaaaaaaaaaaa"), "ab");
}
#[test]
fn test8() {
assert_eq!( longest("ababa", "ababa"), "ab");
}
#[test]
fn test9() {
assert_eq!( longest("abc", ""), "abc");
}
fn main() {}
|
use crate::{parser::Operator, parser_state::Type, Expr, Expression, ParseError, ParserWorkingSet};
impl<'a> ParserWorkingSet<'a> {
pub fn math_result_type(
&self,
lhs: &mut Expression,
op: &mut Expression,
rhs: &mut Expression,
) -> (Type, Option<ParseError>) {
match &op.expr {
Expr::Operator(operator) => match operator {
Operator::Multiply => match (&lhs.ty, &rhs.ty) {
(Type::Int, Type::Int) => (Type::Int, None),
(Type::Unknown, _) => (Type::Unknown, None),
(_, Type::Unknown) => (Type::Unknown, None),
_ => {
*op = Expression::garbage(op.span);
(
Type::Unknown,
Some(ParseError::Mismatch("math".into(), op.span)),
)
}
},
Operator::Plus => match (&lhs.ty, &rhs.ty) {
(Type::Int, Type::Int) => (Type::Int, None),
(Type::String, Type::String) => (Type::String, None),
(Type::Unknown, _) => (Type::Unknown, None),
(_, Type::Unknown) => (Type::Unknown, None),
(Type::Int, _) => {
*rhs = Expression::garbage(rhs.span);
(
Type::Unknown,
Some(ParseError::Mismatch("int".into(), rhs.span)),
)
}
_ => {
*op = Expression::garbage(op.span);
(
Type::Unknown,
Some(ParseError::Mismatch("math".into(), op.span)),
)
}
},
_ => {
*op = Expression::garbage(op.span);
(
Type::Unknown,
Some(ParseError::Mismatch("math".into(), op.span)),
)
}
},
_ => {
*op = Expression::garbage(op.span);
(
Type::Unknown,
Some(ParseError::Mismatch("operator".into(), op.span)),
)
}
}
}
}
|
// ====================================================
// Netlyser Copyright(C) 2019 Furkan Türkal
// This program comes with ABSOLUTELY NO WARRANTY; This is free software,
// and you are welcome to redistribute it under certain conditions; See
// file LICENSE, which is part of this source code package, for details.
// ====================================================
use std::{
collections::HashMap,
fs::OpenOptions,
io::{BufRead, BufReader, Error, ErrorKind},
net::Ipv4Addr,
process::exit,
process::{Command, Stdio},
str::FromStr,
};
use regex::Regex;
use pnet::util::MacAddr;
use tempfile::NamedTempFile;
use crate::run::ExitCodes;
use serde_xml_rs::from_reader;
#[derive(Debug, Clone)]
pub struct Gateway {
pub ip: Ipv4Addr,
pub mac: MacAddr,
}
// ip : IP to scan (192.168.1.0)
// msak: Net Mask to scan (/24)
#[derive(Debug, Clone)]
pub struct ScanInfo {
pub addr: Ipv4Addr,
pub mask: u8,
}
#[derive(PartialEq, Debug, Deserialize)]
pub struct Times {
pub srtt: String,
pub rttvar: String,
pub to: String,
}
#[derive(PartialEq, Debug, Deserialize)]
pub struct Address {
pub addr: String,
pub addrtype: String,
#[serde(rename = "vendor", default = "get_unknown")]
pub vendor: String,
}
#[derive(PartialEq, Debug, Deserialize)]
pub struct Status {
pub state: String,
pub reason: String,
pub reason_ttl: String,
}
#[derive(Debug, Deserialize)]
pub struct Host {
#[serde(rename = "status")]
pub status: Status,
#[serde(rename = "address")]
pub address: Vec<Address>,
}
#[derive(Debug, Deserialize)]
pub struct NmapRun {
pub scanner: String,
pub args: String,
pub start: String,
pub startstr: String,
pub version: String,
pub xmloutputversion: String,
#[serde(rename = "host", default)]
pub hosts: Vec<Host>,
}
impl PartialEq for Host {
fn eq(&self, other: &Host) -> bool {
self.address[0].addr == other.address[0].addr
}
}
fn get_unknown() -> String { "Unknown".to_string() }
//ipmask: IP/Mask in String format like '192.168.1.0/24'
//round: Total round of scan can increase accuracy of result
pub fn do_scan_nmap(ipmask: &String, round: u8) -> Vec<Host> {
let mut res: Vec<Host> = vec![];
for _ in 0..round {
let file_temp = NamedTempFile::new().expect("Could not create tempfile");
let file_temp_path = file_temp
.path()
.to_str()
.expect("Could not find tempfile")
.to_string();
match Command::new("nmap")
.arg("-sn")
.arg("-PS")
.arg(format!("{}", &ipmask))
.arg("-oX")
.arg(file_temp_path.clone())
.stdout(Stdio::null())
.output()
{
Ok(r) => r,
Err(ref e) if e.kind() == ErrorKind::NotFound => {
exit(ExitCodes::NmapNotInstalled as i32);
}
Err(_) => {
exit(ExitCodes::NmapRunError as i32);
}
};
let reader = BufReader::new(file_temp.as_file());
let result: NmapRun = from_reader(reader).unwrap();
for g in result.hosts {
if !res.contains(&g) {
res.push(g);
}
}
}
res
}
pub fn do_scan_arp() -> HashMap<Ipv4Addr, MacAddr> {
let path = "/proc/net/arp";
let mut map: HashMap<Ipv4Addr, MacAddr> = HashMap::new();
let _f = match OpenOptions::new().read(true).write(false).open(path) {
Ok(v) => {
let file = BufReader::new(&v);
for (num, line) in file.lines().enumerate() {
if num == 0 {
continue;
}
let l = line.unwrap();
let mut x = l.split_whitespace();
let str_ip: &str = x.nth(0).unwrap();
let str_mac: &str = x.nth(2).unwrap();
if str_mac == "00:00:00:00:00:00" {
continue;
}
let ip: Ipv4Addr = str_ip.parse().unwrap();
let mac: MacAddr = MacAddr::from_str(str_mac).unwrap();
map.insert(ip, mac);
}
return map;
}
Err(e) => panic!("Unable to read mac address from {}, Err: {}", path, e),
};
}
pub fn get_hostname_addr() -> Result<Ipv4Addr, Error> {
let output = match Command::new("hostname").arg("-i").output() {
Ok(r) => r,
Err(ref e) if e.kind() == ErrorKind::NotFound => {
error!("Hostname command not found!");
exit(ExitCodes::HostnameNotFound as i32);
}
Err(e) => {
error!("Hostname command run error: {}", e);
exit(ExitCodes::HostnameRunError as i32);
}
};
let ip: Ipv4Addr = match String::from_utf8_lossy(&output.stdout).trim().parse() {
Ok(r) => r,
Err(e) => {
error!("Hostname output parse error: {}", e);
exit(ExitCodes::HostnameParseError as i32);
}
};
Ok(ip)
}
pub fn get_gateway() -> Gateway {
lazy_static! {
static ref RGX_MAC: Regex = Regex::new(r"([0-9a-fA-F]{1,2}[\.:-]){5}([0-9a-fA-F]{1,2})").unwrap();
static ref RGX_IP: Regex = Regex::new(r"((?:[0-9]{1,3}\.){3}[0-9]{1,3})").unwrap();
}
let output = Command::new("arp")
.arg("-a")
.arg("_gateway")
.output()
.expect("failed to execute process");
let f = String::from_utf8(output.stdout).unwrap();
if output.status.success() {
let ip = RGX_IP.find(&f).unwrap().as_str().parse().unwrap();
let mac = RGX_MAC.find(&f).unwrap().as_str().parse().unwrap();
let gw: Gateway = Gateway { ip: ip, mac: mac };
return gw;
} else {
let err = String::from_utf8_lossy(&output.stderr);
panic!("Unable to get gw! Err: {}", err);
}
}
|
// RaftFS :: A fancy filesystem that manages synchronized mirrors.
//
// Implemented using fuse_mt::FilesystemMT.
//
// Copyright (c) 2016-2017 by William R. Fraser
//
use std;
use std::ffi::{CStr, CString, OsStr, OsString};
use std::fs::{self, File};
use std::io::{self, Read, Write, Seek, SeekFrom};
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::os::unix::io::{FromRawFd, IntoRawFd};
use std::path::{Path, PathBuf};
use super::libc_extras::libc;
use super::libc_wrappers;
use fuse_mt::*;
use time::*;
pub struct RaftFS {
pub target: OsString,
}
fn mode_to_filetype(mode: libc::mode_t) -> FileType {
match mode & libc::S_IFMT {
libc::S_IFDIR => FileType::Directory,
libc::S_IFREG => FileType::RegularFile,
libc::S_IFLNK => FileType::Symlink,
libc::S_IFBLK => FileType::BlockDevice,
libc::S_IFCHR => FileType::CharDevice,
libc::S_IFIFO => FileType::NamedPipe,
libc::S_IFSOCK => FileType::Socket,
_ => { panic!("unknown file type"); }
}
}
fn stat_to_fuse(stat: libc::stat64) -> FileAttr {
let kind = mode_to_filetype(stat.st_mode);
let mode = stat.st_mode & 0o7777; // st_mode encodes the type AND the mode.
FileAttr {
size: stat.st_size as u64,
blocks: stat.st_blocks as u64,
atime: Timespec { sec: stat.st_atime as i64, nsec: stat.st_atime_nsec as i32 },
mtime: Timespec { sec: stat.st_mtime as i64, nsec: stat.st_mtime_nsec as i32 },
ctime: Timespec { sec: stat.st_ctime as i64, nsec: stat.st_ctime_nsec as i32 },
crtime: Timespec { sec: 0, nsec: 0 },
kind: kind,
perm: mode as u16,
nlink: stat.st_nlink as u32,
uid: stat.st_uid,
gid: stat.st_gid,
rdev: stat.st_rdev as u32,
flags: 0,
}
}
#[cfg(target_os = "macos")]
fn statfs_to_fuse(statfs: libc::statfs) -> Statfs {
Statfs {
blocks: statfs.f_blocks,
bfree: statfs.f_bfree,
bavail: statfs.f_bavail,
files: statfs.f_files,
ffree: statfs.f_ffree,
bsize: statfs.f_bsize as u32,
namelen: 0, // TODO
frsize: 0, // TODO
}
}
#[cfg(target_os = "linux")]
fn statfs_to_fuse(statfs: libc::statfs) -> Statfs {
Statfs {
blocks: statfs.f_blocks as u64,
bfree: statfs.f_bfree as u64,
bavail: statfs.f_bavail as u64,
files: statfs.f_files as u64,
ffree: statfs.f_ffree as u64,
bsize: statfs.f_bsize as u32,
namelen: statfs.f_namelen as u32,
frsize: statfs.f_frsize as u32,
}
}
impl RaftFS {
fn mustnt_exist(&self, partial: &Path) -> Result<(), i32> {
let partial = partial.strip_prefix("/").unwrap();
println!("backup_snapshot for {:?}", partial);
let path = PathBuf::from(&self.target).join(partial);
if path.symlink_metadata().is_ok() {
return Err(libc::EROFS);
}
Ok(())
}
fn copy_for_backup(&self, from: &Path, to: &Path) -> Result<(), std::io::Error> {
if !to.exists() {
if let Some(par) = to.parent() {
if !par.exists() {
self.copy_for_backup(from.parent().unwrap(), &par)?;
}
}
if from.is_file() {
std::fs::copy(from, to)?;
} else {
std::fs::create_dir(to)?;
}
}
Ok(())
}
fn backup_snapshot(&self, partial: &Path) -> Result<(), std::io::Error> {
let partial = partial.strip_prefix("/").unwrap();
println!("backup_snapshot for {:?}", partial);
let from = PathBuf::from(&self.target).join(partial);
for e in std::fs::read_dir(PathBuf::from(&self.target).join(".snapshots"))? {
let snappath = e?.path();
println!("backup_snapshot: {:?} for {:?}", snappath, partial);
self.copy_for_backup(&from, &snappath.join(partial))?;
}
Ok(())
}
fn whiteout_snapshot(&self, partial: &Path) -> Result<(), std::io::Error> {
let partial = partial.strip_prefix("/").unwrap();
println!("whiteout_snapshot for {:?}", partial);
for e in std::fs::read_dir(PathBuf::from(&self.target).join(".snapshots"))? {
let snappath = e?.path();
let real = snappath.join(partial);
println!("whiteout_snapshot: {:?}", real);
// whiteout is a socket
let result = unsafe {
let path_c = CString::from_vec_unchecked(real.as_os_str().as_bytes().to_vec());
libc::mknod(path_c.as_ptr(), libc::S_IFSOCK, 0)
};
if -1 == result {
let e = io::Error::last_os_error();
error!("whiteout mknod error({:?}, S_IFCHR, 0): {}", real, e);
return Err(e)
}
}
Ok(())
}
fn is_in_snapshot(&self, partial: &Path) -> bool {
if let Ok(child) = partial.strip_prefix("/.snapshots") {
let mut childstuff = child.iter();
if let Some(_) = childstuff.next() {
return childstuff.next().is_some();
}
}
false
}
fn is_snapshot(&self, partial: &Path) -> bool {
if let Ok(child) = partial.strip_prefix("/.snapshots") {
return child.iter().next().is_some();
}
false
}
fn real_path(&self, partial: &Path) -> OsString {
println!("reading real_path {:?}", partial);
let partial = partial.strip_prefix("/").unwrap();
if let Ok(child) = partial.strip_prefix(".snapshots") {
let mut childstuff = child.iter();
if let Some(snapname) = childstuff.next() {
let rest = childstuff.as_path();
if PathBuf::from(&self.target).join(".snapshots").join(snapname).is_dir() {
// The snapshot exists! Now check if the path has
// a snapshot value or whiteout.
match libc_wrappers::lstat(PathBuf::from(&self.target).join(partial).into_os_string()) {
Ok(stat) => {
let typ = mode_to_filetype(stat.st_mode);
if typ == FileType::Socket {
return OsString::from("this is an invalid whiteout path");
}
if typ == FileType::Directory {
// It is not a file that has been
// overridden. Directories are joined
// between the snapshot and the
// "real" directory.
println!("case 1 not overridden");
return PathBuf::from(&self.target).join(rest)
.into_os_string();
}
},
Err(_) => {
// It is not a file that has been overridden
println!("case 2 not overridden {:?}",
PathBuf::from(&self.target).join(partial));
return PathBuf::from(&self.target).join(rest)
.into_os_string();
}
}
if !PathBuf::from(&self.target).join(partial).is_file() {
// It is not a file that has been overridden
println!("case 3 not overridden");
return PathBuf::from(&self.target).join(rest)
.into_os_string();
}
}
}
}
PathBuf::from(&self.target).join(partial).into_os_string()
}
fn snap_path(&self, partial: &Path) -> OsString {
println!("reading snap_path {:?}", partial);
let partial = partial.strip_prefix("/").unwrap();
PathBuf::from(&self.target).join(partial).into_os_string()
}
fn stat_real(&self, path: &Path) -> io::Result<FileAttr> {
let real: OsString = self.real_path(path);
debug!("stat_real: {:?}", real);
match libc_wrappers::lstat(real) {
Ok(stat) => {
Ok(stat_to_fuse(stat))
},
Err(e) => {
let err = io::Error::from_raw_os_error(e);
error!("lstat({:?}): {}", path, err);
Err(err)
}
}
}
}
const TTL: Timespec = Timespec { sec: 1, nsec: 0 };
impl FilesystemMT for RaftFS {
fn init(&self, _req: RequestInfo) -> ResultEmpty {
debug!("init");
Ok(())
}
fn destroy(&self, _req: RequestInfo) {
debug!("destroy");
}
fn getattr(&self, _req: RequestInfo, path: &Path, fh: Option<u64>) -> ResultEntry {
debug!("getattr: {:?}", path);
if let Some(fh) = fh {
match libc_wrappers::fstat(fh) {
Ok(stat) => Ok((TTL, stat_to_fuse(stat))),
Err(e) => Err(e)
}
} else {
match self.stat_real(path) {
Ok(attr) => Ok((TTL, attr)),
Err(e) => Err(e.raw_os_error().unwrap())
}
}
}
fn opendir(&self, _req: RequestInfo, path: &Path, _flags: u32) -> ResultOpen {
let real = self.real_path(path);
let is_snap = self.is_snapshot(path);
debug!("opendir: {:?} (flags = {:#o}) {:?} IS_SNAP = {}",
real, _flags, path, is_snap);
match libc_wrappers::opendir(real) {
Ok(fh) => if is_snap {
Ok((fh | 1<<63, 0)) // large invalid file descriptor means snapshot!
} else {
Ok((fh, 0))
},
Err(e) => {
if is_snap {
// If the "real" directory is unreadable, just
// read the snapshot version of the directory.
if let Ok(fh) = libc_wrappers::opendir(self.snap_path(path)) {
return Ok((fh,0));
}
}
let ioerr = io::Error::from_raw_os_error(e);
error!("opendir({:?}): {}", path, ioerr);
Err(e)
}
}
}
fn releasedir(&self, _req: RequestInfo, path: &Path, fh: u64, _flags: u32) -> ResultEmpty {
debug!("releasedir: {:?}", path);
libc_wrappers::closedir(fh)
}
fn readdir(&self, _req: RequestInfo, path: &Path, infh: u64) -> ResultReaddir {
debug!("readdir: {:?}", path);
let mut entries: Vec<DirectoryEntry> = vec![];
let fh = infh & (! (1 << 63));
let is_snap = (infh & (1 << 63)) != 0;
if fh == 0 {
error!("readdir: missing fh");
return Err(libc::EINVAL);
}
loop {
match libc_wrappers::readdir(fh) {
Ok(Some(entry)) => {
let name_c = unsafe { CStr::from_ptr(entry.d_name.as_ptr()) };
let name = OsStr::from_bytes(name_c.to_bytes()).to_owned();
let mut filetype = match entry.d_type {
libc::DT_DIR => FileType::Directory,
libc::DT_REG => FileType::RegularFile,
libc::DT_LNK => FileType::Symlink,
libc::DT_BLK => FileType::BlockDevice,
libc::DT_CHR => FileType::CharDevice,
libc::DT_FIFO => FileType::NamedPipe,
libc::DT_SOCK => {
warn!("FUSE doesn't support Socket file type; translating to NamedPipe instead.");
FileType::NamedPipe
},
0 | _ => {
let entry_path = PathBuf::from(path).join(&name);
let real_path = self.real_path(&entry_path);
match libc_wrappers::lstat(real_path) {
Ok(stat64) => mode_to_filetype(stat64.st_mode),
Err(errno) => {
let ioerr = io::Error::from_raw_os_error(errno);
panic!("lstat failed after readdir_r gave no file type for {:?}: {}",
entry_path, ioerr);
}
}
}
};
if is_snap {
if name == OsStr::new(".snapshots") {
continue; // ignore any .snapshots in a snapshot
}
// Need to look for version of file in the
// snapshots directory now...
let entry_path = PathBuf::from(path).join(&name);
let real_path = self.real_path(&entry_path);
if let Ok(stat64) = libc_wrappers::lstat(real_path) {
// filetype of snap version should
// override the other
if stat64.st_mode == libc::S_IFSOCK {
continue; // treat as whiteout
}
filetype = mode_to_filetype(stat64.st_mode);
}
}
entries.push(DirectoryEntry {
name: name,
kind: filetype,
})
},
Ok(None) => { break; },
Err(e) => {
error!("readdir: {:?}: {}", path, e);
return Err(e);
}
}
}
Ok(entries)
}
fn open(&self, _req: RequestInfo, path: &Path, flags: u32) -> ResultOpen {
debug!("open: {:?} flags={:#x}", path, flags);
let real = self.real_path(path);
match libc_wrappers::open(real, flags as libc::c_int) {
Ok(fh) => Ok((fh, flags)),
Err(e) => {
error!("open({:?}) [... was {:?}]: {}", path, self.real_path(path),
io::Error::from_raw_os_error(e));
Err(e)
}
}
}
fn release(&self, _req: RequestInfo, path: &Path, fh: u64, _flags: u32, _lock_owner: u64, _flush: bool) -> ResultEmpty {
debug!("release: {:?}", path);
libc_wrappers::close(fh)
}
fn read(&self, _req: RequestInfo, path: &Path, fh: u64, offset: u64, size: u32) -> ResultData {
debug!("read: {:?} {:#x} @ {:#x}", path, size, offset);
let mut file = unsafe { UnmanagedFile::new(fh) };
let mut data = Vec::<u8>::with_capacity(size as usize);
unsafe { data.set_len(size as usize) };
if let Err(e) = file.seek(SeekFrom::Start(offset)) {
error!("seek({:?}, {}): {}", path, offset, e);
return Err(e.raw_os_error().unwrap());
}
match file.read(&mut data) {
Ok(n) => { data.truncate(n); },
Err(e) => {
error!("read {:?}, {:#x} @ {:#x}: {}", path, size, offset, e);
return Err(e.raw_os_error().unwrap());
}
}
Ok(data)
}
fn write(&self, _req: RequestInfo, path: &Path, fh: u64, offset: u64, data: Vec<u8>, _flags: u32) -> ResultWrite {
debug!("write: {:?} {:#x} @ {:#x}", path, data.len(), offset);
let mut file = unsafe { UnmanagedFile::new(fh) };
if let Err(e) = file.seek(SeekFrom::Start(offset)) {
error!("seek({:?}, {}): {}", path, offset, e);
return Err(e.raw_os_error().unwrap());
}
let nwritten: u32 = match file.write(&data) {
Ok(n) => n as u32,
Err(e) => {
error!("write {:?}, {:#x} @ {:#x}: {}", path, data.len(), offset, e);
return Err(e.raw_os_error().unwrap());
}
};
Ok(nwritten)
}
fn flush(&self, _req: RequestInfo, path: &Path, fh: u64, _lock_owner: u64) -> ResultEmpty {
debug!("flush: {:?}", path);
let mut file = unsafe { UnmanagedFile::new(fh) };
if let Err(e) = file.flush() {
error!("flush({:?}): {}", path, e);
return Err(e.raw_os_error().unwrap());
}
Ok(())
}
fn fsync(&self, _req: RequestInfo, path: &Path, fh: u64, datasync: bool) -> ResultEmpty {
debug!("fsync: {:?}, data={:?}", path, datasync);
let file = unsafe { UnmanagedFile::new(fh) };
if let Err(e) = if datasync {
file.sync_data()
} else {
file.sync_all()
} {
error!("fsync({:?}, {:?}): {}", path, datasync, e);
return Err(e.raw_os_error().unwrap());
}
Ok(())
}
fn chmod(&self, _req: RequestInfo, path: &Path, fh: Option<u64>, mode: u32) -> ResultEmpty {
debug!("chown: {:?} to {:#o}", path, mode);
let result = if let Some(fh) = fh {
unsafe { libc::fchmod(fh as libc::c_int, mode as libc::mode_t) }
} else {
let real = self.real_path(path);
unsafe {
let path_c = CString::from_vec_unchecked(real.into_vec());
libc::chmod(path_c.as_ptr(), mode as libc::mode_t)
}
};
if -1 == result {
let e = io::Error::last_os_error();
error!("chown({:?}, {:#o}): {}", path, mode, e);
Err(e.raw_os_error().unwrap())
} else {
Ok(())
}
}
fn chown(&self, _req: RequestInfo, path: &Path, fh: Option<u64>, uid: Option<u32>, gid: Option<u32>) -> ResultEmpty {
let uid = uid.unwrap_or(::std::u32::MAX); // docs say "-1", but uid_t is unsigned
let gid = gid.unwrap_or(::std::u32::MAX); // ditto for gid_t
debug!("chmod: {:?} to {}:{}", path, uid, gid);
let result = if let Some(fd) = fh {
unsafe { libc::fchown(fd as libc::c_int, uid, gid) }
} else {
let real = self.real_path(path);
unsafe {
let path_c = CString::from_vec_unchecked(real.into_vec());
libc::chown(path_c.as_ptr(), uid, gid)
}
};
if -1 == result {
let e = io::Error::last_os_error();
error!("chmod({:?}, {}, {}): {}", path, uid, gid, e);
Err(e.raw_os_error().unwrap())
} else {
Ok(())
}
}
fn truncate(&self, _req: RequestInfo, path: &Path, fh: Option<u64>, size: u64) -> ResultEmpty {
debug!("truncate: {:?} to {:#x}", path, size);
let result = if let Some(fd) = fh {
unsafe { libc::ftruncate64(fd as libc::c_int, size as i64) }
} else {
let real = self.real_path(path);
unsafe {
let path_c = CString::from_vec_unchecked(real.into_vec());
libc::truncate64(path_c.as_ptr(), size as i64)
}
};
if -1 == result {
let e = io::Error::last_os_error();
error!("truncate({:?}, {}): {}", path, size, e);
Err(e.raw_os_error().unwrap())
} else {
Ok(())
}
}
fn utimens(&self, _req: RequestInfo, path: &Path, fh: Option<u64>, atime: Option<Timespec>, mtime: Option<Timespec>) -> ResultEmpty {
debug!("utimens: {:?}: {:?}, {:?}", path, atime, mtime);
fn timespec_to_libc(time: Option<Timespec>) -> libc::timespec {
if let Some(time) = time {
libc::timespec {
tv_sec: time.sec as libc::time_t,
tv_nsec: time.nsec as libc::time_t,
}
} else {
libc::timespec {
tv_sec: 0,
tv_nsec: libc::UTIME_OMIT,
}
}
}
let times = [timespec_to_libc(atime), timespec_to_libc(mtime)];
let result = if let Some(fd) = fh {
unsafe { libc::futimens(fd as libc::c_int, × as *const libc::timespec) }
} else {
let real = self.real_path(path);
unsafe {
let path_c = CString::from_vec_unchecked(real.into_vec());
libc::utimensat(libc::AT_FDCWD, path_c.as_ptr(), × as *const libc::timespec, libc::AT_SYMLINK_NOFOLLOW)
}
};
if -1 == result {
let e = io::Error::last_os_error();
error!("utimens({:?}, {:?}, {:?}): {}", path, atime, mtime, e);
Err(e.raw_os_error().unwrap())
} else {
Ok(())
}
}
fn readlink(&self, _req: RequestInfo, path: &Path) -> ResultData {
debug!("readlink: {:?}", path);
let real = self.real_path(path);
match ::std::fs::read_link(real) {
Ok(target) => Ok(target.into_os_string().into_vec()),
Err(e) => Err(e.raw_os_error().unwrap()),
}
}
fn statfs(&self, _req: RequestInfo, path: &Path) -> ResultStatfs {
debug!("statfs: {:?}", path);
let real = self.real_path(path);
let mut buf: libc::statfs = unsafe { ::std::mem::zeroed() };
let result = unsafe {
let path_c = CString::from_vec_unchecked(real.into_vec());
libc::statfs(path_c.as_ptr(), &mut buf)
};
if -1 == result {
let e = io::Error::last_os_error();
error!("statfs({:?}): {}", path, e);
Err(e.raw_os_error().unwrap())
} else {
Ok(statfs_to_fuse(buf))
}
}
fn fsyncdir(&self, _req: RequestInfo, path: &Path, fh: u64, datasync: bool) -> ResultEmpty {
debug!("fsyncdir: {:?} (datasync = {:?})", path, datasync);
// TODO: what does datasync mean with regards to a directory handle?
let result = unsafe { libc::fsync(fh as libc::c_int) };
if -1 == result {
let e = io::Error::last_os_error();
error!("fsyncdir({:?}): {}", path, e);
Err(e.raw_os_error().unwrap())
} else {
Ok(())
}
}
fn mknod(&self, _req: RequestInfo, parent_path: &Path, name: &OsStr, mode: u32, rdev: u32) -> ResultEntry {
debug!("mknod: {:?}/{:?} (mode={:#o}, rdev={})", parent_path, name, mode, rdev);
let parent_path_name = parent_path.join(name);
self.mustnt_exist(&parent_path_name)?;
if self.is_snapshot(parent_path) {
return Err(libc::EROFS);
}
self.whiteout_snapshot(&parent_path_name);
let real = PathBuf::from(self.real_path(parent_path)).join(name);
let result = unsafe {
let path_c = CString::from_vec_unchecked(real.as_os_str().as_bytes().to_vec());
libc::mknod(path_c.as_ptr(), mode as libc::mode_t, rdev as libc::dev_t)
};
if -1 == result {
let e = io::Error::last_os_error();
error!("mknod({:?}, {}, {}): {}", real, mode, rdev, e);
Err(e.raw_os_error().unwrap())
} else {
match libc_wrappers::lstat(real.into_os_string()) {
Ok(attr) => Ok((TTL, stat_to_fuse(attr))),
Err(e) => Err(e), // if this happens, yikes
}
}
}
fn mkdir(&self, _req: RequestInfo, parent_path: &Path, name: &OsStr, mode: u32) -> ResultEntry {
debug!("mkdir {:?}/{:?} (mode={:#o})", parent_path, name, mode);
let parent_path_name = parent_path.join(name);
self.mustnt_exist(&parent_path_name)?;
if self.is_snapshot(parent_path) {
return Err(libc::EROFS);
}
self.whiteout_snapshot(&parent_path_name);
let real = PathBuf::from(self.real_path(parent_path)).join(name);
let result = unsafe {
let path_c = CString::from_vec_unchecked(real.as_os_str().as_bytes().to_vec());
libc::mkdir(path_c.as_ptr(), mode as libc::mode_t)
};
if -1 == result {
let e = io::Error::last_os_error();
error!("mkdir({:?}, {:#o}): {}", real, mode, e);
Err(e.raw_os_error().unwrap())
} else {
match libc_wrappers::lstat(real.clone().into_os_string()) {
Ok(attr) => Ok((TTL, stat_to_fuse(attr))),
Err(e) => {
error!("lstat after mkdir({:?}, {:#o}): {}", real, mode, e);
Err(e) // if this happens, yikes
},
}
}
}
fn unlink(&self, _req: RequestInfo, parent_path: &Path, name: &OsStr) -> ResultEmpty {
debug!("unlink {:?}/{:?}", parent_path, name);
if self.is_snapshot(parent_path) {
return Err(libc::EROFS);
}
let parent_path_name = parent_path.join(name);
self.backup_snapshot(&parent_path_name);
let real = PathBuf::from(self.real_path(parent_path)).join(name);
fs::remove_file(&real)
.map_err(|ioerr| {
error!("unlink({:?}): {}", real, ioerr);
ioerr.raw_os_error().unwrap()
})
}
fn rmdir(&self, _req: RequestInfo, parent_path: &Path, name: &OsStr) -> ResultEmpty {
debug!("rmdir: {:?}/{:?}", parent_path, name);
if self.is_snapshot(parent_path) {
return Err(libc::EROFS);
}
let real = PathBuf::from(self.real_path(parent_path)).join(name);
fs::remove_dir(&real)
.map_err(|ioerr| {
error!("rmdir({:?}): {}", real, ioerr);
ioerr.raw_os_error().unwrap()
})
}
fn symlink(&self, _req: RequestInfo, parent_path: &Path, name: &OsStr, target: &Path) -> ResultEntry {
debug!("symlink: {:?}/{:?} -> {:?}", parent_path, name, target);
if self.is_snapshot(parent_path) {
return Err(libc::EROFS);
}
let real = PathBuf::from(self.real_path(parent_path)).join(name);
match ::std::os::unix::fs::symlink(target, &real) {
Ok(()) => {
match libc_wrappers::lstat(real.clone().into_os_string()) {
Ok(attr) => Ok((TTL, stat_to_fuse(attr))),
Err(e) => {
error!("lstat after symlink({:?}, {:?}): {}", real, target, e);
Err(e)
},
}
},
Err(e) => {
error!("symlink({:?}, {:?}): {}", real, target, e);
Err(e.raw_os_error().unwrap())
}
}
}
fn rename(&self, _req: RequestInfo,
parent_path: &Path, name: &OsStr,
newparent_path: &Path, newname: &OsStr) -> ResultEmpty {
debug!("rename: {:?}/{:?} -> {:?}/{:?}",
parent_path, name, newparent_path, newname);
if self.is_snapshot(parent_path) || self.is_snapshot(newparent_path) {
return Err(libc::EROFS);
}
self.backup_snapshot(&parent_path.join(name));
self.whiteout_snapshot(&newparent_path.join(newname));
let real = PathBuf::from(self.real_path(parent_path)).join(name);
let newreal = PathBuf::from(self.real_path(newparent_path)).join(newname);
fs::rename(&real, &newreal)
.map_err(|ioerr| {
error!("rename({:?}, {:?}): {}", real, newreal, ioerr);
ioerr.raw_os_error().unwrap()
})
}
fn link(&self, _req: RequestInfo, path: &Path, newparent: &Path, newname: &OsStr) -> ResultEntry {
debug!("link: {:?} -> {:?}/{:?}", path, newparent, newname);
if self.is_snapshot(newparent) {
return Err(libc::EROFS);
}
let real = self.real_path(path);
let newreal = PathBuf::from(self.real_path(newparent)).join(newname);
match fs::hard_link(&real, &newreal) {
Ok(()) => {
match libc_wrappers::lstat(real.clone()) {
Ok(attr) => Ok((TTL, stat_to_fuse(attr))),
Err(e) => {
error!("lstat after link({:?}, {:?}): {}", real, newreal, e);
Err(e)
},
}
},
Err(e) => {
error!("link({:?}, {:?}): {}", real, newreal, e);
Err(e.raw_os_error().unwrap())
},
}
}
fn create(&self, _req: RequestInfo, parent: &Path, name: &OsStr, mode: u32, flags: u32) -> ResultCreate {
debug!("create: {:?}/{:?} (mode={:#o}, flags={:#x})", parent, name, mode, flags);
if self.is_snapshot(parent) {
return Err(libc::EROFS);
}
let real = PathBuf::from(self.real_path(parent)).join(name);
let fd = unsafe {
let real_c = CString::from_vec_unchecked(real.clone().into_os_string().into_vec());
libc::open(real_c.as_ptr(), flags as i32 | libc::O_CREAT | libc::O_EXCL, mode)
};
if -1 == fd {
let ioerr = io::Error::last_os_error();
error!("create({:?}): {}", real, ioerr);
Err(ioerr.raw_os_error().unwrap())
} else {
match libc_wrappers::lstat(real.clone().into_os_string()) {
Ok(attr) => Ok(CreatedEntry {
ttl: TTL,
attr: stat_to_fuse(attr),
fh: fd as u64,
flags: flags,
}),
Err(e) => {
error!("lstat after create({:?}): {}", real, io::Error::from_raw_os_error(e));
Err(e)
},
}
}
}
fn listxattr(&self, _req: RequestInfo, path: &Path, size: u32) -> ResultXattr {
debug!("listxattr: {:?}", path);
let real = self.real_path(path);
if size > 0 {
let mut data = Vec::<u8>::with_capacity(size as usize);
unsafe { data.set_len(size as usize) };
let nread = try!(libc_wrappers::llistxattr(real, data.as_mut_slice()));
data.truncate(nread);
Ok(Xattr::Data(data))
} else {
let nbytes = try!(libc_wrappers::llistxattr(real, &mut[]));
Ok(Xattr::Size(nbytes as u32))
}
}
fn getxattr(&self, _req: RequestInfo, path: &Path, name: &OsStr, size: u32) -> ResultXattr {
debug!("getxattr: {:?} {:?} {}", path, name, size);
let real = self.real_path(path);
if size > 0 {
let mut data = Vec::<u8>::with_capacity(size as usize);
unsafe { data.set_len(size as usize) };
let nread = try!(libc_wrappers::lgetxattr(real, name.to_owned(), data.as_mut_slice()));
data.truncate(nread);
Ok(Xattr::Data(data))
} else {
let nbytes = try!(libc_wrappers::lgetxattr(real, name.to_owned(), &mut []));
Ok(Xattr::Size(nbytes as u32))
}
}
fn setxattr(&self, _req: RequestInfo, path: &Path, name: &OsStr, value: &[u8], flags: u32, position: u32) -> ResultEmpty {
debug!("setxattr: {:?} {:?} {} bytes, flags = {:#x}, pos = {}", path, name, value.len(), flags, position);
if self.is_snapshot(path) {
return Err(libc::EROFS);
}
let real = self.real_path(path);
libc_wrappers::lsetxattr(real, name.to_owned(), value, flags, position)
}
fn removexattr(&self, _req: RequestInfo, path: &Path, name: &OsStr) -> ResultEmpty {
debug!("removexattr: {:?} {:?}", path, name);
if self.is_snapshot(path) {
return Err(libc::EROFS);
}
let real = self.real_path(path);
libc_wrappers::lremovexattr(real, name.to_owned())
}
}
/// A file that is not closed upon leaving scope.
struct UnmanagedFile {
inner: Option<File>,
}
impl UnmanagedFile {
unsafe fn new(fd: u64) -> UnmanagedFile {
UnmanagedFile {
inner: Some(File::from_raw_fd(fd as i32))
}
}
fn sync_all(&self) -> io::Result<()> {
self.inner.as_ref().unwrap().sync_all()
}
fn sync_data(&self) -> io::Result<()> {
self.inner.as_ref().unwrap().sync_data()
}
}
impl Drop for UnmanagedFile {
fn drop(&mut self) {
// Release control of the file descriptor so it is not closed.
let file = self.inner.take().unwrap();
file.into_raw_fd();
}
}
impl Read for UnmanagedFile {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.inner.as_ref().unwrap().read(buf)
}
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
self.inner.as_ref().unwrap().read_to_end(buf)
}
}
impl Write for UnmanagedFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.inner.as_ref().unwrap().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.inner.as_ref().unwrap().flush()
}
}
impl Seek for UnmanagedFile {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
self.inner.as_ref().unwrap().seek(pos)
}
}
|
extern crate rand;
extern crate wasm_bindgen;
mod functions;
mod neural_network;
mod neuron;
|
use colored::*;
use std::borrow::Cow;
use std::cell::RefCell;
use std::rc::Rc;
use anyhow::{Context, Result};
use clap::ArgMatches;
use crate::cli::cfg::get_cfg;
use crate::cli::error::CliError;
use crate::cli::settings::get_settings;
use crate::cli::terminal::confirm::{confirm, EnumConfirm};
use crate::cli::terminal::message::success;
use crate::env_file::{Env, EnvDiffController};
#[derive(Debug)]
pub struct SyncSettings {
pub empty: bool,
pub copy: bool,
pub delete: bool,
pub no_delete: bool,
pub file: Option<String>,
}
impl SyncSettings {
pub fn new(args: &ArgMatches) -> Self {
Self {
empty: args.is_present("empty"),
copy: args.is_present("copy"),
delete: args.is_present("delete"),
no_delete: args.is_present("no_delete"),
file: args.value_of("file").map(|f| f.to_string()),
}
}
}
enum_confirm!(SyncConfirmEnum, y, n);
pub fn env_sync(app: &ArgMatches) -> Result<()> {
let mut cfg = get_cfg()?;
cfg.sync_local_to_global()?;
let cfg = cfg;
let settings = get_settings(app, &cfg);
let sync_settings = SyncSettings::new(app);
let setup = cfg.current_setup(settings.setup()?)?;
let envs = setup.envs();
let envs: Vec<_> = envs.into_iter().filter_map(|r| r.ok()).collect();
let recent_env = Env::recent(&envs)?;
sync_workflow(recent_env, envs, sync_settings)?;
success("files synchronized");
Ok(())
}
pub fn sync_workflow(
source_env: Env,
envs: Vec<Env>,
sync_settings: SyncSettings,
) -> Result<Vec<Env>> {
let source_env = if let Some(file) = sync_settings.file.as_ref() {
Env::from_file_reader(file)?
} else {
source_env
};
let envs: Vec<_> = envs.into_iter().map(|env| RefCell::new(env)).collect();
let sync_settings = Rc::new(sync_settings);
for env_cell in envs.iter() {
let mut env = env_cell.borrow_mut();
if env.file() == source_env.file() {
continue;
}
let env_name = Rc::new(env.name()?);
let env_name_update_var = Rc::clone(&env_name);
let env_name_delete_var = Rc::clone(&env_name);
let sync_settings_update_var = Rc::clone(&sync_settings);
let sync_settings_delete_var = Rc::clone(&sync_settings);
let controller = EnvDiffController::new(
move |var| {
if sync_settings_update_var.empty {
var.set_value("");
return Ok(Cow::Borrowed(var));
}
if sync_settings_update_var.copy {
return Ok(Cow::Borrowed(var));
}
let output = std::io::stdout();
let r = match confirm(
output,
format!(
"Set `{}`:`{}`=`{}`. Change value ?",
env_name_update_var.bold(),
var.name().bold(),
var.value().bold()
)
.as_str(),
SyncConfirmEnum::to_vec(),
) {
Ok(r) => r,
Err(e) => return Err(e),
};
let new_value = match &r {
SyncConfirmEnum::y => {
println!("New value `{}`=", var.name());
let mut new_value = String::new();
std::io::stdin().read_line(&mut new_value).unwrap();
Some(new_value)
}
_ => None,
};
if let Some(new_value) = new_value {
var.set_value(new_value.as_str());
Ok(Cow::Borrowed(var))
} else {
Ok(Cow::Borrowed(var))
}
},
move |var| {
if sync_settings_delete_var.delete {
return Ok(true);
}
if sync_settings_delete_var.no_delete {
return Err(CliError::DeleteVarNowAllowed(
var.name().clone(),
var.value().clone(),
env_name_delete_var.to_string(),
)
.into());
}
let output = std::io::stdout();
let r = confirm(
output,
format!(
"Remove `{}`:`{}`=`{}`",
env_name_delete_var.bold(),
var.name().bold(),
var.value().bold()
)
.as_str(),
SyncConfirmEnum::to_vec(),
)
.unwrap();
if let SyncConfirmEnum::y = r {
Ok(true)
} else {
Err(CliError::DeleteVarNowAllowed(
var.name().clone(),
var.value().clone(),
env_name_delete_var.to_string(),
)
.into())
}
},
);
env.update_by_diff(&source_env, &controller)
.context((CliError::EnvFileMustBeSync).to_string())?;
env.save().unwrap();
}
let envs: Vec<_> = envs.into_iter().map(|env| env.into_inner()).collect();
Ok(envs)
}
|
use std::env::current_exe;
use std::fs::File;
use std::io::{self, Read};
use std::path::PathBuf;
use std::vec::IntoIter;
#[derive(Debug)]
pub struct Command {
exe: Option<PathBuf>,
args: Vec<String>,
}
impl Command {
pub fn new() -> Self {
Command { exe: None, args: vec![] }
}
pub fn arg(&mut self, arg: String) {
match self.exe {
Some(_) => self.args.push(arg),
None => self.exe = Some(PathBuf::from(arg)),
}
}
pub fn exe(&self) -> Option<&PathBuf> {
self.exe.as_ref()
}
pub fn args(&self) -> &Vec<String> {
&self.args
}
}
pub struct Commands {
iter: IntoIter<Result<u8, io::Error>>,
done: bool,
}
// Helper to push a byte array as argument into command.
macro_rules! push_arg {
( $command:expr, $bytes:expr ) => {
match String::from_utf8($bytes) {
Ok(arg) => { $command.arg(arg); },
Err(e) => {
eprintln!("bad shim: {}", e);
return None;
},
}
};
}
impl Commands {
pub fn from(bytes: Vec<Result<u8, io::Error>>) -> Self {
Commands { iter: bytes.into_iter(), done: false }
}
pub fn from_current_exe() -> Result<Self, String> {
let exe = current_exe().map_err(|e| e.to_string())?;
let file = File::open(&exe).map_err(|e| e.to_string())?;
let mut bytes: Vec<_> = io::BufReader::new(file).bytes().collect();
bytes.reverse();
Ok(Self::from(bytes))
}
fn read_next_command(&mut self) -> Option<Command> {
let mut command = Command::new();
let mut bytes = vec![];
while let Some(result) = self.iter.next() { match result {
Ok(byte) => match byte {
10 => { // Line feed signifies end of command.
if !bytes.is_empty() {
push_arg!(command, bytes);
}
return match command.exe() {
Some(_) => Some(command),
None => None,
};
},
0 => { // Null signifies end of argument.
push_arg!(command, bytes);
bytes = vec![];
},
_ => { bytes.push(byte); },
},
Err(e) => {
eprintln!("shim read failure: {}", e);
return None;
},
}}
None
}
}
impl Iterator for Commands {
type Item = Command;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
match self.read_next_command() {
r @ Some(_) => r,
None => { self.done = true; None },
}
}
}
#[cfg(test)]
mod command_test {
use std::path::PathBuf;
use super::Command;
#[test]
fn new() {
let command = Command::new();
assert_eq!(command.exe(), None);
assert_eq!(command.args(), &Vec::<String>::new());
}
#[test]
fn push_exe() {
let mut command = Command::new();
command.arg(String::from("C:\\python.exe"));
assert_eq!(command.exe(), Some(&PathBuf::from("C:\\python.exe")));
assert_eq!(command.args(), &Vec::<String>::new());
}
#[test]
fn push_exe_arg() {
let mut command = Command::new();
command.arg(String::from("C:\\python.exe"));
command.arg(String::from("-OO"));
command.arg(String::from("-c"));
command.arg(String::from("import sys; print(sys.executable)"));
assert_eq!(command.exe(), Some(&PathBuf::from("C:\\python.exe")));
assert_eq!(command.args(), &vec![
String::from("-OO"),
String::from("-c"),
String::from("import sys; print(sys.executable)"),
]);
}
}
#[cfg(test)]
mod commands_test {
use std::path::PathBuf;
use super::Commands;
#[test]
fn consume_all() {
let mut commands = Commands::from("\
C:\\python.exe\n\
C:\\python.exe\0--version\n\
C:\\python.exe\0-OO\0-c\0import sys; print(sys.executable)\n\
".bytes().map(|b| Ok(b)).collect());
let command = commands.next().unwrap();
assert_eq!(command.exe(), Some(&PathBuf::from("C:\\python.exe")));
assert_eq!(command.args(), &Vec::<String>::new());
let command = commands.next().unwrap();
assert_eq!(command.exe(), Some(&PathBuf::from("C:\\python.exe")));
assert_eq!(command.args(), &vec![String::from("--version")]);
let command = commands.next().unwrap();
assert_eq!(command.exe(), Some(&PathBuf::from("C:\\python.exe")));
assert_eq!(command.args(), &vec![
String::from("-OO"),
String::from("-c"),
String::from("import sys; print(sys.executable)"),
]);
assert_eq!(commands.next().is_none(), true);
}
#[test]
fn avoid_garbage() {
let mut commands = Commands::from(
"C:\\python.exe\n\n12345".bytes().map(|b| Ok(b)).collect(),
);
let command = commands.next().unwrap();
assert_eq!(command.exe(), Some(&PathBuf::from("C:\\python.exe")));
assert_eq!(command.args(), &Vec::<String>::new());
assert_eq!(commands.next().is_none(), true);
assert_eq!(commands.next().is_none(), true);
assert_eq!(commands.next().is_none(), true);
}
}
|
#![allow(unused_parens)]
#![allow(unused_imports)]
use frame_support::{traits::Get, weights::Weight};
use sp_std::marker::PhantomData;
/// Weight functions for pallet_session.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_session::WeightInfo for WeightInfo<T> {
fn set_keys() -> Weight {
(25_201_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn purge_keys() -> Weight {
(17_510_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
}
|
use std::iter;
use std::convert::TryInto;
pub fn is_square_free(n: i64) -> bool {
// Enough to test 4 followed by all odd squares that are less than n.
let n = n.abs();
!iter::once(2i64)
.chain((3..n).into_iter().step_by(2))
.map(|i| i.pow(2))
.take_while(|i| i <= &n)
.any(|i| (n % i) == 0)
}
pub fn convert_input(base: i32, exponent: i32, sub: i32) -> i64 {
(base as i64).pow(exponent.try_into().unwrap()) - (sub as i64)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn not_square_free() {
assert!(!is_square_free(4));
assert!(!is_square_free(9));
assert!(!is_square_free(144));
}
#[test]
fn square_free() {
assert!(is_square_free(2));
assert!(is_square_free(21));
assert!(is_square_free(2_u128.pow(5) - 1));
}
}
|
use bootstrap;
use std::fs::{self, File};
use std::io;
use std::io::prelude::*;
use std::os::unix::fs::*;
use std::path::{Path, PathBuf};
use time::{self, Timespec};
use util::RecursiveDirIterator;
use zip::write::*;
/// Update metadata information.
#[derive(Clone)]
pub enum UpdateEndpoint {
Zsync {
url: String,
},
BintrayZsync {
username: String,
repository: String,
package: String,
path: String,
},
}
impl ToString for UpdateEndpoint {
fn to_string(&self) -> String {
match self {
&UpdateEndpoint::Zsync {
ref url,
} => format!("zsync|{}", url),
&UpdateEndpoint::BintrayZsync {
ref username,
ref repository,
ref package,
ref path,
} => format!("bintray-zsync|{}|{}|{}|{}", username, repository, package, path),
}
}
}
/// Creates an AppImage.
pub struct Creator {
app_dir: PathBuf,
update_endpoint: Option<UpdateEndpoint>,
}
impl Creator {
pub fn new<P: Into<PathBuf>>(app_dir: P) -> Creator {
Creator {
app_dir: app_dir.into(),
update_endpoint: None,
}
}
pub fn write_to<W: Write + Seek>(&self, mut writer: W) -> io::Result<()> {
// First start the file with the bootstrap binary.
bootstrap::write(&mut writer);
// Now create a zip archive by copying all files in the app dir.
let mut zip = ZipWriter::new(&mut writer);
for entry in RecursiveDirIterator::new(&self.app_dir)?.filter_map(|r| r.ok()) {
println!("copy: {:?}", entry.path());
let path = entry.path();
let relative_path = entry.path().strip_prefix(&self.app_dir).unwrap().to_path_buf();
if path.exists() {
let metadata = fs::metadata(entry.path())?;
let mtime = Timespec::new(metadata.mtime(), metadata.mtime_nsec() as i32);
let options = FileOptions::default()
.last_modified_time(time::at(mtime))
.unix_permissions(metadata.mode());
if entry.file_type()?.is_dir() {
let name_with_slash = format!("{}/", relative_path.to_string_lossy());
zip.add_directory(name_with_slash, options)?;
} else {
zip.start_file(relative_path.to_string_lossy(), options)?;
let mut file = File::open(entry.path())?;
io::copy(&mut file, &mut zip)?;
zip.flush()?;
}
}
}
zip.finish()?;
Ok(())
}
pub fn write_to_file<P: AsRef<Path>>(&self, path: P)-> io::Result<()> {
let mut file = File::create(path)?;
self.write_to(&mut file)?;
// Mark the file as executable.
let mut permissions = file.metadata()?.permissions();
let mode = permissions.mode() | 0o111;
permissions.set_mode(mode);
file.set_permissions(permissions)?;
Ok(())
}
}
|
use crate::conv_req::convert_req;
use crate::Options;
use actix_web::{http::StatusCode, web, HttpRequest, HttpResponse};
use fmterr::fmt_err;
use perseus::error_pages::ErrorPageData;
use perseus::html_shell::interpolate_page_data;
use perseus::router::{match_route, RouteInfo, RouteVerdict};
use perseus::{
err_to_status_code,
serve::get_page_for_template,
stores::{ImmutableStore, MutableStore},
ErrorPages, SsrNode, TranslationsManager, Translator,
};
use std::collections::HashMap;
use std::rc::Rc;
/// Returns a fully formed error page to the client, with parameters for hydration.
fn return_error_page(
url: &str,
status: &u16,
// This should already have been transformed into a string (with a source chain etc.)
err: &str,
translator: Option<Rc<Translator>>,
error_pages: &ErrorPages<SsrNode>,
html: &str,
root_id: &str,
) -> HttpResponse {
let error_html = error_pages.render_to_string(url, status, err, translator);
// We create a JSON representation of the data necessary to hydrate the error page on the client-side
// Right now, translators are never included in transmitted error pages
let error_page_data = serde_json::to_string(&ErrorPageData {
url: url.to_string(),
status: *status,
err: err.to_string(),
})
.unwrap();
// Add a global variable that defines this as an error
let state_var = format!(
"<script>window.__PERSEUS_INITIAL_STATE = `error-{}`;</script>",
error_page_data
// We escape any backslashes to prevent their interfering with JSON delimiters
.replace(r#"\"#, r#"\\"#)
// We escape any backticks, which would interfere with JS's raw strings system
.replace(r#"`"#, r#"\`"#)
// We escape any interpolations into JS's raw string system
.replace(r#"${"#, r#"\${"#)
);
let html_with_declaration = html.replace("</head>", &format!("{}\n</head>", state_var));
// Interpolate the error page itself
let html_to_replace_double = format!("<div id=\"{}\">", root_id);
let html_to_replace_single = format!("<div id='{}'>", root_id);
let html_replacement = format!(
// We give the content a specific ID so that it can be hydrated properly
"{}<div id=\"__perseus_content_initial\" class=\"__perseus_content\">{}</div>",
&html_to_replace_double,
&error_html
);
// Now interpolate that HTML into the HTML shell
let final_html = html_with_declaration
.replace(&html_to_replace_double, &html_replacement)
.replace(&html_to_replace_single, &html_replacement);
HttpResponse::build(StatusCode::from_u16(*status).unwrap())
.content_type("text/html")
.body(final_html)
}
/// The handler for calls to any actual pages (first-time visits), which will render the appropriate HTML and then interpolate it into
/// the app shell.
pub async fn initial_load<M: MutableStore, T: TranslationsManager>(
req: HttpRequest,
opts: web::Data<Options>,
html_shell: web::Data<String>,
render_cfg: web::Data<HashMap<String, String>>,
immutable_store: web::Data<ImmutableStore>,
mutable_store: web::Data<M>,
translations_manager: web::Data<T>,
) -> HttpResponse {
let templates = &opts.templates_map;
let error_pages = &opts.error_pages;
let path = req.path();
let path_slice: Vec<&str> = path
.split('/')
// Removing empty elements is particularly important, because the path will have a leading `/`
.filter(|p| !p.is_empty())
.collect();
// Create a closure to make returning error pages easier (most have the same data)
let html_err = |status: u16, err: &str| {
return return_error_page(
path,
&status,
err,
None,
error_pages,
html_shell.get_ref(),
&opts.root_id,
);
};
// Run the routing algorithms on the path to figure out which template we need
let verdict = match_route(&path_slice, render_cfg.get_ref(), templates, &opts.locales);
match verdict {
// If this is the outcome, we know that the locale is supported and the like
// Given that all this is valid from the client, any errors are 500s
RouteVerdict::Found(RouteInfo {
path, // Used for asset fetching, this is what we'd get in `page_data`
template, // The actual template to use
locale,
was_incremental_match,
}) => {
// We need to turn the Actix Web request into one acceptable for Perseus (uses `http` internally)
let http_req = convert_req(&req);
let http_req = match http_req {
Ok(http_req) => http_req,
// If this fails, the client request is malformed, so it's a 400
Err(err) => {
return html_err(400, &fmt_err(&err));
}
};
// Actually render the page as we would if this weren't an initial load
let page_data = get_page_for_template(
&path,
&locale,
&template,
was_incremental_match,
http_req,
(immutable_store.get_ref(), mutable_store.get_ref()),
translations_manager.get_ref(),
)
.await;
let page_data = match page_data {
Ok(page_data) => page_data,
// We parse the error to return an appropriate status code
Err(err) => {
return html_err(err_to_status_code(&err), &fmt_err(&err));
}
};
let final_html = interpolate_page_data(&html_shell, &page_data, &opts.root_id);
let mut http_res = HttpResponse::Ok();
http_res.content_type("text/html");
// Generate and add HTTP headers
for (key, val) in template.get_headers(page_data.state) {
http_res.set_header(key.unwrap(), val);
}
http_res.body(final_html)
}
// For locale detection, we don't know the user's locale, so there's not much we can do except send down the app shell, which will do the rest and fetch from `.perseus/page/...`
RouteVerdict::LocaleDetection(_) => {
// We use a `302 Found` status code to indicate a redirect
// We 'should' generate a `Location` field for the redirect, but it's not RFC-mandated, so we can use the app shell
HttpResponse::Found()
.content_type("text/html")
.body(html_shell.get_ref())
}
RouteVerdict::NotFound => html_err(404, "page not found"),
}
}
|
#[doc = "Register `SECCFGR` reader"]
pub type R = crate::R<SECCFGR_SPEC>;
#[doc = "Register `SECCFGR` writer"]
pub type W = crate::W<SECCFGR_SPEC>;
#[doc = "Field `SYSCFGSEC` reader - SYSCFG clock control security"]
pub type SYSCFGSEC_R = crate::BitReader;
#[doc = "Field `SYSCFGSEC` writer - SYSCFG clock control security"]
pub type SYSCFGSEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CLASSBSEC` reader - ClassB security"]
pub type CLASSBSEC_R = crate::BitReader;
#[doc = "Field `CLASSBSEC` writer - ClassB security"]
pub type CLASSBSEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SRAM2SEC` reader - SRAM2 security"]
pub type SRAM2SEC_R = crate::BitReader;
#[doc = "Field `SRAM2SEC` writer - SRAM2 security"]
pub type SRAM2SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FPUSEC` reader - FPUSEC"]
pub type FPUSEC_R = crate::BitReader;
#[doc = "Field `FPUSEC` writer - FPUSEC"]
pub type FPUSEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - SYSCFG clock control security"]
#[inline(always)]
pub fn syscfgsec(&self) -> SYSCFGSEC_R {
SYSCFGSEC_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - ClassB security"]
#[inline(always)]
pub fn classbsec(&self) -> CLASSBSEC_R {
CLASSBSEC_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - SRAM2 security"]
#[inline(always)]
pub fn sram2sec(&self) -> SRAM2SEC_R {
SRAM2SEC_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - FPUSEC"]
#[inline(always)]
pub fn fpusec(&self) -> FPUSEC_R {
FPUSEC_R::new(((self.bits >> 3) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - SYSCFG clock control security"]
#[inline(always)]
#[must_use]
pub fn syscfgsec(&mut self) -> SYSCFGSEC_W<SECCFGR_SPEC, 0> {
SYSCFGSEC_W::new(self)
}
#[doc = "Bit 1 - ClassB security"]
#[inline(always)]
#[must_use]
pub fn classbsec(&mut self) -> CLASSBSEC_W<SECCFGR_SPEC, 1> {
CLASSBSEC_W::new(self)
}
#[doc = "Bit 2 - SRAM2 security"]
#[inline(always)]
#[must_use]
pub fn sram2sec(&mut self) -> SRAM2SEC_W<SECCFGR_SPEC, 2> {
SRAM2SEC_W::new(self)
}
#[doc = "Bit 3 - FPUSEC"]
#[inline(always)]
#[must_use]
pub fn fpusec(&mut self) -> FPUSEC_W<SECCFGR_SPEC, 3> {
FPUSEC_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 = "SYSCFG secure configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`seccfgr::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 [`seccfgr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SECCFGR_SPEC;
impl crate::RegisterSpec for SECCFGR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`seccfgr::R`](R) reader structure"]
impl crate::Readable for SECCFGR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`seccfgr::W`](W) writer structure"]
impl crate::Writable for SECCFGR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets SECCFGR to value 0"]
impl crate::Resettable for SECCFGR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
pub extern crate style;
pub extern crate cssparser;
pub extern crate style_traits;
pub extern crate servo_url;
use style::properties::longhands::background_size;
use style::properties::longhands::{
background_attachment, background_clip, background_color, background_image,
};
use style::properties::longhands::{
background_origin, background_position_x, background_position_y, background_repeat,
};
use style::properties::shorthands::background;
use style_traits::CssWriter;
use cssparser::{Parser, ParserInput};
use style::context::QuirksMode;
use style::parser::ParserContext;
use style::stylesheets::{CssRuleType, Origin};
use style_traits::{ParseError, ParsingMode, ToCss};
pub fn parse_background(input: &str) -> style::properties::shorthands::background::Longhands {
return parse(background::parse_value, input).unwrap();
}
fn parse<'a, T, F>(f: F, s: &'a str) -> Result<T, ParseError<'a>>
where
F: for<'t> Fn(&ParserContext, &mut Parser<'a, 't>) -> Result<T, ParseError<'a>>,
{
let mut input = ParserInput::new(s);
parse_input(f, &mut input)
}
fn parse_input<'i: 't, 't, T, F>(f: F, input: &'t mut ParserInput<'i>) -> Result<T, ParseError<'i>>
where
F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>>,
{
let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap();
let context = ParserContext::new(
Origin::Author,
&url,
Some(CssRuleType::Style),
ParsingMode::DEFAULT,
QuirksMode::NoQuirks,
None,
None,
);
let mut parser = Parser::new(input);
f(&context, &mut parser)
}
|
mod container;
mod generation;
mod icons;
mod template;
pub use template::get_template;
|
use super::constants::{LEDGERS_FREEZE, GET_FROZEN_LEDGERS};
#[derive(Serialize, PartialEq, Debug)]
pub struct LedgersFreezeOperation {
#[serde(rename = "type")]
pub _type: String,
pub ledgers_ids: Vec<u64>,
}
impl LedgersFreezeOperation {
pub fn new(ledgers_ids: Vec<u64>) -> LedgersFreezeOperation {
LedgersFreezeOperation {
_type: LEDGERS_FREEZE.to_string(),
ledgers_ids
}
}
}
#[derive(Serialize, PartialEq, Debug)]
pub struct GetFrozenLedgersOperation {
#[serde(rename = "type")]
pub _type: String
}
impl GetFrozenLedgersOperation {
pub fn new() -> GetFrozenLedgersOperation {
GetFrozenLedgersOperation {
_type: GET_FROZEN_LEDGERS.to_string()
}
}
}
|
pub fn write(fd: u64, buf: u64, count: u64) -> u64 {
let buf = buf as usize;
let count = count as usize;
println!("Syscall: write fd={:x} buf={:x} count={:x}", fd, buf, count);
unsafe {
let s = ::utils::zs_to_str_n(buf, count);
println!("-> {}", s);
}
count as u64
}
|
use crate::{
bytes::Bytes,
core::error::OutPointError,
core::{BlockView, Capacity, DepType, TransactionInfo, TransactionView},
packed::{Byte32, CellOutput, OutPoint, OutPointVec},
prelude::*,
};
use ckb_error::Error;
use ckb_occupied_capacity::Result as CapacityResult;
use std::collections::{HashMap, HashSet};
use std::convert::TryInto;
use std::fmt;
use std::hash::BuildHasher;
#[derive(Clone, Eq, PartialEq, Default)]
pub struct CellMeta {
pub cell_output: CellOutput,
pub out_point: OutPoint,
pub transaction_info: Option<TransactionInfo>,
pub data_bytes: u64,
/// In memory cell data and its hash
/// A live cell either exists in memory or DB
/// must check DB if this field is None
pub mem_cell_data: Option<(Bytes, Byte32)>,
}
#[derive(Default)]
pub struct CellMetaBuilder {
cell_output: CellOutput,
out_point: OutPoint,
transaction_info: Option<TransactionInfo>,
data_bytes: u64,
mem_cell_data: Option<(Bytes, Byte32)>,
}
impl CellMetaBuilder {
pub fn from_cell_meta(cell_meta: CellMeta) -> Self {
let CellMeta {
cell_output,
out_point,
transaction_info,
data_bytes,
mem_cell_data,
} = cell_meta;
Self {
cell_output,
out_point,
transaction_info,
data_bytes,
mem_cell_data,
}
}
pub fn from_cell_output(cell_output: CellOutput, data: Bytes) -> Self {
let mut builder = CellMetaBuilder::default();
builder.cell_output = cell_output;
builder.data_bytes = data.len().try_into().expect("u32");
let data_hash = CellOutput::calc_data_hash(&data);
builder.mem_cell_data = Some((data, data_hash));
builder
}
pub fn out_point(mut self, out_point: OutPoint) -> Self {
self.out_point = out_point;
self
}
pub fn transaction_info(mut self, transaction_info: TransactionInfo) -> Self {
self.transaction_info = Some(transaction_info);
self
}
pub fn build(self) -> CellMeta {
let Self {
cell_output,
out_point,
transaction_info,
data_bytes,
mem_cell_data,
} = self;
CellMeta {
cell_output,
out_point,
transaction_info,
data_bytes,
mem_cell_data,
}
}
}
impl fmt::Debug for CellMeta {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("CellMeta")
.field("cell_output", &self.cell_output)
.field("out_point", &self.out_point)
.field("transaction_info", &self.transaction_info)
.field("data_bytes", &self.data_bytes)
.finish()
}
}
impl CellMeta {
pub fn is_cellbase(&self) -> bool {
self.transaction_info
.as_ref()
.map(TransactionInfo::is_cellbase)
.unwrap_or(false)
}
pub fn capacity(&self) -> Capacity {
self.cell_output.capacity().unpack()
}
pub fn occupied_capacity(&self) -> CapacityResult<Capacity> {
self.cell_output
.occupied_capacity(Capacity::bytes(self.data_bytes as usize)?)
}
pub fn is_lack_of_capacity(&self) -> CapacityResult<bool> {
self.cell_output
.is_lack_of_capacity(Capacity::bytes(self.data_bytes as usize)?)
}
}
#[derive(PartialEq, Debug)]
pub enum CellStatus {
/// Cell exists and has not been spent.
Live(Box<CellMeta>),
/// Cell exists and has been spent.
Dead,
/// Cell does not exist.
Unknown,
}
impl CellStatus {
pub fn live_cell(cell_meta: CellMeta) -> CellStatus {
CellStatus::Live(Box::new(cell_meta))
}
pub fn is_live(&self) -> bool {
match *self {
CellStatus::Live(_) => true,
_ => false,
}
}
pub fn is_dead(&self) -> bool {
self == &CellStatus::Dead
}
pub fn is_unknown(&self) -> bool {
self == &CellStatus::Unknown
}
}
/// Transaction with resolved input cells.
#[derive(Debug)]
pub struct ResolvedTransaction {
pub transaction: TransactionView,
pub resolved_cell_deps: Vec<CellMeta>,
pub resolved_inputs: Vec<CellMeta>,
pub resolved_dep_groups: Vec<CellMeta>,
}
pub trait CellProvider {
fn cell(&self, out_point: &OutPoint, with_data: bool) -> CellStatus;
}
pub struct OverlayCellProvider<'a, A, B> {
overlay: &'a A,
cell_provider: &'a B,
}
impl<'a, A, B> OverlayCellProvider<'a, A, B>
where
A: CellProvider,
B: CellProvider,
{
pub fn new(overlay: &'a A, cell_provider: &'a B) -> Self {
Self {
overlay,
cell_provider,
}
}
}
impl<'a, A, B> CellProvider for OverlayCellProvider<'a, A, B>
where
A: CellProvider,
B: CellProvider,
{
fn cell(&self, out_point: &OutPoint, with_data: bool) -> CellStatus {
match self.overlay.cell(out_point, with_data) {
CellStatus::Live(cell_meta) => CellStatus::Live(cell_meta),
CellStatus::Dead => CellStatus::Dead,
CellStatus::Unknown => self.cell_provider.cell(out_point, with_data),
}
}
}
pub struct BlockCellProvider<'a> {
output_indices: HashMap<Byte32, usize>,
block: &'a BlockView,
}
// Transactions are expected to be sorted within a block,
// Transactions have to appear after any transactions upon which they depend
impl<'a> BlockCellProvider<'a> {
pub fn new(block: &'a BlockView) -> Result<Self, Error> {
let output_indices: HashMap<Byte32, usize> = block
.transactions()
.iter()
.enumerate()
.map(|(idx, tx)| (tx.hash(), idx))
.collect();
for (idx, tx) in block.transactions().iter().enumerate() {
for dep in tx.cell_deps_iter() {
if let Some(output_idx) = output_indices.get(&dep.out_point().tx_hash()) {
if *output_idx >= idx {
return Err(OutPointError::OutOfOrder(dep.out_point()).into());
}
}
}
for out_point in tx.input_pts_iter() {
if let Some(output_idx) = output_indices.get(&out_point.tx_hash()) {
if *output_idx >= idx {
return Err(OutPointError::OutOfOrder(out_point).into());
}
}
}
}
Ok(Self {
output_indices,
block,
})
}
}
impl<'a> CellProvider for BlockCellProvider<'a> {
fn cell(&self, out_point: &OutPoint, _with_data: bool) -> CellStatus {
self.output_indices
.get(&out_point.tx_hash())
.and_then(|i| {
let transaction = self.block.transaction(*i).should_be_ok();
let j: usize = out_point.index().unpack();
self.block.output(*i, j).map(|output| {
let data = transaction
.outputs_data()
.get(j)
.expect("must exists")
.raw_data();
let data_hash = CellOutput::calc_data_hash(&data);
let header = self.block.header();
CellStatus::live_cell(CellMeta {
cell_output: output,
out_point: out_point.clone(),
transaction_info: Some(TransactionInfo {
block_number: header.number(),
block_epoch: header.epoch(),
block_hash: self.block.hash(),
index: *i,
}),
data_bytes: data.len() as u64,
mem_cell_data: Some((data, data_hash)),
})
})
})
.unwrap_or_else(|| CellStatus::Unknown)
}
}
#[derive(Default)]
pub struct TransactionsProvider<'a> {
transactions: HashMap<Byte32, &'a TransactionView>,
}
impl<'a> TransactionsProvider<'a> {
pub fn new(transactions: impl Iterator<Item = &'a TransactionView>) -> Self {
let transactions = transactions.map(|tx| (tx.hash(), tx)).collect();
Self { transactions }
}
pub fn insert(&mut self, transaction: &'a TransactionView) {
self.transactions.insert(transaction.hash(), transaction);
}
}
impl<'a> CellProvider for TransactionsProvider<'a> {
fn cell(&self, out_point: &OutPoint, _with_data: bool) -> CellStatus {
match self.transactions.get(&out_point.tx_hash()) {
Some(tx) => tx
.outputs()
.get(out_point.index().unpack())
.map(|cell| {
let data = tx
.outputs_data()
.get(out_point.index().unpack())
.expect("output data")
.raw_data();
CellStatus::live_cell(CellMetaBuilder::from_cell_output(cell, data).build())
})
.unwrap_or(CellStatus::Unknown),
None => CellStatus::Unknown,
}
}
}
pub trait HeaderChecker {
/// Check if header in main chain
fn check_valid(&self, block_hash: &Byte32) -> Result<(), Error>;
}
/// Gather all cell dep out points and resolved dep group out points
pub fn get_related_dep_out_points<F: Fn(&OutPoint) -> Option<Bytes>>(
tx: &TransactionView,
get_cell_data: F,
) -> Result<Vec<OutPoint>, String> {
tx.cell_deps_iter().try_fold(
Vec::with_capacity(tx.cell_deps().len()),
|mut out_points, dep| {
let out_point = dep.out_point();
if dep.dep_type() == DepType::DepGroup.into() {
let data = get_cell_data(&out_point)
.ok_or_else(|| String::from("Can not get cell data"))?;
let sub_out_points =
parse_dep_group_data(&data).map_err(|err| format!("Invalid data: {}", err))?;
out_points.extend(sub_out_points.into_iter());
}
out_points.push(out_point);
Ok(out_points)
},
)
}
fn parse_dep_group_data(slice: &[u8]) -> Result<OutPointVec, String> {
if slice.is_empty() {
Err("data is empty".to_owned())
} else {
match OutPointVec::from_slice(slice) {
Ok(v) => {
if v.is_empty() {
Err("dep group is empty".to_owned())
} else {
Ok(v)
}
}
Err(err) => Err(err.to_string()),
}
}
}
fn resolve_dep_group<F: FnMut(&OutPoint, bool) -> Result<Option<Box<CellMeta>>, Error>>(
out_point: &OutPoint,
mut cell_resolver: F,
) -> Result<Option<(CellMeta, Vec<CellMeta>)>, Error> {
let dep_group_cell = match cell_resolver(out_point, true)? {
Some(cell_meta) => cell_meta,
None => return Ok(None),
};
let data = dep_group_cell
.mem_cell_data
.clone()
.expect("Load cell meta must with data")
.0;
let sub_out_points = parse_dep_group_data(&data)
.map_err(|_| OutPointError::InvalidDepGroup(out_point.clone()))?;
let mut resolved_deps = Vec::with_capacity(sub_out_points.len());
for sub_out_point in sub_out_points.into_iter() {
if let Some(sub_cell_meta) = cell_resolver(&sub_out_point, true)? {
resolved_deps.push(*sub_cell_meta);
}
}
Ok(Some((*dep_group_cell, resolved_deps)))
}
pub fn resolve_transaction<CP: CellProvider, HC: HeaderChecker, S: BuildHasher>(
transaction: TransactionView,
seen_inputs: &mut HashSet<OutPoint, S>,
cell_provider: &CP,
header_checker: &HC,
) -> Result<ResolvedTransaction, Error> {
let (
mut unknown_out_points,
mut resolved_inputs,
mut resolved_cell_deps,
mut resolved_dep_groups,
) = (
Vec::new(),
Vec::with_capacity(transaction.inputs().len()),
Vec::with_capacity(transaction.cell_deps().len()),
Vec::new(),
);
let mut current_inputs = HashSet::new();
let mut resolve_cell =
|out_point: &OutPoint, with_data: bool| -> Result<Option<Box<CellMeta>>, Error> {
if seen_inputs.contains(out_point) {
return Err(OutPointError::Dead(out_point.clone()).into());
}
let cell_status = cell_provider.cell(out_point, with_data);
match cell_status {
CellStatus::Dead => Err(OutPointError::Dead(out_point.clone()).into()),
CellStatus::Unknown => {
unknown_out_points.push(out_point.clone());
Ok(None)
}
CellStatus::Live(cell_meta) => Ok(Some(cell_meta)),
}
};
// skip resolve input of cellbase
if !transaction.is_cellbase() {
for out_point in transaction.input_pts_iter() {
if !current_inputs.insert(out_point.to_owned()) {
return Err(OutPointError::Dead(out_point).into());
}
if let Some(cell_meta) = resolve_cell(&out_point, false)? {
resolved_inputs.push(*cell_meta);
}
}
}
for cell_dep in transaction.cell_deps_iter() {
if cell_dep.dep_type() == DepType::DepGroup.into() {
if let Some((dep_group, cell_deps)) =
resolve_dep_group(&cell_dep.out_point(), &mut resolve_cell)?
{
resolved_dep_groups.push(dep_group);
resolved_cell_deps.extend(cell_deps);
}
} else if let Some(cell_meta) = resolve_cell(&cell_dep.out_point(), true)? {
resolved_cell_deps.push(*cell_meta);
}
}
for block_hash in transaction.header_deps_iter() {
header_checker.check_valid(&block_hash)?;
}
if !unknown_out_points.is_empty() {
Err(OutPointError::Unknown(unknown_out_points).into())
} else {
seen_inputs.extend(current_inputs);
Ok(ResolvedTransaction {
transaction,
resolved_inputs,
resolved_cell_deps,
resolved_dep_groups,
})
}
}
impl ResolvedTransaction {
// cellbase will be resolved with empty input cells, we can use low cost check here:
pub fn is_cellbase(&self) -> bool {
self.resolved_inputs.is_empty()
}
pub fn inputs_capacity(&self) -> CapacityResult<Capacity> {
self.resolved_inputs
.iter()
.map(CellMeta::capacity)
.try_fold(Capacity::zero(), Capacity::safe_add)
}
pub fn outputs_capacity(&self) -> CapacityResult<Capacity> {
self.transaction.outputs_capacity()
}
pub fn related_dep_out_points(&self) -> Vec<OutPoint> {
self.resolved_cell_deps
.iter()
.map(|d| &d.out_point)
.chain(self.resolved_dep_groups.iter().map(|d| &d.out_point))
.cloned()
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
core::{
capacity_bytes, BlockBuilder, BlockView, Capacity, EpochNumberWithFraction,
TransactionBuilder,
},
h256,
packed::{Byte32, CellDep, CellInput},
H256,
};
use ckb_error::assert_error_eq;
use std::collections::HashMap;
#[derive(Default)]
pub struct BlockHeadersChecker {
attached_indices: HashSet<Byte32>,
detached_indices: HashSet<Byte32>,
}
impl BlockHeadersChecker {
pub fn push_attached(&mut self, block_hash: Byte32) {
self.attached_indices.insert(block_hash);
}
}
impl HeaderChecker for BlockHeadersChecker {
fn check_valid(&self, block_hash: &Byte32) -> Result<(), Error> {
if !self.detached_indices.contains(block_hash)
&& self.attached_indices.contains(block_hash)
{
Ok(())
} else {
Err(OutPointError::InvalidHeader(block_hash.clone()).into())
}
}
}
#[derive(Default)]
struct CellMemoryDb {
cells: HashMap<OutPoint, Option<CellMeta>>,
}
impl CellProvider for CellMemoryDb {
fn cell(&self, o: &OutPoint, _with_data: bool) -> CellStatus {
match self.cells.get(o) {
Some(&Some(ref cell_meta)) => CellStatus::live_cell(cell_meta.clone()),
Some(&None) => CellStatus::Dead,
None => CellStatus::Unknown,
}
}
}
fn generate_dummy_cell_meta_with_info(out_point: OutPoint, data: Bytes) -> CellMeta {
let cell_output = CellOutput::new_builder()
.capacity(capacity_bytes!(2).pack())
.build();
let data_hash = CellOutput::calc_data_hash(&data);
CellMeta {
transaction_info: Some(TransactionInfo {
block_number: 1,
block_epoch: EpochNumberWithFraction::new(1, 1, 10),
block_hash: Byte32::zero(),
index: 1,
}),
cell_output,
out_point,
data_bytes: data.len() as u64,
mem_cell_data: Some((data, data_hash)),
}
}
fn generate_dummy_cell_meta_with_out_point(out_point: OutPoint) -> CellMeta {
generate_dummy_cell_meta_with_info(out_point, Bytes::default())
}
fn generate_dummy_cell_meta_with_data(data: Bytes) -> CellMeta {
generate_dummy_cell_meta_with_info(OutPoint::new(Default::default(), 0), data)
}
fn generate_dummy_cell_meta() -> CellMeta {
generate_dummy_cell_meta_with_data(Bytes::default())
}
fn generate_block(txs: Vec<TransactionView>) -> BlockView {
BlockBuilder::default().transactions(txs).build()
}
#[test]
fn cell_provider_trait_works() {
let mut db = CellMemoryDb::default();
let p1 = OutPoint::new(Byte32::zero(), 1);
let p2 = OutPoint::new(Byte32::zero(), 2);
let p3 = OutPoint::new(Byte32::zero(), 3);
let o = generate_dummy_cell_meta();
db.cells.insert(p1.clone(), Some(o.clone()));
db.cells.insert(p2.clone(), None);
assert_eq!(CellStatus::Live(Box::new(o)), db.cell(&p1, false));
assert_eq!(CellStatus::Dead, db.cell(&p2, false));
assert_eq!(CellStatus::Unknown, db.cell(&p3, false));
}
#[test]
fn resolve_transaction_should_resolve_dep_group() {
let mut cell_provider = CellMemoryDb::default();
let header_checker = BlockHeadersChecker::default();
let op_dep = OutPoint::new(Byte32::zero(), 72);
let op_1 = OutPoint::new(h256!("0x13").pack(), 1);
let op_2 = OutPoint::new(h256!("0x23").pack(), 2);
let op_3 = OutPoint::new(h256!("0x33").pack(), 3);
for op in &[&op_1, &op_2, &op_3] {
cell_provider.cells.insert(
(*op).clone(),
Some(generate_dummy_cell_meta_with_out_point((*op).clone())),
);
}
let cell_data = vec![op_1.clone(), op_2.clone(), op_3.clone()]
.pack()
.as_bytes();
let dep_group_cell = generate_dummy_cell_meta_with_data(cell_data);
cell_provider
.cells
.insert(op_dep.clone(), Some(dep_group_cell));
let dep = CellDep::new_builder()
.out_point(op_dep)
.dep_type(DepType::DepGroup.into())
.build();
let transaction = TransactionBuilder::default().cell_dep(dep).build();
let mut seen_inputs = HashSet::new();
let result = resolve_transaction(
transaction,
&mut seen_inputs,
&cell_provider,
&header_checker,
)
.unwrap();
assert_eq!(result.resolved_cell_deps.len(), 3);
assert_eq!(result.resolved_cell_deps[0].out_point, op_1);
assert_eq!(result.resolved_cell_deps[1].out_point, op_2);
assert_eq!(result.resolved_cell_deps[2].out_point, op_3);
}
#[test]
fn resolve_transaction_resolve_dep_group_failed_because_invalid_data() {
let mut cell_provider = CellMemoryDb::default();
let header_checker = BlockHeadersChecker::default();
let op_dep = OutPoint::new(Byte32::zero(), 72);
let cell_data = Bytes::from("this is invalid data");
let dep_group_cell = generate_dummy_cell_meta_with_data(cell_data);
cell_provider
.cells
.insert(op_dep.clone(), Some(dep_group_cell));
let dep = CellDep::new_builder()
.out_point(op_dep.clone())
.dep_type(DepType::DepGroup.into())
.build();
let transaction = TransactionBuilder::default().cell_dep(dep).build();
let mut seen_inputs = HashSet::new();
let result = resolve_transaction(
transaction,
&mut seen_inputs,
&cell_provider,
&header_checker,
);
assert_error_eq!(result.unwrap_err(), OutPointError::InvalidDepGroup(op_dep));
}
#[test]
fn resolve_transaction_resolve_dep_group_failed_because_unknown_sub_cell() {
let mut cell_provider = CellMemoryDb::default();
let header_checker = BlockHeadersChecker::default();
let op_unknown = OutPoint::new(h256!("0x45").pack(), 5);
let op_dep = OutPoint::new(Byte32::zero(), 72);
let cell_data = vec![op_unknown.clone()].pack().as_bytes();
let dep_group_cell = generate_dummy_cell_meta_with_data(cell_data);
cell_provider
.cells
.insert(op_dep.clone(), Some(dep_group_cell));
let dep = CellDep::new_builder()
.out_point(op_dep)
.dep_type(DepType::DepGroup.into())
.build();
let transaction = TransactionBuilder::default().cell_dep(dep).build();
let mut seen_inputs = HashSet::new();
let result = resolve_transaction(
transaction,
&mut seen_inputs,
&cell_provider,
&header_checker,
);
assert_error_eq!(
result.unwrap_err(),
OutPointError::Unknown(vec![op_unknown]),
);
}
#[test]
fn resolve_transaction_test_header_deps_all_ok() {
let cell_provider = CellMemoryDb::default();
let mut header_checker = BlockHeadersChecker::default();
let block_hash1 = h256!("0x1111").pack();
let block_hash2 = h256!("0x2222").pack();
header_checker.push_attached(block_hash1.clone());
header_checker.push_attached(block_hash2.clone());
let transaction = TransactionBuilder::default()
.header_dep(block_hash1)
.header_dep(block_hash2)
.build();
let mut seen_inputs = HashSet::new();
let result = resolve_transaction(
transaction,
&mut seen_inputs,
&cell_provider,
&header_checker,
);
assert!(result.is_ok());
}
#[test]
fn resolve_transaction_should_test_have_invalid_header_dep() {
let cell_provider = CellMemoryDb::default();
let mut header_checker = BlockHeadersChecker::default();
let main_chain_block_hash = h256!("0xaabbcc").pack();
let invalid_block_hash = h256!("0x3344").pack();
header_checker.push_attached(main_chain_block_hash.clone());
let transaction = TransactionBuilder::default()
.header_dep(main_chain_block_hash)
.header_dep(invalid_block_hash.clone())
.build();
let mut seen_inputs = HashSet::new();
let result = resolve_transaction(
transaction,
&mut seen_inputs,
&cell_provider,
&header_checker,
);
assert_error_eq!(
result.unwrap_err(),
OutPointError::InvalidHeader(invalid_block_hash),
);
}
#[test]
fn resolve_transaction_should_reject_incorrect_order_txs() {
let out_point = OutPoint::new(h256!("0x2").pack(), 3);
let tx1 = TransactionBuilder::default()
.input(CellInput::new(out_point, 0))
.output(
CellOutput::new_builder()
.capacity(capacity_bytes!(2).pack())
.build(),
)
.output_data(Default::default())
.build();
let tx2 = TransactionBuilder::default()
.input(CellInput::new(OutPoint::new(tx1.hash(), 0), 0))
.build();
let dep = CellDep::new_builder()
.out_point(OutPoint::new(tx1.hash(), 0))
.build();
let tx3 = TransactionBuilder::default().cell_dep(dep).build();
// tx1 <- tx2
// ok
{
let block = generate_block(vec![tx1.clone(), tx2.clone()]);
let provider = BlockCellProvider::new(&block);
assert!(provider.is_ok());
}
// tx1 -> tx2
// resolve err
{
let block = generate_block(vec![tx2, tx1.clone()]);
let provider = BlockCellProvider::new(&block);
assert_error_eq!(
provider.err().unwrap(),
OutPointError::OutOfOrder(OutPoint::new(tx1.hash(), 0)),
);
}
// tx1 <- tx3
// ok
{
let block = generate_block(vec![tx1.clone(), tx3.clone()]);
let provider = BlockCellProvider::new(&block);
assert!(provider.is_ok());
}
// tx1 -> tx3
// resolve err
{
let block = generate_block(vec![tx3, tx1.clone()]);
let provider = BlockCellProvider::new(&block);
assert_error_eq!(
provider.err().unwrap(),
OutPointError::OutOfOrder(OutPoint::new(tx1.hash(), 0)),
);
}
}
#[test]
fn resolve_transaction_should_allow_dep_cell_in_current_tx_input() {
let mut cell_provider = CellMemoryDb::default();
let header_checker = BlockHeadersChecker::default();
let out_point = OutPoint::new(h256!("0x2").pack(), 3);
let dummy_cell_meta = generate_dummy_cell_meta();
cell_provider
.cells
.insert(out_point.clone(), Some(dummy_cell_meta.clone()));
let dep = CellDep::new_builder().out_point(out_point.clone()).build();
let tx = TransactionBuilder::default()
.input(CellInput::new(out_point, 0))
.cell_dep(dep)
.build();
let mut seen_inputs = HashSet::new();
let rtx =
resolve_transaction(tx, &mut seen_inputs, &cell_provider, &header_checker).unwrap();
assert_eq!(rtx.resolved_cell_deps[0], dummy_cell_meta,);
}
#[test]
fn resolve_transaction_should_reject_dep_cell_consumed_by_previous_input() {
let mut cell_provider = CellMemoryDb::default();
let header_checker = BlockHeadersChecker::default();
let out_point = OutPoint::new(h256!("0x2").pack(), 3);
cell_provider
.cells
.insert(out_point.clone(), Some(generate_dummy_cell_meta()));
// tx1 dep
// tx2 input consumed
// ok
{
let dep = CellDep::new_builder().out_point(out_point.clone()).build();
let tx1 = TransactionBuilder::default().cell_dep(dep).build();
let tx2 = TransactionBuilder::default()
.input(CellInput::new(out_point.clone(), 0))
.build();
let mut seen_inputs = HashSet::new();
let result1 =
resolve_transaction(tx1, &mut seen_inputs, &cell_provider, &header_checker);
assert!(result1.is_ok());
let result2 =
resolve_transaction(tx2, &mut seen_inputs, &cell_provider, &header_checker);
assert!(result2.is_ok());
}
// tx1 input consumed
// tx2 dep
// tx2 resolve err
{
let tx1 = TransactionBuilder::default()
.input(CellInput::new(out_point.clone(), 0))
.build();
let dep = CellDep::new_builder().out_point(out_point.clone()).build();
let tx2 = TransactionBuilder::default().cell_dep(dep).build();
let mut seen_inputs = HashSet::new();
let result1 =
resolve_transaction(tx1, &mut seen_inputs, &cell_provider, &header_checker);
assert!(result1.is_ok());
let result2 =
resolve_transaction(tx2, &mut seen_inputs, &cell_provider, &header_checker);
assert_error_eq!(result2.unwrap_err(), OutPointError::Dead(out_point));
}
}
}
|
#[derive(Debug)]
pub struct Request {
uri: String,
method: String,
http_version: String,
header: String,
body: String,
}
impl Request {
pub fn new() -> Self {
Self {
uri: String::default(),
method: String::default(),
http_version: String::default(),
header: String::default(),
body: String::default(),
}
}
pub fn with_params(
uri: &str,
method: &str,
http_version: &str,
header: &str,
body: &str
) -> Self {
Self {
uri: uri.to_string(),
method: method.to_string(),
http_version: http_version.to_string(),
header: header.to_string(),
body: body.to_string(),
}
}
pub fn set_uri(&mut self, uri: &str) {
self.uri = uri.to_string();
}
pub fn set_method(&mut self, method: &str) {
self.method = method.to_string();
}
pub fn set_http_version(&mut self, http_version: &str) {
self.http_version = http_version.to_string();
}
pub fn uri(&self) -> String {
self.uri.clone()
}
pub fn method(&self) -> String {
self.method.clone()
}
}
|
use middle::ir::MOpcode;
use middle::ssa::cfg_traits::CFG;
use middle::ssa::ssa_traits::*;
use middle::ssa::ssastorage::SSAStorage;
use petgraph::graph::NodeIndex;
use std::collections::HashSet;
pub fn run(ssa: &mut SSAStorage) -> () {
loop {
let copies = CopyInfo::gather_copies(ssa);
if copies.is_empty() {
break;
}
let mut replaced = HashSet::new();
for CopyInfo(from, to) in copies {
if replaced.contains(&from) {
continue;
}
replaced.insert(to);
ssa.replace_value(to, from);
}
}
}
type From = NodeIndex;
type To = NodeIndex;
struct CopyInfo(From, To);
impl CopyInfo {
fn gather_copies(ssa: &SSAStorage) -> Vec<Self> {
ssa.blocks()
.into_iter()
.flat_map(|b| ssa.exprs_in(b))
.filter_map(|e| match ssa.opcode(e) {
Some(MOpcode::OpMov) => {
if let Some(&o) = ssa.operands_of(e).iter().nth(0) {
Some(CopyInfo(o, e))
} else {
radeco_err!("No operand of `OpMov` found");
None
}
}
_ => None,
})
.collect::<Vec<_>>()
}
}
|
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Default, Debug)]
pub(crate) struct AssociationStats {
n_datas: AtomicU64,
n_sacks: AtomicU64,
n_t3timeouts: AtomicU64,
n_ack_timeouts: AtomicU64,
n_fast_retrans: AtomicU64,
}
impl AssociationStats {
pub(crate) fn inc_datas(&self) {
self.n_datas.fetch_add(1, Ordering::SeqCst);
}
pub(crate) fn get_num_datas(&self) -> u64 {
self.n_datas.load(Ordering::SeqCst)
}
pub(crate) fn inc_sacks(&self) {
self.n_sacks.fetch_add(1, Ordering::SeqCst);
}
pub(crate) fn get_num_sacks(&self) -> u64 {
self.n_sacks.load(Ordering::SeqCst)
}
pub(crate) fn inc_t3timeouts(&self) {
self.n_t3timeouts.fetch_add(1, Ordering::SeqCst);
}
pub(crate) fn get_num_t3timeouts(&self) -> u64 {
self.n_t3timeouts.load(Ordering::SeqCst)
}
pub(crate) fn inc_ack_timeouts(&self) {
self.n_ack_timeouts.fetch_add(1, Ordering::SeqCst);
}
pub(crate) fn get_num_ack_timeouts(&self) -> u64 {
self.n_ack_timeouts.load(Ordering::SeqCst)
}
pub(crate) fn inc_fast_retrans(&self) {
self.n_fast_retrans.fetch_add(1, Ordering::SeqCst);
}
pub(crate) fn get_num_fast_retrans(&self) -> u64 {
self.n_fast_retrans.load(Ordering::SeqCst)
}
pub(crate) fn reset(&self) {
self.n_datas.store(0, Ordering::SeqCst);
self.n_sacks.store(0, Ordering::SeqCst);
self.n_t3timeouts.store(0, Ordering::SeqCst);
self.n_ack_timeouts.store(0, Ordering::SeqCst);
self.n_fast_retrans.store(0, Ordering::SeqCst);
}
}
|
use err_derive::Error;
use sha2::{Digest, Sha256};
use std::fs::File;
use std::io::{self, Read};
#[derive(Debug, Error)]
pub enum ValidateError {
#[error(display = "checksum failed; expected {}, found {}", expected, found)]
Checksum { expected: String, found: String },
#[error(display = "I/O error while checksumming: {}", _0)]
Io(io::Error),
}
pub fn validate_checksum(file: &mut File, checksum: &str) -> Result<(), ValidateError> {
eprintln!("validating checksum of downloaded ISO");
let mut hasher = Sha256::new();
let mut buffer = [0u8; 64 * 1024];
loop {
let read = file.read(&mut buffer).map_err(ValidateError::Io)?;
if read == 0 {
break;
}
hasher.input(&buffer[..read]);
}
let found = format!("{:x}", hasher.result());
if found != checksum {
return Err(ValidateError::Checksum { expected: checksum.into(), found });
}
Ok(())
}
|
pub fn v2s(s: Vec<char>) -> String {
let s: String = s.into_iter().collect();
s.trim().to_owned()
}
|
use byteorder::{ByteOrder, NativeEndian};
use crate::{
traits::{Emitable, Parseable},
DecodeError, Field,
};
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct RouteCacheInfo {
pub clntref: u32,
pub last_use: u32,
pub expires: u32,
pub error: u32,
pub used: u32,
pub id: u32,
pub ts: u32,
pub ts_age: u32,
}
const CLNTREF: Field = 0..4;
const LAST_USE: Field = 4..8;
const EXPIRES: Field = 8..12;
const ERROR: Field = 12..16;
const USED: Field = 16..20;
const ID: Field = 20..24;
const TS: Field = 24..28;
const TS_AGE: Field = 28..32;
pub const ROUTE_CACHE_INFO_LEN: usize = TS_AGE.end;
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct RouteCacheInfoBuffer<T> {
buffer: T,
}
impl<T: AsRef<[u8]>> RouteCacheInfoBuffer<T> {
pub fn new(buffer: T) -> RouteCacheInfoBuffer<T> {
RouteCacheInfoBuffer { buffer }
}
pub fn new_checked(buffer: T) -> Result<RouteCacheInfoBuffer<T>, DecodeError> {
let buf = Self::new(buffer);
buf.check_buffer_length()?;
Ok(buf)
}
fn check_buffer_length(&self) -> Result<(), DecodeError> {
let len = self.buffer.as_ref().len();
if len < ROUTE_CACHE_INFO_LEN {
return Err(format!(
"invalid RouteCacheInfoBuffer buffer: length is {} instead of {}",
len, ROUTE_CACHE_INFO_LEN
)
.into());
}
Ok(())
}
pub fn into_inner(self) -> T {
self.buffer
}
pub fn clntref(&self) -> u32 {
NativeEndian::read_u32(&self.buffer.as_ref()[CLNTREF])
}
pub fn last_use(&self) -> u32 {
NativeEndian::read_u32(&self.buffer.as_ref()[LAST_USE])
}
pub fn expires(&self) -> u32 {
NativeEndian::read_u32(&self.buffer.as_ref()[EXPIRES])
}
pub fn error(&self) -> u32 {
NativeEndian::read_u32(&self.buffer.as_ref()[ERROR])
}
pub fn used(&self) -> u32 {
NativeEndian::read_u32(&self.buffer.as_ref()[USED])
}
pub fn id(&self) -> u32 {
NativeEndian::read_u32(&self.buffer.as_ref()[ID])
}
pub fn ts(&self) -> u32 {
NativeEndian::read_u32(&self.buffer.as_ref()[TS])
}
pub fn ts_age(&self) -> u32 {
NativeEndian::read_u32(&self.buffer.as_ref()[TS_AGE])
}
}
impl<T: AsRef<[u8]> + AsMut<[u8]>> RouteCacheInfoBuffer<T> {
pub fn set_clntref(&mut self, value: u32) {
NativeEndian::write_u32(&mut self.buffer.as_mut()[CLNTREF], value)
}
pub fn set_last_use(&mut self, value: u32) {
NativeEndian::write_u32(&mut self.buffer.as_mut()[LAST_USE], value)
}
pub fn set_expires(&mut self, value: u32) {
NativeEndian::write_u32(&mut self.buffer.as_mut()[EXPIRES], value)
}
pub fn set_error(&mut self, value: u32) {
NativeEndian::write_u32(&mut self.buffer.as_mut()[ERROR], value)
}
pub fn set_used(&mut self, value: u32) {
NativeEndian::write_u32(&mut self.buffer.as_mut()[USED], value)
}
pub fn set_id(&mut self, value: u32) {
NativeEndian::write_u32(&mut self.buffer.as_mut()[ID], value)
}
pub fn set_ts(&mut self, value: u32) {
NativeEndian::write_u32(&mut self.buffer.as_mut()[TS], value)
}
pub fn set_ts_age(&mut self, value: u32) {
NativeEndian::write_u32(&mut self.buffer.as_mut()[TS_AGE], value)
}
}
impl<T: AsRef<[u8]>> Parseable<RouteCacheInfo> for RouteCacheInfoBuffer<T> {
fn parse(&self) -> Result<RouteCacheInfo, DecodeError> {
Ok(RouteCacheInfo {
clntref: self.clntref(),
last_use: self.last_use(),
expires: self.expires(),
error: self.error(),
used: self.used(),
id: self.id(),
ts: self.ts(),
ts_age: self.ts_age(),
})
}
}
impl Emitable for RouteCacheInfo {
fn buffer_len(&self) -> usize {
ROUTE_CACHE_INFO_LEN
}
fn emit(&self, buffer: &mut [u8]) {
let mut buffer = RouteCacheInfoBuffer::new(buffer);
buffer.set_clntref(self.clntref);
buffer.set_last_use(self.last_use);
buffer.set_expires(self.expires);
buffer.set_error(self.error);
buffer.set_used(self.used);
buffer.set_id(self.id);
buffer.set_ts(self.ts);
buffer.set_ts_age(self.ts_age);
}
}
|
mod code;
pub use code::*; |
#[doc = "Register `BMTRGR` reader"]
pub type R = crate::R<BMTRGR_SPEC>;
#[doc = "Register `BMTRGR` writer"]
pub type W = crate::W<BMTRGR_SPEC>;
#[doc = "Field `SW` reader - SW"]
pub type SW_R = crate::BitReader<SW_A>;
#[doc = "SW\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SW_A {
#[doc = "0: No effect"]
NoEffect = 0,
#[doc = "1: Trigger immediate burst mode operation"]
Trigger = 1,
}
impl From<SW_A> for bool {
#[inline(always)]
fn from(variant: SW_A) -> Self {
variant as u8 != 0
}
}
impl SW_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SW_A {
match self.bits {
false => SW_A::NoEffect,
true => SW_A::Trigger,
}
}
#[doc = "No effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == SW_A::NoEffect
}
#[doc = "Trigger immediate burst mode operation"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == SW_A::Trigger
}
}
#[doc = "Field `SW` writer - SW"]
pub type SW_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SW_A>;
impl<'a, REG, const O: u8> SW_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(SW_A::NoEffect)
}
#[doc = "Trigger immediate burst mode operation"]
#[inline(always)]
pub fn trigger(self) -> &'a mut crate::W<REG> {
self.variant(SW_A::Trigger)
}
}
#[doc = "Field `MSTRST` reader - MSTRST"]
pub type MSTRST_R = crate::BitReader<MSTRST_A>;
#[doc = "MSTRST\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MSTRST_A {
#[doc = "0: Master timer reset/roll-over event has no effect"]
NoEffect = 0,
#[doc = "1: Master timer reset/roll-over event triggers a burst mode entry"]
Trigger = 1,
}
impl From<MSTRST_A> for bool {
#[inline(always)]
fn from(variant: MSTRST_A) -> Self {
variant as u8 != 0
}
}
impl MSTRST_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MSTRST_A {
match self.bits {
false => MSTRST_A::NoEffect,
true => MSTRST_A::Trigger,
}
}
#[doc = "Master timer reset/roll-over event has no effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == MSTRST_A::NoEffect
}
#[doc = "Master timer reset/roll-over event triggers a burst mode entry"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == MSTRST_A::Trigger
}
}
#[doc = "Field `MSTRST` writer - MSTRST"]
pub type MSTRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, MSTRST_A>;
impl<'a, REG, const O: u8> MSTRST_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Master timer reset/roll-over event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(MSTRST_A::NoEffect)
}
#[doc = "Master timer reset/roll-over event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut crate::W<REG> {
self.variant(MSTRST_A::Trigger)
}
}
#[doc = "Field `MSTREP` reader - MSTREP"]
pub type MSTREP_R = crate::BitReader<MSTREP_A>;
#[doc = "MSTREP\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MSTREP_A {
#[doc = "0: Master timer repetition event has no effect"]
NoEffect = 0,
#[doc = "1: Master timer repetition event triggers a burst mode entry"]
Trigger = 1,
}
impl From<MSTREP_A> for bool {
#[inline(always)]
fn from(variant: MSTREP_A) -> Self {
variant as u8 != 0
}
}
impl MSTREP_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MSTREP_A {
match self.bits {
false => MSTREP_A::NoEffect,
true => MSTREP_A::Trigger,
}
}
#[doc = "Master timer repetition event has no effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == MSTREP_A::NoEffect
}
#[doc = "Master timer repetition event triggers a burst mode entry"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == MSTREP_A::Trigger
}
}
#[doc = "Field `MSTREP` writer - MSTREP"]
pub type MSTREP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, MSTREP_A>;
impl<'a, REG, const O: u8> MSTREP_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Master timer repetition event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(MSTREP_A::NoEffect)
}
#[doc = "Master timer repetition event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut crate::W<REG> {
self.variant(MSTREP_A::Trigger)
}
}
#[doc = "Field `MSTCMP1` reader - MSTCMP1"]
pub type MSTCMP1_R = crate::BitReader<MSTCMP1_A>;
#[doc = "MSTCMP1\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MSTCMP1_A {
#[doc = "0: Master timer compare X event has no effect"]
NoEffect = 0,
#[doc = "1: Master timer compare X event triggers a burst mode entry"]
Trigger = 1,
}
impl From<MSTCMP1_A> for bool {
#[inline(always)]
fn from(variant: MSTCMP1_A) -> Self {
variant as u8 != 0
}
}
impl MSTCMP1_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MSTCMP1_A {
match self.bits {
false => MSTCMP1_A::NoEffect,
true => MSTCMP1_A::Trigger,
}
}
#[doc = "Master timer compare X event has no effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == MSTCMP1_A::NoEffect
}
#[doc = "Master timer compare X event triggers a burst mode entry"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == MSTCMP1_A::Trigger
}
}
#[doc = "Field `MSTCMP1` writer - MSTCMP1"]
pub type MSTCMP1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, MSTCMP1_A>;
impl<'a, REG, const O: u8> MSTCMP1_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Master timer compare X event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(MSTCMP1_A::NoEffect)
}
#[doc = "Master timer compare X event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut crate::W<REG> {
self.variant(MSTCMP1_A::Trigger)
}
}
#[doc = "Field `MSTCMP2` reader - MSTCMP2"]
pub use MSTCMP1_R as MSTCMP2_R;
#[doc = "Field `MSTCMP3` reader - MSTCMP3"]
pub use MSTCMP1_R as MSTCMP3_R;
#[doc = "Field `MSTCMP4` reader - MSTCMP4"]
pub use MSTCMP1_R as MSTCMP4_R;
#[doc = "Field `MSTCMP2` writer - MSTCMP2"]
pub use MSTCMP1_W as MSTCMP2_W;
#[doc = "Field `MSTCMP3` writer - MSTCMP3"]
pub use MSTCMP1_W as MSTCMP3_W;
#[doc = "Field `MSTCMP4` writer - MSTCMP4"]
pub use MSTCMP1_W as MSTCMP4_W;
#[doc = "Field `TARST` reader - TARST"]
pub type TARST_R = crate::BitReader<TARST_A>;
#[doc = "TARST\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TARST_A {
#[doc = "0: Timer X reset/roll-over event has no effect"]
NoEffect = 0,
#[doc = "1: Timer X reset/roll-over event triggers a burst mode entry"]
Trigger = 1,
}
impl From<TARST_A> for bool {
#[inline(always)]
fn from(variant: TARST_A) -> Self {
variant as u8 != 0
}
}
impl TARST_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TARST_A {
match self.bits {
false => TARST_A::NoEffect,
true => TARST_A::Trigger,
}
}
#[doc = "Timer X reset/roll-over event has no effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == TARST_A::NoEffect
}
#[doc = "Timer X reset/roll-over event triggers a burst mode entry"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == TARST_A::Trigger
}
}
#[doc = "Field `TARST` writer - TARST"]
pub type TARST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TARST_A>;
impl<'a, REG, const O: u8> TARST_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Timer X reset/roll-over event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(TARST_A::NoEffect)
}
#[doc = "Timer X reset/roll-over event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut crate::W<REG> {
self.variant(TARST_A::Trigger)
}
}
#[doc = "Field `TAREP` reader - TAREP"]
pub type TAREP_R = crate::BitReader<TAREP_A>;
#[doc = "TAREP\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TAREP_A {
#[doc = "0: Timer X repetition event has no effect"]
NoEffect = 0,
#[doc = "1: Timer X repetition event triggers a burst mode entry"]
Trigger = 1,
}
impl From<TAREP_A> for bool {
#[inline(always)]
fn from(variant: TAREP_A) -> Self {
variant as u8 != 0
}
}
impl TAREP_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TAREP_A {
match self.bits {
false => TAREP_A::NoEffect,
true => TAREP_A::Trigger,
}
}
#[doc = "Timer X repetition event has no effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == TAREP_A::NoEffect
}
#[doc = "Timer X repetition event triggers a burst mode entry"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == TAREP_A::Trigger
}
}
#[doc = "Field `TAREP` writer - TAREP"]
pub type TAREP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TAREP_A>;
impl<'a, REG, const O: u8> TAREP_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Timer X repetition event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(TAREP_A::NoEffect)
}
#[doc = "Timer X repetition event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut crate::W<REG> {
self.variant(TAREP_A::Trigger)
}
}
#[doc = "Field `TACMP1` reader - TACMP1"]
pub type TACMP1_R = crate::BitReader<TACMP1_A>;
#[doc = "TACMP1\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TACMP1_A {
#[doc = "0: Timer X compare Y event has no effect"]
NoEffect = 0,
#[doc = "1: Timer X compare Y event triggers a burst mode entry"]
Trigger = 1,
}
impl From<TACMP1_A> for bool {
#[inline(always)]
fn from(variant: TACMP1_A) -> Self {
variant as u8 != 0
}
}
impl TACMP1_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TACMP1_A {
match self.bits {
false => TACMP1_A::NoEffect,
true => TACMP1_A::Trigger,
}
}
#[doc = "Timer X compare Y event has no effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == TACMP1_A::NoEffect
}
#[doc = "Timer X compare Y event triggers a burst mode entry"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == TACMP1_A::Trigger
}
}
#[doc = "Field `TACMP1` writer - TACMP1"]
pub type TACMP1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TACMP1_A>;
impl<'a, REG, const O: u8> TACMP1_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Timer X compare Y event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(TACMP1_A::NoEffect)
}
#[doc = "Timer X compare Y event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut crate::W<REG> {
self.variant(TACMP1_A::Trigger)
}
}
#[doc = "Field `TACMP2` reader - TACMP2"]
pub use TACMP1_R as TACMP2_R;
#[doc = "Field `TBCMP1` reader - TBCMP1"]
pub use TACMP1_R as TBCMP1_R;
#[doc = "Field `TBCMP2` reader - TBCMP2"]
pub use TACMP1_R as TBCMP2_R;
#[doc = "Field `TCCMP1` reader - TCCMP1"]
pub use TACMP1_R as TCCMP1_R;
#[doc = "Field `TCCMP2` reader - TCCMP2"]
pub use TACMP1_R as TCCMP2_R;
#[doc = "Field `TDCMP1` reader - TDCMP1"]
pub use TACMP1_R as TDCMP1_R;
#[doc = "Field `TDCMP2` reader - TDCMP2"]
pub use TACMP1_R as TDCMP2_R;
#[doc = "Field `TECMP1` reader - TECMP1"]
pub use TACMP1_R as TECMP1_R;
#[doc = "Field `TECMP2` reader - TECMP2"]
pub use TACMP1_R as TECMP2_R;
#[doc = "Field `TACMP2` writer - TACMP2"]
pub use TACMP1_W as TACMP2_W;
#[doc = "Field `TBCMP1` writer - TBCMP1"]
pub use TACMP1_W as TBCMP1_W;
#[doc = "Field `TBCMP2` writer - TBCMP2"]
pub use TACMP1_W as TBCMP2_W;
#[doc = "Field `TCCMP1` writer - TCCMP1"]
pub use TACMP1_W as TCCMP1_W;
#[doc = "Field `TCCMP2` writer - TCCMP2"]
pub use TACMP1_W as TCCMP2_W;
#[doc = "Field `TDCMP1` writer - TDCMP1"]
pub use TACMP1_W as TDCMP1_W;
#[doc = "Field `TDCMP2` writer - TDCMP2"]
pub use TACMP1_W as TDCMP2_W;
#[doc = "Field `TECMP1` writer - TECMP1"]
pub use TACMP1_W as TECMP1_W;
#[doc = "Field `TECMP2` writer - TECMP2"]
pub use TACMP1_W as TECMP2_W;
#[doc = "Field `TBREP` reader - TBREP"]
pub use TAREP_R as TBREP_R;
#[doc = "Field `TCREP` reader - TCREP"]
pub use TAREP_R as TCREP_R;
#[doc = "Field `TDREP` reader - TDREP"]
pub use TAREP_R as TDREP_R;
#[doc = "Field `TEREP` reader - TEREP"]
pub use TAREP_R as TEREP_R;
#[doc = "Field `TBREP` writer - TBREP"]
pub use TAREP_W as TBREP_W;
#[doc = "Field `TCREP` writer - TCREP"]
pub use TAREP_W as TCREP_W;
#[doc = "Field `TDREP` writer - TDREP"]
pub use TAREP_W as TDREP_W;
#[doc = "Field `TEREP` writer - TEREP"]
pub use TAREP_W as TEREP_W;
#[doc = "Field `TBRST` reader - TBRST"]
pub use TARST_R as TBRST_R;
#[doc = "Field `TCRST` reader - TCRST"]
pub use TARST_R as TCRST_R;
#[doc = "Field `TDRST` reader - TDRST"]
pub use TARST_R as TDRST_R;
#[doc = "Field `TERST` reader - TERST"]
pub use TARST_R as TERST_R;
#[doc = "Field `TBRST` writer - TBRST"]
pub use TARST_W as TBRST_W;
#[doc = "Field `TCRST` writer - TCRST"]
pub use TARST_W as TCRST_W;
#[doc = "Field `TDRST` writer - TDRST"]
pub use TARST_W as TDRST_W;
#[doc = "Field `TERST` writer - TERST"]
pub use TARST_W as TERST_W;
#[doc = "Field `TAEEV7` reader - TAEEV7"]
pub type TAEEV7_R = crate::BitReader<TAEEV7_A>;
#[doc = "TAEEV7\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TAEEV7_A {
#[doc = "0: Timer X period following external event Y has no effect"]
NoEffect = 0,
#[doc = "1: Timer X period following external event Y triggers a burst mode entry"]
Trigger = 1,
}
impl From<TAEEV7_A> for bool {
#[inline(always)]
fn from(variant: TAEEV7_A) -> Self {
variant as u8 != 0
}
}
impl TAEEV7_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TAEEV7_A {
match self.bits {
false => TAEEV7_A::NoEffect,
true => TAEEV7_A::Trigger,
}
}
#[doc = "Timer X period following external event Y has no effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == TAEEV7_A::NoEffect
}
#[doc = "Timer X period following external event Y triggers a burst mode entry"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == TAEEV7_A::Trigger
}
}
#[doc = "Field `TAEEV7` writer - TAEEV7"]
pub type TAEEV7_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TAEEV7_A>;
impl<'a, REG, const O: u8> TAEEV7_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Timer X period following external event Y has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(TAEEV7_A::NoEffect)
}
#[doc = "Timer X period following external event Y triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut crate::W<REG> {
self.variant(TAEEV7_A::Trigger)
}
}
#[doc = "Field `TDEEV8` reader - TDEEV8"]
pub use TAEEV7_R as TDEEV8_R;
#[doc = "Field `TDEEV8` writer - TDEEV8"]
pub use TAEEV7_W as TDEEV8_W;
#[doc = "Field `EEV7` reader - EEV7"]
pub type EEV7_R = crate::BitReader<EEV7_A>;
#[doc = "EEV7\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EEV7_A {
#[doc = "0: External event X has no effect"]
NoEffect = 0,
#[doc = "1: External event X triggers a burst mode entry"]
Trigger = 1,
}
impl From<EEV7_A> for bool {
#[inline(always)]
fn from(variant: EEV7_A) -> Self {
variant as u8 != 0
}
}
impl EEV7_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EEV7_A {
match self.bits {
false => EEV7_A::NoEffect,
true => EEV7_A::Trigger,
}
}
#[doc = "External event X has no effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == EEV7_A::NoEffect
}
#[doc = "External event X triggers a burst mode entry"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == EEV7_A::Trigger
}
}
#[doc = "Field `EEV7` writer - EEV7"]
pub type EEV7_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, EEV7_A>;
impl<'a, REG, const O: u8> EEV7_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "External event X has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(EEV7_A::NoEffect)
}
#[doc = "External event X triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut crate::W<REG> {
self.variant(EEV7_A::Trigger)
}
}
#[doc = "Field `EEV8` reader - EEV8"]
pub use EEV7_R as EEV8_R;
#[doc = "Field `EEV8` writer - EEV8"]
pub use EEV7_W as EEV8_W;
#[doc = "Field `OCHPEV` reader - OCHPEV"]
pub type OCHPEV_R = crate::BitReader<OCHPEV_A>;
#[doc = "OCHPEV\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OCHPEV_A {
#[doc = "0: Rising edge on an on-chip event has no effect"]
NoEffect = 0,
#[doc = "1: Rising edge on an on-chip event triggers a burst mode entry"]
Trigger = 1,
}
impl From<OCHPEV_A> for bool {
#[inline(always)]
fn from(variant: OCHPEV_A) -> Self {
variant as u8 != 0
}
}
impl OCHPEV_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> OCHPEV_A {
match self.bits {
false => OCHPEV_A::NoEffect,
true => OCHPEV_A::Trigger,
}
}
#[doc = "Rising edge on an on-chip event has no effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == OCHPEV_A::NoEffect
}
#[doc = "Rising edge on an on-chip event triggers a burst mode entry"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == OCHPEV_A::Trigger
}
}
#[doc = "Field `OCHPEV` writer - OCHPEV"]
pub type OCHPEV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, OCHPEV_A>;
impl<'a, REG, const O: u8> OCHPEV_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Rising edge on an on-chip event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(OCHPEV_A::NoEffect)
}
#[doc = "Rising edge on an on-chip event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut crate::W<REG> {
self.variant(OCHPEV_A::Trigger)
}
}
impl R {
#[doc = "Bit 0 - SW"]
#[inline(always)]
pub fn sw(&self) -> SW_R {
SW_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - MSTRST"]
#[inline(always)]
pub fn mstrst(&self) -> MSTRST_R {
MSTRST_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - MSTREP"]
#[inline(always)]
pub fn mstrep(&self) -> MSTREP_R {
MSTREP_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - MSTCMP1"]
#[inline(always)]
pub fn mstcmp1(&self) -> MSTCMP1_R {
MSTCMP1_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - MSTCMP2"]
#[inline(always)]
pub fn mstcmp2(&self) -> MSTCMP2_R {
MSTCMP2_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - MSTCMP3"]
#[inline(always)]
pub fn mstcmp3(&self) -> MSTCMP3_R {
MSTCMP3_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - MSTCMP4"]
#[inline(always)]
pub fn mstcmp4(&self) -> MSTCMP4_R {
MSTCMP4_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - TARST"]
#[inline(always)]
pub fn tarst(&self) -> TARST_R {
TARST_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - TAREP"]
#[inline(always)]
pub fn tarep(&self) -> TAREP_R {
TAREP_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - TACMP1"]
#[inline(always)]
pub fn tacmp1(&self) -> TACMP1_R {
TACMP1_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - TACMP2"]
#[inline(always)]
pub fn tacmp2(&self) -> TACMP2_R {
TACMP2_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - TBRST"]
#[inline(always)]
pub fn tbrst(&self) -> TBRST_R {
TBRST_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - TBREP"]
#[inline(always)]
pub fn tbrep(&self) -> TBREP_R {
TBREP_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - TBCMP1"]
#[inline(always)]
pub fn tbcmp1(&self) -> TBCMP1_R {
TBCMP1_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - TBCMP2"]
#[inline(always)]
pub fn tbcmp2(&self) -> TBCMP2_R {
TBCMP2_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - TCRST"]
#[inline(always)]
pub fn tcrst(&self) -> TCRST_R {
TCRST_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - TCREP"]
#[inline(always)]
pub fn tcrep(&self) -> TCREP_R {
TCREP_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - TCCMP1"]
#[inline(always)]
pub fn tccmp1(&self) -> TCCMP1_R {
TCCMP1_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - TCCMP2"]
#[inline(always)]
pub fn tccmp2(&self) -> TCCMP2_R {
TCCMP2_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - TDRST"]
#[inline(always)]
pub fn tdrst(&self) -> TDRST_R {
TDRST_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - TDREP"]
#[inline(always)]
pub fn tdrep(&self) -> TDREP_R {
TDREP_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - TDCMP1"]
#[inline(always)]
pub fn tdcmp1(&self) -> TDCMP1_R {
TDCMP1_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - TDCMP2"]
#[inline(always)]
pub fn tdcmp2(&self) -> TDCMP2_R {
TDCMP2_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - TERST"]
#[inline(always)]
pub fn terst(&self) -> TERST_R {
TERST_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - TEREP"]
#[inline(always)]
pub fn terep(&self) -> TEREP_R {
TEREP_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - TECMP1"]
#[inline(always)]
pub fn tecmp1(&self) -> TECMP1_R {
TECMP1_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 26 - TECMP2"]
#[inline(always)]
pub fn tecmp2(&self) -> TECMP2_R {
TECMP2_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - TAEEV7"]
#[inline(always)]
pub fn taeev7(&self) -> TAEEV7_R {
TAEEV7_R::new(((self.bits >> 27) & 1) != 0)
}
#[doc = "Bit 28 - TDEEV8"]
#[inline(always)]
pub fn tdeev8(&self) -> TDEEV8_R {
TDEEV8_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 29 - EEV7"]
#[inline(always)]
pub fn eev7(&self) -> EEV7_R {
EEV7_R::new(((self.bits >> 29) & 1) != 0)
}
#[doc = "Bit 30 - EEV8"]
#[inline(always)]
pub fn eev8(&self) -> EEV8_R {
EEV8_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - OCHPEV"]
#[inline(always)]
pub fn ochpev(&self) -> OCHPEV_R {
OCHPEV_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - SW"]
#[inline(always)]
#[must_use]
pub fn sw(&mut self) -> SW_W<BMTRGR_SPEC, 0> {
SW_W::new(self)
}
#[doc = "Bit 1 - MSTRST"]
#[inline(always)]
#[must_use]
pub fn mstrst(&mut self) -> MSTRST_W<BMTRGR_SPEC, 1> {
MSTRST_W::new(self)
}
#[doc = "Bit 2 - MSTREP"]
#[inline(always)]
#[must_use]
pub fn mstrep(&mut self) -> MSTREP_W<BMTRGR_SPEC, 2> {
MSTREP_W::new(self)
}
#[doc = "Bit 3 - MSTCMP1"]
#[inline(always)]
#[must_use]
pub fn mstcmp1(&mut self) -> MSTCMP1_W<BMTRGR_SPEC, 3> {
MSTCMP1_W::new(self)
}
#[doc = "Bit 4 - MSTCMP2"]
#[inline(always)]
#[must_use]
pub fn mstcmp2(&mut self) -> MSTCMP2_W<BMTRGR_SPEC, 4> {
MSTCMP2_W::new(self)
}
#[doc = "Bit 5 - MSTCMP3"]
#[inline(always)]
#[must_use]
pub fn mstcmp3(&mut self) -> MSTCMP3_W<BMTRGR_SPEC, 5> {
MSTCMP3_W::new(self)
}
#[doc = "Bit 6 - MSTCMP4"]
#[inline(always)]
#[must_use]
pub fn mstcmp4(&mut self) -> MSTCMP4_W<BMTRGR_SPEC, 6> {
MSTCMP4_W::new(self)
}
#[doc = "Bit 7 - TARST"]
#[inline(always)]
#[must_use]
pub fn tarst(&mut self) -> TARST_W<BMTRGR_SPEC, 7> {
TARST_W::new(self)
}
#[doc = "Bit 8 - TAREP"]
#[inline(always)]
#[must_use]
pub fn tarep(&mut self) -> TAREP_W<BMTRGR_SPEC, 8> {
TAREP_W::new(self)
}
#[doc = "Bit 9 - TACMP1"]
#[inline(always)]
#[must_use]
pub fn tacmp1(&mut self) -> TACMP1_W<BMTRGR_SPEC, 9> {
TACMP1_W::new(self)
}
#[doc = "Bit 10 - TACMP2"]
#[inline(always)]
#[must_use]
pub fn tacmp2(&mut self) -> TACMP2_W<BMTRGR_SPEC, 10> {
TACMP2_W::new(self)
}
#[doc = "Bit 11 - TBRST"]
#[inline(always)]
#[must_use]
pub fn tbrst(&mut self) -> TBRST_W<BMTRGR_SPEC, 11> {
TBRST_W::new(self)
}
#[doc = "Bit 12 - TBREP"]
#[inline(always)]
#[must_use]
pub fn tbrep(&mut self) -> TBREP_W<BMTRGR_SPEC, 12> {
TBREP_W::new(self)
}
#[doc = "Bit 13 - TBCMP1"]
#[inline(always)]
#[must_use]
pub fn tbcmp1(&mut self) -> TBCMP1_W<BMTRGR_SPEC, 13> {
TBCMP1_W::new(self)
}
#[doc = "Bit 14 - TBCMP2"]
#[inline(always)]
#[must_use]
pub fn tbcmp2(&mut self) -> TBCMP2_W<BMTRGR_SPEC, 14> {
TBCMP2_W::new(self)
}
#[doc = "Bit 15 - TCRST"]
#[inline(always)]
#[must_use]
pub fn tcrst(&mut self) -> TCRST_W<BMTRGR_SPEC, 15> {
TCRST_W::new(self)
}
#[doc = "Bit 16 - TCREP"]
#[inline(always)]
#[must_use]
pub fn tcrep(&mut self) -> TCREP_W<BMTRGR_SPEC, 16> {
TCREP_W::new(self)
}
#[doc = "Bit 17 - TCCMP1"]
#[inline(always)]
#[must_use]
pub fn tccmp1(&mut self) -> TCCMP1_W<BMTRGR_SPEC, 17> {
TCCMP1_W::new(self)
}
#[doc = "Bit 18 - TCCMP2"]
#[inline(always)]
#[must_use]
pub fn tccmp2(&mut self) -> TCCMP2_W<BMTRGR_SPEC, 18> {
TCCMP2_W::new(self)
}
#[doc = "Bit 19 - TDRST"]
#[inline(always)]
#[must_use]
pub fn tdrst(&mut self) -> TDRST_W<BMTRGR_SPEC, 19> {
TDRST_W::new(self)
}
#[doc = "Bit 20 - TDREP"]
#[inline(always)]
#[must_use]
pub fn tdrep(&mut self) -> TDREP_W<BMTRGR_SPEC, 20> {
TDREP_W::new(self)
}
#[doc = "Bit 21 - TDCMP1"]
#[inline(always)]
#[must_use]
pub fn tdcmp1(&mut self) -> TDCMP1_W<BMTRGR_SPEC, 21> {
TDCMP1_W::new(self)
}
#[doc = "Bit 22 - TDCMP2"]
#[inline(always)]
#[must_use]
pub fn tdcmp2(&mut self) -> TDCMP2_W<BMTRGR_SPEC, 22> {
TDCMP2_W::new(self)
}
#[doc = "Bit 23 - TERST"]
#[inline(always)]
#[must_use]
pub fn terst(&mut self) -> TERST_W<BMTRGR_SPEC, 23> {
TERST_W::new(self)
}
#[doc = "Bit 24 - TEREP"]
#[inline(always)]
#[must_use]
pub fn terep(&mut self) -> TEREP_W<BMTRGR_SPEC, 24> {
TEREP_W::new(self)
}
#[doc = "Bit 25 - TECMP1"]
#[inline(always)]
#[must_use]
pub fn tecmp1(&mut self) -> TECMP1_W<BMTRGR_SPEC, 25> {
TECMP1_W::new(self)
}
#[doc = "Bit 26 - TECMP2"]
#[inline(always)]
#[must_use]
pub fn tecmp2(&mut self) -> TECMP2_W<BMTRGR_SPEC, 26> {
TECMP2_W::new(self)
}
#[doc = "Bit 27 - TAEEV7"]
#[inline(always)]
#[must_use]
pub fn taeev7(&mut self) -> TAEEV7_W<BMTRGR_SPEC, 27> {
TAEEV7_W::new(self)
}
#[doc = "Bit 28 - TDEEV8"]
#[inline(always)]
#[must_use]
pub fn tdeev8(&mut self) -> TDEEV8_W<BMTRGR_SPEC, 28> {
TDEEV8_W::new(self)
}
#[doc = "Bit 29 - EEV7"]
#[inline(always)]
#[must_use]
pub fn eev7(&mut self) -> EEV7_W<BMTRGR_SPEC, 29> {
EEV7_W::new(self)
}
#[doc = "Bit 30 - EEV8"]
#[inline(always)]
#[must_use]
pub fn eev8(&mut self) -> EEV8_W<BMTRGR_SPEC, 30> {
EEV8_W::new(self)
}
#[doc = "Bit 31 - OCHPEV"]
#[inline(always)]
#[must_use]
pub fn ochpev(&mut self) -> OCHPEV_W<BMTRGR_SPEC, 31> {
OCHPEV_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 = "BMTRGR\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bmtrgr::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 [`bmtrgr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct BMTRGR_SPEC;
impl crate::RegisterSpec for BMTRGR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`bmtrgr::R`](R) reader structure"]
impl crate::Readable for BMTRGR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`bmtrgr::W`](W) writer structure"]
impl crate::Writable for BMTRGR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets BMTRGR to value 0"]
impl crate::Resettable for BMTRGR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#![feature(proc_macro_hygiene)]
use hdk::prelude::*;
use hdk_proc_macros::zome;
// see https://developer.holochain.org/api/0.0.44-alpha3/hdk/ for info on using the hdk library
// This is a sample zome that defines an entry type "MyEntry" that can be committed to the
// agent's chain via the exposed function create_my_entry
mod utils;
#[derive(Serialize, Deserialize, Debug, DefaultJson, Clone)]
pub struct FlightSegment {
secure_flight: Option<bool>,
segment_key: String,
departure: Departure,
arrival: Arrival,
marketing_carrier: MarketingCarrier,
operation_carrier: Option<OperatingCarrier>,
equipement: Option<Equipment>,
class_of_service: Option<ClassOfService>,
flight_detail: Option<FlightDetail>,
}
#[derive(Serialize, Deserialize, Debug, DefaultJson, Clone)]
pub struct Departure {
airport_code: String,
timestamp: String,
airport_name: Option<String>,
terminal_name: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, DefaultJson, Clone)]
pub struct Arrival {
airport_code: String,
timestamp: Option<String>,
change_of_day: Option<String>,
airport_name: Option<String>,
terminal_name: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, DefaultJson, Clone)]
pub struct MarketingCarrier {
airline_id: String,
name: Option<String>,
flight_number: String,
}
#[derive(Serialize, Deserialize, Debug, DefaultJson, Clone)]
pub struct OperatingCarrier {
airline_id: Option<String>,
name: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, DefaultJson, Clone)]
pub struct Equipment {
aircraft_code: String,
name: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, DefaultJson, Clone)]
pub struct ClassOfService {
r#ref: Option<String>,
code: String,
seats_left: Option<String>,
markting_name: Option<MarketingName>,
}
#[derive(Serialize, Deserialize, Debug, DefaultJson, Clone)]
pub struct MarketingName {
cabin_designator: Option<String>,
name: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, DefaultJson, Clone)]
pub struct StopLocation {
airport_code: String,
arrival_timestamp: String,
departure_timestamp: String,
}
#[derive(Serialize, Deserialize, Debug, DefaultJson, Clone)]
pub struct FlightDetail {
flight_segment_type: Option<String>,
flight_duration: String,
stops: Option<String>,
stop_location: Vec<StopLocation>,
}
#[derive(Serialize, Deserialize, Debug, DefaultJson, Clone)]
pub struct Fare {
refs: String,
list_key: String,
fare_code: String,
fare_basis_code: String,
}
#[derive(Serialize, Deserialize, Debug, DefaultJson, Clone)]
pub struct PriceClass {
price_class_id: String,
name: String,
descriptions: Option<Vec<String>>,
class_of_service: Option<ClassOfService>,
}
impl FlightSegment {
fn entry(self) -> Entry {
Entry::App("flight_segment".into(), self.into())
}
}
impl PriceClass {
fn entry(self) -> Entry {
Entry::App("price_class".into(), self.into())
}
}
impl Fare {
fn entry(self) -> Entry {
Entry::App("fare".into(), self.into())
}
}
#[zome]
mod air_shopping {
#[init]
fn init() {
Ok(())
}
#[validate_agent]
pub fn validate_agent(validation_data: EntryValidationData<AgentId>) {
Ok(())
}
#[entry_def]
fn anchor_def() -> ValidatingEntryType {
holochain_anchors::anchor_definition()
}
#[entry_def]
fn flight_segment_def() -> ValidatingEntryType {
entry!(
name: "flight_segment",
description: "this is a same entry defintion",
sharing: Sharing::Public,
validation_package: || {
hdk::ValidationPackageDefinition::Entry
},
validation: | _validation_data: hdk::EntryValidationData<FlightSegment>| {
Ok(())
},
links: [
from!(
holochain_anchors::ANCHOR_TYPE,
link_type: "anchor->flight_segment",
validation_package: || {
hdk::ValidationPackageDefinition::Entry
},
validation: |_validation_data: hdk::LinkValidationData| {
Ok(())
}
)
]
)
}
#[entry_def]
fn fare_def() -> ValidatingEntryType {
entry!(
name: "fare",
description: "this is a same entry defintion",
sharing: Sharing::Public,
validation_package: || {
hdk::ValidationPackageDefinition::Entry
},
validation: | _validation_data: hdk::EntryValidationData<Fare>| {
Ok(())
},
links: [
from!(
holochain_anchors::ANCHOR_TYPE,
link_type: "anchor->fare",
validation_package: || {
hdk::ValidationPackageDefinition::Entry
},
validation: |_validation_data: hdk::LinkValidationData| {
Ok(())
}
)
]
)
}
#[entry_def]
fn price_class_def() -> ValidatingEntryType {
entry!(
name: "price_class",
description: "this is a same entry defintion",
sharing: Sharing::Public,
validation_package: || {
hdk::ValidationPackageDefinition::Entry
},
validation: | _validation_data: hdk::EntryValidationData<PriceClass>| {
match _validation_data{
hdk::EntryValidationData::Create{
entry,..
}=>{
utils::validation_ref_price_class(entry)
},
_=>Err("only create".to_string())
}
},
links: [
from!(
holochain_anchors::ANCHOR_TYPE,
link_type: "anchor->price_class",
validation_package: || {
hdk::ValidationPackageDefinition::Entry
},
validation: |_validation_data: hdk::LinkValidationData| {
Ok(())
}
)
]
)
}
#[zome_fn("hc_public")]
fn create_flight_segment(flight_segment: FlightSegment) -> ZomeApiResult<Address> {
let anchor_address = holochain_anchors::anchor(
"flight_segment".to_string(),
flight_segment.segment_key.clone(),
)?;
let flight_segment_entry = flight_segment.entry();
let flight_segment_address = hdk::commit_entry(&flight_segment_entry)?;
hdk::link_entries(
&anchor_address,
&flight_segment_address.clone(),
"anchor->flight_segment",
"",
)?;
Ok(flight_segment_address)
}
#[zome_fn("hc_public")]
fn get_entry(r#type: String, key: String) -> ZomeApiResult<JsonString> {
let anchor_address = holochain_anchors::anchor(r#type.clone(), key.clone())?;
hdk::debug::<JsonString>(anchor_address.clone().into())?;
let option_address = hdk::get_links(
&anchor_address,
LinkMatch::Exactly(&("anchor->".to_string() + &r#type)),
LinkMatch::Any,
)?;
if let Some(address) = option_address.addresses().last() {
match hdk::get_entry(&address)? {
Some(Entry::App(_tupe, json_string)) => Ok(json_string),
_ => Err(ZomeApiError::Internal("This page no exist".to_string())),
}
} else {
Err(ZomeApiError::Internal("This page no exist".to_string()))
}
}
#[zome_fn("hc_public")]
fn create_fare(fare: Fare) -> ZomeApiResult<Address> {
let anchor_address = holochain_anchors::anchor("fare".to_string(), fare.list_key.clone())?;
let fare_entry = fare.entry();
let fare_address = hdk::commit_entry(&fare_entry)?;
hdk::link_entries(&anchor_address, &fare_address.clone(), "anchor->fare", "")?;
Ok(fare_address)
}
#[zome_fn("hc_public")]
fn create_price_class(price_class: PriceClass) -> ZomeApiResult<Address> {
let anchor_address = holochain_anchors::anchor(
"price_class".to_string(),
price_class.price_class_id.clone(),
)?;
let price_class_entry = price_class.clone().entry();
let price_class_address = hdk::commit_entry(&price_class_entry)?;
hdk::link_entries(
&anchor_address,
&price_class_address.clone(),
"anchor->price_class",
"",
)?;
if let Some(class_of_service) = price_class.class_of_service {
if let Some(r#ref) = class_of_service.r#ref {
let mut iter = r#ref.split_ascii_whitespace();
if let Some(s) = iter.next() {
let anchor_address =
holochain_anchors::anchor("flight_segment".to_string(), s.to_string())?;
hdk::link_entries(
&anchor_address,
&price_class_address.clone(),
"anchor->price_class",
"",
)?;
}
if let Some(s) = iter.next() {
let anchor_address =
holochain_anchors::anchor("fare".to_string(), s.to_string())?;
hdk::link_entries(
&anchor_address,
&price_class_address.clone(),
"anchor->price_class",
"",
)?;
}
}
}
Ok(price_class_address)
}
}
|
use parameterized_macro::parameterized;
#[parameterized(zzz = { "a", "b" }, aaa = { 1, 2, 3 })]
pub(crate) fn my_test(v: &str, w: i32) {}
fn main() {}
|
pub fn build_proverb(list: &[&str]) -> String {
if list.len() == 1 {
return format!("And all for the want of a {}.", list[0]);
}
let mut output = String::new();
for i in 0..list.len() {
if i + 1 == list.len() {
output.push_str(format!("And all for the want of a {}.", list[0]).as_str());
break;
}
output.push_str(format!("For want of a {} the {} was lost.\n", list[i], list[i+1]).as_str());
}
output
}
|
#![allow(non_camel_case_types)]
#![allow(dead_code)]
#![allow(const_err)]
#![allow(unused_imports)]
use libusb_sys as ffi;
use libc::{c_int,c_uchar};
use crate::ftdi::constants::{*};
use crate::ftdi::eeprom::ftdi_eeprom;
use std::sync::{Arc, Mutex};
use std::{mem::{MaybeUninit}, slice, io, ptr};
use snafu::{ensure, Backtrace, ErrorCompat, ResultExt, Snafu};
use log::{debug, info, warn, error};
use linuxver::version;
use crate::ftdi::ftdi_context::ftdi_context;
#[derive(Debug, Snafu)]
pub enum FtdiError {
#[snafu(display("USB SYS INIT: error code: \'{}\', message: \'{}\'\n{}", code, message, backtrace))]
UsbInit {
code: i32,
message: String,
backtrace: Backtrace,
},
#[snafu(display("USB SYS COMMAND: error code: \'{}\', message: \'{}\'\n{}", code, message, backtrace))]
UsbCommandError {
code: i32,
message: String,
backtrace: Backtrace,
},
#[snafu(display("COMMON ERROR: error code: \'{}\', message: \'{}\'\n{}", code, message, backtrace))]
UsbCommonError {
code: i32,
message: String,
backtrace: Backtrace,
}
}
pub type Result<T, E = FtdiError> = std::result::Result<T, E>;
// #[derive(Copy, Debug)]
#[repr(C)]
pub struct ftdi_transfer_control {
pub completed: i32,
pub buf: Vec<u8>,
pub size: i32,
pub offset: i32,
pub ftdi: Arc<Mutex<ftdi_context>>,
// pub ftdi: Option<*mut ffi::libusb_context>,
pub transfer: ffi::libusb_transfer,
// pub transfer: Arc<Mutex<ffi::libusb_transfer>>,
}
impl Default for ftdi_transfer_control {
fn default() -> Self {
let libusb_transfer_uninit = MaybeUninit::<ffi::libusb_transfer>::zeroed();
let libusb_transfer = unsafe { libusb_transfer_uninit.assume_init() };
ftdi_transfer_control {
completed: 0,
buf: Vec::new(),
size: 0,
offset: 0,
ftdi: Arc::new(Mutex::new(ftdi_context::default())),
// transfer: Arc::new(Mutex::new( libusb_transfer ))
transfer: libusb_transfer
}
}
}
impl ftdi_transfer_control {
pub fn new(ftdi: ftdi_context, buffer: &Vec<u8>) -> Self {
// pub fn new(ftdi: ftdi_context, buffer: &Box<[u8]>) -> Self {
let libusb_transfer_uninit = MaybeUninit::<ffi::libusb_transfer>::zeroed();
let libusb_transfer = unsafe { libusb_transfer_uninit.assume_init() };
ftdi_transfer_control {
completed: 0,
buf: buffer.to_vec(), // TODO: check if cloning is correct way here
size: buffer.len() as i32,
offset: 0,
ftdi: Arc::new(Mutex::new(ftdi)),
// transfer: Arc::new(Mutex::new( libusb_transfer ))
transfer: libusb_transfer,
}
}
}
enum ftdi_cbus_func {
CBUS_TXDEN = 0, CBUS_PWREN = 1, CBUS_RXLED = 2, CBUS_TXLED = 3, CBUS_TXRXLED = 4,
CBUS_SLEEP = 5, CBUS_CLK48 = 6, CBUS_CLK24 = 7, CBUS_CLK12 = 8, CBUS_CLK6 = 9,
CBUS_IOMODE = 0xa, CBUS_BB_WR = 0xb, CBUS_BB_RD = 0xc
}
enum ftdi_cbush_func {
CBUSH_TRISTATE = 0, CBUSH_TXLED = 1, CBUSH_RXLED = 2, CBUSH_TXRXLED = 3, CBUSH_PWREN = 4,
CBUSH_SLEEP = 5, CBUSH_DRIVE_0 = 6, CBUSH_DRIVE1 = 7, CBUSH_IOMODE = 8, CBUSH_TXDEN = 9,
CBUSH_CLK30 = 10, CBUSH_CLK15 = 11, CBUSH_CLK7_5 = 12
}
enum ftdi_cbusx_func {
CBUSX_TRISTATE = 0, CBUSX_TXLED = 1, CBUSX_RXLED = 2, CBUSX_TXRXLED = 3, CBUSX_PWREN = 4,
CBUSX_SLEEP = 5, CBUSX_DRIVE_0 = 6, CBUSX_DRIVE1 = 7, CBUSX_IOMODE = 8, CBUSX_TXDEN = 9,
CBUSX_CLK24 = 10, CBUSX_CLK12 = 11, CBUSX_CLK6 = 12, CBUSX_BAT_DETECT = 13,
CBUSX_BAT_DETECT_NEG = 14, CBUSX_I2C_TXE = 15, CBUSX_I2C_RXF = 16, CBUSX_VBUS_SENSE = 17,
CBUSX_BB_WR = 18, CBUSX_BB_RD = 19, CBUSX_TIME_STAMP = 20, CBUSX_AWAKE = 21
}
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct size_and_time {
pub total_bytes: usize,
/// seconds or milliseconds
pub timeval: u128,
}
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct progress {
pub first: size_and_time,
pub prev: size_and_time,
pub current: size_and_time,
pub total_time: f64,
pub total_rate: f64,
pub current_rate: f64,
}
type FTDIProgressInfo = progress;
#[macro_export]
macro_rules! scanf {
( $string:expr, $sep:expr, $( $x:ty ),+ ) => {{
let mut iter = $string.split($sep);
($(iter.next().and_then(|word| word.parse::<$x>().ok()),)*)
}}
}
|
use crate::demo::data::DemoTick;
use crate::demo::parser::MalformedSendPropDefinitionError;
use crate::demo::sendprop::{
RawSendPropDefinition, SendPropDefinition, SendPropFlag, SendPropIdentifier, SendPropType,
};
use crate::{Parse, ParseError, ParserState, Result, Stream};
use bitbuffer::{
BitRead, BitReadStream, BitWrite, BitWriteSized, BitWriteStream, Endianness, LittleEndian,
};
use parse_display::{Display, FromStr};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::cmp::min;
use std::convert::TryFrom;
use std::iter::once;
use std::ops::Deref;
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(
BitRead,
BitWrite,
Debug,
Clone,
Copy,
PartialEq,
Eq,
Hash,
Ord,
PartialOrd,
Display,
FromStr,
Serialize,
Deserialize,
)]
pub struct ClassId(u16);
impl From<u16> for ClassId {
fn from(int: u16) -> Self {
ClassId(int)
}
}
impl From<ClassId> for usize {
fn from(class: ClassId) -> Self {
class.0 as usize
}
}
impl From<ClassId> for u16 {
fn from(class: ClassId) -> Self {
class.0
}
}
impl PartialEq<u16> for ClassId {
fn eq(&self, other: &u16) -> bool {
self.0 == *other
}
}
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(BitRead, BitWrite, PartialEq, Eq, Hash, Debug, Serialize, Deserialize, Clone, Display)]
pub struct ServerClassName(String);
impl ServerClassName {
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl From<String> for ServerClassName {
fn from(value: String) -> Self {
Self(value)
}
}
impl From<&str> for ServerClassName {
fn from(value: &str) -> Self {
Self(value.into())
}
}
impl PartialEq<&str> for ServerClassName {
fn eq(&self, other: &&str) -> bool {
self.as_str() == *other
}
}
impl AsRef<str> for ServerClassName {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl Deref for ServerClassName {
type Target = str;
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(BitRead, BitWrite, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServerClass {
pub id: ClassId,
pub name: ServerClassName,
pub data_table: SendTableName,
}
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(
BitWrite,
PartialEq,
Eq,
Hash,
Debug,
Serialize,
Deserialize,
Clone,
Display,
PartialOrd,
Ord,
Default,
)]
pub struct SendTableName(Cow<'static, str>);
impl SendTableName {
pub fn as_str(&self) -> &str {
self.0.as_ref()
}
}
impl<E: Endianness> BitRead<'_, E> for SendTableName {
fn read(stream: &mut BitReadStream<'_, E>) -> bitbuffer::Result<Self> {
String::read(stream).map(SendTableName::from)
}
}
impl From<String> for SendTableName {
fn from(value: String) -> Self {
Self(Cow::Owned(value))
}
}
impl From<&'static str> for SendTableName {
fn from(value: &'static str) -> Self {
Self(Cow::Borrowed(value))
}
}
impl PartialEq<&str> for SendTableName {
fn eq(&self, other: &&str) -> bool {
self.as_str() == *other
}
}
impl AsRef<str> for SendTableName {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl Deref for SendTableName {
type Target = str;
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ParseSendTable {
pub name: SendTableName,
pub props: Vec<RawSendPropDefinition>,
pub needs_decoder: bool,
}
impl Parse<'_> for ParseSendTable {
fn parse(stream: &mut Stream, _state: &ParserState) -> Result<Self> {
let needs_decoder = stream.read()?;
let name: SendTableName = stream.read()?;
let prop_count = stream.read_int(10)?;
let mut array_element_prop = None;
let mut props = Vec::with_capacity(min(prop_count, 128));
for _ in 0..prop_count {
let prop: RawSendPropDefinition = RawSendPropDefinition::read(stream, &name)?;
if prop.flags.contains(SendPropFlag::InsideArray) {
if array_element_prop.is_some() || prop.flags.contains(SendPropFlag::ChangesOften) {
return Err(MalformedSendPropDefinitionError::ArrayChangesOften.into());
}
array_element_prop = Some(prop);
} else if let Some(array_element) = array_element_prop {
if prop.prop_type != SendPropType::Array {
return Err(MalformedSendPropDefinitionError::UntypedArray.into());
}
array_element_prop = None;
props.push(prop.with_array_property(array_element));
} else {
props.push(prop);
}
}
Ok(ParseSendTable {
name,
props,
needs_decoder,
})
}
}
impl BitWrite<LittleEndian> for ParseSendTable {
fn write(&self, stream: &mut BitWriteStream<LittleEndian>) -> bitbuffer::Result<()> {
self.needs_decoder.write(stream)?;
self.name.write(stream)?;
let prop_count: u16 = self
.props
.iter()
.map(|prop| match prop.array_property {
Some(_) => 2,
None => 1,
})
.sum();
prop_count.write_sized(stream, 10)?;
for prop in self
.props
.iter()
.flat_map(|prop| prop.array_property.as_deref().into_iter().chain(once(prop)))
{
prop.write(stream)?;
}
Ok(())
}
}
#[test]
fn test_parse_send_table_roundtrip() {
use crate::demo::sendprop::SendPropFlags;
let state = ParserState::new(24, |_| false, false);
crate::test_roundtrip_encode(
ParseSendTable {
name: "foo".into(),
props: vec![],
needs_decoder: true,
},
&state,
);
crate::test_roundtrip_encode(
ParseSendTable {
name: "table1".into(),
props: vec![
RawSendPropDefinition {
prop_type: SendPropType::Float,
name: "prop1".into(),
identifier: SendPropIdentifier::new("table1", "prop1"),
flags: SendPropFlags::default() | SendPropFlag::ChangesOften,
table_name: None,
low_value: Some(0.0),
high_value: Some(128.0),
bit_count: Some(10),
element_count: None,
array_property: None,
original_bit_count: Some(10),
},
RawSendPropDefinition {
prop_type: SendPropType::Array,
name: "prop2".into(),
identifier: SendPropIdentifier::new("table1", "prop2"),
flags: SendPropFlags::default(),
table_name: None,
low_value: None,
high_value: None,
bit_count: None,
element_count: Some(10),
array_property: Some(Box::new(RawSendPropDefinition {
prop_type: SendPropType::Int,
name: "prop3".into(),
identifier: SendPropIdentifier::new("table1", "prop3"),
flags: SendPropFlags::default()
| SendPropFlag::InsideArray
| SendPropFlag::NoScale,
table_name: None,
low_value: Some(i32::MIN as f32),
high_value: Some(i32::MAX as f32),
bit_count: Some(32),
element_count: None,
array_property: None,
original_bit_count: Some(32),
})),
original_bit_count: None,
},
RawSendPropDefinition {
prop_type: SendPropType::DataTable,
name: "prop1".into(),
identifier: SendPropIdentifier::new("table1", "prop1"),
flags: SendPropFlags::default() | SendPropFlag::Exclude,
table_name: Some("table2".into()),
low_value: None,
high_value: None,
bit_count: None,
element_count: None,
array_property: None,
original_bit_count: None,
},
],
needs_decoder: true,
},
&state,
);
}
impl ParseSendTable {
pub fn flatten_props(&self, tables: &[ParseSendTable]) -> Result<Vec<SendPropDefinition>> {
let mut flat = Vec::with_capacity(32);
self.push_props_end(
tables,
&self.get_excludes(tables),
&mut flat,
&mut Vec::with_capacity(16),
)?;
// sort often changed props before the others
let mut start = 0;
for i in 0..flat.len() {
if flat[i].parse_definition.changes_often() {
if i != start {
flat.swap(i, start);
}
start += 1;
}
}
Ok(flat)
}
fn get_excludes<'a>(&'a self, tables: &'a [ParseSendTable]) -> Vec<SendPropIdentifier> {
let mut excludes = Vec::with_capacity(8);
self.build_excludes(tables, &mut Vec::with_capacity(8), &mut excludes);
excludes
}
fn build_excludes<'a>(
&'a self,
tables: &'a [ParseSendTable],
processed_tables: &mut Vec<&'a SendTableName>,
excludes: &mut Vec<SendPropIdentifier>,
) {
processed_tables.push(&self.name);
for prop in self.props.iter() {
if let Some(exclude_table) = prop.get_exclude_table() {
excludes.push(SendPropIdentifier::new(
exclude_table.as_str(),
prop.name.as_str(),
))
} else if let Some(table) = prop.get_data_table(tables) {
if !processed_tables.contains(&&table.name) {
table.build_excludes(tables, processed_tables, excludes);
}
}
}
}
// TODO: below is a direct port from the js which is a direct port from C++ and not very optimal
fn push_props_end<'a>(
&'a self,
tables: &'a [ParseSendTable],
excludes: &[SendPropIdentifier],
props: &mut Vec<SendPropDefinition>,
table_stack: &mut Vec<&'a SendTableName>,
) -> Result<()> {
let mut local_props = Vec::new();
self.push_props_collapse(tables, excludes, &mut local_props, props, table_stack)?;
props.extend_from_slice(&local_props);
Ok(())
}
fn push_props_collapse<'a>(
&'a self,
tables: &'a [ParseSendTable],
excludes: &[SendPropIdentifier],
local_props: &mut Vec<SendPropDefinition>,
props: &mut Vec<SendPropDefinition>,
table_stack: &mut Vec<&'a SendTableName>,
) -> Result<()> {
table_stack.push(&self.name);
let result = self
.props
.iter()
.filter(|prop| !prop.is_exclude())
.filter(|prop| !excludes.iter().any(|exclude| *exclude == prop.identifier()))
.try_for_each(|prop| {
if let Some(table) = prop.get_data_table(tables) {
if !table_stack.contains(&&table.name) {
if prop.flags.contains(SendPropFlag::Collapsible) {
table.push_props_collapse(
tables,
excludes,
local_props,
props,
table_stack,
)?;
} else {
table.push_props_end(tables, excludes, props, table_stack)?;
}
}
} else {
local_props.push(SendPropDefinition::try_from(prop)?);
}
Ok(())
});
table_stack.pop();
result
}
}
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SendTable {
pub name: SendTableName,
pub needs_decoder: bool,
pub raw_props: Vec<RawSendPropDefinition>,
pub flattened_props: Vec<SendPropDefinition>,
}
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct DataTablePacket {
pub tick: DemoTick,
pub tables: Vec<ParseSendTable>,
pub server_classes: Vec<ServerClass>,
}
impl Parse<'_> for DataTablePacket {
fn parse(stream: &mut Stream, state: &ParserState) -> Result<Self> {
let tick = stream.read()?;
let len = stream.read_int::<usize>(32)?;
let mut packet_data = stream.read_bits(len * 8)?;
let mut tables = Vec::new();
while packet_data.read_bool()? {
let table = ParseSendTable::parse(&mut packet_data, state)?;
tables.push(table);
}
let server_class_count = packet_data.read_int(16)?;
let server_classes = packet_data.read_sized(server_class_count)?;
if packet_data.bits_left() > 7 {
Err(ParseError::DataRemaining(packet_data.bits_left()))
} else {
Ok(DataTablePacket {
tick,
tables,
server_classes,
})
}
}
}
impl BitWrite<LittleEndian> for DataTablePacket {
fn write(&self, stream: &mut BitWriteStream<LittleEndian>) -> bitbuffer::Result<()> {
self.tick.write(stream)?;
stream.reserve_byte_length(32, |stream| {
for table in self.tables.iter() {
true.write(stream)?;
table.write(stream)?;
}
false.write(stream)?;
(self.server_classes.len() as u16).write(stream)?;
self.server_classes.write(stream)?;
Ok(())
})
}
}
#[test]
fn test_data_table_packet_roundtrip() {
use crate::demo::sendprop::SendPropFlags;
let state = ParserState::new(24, |_| false, false);
crate::test_roundtrip_encode(
DataTablePacket {
tick: 123.into(),
tables: vec![],
server_classes: vec![],
},
&state,
);
let table1 = ParseSendTable {
name: "table1".into(),
props: vec![
RawSendPropDefinition {
prop_type: SendPropType::Float,
name: "prop1".into(),
identifier: SendPropIdentifier::new("table1", "prop1"),
flags: SendPropFlags::default() | SendPropFlag::ChangesOften,
table_name: None,
low_value: Some(0.0),
high_value: Some(128.0),
bit_count: Some(10),
element_count: None,
array_property: None,
original_bit_count: Some(10),
},
RawSendPropDefinition {
prop_type: SendPropType::Array,
name: "prop2".into(),
identifier: SendPropIdentifier::new("table1", "prop2"),
flags: SendPropFlags::default(),
table_name: None,
low_value: None,
high_value: None,
bit_count: None,
element_count: Some(10),
array_property: Some(Box::new(RawSendPropDefinition {
prop_type: SendPropType::Int,
name: "prop3".into(),
identifier: SendPropIdentifier::new("table1", "prop3"),
flags: SendPropFlags::default()
| SendPropFlag::InsideArray
| SendPropFlag::NoScale,
table_name: None,
low_value: Some(i32::MIN as f32),
high_value: Some(i32::MAX as f32),
bit_count: Some(32),
element_count: None,
array_property: None,
original_bit_count: Some(32),
})),
original_bit_count: None,
},
RawSendPropDefinition {
prop_type: SendPropType::DataTable,
name: "prop1".into(),
identifier: SendPropIdentifier::new("table1", "prop1"),
flags: SendPropFlags::default() | SendPropFlag::Exclude,
table_name: Some("table2".into()),
low_value: None,
high_value: None,
bit_count: None,
element_count: None,
array_property: None,
original_bit_count: None,
},
],
needs_decoder: true,
};
let table2 = ParseSendTable {
name: "table2".into(),
props: vec![RawSendPropDefinition {
prop_type: SendPropType::Float,
name: "prop1".into(),
identifier: SendPropIdentifier::new("table2", "prop1"),
flags: SendPropFlags::default() | SendPropFlag::ChangesOften,
table_name: None,
low_value: Some(0.0),
high_value: Some(128.0),
bit_count: Some(10),
element_count: None,
array_property: None,
original_bit_count: Some(10),
}],
needs_decoder: true,
};
crate::test_roundtrip_encode(
DataTablePacket {
tick: 1.into(),
tables: vec![table1, table2],
server_classes: vec![
ServerClass {
id: ClassId(0),
name: "class1".into(),
data_table: "table1".into(),
},
ServerClass {
id: ClassId(1),
name: "class2".into(),
data_table: "table2".into(),
},
],
},
&state,
);
}
|
extern crate bank;
use bank::account::Account as Account;
use bank::writer::output_statement as output_statement;
#[derive(Debug,PartialEq)]
struct Statement {
bytes: Vec<u8>,
}
#[test]
fn account_stores_all_transactions() {
let mut account = Account::new(0);
account.deposit(200);
account.deposit(400);
assert_eq!(account.history().len(), 2)
}
#[test]
fn writing_statement_one_to_buffer() {
// we will write to this buffer
let mut buffer: Vec<u8> = Vec::new();
// load file as bytes
let mut statement_as_bytes = include_bytes!("examples/statement_one.txt").to_vec();
// Add an extra line feed
statement_as_bytes.push(10);
// Store it in a struct to use Debug & PartialEq
let statement = Statement { bytes: statement_as_bytes };
// Run code
let mut account = Account::new(200);
account.deposit(300);
account.withdraw(250);
account.deposit(100);
output_statement(&account,&mut buffer);
assert_eq!(&buffer,&statement.bytes)
}
#[test]
fn writing_statement_two_to_buffer() {
// we will write to this buffer
let mut buffer: Vec<u8> = Vec::new();
// load file as bytes
let mut statement_as_bytes = include_bytes!("examples/statement_two.txt").to_vec();
// Add an extra line feed
statement_as_bytes.push(10);
// Store it in a struct to use Debug & PartialEq
let statement = Statement { bytes: statement_as_bytes };
// Run code
let mut account_two = Account::new(1000);
account_two.deposit(2000);
account_two.withdraw(2999);
output_statement(&account_two,&mut buffer);
assert_eq!(&buffer,&statement.bytes)
}
|
extern crate ralloc;
mod util;
use std::collections::BTreeMap;
#[test]
fn btreemap() {
util::multiply(|| {
let mut map = BTreeMap::new();
util::acid(|| {
map.insert("Nicolas", "Cage");
map.insert("is", "God");
map.insert("according", "to");
map.insert("ca1ek", ".");
});
assert_eq!(map.get("Nicolas"), Some(&"Cage"));
assert_eq!(map.get("is"), Some(&"God"));
assert_eq!(map.get("according"), Some(&"to"));
assert_eq!(map.get("ca1ek"), Some(&"."));
assert_eq!(map.get("This doesn't exist."), None);
});
}
|
use crate::plan::MutatorContext;
use crate::scheduler::gc_work::ProcessEdgesWork;
use crate::scheduler::*;
use crate::util::OpaquePointer;
use crate::vm::VMBinding;
/// VM-specific methods for garbage collection.
pub trait Collection<VM: VMBinding> {
/// Stop all the mutator threads. MMTk calls this method when it requires all the mutator to yield for a GC.
/// This method is called by a single thread in MMTk (the GC controller).
/// This method should not return until all the threads are yielded.
/// The actual thread synchronization mechanism is up to the VM, and MMTk does not make assumptions on that.
///
/// Arguments:
/// * `tls`: The thread pointer for the GC controller/coordinator.
fn stop_all_mutators<E: ProcessEdgesWork<VM = VM>>(tls: OpaquePointer);
/// Resume all the mutator threads, the opposite of the above. When a GC is finished, MMTk calls this method.
///
/// Arguments:
/// * `tls`: The thread pointer for the GC controller/coordinator.
fn resume_mutators(tls: OpaquePointer);
/// Block the current thread for GC. This is called when an allocation request cannot be fulfilled and a GC
/// is needed. MMTk calls this method to inform the VM that the current thread needs to be blocked as a GC
/// is going to happen. Then MMTk starts a GC. For a stop-the-world GC, MMTk will then call `stop_all_mutators()`
/// before the GC, and call `resume_mutators()` after the GC.
///
/// Arguments:
/// * `tls`: The current thread pointer that should be blocked. The VM can optionally check if the current thread matches `tls`.
fn block_for_gc(tls: OpaquePointer);
/// Ask the VM to spawn a GC thread for MMTk. A GC thread may later call into the VM through these VM traits. Some VMs
/// have assumptions that those calls needs to be within VM internal threads.
/// As a result, MMTk does not spawn GC threads itself to avoid breaking this kind of assumptions.
/// MMTk calls this method to spawn GC threads during [`enable_collection()`](../memory_manager/fn.enable_collection.html).
///
/// Arguments:
/// * `tls`: The thread pointer for the parent thread that we spawn new threads from. This is the same `tls` when the VM
/// calls `enable_collection()` and passes as an argument.
/// * `ctx`: The GC worker context for the GC thread. If `None` is passed, it means spawning a GC thread for the GC controller,
/// which does not have a worker context.
fn spawn_worker_thread(tls: OpaquePointer, ctx: Option<&GCWorker<VM>>);
/// Allow VM-specific behaviors for a mutator after all the mutators are stopped and before any actual GC work starts.
///
/// Arguments:
/// * `tls`: The thread pointer for a mutator thread.
/// * `m`: The mutator context for the thread.
fn prepare_mutator<T: MutatorContext<VM>>(tls: OpaquePointer, m: &T);
/// Inform the VM for an out-of-memory error. The VM can implement its own error routine for OOM.
///
/// Arguments:
/// * `tls`: The thread pointer for the mutator which failed the allocation and triggered the OOM.
fn out_of_memory(_tls: OpaquePointer) {
panic!("Out of memory!");
}
/// Inform the VM to schedule finalization threads.
///
/// Arguments:
/// * `tls`: The thread pointer for the current GC thread.
fn schedule_finalization(_tls: OpaquePointer) {}
}
|
//! This module contains settings for render strategy of papergrid.
//!
//! - [`TrimStrategy`] and [`AlignmentStrategy`] allows to set [`Alignment`] settings.
//! - [`TabSize`] sets a default tab size.
//! - [`Charset`] responsible for special char treatment.
//! - [`Justification`] responsible for justification space of content.
//!
//! [`Alignment`]: crate::settings::Alignment
mod alignment_strategy;
mod charset;
mod justification;
mod tab_size;
mod trim_strategy;
pub use alignment_strategy::AlignmentStrategy;
pub use charset::{Charset, CleanCharset};
pub use justification::Justification;
pub use tab_size::TabSize;
pub use trim_strategy::TrimStrategy;
|
$NetBSD: patch-vendor_stacker_src_lib.rs,v 1.7 2023/01/23 18:49:04 he Exp $
Avoid missing pthread_* on older SunOS.
--- vendor/stacker/src/lib.rs.orig 2020-07-13 18:18:17.000000000 +0000
+++ vendor/stacker/src/lib.rs
@@ -407,7 +407,7 @@ cfg_if! {
);
Some(mi.assume_init().AllocationBase as usize + get_thread_stack_guarantee() + 0x1000)
}
- } else if #[cfg(any(target_os = "linux", target_os="solaris", target_os = "netbsd"))] {
+ } else if #[cfg(any(target_os = "linux", target_os = "netbsd"))] {
unsafe fn guess_os_stack_limit() -> Option<usize> {
let mut attr = std::mem::MaybeUninit::<libc::pthread_attr_t>::uninit();
assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0);
|
/*
* Rustパターン(記法)。
* CreatedAt: 2019-07-07
*/
fn main() {
let mut setting_value = Some(5);
let new_setting_value = Some(10);
match (setting_value, new_setting_value) {
(Some(_), Some(_)) => {
println!("既存の値の変更を上書きできません");
}
_ => {
setting_value = new_setting_value;
}
}
println!("設定: {:?}", setting_value);
}
|
//! A simple example that demonstrates the **Graph** widget functionality.
#[macro_use] extern crate conrod;
extern crate conrod_graph_widget;
extern crate petgraph;
use conrod::{widget, Borderable, Colorable, Labelable, Positionable, Sizeable, Widget};
use conrod::backend::glium::glium::{self, Surface};
use conrod_graph_widget::{node, Event, EdgeEvent, Node, NodeEvent, NodeSocket, Graph};
use std::collections::HashMap;
widget_ids! {
struct Ids {
graph,
}
}
type MyGraph = petgraph::Graph<&'static str, (usize, usize)>;
type Layout = conrod_graph_widget::Layout<petgraph::graph::NodeIndex>;
fn main() {
const WIDTH: u32 = 900;
const HEIGHT: u32 = 500;
// Demo Graph.
let mut graph = MyGraph::new();
let a = graph.add_node("A");
let b = graph.add_node("B");
let c = graph.add_node("C");
let d = graph.add_node("D");
let e = graph.add_node("E");
graph.extend_with_edges(&[
(a, c, (1, 0)),
(a, d, (0, 1)),
(b, d, (0, 0)),
(c, d, (0, 2)),
(d, e, (0, 0)),
]);
// Construct a starting layout for the nodes.
let mut layout_map = HashMap::new();
layout_map.insert(b, [-100.0, 100.0]);
layout_map.insert(a, [-300.0, 0.0]);
layout_map.insert(c, [-100.0, -100.0]);
layout_map.insert(d, [100.0, 0.0]);
layout_map.insert(e, [300.0, 0.0]);
let mut layout = Layout::from(layout_map);
// Build the window.
let mut events_loop = glium::glutin::EventsLoop::new();
let window = glium::glutin::WindowBuilder::new()
.with_title("Conrod Graph Widget")
.with_dimensions(WIDTH, HEIGHT);
let context = glium::glutin::ContextBuilder::new()
.with_vsync(true);
let display = glium::Display::new(window, context, &events_loop).unwrap();
// construct our `Ui`.
let mut ui = conrod::UiBuilder::new([WIDTH as f64, HEIGHT as f64]).build();
// Generate the widget identifiers.
let ids = Ids::new(ui.widget_id_generator());
// Add a `Font` to the `Ui`'s `font::Map` from file.
const FONT_PATH: &'static str =
concat!(env!("CARGO_MANIFEST_DIR"), "/assets/fonts/NotoSans/NotoSans-Regular.ttf");
ui.fonts.insert_from_file(FONT_PATH).unwrap();
// A type used for converting `conrod::render::Primitives` into `Command`s that can be used
// for drawing to the glium `Surface`.
let mut renderer = conrod::backend::glium::Renderer::new(&display).unwrap();
// The image map describing each of our widget->image mappings (in our case, none).
let image_map = conrod::image::Map::<glium::texture::Texture2d>::new();
// Begin the event loop.
let mut events = Vec::new();
'render: loop {
events.clear();
// Get all the new events since the last frame.
events_loop.poll_events(|event| { events.push(event); });
// If there are no new events, wait for one.
if events.is_empty() {
events_loop.run_forever(|event| {
events.push(event);
glium::glutin::ControlFlow::Break
});
}
// Process the events.
for event in events.drain(..) {
// Break from the loop upon `Escape` or closed window.
match event.clone() {
glium::glutin::Event::WindowEvent { event, .. } => {
match event {
glium::glutin::WindowEvent::Closed |
glium::glutin::WindowEvent::KeyboardInput {
input: glium::glutin::KeyboardInput {
virtual_keycode: Some(glium::glutin::VirtualKeyCode::Escape),
..
},
..
} => break 'render,
_ => (),
}
}
_ => (),
};
// Use the `winit` backend feature to convert the winit event to a conrod input.
let input = match conrod::backend::winit::convert_event(event, &display) {
None => continue,
Some(input) => input,
};
// Handle the input with the `Ui`.
ui.handle_event(input);
// Set the widgets.
let ui = &mut ui.set_widgets();
set_widgets(ui, &ids, &mut graph, &mut layout);
}
// Draw the `Ui` if it has changed.
if let Some(primitives) = ui.draw_if_changed() {
renderer.fill(&display, primitives, &image_map);
let mut target = display.draw();
target.clear_color(0.1, 0.11, 0.13, 1.0);
renderer.draw(&display, &mut target, &image_map).unwrap();
target.finish().unwrap();
}
}
}
fn set_widgets(ui: &mut conrod::UiCell, ids: &Ids, graph: &mut MyGraph, layout: &mut Layout) {
/////////////////
///// GRAPH /////
/////////////////
//
// Set the `Graph` widget.
//
// This returns a session on which we can begin setting nodes and edges.
//
// The session is used in multiple stages:
//
// 1. `Nodes` for setting a node widget for each node.
// 2. `Edges` for setting an edge widget for each edge.
// 3. `Final` for optionally displaying zoom percentage and cam position.
let session = {
// An identifier for each node in the graph.
let node_indices = graph.node_indices();
// Describe each edge in the graph as NodeSocket -> NodeSocket.
let edges = graph.raw_edges()
.iter()
.map(|e| {
let start = NodeSocket { id: e.source(), socket_index: e.weight.0 };
let end = NodeSocket { id: e.target(), socket_index: e.weight.1 };
(start, end)
});
Graph::new(node_indices, edges, layout)
.wh_of(ui.window)
.middle_of(ui.window)
.set(ids.graph, ui)
};
//////////////////
///// EVENTS /////
//////////////////
//
// Graph events that have occurred since the last time the graph was instantiated.
for event in session.events() {
match event {
Event::Node(event) => match event {
// NodeEvent::Add(node_kind) => {
// },
NodeEvent::Remove(node_id) => {
},
NodeEvent::Dragged { node_id, to, .. } => {
*layout.get_mut(&node_id).unwrap() = to;
},
},
Event::Edge(event) => match event {
EdgeEvent::AddStart(node_socket) => {
},
EdgeEvent::Add { start, end } => {
},
EdgeEvent::Cancelled(node_socket) => {
},
EdgeEvent::Remove { start, end } => {
},
},
}
}
/////////////////
///// NODES /////
/////////////////
//
// Instantiate a widget for each node within the graph.
let mut session = session.next();
for node in session.nodes() {
// Each `Node` contains:
//
// `id` - The unique node identifier for this node.
// `point` - The position at which this node will be set.
// `inputs`
// `outputs`
//
// Calling `node.widget(some_widget)` returns a `NodeWidget`, which contains:
//
// `wiget_id` - The widget identifier for the widget that will represent this node.
let node_id = node.node_id();
let inputs = graph.neighbors_directed(node_id, petgraph::Incoming).count();
let outputs = graph.neighbors_directed(node_id, petgraph::Outgoing).count();
let button = widget::Button::new()
.label(&graph[node_id])
.border(0.0);
let widget = Node::new(button)
.inputs(inputs)
.outputs(outputs)
.socket_color(conrod::color::LIGHT_RED)
.w_h(100.0, 60.0);
for _click in node.widget(widget).set(ui).widget_event {
println!("{} was clicked!", &graph[node_id]);
}
}
/////////////////
///// EDGES /////
/////////////////
//
// Instantiate a widget for each edge within the graph.
let mut session = session.next();
for edge in session.edges() {
let (a, b) = node::edge_socket_rects(&edge, ui);
let line = widget::Line::abs(a.xy(), b.xy())
.color(conrod::color::DARK_CHARCOAL)
.thickness(3.0);
// Each edge contains:
//
// `start` - The unique node identifier for the node at the start of the edge with point.
// `end` - The unique node identifier for the node at the end of the edge with point.
// `widget_id` - The wiget identifier for this edge.
edge.widget(line).set(ui);
}
}
|
extern crate libc;
use std::ptr;
use std::io::Error;
type Address = u64;
type Word = u64;
const PTRACE_GETREGS:libc::c_uint = 12;
#[derive(Clone, Default, Debug)]
struct Registers {
pub r15: Word,
pub r14: Word,
pub r13: Word,
pub r12: Word,
pub rbp: Word,
pub rbx: Word,
pub r11: Word,
pub r10: Word,
pub r9: Word,
pub r8: Word,
pub rax: Word,
pub rcx: Word,
pub rdx: Word,
pub rsi: Word,
pub rdi: Word,
pub orig_rax: Word,
pub rip: Word,
pub cs: Word,
pub eflags: Word,
pub rsp: Word,
pub ss: Word,
pub fs_base: Word,
pub gs_base: Word,
pub ds: Word,
pub es: Word,
pub fs: Word,
pub gs: Word
}
unsafe fn raw(request: libc::c_uint, pid: libc::pid_t, addr: *mut libc::c_void, data: *mut libc::c_void) -> Result<libc::c_long, usize> {
let v = libc::ptrace(request, pid, addr, data);
match v {
-1 => {
println!("OS error: {:?}", Error::last_os_error());
Result::Err(0)
},
_ => Result::Ok(v)
}
}
fn getregs(pid: libc::pid_t) -> Result<Registers, usize> {
let mut buf: Registers = Default::default();
let buf_mut: *mut Registers = &mut buf;
match unsafe {
raw (PTRACE_GETREGS, pid, ptr::null_mut(), buf_mut as *mut libc::c_void)
} {
Ok(_) => Ok(buf),
Err(e) => Err(e)
}
}
fn peek_data(pid: libc::pid_t, address:Address) -> Result<libc::c_long, usize> {
unsafe { raw(libc::PTRACE_PEEKDATA, pid, address as *mut libc::c_void, ptr::null_mut()) }
}
fn attach(pid: libc::pid_t) -> Result<libc::c_long, usize> {
unsafe { raw (libc::PTRACE_ATTACH, pid, ptr::null_mut(), ptr::null_mut()) }
}
fn detach(pid: libc::pid_t) -> Result<libc::c_long, usize>{
unsafe { raw (libc::PTRACE_DETACH, pid, ptr::null_mut() as *mut libc::c_void, ptr::null_mut() as *mut libc::c_void) }
}
fn wait(pid: libc::pid_t){
let mut status: i32 = 0;
unsafe { libc::waitpid(pid, &mut status as *mut libc::c_int, 0) };
}
pub fn patch(pid: libc::pid_t, patch:&str){
println!("{:?}", patch);
match attach(pid) {
Err(f) => println!("Cannot attach to {:?}:{:?}", pid, f),
Ok(_) => {
wait(pid);
println!("Attached to {:?}", pid);
let regs = getregs(pid).unwrap();
match peek_data(pid, regs.ds as Address) {
Ok(m) => println!("{:?}", m),
Err(f) => println!("Data peek error {:?}", f)
};
match detach(pid) {
Ok(_) => {
wait(pid);
println!("Detached from {:?}", pid);
},
Err(f) => println!("Cannot detach from {:?}:{:?}", pid, f)
}
}
}
}
|
use ast::*;
use back::env::{Env, SmartEnv};
use back::runtime_error::{check_args, RuntimeError};
use back::specials;
use back::trampoline;
use back::trampoline::{ContinuationResult, Flag};
use loc::Loc;
use std::rc::Rc;
pub type NodeResult = Result<Node, RuntimeError>;
pub fn eval_node(env: SmartEnv, node: Node, _: Vec<Node>, _: Flag) -> ContinuationResult {
match node.val {
Val::List(..) => Ok(trampoline::bounce(eval_list, env, node)),
Val::Symbol(name) => match env.borrow_mut().get(&name) {
Some(node) => Ok(trampoline::finish(node)),
None => Err(RuntimeError::UndefinedName(name, node.loc)),
},
_ => Ok(trampoline::finish(node)),
}
}
fn eval_each_node(env: SmartEnv, nodes: Vec<Node>) -> Result<Vec<Node>, RuntimeError> {
let mut outputs = Vec::new();
for node in nodes {
let output = trampoline::run(eval_node, Rc::clone(&env), node)?;
outputs.push(output);
}
Ok(outputs)
}
pub fn eval_each_node_in_list_for_single_output(
env: SmartEnv,
list_node: Node,
_: Vec<Node>,
_: Flag,
) -> ContinuationResult {
if let Val::List(mut nodes) = list_node.val {
if nodes.len() == 0 {
Ok(trampoline::finish(Node::new(Val::Nil, Loc::Unknown)))
} else {
while nodes.len() > 1 {
let node = nodes.remove(0);
trampoline::run(eval_node, Rc::clone(&env), node)?;
}
let final_node = nodes.remove(0);
Ok(trampoline::bounce(eval_node, env, final_node))
}
} else {
panic!("Unable to eval this non-list")
}
}
pub fn eval_list(env: SmartEnv, node: Node, _: Vec<Node>, flag: Flag) -> ContinuationResult {
let loc = node.loc;
let mut args = match node.val {
Val::List(children) => children,
_ => panic!("expected list"),
};
if args.len() == 0 {
return Ok(trampoline::finish(Node::new(Val::List(vec![]), loc)));
}
let head_node = args.remove(0);
let head_value = head_node.val;
match head_value {
Val::Symbol(ref name) => match name.as_ref() {
"def" => {
check_args("def", &loc, &args, 2, 2)?;
return specials::eval_special_def(env, args);
}
"quote" => {
check_args("quote", &loc, &args, 1, -1)?;
return specials::eval_special_quote(args);
}
"list" => {
check_args("list", &loc, &args, 0, -1)?;
return specials::eval_special_list(env, loc, args);
}
"fn" => {
check_args("fn", &loc, &args, 2, 2)?;
return specials::eval_special_routine(env, args, RoutineType::Function);
}
"macro" => {
check_args("macro", &loc, &args, 2, 2)?;
return specials::eval_special_routine(env, args, RoutineType::Macro);
}
"macroexpand1" => {
check_args("macroexpand1", &loc, &args, 1, 1)?;
return specials::eval_special_macroexpand1(env, args);
}
"if" => {
check_args("if", &loc, &args, 2, 3)?;
return specials::eval_special_if(env, args);
}
"cond" => {
check_args("cond", &loc, &args, 2, -1)?;
return specials::eval_special_cond(env, args);
}
"for" => {
check_args("for", &loc, &args, 4, 4)?;
return specials::eval_special_for(env, args);
}
"let" => {
check_args("let", &loc, &args, 2, -1)?;
return specials::eval_special_let(env, args);
}
"update!" => {
check_args("update!", &loc, &args, 2, 2)?;
return specials::eval_special_update(env, args);
}
"begin" => {
check_args("begin", &loc, &args, 0, -1)?;
return specials::eval_special_begin(env, args);
}
_ => {}
},
_ => {}
}
let mut evaled_head = trampoline::run(
eval_node,
Rc::clone(&env),
Node::new(head_value, loc.clone()),
)?;
// Sometimes the evaled head will lack a location. When that happens, the location needs
// to be set to the location of the unevaled head, to allow for good error messages.
if evaled_head.loc == Loc::Unknown {
evaled_head.loc = loc.clone();
}
// Prepare the arguments for passing to the procedure
let prepared_args = match &evaled_head.val {
Val::Routine(robj) => match robj.routine_type {
RoutineType::Macro => args,
RoutineType::Function => eval_each_node(Rc::clone(&env), args)?,
},
Val::Primitive(..) => eval_each_node(Rc::clone(&env), args)?,
_ => args,
};
match evaled_head.val {
Val::Routine(..) | Val::Primitive(..) => {
eval_invoke_procedure(env, evaled_head, prepared_args, flag)
}
_ => Err(RuntimeError::UnableToEvalListStartingWith(
format!("{}", evaled_head.val),
loc,
)),
}
}
pub fn eval_invoke_procedure(
env: SmartEnv,
head: Node,
args: Vec<Node>,
flag: Flag,
) -> ContinuationResult {
match head.val {
Val::Routine(..) => Ok(trampoline::bounce_with_nodes(
eval_invoke_routine,
Rc::clone(&env),
head,
args,
flag,
)),
Val::Primitive(ref obj) => {
check_args(&obj.name, &head.loc, &args, obj.min_arity, obj.max_arity)?;
let out = (obj.f)(Rc::clone(&env), head.clone(), args)?;
Ok(trampoline::finish(out))
}
_ => Err(RuntimeError::CannotInvokeNonProcedure(
head.val.to_string(),
head.loc,
)),
}
}
pub fn eval_invoke_routine(
dynamic_env: SmartEnv,
fnode: Node,
mut args: Vec<Node>,
flag: Flag,
) -> ContinuationResult {
let loc = fnode.loc;
if let Val::Routine(robj) = fnode.val {
let mut params = robj.params;
let body = robj.body;
let parent_lexical_env = robj.lexical_env;
// Determine if there is a &rest param
let mut has_variable_params = false;
for param in ¶ms {
if param.val == Val::Symbol("&rest".to_string()) {
has_variable_params = true;
break;
}
}
if !has_variable_params && (params.len() != args.len()) {
// The args and params don't match
return Err(RuntimeError::FunctionArgsDoNotMatchParams {
function_name: robj.name,
params_count: params.len(),
args_count: args.len(),
params_list: params,
args_list: args,
loc,
});
}
// Create the lexical environment based on the procedure's lexical parent
let lexical_env = Env::new(Some(parent_lexical_env));
// Map arguments to parameters
while params.len() > 0 {
let param = params.remove(0);
match param.val {
Val::Symbol(ref name) if name == "&rest" => {
if params.len() != 1 {
return Err(RuntimeError::TooManyFunctionParamsAfterRest {
function_name: robj.name,
remaining_params: params,
loc,
});
}
let rest_param = params.remove(0);
match rest_param.val {
Val::Symbol(name) => {
let l = Node::new(Val::List(args), rest_param.loc);
lexical_env.borrow_mut().define(&name, l)?;
break;
}
v => return Err(RuntimeError::ParamsMustBeSymbols(v, loc)),
}
}
Val::Symbol(name) => {
let arg = if args.len() > 0 {
args.remove(0)
} else {
return Err(RuntimeError::Unknown("not enough args".to_string(), loc));
};
lexical_env.borrow_mut().define(&name, arg)?;
}
v => return Err(RuntimeError::ParamsMustBeSymbols(v, loc)),
}
}
// Evaluate the application of the routine
match robj.routine_type {
RoutineType::Macro => {
let expanded_macro = trampoline::run(eval_node, lexical_env, *body)?;
match flag {
Flag::None => {
// This is executed in the environment of its application, not the
// environment of its definition
return Ok(trampoline::bounce(eval_node, dynamic_env, expanded_macro));
}
Flag::DelayMacroEvaluation => {
return Ok(trampoline::finish(expanded_macro));
}
}
}
RoutineType::Function => {
return Ok(trampoline::bounce(eval_node, lexical_env, *body));
}
}
}
return Err(RuntimeError::CannotInvokeNonProcedure(
fnode.val.to_string(),
loc,
));
}
|
use std::{
collections::HashMap,
fs::{self, File},
io::Read,
str::{from_utf8, FromStr},
};
use framework::{app, encode_base64, macros::serde_json::{self, json}, App, Canvas, Ui, Size};
use lsp_types::{
notification::{DidChangeTextDocument, DidOpenTextDocument, Initialized, Notification},
request::{Initialize, Request, SemanticTokensFullRequest, WorkspaceSymbolRequest},
ClientCapabilities, DidChangeTextDocumentParams, DidOpenTextDocumentParams, InitializeParams,
InitializeResult, InitializedParams, MessageActionItemCapabilities, PartialResultParams,
Position, Range, SemanticTokensParams, ShowDocumentClientCapabilities,
ShowMessageRequestClientCapabilities, TextDocumentContentChangeEvent, TextDocumentIdentifier,
TextDocumentItem, Url, VersionedTextDocumentIdentifier, WindowClientCapabilities,
WorkDoneProgressParams, WorkspaceFolder, WorkspaceSymbolParams,
};
use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
struct Data {
state: State,
message_type: HashMap<String, String>,
last_request_id: usize,
messages_by_type: HashMap<String, Vec<String>>,
token_request_to_file: HashMap<String, String>,
open_files: Vec<String>,
size: Size,
y_scroll_offset: f32,
}
#[derive(Copy, Clone, Deserialize, Serialize)]
enum State {
Initializing,
Initialized,
}
struct ProcessSpawner {
state: Data,
process_id: i32,
root_path: String,
}
#[derive(Clone, Deserialize, Serialize)]
pub enum Edit {
Insert(usize, usize, Vec<u8>),
Delete(usize, usize),
}
#[derive(Serialize, Deserialize, Clone)]
struct EditWithPath {
edit: Edit,
path: String,
}
// TODO:
// I need to properly handle versions of tokens and make sure I always use the latest.
// I need to actually update my tokens myself and then get the refresh.
impl ProcessSpawner {
fn parse_message(
&self,
message: &str,
) -> Result<Vec<serde_json::Value>, Box<dyn std::error::Error>> {
let mut results = vec![];
if let Some(start_json_object) = message.find('{') {
let message = &message[start_json_object..];
let deserializer = serde_json::Deserializer::from_str(message);
let iterator: serde_json::StreamDeserializer<
'_,
serde_json::de::StrRead<'_>,
serde_json::Value,
> = deserializer.into_iter::<serde_json::Value>();
for item in iterator {
results.push(item?);
}
}
Ok(results)
}
fn next_request_id(&mut self) -> String {
self.state.last_request_id += 1;
format!("client/{}", self.state.last_request_id)
}
fn request(&mut self, id: String, method: &str, params: &str) -> String {
// construct the request and add the headers including content-length
let body = format!(
"{{\"jsonrpc\":\"{}\",\"id\":\"{}\",\"method\":\"{}\",\"params\":{}}}",
"2.0", id, method, params
);
let content_length = body.len();
let headers = format!("Content-Length: {}\r\n\r\n", content_length);
format!("{}{}", headers, body)
}
fn send_request(&mut self, method: &str, params: &str) -> String {
let id = self.next_request_id();
let request = self.request(id.clone(), method, params);
self.state.message_type.insert(id.clone(), method.to_string());
self.send_message(self.process_id, request);
id
}
fn notification(&self, method: &str, params: &str) -> String {
let body = format!(
"{{\"jsonrpc\":\"{}\",\"method\":\"{}\",\"params\":{}}}",
"2.0", method, params
);
let content_length = body.len();
let headers = format!("Content-Length: {}\r\n\r\n", content_length);
format!("{}{}", headers, body)
}
fn initialize_rust_analyzer(&mut self) {
let process_id = self.start_process(find_rust_analyzer());
self.process_id = process_id;
#[allow(deprecated)]
// Root path is deprecated, but I also need to specify it
let mut initialize_params = InitializeParams {
process_id: Some(self.process_id as u32),
root_path: Some(self.root_path.to_string()),
root_uri: Some(Url::from_str(&format!("file://{}", self.root_path)).unwrap()),
initialization_options: None,
capabilities: ClientCapabilities::default(),
trace: None,
workspace_folders: Some(vec![WorkspaceFolder {
uri: Url::from_str(&format!("file://{}", self.root_path)).unwrap(),
name: "editor2".to_string(),
}]),
client_info: None,
locale: None,
};
initialize_params.capabilities.window = Some(WindowClientCapabilities {
work_done_progress: Some(true),
show_message: Some(ShowMessageRequestClientCapabilities {
message_action_item: Some(MessageActionItemCapabilities {
additional_properties_support: Some(true),
}),
}),
show_document: Some(ShowDocumentClientCapabilities { support: true }),
});
self.send_request(
Initialize::METHOD,
&serde_json::to_string(&initialize_params).unwrap(),
);
let params: <Initialized as Notification>::Params = InitializedParams {};
let request = self.notification(
Initialized::METHOD,
&serde_json::to_string(¶ms).unwrap(),
);
self.send_message(self.process_id, request);
}
fn resolve_workspace_symbols(&mut self) {
let params: <WorkspaceSymbolRequest as Request>::Params = WorkspaceSymbolParams {
partial_result_params: PartialResultParams { partial_result_token: None },
work_done_progress_params: WorkDoneProgressParams { work_done_token: None },
query: "".to_string(),
};
self.send_request(
WorkspaceSymbolRequest::METHOD,
&serde_json::to_string(¶ms).unwrap(),
);
}
fn open_file(&mut self, path: &str) {
// read entire contents
let mut file = File::open(path).unwrap();
let mut contents = String::new();
let file_results = file.read_to_string(&mut contents);
if let Err(err) = file_results {
println!("Error reading file!: {} {}", path, err);
return;
}
let params: <DidOpenTextDocument as Notification>::Params = DidOpenTextDocumentParams {
text_document: TextDocumentItem {
uri: Url::from_str(&format!("file://{}", &path))
.unwrap(),
language_id: "rust".to_string(),
version: 1,
text: contents,
},
};
let notify = self.notification(
DidOpenTextDocument::METHOD,
&serde_json::to_string(¶ms).unwrap(),
);
self.send_message(self.process_id, notify);
}
fn request_tokens(&mut self, path: &str) {
let params: <SemanticTokensFullRequest as Request>::Params = SemanticTokensParams {
text_document: TextDocumentIdentifier {
uri: Url::from_str(&format!("file://{}", path))
.unwrap(),
},
partial_result_params: PartialResultParams::default(),
work_done_progress_params: WorkDoneProgressParams::default(),
};
let token_request = self.send_request(
SemanticTokensFullRequest::METHOD,
&serde_json::to_string(¶ms).unwrap(),
);
self.state.token_request_to_file.insert(token_request, path.to_string());
}
fn update_document_insert(
&mut self,
path: &str,
line: usize,
column: usize,
bytes: Vec<u8>,
) {
let params: <DidChangeTextDocument as Notification>::Params = DidChangeTextDocumentParams {
text_document: VersionedTextDocumentIdentifier {
uri: Url::from_str(&format!("file://{}", path))
.unwrap(),
version: 0,
},
content_changes: vec![TextDocumentContentChangeEvent {
range: Some(Range {
start: Position {
line: line as u32,
character: column as u32,
},
end: Position {
line: line as u32,
character: column as u32,
},
}),
range_length: None,
text: from_utf8(&bytes).unwrap().to_string(),
}],
};
let request = self.notification(
DidChangeTextDocument::METHOD,
&serde_json::to_string(¶ms).unwrap(),
);
self.send_message(self.process_id, request);
}
fn update_document_delete(&mut self, path: &str, line: usize, column: usize) {
let params: <DidChangeTextDocument as Notification>::Params = DidChangeTextDocumentParams {
text_document: VersionedTextDocumentIdentifier {
uri: Url::from_str(&format!("file://{}", path))
.unwrap(),
version: 0,
},
content_changes: vec![TextDocumentContentChangeEvent {
range: Some(Range {
start: Position {
line: line as u32,
character: column as u32,
},
end: Position {
line: line as u32,
character: column as u32 + 1,
},
}),
range_length: None,
text: "".to_string(),
}],
};
let request = self.notification(
DidChangeTextDocument::METHOD,
&serde_json::to_string(¶ms).unwrap(),
);
self.send_message(self.process_id, request);
}
fn initialized(&mut self) {
// TODO: Get list of initial open files
self.state.state = State::Initialized;
self.resolve_workspace_symbols();
for file in self.state.open_files.clone().iter() {
self.request_tokens(file);
}
}
}
#[derive(Clone, Deserialize, Serialize)]
struct OpenFileInfo {
path: String,
}
impl App for ProcessSpawner {
type State = Data;
fn init() -> Self {
let mut me = ProcessSpawner {
state: Data {
state: State::Initializing,
message_type: HashMap::new(),
token_request_to_file: HashMap::new(),
open_files: Vec::new(),
last_request_id: 0,
messages_by_type: HashMap::new(),
size: Size::default(),
y_scroll_offset: 0.0,
},
process_id: 0,
root_path: "/Users/jimmyhmiller/Documents/Code/PlayGround/rust/editor2".to_string(),
};
me.subscribe("text_change");
me.subscribe("lith/open-file");
me.initialize_rust_analyzer();
me
}
fn draw(&mut self) {
let mut canvas = Canvas::new();
let ui = Ui::new();
let ui = ui.pane(
self.state.size,
(0.0, self.state.y_scroll_offset),
ui.list(self.state.messages_by_type.iter(), |ui, item|
ui.container(ui.text(&format!("{}: {}", item.0, item.1.len())))
),
);
ui.draw(&mut canvas);
}
fn on_click(&mut self, _x: f32, _y: f32) {
// self.request_tokens();
self.resolve_workspace_symbols();
}
fn on_key(&mut self, _input: framework::KeyboardInput) {}
fn on_scroll(&mut self, _x: f64, _y: f64) {
self.state.y_scroll_offset += _y as f32;
if self.state.y_scroll_offset > 0.0 {
self.state.y_scroll_offset = 0.0;
}
}
fn on_event(&mut self, kind: String, event: String) {
match kind.as_str() {
"text_change" => {
let edit: EditWithPath = serde_json::from_str(&event).unwrap();
match edit.edit {
Edit::Insert(line, column, bytes) => {
self.update_document_insert(&edit.path, line, column, bytes);
self.request_tokens(&edit.path);
}
Edit::Delete(line, column) => {
self.update_document_delete(&edit.path, line, column);
self.request_tokens(&edit.path);
}
}
}
"lith/open-file" => {
let info: OpenFileInfo = serde_json::from_str(&event).unwrap();
self.state.open_files.push(info.path.clone());
self.open_file(&info.path);
self.request_tokens(&info.path);
}
_ => {
println!("Unknown event: {}", kind);
}
}
}
fn get_state(&self) -> Self::State {
self.state.clone()
}
fn on_process_message(&mut self, _process_id: i32, message: String) {
let messages = message.split("Content-Length");
for message in messages {
match self.parse_message(message) {
Ok(messages) => {
for message in messages {
// let method = message["method"].as_str();
if let Some(id) = message["id"].as_str() {
if let Some(method) = self.state.message_type.get(id) {
if let Some(messages) = self.state.messages_by_type.get_mut(method) {
messages.push(message.to_string());
} else {
self.state.messages_by_type.insert(method.to_string(), vec![message.to_string()]);
}
// TODO: Need to correlate this with file
if method == "textDocument/semanticTokens/full" {
let path = self.state.token_request_to_file.get(id).unwrap();
self.send_event(
"tokens",
encode_base64(&extract_tokens(path.clone(), &message)),
);
}
if method == "workspace/symbol" {
self.send_event("workspace/symbols", message.to_string());
}
if method == "initialize" {
let result = message.get("result").unwrap();
let parsed_message =
serde_json::from_value::<InitializeResult>(result.clone())
.unwrap();
if let Some(token_provider) =
parsed_message.capabilities.semantic_tokens_provider
{
match token_provider {
lsp_types::SemanticTokensServerCapabilities::SemanticTokensOptions(options) => {
self.send_event("token_options", serde_json::to_string(&options.legend).unwrap());
}
lsp_types::SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(options) => {
self.send_event("token_options", serde_json::to_string(&options.semantic_tokens_options.legend).unwrap());
},
}
}
}
}
} else {
// This isn't in response to a message we sent
let method = message["method"].as_str();
if let Some(method) = method {
if method == "$/progress" {
if let Some(100) = message.get("params")
.and_then(|x| x.get("value"))
.and_then(|x| x.get("percentage"))
.and_then(|x| x.as_u64()) {
self.initialized();
}
}
}
}
}
}
Err(err) => {
println!("Error: {}", err);
println!("Message: {}", message);
}
}
}
// println!("Process {} sent message {}", process_id, message);
}
fn set_state(&mut self, state: Self::State) {
println!("Setting state, {:?}", state.size);
self.state.size = state.size;
}
fn on_size_change(&mut self, width: f32, height: f32) {
self.state.size.width = width;
self.state.size.height = height;
}
}
fn extract_tokens(path: String, message: &serde_json::Value) -> Vec<u8> {
let result = &message["result"];
let data = &result["data"];
serde_json::to_string(&json!({
"path": path,
"tokens": data,
})).unwrap().into_bytes()
}
fn find_rust_analyzer() -> String {
let root = "/Users/jimmyhmiller/.vscode/extensions/";
let folder = fs::read_dir(root)
.unwrap()
.map(|res| res.map(|e| e.path()))
.find(|path| {
path.as_ref()
.unwrap()
.file_name()
.unwrap()
.to_str()
.unwrap()
.starts_with("rust-lang.rust-analyzer")
})
.unwrap()
.unwrap();
format!("{}/server/rust-analyzer", folder.to_str().unwrap())
}
app!(ProcessSpawner);
|
use crate::{qjs::Error as JsError, ValueError};
use std::{
error::Error as StdError,
ffi::NulError,
fmt::{Display, Formatter, Result as FmtResult},
io::Error as IoError,
result::Result as StdResult,
str::Utf8Error,
string::FromUtf8Error,
};
pub type Result<T> = StdResult<T, Error>;
#[derive(Debug)]
pub enum Error {
Io(IoError),
Nul(NulError),
Utf8(Utf8Error),
Data(String),
Val(ValueError),
Js(JsError),
App(String),
}
impl StdError for Error {}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
match self {
Error::Io(error) => {
"Input/Output Error: ".fmt(f)?;
error.fmt(f)
}
Error::Nul(_) => "Invalid String".fmt(f),
Error::Utf8(_) => "Invalid Utf8".fmt(f),
Error::Data(error) => {
"Data Error: ".fmt(f)?;
error.fmt(f)
}
Error::Val(error) => {
"Value Error: ".fmt(f)?;
error.fmt(f)
}
Error::Js(error) => {
"JavaScript Error: ".fmt(f)?;
error.fmt(f)
}
Error::App(error) => {
"Application Error: ".fmt(f)?;
error.fmt(f)
}
}
}
}
macro_rules! from_impls {
($($type:ty => $variant:ident $($func:ident)*,)*) => {
$(
impl From<$type> for Error {
fn from(error: $type) -> Self {
Self::$variant(error$(.$func())*)
}
}
)*
};
}
from_impls! {
IoError => Io,
NulError => Nul,
Utf8Error => Utf8,
FromUtf8Error => Utf8 utf8_error,
ValueError => Val,
JsError => Js,
String => App,
&str => App to_string,
}
impl From<Error> for JsError {
fn from(error: Error) -> JsError {
match error {
Error::Io(error) => JsError::Io(error),
Error::Nul(error) => JsError::InvalidString(error),
Error::Utf8(error) => JsError::Utf8(error),
Error::Val(error) => JsError::Exception {
message: error.to_string(),
file: "".into(),
line: 0,
stack: "".into(),
},
Error::Js(error) => error,
Error::Data(error) | Error::App(error) => JsError::Exception {
message: error,
file: "".into(),
line: 0,
stack: "".into(),
},
}
}
}
impl From<serde_json::Error> for Error {
fn from(error: serde_json::Error) -> Self {
Self::Data(error.to_string())
}
}
#[cfg(feature = "yaml")]
impl From<serde_yaml::Error> for Error {
fn from(error: serde_yaml::Error) -> Self {
Self::Data(error.to_string())
}
}
#[cfg(feature = "toml")]
impl From<toml::de::Error> for Error {
fn from(error: toml::de::Error) -> Self {
Self::Data(error.to_string())
}
}
#[cfg(feature = "toml")]
impl From<toml::ser::Error> for Error {
fn from(error: toml::ser::Error) -> Self {
Self::Data(error.to_string())
}
}
#[cfg(feature = "watch")]
impl From<notify::Error> for Error {
fn from(error: notify::Error) -> Self {
use notify::ErrorKind::*;
match error.kind {
Generic(error) => Self::App(format!("Notifier error: {}", error)),
Io(error) => Self::Io(error),
PathNotFound => Self::App(format!(
"Notifier path does not exist: {}",
error
.paths
.into_iter()
.map(|path| path.display().to_string())
.collect::<Vec<_>>()
.join(" ")
)),
WatchNotFound => Self::App("Notifier watch does not exist.".into()),
InvalidConfig(config) => {
Self::App(format!("Notifier config is not a valid: {:?}", config))
}
}
}
}
|
use crate::error::*;
use std::cmp::Ordering;
use std::path::{Path, PathBuf};
use std::convert::TryFrom;
use crate::unity::InstalledComponents;
use crate::unity::Version;
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct AppInfo {
pub c_f_bundle_version: String,
pub unity_build_number: String,
}
pub trait UnityInstallation: Eq + Ord {
fn path(&self) -> &PathBuf;
fn version(&self) -> &Version;
#[cfg(target_os = "windows")]
fn location(&self) -> PathBuf {
self.path().join("Editor\\Unity.exe")
}
#[cfg(target_os = "macos")]
fn location(&self) -> PathBuf {
self.path().join("Unity.app")
}
#[cfg(target_os = "linux")]
fn location(&self) -> PathBuf {
self.path().join("Editor/Unity")
}
#[cfg(any(target_os = "windows", target_os = "linux"))]
fn exec_path(&self) -> PathBuf {
self.location()
}
#[cfg(target_os = "macos")]
fn exec_path(&self) -> PathBuf {
self.path().join("Unity.app/Contents/MacOS/Unity")
}
}
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct Installation {
version: Version,
path: PathBuf,
}
impl UnityInstallation for Installation {
fn path(&self) -> &PathBuf {
&self.path
}
fn version(&self) -> &Version {
&self.version
}
}
impl Ord for Installation {
fn cmp(&self, other: &Installation) -> Ordering {
self.version.cmp(&other.version)
}
}
impl PartialOrd for Installation {
fn partial_cmp(&self, other: &Installation) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[cfg(target_os = "macos")]
fn adjust_path(path:&Path) -> Option<&Path> {
// if the path points to a file it could be the executable
if path.is_file() {
if let Some(name) = path.file_name() {
if name == "Unity" {
path.parent()
.and_then(|path| path.parent())
.and_then(|path| path.parent())
.and_then(|path| path.parent())
} else {
None
}
} else {
None
}
} else {
None
}
}
#[cfg(target_os = "windows")]
fn adjust_path(path:&Path) -> Option<&Path> {
if path.is_file() {
if let Some(name) = path.file_name() {
if name == "Unity.exe" {
path.parent().and_then(|path| path.parent())
} else {
None
}
} else {
None
}
} else {
None
}
}
#[cfg(target_os = "linux")]
fn adjust_path(path:&Path) -> Option<&Path> {
if path.is_file() {
if let Some(name) = path.file_name() {
if name == "Unity" {
path.parent().and_then(|path| path.parent())
} else {
None
}
} else {
None
}
} else {
None
}
}
#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
fn adjust_path(path:&Path) -> Option<&Path> {
None
}
impl Installation {
pub fn new<P: AsRef<Path>>(path: P) -> Result<Installation> {
let path = path.as_ref();
let path = if let Some(p) = adjust_path(path) {
p
} else {
path
};
Version::try_from(path)
.map(|version| Installation {
version,
path: path.to_path_buf(),
})
.map_err(|err| err.into())
}
//TODO remove clone()
pub fn installed_components(&self) -> InstalledComponents {
InstalledComponents::new(self.clone())
}
pub fn version(&self) -> &Version {
&self.version
}
pub fn version_owned(&self) -> Version {
self.version.to_owned()
}
pub fn path(&self) -> &PathBuf {
&self.path
}
#[cfg(target_os = "windows")]
pub fn location(&self) -> PathBuf {
self.path().join("Editor\\Unity.exe")
}
#[cfg(target_os = "macos")]
pub fn location(&self) -> PathBuf {
self.path().join("Unity.app")
}
#[cfg(target_os = "linux")]
pub fn location(&self) -> PathBuf {
self.path().join("Editor/Unity")
}
#[cfg(any(target_os = "windows", target_os = "linux"))]
pub fn exec_path(&self) -> PathBuf {
self.location()
}
#[cfg(target_os = "macos")]
pub fn exec_path(&self) -> PathBuf {
self.path().join("Unity.app/Contents/MacOS/Unity")
}
}
use std::fmt;
impl fmt::Display for Installation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.version, self.path.display())
}
}
impl From<crate::unity::hub::editors::EditorInstallation> for Installation {
fn from(editor: crate::unity::hub::editors::EditorInstallation) -> Self {
Installation {
version: editor.version().to_owned(),
path: editor.location().to_path_buf(),
}
}
}
#[cfg(all(test, target_os = "macos"))]
mod tests {
use super::*;
use plist::serde::serialize_to_xml;
use std::fs;
use std::fs::File;
use std::path::Path;
use std::str::FromStr;
use tempfile::Builder;
fn create_unity_installation(base_dir: &PathBuf, version: &str) -> PathBuf {
let path = base_dir.join("Unity");
let mut dir_builder = fs::DirBuilder::new();
dir_builder.recursive(true);
dir_builder.create(&path).unwrap();
let info_plist_path = path.join("Unity.app/Contents/Info.plist");
let exec_path = path.join("Unity.app/Contents/MacOS/Unity");
dir_builder
.create(info_plist_path.parent().unwrap())
.unwrap();
dir_builder
.create(exec_path.parent().unwrap())
.unwrap();
let info = AppInfo {
c_f_bundle_version: String::from_str(version).unwrap(),
unity_build_number: String::from_str("ssdsdsdd").unwrap(),
};
let file = File::create(info_plist_path).unwrap();
File::create(exec_path).unwrap();
serialize_to_xml(file, &info).unwrap();
path
}
macro_rules! prepare_unity_installation {
($version:expr) => {{
let test_dir = Builder::new()
.prefix("installation")
.rand_bytes(5)
.tempdir()
.unwrap();
let unity_path = create_unity_installation(&test_dir.path().to_path_buf(), $version);
(test_dir, unity_path)
}};
}
#[test]
fn create_installtion_from_path() {
let (_t, path) = prepare_unity_installation!("2017.1.2f5");
let subject = Installation::new(path).unwrap();
assert_eq!(subject.version.to_string(), "2017.1.2f5");
}
#[test]
fn create_installation_from_executable_path() {
let(_t, path) = prepare_unity_installation!("2017.1.2f5");
let installation = Installation::new(path).unwrap();
let subject = Installation::new(installation.exec_path()).unwrap();
assert_eq!(subject.version.to_string(), "2017.1.2f5");
}
proptest! {
#[test]
fn doesnt_crash(ref s in "\\PC*") {
let _ = Installation::new(Path::new(s).to_path_buf()).is_ok();
}
#[test]
fn parses_all_valid_versions(ref s in r"[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4}[fpb][0-9]{1,4}") {
let (_t, path) = prepare_unity_installation!(s);
Installation::new(path).unwrap();
}
}
}
|
use core::{marker::PhantomData, ops::Index};
use hashbrown::hash_map::HashMap;
use slab::Slab;
use necsim_core::{
cogs::{Backup, Habitat, OriginSampler},
landscape::IndexedLocation,
lineage::Lineage,
};
use crate::cogs::lineage_reference::in_memory::InMemoryLineageReference;
mod store;
#[allow(clippy::module_name_repetitions)]
#[derive(Debug)]
pub struct ClassicalLineageStore<H: Habitat> {
lineages_store: Slab<Lineage>,
indexed_location_to_lineage_reference: HashMap<IndexedLocation, InMemoryLineageReference>,
_marker: PhantomData<H>,
}
impl<H: Habitat> Index<InMemoryLineageReference> for ClassicalLineageStore<H> {
type Output = Lineage;
#[must_use]
#[debug_requires(
self.lineages_store.contains(reference.into()),
"lineage reference is valid in the lineage store"
)]
fn index(&self, reference: InMemoryLineageReference) -> &Self::Output {
&self.lineages_store[usize::from(reference)]
}
}
impl<'h, H: 'h + Habitat> ClassicalLineageStore<H> {
#[must_use]
pub fn new<O: OriginSampler<'h, Habitat = H>>(mut origin_sampler: O) -> Self {
#[allow(clippy::cast_possible_truncation)]
let lineages_amount_hint = origin_sampler.full_upper_bound_size_hint() as usize;
let mut lineages_store = Slab::with_capacity(lineages_amount_hint);
let mut indexed_location_to_lineage_reference =
HashMap::with_capacity(lineages_amount_hint);
while let Some(indexed_location) = origin_sampler.next() {
let lineage = Lineage::new(indexed_location.clone(), origin_sampler.habitat());
let local_reference = InMemoryLineageReference::from(lineages_store.insert(lineage));
indexed_location_to_lineage_reference.insert(indexed_location, local_reference);
}
lineages_store.shrink_to_fit();
Self {
lineages_store,
indexed_location_to_lineage_reference,
_marker: PhantomData::<H>,
}
}
}
#[contract_trait]
impl<H: Habitat> Backup for ClassicalLineageStore<H> {
unsafe fn backup_unchecked(&self) -> Self {
Self {
lineages_store: self.lineages_store.clone(),
indexed_location_to_lineage_reference: self
.indexed_location_to_lineage_reference
.clone(),
_marker: PhantomData::<H>,
}
}
}
|
use vendored_sha3::{Digest, Sha3_384};
use super::Hash;
/// SHA3_384 alias Sha3_384 and implements Hash.
pub type SHA3_384 = Sha3_384;
/// The blocksize of SHA3-384 in bytes.
pub const BLOCK_SIZE384: usize = 104;
/// The size of a SHA3-384 checksum in bytes.
pub const SIZE384: usize = 48;
impl Hash for SHA3_384 {
fn size() -> usize {
Sha3_384::output_size()
}
fn block_size() -> usize {
BLOCK_SIZE384
}
fn reset(&mut self) {
Digest::reset(self);
}
fn sum(&mut self) -> Vec<u8> {
let d = self.clone().result();
let mut out = Vec::with_capacity(d.as_slice().len());
out.extend_from_slice(d.as_slice());
out
}
}
/// new384 creates a new SHA3-384 hash. Its generic security strength is 384 bits against preimage
/// attacks, and 192 bits against collision attacks.
pub fn new384() -> SHA3_384 {
Digest::new()
}
/// sum384 returns the SHA3-384 digest of the data.
pub fn sum384(b: &[u8]) -> [u8; SIZE384] {
let d = Sha3_384::digest(b);
let mut out = [0u8; SIZE384];
(&mut out[..]).copy_from_slice(d.as_slice());
out
}
|
use super::*;
use crate::libs::random_id::U128Id;
impl Renderer {
pub fn reset_canvas_size(canvas: &web_sys::HtmlCanvasElement, dpr: f64) -> [f64; 2] {
let bb = canvas.get_bounding_client_rect();
let w = bb.width() * dpr;
let h = bb.height() * dpr;
canvas.set_width(w as u32);
canvas.set_height(h as u32);
crate::debug::log_2(w, h);
[w, h]
}
pub fn resize_renderbuffer(
gl: &WebGlRenderingContext,
buf: &web_sys::WebGlRenderbuffer,
width: i32,
height: i32,
) {
gl.bind_renderbuffer(web_sys::WebGlRenderingContext::RENDERBUFFER, Some(&buf));
gl.renderbuffer_storage(
web_sys::WebGlRenderingContext::RENDERBUFFER,
web_sys::WebGlRenderingContext::DEPTH_COMPONENT16,
width,
height,
);
}
pub fn resize_texturebuffer(
gl: &WebGlRenderingContext,
buf: &web_sys::WebGlTexture,
tex_id: &U128Id,
tex_table: &mut tex_table::TexTable,
width: i32,
height: i32,
) {
let (_, tex_flag) = tex_table.use_custom(tex_id);
gl.active_texture(tex_flag);
gl.bind_texture(web_sys::WebGlRenderingContext::TEXTURE_2D, Some(&buf));
let _ = gl
.tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
web_sys::WebGlRenderingContext::TEXTURE_2D,
0,
web_sys::WebGlRenderingContext::RGBA as i32,
width,
height,
0,
web_sys::WebGlRenderingContext::RGBA,
web_sys::WebGlRenderingContext::UNSIGNED_BYTE,
None,
);
}
pub fn create_screen_texture(
gl: &WebGlRenderingContext,
tex_table: &mut tex_table::TexTable,
width: i32,
height: i32,
filter: Option<u32>,
) -> (web_sys::WebGlTexture, U128Id) {
let tex_buf = gl.create_texture().unwrap();
let tex_id = U128Id::new();
let (_, tex_flag) = tex_table.use_custom(&tex_id);
let filter = filter.unwrap_or(web_sys::WebGlRenderingContext::LINEAR);
gl.active_texture(tex_flag);
gl.bind_texture(web_sys::WebGlRenderingContext::TEXTURE_2D, Some(&tex_buf));
gl.tex_parameteri(
web_sys::WebGlRenderingContext::TEXTURE_2D,
web_sys::WebGlRenderingContext::TEXTURE_MIN_FILTER,
filter as i32,
);
gl.tex_parameteri(
web_sys::WebGlRenderingContext::TEXTURE_2D,
web_sys::WebGlRenderingContext::TEXTURE_MAG_FILTER,
filter as i32,
);
gl.tex_parameteri(
web_sys::WebGlRenderingContext::TEXTURE_2D,
web_sys::WebGlRenderingContext::TEXTURE_WRAP_S,
web_sys::WebGlRenderingContext::CLAMP_TO_EDGE as i32,
);
gl.tex_parameteri(
web_sys::WebGlRenderingContext::TEXTURE_2D,
web_sys::WebGlRenderingContext::TEXTURE_WRAP_T,
web_sys::WebGlRenderingContext::CLAMP_TO_EDGE as i32,
);
Self::resize_texturebuffer(&gl, &tex_buf, &tex_id, tex_table, width, height);
(tex_buf, tex_id)
}
}
|
#[doc = "Register `AHB1RSTR` reader"]
pub type R = crate::R<AHB1RSTR_SPEC>;
#[doc = "Register `AHB1RSTR` writer"]
pub type W = crate::W<AHB1RSTR_SPEC>;
#[doc = "Field `GPDMA1RST` reader - GPDMA1 block reset Set and reset by software."]
pub type GPDMA1RST_R = crate::BitReader;
#[doc = "Field `GPDMA1RST` writer - GPDMA1 block reset Set and reset by software."]
pub type GPDMA1RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPDMA2RST` reader - GPDMA2 block reset Set and reset by software."]
pub type GPDMA2RST_R = crate::BitReader;
#[doc = "Field `GPDMA2RST` writer - GPDMA2 block reset Set and reset by software."]
pub type GPDMA2RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CRCRST` reader - CRC block reset Set and reset by software."]
pub type CRCRST_R = crate::BitReader;
#[doc = "Field `CRCRST` writer - CRC block reset Set and reset by software."]
pub type CRCRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CORDICRST` reader - CORDIC block reset Set and reset by software."]
pub type CORDICRST_R = crate::BitReader;
#[doc = "Field `CORDICRST` writer - CORDIC block reset Set and reset by software."]
pub type CORDICRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FMACRST` reader - FMAC block reset Set and reset by software."]
pub type FMACRST_R = crate::BitReader;
#[doc = "Field `FMACRST` writer - FMAC block reset Set and reset by software."]
pub type FMACRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RAMCFGRST` reader - RAMCFG block reset Set and reset by software."]
pub type RAMCFGRST_R = crate::BitReader;
#[doc = "Field `RAMCFGRST` writer - RAMCFG block reset Set and reset by software."]
pub type RAMCFGRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TZSC1RST` reader - TZSC1 reset Set and reset by software"]
pub type TZSC1RST_R = crate::BitReader;
#[doc = "Field `TZSC1RST` writer - TZSC1 reset Set and reset by software"]
pub type TZSC1RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - GPDMA1 block reset Set and reset by software."]
#[inline(always)]
pub fn gpdma1rst(&self) -> GPDMA1RST_R {
GPDMA1RST_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - GPDMA2 block reset Set and reset by software."]
#[inline(always)]
pub fn gpdma2rst(&self) -> GPDMA2RST_R {
GPDMA2RST_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 12 - CRC block reset Set and reset by software."]
#[inline(always)]
pub fn crcrst(&self) -> CRCRST_R {
CRCRST_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 14 - CORDIC block reset Set and reset by software."]
#[inline(always)]
pub fn cordicrst(&self) -> CORDICRST_R {
CORDICRST_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - FMAC block reset Set and reset by software."]
#[inline(always)]
pub fn fmacrst(&self) -> FMACRST_R {
FMACRST_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 17 - RAMCFG block reset Set and reset by software."]
#[inline(always)]
pub fn ramcfgrst(&self) -> RAMCFGRST_R {
RAMCFGRST_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 24 - TZSC1 reset Set and reset by software"]
#[inline(always)]
pub fn tzsc1rst(&self) -> TZSC1RST_R {
TZSC1RST_R::new(((self.bits >> 24) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - GPDMA1 block reset Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn gpdma1rst(&mut self) -> GPDMA1RST_W<AHB1RSTR_SPEC, 0> {
GPDMA1RST_W::new(self)
}
#[doc = "Bit 1 - GPDMA2 block reset Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn gpdma2rst(&mut self) -> GPDMA2RST_W<AHB1RSTR_SPEC, 1> {
GPDMA2RST_W::new(self)
}
#[doc = "Bit 12 - CRC block reset Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn crcrst(&mut self) -> CRCRST_W<AHB1RSTR_SPEC, 12> {
CRCRST_W::new(self)
}
#[doc = "Bit 14 - CORDIC block reset Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn cordicrst(&mut self) -> CORDICRST_W<AHB1RSTR_SPEC, 14> {
CORDICRST_W::new(self)
}
#[doc = "Bit 15 - FMAC block reset Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn fmacrst(&mut self) -> FMACRST_W<AHB1RSTR_SPEC, 15> {
FMACRST_W::new(self)
}
#[doc = "Bit 17 - RAMCFG block reset Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn ramcfgrst(&mut self) -> RAMCFGRST_W<AHB1RSTR_SPEC, 17> {
RAMCFGRST_W::new(self)
}
#[doc = "Bit 24 - TZSC1 reset Set and reset by software"]
#[inline(always)]
#[must_use]
pub fn tzsc1rst(&mut self) -> TZSC1RST_W<AHB1RSTR_SPEC, 24> {
TZSC1RST_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 = "RCC AHB1 reset register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb1rstr::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 [`ahb1rstr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct AHB1RSTR_SPEC;
impl crate::RegisterSpec for AHB1RSTR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ahb1rstr::R`](R) reader structure"]
impl crate::Readable for AHB1RSTR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ahb1rstr::W`](W) writer structure"]
impl crate::Writable for AHB1RSTR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets AHB1RSTR to value 0"]
impl crate::Resettable for AHB1RSTR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
// Copyright 2020-Present (c) Raja Lehtihet & Wael El Oraiby
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
use crate::renderer::*;
use rs_gles2::bindings::*;
use rs_ctypes::*;
use rs_alloc::*;
use rs_math3d::*;
pub struct GLProgram {
prog_id : GLuint,
attribs : Vec<(VertexAttributeDesc, GLuint)>,
uniforms : Vec<(UniformDesc, GLuint)>,
}
impl GLProgram {
fn load_shader(src: &str, ty: GLenum) -> Option<GLuint> {
unsafe {
let shader = glCreateShader(ty);
if shader == 0 {
return None
}
glShaderSource(shader, 1, &(src.as_ptr() as *const i8), core::ptr::null());
glCompileShader(shader);
let mut compiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &mut compiled);
if compiled == 0 {
let mut info_len = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &mut info_len);
if info_len > 1 {
let sptr = alloc_array::<u8>(info_len as usize);
glGetShaderInfoLog(shader, info_len as GLsizei, core::ptr::null_mut(), sptr as *mut GLchar);
libc::puts(sptr as *const i8);
free_array(sptr, info_len as usize, info_len as usize);
}
glDeleteShader(shader);
return None
}
Some(shader)
}
}
pub fn load_program(vs: &str, fs: &str, attribs: &[VertexAttributeDesc], uniforms: &[UniformDesc]) -> Option<Box<dyn Program>> {
unsafe {
let program_object = glCreateProgram();
if program_object == 0 {
return None
}
let vertex_shader = Self::load_shader(vs, GL_VERTEX_SHADER);
let fragment_shader = Self::load_shader(fs, GL_FRAGMENT_SHADER);
match (vertex_shader, fragment_shader) {
(None, None) => (),
(None, Some(f)) => glDeleteShader(f),
(Some(v), None) => glDeleteShader(v),
(Some(v), Some(f)) => {
glAttachShader(program_object, v);
glAttachShader(program_object, f);
glLinkProgram(program_object);
let mut linked = 0;
glGetProgramiv(program_object, GL_LINK_STATUS, &mut linked);
if linked == 0 {
let mut info_len = 0;
glGetProgramiv(program_object, GL_INFO_LOG_LENGTH, &mut info_len);
if info_len > 1 {
let sptr = alloc_array::<u8>(info_len as usize);
glGetProgramInfoLog(program_object, info_len as GLsizei, core::ptr::null_mut(), sptr as *mut GLchar);
libc::puts(sptr as *const i8);
free_array(sptr, info_len as usize, info_len as usize);
}
glDeleteProgram(program_object);
return None
}
// done with the shaders
glDetachShader(program_object, v);
glDetachShader(program_object, f);
glDeleteShader(f);
glDeleteShader(v);
}
}
let mut prg_attribs = Vec::new();
for a in attribs {
let mut s = String::from(a.name().as_str());
s.push('\0' as u8);
let au = glGetAttribLocation(program_object, s.as_bytes().as_ptr() as *const GLchar) as GLuint;
prg_attribs.push((a.clone(), au));
}
let mut prg_uniforms = Vec::new();
for u in uniforms {
let mut s = String::from(u.name());
s.push('\0' as u8);
let au = glGetUniformLocation(program_object, s.as_bytes().as_ptr() as *const GLchar) as GLuint;
prg_uniforms.push((u.clone(), au));
}
let s = Box::new(Self { prog_id: program_object, attribs: prg_attribs, uniforms: prg_uniforms });
Some(Box::from_raw(Box::into_raw(s) as *mut dyn Program))
}
}
}
impl Drop for GLProgram {
fn drop(&mut self) {
unsafe { glDeleteProgram(self.prog_id) };
}
}
impl Program for GLProgram {
fn attributes(&self) -> &[VertexAttributeDesc] { &[] }
fn uniforms(&self) -> &[UniformDesc] { &[] }
}
pub struct StaticVertexBuffer {
buff_id : GLuint,
buff_type : GLenum,
size : usize,
stride : usize,
}
impl StaticVertexBuffer {
unsafe fn new_unsafe(stride: usize, buff_data: *const u8, buff_size: usize) -> Self {
let mut buff = 0;
glGenBuffers(1, &mut buff);
glBindBuffer(GL_ARRAY_BUFFER, buff);
glBufferData(GL_ARRAY_BUFFER, buff_size as GLsizeiptr, buff_data as *const rs_ctypes::c_void, GL_STATIC_DRAW);
Self {
stride : stride,
buff_id : buff,
buff_type : GL_STATIC_DRAW,
size : buff_size
}
}
pub fn new<T>(data: &[T]) -> Self {
let s = data.len() * ::core::mem::size_of::<T>();
unsafe { Self::new_unsafe(::core::mem::size_of::<T>(), data.as_ptr() as *const u8, s) }
}
}
impl Drop for StaticVertexBuffer {
fn drop(&mut self) {
unsafe { glDeleteBuffers(1, &self.buff_id as *const GLuint) }
}
}
enum IndexType {
U16,
U32,
}
pub trait IBData {
fn index_type() -> IndexType;
}
impl IBData for u16 {
fn index_type() -> IndexType { IndexType::U16 }
}
impl IBData for u32 {
fn index_type() -> IndexType { IndexType::U32 }
}
pub struct StaticIndexBuffer {
buff_id : GLuint,
buff_type : GLenum,
size : usize,
index_type : IndexType,
}
impl StaticIndexBuffer {
unsafe fn new_unsafe(index_type: IndexType, buff_data: *const u8, buff_size: usize) -> Self {
let mut buff = 0;
glGenBuffers(1, &mut buff);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buff);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, buff_size as GLsizeiptr, buff_data as *const rs_ctypes::c_void, GL_STATIC_DRAW);
Self {
index_type : index_type,
buff_id : buff,
buff_type : GL_STATIC_DRAW,
size : buff_size
}
}
pub fn new<T : IBData>(data: &[T]) -> Self {
let e_size =
match T::index_type() {
IndexType::U16 => 2,
IndexType::U32 => 4,
};
let s = data.len() * e_size;
unsafe { Self::new_unsafe(T::index_type(), data.as_ptr() as *const u8, s) }
}
}
impl Drop for StaticIndexBuffer {
fn drop(&mut self) {
unsafe { glDeleteBuffers(1, &self.buff_id as *const GLuint) }
}
}
trait GLUniformBlock {
fn setup(&self);
}
trait GLVertexBuffer {
fn buff_id(&self) -> GLuint;
}
trait GLIndexBuffer {
fn buff_id(&self) -> GLuint;
fn count(&self) -> GLsizei;
fn index_type(&self) -> GLenum;
}
impl GLVertexBuffer for StaticVertexBuffer {
fn buff_id(&self) -> GLuint { self.buff_id }
}
impl GLIndexBuffer for StaticIndexBuffer {
fn buff_id(&self) -> GLuint { self.buff_id }
fn count(&self) -> GLsizei {
match self.index_type {
IndexType::U16 => (self.size / 2) as GLsizei,
IndexType::U32 => (self.size / 4) as GLsizei,
}
}
fn index_type(&self) -> GLenum {
match self.index_type {
IndexType::U16 => GL_UNSIGNED_SHORT,
IndexType::U32 => GL_UNSIGNED_INT,
}
}
}
trait GLVertexFormat {
fn gl_elem_count(&self) -> GLuint;
fn gl_elem_type(&self) -> GLenum;
fn gl_is_normalized(&self) -> GLboolean;
}
impl GLVertexFormat for VertexFormat {
fn gl_elem_count(&self) -> GLuint {
match self {
VertexFormat::Byte => 1,
VertexFormat::Byte2 => 2,
VertexFormat::Byte3 => 3,
VertexFormat::Byte4 => 4,
VertexFormat::SByte => 1,
VertexFormat::SByte2 => 2,
VertexFormat::SByte3 => 3,
VertexFormat::SByte4 => 4,
VertexFormat::Int => 1,
VertexFormat::Int2 => 2,
VertexFormat::Int3 => 3,
VertexFormat::Int4 => 4,
VertexFormat::Float => 1,
VertexFormat::Float2 => 2,
VertexFormat::Float3 => 3,
VertexFormat::Float4 => 4,
}
}
fn gl_elem_type(&self) -> GLenum {
match self {
VertexFormat::Byte => GL_UNSIGNED_BYTE,
VertexFormat::Byte2 => GL_UNSIGNED_BYTE,
VertexFormat::Byte3 => GL_UNSIGNED_BYTE,
VertexFormat::Byte4 => GL_UNSIGNED_BYTE,
VertexFormat::SByte => GL_BYTE,
VertexFormat::SByte2 => GL_BYTE,
VertexFormat::SByte3 => GL_BYTE,
VertexFormat::SByte4 => GL_BYTE,
VertexFormat::Int => GL_INT,
VertexFormat::Int2 => GL_INT,
VertexFormat::Int3 => GL_INT,
VertexFormat::Int4 => GL_INT,
VertexFormat::Float => GL_FLOAT,
VertexFormat::Float2 => GL_FLOAT,
VertexFormat::Float3 => GL_FLOAT,
VertexFormat::Float4 => GL_FLOAT,
}
}
fn gl_is_normalized(&self) -> GLboolean {
let r = match self {
VertexFormat::Byte => true,
VertexFormat::Byte2 => true,
VertexFormat::Byte3 => true,
VertexFormat::Byte4 => true,
VertexFormat::SByte => true,
VertexFormat::SByte2 => true,
VertexFormat::SByte3 => true,
VertexFormat::SByte4 => true,
VertexFormat::Int => false,
VertexFormat::Int2 => false,
VertexFormat::Int3 => false,
VertexFormat::Int4 => false,
VertexFormat::Float => false,
VertexFormat::Float2 => false,
VertexFormat::Float3 => false,
VertexFormat::Float4 => false,
};
r as GLboolean
}
}
fn uniform_ptr_to_slice<'a, T>(ptr: *const c_void, offset: usize, count: usize) -> &'a [T] {
let cptr = ptr as *const u8;
let _cptr = unsafe { cptr.offset(offset as isize) };
let tptr = _cptr as *const T;
unsafe { core::slice::from_raw_parts(tptr, count) }
}
fn setup_uniforms(uniforms: *const c_void, data_desc_layout: &[UniformDataDesc], prg_desc_layout: &[(UniformDesc, GLuint)]) {
unsafe {
for i in 0..data_desc_layout.len() {
let offset = data_desc_layout[i].offset();
let location = prg_desc_layout[i].1 as GLint;
match &data_desc_layout[i].desc().format() {
UniformDataType::Int => { let s : &[i32] = uniform_ptr_to_slice(uniforms, offset, 1); glUniform1iv(location, 1, s.as_ptr()); },
UniformDataType::Int2 => { let s : &[i32] = uniform_ptr_to_slice(uniforms, offset, 2); glUniform2iv(location, 1, s.as_ptr()); },
UniformDataType::Int3 => { let s : &[i32] = uniform_ptr_to_slice(uniforms, offset, 3); glUniform3iv(location, 1, s.as_ptr()); },
UniformDataType::Int4 => { let s : &[i32] = uniform_ptr_to_slice(uniforms, offset, 4); glUniform4iv(location, 1, s.as_ptr()); },
UniformDataType::Float => { let s : &[f32] = uniform_ptr_to_slice(uniforms, offset, 1); glUniform1fv(location, 1, s.as_ptr()); },
UniformDataType::Float2 => { let s : &[f32] = uniform_ptr_to_slice(uniforms, offset, 2); glUniform2fv(location, 1, s.as_ptr()); },
UniformDataType::Float3 => { let s : &[f32] = uniform_ptr_to_slice(uniforms, offset, 3); glUniform3fv(location, 1, s.as_ptr()); },
UniformDataType::Float4 => { let s : &[f32] = uniform_ptr_to_slice(uniforms, offset, 4); glUniform4fv(location, 1, s.as_ptr()); },
UniformDataType::Float2x2 => { let s : &[f32] = uniform_ptr_to_slice(uniforms, offset, 4); glUniformMatrix2fv(location, 1, false as GLboolean, s.as_ptr()); },
UniformDataType::Float3x3 => { let s : &[f32] = uniform_ptr_to_slice(uniforms, offset, 9); glUniformMatrix3fv(location, 1, false as GLboolean, s.as_ptr()); },
UniformDataType::Float4x4 => { let s : &[f32] = uniform_ptr_to_slice(uniforms, offset, 16); glUniformMatrix4fv(location, 1, false as GLboolean, s.as_ptr()); },
}
}
}
}
fn draw_raw(prg: &GLProgram, buff: &StaticVertexBuffer, uniforms: *const c_void, data_desc_layout: &[UniformDataDesc]) {
unsafe {
glUseProgram(prg.prog_id);
glBindBuffer(GL_ARRAY_BUFFER, buff.buff_id());
for (a, l) in prg.attribs.iter() {
glVertexAttribPointer(*l, a.format().gl_elem_count() as GLint, a.format().gl_elem_type(), a.format().gl_is_normalized(), buff.stride as GLint, a.offset() as *const c_void);
glEnableVertexAttribArray(*l);
}
setup_uniforms(uniforms, data_desc_layout, prg.uniforms.as_slice());
glDrawArrays(GL_TRIANGLES, 0, (buff.size / buff.stride) as GLint);
for (_, l) in prg.attribs.iter() {
glDisableVertexAttribArray(*l);
}
}
}
pub fn draw<T: UniformBlock>(prg: &Box<dyn Program>, buff: &StaticVertexBuffer, uniforms: &T) {
let gl_prog = unsafe { &*(prg.as_ref() as *const dyn Program as *const GLProgram) };
let u_ptr = uniforms as *const T as *const c_void;
draw_raw(gl_prog, buff, u_ptr, T::descriptors().as_slice());
}
fn draw_indexed_raw(prg: &GLProgram, vb: &StaticVertexBuffer, ib: &StaticIndexBuffer, uniforms: *const c_void, data_desc_layout: &[UniformDataDesc]) {
unsafe {
glUseProgram(prg.prog_id);
glBindBuffer(GL_ARRAY_BUFFER, vb.buff_id());
for (a, l) in prg.attribs.iter() {
glVertexAttribPointer(*l, a.format().gl_elem_count() as GLint, a.format().gl_elem_type(), a.format().gl_is_normalized(), vb.stride as GLint, a.offset() as *const c_void);
glEnableVertexAttribArray(*l);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.buff_id);
setup_uniforms(uniforms, data_desc_layout, prg.uniforms.as_slice());
glDrawElements(GL_TRIANGLES, ib.count(), ib.index_type(), core::ptr::null() as *const rs_ctypes::c_void);
for (_, l) in prg.attribs.iter() {
glDisableVertexAttribArray(*l);
}
}
}
pub fn draw_indexed<T: UniformBlock>(prg: &Box<dyn Program>, vb: &StaticVertexBuffer, ib: &StaticIndexBuffer, uniforms: &T) {
let gl_prog = unsafe { &*(prg.as_ref() as *const dyn Program as *const GLProgram) };
let u_ptr = uniforms as *const T as *const c_void;
draw_indexed_raw(gl_prog, vb, ib, u_ptr, T::descriptors().as_slice());
} |
use chore::*;
use regex::Regex;
#[test]
fn general() -> Result<()> {
let ansii_color = Regex::new("\x1b\\[[0-9;]*m").unwrap();
for (args, tasks, expect) in &[
(
vec!["list"],
concat!(
"(M) 2001-02-03 @home +chore add tests\n",
"(Z) foo | bar\n",
"add task due:2002-03-04T05:06:07\n",
"x 2001-02-03 (H) 2001-01-02 @work issue:123\n",
),
concat!(
"1 (M) 2001-02-03 @home +chore add tests\n",
"2 (Z) foo | bar\n",
"3 add task due:2002-03-04T05:06:07\n",
"4 x 2001-02-03 (H) 2001-01-02 @work issue:123\n",
),
),
(
vec!["modify", "pri:A"],
concat!(
"(M) 2001-02-03 @home +chore add tests\n",
),
concat!(
"DEL (M) 2001-02-03 @home +chore add tests\n",
"ADD (A) 2001-02-03 @home +chore add tests\n",
),
),
(
vec!["delete"],
concat!(
"(M) 2001-02-03 @home +chore add tests\n",
),
concat!(
"DEL (M) 2001-02-03 @home +chore add tests\n",
),
),
] {
let config = Config {
now: chrono::NaiveDate::from_ymd(2001, 2, 3).and_hms(4, 5, 6),
args: args.iter().map(|s| s.to_string()).collect(),
tasks: Some(tasks.to_string()),
date_keys: Some("due:\nscheduled:\nwait:\nuntil:\n".to_owned()),
print_color: true,
..Default::default()
};
match chore::run(config)? {
Output::JustPrint { stdout } => {
let stdout = ansii_color.split(&stdout).collect::<Vec<_>>().join("");
assert_eq!(&stdout, expect)
}
Output::WriteFiles { stdout, .. } => {
let stdout = ansii_color.split(&stdout).collect::<Vec<_>>().join("");
assert_eq!(&stdout, expect)
}
}
}
Ok(())
}
|
#[doc = "Register `IFCR` reader"]
pub type R = crate::R<IFCR_SPEC>;
#[doc = "Register `IFCR` writer"]
pub type W = crate::W<IFCR_SPEC>;
#[doc = "Field `CTEIF` reader - Clear Transfer error interrupt flag Programming this bit to 1 clears the TEIF flag in the DMA2D_ISR register"]
pub type CTEIF_R = crate::BitReader;
#[doc = "Field `CTEIF` writer - Clear Transfer error interrupt flag Programming this bit to 1 clears the TEIF flag in the DMA2D_ISR register"]
pub type CTEIF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CTCIF` reader - Clear transfer complete interrupt flag Programming this bit to 1 clears the TCIF flag in the DMA2D_ISR register"]
pub type CTCIF_R = crate::BitReader;
#[doc = "Field `CTCIF` writer - Clear transfer complete interrupt flag Programming this bit to 1 clears the TCIF flag in the DMA2D_ISR register"]
pub type CTCIF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CTWIF` reader - Clear transfer watermark interrupt flag Programming this bit to 1 clears the TWIF flag in the DMA2D_ISR register"]
pub type CTWIF_R = crate::BitReader;
#[doc = "Field `CTWIF` writer - Clear transfer watermark interrupt flag Programming this bit to 1 clears the TWIF flag in the DMA2D_ISR register"]
pub type CTWIF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CAECIF` reader - Clear CLUT access error interrupt flag Programming this bit to 1 clears the CAEIF flag in the DMA2D_ISR register"]
pub type CAECIF_R = crate::BitReader;
#[doc = "Field `CAECIF` writer - Clear CLUT access error interrupt flag Programming this bit to 1 clears the CAEIF flag in the DMA2D_ISR register"]
pub type CAECIF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CCTCIF` reader - Clear CLUT transfer complete interrupt flag Programming this bit to 1 clears the CTCIF flag in the DMA2D_ISR register"]
pub type CCTCIF_R = crate::BitReader;
#[doc = "Field `CCTCIF` writer - Clear CLUT transfer complete interrupt flag Programming this bit to 1 clears the CTCIF flag in the DMA2D_ISR register"]
pub type CCTCIF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CCEIF` reader - Clear configuration error interrupt flag Programming this bit to 1 clears the CEIF flag in the DMA2D_ISR register"]
pub type CCEIF_R = crate::BitReader;
#[doc = "Field `CCEIF` writer - Clear configuration error interrupt flag Programming this bit to 1 clears the CEIF flag in the DMA2D_ISR register"]
pub type CCEIF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - Clear Transfer error interrupt flag Programming this bit to 1 clears the TEIF flag in the DMA2D_ISR register"]
#[inline(always)]
pub fn cteif(&self) -> CTEIF_R {
CTEIF_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Clear transfer complete interrupt flag Programming this bit to 1 clears the TCIF flag in the DMA2D_ISR register"]
#[inline(always)]
pub fn ctcif(&self) -> CTCIF_R {
CTCIF_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Clear transfer watermark interrupt flag Programming this bit to 1 clears the TWIF flag in the DMA2D_ISR register"]
#[inline(always)]
pub fn ctwif(&self) -> CTWIF_R {
CTWIF_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - Clear CLUT access error interrupt flag Programming this bit to 1 clears the CAEIF flag in the DMA2D_ISR register"]
#[inline(always)]
pub fn caecif(&self) -> CAECIF_R {
CAECIF_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - Clear CLUT transfer complete interrupt flag Programming this bit to 1 clears the CTCIF flag in the DMA2D_ISR register"]
#[inline(always)]
pub fn cctcif(&self) -> CCTCIF_R {
CCTCIF_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - Clear configuration error interrupt flag Programming this bit to 1 clears the CEIF flag in the DMA2D_ISR register"]
#[inline(always)]
pub fn cceif(&self) -> CCEIF_R {
CCEIF_R::new(((self.bits >> 5) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Clear Transfer error interrupt flag Programming this bit to 1 clears the TEIF flag in the DMA2D_ISR register"]
#[inline(always)]
#[must_use]
pub fn cteif(&mut self) -> CTEIF_W<IFCR_SPEC, 0> {
CTEIF_W::new(self)
}
#[doc = "Bit 1 - Clear transfer complete interrupt flag Programming this bit to 1 clears the TCIF flag in the DMA2D_ISR register"]
#[inline(always)]
#[must_use]
pub fn ctcif(&mut self) -> CTCIF_W<IFCR_SPEC, 1> {
CTCIF_W::new(self)
}
#[doc = "Bit 2 - Clear transfer watermark interrupt flag Programming this bit to 1 clears the TWIF flag in the DMA2D_ISR register"]
#[inline(always)]
#[must_use]
pub fn ctwif(&mut self) -> CTWIF_W<IFCR_SPEC, 2> {
CTWIF_W::new(self)
}
#[doc = "Bit 3 - Clear CLUT access error interrupt flag Programming this bit to 1 clears the CAEIF flag in the DMA2D_ISR register"]
#[inline(always)]
#[must_use]
pub fn caecif(&mut self) -> CAECIF_W<IFCR_SPEC, 3> {
CAECIF_W::new(self)
}
#[doc = "Bit 4 - Clear CLUT transfer complete interrupt flag Programming this bit to 1 clears the CTCIF flag in the DMA2D_ISR register"]
#[inline(always)]
#[must_use]
pub fn cctcif(&mut self) -> CCTCIF_W<IFCR_SPEC, 4> {
CCTCIF_W::new(self)
}
#[doc = "Bit 5 - Clear configuration error interrupt flag Programming this bit to 1 clears the CEIF flag in the DMA2D_ISR register"]
#[inline(always)]
#[must_use]
pub fn cceif(&mut self) -> CCEIF_W<IFCR_SPEC, 5> {
CCEIF_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 = "DMA2D interrupt flag clear register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ifcr::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 [`ifcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct IFCR_SPEC;
impl crate::RegisterSpec for IFCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ifcr::R`](R) reader structure"]
impl crate::Readable for IFCR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ifcr::W`](W) writer structure"]
impl crate::Writable for IFCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets IFCR to value 0"]
impl crate::Resettable for IFCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::{borrow::Cow, collections::HashMap};
use excel_column_id::ColumnId;
use crate::{
cell::ColIndex,
shared_strings::{SharedStringIndex, SharedStrings},
};
#[derive(Default)]
pub struct Context {
pub(crate) shared_strings: SharedStrings,
pub(crate) column_ids_cache: HashMap<ColIndex, ColumnId>,
}
impl Context {
pub(crate) fn add_shared_string(&mut self, value: Cow<'static, str>) -> SharedStringIndex {
self.shared_strings.insert(value)
}
pub(crate) fn add_col_index(&mut self, col_index: ColIndex) {
self.column_ids_cache
.entry(col_index)
.or_insert_with(|| ColumnId::from(col_index.0 + 1));
}
}
|
//! # 13. 罗马数字转整数
//! https://leetcode-cn.com/problems/roman-to-integer/
//!罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
//! 字符 数值
//! I 1
//! V 5
//! X 10
//! L 50
//! C 100
//! D 500
//! M 1000
//! 例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。
//! 通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,‘
//! 所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:
//! I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
//! X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。
//! C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
//! 给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。
//! # 解题思路
//! 匹配罗马字符转为数字,小的数字如果在大数字的左边用则加上大数字减去小数字,否则一直相加
pub struct Solution;
impl Solution {
pub fn roman_to_int(s: String) -> i32 {
if s.is_empty() {
return 0;
}
let romans: Vec<char> = s.chars().collect();
let mut pre = Self::to_int(romans.first().unwrap());
let mut pre_sum = pre;
let mut ans = pre;
for i in 1..romans.len() {
let cur = Self::to_int(&romans[i]);
match cur.cmp(&pre) {
std::cmp::Ordering::Equal => {
pre_sum += cur;
ans += cur;
}
std::cmp::Ordering::Less => {
pre = cur;
pre_sum = pre;
ans += cur;
}
std::cmp::Ordering::Greater => {
pre = cur;
ans -= pre_sum;
ans += cur - pre_sum;
pre_sum = pre;
}
}
}
ans
}
fn to_int(c: &char) -> i32 {
match c {
&'I' => 1,
&'V' => 5,
&'X' => 10,
&'L' => 50,
&'C' => 100,
&'D' => 500,
&'M' => 1000,
_ => panic!("invalid roman character"),
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(super::Solution::roman_to_int("I".into()), 1);
assert_eq!(super::Solution::roman_to_int("M".into()), 1000);
assert_eq!(super::Solution::roman_to_int("IV".into()), 4);
assert_eq!(super::Solution::roman_to_int("MCMXCIV".into()), 1994);
assert_eq!(super::Solution::roman_to_int("LVIII".into()), 58);
assert_eq!(super::Solution::roman_to_int("MM".into()), 2000);
}
}
|
#[feature(managed_boxes)];
#[desc = "Test game I write to learn rust"];
#[license = "GPLv2"];
extern mod nphysics;
extern mod rsfml;
mod engine;
fn main() {
print("helloWorld");
let mut engine = engine::Engine::new();
print(format!("{:?}\n",engine.textureCache.load(~"images/rust-logo.png")));
engine.run();
}
|
use {Result, Error};
use sys::{cpuinfo, memory};
use std::{fmt, result};
use self::Hardware::{
RaspberryPi
};
#[derive(Clone, Copy, Debug)]
pub struct Board {
pub hardware: Hardware,
pub cpu: CPU,
pub memory: Option<u32>,
pub overvolted: bool
}
#[derive(Clone, Copy, Debug)]
pub enum Hardware {
RaspberryPi(RaspberryModel, RaspberryRevision, RaspberryMaker),
Unknown
}
#[derive(Clone, Copy, Debug)]
pub enum CPU {
BCM2708,
BCM2709,
Unknown
}
// Raspberry Pi
#[derive(Clone, Copy, Debug)]
pub enum RaspberryModel { A, B, BP, AP, CM, B2, UN }
impl<'a> From<&'a RaspberryModel> for &'static str {
fn from(model: &'a RaspberryModel) -> Self {
match *model {
RaspberryModel::A => "Model A",
RaspberryModel::B => "Model B",
RaspberryModel::BP => "Model B+",
RaspberryModel::AP => "Model A+",
RaspberryModel::CM => "Compute Module",
RaspberryModel::B2 => "Model 2B",
RaspberryModel::UN => "Unknown"
}
}
}
impl fmt::Display for RaspberryModel {
fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
let s: &'static str = self.into();
try!(write!(f, "{}", s));
Ok(())
}
}
#[derive(Clone, Copy, Debug)]
pub enum RaspberryRevision { V1, V11, V12, V2, UN }
impl RaspberryRevision {
const PIN_TO_GPIO: [usize; 32] = [
// Primary
17, 18, 27, 22, 23, 24, 25, 4,
// Additional
2, 3, 8, 7, 10, 9, 11, 14, 15,
// Pi B rev.2
28, 29, 30, 31,
// B+, Pi2
5, 6, 13, 19, 26, 12, 16, 20, 21, 0, 1
];
}
impl<'a> From<&'a RaspberryRevision> for &'static str {
fn from(rev: &'a RaspberryRevision) -> Self {
match *rev {
RaspberryRevision::V1 => "1",
RaspberryRevision::V11 => "1.1",
RaspberryRevision::V12 => "1.2",
RaspberryRevision::V2 => "2",
RaspberryRevision::UN => "Unknown"
}
}
}
impl fmt::Display for RaspberryRevision {
fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
let s: &'static str = self.into();
try!(write!(f, "{}", s));
Ok(())
}
}
#[derive(Clone, Copy, Debug)]
pub enum RaspberryMaker { Egoman, Sony, Qisda, MBest, Unknown }
impl<'a> From<&'a RaspberryMaker> for &'static str {
fn from(maker: &'a RaspberryMaker) -> Self {
match *maker {
RaspberryMaker::Egoman => "Egoman",
RaspberryMaker::Sony => "Sony",
RaspberryMaker::Qisda => "Qisda",
RaspberryMaker::MBest => "MBest",
RaspberryMaker::Unknown => "Unknown"
}
}
}
impl fmt::Display for RaspberryMaker {
fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
let s: &'static str = self.into();
try!(write!(f, "{}", s));
Ok(())
}
}
impl Board {
pub fn pin_to_gpio(&self, pin: usize) -> Result<usize> {
match self.hardware {
Hardware::RaspberryPi(model, _, _) => {
let max_pins = match model {
RaspberryModel::BP |
RaspberryModel::AP |
RaspberryModel::B2 |
RaspberryModel::CM => 32,
_ => 21
};
if pin >= max_pins {
return Err(Error::UnconnectedPin);
};
Ok(RaspberryRevision::PIN_TO_GPIO[pin])
},
Hardware::Unknown => Err(Error::UnsupportedHardware)
}
}
}
pub fn board() -> Board {
let memory = match memory() {
Ok(m) => Some(m.total),
Err(_) => None
};
match cpuinfo() {
Ok(cpuinfo) => {
let rev = cpuinfo.0.get("Revision");
match cpuinfo.0.get("Hardware") {
Some(hardware) => match hardware.as_str() {
"BCM2708" => {
match rev {
Some(ref rev) => {
let size = rev.len();
let overvolted = size > 4;
let revision: &str = &rev[size-4..size];
let hardware = match revision.as_ref() {
"0002" => RaspberryPi(RaspberryModel::B, RaspberryRevision::V1, RaspberryMaker::Egoman),
"0003" => RaspberryPi(RaspberryModel::B, RaspberryRevision::V11, RaspberryMaker::Egoman),
"0004" | "000e" => RaspberryPi(RaspberryModel::B, RaspberryRevision::V2, RaspberryMaker::Sony),
"0005" | "0009" => RaspberryPi(RaspberryModel::B, RaspberryRevision::V2, RaspberryMaker::Qisda),
"0006" | "0007" | "000d" | "000f" => RaspberryPi(RaspberryModel::B, RaspberryRevision::V2, RaspberryMaker::Egoman),
"0008" => RaspberryPi(RaspberryModel::A, RaspberryRevision::V2, RaspberryMaker::Sony),
"0010" => RaspberryPi(RaspberryModel::BP, RaspberryRevision::V12, RaspberryMaker::Sony),
"0011" | "0014" => RaspberryPi(RaspberryModel::CM, RaspberryRevision::V12, RaspberryMaker::Sony),
"0012" => RaspberryPi(RaspberryModel::AP, RaspberryRevision::V12, RaspberryMaker::Sony),
"0013" => RaspberryPi(RaspberryModel::BP, RaspberryRevision::V12, RaspberryMaker::MBest),
_ => RaspberryPi(RaspberryModel::UN, RaspberryRevision::UN, RaspberryMaker::Unknown)
};
Board { hardware: hardware, memory: memory, cpu: CPU::BCM2708, overvolted: overvolted }
},
None => Board { hardware: Hardware::Unknown, memory: memory, cpu: CPU::BCM2708, overvolted: false }
}
},
"BCM2709" => Board { hardware: RaspberryPi(RaspberryModel::B2, RaspberryRevision::V11, RaspberryMaker::Sony), memory: memory, cpu: CPU::BCM2709, overvolted: false },
_ => Board { hardware: Hardware::Unknown, memory: memory, cpu: CPU::Unknown, overvolted: false },
},
None => Board { hardware: Hardware::Unknown, memory: memory, cpu: CPU::Unknown, overvolted: false }
}
},
Err(_) => {
Board { hardware: Hardware::Unknown, memory: memory, cpu: CPU::Unknown, overvolted: false }
}
}
}
|
use super::super::prelude::{
HCURSOR
};
pub type Cursor = HCURSOR; |
#[doc = "Register `IER` reader"]
pub type R = crate::R<IER_SPEC>;
#[doc = "Register `IER` writer"]
pub type W = crate::W<IER_SPEC>;
#[doc = "Field `TMEIE` reader - TMEIE"]
pub type TMEIE_R = crate::BitReader<TMEIE_A>;
#[doc = "TMEIE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TMEIE_A {
#[doc = "0: No interrupt when RQCPx bit is set"]
Disabled = 0,
#[doc = "1: Interrupt generated when RQCPx bit is set"]
Enabled = 1,
}
impl From<TMEIE_A> for bool {
#[inline(always)]
fn from(variant: TMEIE_A) -> Self {
variant as u8 != 0
}
}
impl TMEIE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TMEIE_A {
match self.bits {
false => TMEIE_A::Disabled,
true => TMEIE_A::Enabled,
}
}
#[doc = "No interrupt when RQCPx bit is set"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == TMEIE_A::Disabled
}
#[doc = "Interrupt generated when RQCPx bit is set"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == TMEIE_A::Enabled
}
}
#[doc = "Field `TMEIE` writer - TMEIE"]
pub type TMEIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TMEIE_A>;
impl<'a, REG, const O: u8> TMEIE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No interrupt when RQCPx bit is set"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(TMEIE_A::Disabled)
}
#[doc = "Interrupt generated when RQCPx bit is set"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(TMEIE_A::Enabled)
}
}
#[doc = "Field `FMPIE0` reader - FMPIE0"]
pub type FMPIE0_R = crate::BitReader<FMPIE0_A>;
#[doc = "FMPIE0\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FMPIE0_A {
#[doc = "0: No interrupt generated when state of FMP\\[1:0\\]
bits are not 00"]
Disabled = 0,
#[doc = "1: Interrupt generated when state of FMP\\[1:0\\]
bits are not 00b"]
Enabled = 1,
}
impl From<FMPIE0_A> for bool {
#[inline(always)]
fn from(variant: FMPIE0_A) -> Self {
variant as u8 != 0
}
}
impl FMPIE0_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> FMPIE0_A {
match self.bits {
false => FMPIE0_A::Disabled,
true => FMPIE0_A::Enabled,
}
}
#[doc = "No interrupt generated when state of FMP\\[1:0\\]
bits are not 00"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == FMPIE0_A::Disabled
}
#[doc = "Interrupt generated when state of FMP\\[1:0\\]
bits are not 00b"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == FMPIE0_A::Enabled
}
}
#[doc = "Field `FMPIE0` writer - FMPIE0"]
pub type FMPIE0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FMPIE0_A>;
impl<'a, REG, const O: u8> FMPIE0_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No interrupt generated when state of FMP\\[1:0\\]
bits are not 00"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(FMPIE0_A::Disabled)
}
#[doc = "Interrupt generated when state of FMP\\[1:0\\]
bits are not 00b"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(FMPIE0_A::Enabled)
}
}
#[doc = "Field `FFIE0` reader - FFIE0"]
pub type FFIE0_R = crate::BitReader<FFIE0_A>;
#[doc = "FFIE0\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FFIE0_A {
#[doc = "0: No interrupt when FULL bit is set"]
Disabled = 0,
#[doc = "1: Interrupt generated when FULL bit is set"]
Enabled = 1,
}
impl From<FFIE0_A> for bool {
#[inline(always)]
fn from(variant: FFIE0_A) -> Self {
variant as u8 != 0
}
}
impl FFIE0_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> FFIE0_A {
match self.bits {
false => FFIE0_A::Disabled,
true => FFIE0_A::Enabled,
}
}
#[doc = "No interrupt when FULL bit is set"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == FFIE0_A::Disabled
}
#[doc = "Interrupt generated when FULL bit is set"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == FFIE0_A::Enabled
}
}
#[doc = "Field `FFIE0` writer - FFIE0"]
pub type FFIE0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FFIE0_A>;
impl<'a, REG, const O: u8> FFIE0_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No interrupt when FULL bit is set"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(FFIE0_A::Disabled)
}
#[doc = "Interrupt generated when FULL bit is set"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(FFIE0_A::Enabled)
}
}
#[doc = "Field `FOVIE0` reader - FOVIE0"]
pub type FOVIE0_R = crate::BitReader<FOVIE0_A>;
#[doc = "FOVIE0\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FOVIE0_A {
#[doc = "0: No interrupt when FOVR bit is set"]
Disabled = 0,
#[doc = "1: Interrupt generated when FOVR bit is set"]
Enabled = 1,
}
impl From<FOVIE0_A> for bool {
#[inline(always)]
fn from(variant: FOVIE0_A) -> Self {
variant as u8 != 0
}
}
impl FOVIE0_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> FOVIE0_A {
match self.bits {
false => FOVIE0_A::Disabled,
true => FOVIE0_A::Enabled,
}
}
#[doc = "No interrupt when FOVR bit is set"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == FOVIE0_A::Disabled
}
#[doc = "Interrupt generated when FOVR bit is set"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == FOVIE0_A::Enabled
}
}
#[doc = "Field `FOVIE0` writer - FOVIE0"]
pub type FOVIE0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FOVIE0_A>;
impl<'a, REG, const O: u8> FOVIE0_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No interrupt when FOVR bit is set"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(FOVIE0_A::Disabled)
}
#[doc = "Interrupt generated when FOVR bit is set"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(FOVIE0_A::Enabled)
}
}
#[doc = "Field `FMPIE1` reader - FMPIE1"]
pub type FMPIE1_R = crate::BitReader<FMPIE1_A>;
#[doc = "FMPIE1\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FMPIE1_A {
#[doc = "0: No interrupt generated when state of FMP\\[1:0\\]
bits are not 00b"]
Disabled = 0,
#[doc = "1: Interrupt generated when state of FMP\\[1:0\\]
bits are not 00b"]
Enabled = 1,
}
impl From<FMPIE1_A> for bool {
#[inline(always)]
fn from(variant: FMPIE1_A) -> Self {
variant as u8 != 0
}
}
impl FMPIE1_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> FMPIE1_A {
match self.bits {
false => FMPIE1_A::Disabled,
true => FMPIE1_A::Enabled,
}
}
#[doc = "No interrupt generated when state of FMP\\[1:0\\]
bits are not 00b"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == FMPIE1_A::Disabled
}
#[doc = "Interrupt generated when state of FMP\\[1:0\\]
bits are not 00b"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == FMPIE1_A::Enabled
}
}
#[doc = "Field `FMPIE1` writer - FMPIE1"]
pub type FMPIE1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FMPIE1_A>;
impl<'a, REG, const O: u8> FMPIE1_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No interrupt generated when state of FMP\\[1:0\\]
bits are not 00b"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(FMPIE1_A::Disabled)
}
#[doc = "Interrupt generated when state of FMP\\[1:0\\]
bits are not 00b"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(FMPIE1_A::Enabled)
}
}
#[doc = "Field `FFIE1` reader - FFIE1"]
pub type FFIE1_R = crate::BitReader<FFIE1_A>;
#[doc = "FFIE1\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FFIE1_A {
#[doc = "0: No interrupt when FULL bit is set"]
Disabled = 0,
#[doc = "1: Interrupt generated when FULL bit is set"]
Enabled = 1,
}
impl From<FFIE1_A> for bool {
#[inline(always)]
fn from(variant: FFIE1_A) -> Self {
variant as u8 != 0
}
}
impl FFIE1_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> FFIE1_A {
match self.bits {
false => FFIE1_A::Disabled,
true => FFIE1_A::Enabled,
}
}
#[doc = "No interrupt when FULL bit is set"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == FFIE1_A::Disabled
}
#[doc = "Interrupt generated when FULL bit is set"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == FFIE1_A::Enabled
}
}
#[doc = "Field `FFIE1` writer - FFIE1"]
pub type FFIE1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FFIE1_A>;
impl<'a, REG, const O: u8> FFIE1_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No interrupt when FULL bit is set"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(FFIE1_A::Disabled)
}
#[doc = "Interrupt generated when FULL bit is set"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(FFIE1_A::Enabled)
}
}
#[doc = "Field `FOVIE1` reader - FOVIE1"]
pub type FOVIE1_R = crate::BitReader<FOVIE1_A>;
#[doc = "FOVIE1\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FOVIE1_A {
#[doc = "0: No interrupt when FOVR is set"]
Disabled = 0,
#[doc = "1: Interrupt generation when FOVR is set"]
Enabled = 1,
}
impl From<FOVIE1_A> for bool {
#[inline(always)]
fn from(variant: FOVIE1_A) -> Self {
variant as u8 != 0
}
}
impl FOVIE1_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> FOVIE1_A {
match self.bits {
false => FOVIE1_A::Disabled,
true => FOVIE1_A::Enabled,
}
}
#[doc = "No interrupt when FOVR is set"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == FOVIE1_A::Disabled
}
#[doc = "Interrupt generation when FOVR is set"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == FOVIE1_A::Enabled
}
}
#[doc = "Field `FOVIE1` writer - FOVIE1"]
pub type FOVIE1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FOVIE1_A>;
impl<'a, REG, const O: u8> FOVIE1_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No interrupt when FOVR is set"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(FOVIE1_A::Disabled)
}
#[doc = "Interrupt generation when FOVR is set"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(FOVIE1_A::Enabled)
}
}
#[doc = "Field `EWGIE` reader - EWGIE"]
pub type EWGIE_R = crate::BitReader<EWGIE_A>;
#[doc = "EWGIE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EWGIE_A {
#[doc = "0: ERRI bit will not be set when EWGF is set"]
Disabled = 0,
#[doc = "1: ERRI bit will be set when EWGF is set"]
Enabled = 1,
}
impl From<EWGIE_A> for bool {
#[inline(always)]
fn from(variant: EWGIE_A) -> Self {
variant as u8 != 0
}
}
impl EWGIE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EWGIE_A {
match self.bits {
false => EWGIE_A::Disabled,
true => EWGIE_A::Enabled,
}
}
#[doc = "ERRI bit will not be set when EWGF is set"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == EWGIE_A::Disabled
}
#[doc = "ERRI bit will be set when EWGF is set"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == EWGIE_A::Enabled
}
}
#[doc = "Field `EWGIE` writer - EWGIE"]
pub type EWGIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, EWGIE_A>;
impl<'a, REG, const O: u8> EWGIE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "ERRI bit will not be set when EWGF is set"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(EWGIE_A::Disabled)
}
#[doc = "ERRI bit will be set when EWGF is set"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(EWGIE_A::Enabled)
}
}
#[doc = "Field `EPVIE` reader - EPVIE"]
pub type EPVIE_R = crate::BitReader<EPVIE_A>;
#[doc = "EPVIE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EPVIE_A {
#[doc = "0: ERRI bit will not be set when EPVF is set"]
Disabled = 0,
#[doc = "1: ERRI bit will be set when EPVF is set"]
Enabled = 1,
}
impl From<EPVIE_A> for bool {
#[inline(always)]
fn from(variant: EPVIE_A) -> Self {
variant as u8 != 0
}
}
impl EPVIE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EPVIE_A {
match self.bits {
false => EPVIE_A::Disabled,
true => EPVIE_A::Enabled,
}
}
#[doc = "ERRI bit will not be set when EPVF is set"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == EPVIE_A::Disabled
}
#[doc = "ERRI bit will be set when EPVF is set"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == EPVIE_A::Enabled
}
}
#[doc = "Field `EPVIE` writer - EPVIE"]
pub type EPVIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, EPVIE_A>;
impl<'a, REG, const O: u8> EPVIE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "ERRI bit will not be set when EPVF is set"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(EPVIE_A::Disabled)
}
#[doc = "ERRI bit will be set when EPVF is set"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(EPVIE_A::Enabled)
}
}
#[doc = "Field `BOFIE` reader - BOFIE"]
pub type BOFIE_R = crate::BitReader<BOFIE_A>;
#[doc = "BOFIE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BOFIE_A {
#[doc = "0: ERRI bit will not be set when BOFF is set"]
Disabled = 0,
#[doc = "1: ERRI bit will be set when BOFF is set"]
Enabled = 1,
}
impl From<BOFIE_A> for bool {
#[inline(always)]
fn from(variant: BOFIE_A) -> Self {
variant as u8 != 0
}
}
impl BOFIE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> BOFIE_A {
match self.bits {
false => BOFIE_A::Disabled,
true => BOFIE_A::Enabled,
}
}
#[doc = "ERRI bit will not be set when BOFF is set"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == BOFIE_A::Disabled
}
#[doc = "ERRI bit will be set when BOFF is set"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == BOFIE_A::Enabled
}
}
#[doc = "Field `BOFIE` writer - BOFIE"]
pub type BOFIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, BOFIE_A>;
impl<'a, REG, const O: u8> BOFIE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "ERRI bit will not be set when BOFF is set"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(BOFIE_A::Disabled)
}
#[doc = "ERRI bit will be set when BOFF is set"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(BOFIE_A::Enabled)
}
}
#[doc = "Field `LECIE` reader - LECIE"]
pub type LECIE_R = crate::BitReader<LECIE_A>;
#[doc = "LECIE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LECIE_A {
#[doc = "0: ERRI bit will not be set when the error code in LEC\\[2:0\\]
is set by hardware on error detection"]
Disabled = 0,
#[doc = "1: ERRI bit will be set when the error code in LEC\\[2:0\\]
is set by hardware on error detection"]
Enabled = 1,
}
impl From<LECIE_A> for bool {
#[inline(always)]
fn from(variant: LECIE_A) -> Self {
variant as u8 != 0
}
}
impl LECIE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LECIE_A {
match self.bits {
false => LECIE_A::Disabled,
true => LECIE_A::Enabled,
}
}
#[doc = "ERRI bit will not be set when the error code in LEC\\[2:0\\]
is set by hardware on error detection"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == LECIE_A::Disabled
}
#[doc = "ERRI bit will be set when the error code in LEC\\[2:0\\]
is set by hardware on error detection"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == LECIE_A::Enabled
}
}
#[doc = "Field `LECIE` writer - LECIE"]
pub type LECIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, LECIE_A>;
impl<'a, REG, const O: u8> LECIE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "ERRI bit will not be set when the error code in LEC\\[2:0\\]
is set by hardware on error detection"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(LECIE_A::Disabled)
}
#[doc = "ERRI bit will be set when the error code in LEC\\[2:0\\]
is set by hardware on error detection"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(LECIE_A::Enabled)
}
}
#[doc = "Field `ERRIE` reader - ERRIE"]
pub type ERRIE_R = crate::BitReader<ERRIE_A>;
#[doc = "ERRIE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ERRIE_A {
#[doc = "0: No interrupt will be generated when an error condition is pending in the CAN_ESR"]
Disabled = 0,
#[doc = "1: An interrupt will be generation when an error condition is pending in the CAN_ESR"]
Enabled = 1,
}
impl From<ERRIE_A> for bool {
#[inline(always)]
fn from(variant: ERRIE_A) -> Self {
variant as u8 != 0
}
}
impl ERRIE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ERRIE_A {
match self.bits {
false => ERRIE_A::Disabled,
true => ERRIE_A::Enabled,
}
}
#[doc = "No interrupt will be generated when an error condition is pending in the CAN_ESR"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == ERRIE_A::Disabled
}
#[doc = "An interrupt will be generation when an error condition is pending in the CAN_ESR"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == ERRIE_A::Enabled
}
}
#[doc = "Field `ERRIE` writer - ERRIE"]
pub type ERRIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, ERRIE_A>;
impl<'a, REG, const O: u8> ERRIE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No interrupt will be generated when an error condition is pending in the CAN_ESR"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(ERRIE_A::Disabled)
}
#[doc = "An interrupt will be generation when an error condition is pending in the CAN_ESR"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(ERRIE_A::Enabled)
}
}
#[doc = "Field `WKUIE` reader - WKUIE"]
pub type WKUIE_R = crate::BitReader<WKUIE_A>;
#[doc = "WKUIE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WKUIE_A {
#[doc = "0: No interrupt when WKUI is set"]
Disabled = 0,
#[doc = "1: Interrupt generated when WKUI bit is set"]
Enabled = 1,
}
impl From<WKUIE_A> for bool {
#[inline(always)]
fn from(variant: WKUIE_A) -> Self {
variant as u8 != 0
}
}
impl WKUIE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> WKUIE_A {
match self.bits {
false => WKUIE_A::Disabled,
true => WKUIE_A::Enabled,
}
}
#[doc = "No interrupt when WKUI is set"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == WKUIE_A::Disabled
}
#[doc = "Interrupt generated when WKUI bit is set"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == WKUIE_A::Enabled
}
}
#[doc = "Field `WKUIE` writer - WKUIE"]
pub type WKUIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, WKUIE_A>;
impl<'a, REG, const O: u8> WKUIE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No interrupt when WKUI is set"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(WKUIE_A::Disabled)
}
#[doc = "Interrupt generated when WKUI bit is set"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(WKUIE_A::Enabled)
}
}
#[doc = "Field `SLKIE` reader - SLKIE"]
pub type SLKIE_R = crate::BitReader<SLKIE_A>;
#[doc = "SLKIE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SLKIE_A {
#[doc = "0: No interrupt when SLAKI bit is set"]
Disabled = 0,
#[doc = "1: Interrupt generated when SLAKI bit is set"]
Enabled = 1,
}
impl From<SLKIE_A> for bool {
#[inline(always)]
fn from(variant: SLKIE_A) -> Self {
variant as u8 != 0
}
}
impl SLKIE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SLKIE_A {
match self.bits {
false => SLKIE_A::Disabled,
true => SLKIE_A::Enabled,
}
}
#[doc = "No interrupt when SLAKI bit is set"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == SLKIE_A::Disabled
}
#[doc = "Interrupt generated when SLAKI bit is set"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == SLKIE_A::Enabled
}
}
#[doc = "Field `SLKIE` writer - SLKIE"]
pub type SLKIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SLKIE_A>;
impl<'a, REG, const O: u8> SLKIE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No interrupt when SLAKI bit is set"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(SLKIE_A::Disabled)
}
#[doc = "Interrupt generated when SLAKI bit is set"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(SLKIE_A::Enabled)
}
}
impl R {
#[doc = "Bit 0 - TMEIE"]
#[inline(always)]
pub fn tmeie(&self) -> TMEIE_R {
TMEIE_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - FMPIE0"]
#[inline(always)]
pub fn fmpie0(&self) -> FMPIE0_R {
FMPIE0_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - FFIE0"]
#[inline(always)]
pub fn ffie0(&self) -> FFIE0_R {
FFIE0_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - FOVIE0"]
#[inline(always)]
pub fn fovie0(&self) -> FOVIE0_R {
FOVIE0_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - FMPIE1"]
#[inline(always)]
pub fn fmpie1(&self) -> FMPIE1_R {
FMPIE1_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - FFIE1"]
#[inline(always)]
pub fn ffie1(&self) -> FFIE1_R {
FFIE1_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - FOVIE1"]
#[inline(always)]
pub fn fovie1(&self) -> FOVIE1_R {
FOVIE1_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 8 - EWGIE"]
#[inline(always)]
pub fn ewgie(&self) -> EWGIE_R {
EWGIE_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - EPVIE"]
#[inline(always)]
pub fn epvie(&self) -> EPVIE_R {
EPVIE_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - BOFIE"]
#[inline(always)]
pub fn bofie(&self) -> BOFIE_R {
BOFIE_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - LECIE"]
#[inline(always)]
pub fn lecie(&self) -> LECIE_R {
LECIE_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 15 - ERRIE"]
#[inline(always)]
pub fn errie(&self) -> ERRIE_R {
ERRIE_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - WKUIE"]
#[inline(always)]
pub fn wkuie(&self) -> WKUIE_R {
WKUIE_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - SLKIE"]
#[inline(always)]
pub fn slkie(&self) -> SLKIE_R {
SLKIE_R::new(((self.bits >> 17) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - TMEIE"]
#[inline(always)]
#[must_use]
pub fn tmeie(&mut self) -> TMEIE_W<IER_SPEC, 0> {
TMEIE_W::new(self)
}
#[doc = "Bit 1 - FMPIE0"]
#[inline(always)]
#[must_use]
pub fn fmpie0(&mut self) -> FMPIE0_W<IER_SPEC, 1> {
FMPIE0_W::new(self)
}
#[doc = "Bit 2 - FFIE0"]
#[inline(always)]
#[must_use]
pub fn ffie0(&mut self) -> FFIE0_W<IER_SPEC, 2> {
FFIE0_W::new(self)
}
#[doc = "Bit 3 - FOVIE0"]
#[inline(always)]
#[must_use]
pub fn fovie0(&mut self) -> FOVIE0_W<IER_SPEC, 3> {
FOVIE0_W::new(self)
}
#[doc = "Bit 4 - FMPIE1"]
#[inline(always)]
#[must_use]
pub fn fmpie1(&mut self) -> FMPIE1_W<IER_SPEC, 4> {
FMPIE1_W::new(self)
}
#[doc = "Bit 5 - FFIE1"]
#[inline(always)]
#[must_use]
pub fn ffie1(&mut self) -> FFIE1_W<IER_SPEC, 5> {
FFIE1_W::new(self)
}
#[doc = "Bit 6 - FOVIE1"]
#[inline(always)]
#[must_use]
pub fn fovie1(&mut self) -> FOVIE1_W<IER_SPEC, 6> {
FOVIE1_W::new(self)
}
#[doc = "Bit 8 - EWGIE"]
#[inline(always)]
#[must_use]
pub fn ewgie(&mut self) -> EWGIE_W<IER_SPEC, 8> {
EWGIE_W::new(self)
}
#[doc = "Bit 9 - EPVIE"]
#[inline(always)]
#[must_use]
pub fn epvie(&mut self) -> EPVIE_W<IER_SPEC, 9> {
EPVIE_W::new(self)
}
#[doc = "Bit 10 - BOFIE"]
#[inline(always)]
#[must_use]
pub fn bofie(&mut self) -> BOFIE_W<IER_SPEC, 10> {
BOFIE_W::new(self)
}
#[doc = "Bit 11 - LECIE"]
#[inline(always)]
#[must_use]
pub fn lecie(&mut self) -> LECIE_W<IER_SPEC, 11> {
LECIE_W::new(self)
}
#[doc = "Bit 15 - ERRIE"]
#[inline(always)]
#[must_use]
pub fn errie(&mut self) -> ERRIE_W<IER_SPEC, 15> {
ERRIE_W::new(self)
}
#[doc = "Bit 16 - WKUIE"]
#[inline(always)]
#[must_use]
pub fn wkuie(&mut self) -> WKUIE_W<IER_SPEC, 16> {
WKUIE_W::new(self)
}
#[doc = "Bit 17 - SLKIE"]
#[inline(always)]
#[must_use]
pub fn slkie(&mut self) -> SLKIE_W<IER_SPEC, 17> {
SLKIE_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 = "CAN_IER\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ier::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 [`ier::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct IER_SPEC;
impl crate::RegisterSpec for IER_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ier::R`](R) reader structure"]
impl crate::Readable for IER_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ier::W`](W) writer structure"]
impl crate::Writable for IER_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets IER to value 0"]
impl crate::Resettable for IER_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::io::*;
use std::str::FromStr;
fn read<T: FromStr>() -> T {
let stdin = stdin();
let stdin = stdin.lock();
let token: String = stdin
.bytes()
.map(|c| c.expect("failed to read char") as char)
.skip_while(|c| c.is_whitespace())
.take_while(|c| !c.is_whitespace())
.collect();
token.parse().ok().expect("failed to parse token")
}
fn main() {
let s: String = read();
let ret = match s.as_str() {
"SAT" => 1,
"FRI" => 2,
"THU" => 3,
"WED" => 4,
"TUE" => 5,
"MON" => 6,
"SUN" => 7,
_ => 0
};
println!("{}", ret);
}
|
use super::Task; // Import our tasks
use alloc::collections::VecDeque; // VecDeque (allows us to insert tasks on either side of the vec, so we can prioritise certain tasks)
use crate::println;
/// # SimpleExecutor
///
/// SimpleExecutor is a simple executor of async tasks, and shouldn't be used in production
///
/// It implements a very basic `VecDeque` system for storing tasks, and has methods for spawning and waking tasks.
pub struct SimpleExecutor {
task_queue: VecDeque<Task>,
}
impl SimpleExecutor {
/// Create a new SimpleExecutor struct
pub fn new() -> SimpleExecutor {
println!("[LOG] SimpleExecutor initialized");
SimpleExecutor {
task_queue: VecDeque::new(),
}
}
/// spawn a new task on the task queue (note: this consumes the task)
pub fn spawn(&mut self, task: Task) {
self.task_queue.push_back(task)
}
}
use core::task::{Context, Poll}; /// Context and poll for our run
impl SimpleExecutor {
/// Run the tasks. We iterate through every task, check it is finished.
///
/// If it is, we remove it from the task array. Otherwise we keep it in. We loop forever for every task in the queue
pub fn run(&mut self) {
while let Some(mut task) = self.task_queue.pop_front() {
let waker = dummy_waker(); // Create a waker (wakers notify our executor the task has finished, and wake the task.)
let mut context = Context::from_waker(&waker); // Create a context around our waker
match task.poll(&mut context) { // we check the task has finished with our waker
Poll::Ready(()) => {} // task done
Poll::Pending => self.task_queue.push_back(task), // task not yet done
}
}
}
}
use core::task::{Waker, RawWaker}; // Waker struct and RawWaker trait which implements waker functions
/// RawWaker requires a VTable, which is used in programming to support dynamic dispatch.
/// This allows RawWaker to know what functions to call when it is Cloned, Woken or Dropped. As it is run at
/// runtime, it can't know, hence why we use a VTable to define it for us. This is also why it is unsafe to create
/// a waker from raw - it cannot verify the RawWaker has the required functions.
/// Unsafe as we need to ensure that the Waker has the required requirements.
///
/// This function creates a waker from a RawWaker
fn dummy_waker() -> Waker {
unsafe { Waker::from_raw(dummy_raw_waker()) }
}
/// VTable implemention for RawPointer
use core::task::RawWakerVTable;
/// Define the creation of a rawpointer
fn dummy_raw_waker() -> RawWaker {
/// What to do when not doing anything
fn no_op(_: *const ()) {}
/// What to do when cloned
fn clone(_: *const ()) -> RawWaker {
dummy_raw_waker()
}
/// We use the above functions to define what should be done on clone, drop and wake for our
/// dummy rawpointer in the vtable. Here, we clone, then do nothing for the rest
let vtable = &RawWakerVTable::new(clone, no_op, no_op, no_op);
/// We then pass a pointer to data on the heap to pass to the waker. as we aren't using any data,
/// we just point to null. We then include the table to define the functions needed at runtime.
RawWaker::new(0 as *const (), vtable)
} |
#![cfg_attr(feature = "unstable", feature(test))]
// Launch program : cargo run --release < input/input.txt
// Launch benchmark : cargo +nightly bench --features "unstable"
/*
Benchmark results:
running 5 tests
test tests::test_part_1 ... ignored
test tests::test_part_2 ... ignored
test bench::bench_parse_input ... bench: 5,684 ns/iter (+/- 435)
test bench::bench_part_1 ... bench: 811 ns/iter (+/- 44)
test bench::bench_part_2 ... bench: 1,292 ns/iter (+/- 47)
*/
use std::error::Error;
use std::io::{self, Read, Write};
type Result<T> = ::std::result::Result<T, Box<dyn Error>>;
macro_rules! err {
($($tt:tt)*) => { return Err(Box::<dyn Error>::from(format!($($tt)*))) }
}
fn main() -> Result<()> {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
let adapters = parse_input(&input)?;
writeln!(io::stdout(), "Part 1 : {}", part_1(&adapters)?)?;
writeln!(io::stdout(), "Part 2 : {}", part_2(&adapters)?)?;
Ok(())
}
fn parse_input(input: &str) -> Result<Vec<usize>> {
let mut adapters = vec![];
for line in input.lines() {
adapters.push(line.parse::<usize>()?);
}
adapters.sort_unstable();
Ok(adapters)
}
fn part_1(adapters: &[usize]) -> Result<usize> {
let mut difference_1 = 0;
let mut difference_3 = 1;
for i in 0..adapters.len() {
let difference = if i == 0 {
adapters[i]
} else {
adapters[i] - adapters[i - 1]
};
match difference {
0 | 2 => {}
1 => difference_1 += 1,
3 => difference_3 += 1,
other_value => err!(
"Difference between two adapters can't be greater than 3 : {}",
other_value
),
}
}
Ok(difference_1 * difference_3)
}
fn part_2(adapters: &[usize]) -> Result<usize> {
let mut differences = vec![];
let mut ones_found = 0;
let mut result = 1;
for i in 0..adapters.len() {
let difference = if i == 0 {
adapters[i]
} else {
adapters[i] - adapters[i - 1]
};
differences.push(difference);
}
differences.push(3);
/*
Not quite happy with this solution.
In the case of adapters with 5 or more consecutive diff of 1 (eg:"(0), 1, 2, 3, 4, 5, 6, (9)"), the answer would be wrong.
But I can't find any case where this happens
*/
for diff in differences {
if diff == 1 {
ones_found += 1;
} else {
match ones_found {
0 | 1 => {}
2 => result *= 2,
3 => result *= 4,
4 => result *= 7,
_ => err!("Too many consecutive differences of 1 found, need to update the algorithm!"),
}
ones_found = 0;
}
}
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
fn read_test_file() -> Result<String> {
let mut input = String::new();
File::open("input/test.txt")?.read_to_string(&mut input)?;
Ok(input)
}
fn read_test_file_2() -> Result<String> {
let mut input = String::new();
File::open("input/test2.txt")?.read_to_string(&mut input)?;
Ok(input)
}
#[test]
fn test_part_1() -> Result<()> {
let adapters = parse_input(&read_test_file()?)?;
assert_eq!(part_1(&adapters)?, 7 * 5);
let adapters = parse_input(&read_test_file_2()?)?;
assert_eq!(part_1(&adapters)?, 22 * 10);
Ok(())
}
#[test]
fn test_part_2() -> Result<()> {
let adapters = parse_input(&read_test_file()?)?;
assert_eq!(part_2(&adapters)?, 8);
let adapters = parse_input(&read_test_file_2()?)?;
assert_eq!(part_2(&adapters)?, 19208);
Ok(())
}
}
#[cfg(all(feature = "unstable", test))]
mod bench {
extern crate test;
use super::*;
use std::fs::File;
use test::Bencher;
fn read_input_file() -> Result<String> {
let mut input = String::new();
File::open("input/input.txt")?.read_to_string(&mut input)?;
Ok(input)
}
#[bench]
fn bench_parse_input(b: &mut Bencher) -> Result<()> {
let input = read_input_file()?;
b.iter(|| test::black_box(parse_input(&input)));
Ok(())
}
#[bench]
fn bench_part_1(b: &mut Bencher) -> Result<()> {
let adapters = parse_input(&read_input_file()?)?;
b.iter(|| test::black_box(part_1(&adapters)));
Ok(())
}
#[bench]
fn bench_part_2(b: &mut Bencher) -> Result<()> {
let adapters = parse_input(&read_input_file()?)?;
b.iter(|| test::black_box(part_2(&adapters)));
Ok(())
}
}
|
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2017 The developers of rdma-core. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT.
#[repr(u8)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ServiceLevel
{
Default = 0,
_1 = 1,
_2 = 2,
_3 = 3,
_4 = 4,
_5 = 5,
_6 = 6,
_7 = 7,
_8 = 8,
_9 = 9,
_10 = 10,
_11 = 11,
_12 = 12,
_13 = 13,
_14 = 14,
Administrative = 15,
}
impl Default for ServiceLevel
{
#[inline(always)]
fn default() -> Self
{
ServiceLevel::Default
}
}
|
use crate::classification::structural::BracketType;
#[cfg(target_arch = "x86")]
use core::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::*;
pub(crate) struct DelimiterClassifierImpl256 {
opening: i8,
}
impl DelimiterClassifierImpl256 {
pub(crate) fn new(opening: BracketType) -> Self {
let opening = match opening {
BracketType::Square => b'[',
BracketType::Curly => b'{',
};
Self { opening: opening as i8 }
}
#[target_feature(enable = "avx2")]
unsafe fn opening_mask(&self) -> __m256i {
_mm256_set1_epi8(self.opening)
}
#[target_feature(enable = "avx2")]
unsafe fn closing_mask(&self) -> __m256i {
_mm256_set1_epi8(self.opening + 2)
}
#[target_feature(enable = "avx2")]
pub(crate) unsafe fn get_opening_and_closing_masks(&self, bytes: &[u8]) -> (u32, u32) {
assert_eq!(32, bytes.len());
// SAFETY: target_feature invariant
unsafe {
let byte_vector = _mm256_loadu_si256(bytes.as_ptr().cast::<__m256i>());
let opening_brace_cmp = _mm256_cmpeq_epi8(byte_vector, self.opening_mask());
let closing_brace_cmp = _mm256_cmpeq_epi8(byte_vector, self.closing_mask());
let opening_mask = _mm256_movemask_epi8(opening_brace_cmp) as u32;
let closing_mask = _mm256_movemask_epi8(closing_brace_cmp) as u32;
(opening_mask, closing_mask)
}
}
}
|
//! Filesystem session
//!
//! A session runs a filesystem implementation while it is being mounted to a specific mount
//! point. A session begins by mounting the filesystem and ends by unmounting it. While the
//! filesystem is mounted, the session loop receives, dispatches and replies to kernel requests
//! for filesystem operations under its mount point.
use libc::{EAGAIN, EINTR, ENODEV, ENOENT};
use log::{info, warn};
use std::fmt;
use std::path::{Path, PathBuf};
use std::thread::{self, JoinHandle};
use std::{io, ops::DerefMut};
use crate::ll::fuse_abi as abi;
use crate::request::Request;
use crate::Filesystem;
use crate::MountOption;
use crate::{channel::Channel, mnt::Mount};
/// The max size of write requests from the kernel. The absolute minimum is 4k,
/// FUSE recommends at least 128k, max 16M. The FUSE default is 16M on macOS
/// and 128k on other systems.
pub const MAX_WRITE_SIZE: usize = 16 * 1024 * 1024;
/// Size of the buffer for reading a request from the kernel. Since the kernel may send
/// up to MAX_WRITE_SIZE bytes in a write request, we use that value plus some extra space.
const BUFFER_SIZE: usize = MAX_WRITE_SIZE + 4096;
#[derive(Debug, Eq, PartialEq)]
pub(crate) enum SessionACL {
All,
RootAndOwner,
Owner,
}
/// The session data structure
#[derive(Debug)]
pub struct Session<FS: Filesystem> {
/// Filesystem operation implementations
pub(crate) filesystem: FS,
/// Communication channel to the kernel driver
ch: Channel,
/// Handle to the mount. Dropping this unmounts.
mount: Option<Mount>,
/// Mount point
mountpoint: PathBuf,
/// Whether to restrict access to owner, root + owner, or unrestricted
/// Used to implement allow_root and auto_unmount
pub(crate) allowed: SessionACL,
/// User that launched the fuser process
pub(crate) session_owner: u32,
/// FUSE protocol major version
pub(crate) proto_major: u32,
/// FUSE protocol minor version
pub(crate) proto_minor: u32,
/// True if the filesystem is initialized (init operation done)
pub(crate) initialized: bool,
/// True if the filesystem was destroyed (destroy operation done)
pub(crate) destroyed: bool,
}
impl<FS: Filesystem> Session<FS> {
/// Create a new session by mounting the given filesystem to the given mountpoint
pub fn new(
filesystem: FS,
mountpoint: &Path,
options: &[MountOption],
) -> io::Result<Session<FS>> {
info!("Mounting {}", mountpoint.display());
// If AutoUnmount is requested, but not AllowRoot or AllowOther we enforce the ACL
// ourself and implicitly set AllowOther because fusermount needs allow_root or allow_other
// to handle the auto_unmount option
let (file, mount) = if options.contains(&MountOption::AutoUnmount)
&& !(options.contains(&MountOption::AllowRoot)
|| options.contains(&MountOption::AllowOther))
{
warn!("Given auto_unmount without allow_root or allow_other; adding allow_other, with userspace permission handling");
let mut modified_options = options.to_vec();
modified_options.push(MountOption::AllowOther);
Mount::new(mountpoint, &modified_options)?
} else {
Mount::new(mountpoint, options)?
};
let ch = Channel::new(file);
let allowed = if options.contains(&MountOption::AllowRoot) {
SessionACL::RootAndOwner
} else if options.contains(&MountOption::AllowOther) {
SessionACL::All
} else {
SessionACL::Owner
};
Ok(Session {
filesystem,
ch,
mount: Some(mount),
mountpoint: mountpoint.to_owned(),
allowed,
session_owner: unsafe { libc::geteuid() },
proto_major: 0,
proto_minor: 0,
initialized: false,
destroyed: false,
})
}
pub fn restore(filesystem: FS, mountpoint: PathBuf, ch: Channel) -> Session<FS> {
Session{
filesystem: filesystem,
ch,
mount: None,
mountpoint: mountpoint,
allowed: SessionACL::All,
session_owner: 0,
proto_major: 0,
proto_minor: 0,
initialized: true,
destroyed: false
}
}
/// Return path of the mounted filesystem
pub fn mountpoint(&self) -> &Path {
&self.mountpoint
}
/// Run the session loop that receives kernel requests and dispatches them to method
/// calls into the filesystem. This read-dispatch-loop is non-concurrent to prevent
/// having multiple buffers (which take up much memory), but the filesystem methods
/// may run concurrent by spawning threads.
pub fn run(&mut self) -> io::Result<()> {
// Buffer for receiving requests from the kernel. Only one is allocated and
// it is reused immediately after dispatching to conserve memory and allocations.
let mut buffer = vec![0; BUFFER_SIZE];
let buf = aligned_sub_buf(
buffer.deref_mut(),
std::mem::align_of::<abi::fuse_in_header>(),
);
loop {
// Read the next request from the given channel to kernel driver
// The kernel driver makes sure that we get exactly one request per read
match self.ch.receive(buf) {
Ok(size) => match Request::new(self.ch.sender(), &buf[..size]) {
// Dispatch request
Some(req) => req.dispatch(self),
// Quit loop on illegal request
None => break,
},
Err(err) => match err.raw_os_error() {
// Operation interrupted. Accordingly to FUSE, this is safe to retry
Some(ENOENT) => continue,
// Interrupted system call, retry
Some(EINTR) => continue,
// Explicitly try again
Some(EAGAIN) => continue,
// Filesystem was unmounted, quit the loop
Some(ENODEV) => break,
// Unhandled error
_ => return Err(err),
},
}
}
Ok(())
}
/// Unmount the filesystem
pub fn unmount(&mut self) {
drop(std::mem::take(&mut self.mount));
}
}
fn aligned_sub_buf(buf: &mut [u8], alignment: usize) -> &mut [u8] {
let off = alignment - (buf.as_ptr() as usize) % alignment;
if off == alignment {
buf
} else {
&mut buf[off..]
}
}
impl<FS: 'static + Filesystem + Send> Session<FS> {
/// Run the session loop in a background thread
pub fn spawn(self) -> io::Result<BackgroundSession> {
BackgroundSession::new(self)
}
}
impl<FS: Filesystem> Drop for Session<FS> {
fn drop(&mut self) {
if !self.destroyed {
self.filesystem.destroy();
self.destroyed = true;
}
info!("Unmounted {}", self.mountpoint().display());
}
}
/// The background session data structure
pub struct BackgroundSession {
/// Path of the mounted filesystem
pub mountpoint: PathBuf,
/// Thread guard of the background session
pub guard: JoinHandle<io::Result<()>>,
/// Ensures the filesystem is unmounted when the session ends
_mount: Mount,
}
impl BackgroundSession {
/// Create a new background session for the given session by running its
/// session loop in a background thread. If the returned handle is dropped,
/// the filesystem is unmounted and the given session ends.
pub fn new<FS: Filesystem + Send + 'static>(
mut se: Session<FS>,
) -> io::Result<BackgroundSession> {
let mountpoint = se.mountpoint().to_path_buf();
// Take the fuse_session, so that we can unmount it
let mount = std::mem::take(&mut se.mount);
let mount = mount.ok_or_else(|| io::Error::from_raw_os_error(libc::ENODEV))?;
let guard = thread::spawn(move || {
let mut se = se;
se.run()
});
Ok(BackgroundSession {
mountpoint,
guard,
_mount: mount,
})
}
/// Unmount the filesystem and join the background thread.
pub fn join(self) {
let Self {
mountpoint: _,
guard,
_mount,
} = self;
drop(_mount);
guard.join().unwrap().unwrap();
}
}
// replace with #[derive(Debug)] if Debug ever gets implemented for
// thread_scoped::JoinGuard
impl<'a> fmt::Debug for BackgroundSession {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(
f,
"BackgroundSession {{ mountpoint: {:?}, guard: JoinGuard<()> }}",
self.mountpoint
)
}
}
|
#![allow(deprecated)]
use murmurhash3::murmurhash3_x86_32;
use rand::random;
type Seed = u32;
fn create_seed() -> Seed {
random()
}
fn hash(key: Seed, item: usize) -> u32 {
let data: [u8; 4] = unsafe { ::std::mem::transmute(item as u32) };
murmurhash3_x86_32(&data, key)
}
pub struct AMSSketch {
k: u32,
data: Vec<Vec<(Seed, isize)>>,
}
#[allow(dead_code)]
impl AMSSketch {
pub fn new(k: u32, lambda: f32, epsilon: f32) -> Self {
let (s1, s2) = Self::attributes(k,lambda, epsilon);
let data = (0..s2)
.map(|_| (0..s1).map(|_| (create_seed(), 0)).collect())
.collect();
AMSSketch { k, data }
}
pub fn attributes(k: u32, lambda: f32, epsilon: f32) -> (usize, usize) {
let s1 = (8.0 * k as f32 / lambda.powi(2)).ceil() as usize;
let s2 = (2.0 * (1.0 / epsilon).ln()).ceil() as usize;
(s1, s2)
}
pub fn update(&mut self, index: usize) {
for list in self.data.iter_mut() {
for (key, count) in list.iter_mut() {
let sign = (hash(*key, index) % 2) as i32 * 2 - 1;
*count += sign as isize;
}
}
}
pub fn estimate(&self) -> f32 {
let mut means = self
.data
.iter()
.map(|col| {
col.iter()
.map(|(_, count)| count.pow(self.k))
.sum::<isize>() as usize
/ col.len()
})
.collect::<Vec<usize>>();
means.sort();
let center = means.len() / 2;
if means.len() % 2 == 1 {
means[center] as f32
} else {
(means[center - 1] + means[center]) as f32 / 2.0
}
}
}
#[cfg(test)]
mod tests {
use crate::ams_sketch::AMSSketch;
use std::collections::HashMap;
use std::error::Error;
use std::fs::File;
use std::io::Write;
struct Tester(HashMap<usize, usize>, u32);
impl Tester {
pub fn new(k: u32) -> Self {
Tester(HashMap::new(), k)
}
pub fn update(&mut self, i: usize) {
let entry = self.0.entry(i).or_insert(0);
*entry += 1;
}
pub fn estimate(&self) -> f32 {
self.0.values().map(|val| val.pow(self.1)).sum::<usize>() as f32
}
}
#[test]
fn test() -> Result<(), Box<dyn Error>> {
test_impl(0.5, 0.1)?;
test_impl(0.6, 0.1)?;
Ok(())
}
fn test_impl(lambda: f32, epsilon: f32) -> Result<(), Box<dyn Error>> {
let count = 500;
let mut runs = Vec::with_capacity(count);
let k = 2;
let (s1, s2) = AMSSketch::attributes(k, lambda, epsilon);
for _ in 0..count {
let mut sketch = AMSSketch::new(k, lambda, epsilon);
let mut tester = Tester::new(k);
for i in 0..100 {
for _ in 0..10 {
sketch.update(i);
tester.update(i);
}
}
let ams_estimate = sketch.estimate();
let actual = tester.estimate();
runs.push((ams_estimate, actual));
}
let median_error = {
let mut runs = runs
.iter()
.map(|(ams, det)| (ams - det).abs() as u32)
.collect::<Vec<_>>();
runs.sort();
runs[runs.len() / 2]
};
let error_proportion = runs
.iter()
.filter(|(ams, det)| {
let error_dist = det * lambda;
(ams - det).abs() > error_dist
})
.count()
/ runs.len();
{
let mut output = File::create(format!(
"test_results/k_{}_lambda_{}_epsilon_{}.csv",
k, lambda, epsilon
))?;
writeln!(output, "estimate,actual")?;
for (ams_estimate, actual) in runs {
writeln!(output, "{},{}", ams_estimate, actual)?;
}
}
println!(
"{} runs with λ = {}, ε = {} (buckets = {}, copies = {})",
count, lambda, epsilon, s1, s2
);
println!(
"median error {}, error proportion {}",
median_error, error_proportion
);
Ok(())
}
}
|
use std::ops;
use std::collections::{HashMap, HashSet};
use super::utils::{tf_data_type_to_rust, wrap_type, join_vec, type_to_string};
use tensorflow_protos::types::DataType;
use codegen as cg;
pub(crate) trait AddToImpl {
fn add_to_impl(&self, impl_: &mut OpImpl, lib: &mut OpLib) -> Result<(), String>;
}
pub(crate) trait AddToLib {
fn add_to_lib(&self, lib: &mut OpLib) -> Result<(), String>;
}
pub(crate) struct OpLib {
// Maps sets of allowed types to traits that constrain to those types
type_constraint_traits: HashMap<Vec<DataType>, String>,
scope: cg::Scope,
}
impl OpLib {
pub(crate) fn new() -> Self {
let mut lib = Self {
type_constraint_traits: HashMap::new(),
scope: cg::Scope::new(),
};
lib.scope.import("super::graph", "Graph");
lib.scope.import("super::graph", "GraphOperation");
lib.scope.import("super::graph", "Operation");
lib.scope.import("super::graph", "Edge");
lib.scope.import("super::graph", "RefEdge");
lib.scope.import("super::graph", "GraphEdge");
lib.scope.import("super::graph", "GraphRefEdge");
lib.scope.import("super", "Shape as OtherShape");
lib.scope.import("super", "new_id");
lib.scope.import("super", "TensorType");
lib.scope.import("super", "BFloat16");
lib.scope.import("super", "Tensor");
lib.scope.import("super", "AnyTensor");
lib.scope.import("num_complex", "Complex as OtherComplex");
lib.scope.import("std::rc", "Rc");
lib.scope.import("std", "f32");
lib.scope.import("std", "f64");
lib.scope.import("std::convert", "From");
lib.scope.import("std::marker", "PhantomData");
lib.scope.import("super", "Result");
lib
}
fn contraint_name(allowed_types: &Vec<DataType>) -> String {
allowed_types.iter().fold("con".to_string(), |acc, x| format!("{}_or_{:?}", acc, x))
}
pub(crate) fn contraint_trait(&mut self, mut allowed_types: Vec<DataType>) -> Result<String, String> {
allowed_types.sort_by_key(|a| *a as u32);
if let Some(x) = self.type_constraint_traits.get(&allowed_types) {
return Ok(x.to_string());
}
let new_constraint_name = OpLib::contraint_name(&allowed_types);
self.scope.new_trait(&new_constraint_name).vis("pub");
let mut dtypes: Vec<String> = allowed_types.iter()
.filter_map(|x| {
if let Ok(x) = tf_data_type_to_rust(*x) {
Some(x)
} else {
None
}
})
.collect();
dtypes.sort();
dtypes.dedup();
for dtype in dtypes {
self.scope.new_impl(&dtype)
.impl_trait(&new_constraint_name);
}
self.type_constraint_traits.insert(allowed_types, new_constraint_name.clone());
Ok(new_constraint_name)
}
pub(crate) fn string(&self) -> String {
self.scope.to_string()
}
}
/// Represents a struct for building an operation, builders must have static lifetime
/// becuase they get put in an RC, so no lifetime parameters
pub(crate) struct Builder {
name: String,
pub(crate) struct_: cg::Struct,
pub(crate) impl_: cg::Impl,
pub(crate) impl_graph_operation: cg::Impl,
pub(crate) new_fn: cg::Function,
pub(crate) direct_new_fn: cg::Function,
pub(crate) make_self: cg::Block,
pub(crate) op_description_setup: Vec<cg::Block>,
outputs: Vec<(cg::Type, cg::Block, String)>,
// Name used by tensorflow
op_name: String,
}
/// Wrapper around cg::Function as cg::Function does not allow access to the return type once
/// it's been set
#[derive(Clone)]
pub(crate) struct Function {
func: cg::Function,
name: String,
ret: Option<cg::Type>,
}
impl ops::Deref for Function {
type Target = cg::Function;
fn deref(&self) -> &Self::Target {
&self.func
}
}
impl ops::DerefMut for Function {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.func
}
}
impl Into<cg::Function> for Function {
fn into(self) -> cg::Function {
self.func
}
}
impl AsRef<cg::Function> for Function {
fn as_ref(&self) -> &cg::Function {
&self.func
}
}
impl Function {
pub(crate) fn new(name: &str) -> Self {
Self {
func: cg::Function::new(name),
name: name.to_string(),
ret: None,
}
}
pub(crate) fn ret<T: Into<cg::Type>>(&mut self, ret: T) -> &mut Self {
let ret_copy = ret.into();
self.func.ret(&ret_copy);
self.ret = Some(ret_copy);
self
}
fn get_ret(&self) -> cg::Type {
match self.ret {
Some(ref ty) => ty.clone(),
None => cg::Type::new("()"),
}
}
}
/// Represents a struct for using the operation once it's added to a graph
// #[derive(Clone)]
// pub(crate) struct Finished {
// name: String,
// struct_: cg::Struct,
// impl_: cg::Impl,
// outputs: Vec<Function>,
// }
pub(crate) struct OpImpl {
pub(crate) builder: Builder,
generics: HashSet<String>,
phantoms: HashSet<String>,
bounds: HashSet<(String, String)>,
}
impl Builder {
fn new(name: &str, op_name: &str) -> Self {
Self {
name: name.to_string(),
struct_: cg::Struct::new(name),
impl_: cg::Impl::new(name),
impl_graph_operation: cg::Impl::new(name),
new_fn: cg::Function::new("build"),
direct_new_fn: cg::Function::new("new"),
make_self: cg::Block::new("Self"),
op_description_setup: Vec::new(),
op_name: op_name.to_string(),
outputs: Vec::new(),
}
}
/// Do the operation description setup to add the operation to a graph
fn make_op(&self) -> Result<cg::Function, String> {
let mut make_op = cg::Function::new("tf_operation");
make_op.arg_ref_self()
.arg("graph", format!("&mut Graph"))
.ret(format!("Result<Operation>"))
.line("if let Some(x) = graph.get_op_by_id(self.get_id()) {")
.line(" return Ok(x);")
.line("}")
.line("let op_name = match &self.op_name {")
.line(" Some(name) => name.clone(),")
.line(format!(" None => graph.new_op_name(\"{}_{{}}\")?", &self.op_name))
.line("};")
.line("let mut control_inputs = Vec::new();")
.line("for control_input in self.control_inputs.iter() {")
.line(" control_inputs.push(control_input.tf_operation(graph)?);")
.line("}")
.line(format!("let mut new_op = graph.new_operation(\"{}\", &op_name)?;", &self.op_name))
.line("for control_input in control_inputs {")
.line(" new_op.add_control_input(&control_input)")
.line("}");
for block in &self.op_description_setup {
make_op.push_block(block.clone());
}
make_op.line("let op = new_op.finish()?;");
make_op.line("graph.record_op(self.get_id(), op.clone());");
make_op.line("Ok(op)");
Ok(make_op)
}
/// Implement the GraphOperation trait for adding to a graph
fn graph_operation_impl(&mut self) -> Result<cg::Impl, String> {
self.impl_.new_fn("get_id")
.arg_ref_self()
.ret("usize")
.line("self.id_");
let mut graph_operation_impl = self.impl_graph_operation.clone();
graph_operation_impl.impl_trait("GraphOperation");
graph_operation_impl.push_fn(self.make_op()?);
Ok(graph_operation_impl)
}
fn finish_ret(&self) -> cg::Type {
if self.outputs.len() == 1 {
return self.outputs[0].0.clone();
}
let rets = self.outputs.iter().map(|x| type_to_string(&x.0).unwrap()).collect();
format!("({})", join_vec(&rets, ", ")).into()
}
/// Make the finish function for turning the builder into the real op
fn make_finish(&self) -> Result<cg::Function, String> {
let mut make_finish = cg::Function::new("finish");
make_finish.ret(self.finish_ret())
.arg_self()
.vis("pub")
.line("let rc = Rc::new(self);");
if self.outputs.len() != 1 {
make_finish.line("(");
for output in &self.outputs {
let mut blk = output.1.clone();
blk.after(",");
make_finish.push_block(blk);
}
make_finish.line(")");
} else {
make_finish.push_block(self.outputs[0].1.clone());
}
Ok(make_finish)
}
/// Allow the user to give the op a meaningful name
fn add_optional_name(&mut self) {
self.struct_.field("op_name", "Option<String>");
self.make_self.line("op_name: None,");
self.impl_.new_fn("op_name")
.vis("pub")
.arg_mut_self()
.arg("op_name", "&str")
.ret("&mut Self")
.line("self.op_name = Some(op_name.to_string());")
.line("self");
}
fn add_control_inputs(&mut self) {
self.struct_.field("control_inputs", "Vec<Rc<dyn GraphOperation>>");
self.make_self.line("control_inputs: Vec::new(),");
self.impl_.new_fn("control_input")
.vis("pub")
.arg_mut_self()
.generic("ControlInputT")
.bound("ControlInputT", "GraphOperation")
.bound("ControlInputT", "Clone")
.bound("ControlInputT", "'static")
.arg("control_input", "ControlInputT")
.ret("&mut Self")
.line("self.control_inputs.push(Rc::new(control_input.clone()));")
.line("self");
}
fn generic(&mut self, ty: &str) {
self.struct_.generic(ty);
self.impl_.generic(ty);
self.impl_.target_generic(ty);
self.impl_graph_operation.generic(ty);
self.impl_graph_operation.target_generic(ty);
}
fn bound(&mut self, ty: &str, bound: &str) {
self.struct_.bound(ty, bound);
self.impl_.bound(ty, bound);
self.impl_graph_operation.bound(ty, bound);
}
fn phantom(&mut self, ty: &str) {
let field_name = &format!("phantom_{}", ty);
self.struct_.field(field_name, &format!("PhantomData<{}>", ty));
self.make_self.line(&format!("{}: PhantomData,", field_name));
}
pub(crate) fn add_builder_fn(&mut self, mut func: cg::Function) {
// Ideally would take "mut self" and avoid the clone but
// codegen doesn't currently support that
func.ret("Self")
.arg_mut_self()
.vis("pub")
.line("self.clone()");
self.impl_.push_fn(func);
}
pub(crate) fn add_op_description_setup(&mut self, block: cg::Block) {
self.op_description_setup.push(block);
}
fn add_output(&mut self, ty: cg::Type, block: cg::Block, name: &str) {
let mut output_fn = cg::Function::new(name);
output_fn.arg_self()
.vis("pub")
.ret((&ty).clone())
.line("let rc = Rc::new(self);")
.push_block((&block).clone());
self.impl_.push_fn(output_fn);
self.outputs.push((ty, block, name.to_string()));
}
pub(crate) fn new_fn_arg(&mut self, name: &str, ty: &cg::Type) {
self.new_fn.arg(name, ty);
self.direct_new_fn.arg(name, ty);
}
pub(crate) fn new_fn_generic(&mut self, name: &str) {
self.new_fn.generic(name);
self.direct_new_fn.generic(name);
}
pub(crate) fn new_fn_bound(&mut self, name: &str, bound: &str) {
self.new_fn.bound(name, bound);
self.direct_new_fn.bound(name, bound);
}
fn setup_direct_new(&mut self) {
let finish_ret = self.finish_ret();
let mut make_self = self.make_self.clone();
make_self.after(".finish()");
self.direct_new_fn.vis("pub")
.ret(finish_ret)
.push_block(make_self);
}
/// Add all the generated code to the scope
fn finish(mut self, scope: &mut cg::Scope) -> Result<(), String> {
self.add_optional_name();
self.add_control_inputs();
scope.push_impl(self.graph_operation_impl()?);
self.impl_.push_fn(self.make_finish()?);
self.new_fn.ret("Self")
.vis("pub");
self.struct_.field("id_", "usize")
.vis("pub");
self.make_self.line("id_: new_id(),");
self.struct_.derive("Clone");
self.setup_direct_new();
self.new_fn.push_block(self.make_self);
self.impl_.push_fn(self.new_fn);
self.impl_.push_fn(self.direct_new_fn);
scope.push_struct(self.struct_);
scope.push_impl(self.impl_);
Ok(())
}
}
impl OpImpl {
pub(crate) fn new(name: &str) -> Self {
Self {
builder: Builder::new(name, name),
generics: HashSet::new(),
phantoms: HashSet::new(),
bounds: HashSet::new(),
}
}
pub(crate) fn finish(self, lib: &mut OpLib) -> Result<(), String> {
self.builder.finish(&mut lib.scope)?;
Ok(())
}
pub(crate) fn generic(&mut self, ty: &str) {
if self.generics.contains(ty) {
return;
}
self.generics.insert(ty.to_string());
self.builder.generic(ty);
}
pub(crate) fn phantom(&mut self, ty: &str) {
if self.phantoms.contains(ty) {
return;
}
self.phantoms.insert(ty.to_string());
self.builder.phantom(ty);
}
pub(crate) fn bound(&mut self, ty: &str, bound: &str) {
if self.bounds.contains(&(ty.to_string(), bound.to_string())) {
return;
}
self.bounds.insert((ty.to_string(), bound.to_string()));
self.builder.bound(ty, bound);
}
pub(crate) fn add_output(&mut self, ty: cg::Type, block: cg::Block, name: &str) {
self.builder.add_output(ty, block, name)
}
}
|
use time;
use super::{Listener, DistanceModel, SoundEvent, Gain, SoundName, SoundProviderResult};
use super::context::{SoundContext};
use super::source::SoundSourceLoan;
use super::errors::*;
use puck_core::{HashMap, Vec3f};
use cgmath::{Zero};
#[derive(Debug, Clone)]
pub struct SoundRender {
pub master_gain: f32,
pub sounds:Vec<SoundEvent>,
pub persistent_sounds:HashMap<String, SoundEvent>,
pub listener: Listener
}
impl SoundRender {
pub fn non_positional_effects(sounds:Vec<SoundEvent>) -> SoundRender {
SoundRender {
master_gain: 1.0,
sounds: sounds,
persistent_sounds: HashMap::default(),
listener: Listener {
position: Vec3f::zero(),
velocity: Vec3f::zero(),
orientation_up: Vec3f::zero(),
orientation_forward: Vec3f::zero(),
}
}
}
}
#[derive(Debug, Clone)]
pub enum SoundEngineUpdate {
Preload(Vec<(SoundName, Gain)>), // load buffers
DistanceModel(DistanceModel),
Render(SoundRender),
Clear, // unbind all sources, destroy all buffers,
Stop,
}
// we need our state of what's already persisted, loans etc.
pub struct SoundEngine {
// some notion of existing sounds
pub last_render_time: u64,
pub loans : HashMap<String, SoundSourceLoan>,
}
impl SoundEngine {
pub fn new() -> SoundEngine {
SoundEngine {
last_render_time: time::precise_time_ns(),
loans: HashMap::default(),
}
}
pub fn process(&mut self, context: &mut SoundContext, update:SoundEngineUpdate) -> SoundProviderResult<bool> { // book is over clean shutdown
use self::SoundEngineUpdate::*;
let should_continue = match update {
Preload(sounds) => {
for (sound_name, gain) in sounds {
match context.preload(&sound_name, gain) {
Ok(_) => (),
Err(err) => {
println!("Sound Worker failed to preload {:?} err -> {:?}", sound_name, err);
()
},
}
}
true
},
DistanceModel(model) => {
context.set_distace_model(model)?;
true
},
Render(render) => {
// { master_gain, sounds, persistent_sounds, listener }
try!(context.sources.check_bindings());
match context.ensure_buffers_queued() {
Ok(_) => (),
Err(PreloadError::LoadError(le)) => println!("Sound worker received load error while ensuring buffers are queued {:?}", le),
Err(PreloadError::SoundProviderError(sp)) => return Err(sp),
}
if context.master_gain != render.master_gain {
try!(context.set_gain(render.master_gain));
}
if context.listener != render.listener {
try!(context.set_listener(render.listener));
}
for sound_event in render.sounds {
match context.play_event(sound_event.clone(), None) {
Ok(_) => (),
Err(SoundEventError::SoundProviderError(sp)) => return Err(sp),
Err(err) => println!("Sound Worker had problem playing sound_event {:?} err -> {:?}", sound_event, err),
}
}
for (name, sound_event) in render.persistent_sounds {
let old_loan = self.loans.remove(&name);
match context.play_event(sound_event.clone(), old_loan) {
Ok(new_loan) => {
self.loans.insert(name, new_loan);
},
Err(SoundEventError::SoundProviderError(sp)) => return Err(sp),
Err(err) => println!("Sound Worker had problem playing sound_event {:?} err -> {:?}", sound_event, err),
}
}
true
},
Clear => {
try!(context.purge());
true
},
Stop => {
try!(context.purge());
false
}
};
Ok(should_continue)
}
}
|
use crate::isa::{IsaResult, IsaError, SnesOffset};
/// A struct representing the encoding state.
pub struct EncodeCursor<'a> {
offset: usize,
data: &'a mut Vec<u8>,
}
impl <'a> EncodeCursor<'a> {
pub fn new(data: &'a mut Vec<u8>) -> Self {
EncodeCursor { offset: 0, data }
}
pub fn seek(&mut self, offset: usize) {
if offset > self.data.len() {
panic!("Offset out of bounds.")
}
self.offset = offset;
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn offset(&self) -> usize {
self.offset
}
pub fn push_byte(&mut self, byte: u8) {
if self.offset >= self.data.len() {
self.data.push(byte);
} else {
self.data[self.offset] = byte;
}
self.offset += 1;
}
}
/// A struct representing the decoding state.
pub struct DecodeCursor<'a> {
offset: usize,
data: &'a [u8],
}
impl <'a> DecodeCursor<'a> {
pub fn new(data: &'a [u8]) -> Self {
DecodeCursor { offset: 0, data }
}
pub fn seek(&mut self, offset: usize) {
if offset >= self.data.len() {
panic!("Offset out of bounds.")
}
self.offset = offset;
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn offset(&self) -> usize {
self.offset
}
pub fn pull_byte(&mut self) -> IsaResult<u8> {
if let Some(v) = self.data.get(self.offset) {
self.offset += 1;
Ok(*v)
} else {
Err(IsaError::Eof)
}
}
pub fn pull_bytes(&mut self, count: usize) -> IsaResult<&[u8]> {
if let Some(slice) = self.data.get(self.offset..self.offset + count) {
self.offset += count;
Ok(slice)
} else {
Err(IsaError::Eof)
}
}
}
/// A struct representing the context an instruction is being decoded in.
pub struct DecodeContext {
/// State of the 6502 emulation flag.
pub emulation_mode: bool,
/// State of the M flag
pub a_8_bit: bool,
/// State of the X flag
pub xy_8_bit: bool,
}
/// A trait representing the encoding of an instruction to machine code.
pub trait Encoder {
/// The type this encoder encodes to.
type Target: Copy;
/// Encode an instruction to machine code.
fn encode(v: Self::Target, w: &mut EncodeCursor<'_>) -> IsaResult<()>;
/// Decode an instruction from machine code.
fn decode(r: &mut DecodeCursor<'_>, _: &DecodeContext) -> IsaResult<Self::Target>;
/// The length of this instruction.
fn instruction_len(v: Self::Target) -> u8;
}
impl Encoder for u8 {
type Target = Self;
fn encode(v: Self::Target, w: &mut EncodeCursor<'_>) -> IsaResult<()> {
w.push_byte(v);
Ok(())
}
fn decode(r: &mut DecodeCursor<'_>, _: &DecodeContext) -> IsaResult<Self::Target> {
Ok(r.pull_byte()?)
}
fn instruction_len(_: Self::Target) -> u8 {
1
}
}
impl Encoder for u16 {
type Target = Self;
fn encode(v: Self::Target, w: &mut EncodeCursor<'_>) -> IsaResult<()> {
w.push_byte(v as u8);
w.push_byte((v >> 8) as u8);
Ok(())
}
fn decode(r: &mut DecodeCursor<'_>, _: &DecodeContext) -> IsaResult<Self::Target> {
let bytes = r.pull_bytes(2)?;
Ok(bytes[0] as u16 | ((bytes[1] as u16) << 8))
}
fn instruction_len(_: Self::Target) -> u8 {
2
}
}
impl Encoder for SnesOffset {
type Target = Self;
fn encode(v: Self::Target, w: &mut EncodeCursor<'_>) -> IsaResult<()> {
u16::encode(v.1, w)?;
u8::encode(v.0, w)?;
Ok(())
}
fn decode(r: &mut DecodeCursor<'_>, _: &DecodeContext) -> IsaResult<Self::Target> {
let bytes = r.pull_bytes(3)?;
let offset = bytes[0] as u16 | ((bytes[1] as u16) << 8);
Ok(SnesOffset(bytes[2], offset))
}
fn instruction_len(_: Self::Target) -> u8 {
3
}
}
/// A trait representing a table of opcodes.
pub trait OpcodeTable: Sized {
fn op(self, base: u8) -> u8;
fn encode_operands(self, _: &mut EncodeCursor<'_>) -> IsaResult<()>;
}
/// A trait representing a decodable instruction.
pub trait InstructionType: Sized + Copy + Encoder<Target = Self> {
/// Encode an instruction to machine code.
fn encode(self, w: &mut EncodeCursor<'_>) -> IsaResult<()> {
<Self as Encoder>::encode(self, w)
}
/// Decode an instruction from machine code.
fn decode(w: &mut DecodeCursor<'_>, ctx: &DecodeContext) -> IsaResult<Self> {
<Self as Encoder>::decode(w, ctx)
}
/// The length of this instruction.
fn instruction_len(self) -> u8 {
<Self as Encoder>::instruction_len(self)
}
}
/// The function type used in decode tables.
pub(crate) type DecodeFn<T> = fn(&mut DecodeCursor<'_>, &DecodeContext) -> IsaResult<T>;
/// The array type used for decode tables.
pub(crate) type DecodeTable<T> = [DecodeFn<T>; 256];
/// The trait used to map decode tables.
pub(crate) trait DecodeMap<A> {
type Into;
fn apply(a: A, r: &mut DecodeCursor<'_>, ctx: &DecodeContext) -> IsaResult<Self::Into>;
}
/// A null [`DecodeMap`].
pub(crate) enum NullDecodeMap { }
impl <A> DecodeMap<A> for NullDecodeMap {
type Into = A;
fn apply(a: A, _: &mut DecodeCursor<'_>, _: &DecodeContext) -> IsaResult<Self::Into> {
Ok(a)
}
}
/// A helper macro for simple ISAs with an opcode followed by operands.
macro_rules! isa_instruction_table {
(@encode $ty:ty, $val:expr, $r:expr) => {
<$ty as crate::isa::encoding::Encoder>::encode($val, $r)
};
(@encode_op $ty:ty, $val:expr, $r:expr) => {
$val.__isa_encode_subtable($r)
};
(@parse_inner_common
[$s1:ident $s2:ident $s3:ident $enum_name:ident ($vis:vis) $metas:tt
[$($enum_contents:tt)*]
$op_impl:tt
[$($encode_impl:tt)*]
$decode_impl:tt
[$($len_impl:tt)*]]
[$($rest:tt)*]
$opcode:literal $instr:ident $add_len:literal $(($($enc:ident $name:ident: $ty:ty,)*))?
) => {
isa_instruction_table!(@parse
[
$s1 $s2 $s3 $enum_name ($vis) $metas
[
$($enum_contents)*
$instr $(($(<$ty as crate::isa::encoding::Encoder>::Target,)*))?,
]
$op_impl
[
$($encode_impl)*
$enum_name::$instr $(($($name,)*))? => {
$($(
isa_instruction_table!(@$enc $ty, $name, $s1)?;
)*)?
},
]
$decode_impl
[
$($len_impl)*
$enum_name::$instr $(($($name,)*))? => {
$add_len $($(
+ (<$ty as crate::isa::encoding::Encoder>::instruction_len($name))
)*)?
},
]
]
[$($rest)*]
);
};
(@parse_inner
[$s1:ident $s2:ident $s3:ident $enum_name:ident ($vis:vis) $metas:tt
$enum_contents:tt
[$($op_impl:tt)*]
$encode_impl:tt
[$($decode_impl:tt)*]
$len_impl:tt]
[$($rest:tt)*]
$opcode:literal $instr:ident
$(($($name:ident: $ty:ty),*))?
) => {
isa_instruction_table!(@parse_inner_common
[
$s1 $s2 $s3 $enum_name ($vis) $metas
$enum_contents
[$($op_impl)* $enum_name::$instr $(($($name,)*))? => $opcode,]
$encode_impl
[
$($decode_impl)*
{
fn make_fn<M: crate::isa::encoding::DecodeMap<$enum_name>>(
r: &mut crate::isa::encoding::DecodeCursor<'_>,
ctx: &crate::isa::encoding::DecodeContext,
) -> crate::isa::IsaResult<M::Into> {
M::apply($enum_name::$instr $(($(
<$ty as crate::isa::encoding::Encoder>::decode(r, ctx)?,
)*))?, r, ctx)
}
$s1[$s3.wrapping_add($opcode) as usize] = make_fn::<$s2>;
}
]
$len_impl
]
[$($rest)*]
$opcode $instr 1 $(($(encode $name: $ty,)*))?
);
};
(@parse_inner_subtable
[$s1:ident $s2:ident $s3:ident $enum_name:ident ($vis:vis) $metas:tt
$enum_contents:tt
[$($op_impl:tt)*]
$encode_impl:tt
[$($decode_impl:tt)*]
$len_impl:tt]
[$($rest:tt)*]
$opcode:literal $instr:ident ($subt_name:ident: $subt_ty:ty)
($($name:ident: $ty:ty),*)
) => {
isa_instruction_table!(@parse_inner_common
[
$s1 $s2 $s3 $enum_name ($vis) $metas
$enum_contents
[
$($op_impl)*
$enum_name::$instr ($subt_name, $($name,)*) => $subt_name.__isa_op($opcode),
]
$encode_impl
[
$($decode_impl)*
{
struct Map<M>(M);
impl <M: crate::isa::encoding::DecodeMap<$enum_name>>
crate::isa::encoding::DecodeMap<$subt_ty> for Map<M>
{
type Into = M::Into;
fn apply(
m: $subt_ty,
r: &mut crate::isa::encoding::DecodeCursor<'_>,
ctx: &crate::isa::encoding::DecodeContext,
) -> crate::isa::IsaResult<M::Into> {
M::apply($enum_name::$instr (m, $(
<$ty as crate::isa::encoding::Encoder>::decode(r, ctx)?,
)*), r, ctx)
}
}
$s1 = <$subt_ty>::__isa_create_decode_table::<Map<$s2>>(
$s1, $s3.wrapping_add($opcode),
);
}
]
$len_impl
]
[$($rest)*]
$opcode $instr 0 (encode_op $subt_name: $subt_ty, $(encode $name: $ty,)*)
);
};
(@parse $state:tt [$opcode:literal $instr:ident, $($rest:tt)*]) => {
isa_instruction_table!(@parse_inner $state [$($rest)*] $opcode $instr);
};
(@parse $state:tt [$opcode:literal $instr:ident($a:ty), $($rest:tt)*]) => {
isa_instruction_table!(@parse_inner $state [$($rest)*]
$opcode $instr (_a: $a)
);
};
(@parse $state:tt [$opcode:literal $instr:ident($a:ty, $b:ty), $($rest:tt)*]) => {
isa_instruction_table!(@parse_inner $state [$($rest)*]
$opcode $instr (_a: $a, _b: $b)
);
};
(@parse $state:tt [$opcode:literal $instr:ident(subtable $a:ty), $($rest:tt)*]) => {
isa_instruction_table!(@parse_inner_subtable $state [$($rest)*]
$opcode $instr (_a: $a) ()
);
};
(@parse $state:tt [$opcode:literal $instr:ident(subtable $a:ty, $b:ty), $($rest:tt)*]) => {
isa_instruction_table!(@parse_inner_subtable $state [$($rest)*]
$opcode $instr (_a: $a) (_b: $b)
);
};
(@parse
[$s1:ident $s2:ident $s3:ident $name:ident ($vis:vis) ($(#[$meta:meta])*)
[$($enum_contents:tt)*]
[$($op_impl:tt)*]
[$($encode_impl:tt)*]
[$($decode_impl:tt)*]
[$($len_impl:tt)*]]
[]
) => {
$(#[$meta])*
#[derive(Copy, Clone, Ord, PartialOrd, PartialEq, Eq, Debug, Hash)]
$vis enum $name {
$($enum_contents)*
}
impl $name {
#[doc(hidden)]
pub(crate) fn __isa_op(self, base: u8) -> u8 {
base.wrapping_add(match self { $($op_impl)* })
}
#[doc(hidden)]
pub(crate) fn __isa_encode_subtable(
self, $s1: &mut crate::isa::encoding::EncodeCursor<'_>,
) -> crate::isa::IsaResult<()> {
match self { $($encode_impl)* }
Ok(())
}
#[allow(non_camel_case_types)]
#[doc(hidden)]
pub(crate) const fn __isa_create_decode_table<
$s2: crate::isa::encoding::DecodeMap<$name>,
>(
mut $s1: crate::isa::encoding::DecodeTable<$s2::Into>,
$s3: u8,
) -> crate::isa::encoding::DecodeTable<$s2::Into> {
$($decode_impl)*
$s1
}
}
impl crate::isa::encoding::Encoder for $name {
type Target = $name;
fn encode(
v: $name, w: &mut crate::isa::encoding::EncodeCursor<'_>,
) -> crate::isa::IsaResult<()> {
w.push_byte(v.__isa_op(0));
v.__isa_encode_subtable(w)
}
fn decode(
r: &mut crate::isa::encoding::DecodeCursor<'_>,
ctx: &crate::isa::encoding::DecodeContext,
) -> crate::isa::IsaResult<$name> {
const OP_TABLE: crate::isa::encoding::DecodeTable<$name> = {
let table: crate::isa::encoding::DecodeTable<$name> = [
|_, _| Err(crate::isa::IsaError::InvalidInstruction); 256
];
$name::__isa_create_decode_table::<crate::isa::encoding::NullDecodeMap>(
table, 0,
)
};
OP_TABLE[r.pull_byte()? as usize](r, ctx)
}
fn instruction_len(v: $name) -> u8 {
match v { $($len_impl)* }
}
}
};
($($(#[$meta:meta])* $vis:vis table $name:ident { $($body:tt)* })*) => {$(
isa_instruction_table!(@parse
[_s1 _s2 _s3 $name ($vis) ($(#[$meta])*) [] [] [] [] []]
[$($body)*]
);
)*};
} |
#![deny(unused_extern_crates)]
#![warn(
clippy::all,
clippy::nursery,
clippy::pedantic,
future_incompatible,
missing_copy_implementations,
// missing_docs,
nonstandard_style,
rust_2018_idioms,
trivial_casts,
trivial_numeric_casts,
unreachable_pub,
unused_qualifications
)]
#[allow(clippy::redundant_pub_crate)]
mod thumb;
use crate::thumb::Thumb;
use yew::prelude::*;
const NAMES: [&str; 11] = [
"gimme_pizza",
"hey_are_you_ready_to_play",
"p-i-z-z-a",
"um_did_i_happen_to_say",
"finger_lickin",
"whipped_cream",
"pizza_pie",
"caramel",
"spaghetti",
"pasta",
"uh",
];
struct App;
impl Component for App {
type Message = ();
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {
<>
<header id="page_header">
<h1>{ "put it in the pizza." }</h1>
<p>{ "(click a pic)" }</p>
</header>
<article id="page_content">
<table>
<tr>
<Thumb name={ NAMES[0] } text="gimme pizza" />
<Thumb name={ NAMES[1] } text="are you ready?" />
<Thumb name={ NAMES[2] } text="p-i-z-z-a" />
<Thumb name={ NAMES[3] } text="did i happen to say?" />
</tr>
<tr>
<Thumb name={ NAMES[4] } text="finger lickin'" />
<Thumb name={ NAMES[5] } text="whipped cream pourin'" />
<Thumb name={ NAMES[6] } text="fly fly pizza pie" />
<Thumb name={ NAMES[7] } text="caramel coconut cream" />
</tr>
<tr>
<Thumb name={ NAMES[8] } text="1 2 3 4 5 spaghetti" />
<Thumb name={ NAMES[9] } text="pasta, fishsticks, ketchup, meatloaf" />
<Thumb name={ NAMES[10] } text="uhh... put it in the pizza" />
<td></td>
</tr>
</table>
</article>
<footer id="page_footer">
{ "inspired by" }
<a href="http://www.youtube.com/watch?v=wusGIl3v044">{ "this." }</a>
</footer>
</>
}
}
}
fn main() {
yew::start_app::<App>();
}
|
use amethyst::{
ecs::{Join, Read, ReadStorage, System, WriteStorage},
input::InputHandler,
};
use crate::component::{Direction, Paddle};
pub struct PaddleSystem;
impl<'s> System<'s> for PaddleSystem {
type SystemData = (
ReadStorage<'s, Paddle>,
WriteStorage<'s, Direction>,
Read<'s, InputHandler<String, String>>,
);
fn run(&mut self, (paddles, mut directions, input): Self::SystemData) {
for (dir, paddle) in (&mut directions, &paddles).join() {
let movement = input.axis_value("move");
if let Some(mv_amount) = movement {
dir.0[0] = paddle.speed * mv_amount as f32;
}
}
}
}
|
use anyhow::Result;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum TomlError {
#[error("\"{0}\" section could not be found in your config. Add it with [{0}]")]
SectionNotFound(String),
#[error("The language \"{0}\" could not be found in your config.")]
LanguageNotFound(String),
#[error("The value of \"{0}\" is an invalid type, expected String")]
InvalidType(String),
}
fn base_toml_checks(toml_value: &toml::Value) -> Result<(), TomlError> {
let toml_table_unwraped = toml_value.as_table().unwrap();
if !toml_table_unwraped.contains_key("templates") {
return Err(TomlError::SectionNotFound("templates".into()));
}
Ok(())
}
fn get_table<'a>(
toml_value: &toml::Value,
name: &str,
) -> Result<toml::map::Map<String, toml::Value>, TomlError> {
let templates = match toml_value[name].as_table() {
Some(table) => table,
None => return Err(TomlError::SectionNotFound(name.into())),
};
Ok(templates.to_owned())
}
fn extract_language_value<'a, T>(
table: &toml::map::Map<String, toml::Value>,
lang_name: &str,
) -> Result<T, TomlError>
where
T: toml::macros::Deserialize<'a>,
{
if !table.contains_key(lang_name) {
return Err(TomlError::LanguageNotFound(lang_name.into()));
}
match table[lang_name].to_owned().try_into::<T>() {
Ok(val) => Ok(val),
Err(_) => Err(TomlError::InvalidType(lang_name.into())),
}
}
pub enum CommandVariants {
Before,
After,
}
impl ToString for CommandVariants {
fn to_string(&self) -> String {
match self {
Self::Before => "commands-before",
Self::After => "commands-after",
}
.into()
}
}
pub fn get_commands(
toml_value: &toml::Value,
lang_name: &str,
variant: CommandVariants,
) -> Result<Option<Vec<String>>, TomlError> {
base_toml_checks(toml_value)?;
if !toml_value
.as_table()
.unwrap()
.contains_key(&variant.to_string())
{
return Ok(None);
}
let commands = get_table(toml_value, &variant.to_string())?;
match extract_language_value(&commands, lang_name) {
Ok(commands) => Ok(Some(commands)),
Err(_) => Ok(None),
}
}
pub fn get_lang_location(toml_value: &toml::Value, lang_name: &str) -> Result<String, TomlError> {
base_toml_checks(toml_value)?;
let templates = get_table(toml_value, "templates")?;
let language = extract_language_value(&templates, lang_name)?;
Ok(language)
}
|
mod utils;
mod websocket;
use serde::{Deserialize, Serialize};
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};
use pacosako::{
analysis::{self, puzzle, ReplayData},
editor, fen,
setup_options::SetupOptions,
PacoAction, PacoBoard, PacoError,
};
/// This module provides all the methods that should be available on the wasm
/// version of the library. Any encoding & decoding is handled in here.
#[wasm_bindgen]
extern "C" {
fn forwardToMq(messageType: &str, data: &str);
}
#[wasm_bindgen(js_name = "generateRandomPosition")]
pub fn generate_random_position(data: String) -> Result<(), JsValue> {
// We are expecting a json string which just encodes an integer.
let tries: u32 = serde_json::from_str(&data).map_err(|e| e.to_string())?;
let fen = format!(
"{{ \"board_fen\": \"{}\" }}",
fen::write_fen(&editor::random_position(tries).map_err(|e| e.to_string())?)
);
forwardToMq("randomPositionGenerated", &fen);
Ok(())
}
#[derive(Deserialize)]
struct AnalyzePositionData {
board_fen: String,
action_history: Vec<PacoAction>,
}
#[wasm_bindgen(js_name = "analyzePosition")]
pub fn analyze_position(data: String) -> Result<(), JsValue> {
let data: AnalyzePositionData = serde_json::from_str(&data).map_err(|e| e.to_string())?;
let analysis = puzzle::analyze_position(&data.board_fen, &data.action_history)
.map_err(|e| e.to_string())?;
let analysis = serde_json::to_string(&analysis).map_err(|e| e.to_string())?;
forwardToMq("positionAnalysisCompleted", &analysis);
Ok(())
}
#[derive(Deserialize)]
struct AnalyzeReplayData {
board_fen: String,
action_history: Vec<PacoAction>,
setup: SetupOptions,
}
#[wasm_bindgen(js_name = "analyzeReplay")]
pub fn analyze_replay(data: String) -> Result<(), JsValue> {
let data: AnalyzeReplayData = serde_json::from_str(&data).map_err(|e| e.to_string())?;
let analysis = history_to_replay_notation(&data.board_fen, &data.action_history, &data.setup)
.map_err(|e| e.to_string())?;
let analysis = serde_json::to_string(&analysis).map_err(|e| e.to_string())?;
forwardToMq("replayAnalysisCompleted", &analysis);
Ok(())
}
fn history_to_replay_notation(
board_fen: &str,
action_history: &[PacoAction],
setup: &SetupOptions,
) -> Result<ReplayData, PacoError> {
// This "initial_board" stuff really isn't great. This should be included
// into the setup options eventually.
let mut initial_board = fen::parse_fen(board_fen)?;
// Apply setup options to the initial board
initial_board.draw_state.draw_after_n_repetitions = setup.draw_after_n_repetitions;
analysis::history_to_replay_notation(initial_board, action_history)
}
////////////////////////////////////////////////////////////////////////////////
// Proxy function for games. This sits between the client and server. //////////
////////////////////////////////////////////////////////////////////////////////
/// Subscribes to the game on the server.
#[wasm_bindgen(js_name = "subscribeToMatch")]
pub fn subscribe_to_match(data: String) -> Result<(), JsValue> {
forwardToMq("subscribeToMatchSocket", &data);
Ok(())
}
|
#[doc = "Reader of register INTR_MASKED"]
pub type R = crate::R<u32, super::INTR_MASKED>;
#[doc = "Reader of field `EDGE0`"]
pub type EDGE0_R = crate::R<bool, bool>;
#[doc = "Reader of field `EDGE1`"]
pub type EDGE1_R = crate::R<bool, bool>;
#[doc = "Reader of field `EDGE2`"]
pub type EDGE2_R = crate::R<bool, bool>;
#[doc = "Reader of field `EDGE3`"]
pub type EDGE3_R = crate::R<bool, bool>;
#[doc = "Reader of field `EDGE4`"]
pub type EDGE4_R = crate::R<bool, bool>;
#[doc = "Reader of field `EDGE5`"]
pub type EDGE5_R = crate::R<bool, bool>;
#[doc = "Reader of field `EDGE6`"]
pub type EDGE6_R = crate::R<bool, bool>;
#[doc = "Reader of field `EDGE7`"]
pub type EDGE7_R = crate::R<bool, bool>;
#[doc = "Reader of field `FLT_EDGE`"]
pub type FLT_EDGE_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Edge detected AND masked on IO pin 0 '0': Interrupt was not forwarded to CPU '1': Interrupt occurred and was forwarded to CPU"]
#[inline(always)]
pub fn edge0(&self) -> EDGE0_R {
EDGE0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Edge detected and masked on IO pin 1"]
#[inline(always)]
pub fn edge1(&self) -> EDGE1_R {
EDGE1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Edge detected and masked on IO pin 2"]
#[inline(always)]
pub fn edge2(&self) -> EDGE2_R {
EDGE2_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Edge detected and masked on IO pin 3"]
#[inline(always)]
pub fn edge3(&self) -> EDGE3_R {
EDGE3_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Edge detected and masked on IO pin 4"]
#[inline(always)]
pub fn edge4(&self) -> EDGE4_R {
EDGE4_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Edge detected and masked on IO pin 5"]
#[inline(always)]
pub fn edge5(&self) -> EDGE5_R {
EDGE5_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Edge detected and masked on IO pin 6"]
#[inline(always)]
pub fn edge6(&self) -> EDGE6_R {
EDGE6_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - Edge detected and masked on IO pin 7"]
#[inline(always)]
pub fn edge7(&self) -> EDGE7_R {
EDGE7_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - Edge detected and masked on filtered pin selected by INTR_CFG.FLT_SEL"]
#[inline(always)]
pub fn flt_edge(&self) -> FLT_EDGE_R {
FLT_EDGE_R::new(((self.bits >> 8) & 0x01) != 0)
}
}
|
use chrono::prelude::*;
use std::io::{self, Write};
#[derive(Debug, Clone, PartialEq)]
pub struct Point {
pub time: DateTime<FixedOffset>,
pub lat: f64,
pub lon: f64,
pub ele: f64,
pub speed: f64,
pub course: f64,
}
pub fn write_gpx(mut w: impl Write, segments: &[&[Point]]) -> io::Result<()> {
writeln!(w, r#"<?xml version="1.0" encoding="utf-8"?>
<gpx xmlns="http://www.topografix.com/GPX/1/1" version="1.1" creator="wfraser/slopes-gpx/1">"#)?;
for &seg in segments {
writeln!(w, "<trk><trkseg>")?;
for point in seg {
writeln!(w, r#"<trkpt lat="{}" lon="{}"><ele>{}</ele><time>{}</time><speed>{}</speed><course>{}</course></trkpt>"#,
point.lat,
point.lon,
point.ele,
point.time.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
point.speed,
point.course)?;
}
writeln!(w, "</trkseg></trk>")?;
}
writeln!(w, "</gpx>")?;
Ok(())
}
|
#[cfg(all(test, feature = "subtle"))]
mod test {
use cryptographer::subtle;
use vendored_rand as rand;
fn random_bytes() -> (Vec<u8>, Vec<u8>) {
let ell = (rand::random::<u8>() as usize) + 1;
let mut x = vec![0u8; ell];
for v in &mut x {
*v = rand::random();
}
let mut y = vec![0u8; ell];
for v in &mut y {
*v = rand::random();
}
// ensure y!=x
y[0] = x[0].wrapping_add(1);
(x, y)
}
#[test]
fn constant_time_byte_eq() {
// in form of (x, y, expect)
let test_vector = vec![
(0u8, 0u8, 1),
(0, 1, 0),
(1, 0, 0),
(0xff, 0xff, 1),
(0xff, 0xfe, 0),
];
for v in test_vector {
let (x, y, expect) = v;
let got = subtle::constant_time_byte_eq(x, y);
assert_eq!(expect, got, "failed for {} vs {}", x, y);
}
const DEFAULT_MAX_COUNT: usize = 100;
// more random test vector
for _i in 0..DEFAULT_MAX_COUNT {
let x: u8 = rand::random();
let y: u8 = rand::random();
let expect = if x == y { 1 } else { 0 };
let got = subtle::constant_time_byte_eq(x, y);
assert_eq!(expect, got, "failed for {} vs {}", x, y);
}
}
#[test]
fn constant_time_compare() {
// in form of (x, y, expect)
let test_vector = vec![
(Vec::new(), Vec::new(), 1isize),
(vec![0x11], vec![0x11], 1),
(vec![0x12], vec![0x11], 0),
(vec![0x11], vec![0x11, 0x12], 0),
(vec![0x11, 0x12], vec![0x11], 0),
];
for (i, v) in test_vector.iter().enumerate() {
let (x, y, expect) = v;
let got = subtle::constant_time_compare(x.as_slice(), y.as_slice());
assert_eq!(*expect, got, "[{}] failed for {:?} vs {:?}", i, x, y);
}
}
#[test]
fn constant_time_copy() {
const DEFAULT_MAX_COUNT: usize = 100;
for _i in 0..DEFAULT_MAX_COUNT {
let (x, y) = random_bytes();
let mut xx = x.clone();
subtle::constant_time_copy(0, xx.as_mut_slice(), y.as_slice());
assert_eq!(xx, x);
subtle::constant_time_copy(1, xx.as_mut_slice(), y.as_slice());
assert_ne!(xx, x);
}
}
#[test]
fn constant_time_eq() {
const DEFAULT_MAX_COUNT: usize = 100;
for _i in 0..DEFAULT_MAX_COUNT {
let x: i32 = rand::random();
let y: i32 = rand::random();
let expect = if x == y { 1 } else { 0 };
assert_eq!(expect, subtle::constant_time_eq(x, y));
}
}
#[test]
fn constant_time_less_or_eq() {
// in form of (x, y, expect)
let test_vector = vec![
(0isize, 0isize, 1isize),
(1, 0, 0),
(0, 1, 1),
(10, 20, 1),
(20, 10, 0),
(10, 10, 1),
];
for (i, v) in test_vector.iter().enumerate() {
let (x, y, expect) = *v;
let got = subtle::constant_time_less_or_eq(x, y);
assert_eq!(expect, got, "[{}] failed for {:?} vs {:?}", i, x, y);
}
}
}
|
use messagebus::{
derive::{Error as MbError, Message},
error, Message, TypeTagged,
};
use thiserror::Error;
#[derive(Debug, Error, MbError)]
enum Error {
#[error("Error({0})")]
Error(anyhow::Error),
}
impl<M: Message> From<error::Error<M>> for Error {
fn from(err: error::Error<M>) -> Self {
Self::Error(err.into())
}
}
#[derive(Debug, Clone, Message)]
#[namespace("api")]
pub struct Msg<F>(pub F);
#[derive(Debug, Clone, Message)]
#[type_tag("api::Query")]
pub struct Qqq<F, G, H>(pub F, pub G, pub H);
fn main() {
assert_eq!(
Qqq::<Msg<i32>, Msg<()>, u64>::type_tag_(),
"api::Query<api::Msg<i32>,api::Msg<()>,u64>"
);
}
|
//! Implements the CLI interface.
use std::convert::TryFrom;
use std::num::ParseIntError;
use std::path::PathBuf;
use std::str::FromStr;
use structopt::StructOpt;
use thiserror::Error;
use crate::pascal_voc::PrepareOpts;
#[derive(StructOpt, Debug)]
pub enum Command {
/// Use a PASCAL-VOC dataset
PascalVoc(PascalVoc),
}
#[derive(StructOpt, Debug)]
pub enum PascalVoc {
/// Prepare a PASCAL-VOC dataset for tensorflow
/// This operations generates the label map and two tfrecord files: a training set and a test set
Prepare(PrepareCliOpts),
}
#[derive(StructOpt, Debug)]
pub struct PrepareCliOpts {
/// Input directory, where your dataset is. Will be searched recursively
#[structopt(short = "i", long = "input")]
pub input: PathBuf,
/// Output directory, where the TensorFlow configuration files will be written
#[structopt(short = "o", long = "output")]
pub output: PathBuf,
/// Percentage of data that should be retained and placed in the test set
#[structopt(long = "retain", default_value = "20%")]
pub retain: String,
}
// Convert the CLI structure for the prepare operation into out internal representation
impl TryFrom<PrepareCliOpts> for PrepareOpts {
type Error = CliError;
fn try_from(cli: PrepareCliOpts) -> Result<PrepareOpts, CliError> {
let retain = if cli.retain.contains('/') {
cli.retain.split('/').next().unwrap_or("").to_owned()
} else if cli.retain.contains('%') {
cli.retain.split('%').next().unwrap_or("").to_owned()
} else {
cli.retain
};
let opts = PrepareOpts {
input: cli.input,
output: cli.output,
test_set_ratio: u8::from_str(&retain)?,
};
Ok(opts)
}
}
#[derive(Debug, Error)]
pub enum CliError {
#[error("Could not parse integer value")]
Integer(#[from] ParseIntError),
}
|
use game;
use std::collections::HashMap;
use board::Board;
const INITIAL_DEPTH: i32 = 0;
const TIED: i32 = 0;
const MAX_SCORE: i32 = 1000;
const INCREMENT: i32 = 1;
const EARLY_STAGES_OF_GAME: usize = 1;
const FIRST_MOVE: i32 = 4;
const SECOND_MOVE: i32 = 0;
pub fn find_space(board: &Board) -> i32 {
if is_game_in_early_stages(board) {
choose_strategic_space(board)
} else {
find_best_score(board, INITIAL_DEPTH, HashMap::new())
}
}
fn find_best_score(board: &Board, depth: i32, mut best_score: HashMap<i32, i32>) -> i32 {
if game::is_game_over(board) {
score_scenarios(board, depth)
} else {
for space in &board.get_available_spaces() {
let emulated_board = board.clone().place_marker(*space);
best_score.insert(
*space,
-find_best_score(&emulated_board, depth + INCREMENT, HashMap::new()),
);
}
analyse_board(&best_score, depth)
}
}
fn score_scenarios(board: &Board, depth: i32) -> i32 {
if game::is_game_tied(board) {
TIED
} else {
-MAX_SCORE / depth
}
}
fn analyse_board(best_score: &HashMap<i32, i32>, depth: i32) -> i32 {
let space_with_highest_score: (i32, i32) = find_highest_score(best_score);
if current_turn(depth) {
choose_best_space(space_with_highest_score)
} else {
choose_highest_score(space_with_highest_score)
}
}
fn find_highest_score(best_score: &HashMap<i32, i32>) -> (i32, i32) {
let mut scores_to_compare: Vec<(&i32, &i32)> = best_score.iter().collect();
scores_to_compare.sort_by(|key, value| value.1.cmp(key.1));
(*scores_to_compare[0].0, *scores_to_compare[0].1)
}
fn choose_best_space(best_space_with_score: (i32, i32)) -> i32 {
best_space_with_score.0
}
fn choose_highest_score(best_space_with_score: (i32, i32)) -> i32 {
best_space_with_score.1
}
fn current_turn(depth: i32) -> bool {
depth == 0
}
fn is_game_in_early_stages(board: &Board) -> bool {
board.get_spaces().len() <= EARLY_STAGES_OF_GAME
}
fn choose_strategic_space(board: &Board) -> i32 {
if board.is_space_available(&FIRST_MOVE) {
FIRST_MOVE
} else {
SECOND_MOVE
}
}
pub mod tests {
#[cfg(test)]
use super::*;
#[cfg(test)]
use board::tests::set_up_board;
#[test]
fn checks_if_it_is_the_first_two_moves_of_the_game_no_moves() {
let board: Board = set_up_board(3, vec![]);
assert!(is_game_in_early_stages(&board));
}
#[test]
fn checks_if_it_is_the_first_two_moves_of_the_game_one_move() {
let board: Board = set_up_board(3, vec![0]);
assert!(is_game_in_early_stages(&board));
}
#[test]
fn checks_if_it_is_not_in_the_first_two_moves_of_the_game() {
let board: Board = set_up_board(3, vec![0, 4]);
assert!(!is_game_in_early_stages(&board));
}
#[test]
fn chooses_the_middle_if_goes_first() {
let board: Board = set_up_board(3, vec![]);
assert_eq!(4, find_space(&board));
}
#[test]
fn chooses_the_middle_if_it_is_free_and_goes_second() {
let board: Board = set_up_board(3, vec![0]);
assert_eq!(4, find_space(&board));
}
#[test]
fn chooses_the_top_left_if_middle_is_taken() {
let board: Board = set_up_board(3, vec![4]);
assert_eq!(0, find_space(&board));
}
#[test]
fn chooses_the_top_left_if_the_middle_is_taken() {
let board: Board = set_up_board(3, vec![4]);
assert_eq!(0, find_space(&board));
}
#[test]
fn doesnt_play_in_a_space_where_x_can_win_when_starting_in_top_left_corner() {
let board: Board = set_up_board(3, vec![0, 4, 8]);
assert_ne!(2, find_space(&board));
assert_ne!(6, find_space(&board));
}
#[test]
fn doesnt_play_in_a_space_where_x_can_win_when_starting_in_top_right_corner() {
let board: Board = set_up_board(3, vec![2, 4, 6]);
assert_ne!(0, find_space(&board));
assert_ne!(8, find_space(&board));
}
#[test]
fn doesnt_play_in_a_space_where_x_can_win_when_starting_in_bottom_right_corner() {
let board: Board = set_up_board(3, vec![8, 4, 0]);
assert_ne!(2, find_space(&board));
assert_ne!(6, find_space(&board));
}
#[test]
fn doesnt_play_in_a_space_where_x_can_win_when_starting_in_bottom_left_corner() {
let board: Board = set_up_board(3, vec![6, 4, 2]);
assert_ne!(0, find_space(&board));
assert_ne!(8, find_space(&board));
}
#[test]
fn computer_leaves_game_unwinnable_after_top_left_followed_by_right_side_middle() {
let board: Board = set_up_board(3, vec![0, 4, 5]);
assert_ne!(3, find_space(&board));
assert_ne!(6, find_space(&board));
}
#[test]
fn computer_leaves_game_unwinnable_after_top_right_followed_by_left_side_middle() {
let board: Board = set_up_board(3, vec![2, 4, 3]);
assert_ne!(5, find_space(&board));
assert_ne!(8, find_space(&board));
}
#[test]
fn computer_leaves_game_unwinnable_after_bottom_left_followed_by_top_middle() {
let board: Board = set_up_board(3, vec![6, 4, 1]);
assert_ne!(7, find_space(&board));
assert_ne!(8, find_space(&board));
}
#[test]
fn computer_leaves_game_unwinnable_after_bottom_right_followed_by_left_middle() {
let board: Board = set_up_board(3, vec![8, 4, 3]);
assert_ne!(2, find_space(&board));
assert_ne!(5, find_space(&board));
}
#[test]
fn chooses_the_only_available_space() {
let board: Board = set_up_board(3, vec![0, 1, 2, 3, 4, 8, 5, 6]);
assert_eq!(7, find_space(&board));
}
#[test]
fn chooses_the_winning_space() {
let board: Board = set_up_board(3, vec![0, 1, 2, 3, 4, 8]);
assert_eq!(6, find_space(&board));
}
#[test]
fn chooses_a_win_over_a_block() {
let board: Board = set_up_board(3, vec![8, 4, 7]);
assert_eq!(6, find_space(&board));
}
#[test]
fn wins_the_game() {
let board: Board = set_up_board(3, vec![0, 4, 1, 6]);
assert_eq!(2, find_space(&board));
}
#[test]
fn o_blocks_a_win() {
let board: Board = set_up_board(3, vec![0, 1, 4]);
assert_eq!(8, find_space(&board));
}
#[test]
fn x_blocks_a_win() {
let board: Board = set_up_board(3, vec![0, 8, 6]);
assert_eq!(3, find_space(&board));
}
}
|
pub mod compute_py;
pub mod config_py;
pub mod geo_py;
pub mod stl_py;
|
//! `plbc`, the <b>P</b>aral<b>l</b>isp <b>B</b>ootstrap <b>C</b>ompiler, interprets Parallisp
//! code.
extern crate getopts;
extern crate nom;
extern crate plb;
use getopts::Options;
use plb::ParallispError;
use plb::parser::parse;
use plb::interpreter::eval_all;
use plb::interpreter::macros::process_macros;
use plb::interpreter::stdlib::make_env;
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::{Read, stderr, stdin, stdout, Write};
use std::process::exit;
fn main() {
run_with_args(|src: &str| -> Result<String, ParallispError> {
let mut exprs = try!(parse(src));
let env = make_env();
exprs = try!(process_macros(&exprs, env.clone()));
let ret = try!(eval_all(&exprs, env.clone()));
let env_str = format!("{}", *env.borrow());
Ok(format!("returned {} with env:\n{}", ret, env_str))
});
}
fn run_with_args<E: Error, F: Fn(&str) -> Result<String, E>>(f: F) {
fn io_try<T>(r: std::io::Result<T>) -> Box<T> {
match r {
Ok(t) => Box::new(t),
Err(e) => {
writeln!(&mut std::io::stderr(), "Error: {}", e.description()).unwrap();
exit(74); // EX_IOERR, by sysexits.h
}
}
}
fn usage(opts: Options) -> ! {
let exec = env::args().next().unwrap_or("plbi".to_string());
let brief = format!("Usage: {} [FLAGS] FILE", exec);
writeln!(&mut stderr(), "{}", opts.usage(&brief)).unwrap();
exit(64); // EX_USAGE, by sysexits.h
}
fn usage_for(opts: Options, s: String) -> ! {
writeln!(&mut stderr(), "{}", s).unwrap();
usage(opts);
}
// Initialize and parse options.
let mut opts = Options::new();
opts.optflag("h", "help", "Displays help");
let args = match opts.parse(env::args().skip(1)) {
Ok(m) => m,
Err(err) => usage_for(opts, err.to_string()),
};
if args.opt_present("h") {
usage(opts);
}
// Get the input.
let mut input = String::new();
io_try(match args.free.len() {
0 => stdin().read_to_string(&mut input),
1 => io_try(File::open(args.free[0].clone())).read_to_string(&mut input),
_ => usage(opts),
});
// Write the output.
match f(&input) {
Ok(val) => {
writeln!(stdout(), "{}", val).unwrap();
}
Err(err) => {
writeln!(stderr(), "{}", err).unwrap();
exit(1);
}
}
}
|
use docopt::Docopt;
const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
const USAGE: &str = "
Usage: tn edit <note-name>
tn list
tn remove <note-name>
tn show <note-name>
tn (-h | --help)
tn --version
tn --bash-completion
tn --commands
Options:
-h --help Show this screen.
--version Show version.
--bash-completion Prints out bash completion script.
--commands List supported commands.
";
type Result<T> = ::std::result::Result<T, Box<::std::error::Error>>;
#[derive(Debug, Deserialize)]
struct Args {
cmd_show: bool,
cmd_edit: bool,
cmd_list: bool,
cmd_remove: bool,
flag_bash_completion: bool,
flag_commands: bool,
arg_note_name: Option<String>,
}
impl Args {
pub fn command(self) -> Result<Command> {
if self.cmd_show {
return Ok(Command::ShowNote(self.arg_note_name.unwrap()))
}
if self.cmd_edit {
return Ok(Command::EditNote(self.arg_note_name.unwrap()))
}
if self.cmd_list {
return Ok(Command::ListNotes)
}
if self.cmd_remove {
return Ok(Command::RemoveNote(self.arg_note_name.unwrap()))
}
if self.flag_bash_completion {
return Ok(Command::BashCompletion)
}
if self.flag_commands {
return Ok(Command::Commands)
}
Err("invalid command")?
}
}
#[derive(Debug)]
pub enum Command {
ShowNote(String),
EditNote(String),
ListNotes,
RemoveNote(String),
BashCompletion,
Commands,
}
impl Command {
pub fn parse(argv: std::env::Args) -> Result<Command> {
let version = VERSION.map_or(None, |v| Some(v.to_string()));
let args: Args = Docopt::new(USAGE)
.and_then(|d| {
d.version(version)
.argv(argv)
.deserialize()
})?;
Ok(args.command()?)
}
}
|
use std::io;
use std::io::Write;
use std::env;
fn run_cmd (cmd: String) { // what does this return?
println!("{}", cmd);
//cmd.clear(); // use this to clear string when done with cmd
}
fn main() {
let mut status = true;
loop { // rust doesn't have do { while() }
let mut current_dir = match env::current_dir() {
Err(e) => panic!("Error getting current dir: {}", e),
Ok(dir) => dir,
};
print!("ash {} > ", current_dir); // TODO: remove quotes
let mut cmd = String::new();
io::stdout().flush().unwrap();
io::stdin().read_line(&mut cmd)
.expect("Failed to read command.");
run_cmd(cmd);
if !status { break }
}
}
|
#[doc = "Reader of register MMMS_DATA_MEM_DESCRIPTOR[%s]"]
pub type R = crate::R<u32, super::MMMS_DATA_MEM_DESCRIPTOR>;
#[doc = "Writer for register MMMS_DATA_MEM_DESCRIPTOR[%s]"]
pub type W = crate::W<u32, super::MMMS_DATA_MEM_DESCRIPTOR>;
#[doc = "Register MMMS_DATA_MEM_DESCRIPTOR[%s] `reset()`'s with value 0"]
impl crate::ResetValue for super::MMMS_DATA_MEM_DESCRIPTOR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `LLID_C1`"]
pub type LLID_C1_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `LLID_C1`"]
pub struct LLID_C1_W<'a> {
w: &'a mut W,
}
impl<'a> LLID_C1_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x03) | ((value as u32) & 0x03);
self.w
}
}
#[doc = "Reader of field `DATA_LENGTH_C1`"]
pub type DATA_LENGTH_C1_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `DATA_LENGTH_C1`"]
pub struct DATA_LENGTH_C1_W<'a> {
w: &'a mut W,
}
impl<'a> DATA_LENGTH_C1_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xff << 2)) | (((value as u32) & 0xff) << 2);
self.w
}
}
impl R {
#[doc = "Bits 0:1 - N/A"]
#[inline(always)]
pub fn llid_c1(&self) -> LLID_C1_R {
LLID_C1_R::new((self.bits & 0x03) as u8)
}
#[doc = "Bits 2:9 - This field indicates the length of the data packet. Bits \\[9:7\\] are valid only if DLE is set. Range 0x00 to 0xFF."]
#[inline(always)]
pub fn data_length_c1(&self) -> DATA_LENGTH_C1_R {
DATA_LENGTH_C1_R::new(((self.bits >> 2) & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:1 - N/A"]
#[inline(always)]
pub fn llid_c1(&mut self) -> LLID_C1_W {
LLID_C1_W { w: self }
}
#[doc = "Bits 2:9 - This field indicates the length of the data packet. Bits \\[9:7\\] are valid only if DLE is set. Range 0x00 to 0xFF."]
#[inline(always)]
pub fn data_length_c1(&mut self) -> DATA_LENGTH_C1_W {
DATA_LENGTH_C1_W { w: self }
}
}
|
/*
* 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 futures::{try_ready, Async, Future, Poll};
#[derive(Clone, Copy)]
pub(crate) struct NodeLocation<Index> {
pub node_index: Index, // node index inside execution tree
pub child_index: usize, // index inside parents children list
}
// This is essentially just a `.map` over futures `{FFut|UFut}`, this only exisists
// so it would be possible to name `FuturesUnoredered` type parameter.
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub(crate) enum Job<In, UFut, FFut> {
Unfold { value: In, future: UFut },
Fold { value: In, future: FFut },
}
pub(crate) enum JobResult<In, UFutResult, FFutResult> {
Unfold { value: In, result: UFutResult },
Fold { value: In, result: FFutResult },
}
impl<In, UFut, FFut> Future for Job<In, UFut, FFut>
where
In: Clone,
UFut: Future,
FFut: Future<Error = UFut::Error>,
{
type Item = JobResult<In, UFut::Item, FFut::Item>;
type Error = FFut::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let result = match self {
Job::Fold { value, future } => JobResult::Fold {
value: value.clone(),
result: try_ready!(future.poll()),
},
Job::Unfold { value, future } => JobResult::Unfold {
value: value.clone(),
result: try_ready!(future.poll()),
},
};
Ok(Async::Ready(result))
}
}
|
// Copyright 2017 Dmitry Tantsur <divius.inside@gmail.com>
//
// 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.
//! Compute API implementation bits.
mod base;
mod flavors;
mod keypairs;
mod protocol;
mod servers;
pub use self::base::V2 as ServiceType;
pub use self::flavors::{Flavor, FlavorSummary, FlavorQuery};
pub use self::keypairs::{KeyPair, KeyPairQuery, NewKeyPair};
pub use self::protocol::{AddressType, KeyPairType, RebootType, ServerAddress,
ServerFlavor, ServerSortKey, ServerPowerState,
ServerStatus};
pub use self::servers::{NewServer, Server, ServerCreationWaiter, ServerNIC,
ServerQuery, ServerStatusWaiter, ServerSummary};
|
#![allow(unused_imports)]
#![allow(dead_code)]
#[macro_use]
extern crate lazy_static;
mod application;
mod message;
mod message_validator;
mod network;
mod data_dictionary;
mod quickfix_errors;
mod session;
mod types;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{Ipv4Addr, SocketAddrV4, TcpListener, TcpStream};
use crate::application::*;
use crate::message::store::*;
use crate::message::*;
use crate::network::*;
use crate::session::*;
use crate::types::*;
fn test_message_1() -> String {
let mut msg = Message::new();
msg.header_mut().set_string(8, "FIX4.3".to_string());
msg.header_mut().set_string(49, "Gaurav".to_string());
msg.header_mut().set_string(56, "Tatke".to_string());
msg.body_mut().set_int(34, 8765);
msg.body_mut().set_float(44, 1.87856);
msg.body_mut().set_bool(654, true);
msg.body_mut().set_char(54, 'b');
msg.body_mut().set_string(1, "BOX_AccId".to_string());
msg.trailer_mut().set_int(10, 101);
msg.to_string()
// assert!(!msg.to_string().is_empty());
}
fn send_message(stream: &mut TcpStream, input_str: String) {
stream
.write(input_str.as_bytes())
.expect("could not write to output stream");
// loop {
// let mut buffer: Vec<u8> = Vec::new();
// stream.write(input_str.as_bytes()).expect("could not write to output stream");
// let mut reader = BufReader::new(&stream);
// reader.read_until(b'\n', &mut buffer).expect("could not read into buffer");
// print!("{}", str::from_utf8(&buffer).expect("could not write buffer as string"));
// }
}
fn main() {
println!("running main");
let mut session_config = SessionConfig::from_toml("src/FixConfig.toml");
let mut message_store = DefaultMessageStore::new();
let mut log_store = DefaultLogStore::new();
let application = DefaultApplication::new();
let acceptor = SocketConnector::new(
&mut session_config,
&mut message_store,
&mut log_store,
application,
);
let handles = acceptor.start();
for handle in handles {
handle.join().expect("thread joined has panicked");
}
}
|
//! Contains types and definitions for Serial IO registers.
use super::*;
/// Serial IO Control. Read/Write.
pub const SIOCNT: VolAddress<SioControlSetting, Safe, Safe> =
unsafe { VolAddress::new(0x400_0128) };
/// Serial IO Data. Read/Write.
pub const SIODATA8: VolAddress<u16, Safe, Safe> = unsafe { VolAddress::new(0x400_012A) };
/// General IO Control. Read/Write.
pub const RCNT: VolAddress<IoControlSetting, Safe, Safe> = unsafe { VolAddress::new(0x400_0134) };
newtype!(
/// Setting for the serial IO control register.
///
/// * 0-1: `BaudRate`
/// * 2: Use hardware flow control
/// * 3: Use odd parity instead of even
/// * 4: TX buffer is full
/// * 5: RX buffer is empty
/// * 6: Error occurred
/// * 7: Use 8-bit data length instead of 7-bit
/// * 8: Use hardware FIFO
/// * 9: Enable parity check
/// * 10: Enable data receive
/// * 11: Enable data transmit
/// * 12-13: `SioMode`
/// * 14: Trigger interrupt on RX
SioControlSetting,
u16
);
#[allow(missing_docs)]
impl SioControlSetting {
phantom_fields! {
self.0: u16,
baud_rate: 0-1=BaudRate<Bps9600,Bps38400,Bps57600,Bps115200>,
flow_control: 2,
parity_odd: 3,
tx_full: 4,
rx_empty: 5,
error: 6,
data_length_8bit: 7,
fifo_enable:8,
parity_enable: 9,
tx_enable: 10,
rx_enable: 11,
mode: 12-13=SioMode<Normal8Bit,MultiPlayer,Normal32Bit,Uart>,
irq_enable: 14,
}
}
newtype_enum! {
/// Supported baud rates.
BaudRate = u16,
/// * 9600 bps
Bps9600 = 0,
/// * 38400 bps
Bps38400 = 1,
/// * 57600 bps
Bps57600 = 2,
/// * 115200 bps
Bps115200 = 3,
}
newtype_enum! {
/// Serial IO modes.
SioMode = u16,
/// * Normal mode: 8-bit data
Normal8Bit = 0,
/// * Multiplayer mode: 16-bit data
MultiPlayer = 1,
/// * Normal mode: 32-bit data
Normal32Bit = 2,
/// * UART (RS232) mode: 7 or 8-bit data
Uart = 3,
}
newtype!(
/// Setting for the general IO control register.
///
/// * 0: SC state
/// * 1: SD state
/// * 2: SI state
/// * 3: SO state
/// * 4: Set SC as output, instead of input
/// * 5: Set SD as output, instead of input
/// * 6: Set SI as output, instead of input
/// * 7: Set SO as output, instead of input
/// * 8: Trigger interrupt on SI change
/// * 14-15: `IoMode`
IoControlSetting,
u16
);
newtype_enum! {
/// General IO modes.
IoMode = u16,
/// * IO disabled
Disabled = 0,
/// * General Purpose IO
GPIO = 2,
/// * JoyBus mode
JoyBus = 3,
}
#[allow(missing_docs)]
impl IoControlSetting {
phantom_fields! {
self.0: u16,
sc: 0,
sd: 1,
si: 2,
so: 3,
sc_output_enable: 4,
sd_output_enable: 5,
si_output_enable: 6,
so_output_enable: 7,
si_irq_enable: 8,
mode: 14-15=IoMode<Disabled,GPIO,JoyBus>,
}
}
/// Empty struct that implements embedded_hal traits.
#[cfg(feature = "serial")]
#[derive(Clone)]
pub struct SioSerial;
#[cfg(feature = "serial")]
impl SioSerial {
/// Initialize SioSerial with provided baud rate and default 8N1 settings.
pub fn init(baud: BaudRate) -> Self {
RCNT.write(IoControlSetting::new());
SIOCNT.write(
// default settings: 8N1
SioControlSetting::new()
.with_baud_rate(baud)
.with_data_length_8bit(true)
.with_mode(SioMode::Uart)
.with_fifo_enable(true)
.with_rx_enable(true)
.with_tx_enable(true),
);
SioSerial
}
}
/// Serial IO error type.
#[cfg(feature = "serial")]
#[derive(Debug)]
pub enum SioError {
/// * Error bit in SIOCNT is set
ErrorBitSet,
}
#[cfg(feature = "serial")]
impl embedded_hal::serial::Read<u8> for SioSerial {
type Error = SioError;
fn read(&mut self) -> nb::Result<u8, Self::Error> {
match SIOCNT.read() {
siocnt if siocnt.error() => Err(nb::Error::Other(SioError::ErrorBitSet)),
siocnt if siocnt.rx_empty() => Err(nb::Error::WouldBlock),
_ => Ok(SIODATA8.read() as u8),
}
}
}
#[cfg(feature = "serial")]
impl embedded_hal::serial::Write<u8> for SioSerial {
type Error = SioError;
fn write(&mut self, word: u8) -> nb::Result<(), Self::Error> {
self.flush()?;
SIODATA8.write(word as u16);
Ok(())
}
fn flush(&mut self) -> nb::Result<(), Self::Error> {
match SIOCNT.read() {
siocnt if siocnt.error() => Err(nb::Error::Other(SioError::ErrorBitSet)),
siocnt if siocnt.tx_full() => Err(nb::Error::WouldBlock),
_ => Ok(()),
}
}
}
|
use std::any::Any;
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use rand::prelude::*;
#[cfg(feature = "testing")]
use data_buffer::vec_clone::VecClone;
use data_buffer::{VecCopy, VecDyn};
use dyn_derive::dyn_trait;
static SEED: [u8; 32] = [3; 32];
#[dyn_trait(suffix = "VTable", dyn_crate_name = "data_buffer")]
pub trait DynClone {}
impl DynClone for [i64; 3] {}
#[inline]
fn make_random_vec(n: usize) -> Vec<[i64; 3]> {
let mut rng: StdRng = SeedableRng::from_seed(SEED);
(0..n).map(move |_| [rng.gen::<i64>(); 3]).collect()
}
#[inline]
fn make_random_vec_any(n: usize) -> Vec<Box<dyn Any>> {
let mut rng: StdRng = SeedableRng::from_seed(SEED);
(0..n)
.map(move |_| {
let b: Box<dyn Any> = Box::new([rng.gen::<i64>(); 3]);
b
})
.collect()
}
#[inline]
fn make_random_vec_copy(n: usize) -> VecCopy {
let mut rng: StdRng = SeedableRng::from_seed(SEED);
let vec: Vec<_> = (0..n).map(move |_| [rng.gen::<i64>(); 3]).collect();
vec.into()
}
#[cfg(feature = "testing")]
#[inline]
fn make_random_vec_clone(n: usize) -> VecClone {
let mut rng: StdRng = SeedableRng::from_seed(SEED);
let vec: Vec<_> = (0..n).map(move |_| [rng.gen::<i64>(); 3]).collect();
vec.into()
}
#[inline]
fn make_random_vec_dyn(n: usize) -> VecDyn<DynCloneVTable> {
let mut rng: StdRng = SeedableRng::from_seed(SEED);
let vec: Vec<_> = (0..n).map(move |_| [rng.gen::<i64>(); 3]).collect();
vec.into()
}
#[inline]
fn compute(x: i64, y: i64, z: i64) -> [i64; 3] {
[
x * 3 - 5 * y + z * 2,
y * 3 - 5 * z + x * 2,
z * 3 - 5 * x + y * 2,
]
}
#[inline]
fn vec_compute(v: &mut Vec<[i64; 3]>) {
for a in v.iter_mut() {
let res = compute(a[0], a[1], a[2]);
a[0] = res[0];
a[1] = res[1];
a[2] = res[2];
}
}
#[inline]
fn vec_any_compute(v: &mut Vec<Box<dyn Any>>) {
for ref mut a in v.iter_mut() {
let a = (&mut *a).downcast_mut::<[i64; 3]>().unwrap();
let res = compute(a[0], a[1], a[2]);
a[0] = res[0];
a[1] = res[1];
a[2] = res[2];
}
}
#[inline]
fn vec_copy_compute(v: &mut VecCopy) {
for a in v.iter_value_mut() {
let a = a.downcast::<[i64; 3]>().unwrap();
let res = compute(a[0], a[1], a[2]);
a[0] = res[0];
a[1] = res[1];
a[2] = res[2];
}
}
#[cfg(feature = "testing")]
#[inline]
fn vec_clone_compute(v: &mut VecClone) {
for a in v.iter_value_mut() {
let a = a.downcast::<[i64; 3]>().unwrap();
let res = compute(a[0], a[1], a[2]);
a[0] = res[0];
a[1] = res[1];
a[2] = res[2];
}
}
#[inline]
fn vec_dyn_compute<V>(v: &mut VecDyn<V>) {
for a in v.iter_mut() {
let a = a.downcast::<[i64; 3]>().unwrap();
let res = compute(a[0], a[1], a[2]);
a[0] = res[0];
a[1] = res[1];
a[2] = res[2];
}
}
fn type_erasure(c: &mut Criterion) {
let mut group = c.benchmark_group("Type Erasure");
for &buf_size in &[3000, 30_000, 90_000, 180_000, 300_000, 600_000, 900_000] {
group.bench_function(BenchmarkId::new("Vec<[i64;3]>", buf_size), |b| {
let mut v = make_random_vec(buf_size);
b.iter(|| {
vec_compute(&mut v);
})
});
group.bench_function(BenchmarkId::new("Vec<Box<dyn Any>>", buf_size), |b| {
let mut v = make_random_vec_any(buf_size);
b.iter(|| {
vec_any_compute(&mut v);
})
});
group.bench_function(BenchmarkId::new("VecCopy", buf_size), |b| {
let mut v = make_random_vec_copy(buf_size);
b.iter(|| {
vec_copy_compute(&mut v);
})
});
#[cfg(feature = "testing")]
group.bench_function(BenchmarkId::new("VecClone", buf_size), |b| {
let mut v = make_random_vec_clone(buf_size);
b.iter(|| {
vec_clone_compute(&mut v);
})
});
group.bench_function(BenchmarkId::new("VecDyn", buf_size), |b| {
let mut v = make_random_vec_dyn(buf_size);
b.iter(|| {
vec_dyn_compute(&mut v);
})
});
}
group.finish();
}
criterion_group!(benches, type_erasure);
criterion_main!(benches);
|
/// An enum to represent all characters in the Tagalog block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum Tagalog {
/// \u{1700}: 'ᜀ'
LetterA,
/// \u{1701}: 'ᜁ'
LetterI,
/// \u{1702}: 'ᜂ'
LetterU,
/// \u{1703}: 'ᜃ'
LetterKa,
/// \u{1704}: 'ᜄ'
LetterGa,
/// \u{1705}: 'ᜅ'
LetterNga,
/// \u{1706}: 'ᜆ'
LetterTa,
/// \u{1707}: 'ᜇ'
LetterDa,
/// \u{1708}: 'ᜈ'
LetterNa,
/// \u{1709}: 'ᜉ'
LetterPa,
/// \u{170a}: 'ᜊ'
LetterBa,
/// \u{170b}: 'ᜋ'
LetterMa,
/// \u{170c}: 'ᜌ'
LetterYa,
/// \u{170e}: 'ᜎ'
LetterLa,
/// \u{170f}: 'ᜏ'
LetterWa,
/// \u{1710}: 'ᜐ'
LetterSa,
/// \u{1711}: 'ᜑ'
LetterHa,
/// \u{1712}: 'ᜒ'
VowelSignI,
/// \u{1713}: 'ᜓ'
VowelSignU,
/// \u{1714}: '᜔'
SignVirama,
}
impl Into<char> for Tagalog {
fn into(self) -> char {
match self {
Tagalog::LetterA => 'ᜀ',
Tagalog::LetterI => 'ᜁ',
Tagalog::LetterU => 'ᜂ',
Tagalog::LetterKa => 'ᜃ',
Tagalog::LetterGa => 'ᜄ',
Tagalog::LetterNga => 'ᜅ',
Tagalog::LetterTa => 'ᜆ',
Tagalog::LetterDa => 'ᜇ',
Tagalog::LetterNa => 'ᜈ',
Tagalog::LetterPa => 'ᜉ',
Tagalog::LetterBa => 'ᜊ',
Tagalog::LetterMa => 'ᜋ',
Tagalog::LetterYa => 'ᜌ',
Tagalog::LetterLa => 'ᜎ',
Tagalog::LetterWa => 'ᜏ',
Tagalog::LetterSa => 'ᜐ',
Tagalog::LetterHa => 'ᜑ',
Tagalog::VowelSignI => 'ᜒ',
Tagalog::VowelSignU => 'ᜓ',
Tagalog::SignVirama => '᜔',
}
}
}
impl std::convert::TryFrom<char> for Tagalog {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'ᜀ' => Ok(Tagalog::LetterA),
'ᜁ' => Ok(Tagalog::LetterI),
'ᜂ' => Ok(Tagalog::LetterU),
'ᜃ' => Ok(Tagalog::LetterKa),
'ᜄ' => Ok(Tagalog::LetterGa),
'ᜅ' => Ok(Tagalog::LetterNga),
'ᜆ' => Ok(Tagalog::LetterTa),
'ᜇ' => Ok(Tagalog::LetterDa),
'ᜈ' => Ok(Tagalog::LetterNa),
'ᜉ' => Ok(Tagalog::LetterPa),
'ᜊ' => Ok(Tagalog::LetterBa),
'ᜋ' => Ok(Tagalog::LetterMa),
'ᜌ' => Ok(Tagalog::LetterYa),
'ᜎ' => Ok(Tagalog::LetterLa),
'ᜏ' => Ok(Tagalog::LetterWa),
'ᜐ' => Ok(Tagalog::LetterSa),
'ᜑ' => Ok(Tagalog::LetterHa),
'ᜒ' => Ok(Tagalog::VowelSignI),
'ᜓ' => Ok(Tagalog::VowelSignU),
'᜔' => Ok(Tagalog::SignVirama),
_ => Err(()),
}
}
}
impl Into<u32> for Tagalog {
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 Tagalog {
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 Tagalog {
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 Tagalog {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
Tagalog::LetterA
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("Tagalog{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
#![no_std]
//! Generic parallel GPIO interface for display drivers
use embedded_hal::digital::OutputPin;
pub use display_interface::{DataFormat, DisplayError, WriteOnlyDataCommand};
type Result<T = ()> = core::result::Result<T, DisplayError>;
/// This trait represents the data pins of a parallel bus.
///
/// See [Generic8BitBus] and [Generic16BitBus] for generic implementations.
pub trait OutputBus {
/// [u8] for 8-bit buses, [u16] for 16-bit buses, etc.
type Word: Copy;
fn set_value(&mut self, value: Self::Word) -> Result;
}
macro_rules! generic_bus {
($GenericxBitBus:ident { type Word = $Word:ident; Pins {$($PX:ident => $x:tt,)*}}) => {
/// A generic implementation of [OutputBus] using [OutputPin]s
pub struct $GenericxBitBus<$($PX, )*> {
pins: ($($PX, )*),
last: $Word,
}
impl<$($PX, )*> $GenericxBitBus<$($PX, )*>
where
$($PX: OutputPin, )*
{
/// Creates a new instance and initializes the bus to `0`.
///
/// The first pin in the tuple is the least significant bit.
pub fn new(pins: ($($PX, )*)) -> Result<Self> {
let mut bus = Self { pins, last: $Word::MAX };
// By setting `last` to all ones, we ensure that this will update all the pins
bus.set_value(0)?;
Ok(bus)
}
/// Consumes the bus and returns the pins. This does not change the state of the pins.
pub fn release(self) -> ($($PX, )*) {
self.pins
}
}
impl<$($PX, )*> OutputBus
for $GenericxBitBus<$($PX, )*>
where
$($PX: OutputPin, )*
{
type Word = $Word;
fn set_value(&mut self, value: Self::Word) -> Result {
let changed = value ^ self.last;
// It's quite common for multiple consecutive values to be identical, e.g. when filling or
// clearing the screen, so let's optimize for that case
if changed != 0 {
$(
let mask = 1 << $x;
if changed & mask != 0 {
if value & mask != 0 {
self.pins.$x.set_high()
} else {
self.pins.$x.set_low()
}
.map_err(|_| DisplayError::BusWriteError)?;
}
)*
self.last = value;
}
Ok(())
}
}
impl<$($PX, )*> core::convert::TryFrom<($($PX, )*)>
for $GenericxBitBus<$($PX, )*>
where
$($PX: OutputPin, )*
{
type Error = DisplayError;
fn try_from(pins: ($($PX, )*)) -> Result<Self> {
Self::new(pins)
}
}
};
}
generic_bus! {
Generic8BitBus {
type Word = u8;
Pins {
P0 => 0,
P1 => 1,
P2 => 2,
P3 => 3,
P4 => 4,
P5 => 5,
P6 => 6,
P7 => 7,
}
}
}
generic_bus! {
Generic16BitBus {
type Word = u16;
Pins {
P0 => 0,
P1 => 1,
P2 => 2,
P3 => 3,
P4 => 4,
P5 => 5,
P6 => 6,
P7 => 7,
P8 => 8,
P9 => 9,
P10 => 10,
P11 => 11,
P12 => 12,
P13 => 13,
P14 => 14,
P15 => 15,
}
}
}
/// Parallel 8 Bit communication interface
///
/// This interface implements an 8-Bit "8080" style write-only display interface using any
/// 8-bit [OutputBus] implementation as well as one
/// `OutputPin` for the data/command selection and one `OutputPin` for the write-enable flag.
///
/// All pins are supposed to be high-active, high for the D/C pin meaning "data" and the
/// write-enable being pulled low before the setting of the bits and supposed to be sampled at a
/// low to high edge.
pub struct PGPIO8BitInterface<BUS, DC, WR> {
bus: BUS,
dc: DC,
wr: WR,
}
impl<BUS, DC, WR> PGPIO8BitInterface<BUS, DC, WR>
where
BUS: OutputBus<Word = u8>,
DC: OutputPin,
WR: OutputPin,
{
/// Create new parallel GPIO interface for communication with a display driver
pub fn new(bus: BUS, dc: DC, wr: WR) -> Self {
Self { bus, dc, wr }
}
/// Consume the display interface and return
/// the bus and GPIO pins used by it
pub fn release(self) -> (BUS, DC, WR) {
(self.bus, self.dc, self.wr)
}
fn write_iter(&mut self, iter: impl Iterator<Item = u8>) -> Result {
for value in iter {
self.wr.set_low().map_err(|_| DisplayError::BusWriteError)?;
self.bus.set_value(value)?;
self.wr
.set_high()
.map_err(|_| DisplayError::BusWriteError)?;
}
Ok(())
}
fn write_pairs(&mut self, iter: impl Iterator<Item = [u8; 2]>) -> Result {
use core::iter::once;
self.write_iter(iter.flat_map(|[first, second]| once(first).chain(once(second))))
}
fn write_data(&mut self, data: DataFormat<'_>) -> Result {
match data {
DataFormat::U8(slice) => self.write_iter(slice.iter().copied()),
DataFormat::U8Iter(iter) => self.write_iter(iter),
DataFormat::U16(slice) => self.write_pairs(slice.iter().copied().map(u16::to_ne_bytes)),
DataFormat::U16BE(slice) => {
self.write_pairs(slice.iter().copied().map(u16::to_be_bytes))
}
DataFormat::U16LE(slice) => {
self.write_pairs(slice.iter().copied().map(u16::to_le_bytes))
}
DataFormat::U16BEIter(iter) => self.write_pairs(iter.map(u16::to_be_bytes)),
DataFormat::U16LEIter(iter) => self.write_pairs(iter.map(u16::to_le_bytes)),
_ => Err(DisplayError::DataFormatNotImplemented),
}
}
}
impl<BUS, DC, WR> WriteOnlyDataCommand for PGPIO8BitInterface<BUS, DC, WR>
where
BUS: OutputBus<Word = u8>,
DC: OutputPin,
WR: OutputPin,
{
fn send_commands(&mut self, cmds: DataFormat<'_>) -> Result {
self.dc.set_low().map_err(|_| DisplayError::DCError)?;
self.write_data(cmds)
}
fn send_data(&mut self, buf: DataFormat<'_>) -> Result {
self.dc.set_high().map_err(|_| DisplayError::DCError)?;
self.write_data(buf)
}
}
/// Parallel 16 Bit communication interface
///
/// This interface implements a 16-Bit "8080" style write-only display interface using any
/// 16-bit [OutputBus] implementation as well as one
/// `OutputPin` for the data/command selection and one `OutputPin` for the write-enable flag.
///
/// All pins are supposed to be high-active, high for the D/C pin meaning "data" and the
/// write-enable being pulled low before the setting of the bits and supposed to be sampled at a
/// low to high edge.
pub struct PGPIO16BitInterface<BUS, DC, WR> {
bus: BUS,
dc: DC,
wr: WR,
}
impl<BUS, DC, WR> PGPIO16BitInterface<BUS, DC, WR>
where
BUS: OutputBus<Word = u16>,
DC: OutputPin,
WR: OutputPin,
{
/// Create new parallel GPIO interface for communication with a display driver
pub fn new(bus: BUS, dc: DC, wr: WR) -> Self {
Self { bus, dc, wr }
}
/// Consume the display interface and return
/// the bus and GPIO pins used by it
pub fn release(self) -> (BUS, DC, WR) {
(self.bus, self.dc, self.wr)
}
fn write_iter(&mut self, iter: impl Iterator<Item = u16>) -> Result {
for value in iter {
self.wr.set_low().map_err(|_| DisplayError::BusWriteError)?;
self.bus.set_value(value)?;
self.wr
.set_high()
.map_err(|_| DisplayError::BusWriteError)?;
}
Ok(())
}
fn write_data(&mut self, data: DataFormat<'_>) -> Result {
match data {
DataFormat::U8(slice) => self.write_iter(slice.iter().copied().map(u16::from)),
DataFormat::U8Iter(iter) => self.write_iter(iter.map(u16::from)),
DataFormat::U16(slice) => self.write_iter(slice.iter().copied()),
DataFormat::U16BE(slice) => self.write_iter(slice.iter().copied()),
DataFormat::U16LE(slice) => self.write_iter(slice.iter().copied()),
DataFormat::U16BEIter(iter) => self.write_iter(iter),
DataFormat::U16LEIter(iter) => self.write_iter(iter),
_ => Err(DisplayError::DataFormatNotImplemented),
}
}
}
impl<BUS, DC, WR> WriteOnlyDataCommand for PGPIO16BitInterface<BUS, DC, WR>
where
BUS: OutputBus<Word = u16>,
DC: OutputPin,
WR: OutputPin,
{
fn send_commands(&mut self, cmds: DataFormat<'_>) -> Result {
self.dc.set_low().map_err(|_| DisplayError::DCError)?;
self.write_data(cmds)
}
fn send_data(&mut self, buf: DataFormat<'_>) -> Result {
self.dc.set_high().map_err(|_| DisplayError::DCError)?;
self.write_data(buf)
}
}
|
use serde::Deserialize;
#[derive(Debug, Default, Deserialize)]
pub struct MultiDimensional {
#[serde(rename = "k")]
pub value: Vec<f64>,
#[serde(rename = "x")]
pub expression: Option<String>,
#[serde(rename = "ix")]
pub index: Option<i64>,
}
|
use super::Room;
impl Room {
pub fn add_character_texture(&mut self) -> Cmd {}
}
|
enum CarType {
hatch,
sedan,
suv
}
fn print_size(car:CarType){
match car {
hatch => println!("Small sized car"),
sedan => println!("Medium sized car"),
suv => println!("Large sized car")
}
}
fn main() {
print_size(CarType::hatch);
print_size(CarType::sedan);
print_size(CarType::suv);
}
|
#![feature(uniform_paths)]
mod linked_stack;
mod singly_linked_list;
pub use linked_stack::LinkedStack;
pub use singly_linked_list::SinglyLinkedList;
|
use std::path::PathBuf;
use std::process::{Child, Command};
use std::thread::sleep;
use std::{convert::TryInto, fs, time::Duration};
use criterion::measurement::WallTime;
use criterion::{criterion_group, criterion_main, BenchmarkGroup, Criterion};
use reqwest::blocking::Client;
use reqwest::blocking::ClientBuilder;
use reqwest::Result;
use serde::{Deserialize, Serialize};
use htsget_config::types::{Headers, JsonResponse};
use htsget_http::{PostRequest, Region};
use htsget_test::http_tests::{default_config_fixed_port, default_dir, default_dir_data};
const REFSERVER_DOCKER_IMAGE: &str = "ga4gh/htsget-refserver:1.5.0";
const BENCHMARK_DURATION_SECONDS: u64 = 30;
const NUMBER_OF_SAMPLES: usize = 50;
#[derive(Serialize)]
struct Empty;
#[derive(Deserialize)]
struct RefserverConfig {
#[serde(rename = "htsgetConfig")]
htsget_config: RefserverProps,
}
#[derive(Deserialize)]
struct RefserverProps {
props: RefserverAddr,
}
#[derive(Deserialize)]
struct RefserverAddr {
port: u64,
host: String,
}
struct DropGuard(Child);
impl Drop for DropGuard {
fn drop(&mut self) {
drop(self.0.kill());
}
}
fn request(url: reqwest::Url, json_content: &impl Serialize, client: &Client) -> usize {
let response: JsonResponse = client
.post(url)
.json(json_content)
.send()
.unwrap()
.json()
.unwrap();
response
.htsget
.urls
.iter()
.map(|json_url| {
Ok(
client
.get(&json_url.url)
.headers(
json_url
.headers
.as_ref()
.unwrap_or(&Headers::default())
.as_ref_inner()
.try_into()
.unwrap(),
)
.send()?
.bytes()?
.len(),
)
})
.fold(0, |acc, x: Result<usize>| acc + x.unwrap_or(0))
}
fn format_url(url: &str, path: &str) -> reqwest::Url {
reqwest::Url::parse(url)
.expect("invalid url")
.join(path)
.expect("invalid url")
}
fn bench_pair(
group: &mut BenchmarkGroup<WallTime>,
name: &str,
htsget_url: reqwest::Url,
refserver_url: reqwest::Url,
json_content: &impl Serialize,
) {
let client = ClientBuilder::new()
.danger_accept_invalid_certs(true)
.use_rustls_tls()
.build()
.unwrap();
group.bench_with_input(
format!("{} {}", name, "htsget-rs"),
&htsget_url,
|b, input| b.iter(|| request(input.clone(), json_content, &client)),
);
group.bench_with_input(
format!("{} {}", name, "htsget-refserver"),
&refserver_url,
|b, input| b.iter(|| request(input.clone(), json_content, &client)),
);
}
#[cfg(target_os = "windows")]
pub fn new_command(cmd: &str) -> Command {
let mut command = Command::new("cmd.exe");
command.arg("/c");
command.arg(cmd);
command
}
#[cfg(not(target_os = "windows"))]
pub fn new_command(cmd: &str) -> Command {
Command::new(cmd)
}
fn query_server_until_response(url: &reqwest::Url) {
let client = Client::new();
for _ in 0..120 {
sleep(Duration::from_secs(1));
if let Err(err) = client.get(url.clone()).send() {
if err.is_connect() {
continue;
}
}
break;
}
}
fn start_htsget_rs() -> (DropGuard, String) {
let config = default_config_fixed_port();
let child = new_command("cargo")
.current_dir(default_dir())
.arg("run")
.arg("-p")
.arg("htsget-actix")
.arg("--no-default-features")
.env("HTSGET_PATH", default_dir_data())
.env("RUST_LOG", "warn")
.spawn()
.unwrap();
let htsget_rs_url = format!("http://{}", config.ticket_server().addr());
query_server_until_response(&format_url(&htsget_rs_url, "reads/service-info"));
let htsget_rs_ticket_url = format!("http://{}", config.data_server().addr());
query_server_until_response(&format_url(&htsget_rs_ticket_url, ""));
(DropGuard(child), htsget_rs_url)
}
fn start_htsget_refserver() -> (DropGuard, String) {
let config_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("benches")
.join("htsget-refserver-config.json");
let refserver_config: RefserverConfig =
serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();
new_command("docker")
.arg("image")
.arg("pull")
.arg(REFSERVER_DOCKER_IMAGE)
.spawn()
.unwrap()
.wait()
.unwrap();
let child = new_command("docker")
.current_dir(default_dir())
.arg("container")
.arg("run")
.arg("-p")
.arg(format!(
"{}:3000",
&refserver_config.htsget_config.props.port
))
.arg("-v")
.arg(format!(
"{}:/data",
default_dir()
.join("data")
.canonicalize()
.unwrap()
.to_string_lossy()
))
.arg("-v")
.arg(format!(
"{}:/config",
&config_path
.canonicalize()
.unwrap()
.parent()
.unwrap()
.to_string_lossy()
))
.arg(REFSERVER_DOCKER_IMAGE)
.arg("./htsget-refserver")
.arg("-config")
.arg("/config/htsget-refserver-config.json")
.spawn()
.unwrap();
let refserver_url = refserver_config.htsget_config.props.host;
query_server_until_response(&format_url(&refserver_url, "reads/service-info"));
(DropGuard(child), refserver_url)
}
fn criterion_benchmark(c: &mut Criterion) {
let mut group = c.benchmark_group("Requests");
group
.sample_size(NUMBER_OF_SAMPLES)
.measurement_time(Duration::from_secs(BENCHMARK_DURATION_SECONDS));
let (_htsget_rs_server, htsget_rs_url) = start_htsget_rs();
let (_htsget_refserver_server, htsget_refserver_url) = start_htsget_refserver();
let json_content = PostRequest {
format: None,
class: None,
fields: None,
tags: None,
notags: None,
regions: None,
};
bench_pair(
&mut group,
"[LIGHT] simple request",
format_url(&htsget_rs_url, "reads/data/bam/htsnexus_test_NA12878"),
format_url(&htsget_refserver_url, "reads/htsnexus_test_NA12878"),
&json_content,
);
let json_content = PostRequest {
format: None,
class: None,
fields: None,
tags: None,
notags: None,
regions: Some(vec![Region {
reference_name: "20".to_string(),
start: None,
end: None,
}]),
};
bench_pair(
&mut group,
"[LIGHT] with region",
format_url(&htsget_rs_url, "reads/data/bam/htsnexus_test_NA12878"),
format_url(&htsget_refserver_url, "reads/htsnexus_test_NA12878"),
&json_content,
);
let json_content = PostRequest {
format: None,
class: None,
fields: None,
tags: None,
notags: None,
regions: Some(vec![
Region {
reference_name: "20".to_string(),
start: None,
end: None,
},
Region {
reference_name: "11".to_string(),
start: Some(4999977),
end: Some(5008321),
},
]),
};
bench_pair(
&mut group,
"[LIGHT] with two regions",
format_url(&htsget_rs_url, "reads/data/bam/htsnexus_test_NA12878"),
format_url(&htsget_refserver_url, "reads/htsnexus_test_NA12878"),
&json_content,
);
let json_content = PostRequest {
format: None,
class: None,
fields: None,
tags: None,
notags: None,
regions: Some(vec![Region {
reference_name: "chrM".to_string(),
start: Some(1),
end: Some(153),
}]),
};
bench_pair(
&mut group,
"[LIGHT] with VCF",
format_url(&htsget_rs_url, "variants/data/vcf/sample1-bcbio-cancer"),
format_url(&htsget_refserver_url, "variants/sample1-bcbio-cancer"),
&json_content,
);
let json_content = PostRequest {
format: None,
class: None,
fields: None,
tags: None,
notags: None,
regions: Some(vec![Region {
reference_name: "14".to_string(),
start: None,
end: None,
}]),
};
bench_pair(
&mut group,
"[HEAVY] with big VCF",
format_url(
&htsget_rs_url,
"variants/data/vcf/internationalgenomesample",
),
format_url(&htsget_refserver_url, "variants/internationalgenomesample"),
&json_content,
);
group.finish();
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
extern crate openssl;
#[macro_use]
extern crate juniper;
#[macro_use]
extern crate diesel;
extern crate serde_json;
use actix_cors::Cors;
use actix_web::{middleware, web, App, HttpServer};
use crate::db::get_db_pool;
use crate::handlers::register;
mod db;
mod handlers;
mod schema;
mod schemas;
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info,info");
env_logger::init();
let pool = get_db_pool();
HttpServer::new(move || {
App::new()
.data(pool.clone())
.wrap(middleware::Logger::default())
.wrap(Cors::default())
.configure(register)
.default_service(web::to(|| async { "404" }))
})
.bind("0.0.0.0:8080")?
.run()
.await
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::io;
use std::net::SocketAddr;
use std::path::Path;
use bytes::BytesMut;
use futures::future;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::net::UnixListener;
use tokio::net::UnixStream;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use super::error::Error;
use super::inferior::StoppedInferior;
use super::packet::Packet;
use super::session::Session;
/// GdbServer controller
pub struct GdbServer {
/// Signal gdbserver to start.
pub server_tx: Option<oneshot::Sender<()>>,
/// Signal gdbserver the very first tracee is ready.
pub inferior_attached_tx: Option<mpsc::Sender<StoppedInferior>>,
/// FIXME: the tracees are serialized already, tell gdbserver not to
/// serialize by its own.
pub sequentialized_guest: bool,
}
impl GdbServer {
/// Creates a GDB server and binds to the given address.
///
/// NOTE: The canonical GDB server port is `1234`.
pub async fn from_addr(addr: SocketAddr) -> Result<Self, Error> {
let (inferior_attached_tx, inferior_attached_rx) = mpsc::channel(1);
let (server_tx, server_rx) = oneshot::channel();
let server = GdbServerImpl::from_addr(addr, server_rx, inferior_attached_rx).await?;
tokio::task::spawn(async move {
if let Err(err) = server.run().await {
tracing::error!("Failed to run gdbserver: {:?}", err);
}
});
Ok(Self {
server_tx: Some(server_tx),
inferior_attached_tx: Some(inferior_attached_tx),
sequentialized_guest: false,
})
}
/// Creates a GDB server from the given unix domain socket. This is useful
/// when we know there will only be one client and want to avoid binding to a
/// port.
pub async fn from_path(path: &Path) -> Result<Self, Error> {
let (inferior_attached_tx, inferior_attached_rx) = mpsc::channel(1);
let (server_tx, server_rx) = oneshot::channel();
let server = GdbServerImpl::from_path(path, server_rx, inferior_attached_rx).await?;
tokio::task::spawn(async move {
if let Err(err) = server.run().await {
tracing::error!("Failed to run gdbserver: {:?}", err);
}
});
Ok(Self {
server_tx: Some(server_tx),
inferior_attached_tx: Some(inferior_attached_tx),
sequentialized_guest: false,
})
}
pub fn sequentialized_guest(&mut self) -> &mut Self {
self.sequentialized_guest = true;
self
}
#[allow(unused)]
pub async fn notify_start(&mut self) -> Result<(), Error> {
if let Some(tx) = self.server_tx.take() {
tx.send(()).map_err(|_| Error::GdbServerNotStarted)
} else {
Ok(())
}
}
#[allow(unused)]
pub async fn notify_gdb_stop(&mut self, stopped: StoppedInferior) -> Result<(), Error> {
if let Some(tx) = self.inferior_attached_tx.take() {
tx.send(stopped)
.await
.map_err(|_| Error::GdbServerSendPacketError)
} else {
Ok(())
}
}
}
struct GdbServerImpl {
reader: Box<dyn AsyncRead + Send + Unpin>,
pkt_tx: mpsc::Sender<Packet>,
server_rx: Option<oneshot::Receiver<()>>,
session: Option<Session>,
}
/// Binds to the given address and waits for an incoming connection.
async fn wait_for_tcp_connection(addr: SocketAddr) -> io::Result<TcpStream> {
// NOTE: `tokio::net::TcpListener::bind` is not used here on purpose. It
// spawns an additional tokio worker thread. We want to avoid an extra
// thread here since it could perturb the deterministic allocation of PIDs.
// Using `std::net::TcpListener::bind` appears to avoid spawning an extra
// tokio worker thread.
let listener = std::net::TcpListener::bind(addr)?;
listener.set_nonblocking(true)?;
let listener = TcpListener::from_std(listener)?;
let (stream, client_addr) = listener.accept().await?;
tracing::info!("Accepting client connection: {:?}", client_addr);
Ok(stream)
}
/// Binds to the given socket path and waits for an incoming connection.
async fn wait_for_unix_connection(path: &Path) -> io::Result<UnixStream> {
let listener = UnixListener::bind(path)?;
let (stream, client_addr) = listener.accept().await?;
tracing::info!("Accepting client connection: {:?}", client_addr);
Ok(stream)
}
// NB: during handshake, gdb may send packet prefixed with `+' (Ack), or send
// `+' then the actual packet (send two times). Since Ack is also a valid packet
// This may cause confusion to Packet::try_from(), since it tries to decode one
// packet at a time.
enum PacketWithAck {
// Just a packet, note `+' only is considered to be `JustPacket'.
JustPacket(Packet),
// `+' (Ack) followed by a packet, such as `+StartNoAckMode'.
WithAck(Packet),
}
const PACKET_BUFFER_CAPACITY: usize = 0x8000;
impl GdbServerImpl {
/// Creates a new gdbserver, by accepting remote connection at `addr`.
async fn from_addr(
addr: SocketAddr,
server_rx: oneshot::Receiver<()>,
inferior_attached_rx: mpsc::Receiver<StoppedInferior>,
) -> Result<Self, Error> {
let stream = wait_for_tcp_connection(addr)
.await
.map_err(|source| Error::WaitForGdbConnect { source })?;
let (reader, writer) = stream.into_split();
let (tx, rx) = mpsc::channel(1);
// create a gdb session.
let session = Session::new(Box::new(writer), rx, inferior_attached_rx);
Ok(GdbServerImpl {
reader: Box::new(reader),
pkt_tx: tx,
server_rx: Some(server_rx),
session: Some(session),
})
}
/// Creates a GDB server and listens on the given unix domain socket.
async fn from_path(
path: &Path,
server_rx: oneshot::Receiver<()>,
inferior_attached_rx: mpsc::Receiver<StoppedInferior>,
) -> Result<Self, Error> {
let stream = wait_for_unix_connection(path)
.await
.map_err(|source| Error::WaitForGdbConnect { source })?;
let (reader, writer) = stream.into_split();
let (tx, rx) = mpsc::channel(1);
// Create a gdb session.
let session = Session::new(Box::new(writer), rx, inferior_attached_rx);
Ok(GdbServerImpl {
reader: Box::new(reader),
pkt_tx: tx,
server_rx: Some(server_rx),
session: Some(session),
})
}
async fn recv_packet(&mut self) -> Result<PacketWithAck, Error> {
let mut rx_buf = BytesMut::with_capacity(PACKET_BUFFER_CAPACITY);
self.reader
.read_buf(&mut rx_buf)
.await
.map_err(|_| Error::ConnReset)?;
// packet to follow, such as `+StartNoAckMode`.
Ok(if rx_buf.starts_with(b"+") && rx_buf.len() > 1 {
PacketWithAck::WithAck(Packet::new(rx_buf.split_off(1))?)
} else {
PacketWithAck::JustPacket(Packet::new(rx_buf.split())?)
})
}
async fn send_packet(&mut self, packet: Packet) -> Result<(), Error> {
self.pkt_tx
.send(packet)
.await
.map_err(|_| Error::GdbServerSendPacketError)
}
async fn relay_gdb_packets(&mut self) -> Result<(), Error> {
while let Ok(pkt) = self.recv_packet().await {
match pkt {
PacketWithAck::JustPacket(pkt) => {
self.send_packet(Packet::Ack).await?;
self.send_packet(pkt).await?;
}
PacketWithAck::WithAck(pkt) => self.send_packet(pkt).await?,
}
}
// remote client closed connection.
Ok(())
}
/// Run gdbserver.
///
/// The gdbserver can run in a separate tokio thread pool.
///
/// ```no_compile
/// let gdbserver = GdbServer::new(..).await?;
/// let handle = tokio::task::spawn(gdbserver.run());
/// // snip
/// handle.await??
/// ```
async fn run(mut self) -> Result<(), Error> {
// NB: waiting for initial request to start gdb server. This is
// required because if gdbserver is started too soon, gdb (client)
// could get timeout. Some requests such as `g' needs IPC with a
// gdb session, which only becomes ready later.
if let Some(server_rx) = self.server_rx.take() {
let _ = server_rx.await.map_err(|_| Error::GdbServerNotStarted)?;
let mut session = self.session.take().ok_or(Error::SessionNotStarted)?;
let run_session = session.run();
let run_loop = self.relay_gdb_packets();
future::try_join(run_session, run_loop).await?;
}
Ok(())
}
}
|
mod context;
mod errors;
mod lisp_ops;
mod storage;
mod value;
pub use context::Context;
pub use errors::{ErrorKind, LispError, LispResult};
pub use lisp_ops::LispOps;
pub use value::LispValue;
pub trait LispData: Sized {
type Integer;
type Symbol;
type ByteArray;
fn is_nil(&self) -> bool;
fn is_bool(&self) -> bool;
fn is_true(&self) -> bool;
fn is_number(&self) -> bool;
fn is_symbol(&self) -> bool;
fn is_pair(&self) -> bool;
fn undefined() -> Self;
fn nil() -> Self;
fn bool(b: bool) -> Self;
fn int(i: Self::Integer) -> Self;
fn char(ch: char) -> Self;
fn symbol(s: &str) -> Self;
fn keyword(s: &str) -> Self;
fn set_car(&self, item: Self) -> LispResult<()>;
fn set_cdr(&self, item: Self) -> LispResult<()>;
fn set_array_item(&self, index: usize, item: Self) -> LispResult<()>;
fn car(&self) -> LispResult<Self>;
fn cdr(&self) -> LispResult<Self>;
fn get_array_item(&self, index: usize) -> LispResult<Self>;
fn string_from_array(self) -> Option<Self>;
fn equals_str(&self, s: &str) -> bool;
}
pub trait Managable: Sized + Copy + Default {
fn record(ptr: *mut Self, len: usize) -> Self;
fn array(ptr: *mut u8, len: usize) -> Self;
fn relocated(ptr: *const Self) -> Self;
unsafe fn as_array(&self) -> Option<&mut [u8]>;
unsafe fn as_record(&self) -> Option<&mut [Self]>;
fn as_relocated(&self) -> Option<*const Self>;
fn is_record(&self) -> bool {
unsafe { self.as_record().is_some() }
}
fn is_relocated(&self) -> bool {
self.as_relocated().is_some()
}
fn is_array(&self) -> bool {
unsafe { self.as_array().is_some() }
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.