text stringlengths 8 4.13M |
|---|
use crate::{
queries::tokens::Token,
};
use actix::Message;
use chrono::{DateTime, Utc};
use derive_more::From;
use serde::{Serialize, Deserialize, Deserializer};
use std::{
convert::Infallible,
result::Result,
};
use strum_macros::AsRefStr;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionIdSubjectAction {
pub id: i32,
pub subject: String,
pub action: String,
}
// From https://github.com/serde-rs/serde/issues/984#issuecomment-314143738
pub fn double_option<'de, T, D>(de: D) -> Result<Option<Option<T>>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de> {
Deserialize::deserialize(de).map(Some)
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
#[serde(transparent)]
pub struct TokenAcquired(pub Token);
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct TokenRevoked {
pub jti: i32,
pub uid: i32,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UserCreated {
pub id: i32,
pub username: String,
pub roles: Vec<String>,
pub email: Option<String>,
pub created_at: DateTime<Utc>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UserDeleted {
pub id: i32,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UserUpdated {
pub id: i32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub username: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub password: Option<()>,
#[serde(deserialize_with = "double_option")]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub email: Option<Option<String>>,
#[serde(deserialize_with = "double_option")]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub nickname: Option<Option<String>>,
#[serde(deserialize_with = "double_option")]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub avatar: Option<Option<String>>,
#[serde(deserialize_with = "double_option")]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub avatar128: Option<Option<String>>,
#[serde(deserialize_with = "double_option")]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub blocked: Option<Option<bool>>,
pub updated_at: DateTime<Utc>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct InternalUserRoleCreated {
pub user: i32,
pub role: i32,
pub role_permissions: Vec<PermissionIdSubjectAction>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UserRoleCreated {
pub user: i32,
pub role: i32,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UserRoleDeleted {
pub user: i32,
pub role: i32,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct InternalRolePermissionCreated {
pub role: i32,
pub permission: i32,
pub subject: String,
pub action: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RolePermissionCreated {
pub role: i32,
pub permission: i32,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RolePermissionDeleted {
pub role: i32,
pub permission: i32,
}
#[derive(Debug, Serialize, Deserialize, From, Clone, AsRefStr)]
#[serde(tag = "type")]
#[serde(rename_all = "kebab-case")]
pub enum InnerInternalMessage {
TokenAcquired(TokenAcquired),
TokenRevoked(TokenRevoked),
UserCreated(UserCreated),
UserUpdated(UserUpdated),
UserDeleted(UserDeleted),
UserRoleCreated(InternalUserRoleCreated),
UserRoleDeleted(UserRoleDeleted),
RolePermissionCreated(InternalRolePermissionCreated),
RolePermissionDeleted(RolePermissionDeleted),
}
#[derive(Debug, Serialize, Deserialize, Message, Clone)]
#[rtype(result = "Result<(), Infallible>")]
#[serde(rename_all = "camelCase")]
pub struct InternalMessage {
pub sender_uid: Option<i32>,
pub sender_jti: Option<i32>,
pub messages: Vec<InnerInternalMessage>,
pub created_at: DateTime<Utc>,
}
#[derive(Debug, Serialize, Deserialize, From, Clone, AsRefStr)]
#[serde(tag = "type")]
#[serde(rename_all = "kebab-case")]
pub enum InnerPublicMessage {
TokenAcquired(TokenAcquired),
TokenRevoked(TokenRevoked),
UserCreated(UserCreated),
UserUpdated(UserUpdated),
UserDeleted(UserDeleted),
UserRoleCreated(UserRoleCreated),
UserRoleDeleted(UserRoleDeleted),
RolePermissionCreated(RolePermissionCreated),
RolePermissionDeleted(RolePermissionDeleted),
}
#[derive(Debug, Serialize, Deserialize, Message, Clone)]
#[rtype(result = "Result<(), Infallible>")]
#[serde(rename_all = "camelCase")]
pub struct PublicMessage {
pub sender_uid: Option<i32>,
pub sender_jti: Option<i32>,
pub messages: Vec<InnerPublicMessage>,
pub created_at: DateTime<Utc>,
} |
pub let kill_AV: bool = false;
pub let bypass_AV: bool = false; |
extern crate httpserver;
use httpserver::options::Options;
use httpserver::webserver::WebServer;
fn main() {
let options = Options::new(String::from("127.0.0.1:8080"), 4);
let server = WebServer::new(options);
server.start();
}
|
use byteorder;
use std::io::Cursor;
use self::byteorder::{ByteOrder, BigEndian, WriteBytesExt, ReadBytesExt};
pub type Instructions = Vec<u8>;
pub trait InstructionsFns {
fn string(&self) -> String;
fn fmt_instruction(op: &Op, operands: &Vec<usize>) -> String;
}
impl InstructionsFns for Instructions {
fn string(&self) -> String {
let mut ret = String::new();
let mut i = 0;
while i < self.len() {
let op:u8 = *self.get(i).unwrap();
let op = unsafe { ::std::mem::transmute(op) };
let (operands, read) = read_operands(&op, &self[i+1..]);
ret.push_str(&format!("{:04} {}\n", i, Self::fmt_instruction(&op, &operands)));
i = i + 1 + read;
}
ret
}
fn fmt_instruction(op: &Op, operands: &Vec<usize>) -> String {
match op.operand_widths().len() {
2 => format!("{} {} {}", op.name(), operands[0], operands[1]),
1 => format!("{} {}", op.name(), operands[0]),
0 => format!("{}", op.name()),
_ => panic!("unsuported operand width")
}
}
}
#[repr(u8)]
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Op {
Constant,
Add,
Sub,
Mul,
Div,
Pop,
True,
False,
Equal,
NotEqual,
GreaterThan,
Minus,
Bang,
JumpNotTruthy,
Jump,
Null,
GetGlobal,
SetGobal,
Array,
Hash,
Index,
Call,
ReturnValue,
Return,
GetLocal,
SetLocal,
GetBuiltin,
Closure,
GetFree,
}
impl Op {
pub fn name(&self) -> &str {
match self {
Op::Constant => "OpConstant",
Op::Add => "OpAdd",
Op::Sub => "OpSub",
Op::Mul => "OpMul",
Op::Div => "OpDiv",
Op::Pop => "OpPop",
Op::True => "OpTrue",
Op::False => "OpFalse",
Op::Equal => "OpEqual",
Op::NotEqual => "OpNotEqual",
Op::GreaterThan => "OpGreaterThan",
Op::Minus => "OpMinus",
Op::Bang => "OpBang",
Op::JumpNotTruthy => "OpJumpNotTruthy",
Op::Jump => "OpJump",
Op::Null => "OpNull",
Op::GetGlobal => "OpGetGlobal",
Op::SetGobal => "OpSetGlobal",
Op::Array => "OpArray",
Op::Hash => "OpHash",
Op::Index => "OpIndex",
Op::Call => "OpCall",
Op::ReturnValue => "OpReturnValue",
Op::Return => "OpReturn",
Op::GetLocal => "OpGetLocal",
Op::SetLocal => "OpSetLocal",
Op::GetBuiltin => "OpGetBuiltin",
Op::Closure => "OpClosure",
Op::GetFree => "OpGetFree",
}
}
pub fn operand_widths(&self) -> Vec<u8> {
match self {
Op::Constant | Op::JumpNotTruthy | Op::Jump |
Op::SetGobal | Op::GetGlobal | Op::Array | Op::Hash => vec![2],
Op::Add | Op::Sub | Op::Mul |
Op::Div | Op::Pop | Op::True |
Op::False | Op::Equal | Op::NotEqual |
Op::GreaterThan | Op::Minus | Op::Bang | Op::Null |
Op::Index | Op::ReturnValue | Op::Return => vec![],
Op::GetLocal | Op::SetLocal | Op::Call | Op::GetBuiltin | Op::GetFree => vec![1],
Op::Closure => vec![2, 1],
}
}
}
pub fn make_instruction(op: Op, operands: &Vec<usize>) -> Vec<u8> {
let mut instruction = Vec::new();
let widths = op.operand_widths();
instruction.push(op as u8);
for (o, width) in operands.into_iter().zip(widths) {
match width {
2 => {
instruction.write_u16::<BigEndian>(*o as u16).unwrap()
},
1 => {
instruction.write_u8(*o as u8).unwrap()
},
_ => panic!("unsupported operand width {}", width),
};
}
instruction
}
pub fn read_operands(op: &Op, instructions: &[u8]) -> (Vec<usize>, usize) {
let mut operands = Vec::with_capacity(op.operand_widths().len());
let mut offset = 0;
for width in op.operand_widths() {
match width {
2 => {
operands.push(BigEndian::read_u16(&instructions[offset..offset+2]) as usize);
offset += 2;
},
1 => {
operands.push(instructions[offset] as usize);
offset += 1;
},
_ => panic!("width not supported for operand")
}
}
(operands, offset)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn make() {
struct Test {
op: Op,
operands: Vec<usize>,
expected: Vec<u8>,
}
let tests = vec![
Test{op: Op::Constant, operands: vec![65534], expected: vec![Op::Constant as u8, 255, 254]},
Test{op: Op::Add, operands: vec![], expected: vec![Op::Add as u8]},
Test{op: Op::GetLocal, operands: vec![255], expected: vec![Op::GetLocal as u8, 255]},
Test{op: Op::Call, operands: vec![255], expected: vec![Op::Call as u8, 255]},
];
for t in tests {
let instruction = make_instruction(t.op, &t.operands);
assert_eq!(t.expected, instruction)
}
}
#[test]
fn instructions_string() {
let instructions = vec![
make_instruction(Op::Add, &vec![]),
make_instruction(Op::GetLocal, &vec![1]),
make_instruction(Op::Constant, &vec![2]),
make_instruction(Op::Constant, &vec![65535]),
make_instruction(Op::Closure, &vec![65535, 255]),
];
let expected = "0000 OpAdd\n\
0001 OpGetLocal 1\n\
0003 OpConstant 2\n\
0006 OpConstant 65535\n\
0009 OpClosure 65535 255\n";
let concatted = instructions.into_iter().flatten().collect::<Instructions>();
assert_eq!(expected, concatted.string())
}
#[test]
fn test_read_operands() {
struct Test {
op: Op,
operands: Vec<usize>,
bytes_read: usize,
}
let tests = vec![
Test{op: Op::Constant, operands: vec![65535], bytes_read: 2},
Test{op: Op::GetLocal, operands: vec![255], bytes_read: 1},
];
for t in tests {
let instruction = make_instruction(t.op.clone(), &t.operands);
let (operands_read, n) = read_operands(&t.op, &instruction[1..]);
assert_eq!(n, t.bytes_read);
assert_eq!(operands_read, t.operands);
}
}
} |
use std::fs::File;
use std::io::{self, Read as _};
use std::time::Instant;
use json;
use simsearch::SimSearch;
fn main() -> io::Result<()> {
let mut engine = SimSearch::new();
let mut file = File::open("./books.json")?;
let mut content = String::new();
file.read_to_string(&mut content)?;
let j = json::parse(&content).unwrap();
for title in j.members() {
engine.insert(title.as_str().unwrap(), title.as_str().unwrap());
}
println!("Please input a query string and hit enter (e.g 'old man'):",);
loop {
let mut pattern = String::new();
io::stdin()
.read_line(&mut pattern)
.expect("failed to read from stdin");
let start = Instant::now();
let res = engine.search(&pattern);
let end = Instant::now();
println!("pattern: {:?}", pattern.trim());
println!("results: {:?}", res);
println!("time: {:?}", end - start);
}
}
|
extern crate timely;
extern crate differential_dataflow;
#[macro_use]
extern crate abomonation_derive;
extern crate abomonation;
#[macro_use]
extern crate serde_derive;
use std::string::String;
use std::boxed::Box;
use std::ops::Deref;
use std::collections::{HashMap, HashSet};
use timely::dataflow::*;
use timely::dataflow::scopes::{Root, Child};
use timely::progress::Timestamp;
use timely::progress::timestamp::RootTimestamp;
use timely::progress::nested::product::Product;
use timely::dataflow::operators::probe::{Handle};
use differential_dataflow::collection::{Collection};
use differential_dataflow::lattice::Lattice;
use differential_dataflow::input::{Input, InputSession};
use differential_dataflow::trace::implementations::ord::{OrdValSpine, OrdKeySpine};
use differential_dataflow::operators::arrange::{ArrangeByKey, ArrangeBySelf, TraceAgent, Arranged};
use differential_dataflow::operators::group::Threshold;
use differential_dataflow::operators::join::{JoinCore};
use differential_dataflow::operators::iterate::Variable;
//
// TYPES
//
pub type Entity = u64;
pub type Attribute = u32;
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Abomonation, Debug, Serialize, Deserialize)]
pub enum Value {
Eid(Entity),
Attribute(Attribute),
Number(i64),
String(String),
}
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Abomonation, Debug, Serialize, Deserialize)]
pub struct Datom(pub Entity, pub Attribute, pub Value);
#[derive(Deserialize, Debug)]
pub struct TxData(pub isize, pub Entity, pub Attribute, pub Value);
#[derive(Serialize, Debug)]
pub struct Out(Vec<Value>, isize);
type ProbeHandle<T> = Handle<Product<RootTimestamp, T>>;
type TraceKeyHandle<K, T, R> = TraceAgent<K, (), T, R, OrdKeySpine<K, T, R>>;
type TraceValHandle<K, V, T, R> = TraceAgent<K, V, T, R, OrdValSpine<K, V, T, R>>;
type Arrange<G: Scope, K, V, R> = Arranged<G, K, V, R, TraceValHandle<K, V, G::Timestamp, R>>;
type ArrangeSelf<G: Scope, K, R> = Arranged<G, K, (), R, TraceKeyHandle<K, G::Timestamp, R>>;
type InputMap<G: Scope> = HashMap<(Option<Entity>, Option<Attribute>, Option<Value>), ArrangeSelf<G, Vec<Value>, isize>>;
type QueryMap<T, R> = HashMap<String, TraceKeyHandle<Vec<Value>, Product<RootTimestamp, T>, R>>;
type RelationMap<'a, G> = HashMap<String, NamedRelation<'a, G>>;
//
// CONTEXT
//
pub struct DB<T: Timestamp+Lattice> {
e_av: TraceValHandle<Vec<Value>, Vec<Value>, Product<RootTimestamp, T>, isize>,
a_ev: TraceValHandle<Vec<Value>, Vec<Value>, Product<RootTimestamp, T>, isize>,
ea_v: TraceValHandle<Vec<Value>, Vec<Value>, Product<RootTimestamp, T>, isize>,
av_e: TraceValHandle<Vec<Value>, Vec<Value>, Product<RootTimestamp, T>, isize>,
}
struct ImplContext<G: Scope + ScopeParent> where G::Timestamp : Lattice {
// Imported traces
e_av: Arrange<G, Vec<Value>, Vec<Value>, isize>,
a_ev: Arrange<G, Vec<Value>, Vec<Value>, isize>,
ea_v: Arrange<G, Vec<Value>, Vec<Value>, isize>,
av_e: Arrange<G, Vec<Value>, Vec<Value>, isize>,
// Parameter inputs
input_map: InputMap<G>,
// Collection variables for recursion
// variable_map: RelationMap<'a, G>,
}
pub struct Context<T: Timestamp+Lattice> {
pub input_handle: InputSession<T, Datom, isize>,
pub db: DB<T>,
pub probes: Vec<ProbeHandle<T>>,
pub queries: QueryMap<T, isize>,
}
//
// QUERY PLAN GRAMMAR
//
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum Plan {
Project(Box<Plan>, Vec<Var>),
Union(Box<Plan>, Box<Plan>, Vec<Var>),
Join(Box<Plan>, Box<Plan>, Var),
Not(Box<Plan>),
Lookup(Entity, Attribute, Var),
Entity(Entity, Var, Var),
HasAttr(Var, Attribute, Var),
Filter(Var, Attribute, Value),
Recur(Vec<Var>),
}
type Var = u32;
//
// RELATIONS
//
trait Relation<'a, G: Scope> where G::Timestamp : Lattice {
fn symbols(&self) -> &Vec<Var>;
fn tuples(self) -> Collection<Child<'a, G, u64>, Vec<Value>, isize>;
fn tuples_by_symbols(self, syms: Vec<Var>) -> Collection<Child<'a, G, u64>, (Vec<Value>, Vec<Value>), isize>;
}
pub struct RelationHandles<T: Timestamp+Lattice> {
pub input: InputSession<T, Vec<Value>, isize>,
pub trace: TraceKeyHandle<Vec<Value>, Product<RootTimestamp, T>, isize>,
}
struct SimpleRelation<'a, G: Scope> where G::Timestamp : Lattice {
symbols: Vec<Var>,
tuples: Collection<Child<'a, G, u64>, Vec<Value>, isize>,
}
impl<'a, G: Scope> Relation<'a, G> for SimpleRelation<'a, G> where G::Timestamp : Lattice {
fn symbols(&self) -> &Vec<Var> { &self.symbols }
fn tuples(self) -> Collection<Child<'a, G, u64>, Vec<Value>, isize> { self.tuples }
fn tuples_by_symbols(self, syms: Vec<Var>) -> Collection<Child<'a, G, u64>, (Vec<Value>, Vec<Value>), isize>{
let key_length = syms.len();
let values_length = self.symbols().len() - key_length;
let mut key_offsets: Vec<usize> = Vec::with_capacity(key_length);
let mut value_offsets: Vec<usize> = Vec::with_capacity(values_length);
let sym_set: HashSet<Var> = syms.iter().cloned().collect();
// It is important to preservere the key symbols in the order
// they were specified.
for sym in syms.iter() {
key_offsets.push(self.symbols().iter().position(|&v| *sym == v).unwrap());
}
// Values we'll just take in the order they were.
for (idx, sym) in self.symbols().iter().enumerate() {
if sym_set.contains(sym) == false {
value_offsets.push(idx);
}
}
// let debug_keys: Vec<String> = key_offsets.iter().map(|x| x.to_string()).collect();
// let debug_values: Vec<String> = value_offsets.iter().map(|x| x.to_string()).collect();
// println!("key offsets: {:?}", debug_keys);
// println!("value offsets: {:?}", debug_values);
self.tuples()
.map(move |tuple| {
let key: Vec<Value> = key_offsets.iter().map(|i| tuple[*i].clone()).collect();
// @TODO second clone not really neccessary
let values: Vec<Value> = value_offsets.iter().map(|i| tuple[*i].clone()).collect();
(key, values)
})
}
}
struct NamedRelation<'a, G: Scope> where G::Timestamp : Lattice {
variable: Option<Variable<'a, G, Vec<Value>, isize>>,
tuples: Collection<Child<'a, G, u64>, Vec<Value>, isize>,
}
impl<'a, G: Scope> NamedRelation<'a, G> where G::Timestamp : Lattice {
pub fn from (source: &Collection<Child<'a, G, u64>, Vec<Value>, isize>) -> Self {
let variable = Variable::from(source.clone());
NamedRelation {
variable: Some(variable),
tuples: source.clone(),
}
}
pub fn add_execution(&mut self, execution: &Collection<Child<'a, G, u64>, Vec<Value>, isize>) {
self.tuples = self.tuples.concat(execution);
}
}
impl<'a, G: Scope> Drop for NamedRelation<'a, G> where G::Timestamp : Lattice {
fn drop(&mut self) {
if let Some(variable) = self.variable.take() {
variable.set(&self.tuples.distinct());
}
}
}
//
// QUERY PLAN IMPLEMENTATION
//
/// Takes a query plan and turns it into a differential dataflow. The
/// dataflow is extended to feed output tuples to JS clients. A probe
/// on the dataflow is returned.
fn implement<A: timely::Allocate, T: Timestamp+Lattice> (name: &String, plan: Plan, scope: &mut Child<Root<A>, T>, ctx: &mut Context<T>) -> HashMap<String, RelationHandles<T>> {
let db = &mut ctx.db;
let queries = &mut ctx.queries;
// @TODO Only import those we need for the query?
let impl_ctx: ImplContext<Child<Root<A>, T>> = ImplContext {
e_av: db.e_av.import(scope),
a_ev: db.a_ev.import(scope),
ea_v: db.ea_v.import(scope),
av_e: db.av_e.import(scope),
input_map: create_inputs(&plan, scope)
};
let (source_handle, source) = scope.new_collection();
scope.scoped(|nested| {
let mut relation_map = HashMap::new();
let mut result_map = HashMap::new();
let output_relation = NamedRelation::from(&source.enter(nested));
let output_trace = output_relation.variable.as_ref().unwrap().leave().arrange_by_self().trace;
result_map.insert(name.clone(), RelationHandles { input: source_handle, trace: output_trace });
relation_map.insert("self".to_string(), output_relation);
let execution = implement_plan(&plan, &impl_ctx, nested, &relation_map, queries);
relation_map
.get_mut(&"self".to_string()).unwrap() // @TODO try without to_string
.add_execution(&execution.tuples());
result_map
})
}
fn create_inputs<'a, A: timely::Allocate, T: Timestamp+Lattice>
(plan: &Plan, scope: &mut Child<'a, Root<A>, T>) -> InputMap<Child<'a, Root<A>, T>> {
match plan {
&Plan::Project(ref plan, _) => { create_inputs(plan.deref(), scope) },
&Plan::Union(ref left_plan, ref right_plan, _) => {
let mut left_inputs = create_inputs(left_plan.deref(), scope);
let mut right_inputs = create_inputs(right_plan.deref(), scope);
for (k, v) in right_inputs.drain() {
left_inputs.insert(k, v);
}
left_inputs
},
&Plan::Join(ref left_plan, ref right_plan, _) => {
let mut left_inputs = create_inputs(left_plan.deref(), scope);
let mut right_inputs = create_inputs(right_plan.deref(), scope);
for (k, v) in right_inputs.drain() {
left_inputs.insert(k, v);
}
left_inputs
},
&Plan::Not(ref plan) => { create_inputs(plan.deref(), scope) },
&Plan::Lookup(e, a, _) => {
let mut inputs = HashMap::new();
inputs.insert((Some(e), Some(a), None), scope.new_collection_from(vec![vec![Value::Eid(e), Value::Attribute(a)]]).1.arrange_by_self());
inputs
},
&Plan::Entity(e, _, _) => {
let mut inputs = HashMap::new();
inputs.insert((Some(e), None, None), scope.new_collection_from(vec![vec![Value::Eid(e)]]).1.arrange_by_self());
inputs
},
&Plan::HasAttr(_, a, _) => {
let mut inputs = HashMap::new();
inputs.insert((None, Some(a), None), scope.new_collection_from(vec![vec![Value::Attribute(a)]]).1.arrange_by_self());
inputs
},
&Plan::Filter(_, a, ref v) => {
let mut inputs = HashMap::new();
inputs.insert((None, Some(a), Some(v.clone())), scope.new_collection_from(vec![vec![Value::Attribute(a), v.clone()]]).1.arrange_by_self());
inputs
},
&Plan::Recur(_) => { HashMap::new() }
}
}
fn implement_plan<'a, 'b, A: timely::Allocate, T: Timestamp+Lattice>
(plan: &Plan,
db: &ImplContext<Child<'a, Root<A>, T>>,
nested: &mut Child<'b, Child<'a, Root<A>, T>, u64>,
relation_map: &RelationMap<'b, Child<'a, Root<A>, T>>,
queries: &QueryMap<T, isize>) -> SimpleRelation<'b, Child<'a, Root<A>, T>> {
match plan {
&Plan::Project(ref plan, ref symbols) => {
let mut relation = implement_plan(plan.deref(), db, nested, relation_map, queries);
let tuples = relation
.tuples_by_symbols(symbols.clone())
.map(|(key, _tuple)| key);
// @TODO distinct? or just before negation?
SimpleRelation { symbols: symbols.to_vec(), tuples }
},
&Plan::Union(ref left_plan, ref right_plan, ref symbols) => {
// @TODO can just concat more than two + a single distinct
// @TODO or move out distinct, except for negation
let mut left = implement_plan(left_plan.deref(), db, nested, relation_map, queries);
let mut right = implement_plan(right_plan.deref(), db, nested, relation_map, queries);
let mut left_tuples;
if left.symbols() == symbols {
left_tuples = left.tuples();
} else {
left_tuples = left
.tuples_by_symbols(symbols.clone())
.map(|(key, _tuple)| key);
}
let mut right_tuples;
if right.symbols() == symbols {
right_tuples = right.tuples();
} else {
right_tuples = right
.tuples_by_symbols(symbols.clone())
.map(|(key, _tuple)| key);
}
SimpleRelation {
symbols: symbols.to_vec(),
tuples: left_tuples.concat(&right_tuples).distinct()
}
},
&Plan::Join(ref left_plan, ref right_plan, join_var) => {
let mut left = implement_plan(left_plan.deref(), db, nested, relation_map, queries);
let mut right = implement_plan(right_plan.deref(), db, nested, relation_map, queries);
let mut join_vars = vec![join_var];
let mut left_syms: Vec<Var> = left.symbols().clone();
left_syms.retain(|&sym| sym != join_var);
let mut right_syms: Vec<Var> = right.symbols().clone();
right_syms.retain(|&sym| sym != join_var);
// useful for inspecting join inputs
//.inspect(|&((ref key, ref values), _, _)| { println!("right {:?} {:?}", key, values) })
let tuples = left.tuples_by_symbols(join_vars.clone())
.arrange_by_key()
.join_core(&right.tuples_by_symbols(join_vars.clone()).arrange_by_key(), |key, v1, v2| {
// @TODO can haz array here?
// @TODO avoid allocation, if capacity available in v1
let mut vstar = Vec::with_capacity(key.len() + v1.len() + v2.len());
vstar.extend(key.iter().cloned());
vstar.extend(v1.iter().cloned());
vstar.extend(v2.iter().cloned());
Some(vstar)
});
let mut symbols: Vec<Var> = Vec::with_capacity(left_syms.len() + right_syms.len());
symbols.append(&mut join_vars);
symbols.append(&mut left_syms);
symbols.append(&mut right_syms);
// let debug_syms: Vec<String> = symbols.iter().map(|x| x.to_string()).collect();
// println!(debug_syms);
SimpleRelation { symbols, tuples }
},
&Plan::Not(ref plan) => {
// implement_negation(plan.deref(), db)
let mut rel = implement_plan(plan.deref(), db, nested, relation_map, queries);
SimpleRelation {
symbols: rel.symbols().clone(),
tuples: rel.tuples().negate()
}
},
&Plan::Lookup(e, a, sym1) => {
// let ea_in = scope.new_collection_from(vec![(e, a)]).1.enter(nested).arrange_by_self();
let ea_in = db.input_map.get(&(Some(e), Some(a), None)).unwrap().enter(nested);
let tuples = db.ea_v.enter(nested)
.join_core(&ea_in, |_, tuple, _| { Some(tuple.clone()) });
SimpleRelation { symbols: vec![sym1], tuples }
},
&Plan::Entity(e, sym1, sym2) => {
// let e_in = scope.new_collection_from(vec![e]).1.enter(nested).arrange_by_self();
let e_in = db.input_map.get(&(Some(e), None, None)).unwrap().enter(nested);
let tuples = db.e_av.enter(nested)
.join_core(&e_in, |_, tuple, _| { Some(tuple.clone()) });
SimpleRelation { symbols: vec![sym1, sym2], tuples }
},
&Plan::HasAttr(sym1, a, sym2) => {
// let a_in = scope.new_collection_from(vec![a]).1.enter(nested).arrange_by_self();
let a_in = db.input_map.get(&(None, Some(a), None)).unwrap().enter(nested);
let tuples = db.a_ev.enter(nested)
.join_core(&a_in, |_, tuple, _| { Some(tuple.clone()) });
SimpleRelation { symbols: vec![sym1, sym2], tuples }
},
&Plan::Filter(sym1, a, ref v) => {
// let av_in = scope.new_collection_from(vec![(a, v.clone())]).1.enter(nested).arrange_by_self();
let av_in = db.input_map.get(&(None, Some(a), Some(v.clone()))).unwrap().enter(nested);
let tuples = db.av_e.enter(nested)
.join_core(&av_in, |_, tuple, _| { Some(tuple.clone()) });
SimpleRelation { symbols: vec![sym1], tuples }
}
&Plan::Recur(ref syms) => {
match relation_map.get(&"self".to_string()) {
None => panic!("'self' not in relation map"),
Some(named) => {
SimpleRelation {
symbols: syms.clone(),
tuples: named.variable.as_ref().unwrap().deref().map(|tuple| tuple.clone()),
}
}
}
}
}
}
// fn implement_negation<'a>(plan: &Plan, db: &mut DB, scope: &mut Scope<'a>) -> SimpleRelation<'a> {
// match plan {
// &Plan::Lookup(e, a, sym1) => {
// let ea_in = scope.new_collection_from(vec![(e, a)]).1;
// let tuples = db.ea_v.import(scope)
// .antijoin(&ea_in)
// .distinct()
// .map(|(_, v)| { vec![v] });
// SimpleRelation { symbols: vec![sym1], tuples }
// },
// &Plan::Entity(e, sym1, sym2) => {
// let e_in = scope.new_collection_from(vec![e]).1;
// let tuples = db.e_av.import(scope)
// .antijoin(&e_in)
// .distinct()
// .map(|(_, (a, v))| { vec![Value::Attribute(a), v] });
// SimpleRelation { symbols: vec![sym1, sym2], tuples }
// },
// &Plan::HasAttr(sym1, a, sym2) => {
// let a_in = scope.new_collection_from(vec![a]).1;
// let tuples = db.a_ev.import(scope)
// .antijoin(&a_in)
// .distinct()
// .map(|(_, (e, v))| { vec![Value::Eid(e), v] });
// SimpleRelation { symbols: vec![sym1, sym2], tuples }
// },
// &Plan::Filter(sym1, a, ref v) => {
// let av_in = scope.new_collection_from(vec![(a, v.clone())]).1;
// let tuples = db.av_e.import(scope)
// .antijoin(&av_in)
// .distinct()
// .map(|(_, e)| { vec![Value::Eid(e)] });
// SimpleRelation { symbols: vec![sym1], tuples }
// },
// _ => panic!("Negation not supported for this plan.")
// }
// }
//
// PUBLIC API
//
pub fn setup_db<A: timely::Allocate, T: Timestamp+Lattice> (scope: &mut Child<Root<A>, T>) -> (InputSession<T, Datom, isize>, DB<T>) {
let (input_handle, datoms) = scope.new_collection::<Datom, isize>();
let db = DB {
e_av: datoms.map(|Datom(e, a, v)| (vec![Value::Eid(e)], vec![Value::Attribute(a), v])).arrange_by_key().trace,
a_ev: datoms.map(|Datom(e, a, v)| (vec![Value::Attribute(a)], vec![Value::Eid(e), v])).arrange_by_key().trace,
ea_v: datoms.map(|Datom(e, a, v)| (vec![Value::Eid(e), Value::Attribute(a)], vec![v])).arrange_by_key().trace,
av_e: datoms.map(|Datom(e, a, v)| (vec![Value::Attribute(a), v], vec![Value::Eid(e)])).arrange_by_key().trace,
};
(input_handle, db)
}
pub fn register<A: timely::Allocate, T: Timestamp+Lattice>
(scope: &mut Child<Root<A>, T>, ctx: &mut Context<T>, name: String, plan: Plan) -> HashMap<String, RelationHandles<T>> {
let mut result_map = implement(&name, plan, scope, ctx);
// @TODO store trace somewhere for re-use from other queries later
// queries.insert(name.clone(), output_collection.arrange_by_self().trace);
result_map
}
// @TODO this is probably only neccessary in the WASM interface
//
// pub fn transact<A: Allocate>(ctx: &mut Context<A, usize>, tx: usize, d: Vec<TxData>) -> bool {
// for TxData(op, e, a, v) in d {
// ctx.input_handle.update(Datom(e, a, v), op);
// }
// ctx.input_handle.advance_to(tx + 1);
// ctx.input_handle.flush();
// for probe in &mut ctx.probes {
// while probe.less_than(ctx.input_handle.time()) {
// ctx.root.step();
// }
// }
// true
// }
|
use std::ops::RangeInclusive;
pub trait RangeExt<T> {
/// Constrains the value to be contained within the range
fn clamp(&self, t: T) -> T
where
T: Clone + Ord;
}
impl<T> RangeExt<T> for RangeInclusive<T> {
fn clamp(&self, t: T) -> T
where
T: Clone + Ord,
{
if &t < self.start() {
self.start().clone()
} else if &t > self.end() {
self.end().clone()
} else {
t
}
}
}
|
mod fake;
pub use fake::FakeKV;
|
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig, ALL_WEBSOCKET_PROTOCOLS};
use async_graphql::Schema;
use async_graphql_axum::{
graphql_subscription, GraphQLRequest, GraphQLResponse, SecWebsocketProtocol,
};
use axum::extract::{self, ws::WebSocketUpgrade, TypedHeader};
use axum::response::{self, IntoResponse};
use axum::routing::get;
use axum::{AddExtensionLayer, Router, Server};
use books::{BooksSchema, MutationRoot, QueryRoot, Storage, SubscriptionRoot};
async fn graphql_handler(
schema: extract::Extension<BooksSchema>,
req: GraphQLRequest,
) -> GraphQLResponse {
schema.execute(req.into_inner()).await.into()
}
async fn graphql_subscription_handler(
ws: WebSocketUpgrade,
schema: extract::Extension<BooksSchema>,
protocol: TypedHeader<SecWebsocketProtocol>,
) -> impl IntoResponse {
ws.protocols(ALL_WEBSOCKET_PROTOCOLS)
.on_upgrade(move |socket| async move {
graphql_subscription(socket, schema.0.clone(), protocol.0).await
})
}
async fn graphql_playground() -> impl IntoResponse {
response::Html(playground_source(
GraphQLPlaygroundConfig::new("/").subscription_endpoint("/ws"),
))
}
#[tokio::main]
async fn main() {
let schema = Schema::build(QueryRoot, MutationRoot, SubscriptionRoot)
.data(Storage::default())
.finish();
let app = Router::new()
.route("/", get(graphql_playground).post(graphql_handler))
.route("/ws", get(graphql_subscription_handler))
.layer(AddExtensionLayer::new(schema));
println!("Playground: http://localhost:8000");
Server::bind(&"0.0.0.0:8000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
|
mod map;
pub use map::MapBundle;
|
// Macros
#[macro_use]
extern crate clap;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate prettytable;
#[macro_use]
extern crate indexmap;
#[macro_use]
extern crate anyhow;
// Std
use std::collections::{HashMap, HashSet};
use std::env;
use std::str;
// Crates
use anyhow::{Context, Result};
use chrono::offset::TimeZone;
use chrono::{Datelike, Duration, Local, NaiveDateTime};
use clap::{App, Arg};
use dotenv::dotenv;
use http::StatusCode;
use indexmap::IndexMap;
use prettytable::{color, Attr, Cell, Row, Table};
use reqwest::Client;
// Local
use timecard::{Entry, Project};
lazy_static! {
static ref WEEKDAYS: HashMap<String, i64> = vec![
("Sun".to_owned(), 0),
("Mon".to_owned(), 1),
("Tue".to_owned(), 2),
("Wed".to_owned(), 3),
("Thu".to_owned(), 4),
("Fri".to_owned(), 5),
("Sat".to_owned(), 6),
]
.into_iter()
.collect();
}
static DATE_FORMAT: &str = "%Y-%m-%d %H:%M:%S";
const MAX_WIDTH: usize = 20;
struct HourRowData {
project: String,
hours: IndexMap<String, f64>,
}
struct MemoRowData {
project: String,
memos: IndexMap<String, String>,
}
impl HourRowData {
fn new() -> Self {
HourRowData {
project: String::new(),
hours: indexmap! {
"Sun".to_string() => 0.0,
"Mon".to_string() => 0.0,
"Tue".to_string() => 0.0,
"Wed".to_string() => 0.0,
"Thu".to_string() => 0.0,
"Fri".to_string() => 0.0,
"Sat".to_string() => 0.0,
},
}
}
fn convert_to_row(&self, text_color: color::Color) -> Row {
let mut cells: Vec<Cell> = Vec::new();
cells.push(Cell::new(&self.project).with_style(Attr::ForegroundColor(text_color)));
for (_, value) in self.hours.iter() {
cells.push(Cell::new(&value.to_string()).with_style(Attr::ForegroundColor(text_color)));
}
Row::new(cells)
}
}
impl MemoRowData {
fn new() -> Self {
MemoRowData {
project: String::new(),
memos: indexmap! {
"Sun".to_string() => String::from(""),
"Mon".to_string() => String::from(""),
"Tue".to_string() => String::from(""),
"Wed".to_string() => String::from(""),
"Thu".to_string() => String::from(""),
"Fri".to_string() => String::from(""),
"Sat".to_string() => String::from(""),
},
}
}
fn convert_to_row(&self, text_color: color::Color) -> Row {
let mut cells: Vec<Cell> = Vec::new();
cells.push(Cell::new(&self.project).with_style(Attr::ForegroundColor(text_color)));
for (_, value) in self.memos.iter() {
cells.push(Cell::new(&value).with_style(Attr::ForegroundColor(text_color)));
}
Row::new(cells)
}
}
#[tokio::main]
async fn main() -> Result<()> {
dotenv().ok();
let base_url: String = env::var("BASE_URL").context("BASE_URL env var must be set!")?;
let client = Client::new();
let matches = App::new("timecard")
.version(crate_version!())
.author("Samuel Vanderwaal")
.about("A time-tracking command line program.")
.arg(
Arg::with_name("entry")
.short('e')
.long("entry")
.value_names(&["start", "stop", "code", "memo"])
.about("Add a new time entry.")
.takes_value(true)
.value_delimiter("|"),
)
.arg(
Arg::with_name("backdate")
.short('b')
.long("backdate")
.value_names(&["backdate", "start", "stop", "code", "memo"])
.about("Add a backdated entry.")
.takes_value(true)
.value_delimiter("|"),
)
.arg(
Arg::with_name("week")
.short('w')
.long("week")
.takes_value(true)
.about("Print weekly report."),
)
.arg(
Arg::with_name("with_memos")
.short('m')
.long("with-memos")
.about("Use with '-w'. Adds memos to weekly report."),
)
.arg(
Arg::with_name("last_entry")
.long("last")
.about("Display the most recent entry."),
)
.arg(
Arg::with_name("delete_last_entry")
.short('d')
.long("delete")
.about("Delete the most recent entry."),
)
.arg(
Arg::with_name("add_project")
.short('a')
.long("add-project")
.value_names(&["name", "code"])
.about("Add a new project to the reference table."),
)
.arg(
Arg::with_name("list_projects")
.short('p')
.long("list-projects")
.about("List all projects in the reference table."),
)
.arg(
Arg::with_name("delete_project")
.long("delete-project")
.takes_value(true)
.value_name("code")
.about("Delete a project from the reference table."),
)
.get_matches();
if let Some(values) = matches.values_of("entry") {
match process_new_entry(&base_url, client, values.collect()).await {
Ok(_) => println!("Entry submitted."),
// TODO: Log error
Err(e) => eprintln!("Error writing entry: {}", e),
}
std::process::exit(1);
}
if let Some(values) = matches.values_of("backdate") {
match backdated_entry(&base_url, client, values.collect()).await {
Ok(_) => println!("Entry submitted."),
// TODO: Log error
Err(_e) => println!("Error writing entry."),
}
std::process::exit(1);
}
if let Some(value) = matches.value_of("week") {
let mut memos = false;
let num = match value.parse::<i64>() {
Ok(n) => n,
// TODO: Log error
Err(_e) => {
eprintln!("Error: week value must be an integer.");
std::process::exit(1);
}
};
if matches.is_present("with_memos") {
memos = true;
}
create_weekly_report(&base_url, client, num, memos).await?;
std::process::exit(1);
}
if matches.is_present("last_entry") {
match display_last_entry(&base_url, client).await {
Ok(table) => table.printstd(),
Err(e) => {
eprintln!("Error: {:?}", e);
std::process::exit(1);
}
};
std::process::exit(1);
}
if matches.is_present("delete_last_entry") {
let url = format!("{}/delete_last_entry", &base_url);
let res = client.post(&url).send().await?;
match res.status() {
StatusCode::OK => println!("Most recent entry deleted."),
_ => println!("Error: {:?}", res.status()),
}
}
if let Some(values) = matches.values_of("add_project") {
let values: Vec<&str> = values.collect();
let new_project = Project {
id: None,
name: values[0].to_string(),
code: values[1].to_string(),
};
let url = format!("{}/project", &base_url);
let res = client.post(&url).json(&new_project).send().await?;
if res.status().is_success() {
println!("Project saved.");
} else {
println!("Http error: {}", res.status());
}
}
if matches.is_present("list_projects") {
let url = format!("{}/all_projects", &base_url);
let projects = client
.get(&url)
.send()
.await?
.json::<Vec<Project>>()
.await?;
let mut table = Table::new();
table.add_row(row![Fb => "Name", "Code"]);
for project in projects {
table.add_row(row![project.name, project.code]);
}
table.printstd();
}
if let Some(value) = matches.value_of("delete_project") {
let code = value.parse::<String>()?;
let url = format!("{}/delete_project/{}", &base_url, code);
let res = client.post(&url).send().await?;
if res.status().is_success() {
println!("Project deleted.");
} else {
println!("Http error: {}", res.status());
}
}
Ok(())
}
async fn process_new_entry(base_url: &str, client: Client, values: Vec<&str>) -> Result<()> {
let (start_hour, start_minute) = parse_entry_time(values[0].to_owned())?;
let (stop_hour, stop_minute) = parse_entry_time(values[1].to_owned())?;
let date = Local::now();
let start = entry_time_to_full_date(date, start_hour, start_minute);
let stop = entry_time_to_full_date(date, stop_hour, stop_minute);
let week_day: String = Local::today().weekday().to_string();
let code = values[2].to_owned();
let memo = values[3].to_owned();
let new_entry = Entry {
id: None,
start,
stop,
week_day,
code,
memo,
};
let url = format!("{}/entry", base_url);
let res = client.post(&url).json(&new_entry).send().await?;
match res.status() {
StatusCode::OK => Ok(()),
_ => Err(anyhow!("Status code: {}", res.status())),
}
}
async fn backdated_entry(base_url: &str, client: Client, values: Vec<&str>) -> Result<()> {
let date = match values[0] {
"today" => Local::today(),
"yesterday" => Local::today() - Duration::days(1),
"tomorrow" => Local::today() + Duration::days(1),
_ => {
let date_values: Vec<&str> = values[0].split('-').collect();
let year: i32 = date_values[0].parse()?;
let month: u32 = date_values[1].parse()?;
let day: u32 = date_values[2].parse()?;
Local.ymd(year, month, day)
}
};
let (start_hour, start_minute) = parse_entry_time(values[1].to_owned())?;
let (stop_hour, stop_minute) = parse_entry_time(values[2].to_owned())?;
let start = entry_time_to_full_date(date, start_hour, start_minute);
let stop = entry_time_to_full_date(date, stop_hour, stop_minute);
let week_day: String = date.weekday().to_string();
let code = values[3].to_owned();
let memo = values[4].to_owned();
let new_entry = Entry {
id: None,
start,
stop,
week_day,
code,
memo,
};
let url = format!("{}/entry", base_url);
let res = client.post(&url).json(&new_entry).send().await?;
match res.status() {
StatusCode::OK => Ok(()),
_ => Err(anyhow!("Status code: {}", res.status())),
}
}
fn parse_entry_time(time_str: String) -> Result<(u32, u32)> {
let time = time_str.parse::<u32>()?;
Ok((time / 100, time % 100))
}
fn entry_time_to_full_date<T: Datelike>(date: T, hour: u32, minute: u32) -> String {
let year = date.year();
let month = date.month();
let day = date.day();
return format!(
"{}-{:02}-{:02} {:02}:{:02}:{:02}",
year, month, day, hour, minute, 0
);
}
async fn create_weekly_report(
base_url: &str,
client: Client,
num_weeks: i64,
with_memos: bool,
) -> Result<()> {
let parse_from_str = NaiveDateTime::parse_from_str;
let day_of_week: String = Local::today().weekday().to_string();
let offset = *WEEKDAYS.get(&day_of_week).expect("Day does not exist!") + (7 * num_weeks);
let week_beginning = Local::today() - Duration::days(offset);
let week_ending = week_beginning + Duration::days(6);
let url = format!(
"{}/entries_between/{}/{}",
base_url, week_beginning, week_ending
);
let entries = client.get(&url).send().await?.json::<Vec<Entry>>().await?;
let mut table = Table::new();
table.add_row(row![Fb => "Project", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]);
let mut codes: HashSet<String> = HashSet::new();
for entry in &entries {
codes.insert(entry.code.clone());
}
for (index, code) in codes.iter().enumerate() {
let mut hour_data = HourRowData::new();
let mut memo_data = MemoRowData::new();
hour_data.project = code.clone();
memo_data.project = code.clone();
let project_entries = entries.iter().filter(|entry| &entry.code == code);
for entry in project_entries {
let start: NaiveDateTime =
parse_from_str(&entry.start, DATE_FORMAT).expect("Parsing error!");
let stop: NaiveDateTime =
parse_from_str(&entry.stop, DATE_FORMAT).expect("Parsing error!");
let h = hour_data.hours.entry(entry.week_day.clone()).or_insert(0.0);
*h += stop.signed_duration_since(start).num_minutes() as f64 / 60.0;
let current_memo = memo_data
.memos
.entry(entry.week_day.clone())
.or_insert(String::from(""));
// Implement max width
for chunk in entry.memo.as_bytes().chunks(MAX_WIDTH) {
let chunk_str = str::from_utf8(chunk)?;
(*current_memo).push_str(chunk_str);
if chunk_str.len() >= MAX_WIDTH {
(*current_memo).push_str("\n");
}
}
(*current_memo).push_str("; ");
(*current_memo).push_str("\n");
}
let text_color = if index % 2 == 1 {
color::MAGENTA
} else {
color::WHITE
};
table.add_row(hour_data.convert_to_row(text_color));
if with_memos {
table.add_row(memo_data.convert_to_row(text_color));
}
}
table.printstd();
Ok(())
}
async fn display_last_entry(base_url: &str, client: Client) -> Result<Table> {
let url = format!("{}/last_entry", base_url);
let e = client.get(&url).send().await?.json::<Entry>().await?;
let mut table = Table::new();
table.add_row(row![Fb => "Start Time", "Stop Time", "Week Day", "Code", "Memo"]);
table.add_row(row![e.start, e.stop, e.week_day, e.code, e.memo]);
Ok(table)
}
|
use piston_window::{rectangle, Context, G2d};
use piston_window::types::Color;
pub fn draw_rectangle(
color: Color,
x: f64,
y: f64,
width: f64,
height: f64,
con: &Context,
g: &mut G2d,
){
//let gui_x = x;
//let gui_y = to_coord(y);
rectangle(
color,
[
x,
y,
width,
height,
],
con.transform,
g,
);
} |
#![no_std]
#![no_main]
extern crate panic_halt as _;
extern crate stm32f1xx_hal as hal;
use crate::hal::{
gpio::*,
prelude::*,
stm32::{interrupt, Interrupt, Peripherals, TIM2},
timer::*,
};
use core::cell::RefCell;
use cortex_m::{
asm::wfi,
interrupt::Mutex,
peripheral::Peripherals as c_m_Peripherals,
};
use cortex_m_rt::entry;
type LEDPIN = gpioc::PC13<Output<PushPull>>;
static G_LED: Mutex<RefCell<Option<LEDPIN>>> = Mutex::new(RefCell::new(None));
static G_TIM: Mutex<RefCell<Option<CountDownTimer<TIM2>>>> = Mutex::new(RefCell::new(None));
#[interrupt]
fn TIM2() {
static mut LED: Option<LEDPIN> = None;
static mut TIM: Option<CountDownTimer<TIM2>> = None;
let led = LED.get_or_insert_with(|| {
cortex_m::interrupt::free(|cs| {
G_LED.borrow(cs).replace(None).unwrap()
})
});
let tim = TIM.get_or_insert_with(|| {
cortex_m::interrupt::free(|cs| {
// Move LED pin here, leaving a None in its place
G_TIM.borrow(cs).replace(None).unwrap()
})
});
led.toggle().ok();
tim.wait().ok();
}
#[entry]
fn main() -> ! {
if let (Some(dp), Some(cp)) = (Peripherals::take(), c_m_Peripherals::take()) {
cortex_m::interrupt::free(move |cs| {
let mut rcc = dp.RCC.constrain();
let mut flash = dp.FLASH.constrain();
let clocks = rcc
.cfgr
.sysclk(8.mhz())
.pclk1(8.mhz())
.freeze(&mut flash.acr);
let mut gpioc = dp.GPIOC.split(&mut rcc.apb2);
let led = gpioc.pc13.into_push_pull_output(&mut gpioc.crh);
*G_LED.borrow(cs).borrow_mut() = Some(led);
let mut timer = Timer::tim2(dp.TIM2, &clocks, &mut rcc.apb1).start_count_down(10.hz());
timer.listen(Event::Update);
*G_TIM.borrow(cs).borrow_mut() = Some(timer);
let mut nvic = cp.NVIC;
unsafe {
nvic.set_priority(Interrupt::TIM2, 1);
cortex_m::peripheral::NVIC::unmask(Interrupt::TIM2);
}
cortex_m::peripheral::NVIC::unpend(Interrupt::TIM2);
});
}
loop {
wfi();
}
} |
#[doc = "Register `FDCAN_TTOCN` reader"]
pub type R = crate::R<FDCAN_TTOCN_SPEC>;
#[doc = "Register `FDCAN_TTOCN` writer"]
pub type W = crate::W<FDCAN_TTOCN_SPEC>;
#[doc = "Field `SGT` reader - Set Global time"]
pub type SGT_R = crate::BitReader;
#[doc = "Field `SGT` writer - Set Global time"]
pub type SGT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ECS` reader - External Clock Synchronization"]
pub type ECS_R = crate::BitReader;
#[doc = "Field `ECS` writer - External Clock Synchronization"]
pub type ECS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SWP` reader - Stop Watch Polarity"]
pub type SWP_R = crate::BitReader;
#[doc = "Field `SWP` writer - Stop Watch Polarity"]
pub type SWP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SWS` reader - Stop Watch Source."]
pub type SWS_R = crate::FieldReader;
#[doc = "Field `SWS` writer - Stop Watch Source."]
pub type SWS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `RTIE` reader - Register Time Mark Interrupt Pulse Enable"]
pub type RTIE_R = crate::BitReader;
#[doc = "Field `RTIE` writer - Register Time Mark Interrupt Pulse Enable"]
pub type RTIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TMC` reader - Register Time Mark Compare"]
pub type TMC_R = crate::FieldReader;
#[doc = "Field `TMC` writer - Register Time Mark Compare"]
pub type TMC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `TTIE` reader - Trigger Time Mark Interrupt Pulse Enable"]
pub type TTIE_R = crate::BitReader;
#[doc = "Field `TTIE` writer - Trigger Time Mark Interrupt Pulse Enable"]
pub type TTIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GCS` reader - Gap Control Select"]
pub type GCS_R = crate::BitReader;
#[doc = "Field `GCS` writer - Gap Control Select"]
pub type GCS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FGP` reader - Finish Gap."]
pub type FGP_R = crate::BitReader;
#[doc = "Field `FGP` writer - Finish Gap."]
pub type FGP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TMG` reader - Time Mark Gap"]
pub type TMG_R = crate::BitReader;
#[doc = "Field `TMG` writer - Time Mark Gap"]
pub type TMG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `NIG` reader - Next is Gap"]
pub type NIG_R = crate::BitReader;
#[doc = "Field `NIG` writer - Next is Gap"]
pub type NIG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ESCN` reader - External Synchronization Control"]
pub type ESCN_R = crate::BitReader;
#[doc = "Field `ESCN` writer - External Synchronization Control"]
pub type ESCN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `LCKC` reader - TT Operation Control Register Locked"]
pub type LCKC_R = crate::BitReader;
#[doc = "Field `LCKC` writer - TT Operation Control Register Locked"]
pub type LCKC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - Set Global time"]
#[inline(always)]
pub fn sgt(&self) -> SGT_R {
SGT_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - External Clock Synchronization"]
#[inline(always)]
pub fn ecs(&self) -> ECS_R {
ECS_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Stop Watch Polarity"]
#[inline(always)]
pub fn swp(&self) -> SWP_R {
SWP_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bits 3:4 - Stop Watch Source."]
#[inline(always)]
pub fn sws(&self) -> SWS_R {
SWS_R::new(((self.bits >> 3) & 3) as u8)
}
#[doc = "Bit 5 - Register Time Mark Interrupt Pulse Enable"]
#[inline(always)]
pub fn rtie(&self) -> RTIE_R {
RTIE_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bits 6:7 - Register Time Mark Compare"]
#[inline(always)]
pub fn tmc(&self) -> TMC_R {
TMC_R::new(((self.bits >> 6) & 3) as u8)
}
#[doc = "Bit 8 - Trigger Time Mark Interrupt Pulse Enable"]
#[inline(always)]
pub fn ttie(&self) -> TTIE_R {
TTIE_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - Gap Control Select"]
#[inline(always)]
pub fn gcs(&self) -> GCS_R {
GCS_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - Finish Gap."]
#[inline(always)]
pub fn fgp(&self) -> FGP_R {
FGP_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - Time Mark Gap"]
#[inline(always)]
pub fn tmg(&self) -> TMG_R {
TMG_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - Next is Gap"]
#[inline(always)]
pub fn nig(&self) -> NIG_R {
NIG_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - External Synchronization Control"]
#[inline(always)]
pub fn escn(&self) -> ESCN_R {
ESCN_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 15 - TT Operation Control Register Locked"]
#[inline(always)]
pub fn lckc(&self) -> LCKC_R {
LCKC_R::new(((self.bits >> 15) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Set Global time"]
#[inline(always)]
#[must_use]
pub fn sgt(&mut self) -> SGT_W<FDCAN_TTOCN_SPEC, 0> {
SGT_W::new(self)
}
#[doc = "Bit 1 - External Clock Synchronization"]
#[inline(always)]
#[must_use]
pub fn ecs(&mut self) -> ECS_W<FDCAN_TTOCN_SPEC, 1> {
ECS_W::new(self)
}
#[doc = "Bit 2 - Stop Watch Polarity"]
#[inline(always)]
#[must_use]
pub fn swp(&mut self) -> SWP_W<FDCAN_TTOCN_SPEC, 2> {
SWP_W::new(self)
}
#[doc = "Bits 3:4 - Stop Watch Source."]
#[inline(always)]
#[must_use]
pub fn sws(&mut self) -> SWS_W<FDCAN_TTOCN_SPEC, 3> {
SWS_W::new(self)
}
#[doc = "Bit 5 - Register Time Mark Interrupt Pulse Enable"]
#[inline(always)]
#[must_use]
pub fn rtie(&mut self) -> RTIE_W<FDCAN_TTOCN_SPEC, 5> {
RTIE_W::new(self)
}
#[doc = "Bits 6:7 - Register Time Mark Compare"]
#[inline(always)]
#[must_use]
pub fn tmc(&mut self) -> TMC_W<FDCAN_TTOCN_SPEC, 6> {
TMC_W::new(self)
}
#[doc = "Bit 8 - Trigger Time Mark Interrupt Pulse Enable"]
#[inline(always)]
#[must_use]
pub fn ttie(&mut self) -> TTIE_W<FDCAN_TTOCN_SPEC, 8> {
TTIE_W::new(self)
}
#[doc = "Bit 9 - Gap Control Select"]
#[inline(always)]
#[must_use]
pub fn gcs(&mut self) -> GCS_W<FDCAN_TTOCN_SPEC, 9> {
GCS_W::new(self)
}
#[doc = "Bit 10 - Finish Gap."]
#[inline(always)]
#[must_use]
pub fn fgp(&mut self) -> FGP_W<FDCAN_TTOCN_SPEC, 10> {
FGP_W::new(self)
}
#[doc = "Bit 11 - Time Mark Gap"]
#[inline(always)]
#[must_use]
pub fn tmg(&mut self) -> TMG_W<FDCAN_TTOCN_SPEC, 11> {
TMG_W::new(self)
}
#[doc = "Bit 12 - Next is Gap"]
#[inline(always)]
#[must_use]
pub fn nig(&mut self) -> NIG_W<FDCAN_TTOCN_SPEC, 12> {
NIG_W::new(self)
}
#[doc = "Bit 13 - External Synchronization Control"]
#[inline(always)]
#[must_use]
pub fn escn(&mut self) -> ESCN_W<FDCAN_TTOCN_SPEC, 13> {
ESCN_W::new(self)
}
#[doc = "Bit 15 - TT Operation Control Register Locked"]
#[inline(always)]
#[must_use]
pub fn lckc(&mut self) -> LCKC_W<FDCAN_TTOCN_SPEC, 15> {
LCKC_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 = "FDCAN TT Operation Control Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fdcan_ttocn::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`fdcan_ttocn::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct FDCAN_TTOCN_SPEC;
impl crate::RegisterSpec for FDCAN_TTOCN_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`fdcan_ttocn::R`](R) reader structure"]
impl crate::Readable for FDCAN_TTOCN_SPEC {}
#[doc = "`write(|w| ..)` method takes [`fdcan_ttocn::W`](W) writer structure"]
impl crate::Writable for FDCAN_TTOCN_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets FDCAN_TTOCN to value 0"]
impl crate::Resettable for FDCAN_TTOCN_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
/// An enum to represent all characters in the Phagspa block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum Phagspa {
/// \u{a840}: 'ꡀ'
PhagsDashPaLetterKa,
/// \u{a841}: 'ꡁ'
PhagsDashPaLetterKha,
/// \u{a842}: 'ꡂ'
PhagsDashPaLetterGa,
/// \u{a843}: 'ꡃ'
PhagsDashPaLetterNga,
/// \u{a844}: 'ꡄ'
PhagsDashPaLetterCa,
/// \u{a845}: 'ꡅ'
PhagsDashPaLetterCha,
/// \u{a846}: 'ꡆ'
PhagsDashPaLetterJa,
/// \u{a847}: 'ꡇ'
PhagsDashPaLetterNya,
/// \u{a848}: 'ꡈ'
PhagsDashPaLetterTa,
/// \u{a849}: 'ꡉ'
PhagsDashPaLetterTha,
/// \u{a84a}: 'ꡊ'
PhagsDashPaLetterDa,
/// \u{a84b}: 'ꡋ'
PhagsDashPaLetterNa,
/// \u{a84c}: 'ꡌ'
PhagsDashPaLetterPa,
/// \u{a84d}: 'ꡍ'
PhagsDashPaLetterPha,
/// \u{a84e}: 'ꡎ'
PhagsDashPaLetterBa,
/// \u{a84f}: 'ꡏ'
PhagsDashPaLetterMa,
/// \u{a850}: 'ꡐ'
PhagsDashPaLetterTsa,
/// \u{a851}: 'ꡑ'
PhagsDashPaLetterTsha,
/// \u{a852}: 'ꡒ'
PhagsDashPaLetterDza,
/// \u{a853}: 'ꡓ'
PhagsDashPaLetterWa,
/// \u{a854}: 'ꡔ'
PhagsDashPaLetterZha,
/// \u{a855}: 'ꡕ'
PhagsDashPaLetterZa,
/// \u{a856}: 'ꡖ'
PhagsDashPaLetterSmallA,
/// \u{a857}: 'ꡗ'
PhagsDashPaLetterYa,
/// \u{a858}: 'ꡘ'
PhagsDashPaLetterRa,
/// \u{a859}: 'ꡙ'
PhagsDashPaLetterLa,
/// \u{a85a}: 'ꡚ'
PhagsDashPaLetterSha,
/// \u{a85b}: 'ꡛ'
PhagsDashPaLetterSa,
/// \u{a85c}: 'ꡜ'
PhagsDashPaLetterHa,
/// \u{a85d}: 'ꡝ'
PhagsDashPaLetterA,
/// \u{a85e}: 'ꡞ'
PhagsDashPaLetterI,
/// \u{a85f}: 'ꡟ'
PhagsDashPaLetterU,
/// \u{a860}: 'ꡠ'
PhagsDashPaLetterE,
/// \u{a861}: 'ꡡ'
PhagsDashPaLetterO,
/// \u{a862}: 'ꡢ'
PhagsDashPaLetterQa,
/// \u{a863}: 'ꡣ'
PhagsDashPaLetterXa,
/// \u{a864}: 'ꡤ'
PhagsDashPaLetterFa,
/// \u{a865}: 'ꡥ'
PhagsDashPaLetterGga,
/// \u{a866}: 'ꡦ'
PhagsDashPaLetterEe,
/// \u{a867}: 'ꡧ'
PhagsDashPaSubjoinedLetterWa,
/// \u{a868}: 'ꡨ'
PhagsDashPaSubjoinedLetterYa,
/// \u{a869}: 'ꡩ'
PhagsDashPaLetterTta,
/// \u{a86a}: 'ꡪ'
PhagsDashPaLetterTtha,
/// \u{a86b}: 'ꡫ'
PhagsDashPaLetterDda,
/// \u{a86c}: 'ꡬ'
PhagsDashPaLetterNna,
/// \u{a86d}: 'ꡭ'
PhagsDashPaLetterAlternateYa,
/// \u{a86e}: 'ꡮ'
PhagsDashPaLetterVoicelessSha,
/// \u{a86f}: 'ꡯ'
PhagsDashPaLetterVoicedHa,
/// \u{a870}: 'ꡰ'
PhagsDashPaLetterAspiratedFa,
/// \u{a871}: 'ꡱ'
PhagsDashPaSubjoinedLetterRa,
/// \u{a872}: 'ꡲ'
PhagsDashPaSuperfixedLetterRa,
/// \u{a873}: 'ꡳ'
PhagsDashPaLetterCandrabindu,
/// \u{a874}: '꡴'
PhagsDashPaSingleHeadMark,
/// \u{a875}: '꡵'
PhagsDashPaDoubleHeadMark,
/// \u{a876}: '꡶'
PhagsDashPaMarkShad,
/// \u{a877}: '꡷'
PhagsDashPaMarkDoubleShad,
}
impl Into<char> for Phagspa {
fn into(self) -> char {
match self {
Phagspa::PhagsDashPaLetterKa => 'ꡀ',
Phagspa::PhagsDashPaLetterKha => 'ꡁ',
Phagspa::PhagsDashPaLetterGa => 'ꡂ',
Phagspa::PhagsDashPaLetterNga => 'ꡃ',
Phagspa::PhagsDashPaLetterCa => 'ꡄ',
Phagspa::PhagsDashPaLetterCha => 'ꡅ',
Phagspa::PhagsDashPaLetterJa => 'ꡆ',
Phagspa::PhagsDashPaLetterNya => 'ꡇ',
Phagspa::PhagsDashPaLetterTa => 'ꡈ',
Phagspa::PhagsDashPaLetterTha => 'ꡉ',
Phagspa::PhagsDashPaLetterDa => 'ꡊ',
Phagspa::PhagsDashPaLetterNa => 'ꡋ',
Phagspa::PhagsDashPaLetterPa => 'ꡌ',
Phagspa::PhagsDashPaLetterPha => 'ꡍ',
Phagspa::PhagsDashPaLetterBa => 'ꡎ',
Phagspa::PhagsDashPaLetterMa => 'ꡏ',
Phagspa::PhagsDashPaLetterTsa => 'ꡐ',
Phagspa::PhagsDashPaLetterTsha => 'ꡑ',
Phagspa::PhagsDashPaLetterDza => 'ꡒ',
Phagspa::PhagsDashPaLetterWa => 'ꡓ',
Phagspa::PhagsDashPaLetterZha => 'ꡔ',
Phagspa::PhagsDashPaLetterZa => 'ꡕ',
Phagspa::PhagsDashPaLetterSmallA => 'ꡖ',
Phagspa::PhagsDashPaLetterYa => 'ꡗ',
Phagspa::PhagsDashPaLetterRa => 'ꡘ',
Phagspa::PhagsDashPaLetterLa => 'ꡙ',
Phagspa::PhagsDashPaLetterSha => 'ꡚ',
Phagspa::PhagsDashPaLetterSa => 'ꡛ',
Phagspa::PhagsDashPaLetterHa => 'ꡜ',
Phagspa::PhagsDashPaLetterA => 'ꡝ',
Phagspa::PhagsDashPaLetterI => 'ꡞ',
Phagspa::PhagsDashPaLetterU => 'ꡟ',
Phagspa::PhagsDashPaLetterE => 'ꡠ',
Phagspa::PhagsDashPaLetterO => 'ꡡ',
Phagspa::PhagsDashPaLetterQa => 'ꡢ',
Phagspa::PhagsDashPaLetterXa => 'ꡣ',
Phagspa::PhagsDashPaLetterFa => 'ꡤ',
Phagspa::PhagsDashPaLetterGga => 'ꡥ',
Phagspa::PhagsDashPaLetterEe => 'ꡦ',
Phagspa::PhagsDashPaSubjoinedLetterWa => 'ꡧ',
Phagspa::PhagsDashPaSubjoinedLetterYa => 'ꡨ',
Phagspa::PhagsDashPaLetterTta => 'ꡩ',
Phagspa::PhagsDashPaLetterTtha => 'ꡪ',
Phagspa::PhagsDashPaLetterDda => 'ꡫ',
Phagspa::PhagsDashPaLetterNna => 'ꡬ',
Phagspa::PhagsDashPaLetterAlternateYa => 'ꡭ',
Phagspa::PhagsDashPaLetterVoicelessSha => 'ꡮ',
Phagspa::PhagsDashPaLetterVoicedHa => 'ꡯ',
Phagspa::PhagsDashPaLetterAspiratedFa => 'ꡰ',
Phagspa::PhagsDashPaSubjoinedLetterRa => 'ꡱ',
Phagspa::PhagsDashPaSuperfixedLetterRa => 'ꡲ',
Phagspa::PhagsDashPaLetterCandrabindu => 'ꡳ',
Phagspa::PhagsDashPaSingleHeadMark => '꡴',
Phagspa::PhagsDashPaDoubleHeadMark => '꡵',
Phagspa::PhagsDashPaMarkShad => '꡶',
Phagspa::PhagsDashPaMarkDoubleShad => '꡷',
}
}
}
impl std::convert::TryFrom<char> for Phagspa {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'ꡀ' => Ok(Phagspa::PhagsDashPaLetterKa),
'ꡁ' => Ok(Phagspa::PhagsDashPaLetterKha),
'ꡂ' => Ok(Phagspa::PhagsDashPaLetterGa),
'ꡃ' => Ok(Phagspa::PhagsDashPaLetterNga),
'ꡄ' => Ok(Phagspa::PhagsDashPaLetterCa),
'ꡅ' => Ok(Phagspa::PhagsDashPaLetterCha),
'ꡆ' => Ok(Phagspa::PhagsDashPaLetterJa),
'ꡇ' => Ok(Phagspa::PhagsDashPaLetterNya),
'ꡈ' => Ok(Phagspa::PhagsDashPaLetterTa),
'ꡉ' => Ok(Phagspa::PhagsDashPaLetterTha),
'ꡊ' => Ok(Phagspa::PhagsDashPaLetterDa),
'ꡋ' => Ok(Phagspa::PhagsDashPaLetterNa),
'ꡌ' => Ok(Phagspa::PhagsDashPaLetterPa),
'ꡍ' => Ok(Phagspa::PhagsDashPaLetterPha),
'ꡎ' => Ok(Phagspa::PhagsDashPaLetterBa),
'ꡏ' => Ok(Phagspa::PhagsDashPaLetterMa),
'ꡐ' => Ok(Phagspa::PhagsDashPaLetterTsa),
'ꡑ' => Ok(Phagspa::PhagsDashPaLetterTsha),
'ꡒ' => Ok(Phagspa::PhagsDashPaLetterDza),
'ꡓ' => Ok(Phagspa::PhagsDashPaLetterWa),
'ꡔ' => Ok(Phagspa::PhagsDashPaLetterZha),
'ꡕ' => Ok(Phagspa::PhagsDashPaLetterZa),
'ꡖ' => Ok(Phagspa::PhagsDashPaLetterSmallA),
'ꡗ' => Ok(Phagspa::PhagsDashPaLetterYa),
'ꡘ' => Ok(Phagspa::PhagsDashPaLetterRa),
'ꡙ' => Ok(Phagspa::PhagsDashPaLetterLa),
'ꡚ' => Ok(Phagspa::PhagsDashPaLetterSha),
'ꡛ' => Ok(Phagspa::PhagsDashPaLetterSa),
'ꡜ' => Ok(Phagspa::PhagsDashPaLetterHa),
'ꡝ' => Ok(Phagspa::PhagsDashPaLetterA),
'ꡞ' => Ok(Phagspa::PhagsDashPaLetterI),
'ꡟ' => Ok(Phagspa::PhagsDashPaLetterU),
'ꡠ' => Ok(Phagspa::PhagsDashPaLetterE),
'ꡡ' => Ok(Phagspa::PhagsDashPaLetterO),
'ꡢ' => Ok(Phagspa::PhagsDashPaLetterQa),
'ꡣ' => Ok(Phagspa::PhagsDashPaLetterXa),
'ꡤ' => Ok(Phagspa::PhagsDashPaLetterFa),
'ꡥ' => Ok(Phagspa::PhagsDashPaLetterGga),
'ꡦ' => Ok(Phagspa::PhagsDashPaLetterEe),
'ꡧ' => Ok(Phagspa::PhagsDashPaSubjoinedLetterWa),
'ꡨ' => Ok(Phagspa::PhagsDashPaSubjoinedLetterYa),
'ꡩ' => Ok(Phagspa::PhagsDashPaLetterTta),
'ꡪ' => Ok(Phagspa::PhagsDashPaLetterTtha),
'ꡫ' => Ok(Phagspa::PhagsDashPaLetterDda),
'ꡬ' => Ok(Phagspa::PhagsDashPaLetterNna),
'ꡭ' => Ok(Phagspa::PhagsDashPaLetterAlternateYa),
'ꡮ' => Ok(Phagspa::PhagsDashPaLetterVoicelessSha),
'ꡯ' => Ok(Phagspa::PhagsDashPaLetterVoicedHa),
'ꡰ' => Ok(Phagspa::PhagsDashPaLetterAspiratedFa),
'ꡱ' => Ok(Phagspa::PhagsDashPaSubjoinedLetterRa),
'ꡲ' => Ok(Phagspa::PhagsDashPaSuperfixedLetterRa),
'ꡳ' => Ok(Phagspa::PhagsDashPaLetterCandrabindu),
'꡴' => Ok(Phagspa::PhagsDashPaSingleHeadMark),
'꡵' => Ok(Phagspa::PhagsDashPaDoubleHeadMark),
'꡶' => Ok(Phagspa::PhagsDashPaMarkShad),
'꡷' => Ok(Phagspa::PhagsDashPaMarkDoubleShad),
_ => Err(()),
}
}
}
impl Into<u32> for Phagspa {
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 Phagspa {
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 Phagspa {
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 Phagspa {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
Phagspa::PhagsDashPaLetterKa
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("Phagspa{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(name = "Cat", about = "Read a file and display its content.")]
pub struct CatArgs {
pub file_name: String,
}
|
use std::{io, net::SocketAddr, process::exit, sync::Arc, sync::atomic::{AtomicBool, Ordering}, sync::mpsc::{channel, Sender}, thread::{JoinHandle, sleep}, thread, time::Duration};
use std::fmt::{Display, Formatter};
use std::sync::atomic::Ordering::SeqCst;
use structopt::StructOpt;
use crate::{
blockchain::Blockchain,
Direction::{Inbound, Outbound},
networked_message::NetworkedMessage,
};
use crate::block::Block;
use crate::miner::ToMiner;
use crate::networking::Networking;
use crate::node::{Node, Outgoing};
use crate::terminal_input::{Command, PollError};
use rand::Rng;
mod blockchain;
mod terminal_input;
mod networked_message;
mod node;
mod networking;
mod miner;
mod block;
#[derive(Debug)]
pub struct Connection {
addr: SocketAddr,
thread: JoinHandle<io::Result<()>>,
sender: Sender<NetworkedMessage>,
direction: Direction,
}
impl PartialEq for Connection {
fn eq(&self, other: &Self) -> bool {
self.addr == other.addr
}
}
impl Display for Connection {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "({}, {})", self.addr, self.direction)
}
}
#[derive(Debug, PartialEq, Copy, Clone)]
enum Direction {
Inbound,
Outbound,
}
impl Display for Direction {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Inbound => write!(f, "Inbound"),
Outbound => write!(f, "Outbound"),
}
}
}
// TODO: # Introduce sync phase #
// Phase 1, Sync:
// seed peers
// For now just rely on the user specifying exact IP's
// Maybe just choose a node and ask it to send a full history
// Phase 2, maintain the blockchain & mine
//
// TODO: In line with the syncing phase, do not spam the network as much/be smarter about when to
// request
// TODO: Add transactions to blocks
// TODO: Handle blocks of different sizes, AKA don't assume all blocks have the same size, but DO
// assume a max size for buffer purposes/DOS-protection
// TODO: Persist peers on shutdown
// TODO: Clean up all the unwraps
// TODO: Simulate poor network conditions
#[derive(StructOpt, Debug)]
#[structopt()]
struct Args {
/// Bind node to this address
#[structopt()]
address: SocketAddr,
/// Connect to this address
#[structopt(short, long)]
connect: Vec<SocketAddr>,
/// Start mining right away
#[structopt(short, long)]
mine: bool,
/// Path to the blockchain database file, if none exists, it will be created
#[structopt(short, long)]
blockchain_path: String,
}
pub fn spawn_with_name<F, T>(name: &str, f: F) -> JoinHandle<T>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static
{
let builder = thread::Builder::new();
builder.name(name.into()).spawn(f).expect("failed to spawn thread")
}
fn main() -> io::Result<()> {
let args = Args::from_args();
let should_mine_on_startup = args.mine;
let quit_requested = Arc::new(AtomicBool::new(false));
{
let quit_requested = quit_requested.clone();
ctrlc::set_handler(move || {
if quit_requested.load(Ordering::SeqCst) {
eprintln!("\rExiting forcefully");
exit(1);
} else {
eprint!("\r"); // Let further printing override the '^C'
quit_requested.store(true, Ordering::SeqCst);
}
}).unwrap();
}
let blockchain = Blockchain::new(Block::new(
[0; 32],
[0; 32],
0,
1622999578, // SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(),
), &args.blockchain_path).unwrap();
let (node_sender, node_receiver) = channel();
let (networking_sender, networking_receiver) = channel();
let (miner_sender, miner_receiver) = channel();
let mut networking = Networking::new(args.address, node_sender.clone(), networking_receiver);
let mut node = Node::new(blockchain, node_receiver, networking_sender.clone(), miner_sender.clone());
let miner_address = rand::thread_rng().gen::<[u8; 32]>();
let miner_thread = miner::spawn_miner(miner_address, miner_receiver, node_sender.clone());
for addr in args.connect {
networking_sender.send(Outgoing::Connect(addr)).unwrap();
}
if should_mine_on_startup {
let top = node.blockchain.top().unwrap();
miner_sender.send(ToMiner::Start(
node.blockchain.difficulty_target(&top).unwrap(), top.clone(),
)).unwrap();
}
let mut terminal_input_enabled = true;
let mut command_reader = terminal_input::CommandReader::new();
loop {
if quit_requested.load(SeqCst) {
eprintln!("Shutting down...");
std::mem::drop(miner_sender);
std::mem::drop(node);
networking.close();
miner_thread.join().unwrap().unwrap();
break;
}
if terminal_input_enabled {
loop {
match command_reader.poll() {
Ok(Command::Quit) => quit_requested.store(true, SeqCst),
Ok(Command::Connect(addr)) =>
networking_sender.send(Outgoing::Connect(addr)).unwrap(),
Ok(Command::SendPing) =>
networking_sender.send(Outgoing::Broadcast(NetworkedMessage::Ping)).unwrap(),
Ok(Command::StartMiner) => {
let top = node.blockchain.top().unwrap();
miner_sender.send(ToMiner::Start(
node.blockchain.difficulty_target(&top).unwrap(),
top.clone())
).unwrap();
}
Ok(Command::StopMiner) => miner_sender.send(ToMiner::Stop).unwrap(),
Ok(Command::ShowTopBlock) => {
let top = node.blockchain.top().unwrap();
eprintln!(
"{}, height: {}",
top,
node.blockchain.height(top.hash()).unwrap())
}
Ok(Command::Peers) => eprintln!("{:?}", node.peers),
Ok(Command::Blocks) => node.blockchain.print_blocks().unwrap(),
Err(PollError::WouldBlock) => break,
Err(error) => {
eprintln!("Failed to read from terminal, disabling terminal input: {:?}", error);
terminal_input_enabled = false;
break;
}
}
}
}
networking.process(); // TODO: Any reason these are not thread blocking on the channel, handling their own sleep?
node.process(); // TODO: Any reason these are not thread blocking on the channel, handling their own sleep?
// TODO: Replace with something smarter and OS dependant (i.e. sleep until
// terminal/socket/miner event received)
sleep(Duration::from_millis(10));
}
Ok(())
}
|
//!
//! Snippet Archive for Line Protocol Formatting/Parsing
//!
// pub fn from_line(line: &str) -> InfluxResult<Self>
// {
// let parts = line.split(" ")
// .collect::<Vec<&str>>();
// if parts.len() != 3 {
// return Err(format!("Invalid measurement line: '{}'. Please consult the InfluxDB line protocol documentation", line).into())
// }
// let part_msrmt = parse_measurement(parts[0])?;
// let part_fields = parse_fields(parts[1])?;
// let part_tstamp = parts[2];
// let mut this = Self::new(part_msrmt.0);
// this.tags = part_msrmt.1;
// this.fields = part_fields;
// this.timestamp = Some(part_tstamp);
// Ok(this)
// }
// fn parse_measurement<'m>(fragment: &'m str) -> InfluxResult<(&'m str, BTreeMap<String, String>)>
// {
// let mut tags = BTreeMap::new();
// let mut parts = fragment.split(",");
// if let Some(msrmt) = parts.next()
// {
// while let Some(tag) = parts.next()
// {
// let tag_parts = tag.split("=")
// .collect::<Vec<&str>>();
// if tag_parts.len() != 2 {
// return Err("All tags must have a key=value format".into());
// }
// let key = tag_parts[0].to_owned();
// let value = tag_parts[1].to_owned();
// tags.insert(key, value);
// }
// Ok((msrmt, tags))
// }
// else {
// Err("Measurement is missing in line".into())
// }
// }
// fn parse_fields(fragment: &str) -> InfluxResult<BTreeMap<String, String>>
// {
// let mut fields = BTreeMap::new();
// let mut parts = fragment.split(",");
// while let Some(field) = parts.next()
// {
// let field_parts = field.split("=")
// .collect::<Vec<&str>>();
// if field_parts.len() != 2 {
// return Err("All fields must have a key=value format".into());
// }
// let key = field_parts[0].to_owned();
// let value = field_parts[1].to_owned();
// fields.insert(key, value);
// }
// Ok(fields)
// }
|
--- cargo-crates/termios-0.2.2/src/lib.rs.orig 2016-01-20 16:52:20 UTC
+++ cargo-crates/termios-0.2.2/src/lib.rs
@@ -89,6 +89,11 @@
//! cfsetspeed(termios, termios::os::macos::B230400)
//! }
//!
+//! #[cfg(target_os = "dragonfly")]
+//! fn set_fastest_speed(termios: &mut Termios) -> io::Result<()> {
+//! cfsetspeed(termios, termios::os::dragonfly::B921600)
+//! }
+//!
//! #[cfg(target_os = "freebsd")]
//! fn set_fastest_speed(termios: &mut Termios) -> io::Result<()> {
//! cfsetspeed(termios, termios::os::freebsd::B921600)
|
use std::io::*;
use std::sync::Arc;
use flicbtn::*;
#[tokio::main]
async fn main() -> Result<()> {
let event = event_handler(|event| {
println!("ping response: {:?}", event);
});
let client = FlicClient::new("127.0.0.1:5551")
.await?
.register_event_handler(event)
.await;
let client1 = Arc::new(client);
let client2 = client1.clone();
let button = "80:e4:da:76:fa:55";
let mut scan_wizard_id = 0;
let mut conn_id = 0;
let cmd = tokio::spawn(async move {
println!("===============================================");
println!("*** Hello to the Flic2 Button Simple Client ***");
println!("===============================================");
client1.submit(Command::GetInfo).await;
println!("");
loop {
show_commands();
println!("");
print!("-- Choose: ");
let _ = stdout().flush();
let mut input = String::new();
stdin()
.read_line(&mut input)
.expect("Did not enter correct string!");
let input = input.trim();
match input.as_str() {
"X" => break,
"1" => {
println!("-- start scan wizard");
scan_wizard_id += 1;
client1
.submit(Command::CreateScanWizard { scan_wizard_id })
.await;
}
"2" => {
println!("-- cancel scan wizard");
client1
.submit(Command::CancelScanWizard { scan_wizard_id })
.await;
//scan_wizard_id -= 1;
}
"3" => {
println!("-- create connection channel");
conn_id += 1;
client1
.submit(Command::CreateConnectionChannel {
conn_id,
bd_addr: button.to_string(),
latency_mode: LatencyMode::NormalLatency,
auto_disconnect_time: 11111_i16,
})
.await;
}
"4" => {
println!("-- remove connection channel");
client1
.submit(Command::RemoveConnectionChannel { conn_id })
.await;
//conn_id -= 1;
}
"5" => {
println!("-- button info");
client1
.submit(Command::GetButtonInfo {
bd_addr: button.to_string(),
})
.await;
}
_ => {
println!("-- unknown command");
}
}
println!("");
}
client1.stop().await;
});
let lst = tokio::spawn(async move {
client2.listen().await;
println!("stop");
});
lst.await?;
cmd.await?;
Ok(())
}
fn show_commands() {
println!("1) Start Scan Wizard");
println!("2) Cancel Scan Wizard");
println!("3) Create Connection Channel");
println!("4) Remove Connection Channel");
println!("5) Get Button Info");
println!("X) End");
}
|
use actix::prelude::*;
use diesel::prelude::*;
use failure_derive::Fail;
use unicode_normalization::UnicodeNormalization;
use crate::db::models::{NewUser, User, UserLog};
use crate::db::DbExecutor;
use crate::utils::PerfLog;
use actix_web::{dev::Body, http::StatusCode, web::HttpResponse, ResponseError};
use rand::Rng;
const HASH_CONFIG: argon2::Config = argon2::Config {
ad: &[],
hash_length: 32,
lanes: 1,
mem_cost: 128 * 1024, // 128 MiB
secret: &[],
thread_mode: argon2::ThreadMode::Sequential,
time_cost: 2,
variant: argon2::Variant::Argon2i,
version: argon2::Version::Version13,
};
pub struct CreateUser {
pub name: String,
pub password: Vec<u8>,
}
#[derive(Debug, Fail)]
pub enum Error {
#[fail(display = "Incorrect username or password")]
InvalidCredentials,
#[fail(display = "User already exists")]
UserExists,
#[fail(display = "Requested user not found")]
NotFound,
#[fail(display = "Database error occurred")]
DbError(#[cause] diesel::result::Error),
#[fail(display = "Error while hashing")]
HashError(#[cause] argon2::Error),
}
impl ResponseError for Error {
fn error_response(&self) -> HttpResponse<Body> {
match self {
Error::InvalidCredentials => HttpResponse::new(StatusCode::BAD_REQUEST),
Error::UserExists => HttpResponse::new(StatusCode::BAD_REQUEST),
Error::NotFound => HttpResponse::new(StatusCode::NOT_FOUND),
Error::DbError(_) => HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR),
Error::HashError(_) => HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR),
}
}
}
impl From<diesel::result::Error> for Error {
fn from(f: diesel::result::Error) -> Self {
Error::DbError(f)
}
}
impl From<argon2::Error> for Error {
fn from(f: argon2::Error) -> Self {
Error::HashError(f)
}
}
impl Message for CreateUser {
type Result = Result<(), Error>;
}
impl Handler<CreateUser> for DbExecutor {
type Result = Result<(), Error>;
fn handle(&mut self, msg: CreateUser, _: &mut Self::Context) -> Self::Result {
use super::schema::users::dsl::{self, users};
let mut salt = [0u8; 16];
rand::thread_rng().fill(&mut salt);
let username = normalize_username(&msg.name);
// Check if user already exists
match users
.filter(dsl::login.eq(&username))
.first::<User>(&self.0)
{
Err(diesel::result::Error::NotFound) => (),
Ok(_) => return Err(Error::UserExists),
Err(e) => return Err(Error::DbError(e)),
}
let p = PerfLog::new();
let hash = &argon2::hash_encoded(&msg.password, &salt, &HASH_CONFIG)?;
p.log("Hash time");
let new_user = NewUser {
login: &username,
hash,
role: User::ROLE_CUSTOMER,
};
diesel::insert_into(users)
.values(&new_user)
.execute(&self.0)?;
Ok(())
}
}
pub struct Login {
pub name: String,
pub password: Vec<u8>,
pub ip_addr: String,
pub user_agent: String,
}
impl Message for Login {
type Result = Result<User, Error>;
}
impl Handler<Login> for DbExecutor {
type Result = Result<User, Error>;
fn handle(&mut self, msg: Login, _: &mut Self::Context) -> Self::Result {
use super::schema::logs::dsl::logs;
use super::schema::users::dsl::{self, users};
let username = normalize_username(&msg.name);
let mut log_entry = UserLog {
login: &username,
logging_time: chrono::offset::Utc::now().naive_utc(),
logging_succession: false,
ip_addr: &msg.ip_addr,
user_agent: &msg.user_agent,
};
let user = match users
.filter(dsl::login.eq(&username))
.first::<User>(&self.0)
{
Ok(u) => u,
Err(diesel::result::Error::NotFound) => {
diesel::insert_into(logs)
.values(&log_entry)
.execute(&self.0)?;
return Err(Error::InvalidCredentials);
}
Err(e) => return Err(Error::DbError(e)),
};
log_entry.logging_succession =
user.active && argon2::verify_encoded(&user.hash, &msg.password)?;
diesel::insert_into(logs)
.values(&log_entry)
.execute(&self.0)?;
if log_entry.logging_succession {
Ok(user)
} else {
Err(Error::InvalidCredentials)
}
}
}
pub struct DeleteAccount {
pub id: i32,
}
impl Message for DeleteAccount {
type Result = Result<(), Error>;
}
impl Handler<DeleteAccount> for DbExecutor {
type Result = Result<(), Error>;
fn handle(&mut self, msg: DeleteAccount, _: &mut Self::Context) -> Self::Result {
use super::schema::users::dsl::{active, id, users};
match diesel::update(users.filter(id.eq(msg.id)))
.set(active.eq(false))
.execute(&self.0)
{
Ok(_) => Ok(()),
Err(diesel::result::Error::NotFound) => Err(Error::NotFound),
Err(e) => Err(Error::DbError(e)),
}
}
}
pub struct GetUsers;
impl Message for GetUsers {
type Result = Result<Vec<User>, Error>;
}
impl Handler<GetUsers> for DbExecutor {
type Result = Result<Vec<User>, Error>;
fn handle(&mut self, _msg: GetUsers, _: &mut Self::Context) -> Self::Result {
use super::schema::users::dsl::users;
Ok(users.load::<User>(&self.0)?)
}
}
fn normalize_username(s: &str) -> String {
s.nfkc().collect::<String>().to_lowercase()
}
|
// Copyright (C) 2017 1aim GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::parser::helper::*;
use nom::{branch::*, combinator::*, multi::*, IResult};
pub fn phone_number(i: &str) -> IResult<&str, &str> {
parse! { i => recognize(alt((short, long))) }
}
fn short(i: &str) -> IResult<&str, ()> {
parse! { i =>
count(digit, 2);
ieof;
};
Ok((i, ()))
}
fn long(i: &str) -> IResult<&str, ()> {
parse! { i =>
many0(plus);
many0(alt((punctuation, star)));
count(digit, 3);
many0(digit);
many0(alt((punctuation, star, digit, alpha)));
ieof;
};
Ok((i, ()))
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn phone() {
assert!(phone_number("1").is_err());
// Only one or two digits before strange non-possible punctuation.
assert!(phone_number("1+1+1").is_err());
assert!(phone_number("80+0").is_err());
// Two digits is viable.
assert!(phone_number("00").is_ok());
assert!(phone_number("111").is_ok());
// Alpha numbers.
assert!(phone_number("0800-4-pizza").is_ok());
assert!(phone_number("0800-4-PIZZA").is_ok());
// We need at least three digits before any alpha characters.
assert!(phone_number("08-PIZZA").is_err());
assert!(phone_number("8-PIZZA").is_err());
assert!(phone_number("12. March").is_err());
}
}
|
use lazy_static::lazy_static;
use regex::Regex;
use serde_json::Value;
use crate::validator::{scope::ScopedSchema, state::ValidationState};
lazy_static! {
// data:text/plain;name=test.txt;base64,aGV...
static ref FILE_REGEX: Regex =
Regex::new(r"^data:.*;name=(.*);([a-zA-Z0-9]+),(.*)$").unwrap();
}
pub fn validate_as_file(scope: &ScopedSchema, data: &Value) -> ValidationState {
let s = match data.as_str() {
Some(x) => x,
None => return scope.error("type", "expected `file`").into(),
};
let captures = match FILE_REGEX.captures(s) {
Some(x) => x,
_ => return scope.error("type", "expected `file`").into(),
};
if (&captures[1]).is_empty() {
return scope.error("type", "file name is missing").into();
}
if &captures[2] != "base64" {
return scope.error("type", "only base64 is supported").into();
}
match base64::decode(&captures[3]) {
Ok(_) => ValidationState::new(),
Err(_) => scope.error("type", "unable to decode file data").into(),
}
}
|
extern crate rand;
mod ability;
mod action;
mod confirmation;
mod dice;
mod game;
mod map;
mod player;
mod room;
mod test_world;
use ability::{Ability, AbilityFactory};
use game::Game;
use player::PlayerBuilder;
use std::io;
fn main() {
println!("D20 System Initializing");
let mut player_builder = PlayerBuilder::new();
println!("Name your hero");
let mut name = String::new();
io::stdin().read_line(&mut name).expect("Failed to read name");
player_builder.name(name.trim().to_string());
let mut rolls;
loop {
rolls = vec![
dice::roll(3, 6),
dice::roll(3, 6),
dice::roll(3, 6),
dice::roll(3, 6),
dice::roll(3, 6),
dice::roll(3, 6),
];
if rolls_valid(&rolls) {
break;
}
}
let mut rolls: Vec<Ability> = rolls
.iter()
.map(|roll| AbilityFactory::new().roll(*roll).finalize())
.collect();
player_builder.strength(select_ability(&mut rolls, "Strength"));
player_builder.dexterity(select_ability(&mut rolls, "Dexterity"));
player_builder.constitution(select_ability(&mut rolls, "Constitution"));
player_builder.intelligence(select_ability(&mut rolls, "Intelligence"));
player_builder.wisdom(select_ability(&mut rolls, "Wisdom"));
player_builder.charisma(select_ability(&mut rolls, "Charisma"));
let player = player_builder.finalize();
println!("Created player {}", player.get_name());
println!(
"STR: {} -> {:+}",
player.get_strength().get_roll(),
player.get_strength().get_modifier());
println!(
"DEX: {} -> {:+}",
player.get_dexterity().get_roll(),
player.get_dexterity().get_modifier());
println!(
"CON: {} -> {:+}",
player.get_constitution().get_roll(),
player.get_constitution().get_modifier());
println!(
"INT: {} -> {:+}",
player.get_intelligence().get_roll(),
player.get_intelligence().get_modifier());
println!(
"WIS: {} -> {:+}",
player.get_wisdom().get_roll(),
player.get_wisdom().get_modifier());
println!(
"CHA: {} -> {:+}",
player.get_charisma().get_roll(),
player.get_charisma().get_modifier());
println!("Building game...");
let mut map = test_world::build_world();
let mut game = Game::new(player, &mut map);
game.start();
}
fn select_ability(rolls: &mut Vec<Ability>, name: &str) -> Ability {
println!("Ability Scores Available:");
for (index, roll) in rolls.iter().enumerate() {
println!("[{}] {} -> {}", index, roll.get_roll(), roll.get_modifier());
}
loop {
println!("Select Ability for {}:", name);
let mut selection = String::new();
io::stdin().read_line(&mut selection).expect("Failed to read line");
let selection: i32 = match selection.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Couldn't parse {}, try again!", selection);
continue;
}
};
if selection < 0 || selection >= rolls.len() as i32 {
println!("{} is not a valid index", selection);
continue;
}
return rolls.remove(selection as usize);
}
}
fn rolls_valid(rolls: &Vec<i32>) -> bool {
if rolls.len() != 6 {
return false;
}
let mut sum: i32 = 0;
let mut max: i32 = i32::min_value();
for roll in rolls {
sum += *roll;
if *roll > max {
max = *roll;
}
}
sum > 0 && max > 1
}
|
/*
* Copyright (C) 2019-2021 TON Labs. All Rights Reserved.
*
* Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use
* this file except in compliance with the License.
*
* 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 TON DEV software governing permissions and
* limitations under the License.
*/
use num_bigint::{BigInt, BigUint};
#[derive(Clone, Debug, PartialEq)]
pub struct Int {
pub number: BigInt,
pub size: usize,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Uint {
pub number: BigUint,
pub size: usize,
}
impl Int {
pub fn new(number: i128, size: usize) -> Self {
Self { number: BigInt::from(number), size }
}
}
impl Uint {
pub fn new(number: u128, size: usize) -> Self {
Self { number: BigUint::from(number), size }
}
}
|
use bitcoin::hashes::hex::ToHex;
use bitcoin::{Script, Txid};
use types::{Param, ToElectrumScriptHash};
pub struct Batch {
calls: Vec<(String, Vec<Param>)>,
}
impl Batch {
pub fn script_list_unspent(&mut self, script: &Script) {
let params = vec![Param::String(script.to_electrum_scripthash().to_hex())];
self.calls
.push((String::from("blockchain.scripthash.listunspent"), params));
}
pub fn script_get_history(&mut self, script: &Script) {
let params = vec![Param::String(script.to_electrum_scripthash().to_hex())];
self.calls
.push((String::from("blockchain.scripthash.get_history"), params));
}
pub fn script_get_balance(&mut self, script: &Script) {
let params = vec![Param::String(script.to_electrum_scripthash().to_hex())];
self.calls
.push((String::from("blockchain.scripthash.get_balance"), params));
}
pub fn transaction_get(&mut self, tx_hash: &Txid) {
let params = vec![Param::String(tx_hash.to_hex())];
self.calls
.push((String::from("blockchain.transaction.get"), params));
}
}
impl std::iter::IntoIterator for Batch {
type Item = (String, Vec<Param>);
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.calls.into_iter()
}
}
impl std::default::Default for Batch {
fn default() -> Self {
Batch { calls: Vec::new() }
}
}
|
#![crate_type = "lib"]
#![crate_name = "rsnova"]
#![recursion_limit = "256"]
#[macro_use]
extern crate log;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate futures;
pub use self::config::Config;
mod channel;
pub mod config;
mod debug;
mod rmux;
mod tunnel;
mod utils;
use futures::FutureExt;
use std::error::Error;
use std::thread;
pub async fn start_rsnova(cfg: config::Config) -> Result<(), Box<dyn Error>> {
let mut logger = flexi_logger::Logger::with_str(cfg.log.level.as_str());
if !cfg.log.logdir.is_empty() {
logger = logger
.log_to_file()
.rotate(
flexi_logger::Criterion::Size(1024 * 1024),
flexi_logger::Naming::Numbers,
flexi_logger::Cleanup::KeepLogFiles(10),
)
.directory(cfg.log.logdir)
.format(flexi_logger::colored_opt_format);
}
if cfg.log.logtostderr {
logger = logger.duplicate_to_stderr(flexi_logger::Duplicate::Info);
}
logger.start().unwrap();
if cfg.debug.is_some() {
let debug_cfg = cfg.debug.unwrap();
let debug_server = tiny_http::Server::http(debug_cfg.listen.as_str()).unwrap();
thread::spawn(move || {
debug::handle_debug_server(debug_server);
});
}
for c in cfg.tunnel {
info!("Start rsnova client at {} ", c.listen);
let handle = tunnel::start_tunnel_server(c).map(|r| {
if let Err(e) = r {
error!("Failed to start server; error={}", e);
}
});
tokio::spawn(handle);
}
channel::routine_channels(cfg.channel).await;
Ok(())
}
|
use platform;
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let app = platform::commands::new_app();
app.run(args);
}
|
#![allow(dead_code)]
use crate::cpu::CpuInterface;
use crate::cpu::Interface;
use crate::savable::Savable;
/// Bus used for easier cpu testing
pub struct TestBus {
ram: [u8; 0x800],
program: Vec<u8>,
}
impl Interface for TestBus {
fn read(&mut self, addr: u16) -> u8 {
match addr {
0x0000..=0x1FFF => self.ram[(addr & 0x7FF) as usize],
_ => self.program[(addr - 0x2000) as usize],
}
}
fn write(&mut self, addr: u16, data: u8) {
match addr {
0x0000..=0x1FFF => self.ram[(addr & 0x7FF) as usize] = data,
_ => self.program[(addr - 0x2000) as usize] = data,
}
}
}
impl CpuInterface for TestBus {}
impl TestBus {
pub fn new(program: Vec<u8>) -> Self {
Self {
ram: [0; 0x800],
program,
}
}
/// Sets a value at a RAM address
pub fn set_ram(&mut self, addr: u16, data: u8) {
self.ram[(addr & 0x7FF) as usize] = data;
}
}
impl Savable for TestBus {}
|
#[doc = "Register `DINR8` reader"]
pub type R = crate::R<DINR8_SPEC>;
#[doc = "Field `DIN8` reader - Input data received from MDIO Master during write frames"]
pub type DIN8_R = crate::FieldReader<u16>;
impl R {
#[doc = "Bits 0:15 - Input data received from MDIO Master during write frames"]
#[inline(always)]
pub fn din8(&self) -> DIN8_R {
DIN8_R::new((self.bits & 0xffff) as u16)
}
}
#[doc = "MDIOS input data register 8\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dinr8::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DINR8_SPEC;
impl crate::RegisterSpec for DINR8_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`dinr8::R`](R) reader structure"]
impl crate::Readable for DINR8_SPEC {}
#[doc = "`reset()` method sets DINR8 to value 0"]
impl crate::Resettable for DINR8_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[doc = "Register `DDRPHYC_DX1GSR0` reader"]
pub type R = crate::R<DDRPHYC_DX1GSR0_SPEC>;
#[doc = "Field `DTDONE` reader - DTDONE"]
pub type DTDONE_R = crate::BitReader;
#[doc = "Field `DTERR` reader - DTERR"]
pub type DTERR_R = crate::BitReader;
#[doc = "Field `DTIERR` reader - DTIERR"]
pub type DTIERR_R = crate::BitReader;
#[doc = "Field `DTPASS` reader - DTPASS"]
pub type DTPASS_R = crate::FieldReader;
impl R {
#[doc = "Bit 0 - DTDONE"]
#[inline(always)]
pub fn dtdone(&self) -> DTDONE_R {
DTDONE_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 4 - DTERR"]
#[inline(always)]
pub fn dterr(&self) -> DTERR_R {
DTERR_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 8 - DTIERR"]
#[inline(always)]
pub fn dtierr(&self) -> DTIERR_R {
DTIERR_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bits 13:15 - DTPASS"]
#[inline(always)]
pub fn dtpass(&self) -> DTPASS_R {
DTPASS_R::new(((self.bits >> 13) & 7) as u8)
}
}
#[doc = "DDRPHYC byte lane 1 GS register 0\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ddrphyc_dx1gsr0::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DDRPHYC_DX1GSR0_SPEC;
impl crate::RegisterSpec for DDRPHYC_DX1GSR0_SPEC {
type Ux = u16;
}
#[doc = "`read()` method returns [`ddrphyc_dx1gsr0::R`](R) reader structure"]
impl crate::Readable for DDRPHYC_DX1GSR0_SPEC {}
#[doc = "`reset()` method sets DDRPHYC_DX1GSR0 to value 0"]
impl crate::Resettable for DDRPHYC_DX1GSR0_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::renderer::con_back::ConBackError;
use log::error;
pub trait LogError {
fn log(&self);
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Error {
Static(&'static str),
Owned(String),
ConBack(ConBackError),
// IO(std::io::Error),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
use Error::*;
match self {
Static(m) => write!(f, "{}", m),
Owned(m) => write!(f, "{}", m),
ConBack(e) => write!(f, "{}", e),
}
}
}
impl<T> LogError for Result<T, Error> {
fn log(&self) {
match self {
Ok(_) => (),
Err(err) => error!("{}", err),
}
}
}
impl From<ConBackError> for Error {
fn from(e: ConBackError) -> Self {
Error::ConBack(e)
}
}
impl From<&'static str> for Error {
fn from(m: &'static str) -> Self {
Error::Static(m)
}
}
impl From<String> for Error {
fn from(m: String) -> Self {
Error::Owned(m)
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
// Error::IO(e)
Error::Owned(format!("{}", e))
}
}
impl From<gfx_hal::device::MapError> for Error {
fn from(e: gfx_hal::device::MapError) -> Self {
Error::Owned(format!("{}", e))
}
}
impl From<gfx_hal::device::OutOfMemory> for Error {
fn from(e: gfx_hal::device::OutOfMemory) -> Self {
Error::Owned(format!("{}", e))
}
}
impl From<gfx_hal::pso::AllocationError> for Error {
fn from(e: gfx_hal::pso::AllocationError) -> Self {
Error::Owned(format!("{}", e))
}
}
impl From<gfx_hal::device::OomOrDeviceLost> for Error {
fn from(e: gfx_hal::device::OomOrDeviceLost) -> Self {
Error::Static("Out of memory, device lost")
}
}
impl From<gfx_hal::window::PresentError> for Error {
fn from(e: gfx_hal::window::PresentError) -> Self {
Error::Owned(format!("Could not present into swapchain: {}", e))
}
}
impl From<gfx_hal::image::CreationError> for Error {
fn from(e: gfx_hal::image::CreationError) -> Self {
Error::Owned(format!("{}", e))
}
}
impl From<gfx_hal::device::AllocationError> for Error {
fn from(e: gfx_hal::device::AllocationError) -> Self {
Error::Owned(format!("{}", e))
}
}
impl From<gfx_hal::device::BindError> for Error {
fn from(e: gfx_hal::device::BindError) -> Self {
Error::Owned(format!("{}", e))
}
}
impl From<gfx_hal::image::ViewError> for Error {
fn from(e: gfx_hal::image::ViewError) -> Self {
Error::Owned(format!("{}", e))
}
}
|
use std::ops::{Bound, Not};
use std::sync::Arc;
use anyhow::Context;
use axum::extract::{Extension, Path};
use chrono::Utc;
use hyper::{Body, Response};
use serde_derive::Deserialize;
use svc_agent::AgentId;
use svc_authn::AccountId;
use svc_utils::extractors::AccountIdExtractor;
use uuid::Uuid;
use super::{find, AppResult, ClassResponseBody};
use crate::app::error::ErrorKind as AppErrorKind;
use crate::app::http::Json;
use crate::app::{api::v1::find_by_scope, error::ErrorExt};
use crate::app::{authz::AuthzObject, metrics::AuthorizeMetrics};
use crate::app::{error, AppContext};
use crate::clients::{
conference::RoomUpdate as ConfRoomUpdate, event::RoomUpdate as EventRoomUpdate,
};
use crate::db::class;
use crate::db::class::{AsClassType, BoundedDateTimeTuple};
#[derive(Deserialize)]
pub struct ClassUpdate {
#[serde(default, with = "crate::serde::ts_seconds_option_bound_tuple")]
time: Option<BoundedDateTimeTuple>,
reserve: Option<i32>,
host: Option<AgentId>,
}
pub async fn update<T: AsClassType>(
Extension(ctx): Extension<Arc<dyn AppContext>>,
Path(id): Path<Uuid>,
AccountIdExtractor(account_id): AccountIdExtractor,
Json(payload): Json<ClassUpdate>,
) -> AppResult {
let class = find::<T>(ctx.as_ref(), id)
.await
.error(AppErrorKind::ClassNotFound)?;
let updated_class = do_update::<T>(ctx.as_ref(), &account_id, class, payload).await?;
Ok(Response::builder()
.body(Body::from(
serde_json::to_string(&updated_class)
.context("Failed to serialize minigroup")
.error(AppErrorKind::SerializationFailed)?,
))
.unwrap())
}
pub async fn update_by_scope<T: AsClassType>(
Extension(ctx): Extension<Arc<dyn AppContext>>,
Path((audience, scope)): Path<(String, String)>,
AccountIdExtractor(account_id): AccountIdExtractor,
Json(payload): Json<ClassUpdate>,
) -> AppResult {
let class = find_by_scope::<T>(ctx.as_ref(), &audience, &scope)
.await
.error(AppErrorKind::ClassNotFound)?;
let updated_class = do_update::<T>(ctx.as_ref(), &account_id, class, payload).await?;
let response =
ClassResponseBody::new(&updated_class, ctx.turn_host_selector().get(&updated_class));
Ok(Response::builder()
.body(Body::from(
serde_json::to_string(&response)
.context("Failed to serialize minigroup")
.error(AppErrorKind::SerializationFailed)?,
))
.unwrap())
}
async fn do_update<T: AsClassType>(
state: &dyn AppContext,
account_id: &AccountId,
class: crate::db::class::Object,
body: ClassUpdate,
) -> Result<class::Object, error::Error> {
let object = AuthzObject::new(&["classrooms", &class.id().to_string()]).into();
state
.authz()
.authorize(
class.audience().to_owned(),
account_id.clone(),
object,
"update".into(),
)
.await
.measure()?;
let event_update = get_event_update(&class, &body)
.map(|(id, update)| state.event_client().update_room(id, update));
let conference_update = get_coneference_update(&class, &body)
.map(|(id, update)| state.conference_client().update_room(id, update));
match (event_update, conference_update) {
(None, None) => Ok(()),
(None, Some(c)) => c.await,
(Some(e), None) => e.await,
(Some(e), Some(c)) => tokio::try_join!(e, c).map(|_| ()),
}
.context("Services requests")
.error(AppErrorKind::MqttRequestFailed)?;
let mut query = crate::db::class::ClassUpdateQuery::new(class.id());
if let Some(t) = body.time {
query = query.time(t.into());
}
if let Some(r) = body.reserve {
query = query.reserve(r);
}
if let Some(host) = body.host {
query = query.host(host);
}
let mut conn = state.get_conn().await.error(AppErrorKind::DbQueryFailed)?;
let class = query
.execute(&mut conn)
.await
.context("Failed to update webinar")
.error(AppErrorKind::DbQueryFailed)?;
Ok(class)
}
fn get_coneference_update(
class: &class::Object,
update: &ClassUpdate,
) -> Option<(Uuid, ConfRoomUpdate)> {
let conf_room_id = class.conference_room_id();
let conf_update = ConfRoomUpdate {
time: update.time.map(|(start, end)| match start {
Bound::Included(t) | Bound::Excluded(t) => (Bound::Included(t), end),
Bound::Unbounded => (Bound::Unbounded, Bound::Unbounded),
}),
reserve: update.reserve,
classroom_id: None,
host: update.host.clone(),
};
conf_update
.is_empty_update()
.not()
.then_some((conf_room_id, conf_update))
}
fn get_event_update(
class: &class::Object,
update: &ClassUpdate,
) -> Option<(Uuid, EventRoomUpdate)> {
let update = EventRoomUpdate {
time: update
.time
.map(|_| (Bound::Included(Utc::now()), Bound::Unbounded)),
classroom_id: None,
};
update
.is_empty_update()
.not()
.then(|| (class.event_room_id(), update))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
db::class::{WebinarReadQuery, WebinarType},
test_helpers::prelude::*,
};
use chrono::Duration;
use mockall::predicate as pred;
use uuid::Uuid;
#[test]
fn update_serde_test() {
let update = "{}";
let update: ClassUpdate = serde_json::from_str(update).unwrap();
assert!(update.time.is_none());
let update = "{\"reserve\": 10}";
let _update: ClassUpdate = serde_json::from_str(update).unwrap();
}
#[tokio::test]
async fn update_webinar_unauthorized() {
let agent = TestAgent::new("web", "user1", USR_AUDIENCE);
let event_room_id = Uuid::new_v4();
let conference_room_id = Uuid::new_v4();
let state = TestState::new(TestAuthz::new()).await;
let webinar = {
let mut conn = state.get_conn().await.expect("Failed to fetch connection");
factory::Webinar::new(
random_string(),
USR_AUDIENCE.to_string(),
(Bound::Unbounded, Bound::Unbounded).into(),
event_room_id,
conference_room_id,
)
.insert(&mut conn)
.await
};
let state = Arc::new(state);
let body = ClassUpdate {
time: Some((
Bound::Included(Utc::now() + Duration::hours(2)),
Bound::Unbounded,
)),
reserve: None,
host: None,
};
do_update::<WebinarType>(state.as_ref(), agent.account_id(), webinar, body)
.await
.expect_err("Unexpectedly succeeded");
}
#[tokio::test]
async fn update_webinar() {
let agent = TestAgent::new("web", "user1", USR_AUDIENCE);
let event_room_id = Uuid::new_v4();
let conference_room_id = Uuid::new_v4();
let db_pool = TestDb::new().await;
let webinar = {
let mut conn = db_pool.get_conn().await;
factory::Webinar::new(
random_string(),
USR_AUDIENCE.to_string(),
(Bound::Unbounded, Bound::Unbounded).into(),
conference_room_id,
event_room_id,
)
.reserve(20)
.insert(&mut conn)
.await
};
let mut authz = TestAuthz::new();
authz.allow(
agent.account_id(),
vec!["classrooms", &webinar.id().to_string()],
"update",
);
let mut state = TestState::new_with_pool(db_pool, authz);
update_webinar_mocks(&mut state, event_room_id, conference_room_id);
let state = Arc::new(state);
let body = ClassUpdate {
time: Some((
Bound::Included(Utc::now() + Duration::hours(2)),
Bound::Unbounded,
)),
reserve: None,
host: None,
};
let response =
do_update::<WebinarType>(state.as_ref(), agent.account_id(), webinar.clone(), body)
.await
.expect("Failed to update");
let mut conn = state.get_conn().await.expect("Failed to get conn");
let updated_webinar = WebinarReadQuery::by_id(webinar.id())
.execute(&mut conn)
.await
.expect("Failed to fetch webinar")
.expect("Webinar not found");
let time: BoundedDateTimeTuple = updated_webinar.time().to_owned().into();
assert!(matches!(time.0, Bound::Included(_)));
assert_eq!(updated_webinar.reserve(), Some(20));
assert_eq!(response.reserve(), Some(20));
assert_eq!(updated_webinar.time(), response.time());
assert_eq!(updated_webinar.host(), response.host());
}
fn update_webinar_mocks(state: &mut TestState, event_room_id: Uuid, conference_room_id: Uuid) {
state
.event_client_mock()
.expect_update_room()
.with(pred::eq(event_room_id), pred::always())
.returning(move |_room_id, _| Ok(()));
state
.conference_client_mock()
.expect_update_room()
.with(pred::eq(conference_room_id), pred::always())
.returning(move |_room_id, _| Ok(()));
}
}
|
extern crate nom;
use nohash_hasher::IntMap;
use std::fs;
//use std::collections::IntMap;
pub enum Either<L, M, R> {
Left(L),
Middle(M),
Right(R),
}
use nom::{
branch::alt,
character::complete::char,
character::complete::{digit1, space0, anychar},
combinator::map_res,
multi::many0,
sequence::{delimited, separated_pair},
IResult,
};
use std::str::FromStr;
/* Single Rule */
fn factor(i: &str) -> IResult<&str, u16> {
map_res(delimited(space0, digit1, space0), FromStr::from_str)(i)
}
fn term(i: &str) -> IResult<&str, Either<char, Vec<u16>, (Vec<u16>, Vec<u16>)>> {
many0(factor)
(i).map(|(next_input, res)| (next_input, Either::Middle(res)))
}
fn unique_char(i: &str) -> IResult<&str, Either<char, Vec<u16>, (Vec<u16>, Vec<u16>)>> {
delimited(space0, delimited(char('"'), anychar, char('"')), space0)
(i).map(|(next_input, res)| (next_input, Either::Left(res)))
}
fn simple_rule(i: &str) -> IResult<&str, Either<char, Vec<u16>, (Vec<u16>, Vec<u16>)>> {
alt(
(
unique_char,
term
)
)(i)
}
fn complex_rule(i: &str) -> IResult<&str, Either<char, Vec<u16>, (Vec<u16>, Vec<u16>)>> {
separated_pair(term, char('|'), term)
(i)
.map(|(next_input, res)| {
match res {
(Either::Middle(left), Either::Middle(right)) => (next_input, Either::Right((left, right))),
_ => panic!("{}")
}
})
}
fn expr(i: &str) -> IResult<&str, Either<char, Vec<u16>, (Vec<u16>, Vec<u16>)>> {
alt(
(
complex_rule,
simple_rule
)
)(i)
}
fn is_valid<'a>(line: &'a str, idx: &[u16], rules: &IntMap<u16, Either<char, Vec<u16>, (Vec<u16>, Vec<u16>)>>) -> bool {
match idx.len() {
0 => {
return line.len() == 0
},
_ => {
match &rules[&idx[0]] {
Either::Left(car) => {
return match line.len() {
0 => false,
_ => match line.chars().nth(0) {
Some(x) if x == *car => {
is_valid(&line[1..], &idx[1..], rules)
},
_ => false
}
}
},
Either::Right((first, second)) => {
return is_valid(&line, &[&first[..], &idx[1..]].concat(), rules) ||
is_valid(&line, &[&second[..], &idx[1..]].concat(), rules);
},
Either::Middle(mid) => {
return is_valid(&line, &[&mid[..], &idx[1..]].concat(), rules)
}
}
}
}
}
fn main() {
let filename = "/home/remy/AOC/2020/19/input";
let mut rules_map: IntMap<u16, Either<char, Vec<u16>, (Vec<u16>, Vec<u16>)>> = IntMap::default();
let data = fs::read_to_string(filename).unwrap();
for rule in data.lines() {
if rule.is_empty() {
break;
}
let mut tokens = rule.split(":");
let number = &tokens.next().unwrap().parse::<u16>().unwrap();
let rule = &tokens.next().unwrap().trim();
match expr(rule) {
Ok((_, foo)) => {
rules_map.insert(*number, foo);
},
Err(_) => panic!("wat")
}
}
let mut valid: u16 = 0;
for line in data.lines() {
if is_valid(line, &vec![0], &rules_map) {
valid += 1;
}
}
println!("Valids: {}", valid);
}
|
//! Power configuration and management
//!
//! At present this module only contains functions to permit setting the appropriate VCore range
//! for a desired frequency. You should probably not need to use this API yourself, as this is done
//! by the `Rcc::freeze` method.
//!
//! If you _do_ decide to use this directly for some reason, please note that changing the `VCORE`
//! type state of the Power object _does not take effect immediately_. This is due to the fact that
//! we must be able to control the ordering of changing the power level and adjusting the clocks.
//! In order to make the type state change take effect, you must call the `enact` method.
use core::marker::PhantomData;
use crate::common::Constrain;
use crate::rcc;
use crate::stm32l0x1::{pwr, PWR};
use crate::time::Hertz;
mod private {
pub trait Sealed {}
impl Sealed for super::VCoreRange1 {}
impl Sealed for super::VCoreRange2 {}
impl Sealed for super::VCoreRange3 {}
}
// Why do I impl Constrain twice? Good question. The VDD range is physical property, and I can't
// pick the correct value for you. The VCore range and RTC enable state are set at startup time by
// the chip, so I can pick defaults based on that. It's admittedly a bit unergonomic, but you will
// need to specify the type of `T` for constrain:
//
// let pwr: Power<VddHigh, VCoreRange2, RtcDis> = d.PWR.constrain();
//
// The annotation is necessary because the spec for `fn constrain` does not permit us to say:
// ```rust
// impl Constrain<Power<VDD, VCoreRange2, RtcDis>> for PWR {
// fn constrain<VDD>(self) -> Power<VDD, VCoreRange2, RtcDis> { // <-- fn type mis-match
// ```
impl Constrain<Power<VddLow, VCoreRange2, RtcDis>> for PWR {
fn constrain(self) -> Power<VddLow, VCoreRange2, RtcDis> {
Power {
cr: CR(()),
csr: CSR(()),
_vdd: PhantomData,
_vcore: PhantomData,
_rtc: PhantomData,
}
}
}
impl Constrain<Power<VddHigh, VCoreRange2, RtcDis>> for PWR {
fn constrain(self) -> Power<VddHigh, VCoreRange2, RtcDis> {
Power {
cr: CR(()),
csr: CSR(()),
_vdd: PhantomData,
_vcore: PhantomData,
_rtc: PhantomData,
}
}
}
/// The constrained Power peripheral
pub struct Power<VDD, VCORE, RTC> {
/// Power control register
cr: CR,
/// Power control status register
csr: CSR,
#[doc(hidden)]
/// MCU VDD voltage range. This is external to the chip.
_vdd: PhantomData<VDD>,
#[doc(hidden)]
/// MCU VCore voltage range. This is configurable.
_vcore: PhantomData<VCORE>,
#[doc(hidden)]
/// RTC enable/disable state
_rtc: PhantomData<RTC>,
}
/// Power control register
pub struct CR(());
impl CR {
/// Direct access to PWR_CR
#[inline]
pub fn inner(&self) -> &pwr::CR {
unsafe { &(*PWR::ptr()).cr }
}
}
/// Power control/status register
pub struct CSR(());
impl CSR {
/// Direct access to PWR_CR
#[inline]
pub fn inner(&self) -> &pwr::CSR {
unsafe { &(*PWR::ptr()).csr }
}
}
/// 1.71 V - 3.6 V
pub struct VddHigh(());
/// 1.65 V - 3.6 V
pub struct VddLow(());
#[derive(PartialOrd, PartialEq)]
/// Available VCore Ranges
pub enum VCoreRange {
/// ~1.2V
Range3,
/// ~1.5V
Range2,
/// 1.8V
Range1,
}
impl VCoreRange {
#[doc(hidden)]
/// Helper method for configuration bits
pub fn bits(&self) -> u8 {
match self {
VCoreRange::Range1 => 0b01,
VCoreRange::Range2 => 0b10,
VCoreRange::Range3 => 0b11,
}
}
}
#[doc(hidden)]
/// Helper trait to turn VOS bits into a usable VCoreRange
pub trait Vos: private::Sealed {
/// Get the range based on the type
fn range() -> VCoreRange;
}
#[doc(hidden)]
/// Helper trait to correlate vcore ranges with maximum frequencies
pub trait FreqLimit: private::Sealed {
fn max_freq() -> Hertz;
}
/// Range 1 is the "high performance" range. VCore = 1.8V
pub struct VCoreRange1(());
impl Vos for VCoreRange1 {
fn range() -> VCoreRange {
VCoreRange::Range1
}
}
impl FreqLimit for VCoreRange1 {
fn max_freq() -> Hertz {
Hertz(32_000_000)
}
}
/// Range 2 is the "medium performance" range. VCore = 1.5V
pub struct VCoreRange2(());
impl Vos for VCoreRange2 {
fn range() -> VCoreRange {
VCoreRange::Range2
}
}
impl FreqLimit for VCoreRange2 {
fn max_freq() -> Hertz {
Hertz(16_000_000)
}
}
/// Range 3 is the "low power" range. VCore = 1.2V
pub struct VCoreRange3(());
impl Vos for VCoreRange3 {
fn range() -> VCoreRange {
VCoreRange::Range3
}
}
impl FreqLimit for VCoreRange3 {
fn max_freq() -> Hertz {
Hertz(4_200_000)
}
}
// Here, we only permit calling into_vdd_range when the VCore range is range 2 or range 3. This is
// because, if the range is 1, the vdd range _must_ be High. The type system prevents us from
// constructing a Power<VddLow, VCoreRange1, RTC>.
impl<VDD, RTC> Power<VDD, VCoreRange2, RTC> {
/// Change the VDD range (logically - not physically)
pub fn into_vdd_range<NEWVDD>(self) -> Power<VDD, VCoreRange2, RTC> {
Power {
cr: self.cr,
csr: self.csr,
_vdd: PhantomData,
_vcore: PhantomData,
_rtc: PhantomData,
}
}
}
impl<VDD, RTC> Power<VDD, VCoreRange3, RTC> {
/// Change the VDD range (logically - not physically)
pub fn into_vdd_range<NEWVDD>(self) -> Power<VDD, VCoreRange3, RTC> {
Power {
cr: self.cr,
csr: self.csr,
_vdd: PhantomData,
_vcore: PhantomData,
_rtc: PhantomData,
}
}
}
impl<VCORE, RTC> Power<VddHigh, VCORE, RTC> {
/// Change the power peripheral's VCoreRange type state.
///
/// This does not take effect until `enact()` is called
pub fn into_vcore_range<NEWRANGE>(self) -> Power<VddHigh, NEWRANGE, RTC>
where
NEWRANGE: Vos,
{
Power {
cr: self.cr,
csr: self.csr,
_vdd: PhantomData,
_vcore: PhantomData,
_rtc: PhantomData,
}
}
}
impl<RTC> Power<VddLow, VCoreRange2, RTC> {
/// Change the power peripheral's VCoreRange type state.
///
/// This does not take effect until `enact()` is called
pub fn into_vcore_range(self) -> Power<VddLow, VCoreRange3, RTC> {
Power {
cr: self.cr,
csr: self.csr,
_vdd: PhantomData,
_vcore: PhantomData,
_rtc: PhantomData,
}
}
}
impl<RTC> Power<VddLow, VCoreRange3, RTC> {
/// Change the power peripheral's VCoreRange type state.
///
/// This does not take effect until `enact()` is called
pub fn into_vcore_range(self) -> Power<VddLow, VCoreRange2, RTC> {
Power {
cr: self.cr,
csr: self.csr,
_vdd: PhantomData,
_vcore: PhantomData,
_rtc: PhantomData,
}
}
}
impl<VDD, VCORE, RTC> Power<VDD, VCORE, RTC>
where
VCORE: Vos,
{
/// Enable the POWER clock while the closure is executed
///
/// The PWREN bit must be set while changing the configuration of the power peripheral. This
/// provides a context within which this is true.
fn while_clk_en<F>(apb1: &mut rcc::APB1, mut op: F)
where
F: FnMut(),
{
// Enable configuration of the PWR peripheral
apb1.enr().modify(|_, w| w.pwren().set_bit());
while !apb1.enr().read().pwren().bit_is_set() {}
op();
apb1.enr().modify(|_, w| w.pwren().clear_bit());
while apb1.enr().read().pwren().bit_is_set() {}
}
/// Provide a context for changing LSE and RTC settings.
///
/// 7.3.20: Note: The LSEON, LSEBYP, RTCSEL, LSEDRV and RTCEN bits in the RCC control and
/// status register (RCC_CSR) are in the RTC domain. As these bits are write protected after
/// reset, the DBP bit in the Power control register (PWR_CR) has to be set to be able to
/// modify them. Refer to Section 6.1.2: RTC and RTC backup registers for further
/// information.
pub fn dbp_context<F>(&mut self, mut op: F)
where
F: FnMut(),
{
self.cr.inner().modify(|_, w| w.dbp().set_bit());
while self.cr.inner().read().dbp().bit_is_clear() {}
op();
self.cr.inner().modify(|_, w| w.dbp().clear_bit());
while self.cr.inner().read().dbp().bit_is_set() {}
}
/// Enact the current Power type states
///
/// This function is unsafe because it does not validate the requested setting against the
/// currently configured clock. `Rcc::freeze` takes care of this for you.
pub unsafe fn enact(&mut self, apb1: &mut rcc::APB1) {
Power::<VDD, VCORE, RTC>::while_clk_en(apb1, || {
self.cr
.inner()
.modify(|_, w| w.vos().bits(VCORE::range().bits()));
// 4. Poll VOSF bit of in PWR_CSR register. Wait until it is reset to 0.
while self.csr.inner().read().vosf().bit_is_set() {}
});
}
/// Read the current VCoreRange value from the register
pub fn read_vcore_range(&self) -> VCoreRange {
match self.cr.inner().read().vos().bits() {
0b01 => VCoreRange::Range1,
0b10 => VCoreRange::Range2,
0b11 => VCoreRange::Range3,
_ => unreachable!(),
}
}
}
/// RTC enabled (type state)
pub struct RtcEn(());
/// RTC disabled (type state)
pub struct RtcDis(());
impl<VDD, VCORE> Power<VDD, VCORE, RtcEn>
where
VCORE: Vos,
{
/// Disable the RTC, changing the type state of self
pub fn disable_rtc(self, apb1: &mut rcc::APB1) -> Power<VDD, VCORE, RtcDis> {
// (Disable the power interface clock)
apb1.enr().modify(|_, w| w.pwren().clear_bit());
while apb1.enr().read().pwren().bit_is_set() {}
self.cr.inner().modify(|_, w| w.dbp().clear_bit());
Power {
cr: self.cr,
csr: self.csr,
_vdd: PhantomData,
_vcore: PhantomData,
_rtc: PhantomData,
}
}
}
impl<VDD, VCORE> Power<VDD, VCORE, RtcDis>
where
VCORE: Vos,
{
/// Enable the RTC, changing the type state of self
pub fn enable_rtc(
mut self,
cr: &mut rcc::CR,
apb1: &mut rcc::APB1,
) -> Power<VDD, VCORE, RtcEn> {
// From 6.4.1 bit 8 DBP:
// Note: If the HSE divided by 2, 4, 8 or 16 is used as the RTC clock, this bit must
// remain set to 1.
if cr.inner().read().rtcpre().bits() == 0 {
self.cr.inner().modify(|_, w| w.dbp().clear_bit());
} else {
self.cr.inner().modify(|_, w| w.dbp().set_bit());
}
// From 6.1.2 RTC registers access
// 1. Enable the power interface clock by setting the PWREN bits in the RCC_APB1ENR register.
apb1.enr().modify(|_, w| w.pwren().set_bit());
while !apb1.enr().read().pwren().bit_is_set() {}
// 2. Set the DBP bit in the PWR_CR register (see Section 6.4.1).
// (note: or any other thing)
self.dbp_context(|| {
// 3. Select the RTC clock source through RTCSEL[1:0] bits in RCC_CSR register.
// 4. Enable the RTC clock by programming the RTCEN bit in the RCC_CSR register.
});
Power {
cr: self.cr,
csr: self.csr,
_vdd: PhantomData,
_vcore: PhantomData,
_rtc: PhantomData,
}
}
}
|
use std::error::Error;
use modify::Modify;
mod modify;
mod kvdb;
pub mod inner;
mod allocator;
#[macro_use]
mod cache;
mod crc64;
mod mmap;
mod cmd;
/// Storage represents the internal-facing server part of TinyKV, it handles sending and receiving from other
/// TinyKV nodes. As part of that responsibility, it also reads and writes data to disk (or semi-permanent memory).
trait Storage {
fn start(&self) -> Result<(), Box<dyn Error>>;
fn stop(&self) -> Result<(), Box<dyn Error>>;
fn write(&self, batch: Vec<Modify>) -> Result<(), Box<dyn Error>>;
fn reader(&self) -> Result<Box<dyn StorageReader>, Box<dyn Error>>;
}
trait StorageReader {
fn get_cf(&self, cf: String, key: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>>;
fn iter_cf(&self, cf: String) -> dyn Iterator<Item=dyn DBItem>;
fn close(&self);
}
trait DBItem {
/// Key returns the key.
fn key(&self) -> Vec<u8>;
/// KeyCopy returns a copy of the key of the item, writing it to dst slice.
/// If nil is passed, or capacity of dst isn't sufficient, a new slice would be allocated and
/// returned.
fn key_copy(&self, dst: Vec<u8>) -> Vec<u8>;
/// Value retrieves the value of the item.
fn value(&self) -> Result<Vec<u8>, Box<dyn Error>>;
/// ValueSize returns the size of the value.
fn value_size(&self) -> i32;
/// ValueCopy returns a copy of the value of the item from the value log, writing it to dst slice.
/// If nil is passed, or capacity of dst isn't sufficient, a new slice would be allocated and
/// returned.
fn value_copy(&self, dst: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>>;
}
#[cfg(test)]
mod tests {
use crate::kv::storage::cache::cache_s;
use crate::kv::storage::inner::Node;
#[test]
fn is_it_work() {
assert_eq!(1 + 2, 3);
}
#[test]
fn test_cache_s_new() {
let cache = cache_s::new();
for (i, emem) in cache.hash.iter().enumerate() {
println!("cache.hash {}:{:?}", i, emem);
}
}
}
|
// Copyright (c) The diem-x Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
use structopt::StructOpt;
use testrunner::dispatch::Opts;
fn main() -> anyhow::Result<()> {
let opts = Opts::from_args();
opts.exec()
}
|
use clap::{App, AppSettings, Arg, };
use zmq::{Context, Socket};
use crate::socket::{SocketParameters, create_socket};
use std::error::Error;
pub struct Chat {
#[allow(dead_code)]
ctx: Context,
socket: Socket
}
impl Chat {
pub fn new(parameters: &SocketParameters) -> Result<Self, Box<dyn Error>> {
let ctx = zmq::Context::new();
let socket = create_socket(&ctx, ¶meters)?;
socket.set_rcvtimeo(100)?;
Ok(Self { ctx, socket })
}
pub fn send(&self, message: &str) -> Result<(), Box<dyn Error>> {
self.socket.send(message, 0)?;
Ok(())
}
pub fn send_with_id(&self, id: &str, message: &str) -> Result<(), Box<dyn Error>> {
self.socket.send_multipart(&[id, message], 0)?;
Ok(())
}
pub fn receive(&self) -> Result<Vec<String>, Box<dyn Error>> {
let message = self.socket.recv_multipart(0)?;
let result = message
.iter()
.map(|part | {
String::from_utf8(part.to_vec())
}).collect::<Result<Vec<_>, _>>()?;
Ok(result)
}
}
pub fn chat(parameters: SocketParameters) -> Result<(), Box<dyn Error>> {
println!("Chat {:?}", parameters.address);
let mut chat = Chat::new(¶meters)?;
let mut rl = rustyline::Editor::<()>::new();
let _ = rl.load_history("history.txt");
loop {
let readline = rl.readline(">> ");
match readline {
Ok(line) => {
rl.add_history_entry(line.as_str());
execute_chat_command(&mut chat, parse_chat_command(line));
},
Err(rustyline::error::ReadlineError::Interrupted) | Err(rustyline::error::ReadlineError::Eof) => {
break
},
Err(err) => {
println!("Error: {:?}", err);
break
}
}
}
rl.save_history("history.txt")?;
Ok(())
}
#[derive(Debug, PartialEq)]
enum ChatCommand {
Receive,
Send(String),
SendTo(String, String)
}
fn tokenize(input: &str) -> Vec<String> {
let mut r = Vec::<String>::new();
for c in regex::Regex::new("['\"](.+)['\"]|([^\\s\"']\\S*[^\\s\"'])")
.unwrap()
.captures_iter(input) {
if let Some(m) = c.get(1) {
r.push(m.as_str().to_string());
} else if let Some(m) = c.get(2) {
r.push(m.as_str().to_string());
}
}
r
}
fn parse_chat_command(input: String) -> ChatCommand {
let matches = App::new("chat")
.setting(AppSettings::NoBinaryName)
.setting(AppSettings::InferSubcommands)
.arg(Arg::with_name("receive").long("receive").short("r").takes_value(false))
.arg(Arg::with_name("send").long("send").short("s").takes_value(true).conflicts_with("receive"))
.arg(Arg::with_name("receiver id").long("id").takes_value(true).conflicts_with("receive"))
.get_matches_from_safe(tokenize(input.as_str()).into_iter());
if let Ok(m) = matches {
if m.is_present("receive") {
return ChatCommand::Receive;
} else if m.is_present("send") {
if m.is_present("receiver id") {
return ChatCommand::SendTo(m.value_of("receiver id").unwrap().to_string(),
m.values_of("send").unwrap().map(str::to_string).collect());
}
return ChatCommand::Send(m.values_of("send").unwrap().map(str::to_string).collect());
}
}
if input.is_empty() {
return ChatCommand::Receive;
}
ChatCommand::Send(input)
}
fn execute_chat_command(chat: &mut Chat, command: ChatCommand) {
match command {
ChatCommand::Receive => {
if let Ok(message) = chat.receive() {
println!("received: {:?}", message);
}
},
ChatCommand::Send(message) => {
match chat.send(&message) {
Ok(_) => println!("sent: {}", message),
Err(err) => println!("error: {}", err)
}
},
ChatCommand::SendTo(id, message) => {
match chat.send_with_id(&id, &message) {
Ok(_) => println!("sent: {}", message),
Err(err) => println!("error: {}", err)
}
},
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn tokenizing() {
assert_eq!(vec!["word", "word2"], tokenize("word word2"));
assert_eq!(vec!["two words"], tokenize("\"two words\""));
assert_eq!(vec!["word", "two words"], tokenize("word \"two words\""));
assert_eq!(vec!["word", "two words"], tokenize("word 'two words'"));
}
#[test]
fn chat_command_parsing() {
assert_eq!(ChatCommand::Receive, parse_chat_command("".to_string()));
assert_eq!(ChatCommand::Receive, parse_chat_command("--receive".to_string()));
assert_eq!(ChatCommand::Receive, parse_chat_command("-r".to_string()));
assert_eq!(ChatCommand::Send(String::from("message")), parse_chat_command("--send message".to_string()));
assert_eq!(ChatCommand::Send(String::from("message")), parse_chat_command("-s message".to_string()));
assert_eq!(ChatCommand::Send(String::from("message")), parse_chat_command("-s message".to_string()));
assert_eq!(ChatCommand::Send(String::from("message")), parse_chat_command("message".to_string()));
assert_eq!(ChatCommand::Send(String::from("multiple words")), parse_chat_command("multiple words".to_string()));
assert_eq!(ChatCommand::Send(String::from("multiple words")), parse_chat_command("-s 'multiple words'".to_string()));
assert_eq!(ChatCommand::SendTo(String::from("ID1"), String::from("message")), parse_chat_command("--id ID1 -s message".to_string()));
assert_eq!(ChatCommand::Send(String::from("Hi again")), parse_chat_command("--send \"Hi again\"".to_string()));
}
}
|
#[doc = "Register `RXF0S` reader"]
pub type R = crate::R<RXF0S_SPEC>;
#[doc = "Register `RXF0S` writer"]
pub type W = crate::W<RXF0S_SPEC>;
#[doc = "Field `F0FL` reader - Rx FIFO 0 Fill Level"]
pub type F0FL_R = crate::FieldReader;
#[doc = "Field `F0FL` writer - Rx FIFO 0 Fill Level"]
pub type F0FL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 7, O>;
#[doc = "Field `F0GI` reader - Rx FIFO 0 Get Index"]
pub type F0GI_R = crate::FieldReader;
#[doc = "Field `F0GI` writer - Rx FIFO 0 Get Index"]
pub type F0GI_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 6, O>;
#[doc = "Field `F0PI` reader - Rx FIFO 0 Put Index"]
pub type F0PI_R = crate::FieldReader;
#[doc = "Field `F0PI` writer - Rx FIFO 0 Put Index"]
pub type F0PI_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 6, O>;
#[doc = "Field `F0F` reader - Rx FIFO 0 Full"]
pub type F0F_R = crate::BitReader;
#[doc = "Field `F0F` writer - Rx FIFO 0 Full"]
pub type F0F_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RF0L` reader - Rx FIFO 0 Message Lost"]
pub type RF0L_R = crate::BitReader;
#[doc = "Field `RF0L` writer - Rx FIFO 0 Message Lost"]
pub type RF0L_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bits 0:6 - Rx FIFO 0 Fill Level"]
#[inline(always)]
pub fn f0fl(&self) -> F0FL_R {
F0FL_R::new((self.bits & 0x7f) as u8)
}
#[doc = "Bits 8:13 - Rx FIFO 0 Get Index"]
#[inline(always)]
pub fn f0gi(&self) -> F0GI_R {
F0GI_R::new(((self.bits >> 8) & 0x3f) as u8)
}
#[doc = "Bits 16:21 - Rx FIFO 0 Put Index"]
#[inline(always)]
pub fn f0pi(&self) -> F0PI_R {
F0PI_R::new(((self.bits >> 16) & 0x3f) as u8)
}
#[doc = "Bit 24 - Rx FIFO 0 Full"]
#[inline(always)]
pub fn f0f(&self) -> F0F_R {
F0F_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - Rx FIFO 0 Message Lost"]
#[inline(always)]
pub fn rf0l(&self) -> RF0L_R {
RF0L_R::new(((self.bits >> 25) & 1) != 0)
}
}
impl W {
#[doc = "Bits 0:6 - Rx FIFO 0 Fill Level"]
#[inline(always)]
#[must_use]
pub fn f0fl(&mut self) -> F0FL_W<RXF0S_SPEC, 0> {
F0FL_W::new(self)
}
#[doc = "Bits 8:13 - Rx FIFO 0 Get Index"]
#[inline(always)]
#[must_use]
pub fn f0gi(&mut self) -> F0GI_W<RXF0S_SPEC, 8> {
F0GI_W::new(self)
}
#[doc = "Bits 16:21 - Rx FIFO 0 Put Index"]
#[inline(always)]
#[must_use]
pub fn f0pi(&mut self) -> F0PI_W<RXF0S_SPEC, 16> {
F0PI_W::new(self)
}
#[doc = "Bit 24 - Rx FIFO 0 Full"]
#[inline(always)]
#[must_use]
pub fn f0f(&mut self) -> F0F_W<RXF0S_SPEC, 24> {
F0F_W::new(self)
}
#[doc = "Bit 25 - Rx FIFO 0 Message Lost"]
#[inline(always)]
#[must_use]
pub fn rf0l(&mut self) -> RF0L_W<RXF0S_SPEC, 25> {
RF0L_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 = "FDCAN Rx FIFO 0 Status Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rxf0s::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 [`rxf0s::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct RXF0S_SPEC;
impl crate::RegisterSpec for RXF0S_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`rxf0s::R`](R) reader structure"]
impl crate::Readable for RXF0S_SPEC {}
#[doc = "`write(|w| ..)` method takes [`rxf0s::W`](W) writer structure"]
impl crate::Writable for RXF0S_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets RXF0S to value 0"]
impl crate::Resettable for RXF0S_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::{
env, fmt, fs,
io::{self, Write},
process,
};
use stacc::{interpreter::Interpreter, parser::Parser};
fn unwrap<T, E: fmt::Display + fmt::Debug>(result: Result<T, E>) -> T {
if let Err(err) = result {
eprintln!("{}", err);
process::exit(1);
}
result.unwrap()
}
fn main() {
let filename = env::args().nth(1);
if filename.is_none() {
repl();
process::exit(1);
}
let filename = filename.unwrap();
let contents = unwrap(fs::read_to_string(filename));
let stmts = unwrap(Parser::new(&contents).parse());
let mut interpreter = Interpreter::new();
unwrap(interpreter.run(&stmts))
}
fn repl() {
let mut interpreter = Interpreter::new();
loop {
print!("> ");
io::stdout().flush().unwrap();
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
input.push('\n');
let stmt = Parser::new(&input).parse_stmt();
match stmt {
Ok(stmt) => match interpreter.run_one(&stmt) {
Ok(_) => interpreter.print_state(),
Err(err) => eprintln!("{}", err),
},
Err(err) => eprintln!("{}", err),
}
}
}
|
#[derive(juniper::GraphQLObject, Clone, Serialize, Deserialize)]
pub struct Drive {
pub id: i32,
pub location: Option<String>,
}
|
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct NotARange;
impl NotARange {
fn step_by(&self, _: u32) {}
}
#[warn(clippy::iterator_step_by_zero, clippy::range_zip_with_len)]
fn main() {
let _ = (0..1).step_by(0);
// No warning for non-zero step
let _ = (0..1).step_by(1);
let _ = (1..).step_by(0);
let _ = (1..=2).step_by(0);
let x = 0..1;
let _ = x.step_by(0);
// No error, not a range.
let y = NotARange;
y.step_by(0);
let v1 = vec![1, 2, 3];
let v2 = vec![4, 5];
let _x = v1.iter().zip(0..v1.len());
let _y = v1.iter().zip(0..v2.len()); // No error
// check const eval
let _ = v1.iter().step_by(2 / 3);
}
#[allow(unused)]
fn no_panic_with_fake_range_types() {
struct Range {
foo: i32,
}
let _ = Range { foo: 0 };
}
|
use std::thread;
use std::fs;
use std::sync::mpsc;
struct Filenames {
source: String,
destination: String,
}
impl Drop for Filenames {
fn drop(&mut self) {
if thread::panicking() {
println!("dropped due to panic");
} else {
println!("dropped without panic");
}
}
}
fn main() {
// thread1();
// thread2();
// thread3();
// thread4();
thread5();
}
fn thread1() {
for _ in 1..5 {
thread::spawn(|| {
println!("Hi from thread id {:?}",
thread::current().id());
});
}
}
fn thread2() {
let mut child_threads = Vec::new();
for i in 1..5 {
let builder = thread::Builder::new().name(format!("mythread{}", i));
let handle = builder.spawn(|| {
println!(" Hi from thread is {:?}",
thread::current().id());
}).unwrap();
child_threads.push(handle);
}
for i in child_threads {
i.join().unwrap();
}
}
fn copy_file() -> thread::Result<()> {
thread::spawn(|| {
fs::copy("a.txt", "b.txt").expect("Error occured");
}).join()
}
fn copy_file2(file_struct: Filenames) -> thread::Result<()> {
thread::spawn(move || {
fs::copy(&file_struct.source, &file_struct.destination)
.expect("Error occurred");
}).join()
}
fn thread3() {
match copy_file() {
Ok(_) => println!("Ok. copied"),
Err(_) => println!("Error in copying file"),
}
}
fn thread4() {
let foo = Filenames {
source: "a1.txt".into(),
destination: "b.txt".into(),
};
match copy_file2(foo) {
Ok(_) => println!("Copied"),
Err(_) => println!("Error in copying file"),
}
}
fn thread5() {
let (transmitter1, receiver) = mpsc::channel();
let transmitter2 = mpsc::Sender::clone(&transmitter1);
thread::spawn(move || {
let num_vec: Vec<String> = vec!["one".into(), "two".into(),
"three".into(), "four".into()];
for num in num_vec {
transmitter1.send(num).unwrap();
}
});
thread::spawn(move || {
let num_vec: Vec<String> = vec!["Five".into(), "Six".into(),
"Seven".into(), "eight".into()];
for num in num_vec {
transmitter2.send(num).unwrap();
}
});
for received_val in receiver {
println!("Recieved from thread: {}", received_val);
}
} |
use chrono::Utc;
use proptest::prelude::*;
use taskwarrior_rust::{taskstorage, Operation, Server, DB};
use uuid::Uuid;
fn newdb() -> DB {
DB::new(Box::new(taskstorage::InMemoryStorage::new()))
}
#[derive(Debug)]
enum Action {
Op(Operation),
Sync,
}
fn action_sequence_strategy() -> impl Strategy<Value = Vec<(Action, u8)>> {
// Create, Update, Delete, or Sync on client 1, 2, .., followed by a round of syncs
"([CUDS][123])*S1S2S3S1S2".prop_map(|seq| {
let uuid = Uuid::parse_str("83a2f9ef-f455-4195-b92e-a54c161eebfc").unwrap();
seq.as_bytes()
.chunks(2)
.map(|action_on| {
let action = match action_on[0] {
b'C' => Action::Op(Operation::Create { uuid }),
b'U' => Action::Op(Operation::Update {
uuid,
property: "title".into(),
value: Some("foo".into()),
timestamp: Utc::now(),
}),
b'D' => Action::Op(Operation::Delete { uuid }),
b'S' => Action::Sync,
_ => unreachable!(),
};
let acton = action_on[1] - b'1';
(action, acton)
})
.collect::<Vec<(Action, u8)>>()
})
}
proptest! {
#[test]
// check that various sequences of operations on mulitple db's do not get the db's into an
// incompatible state. The main concern here is that there might be a sequence of create
// and delete operations that results in a task existing in one DB but not existing in
// another. So, the generated sequences focus on a single task UUID.
fn transform_sequences_of_operations(action_sequence in action_sequence_strategy()) {
let mut server = Server::new();
let mut dbs = [newdb(), newdb(), newdb()];
for (action, db) in action_sequence {
println!("{:?} on db {}", action, db);
let db = &mut dbs[db as usize];
match action {
Action::Op(op) => {
if let Err(e) = db.apply(op) {
println!(" {:?} (ignored)", e);
}
},
Action::Sync => db.sync("me", &mut server).unwrap(),
}
}
assert_eq!(dbs[0].sorted_tasks(), dbs[0].sorted_tasks());
assert_eq!(dbs[1].sorted_tasks(), dbs[2].sorted_tasks());
}
}
|
// libmain.rs
// loads a module from a compiled library as an extern mod
// compile using "rustc libmain.rs -L ./libmodules/"
extern mod libworld;
fn main() {
use libworld::libearth::libexplore;
use libtrek = libworld::libearth::libexplore;
io::println(~"hello " + libexplore());
io::println(~"hello " + libtrek());
io::println(~"hello " + libworld::libearth::libexplore());
}
|
#[doc = "Register `PCTLR` reader"]
pub type R = crate::R<PCTLR_SPEC>;
#[doc = "Register `PCTLR` writer"]
pub type W = crate::W<PCTLR_SPEC>;
#[doc = "Field `DEN` reader - Digital Enable"]
pub type DEN_R = crate::BitReader;
#[doc = "Field `DEN` writer - Digital Enable"]
pub type DEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CKE` reader - Clock Enable"]
pub type CKE_R = crate::BitReader;
#[doc = "Field `CKE` writer - Clock Enable"]
pub type CKE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 1 - Digital Enable"]
#[inline(always)]
pub fn den(&self) -> DEN_R {
DEN_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Clock Enable"]
#[inline(always)]
pub fn cke(&self) -> CKE_R {
CKE_R::new(((self.bits >> 2) & 1) != 0)
}
}
impl W {
#[doc = "Bit 1 - Digital Enable"]
#[inline(always)]
#[must_use]
pub fn den(&mut self) -> DEN_W<PCTLR_SPEC, 1> {
DEN_W::new(self)
}
#[doc = "Bit 2 - Clock Enable"]
#[inline(always)]
#[must_use]
pub fn cke(&mut self) -> CKE_W<PCTLR_SPEC, 2> {
CKE_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 = "DSI Host PHY Control Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pctlr::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 [`pctlr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct PCTLR_SPEC;
impl crate::RegisterSpec for PCTLR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`pctlr::R`](R) reader structure"]
impl crate::Readable for PCTLR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`pctlr::W`](W) writer structure"]
impl crate::Writable for PCTLR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets PCTLR to value 0"]
impl crate::Resettable for PCTLR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
fn main() {
// declaring some variables
let hello: i32 = 10;
let mut goodbye = 11;
println!("goodbye is now: {}", goodbye);
// hello = 12;
// goodbye = "its now a string!"
goodbye = 44;
println!("goodbye is now: {}", goodbye);
let v = vec![1, 2, 3, 4, 5];
//v.push(4);
println!("v[3]: {}", v[3]);
let mut v2 = Vec::new();
for n in 1..11 {
v2.push(n);
}
for i in v2.iter() {
match i {
1 => println!("One is the loneliest number"),
2 | 3 | 5 => println!("Two Three Five!"),
6 | 7 => println!("Fallout: 67"),
9 => println!("What is 9*9??"),
10 => println!("Ten"),
_ => println!("4 & 8 didnt get any matches :(")
}
}
}
|
extern crate image;
extern crate rand;
use rand::Rng;
use std::fs::File;
struct Point{
x: u32,
y: u32,
}
const WIDTH: u32 = 800;
const HEIGHT: u32 =600;
fn main() {
let mut img =image::ImageBuffer::from_fn(WIDTH,HEIGHT,|x,y|{
if x==0 && y==0{
image::Luma([0u8])
}else{
image::Luma([255u8])
}
});
let ref mut before=File::create("before.png").unwrap();
let _ = image::ImageLuma8(img.clone()).save(before,image::PNG);
let mut cnt: u32=1_000_000;
let pts: [Point; 3]=[
Point {x: WIDTH/2,y: 0},
Point {x: 0, y: HEIGHT},
Point {x: WIDTH, y: HEIGHT},
];
let mut p=Point{x: rand::thread_rng().gen_range(0, WIDTH),
y: rand::thread_rng().gen_range(0,HEIGHT),
};
let pixel=img[(0,0)];
while cnt>0{
cnt=cnt-1;
let num = rand::thread_rng().gen_range(0,3);
p.x=(p.x+pts[num].x)/2;
p.y=(p.y+pts[num].y)/2;
img.put_pixel(p.x, p.y, pixel);
}
let ref mut fout=File::create("tri.png").unwrap();
let _ = image::ImageLuma8(img).save(fout,image::PNG);
}
|
#[doc = "Reader of register IIDR"]
pub type R = crate::R<u32, super::IIDR>;
#[doc = "Reader of field `IIDR`"]
pub type IIDR_R = crate::R<u32, u32>;
impl R {
#[doc = "Bits 0:31 - IIDR"]
#[inline(always)]
pub fn iidr(&self) -> IIDR_R {
IIDR_R::new((self.bits & 0xffff_ffff) as u32)
}
}
|
//
// Win module
//
mod win_push_button; |
use std::{
collections::{HashSet, VecDeque},
env::args,
};
mod http;
mod login;
mod parse;
use crate::{
http::HttpClient,
login::login,
parse::{body, code, get_header, internal_url, scrape, DropUntilFirstOccurrence},
};
const BASE_URL: &str = "https://fakebook.3700.network/fakebook/";
const LOGIN_URL: &str = "https://fakebook.3700.network/accounts/login/?next=/fakebook/";
const DEBUG: bool = false;
fn main() {
// collect the arguments
let args: Vec<String> = args().collect();
assert_eq!(args.len(), 3);
let username = &args[1];
let password = &args[2];
if DEBUG {
println!("Username: {:?}, Password: {:?}", username, password);
}
let mut client = HttpClient::new(LOGIN_URL);
let mut visited_links: HashSet<String> = HashSet::new();
let mut collected_flags: u8 = 0;
let mut link_queue: VecDeque<String> = VecDeque::new();
// login to the server
let login_res = login(LOGIN_URL, &username, &password, &mut client).unwrap();
assert_eq!(code(&login_res).0, 302);
link_queue.push_front(BASE_URL.to_owned());
// begin the process of web scraping
while let Some(cur) = link_queue.pop_front() {
if collected_flags >= 5 {
break;
}
if !visited_links.insert(cur.clone()) {
continue;
}
// Get the webpage, skipping this site if the request errors
let res = match client.get(cur.as_str(), None) {
Ok(r) => r,
Err(x) => {
if DEBUG {
println!("Error on get: {}", x);
}
client.reconnect();
link_queue.push_front(cur);
continue;
}
};
// Confirm valid response, if not try the next link
let (res_code, _) = code(&res);
match res_code {
300..=399 => {
if let Some(hdr) = get_header(&res, "Location").into_iter().next() {
if let Some(url) = internal_url(&cur, &hdr.drop_to_fst_occ(" ")).unwrap_or(None)
{
link_queue.push_front(url);
}
}
}
500..=599 => {
link_queue.push_back(cur.clone());
visited_links.remove(&cur);
}
_ => (),
};
match res_code {
100..=299 => (),
_ => continue,
};
// Scrape the page and add the valid links and keys
let html = body(&res);
let (links, flags) = scrape(html);
for flag in flags {
collected_flags += 1;
println!("{}", flag);
}
link_queue.extend(
links
.into_iter()
.filter_map(|href| internal_url(&cur, &href).unwrap_or(None)),
);
}
if DEBUG {
println!("Done! Visited {} links\nFLAGS:", visited_links.len(),);
}
}
|
#![allow(unused)]
// Custom KORG nanoKONTROL2 setup.
// [16, 24) = knobs
// [24, 32) = sliders
// [70, 78) = S buttons
// [78, 86) = M buttons
// [86, 94) = R buttons
// 102, 103 = track left/right
// 104, 105, 106 = marker set, left, right
// 107 = cycle
// [108, 113) = prev, next, stop, play, record
pub const KORG_KNOB1: usize = 0 + 16;
pub const KORG_KNOB2: usize = 1 + 16;
pub const KORG_KNOB3: usize = 2 + 16;
pub const KORG_KNOB4: usize = 3 + 16;
pub const KORG_KNOB5: usize = 4 + 16;
pub const KORG_KNOB6: usize = 5 + 16;
pub const KORG_KNOB7: usize = 6 + 16;
pub const KORG_KNOB8: usize = 7 + 16;
pub const KORG_SLIDER1: usize = 0 + 24;
pub const KORG_SLIDER2: usize = 1 + 24;
pub const KORG_SLIDER3: usize = 2 + 24;
pub const KORG_SLIDER4: usize = 3 + 24;
pub const KORG_SLIDER5: usize = 4 + 24;
pub const KORG_SLIDER6: usize = 5 + 24;
pub const KORG_SLIDER7: usize = 6 + 24;
pub const KORG_SLIDER8: usize = 7 + 24;
pub const KORG_S1: usize = 0 + 70;
pub const KORG_S2: usize = 1 + 70;
pub const KORG_S3: usize = 2 + 70;
pub const KORG_S4: usize = 3 + 70;
pub const KORG_S5: usize = 4 + 70;
pub const KORG_S6: usize = 5 + 70;
pub const KORG_S7: usize = 6 + 70;
pub const KORG_S8: usize = 7 + 70;
pub const KORG_M1: usize = 0 + 78;
pub const KORG_M2: usize = 1 + 78;
pub const KORG_M3: usize = 2 + 78;
pub const KORG_M4: usize = 3 + 78;
pub const KORG_M5: usize = 4 + 78;
pub const KORG_M6: usize = 5 + 78;
pub const KORG_M7: usize = 6 + 78;
pub const KORG_M8: usize = 7 + 78;
pub const KORG_R1: usize = 0 + 86;
pub const KORG_R2: usize = 1 + 86;
pub const KORG_R3: usize = 2 + 86;
pub const KORG_R4: usize = 3 + 86;
pub const KORG_R5: usize = 4 + 86;
pub const KORG_R6: usize = 5 + 86;
pub const KORG_R7: usize = 6 + 86;
pub const KORG_R8: usize = 7 + 86;
pub const KORG_TRACK_LEFT: usize = 102;
pub const KORG_TRACK_RIGHT: usize = 103;
pub const KORG_MARKER_SET: usize = 104;
pub const KORG_MARKER_LEFT: usize = 105;
pub const KORG_MARKER_RIGHT: usize = 106;
pub const KORG_CYCLE: usize = 107;
pub const KORG_PREV: usize = 108;
pub const KORG_NEXT: usize = 109;
pub const KORG_STOP: usize = 110;
pub const KORG_PLAY: usize = 111;
pub const KORG_RECORD: usize = 112;
pub const MASTER_VOLUME: usize = KORG_KNOB1;
pub const OSC_BALANCE: usize = KORG_SLIDER1;
pub const ENVELOPE_A: usize = KORG_KNOB2;
pub const ENVELOPE_D: usize = KORG_SLIDER2;
pub const ENVELOPE_S: usize = KORG_SLIDER3;
pub const ENVELOPE_R: usize = KORG_KNOB3;
pub const OSC1_SINESAW: usize = KORG_S1;
pub const OSC1_SQUARE: usize = KORG_M1;
pub const OSC2_SINESAW: usize = KORG_S2;
pub const OSC2_SQUARE: usize = KORG_M2;
pub const FILTER_CUTOFF: usize = KORG_KNOB4;
pub fn control_name(control: usize) -> Option<&'static str> {
match control {
MASTER_VOLUME => Some("Master volume"),
ENVELOPE_A => Some("Envelope attack"),
ENVELOPE_D => Some("Envelope decay"),
ENVELOPE_S => Some("Envelope sustain"),
ENVELOPE_R => Some("Envelope release"),
OSC_BALANCE => Some("Oscillator balance"),
OSC1_SINESAW => Some("Osc1 sine/saw"),
OSC1_SQUARE => Some("Osc1 squared"),
OSC2_SINESAW => Some("Osc2 sine/saw"),
OSC2_SQUARE => Some("Osc2 squared"),
FILTER_CUTOFF => Some("Filter cutoff"),
_ => None
}
}
|
use super::*;
use crate::gui::*;
use physics::*;
#[derive(Default)]
pub struct GUISystem;
impl<'a> System<'a> for GUISystem {
type SystemData = (
(
Entities<'a>,
ReadStorage<'a, CharacterMarker>,
ReadStorage<'a, Lifes>,
ReadStorage<'a, Shield>,
ReadStorage<'a, SideBulletAbility>,
ReadStorage<'a, DoubleCoinsAbility>,
ReadStorage<'a, DoubleExpAbility>,
WriteStorage<'a, ShipStats>,
WriteStorage<'a, ShotGun>,
WriteStorage<'a, Isometry>,
WriteStorage<'a, Velocity>,
WriteStorage<'a, Spin>,
ReadStorage<'a, PhysicsComponent>,
ReadExpect<'a, red::Viewport>,
),
ReadExpect<'a, DevInfo>,
Write<'a, UI>,
Read<'a, Progress>,
WriteExpect<'a, PreloadedImages>,
Write<'a, SpawnedUpgrades>,
Read<'a, CurrentWave>,
ReadExpect<'a, Pallete>,
ReadExpect<'a, MacroGame>,
ReadExpect<'a, PreloadedSounds>,
Write<'a, EventChannel<Sound>>,
WriteExpect<'a, Touches>,
Write<'a, World<f32>>,
Write<'a, EventChannel<InsertEvent>>,
Write<'a, AppState>,
);
fn run(&mut self, data: Self::SystemData) {
let (
(
entities,
character_markers,
lifes,
shields,
side_bullet_abilities,
double_coins_abilities,
double_exp_abilities,
mut ships_stats,
mut shotguns,
isometries,
mut velocities,
mut spins,
physics,
viewport,
),
// preloaded_particles,
dev_info,
mut ui,
progress,
preloaded_images,
spawned_upgrades,
current_wave,
pallete,
macro_game,
preloaded_sounds,
mut sounds_channel,
touches,
mut world,
mut insert_channel,
mut app_state,
) = data;
let dims = viewport.dimensions();
let (w, h) = (dims.0 as f32, dims.1 as f32);
let d = (w * w + h * h).sqrt();
//contorls
#[cfg(any(target_os = "android"))]
let stick_size = w / 80.0;
#[cfg(any(target_os = "android"))]
let ctrl_size = stick_size * 10.0;
#[cfg(any(target_os = "android"))]
let move_controller = VecController::new(
Point2::new(ctrl_size, h - ctrl_size),
ctrl_size,
stick_size,
preloaded_images.circle,
);
#[cfg(any(target_os = "android"))]
let attack_controller = VecController::new(
Point2::new(w - ctrl_size, h - ctrl_size),
ctrl_size,
stick_size,
preloaded_images.circle,
);
let (character, ship_stats, _) = if let Some(value) =
(&entities, &mut ships_stats, &character_markers)
.join()
.next()
{
value
} else {
return;
};
// move controller
#[cfg(target_os = "android")]
{
let mut controlling = touches.iter().any(|x| x.is_some());
if let Some(dir) = move_controller.set(0, &mut ui, &touches) {
let (character, _) =
(&entities, &character_markers).join().next().unwrap();
let (_character_isometry, mut character_velocity) = {
let character_body = world
.rigid_body(physics.get(character).unwrap().body_handle)
.unwrap();
(*character_body.position(), *character_body.velocity())
};
let time_scaler =
normalize_60frame(TRACKER.lock().unwrap().last_delta());
let mut thrust =
ship_stats.thrust_force * Vector3::new(dir.x, dir.y, 0.0);
thrust = thrust_calculation(
ship_stats.maneuverability.unwrap(),
thrust,
*character_velocity.as_vector(),
);
*character_velocity.as_vector_mut() += thrust;
let character_body = world
.rigid_body_mut(physics.get(character).unwrap().body_handle)
.unwrap();
character_body.set_velocity(character_velocity);
}
if let Some(dir) = attack_controller.set(1, &mut ui, &touches) {
for (iso, _vel, spin, _char_marker) in (
&isometries,
&mut velocities,
&mut spins,
&character_markers,
)
.join()
{
let player_torque = DT
* calculate_player_ship_spin_for_aim(
dir,
iso.rotation(),
spin.0,
);
spin.0 += player_torque.max(-MAX_TORQUE).min(MAX_TORQUE);
}
let dir = dir.normalize();
let shotgun = shotguns.get_mut(character);
if let Some(shotgun) = shotgun {
if shotgun.shoot() {
let isometry = *isometries.get(character).unwrap();
let position = isometry.0.translation.vector;
// let direction = isometry.0 * Vector3::new(0f32, -1f32, 0f32);
let velocity_rel = shotgun.bullet_speed * dir;
let char_velocity = velocities.get(character).unwrap();
let projectile_velocity = Velocity::new(
char_velocity.0.x + velocity_rel.x,
char_velocity.0.y + velocity_rel.y,
);
sounds_channel.single_write(Sound(
preloaded_sounds.shot,
Point2::new(position.x, position.y),
));
let rotation = Rotation2::rotation_between(
&Vector2::new(0.0, 1.0),
&dir,
);
let bullets = shotgun.spawn_bullets(
EntityType::Player,
isometries.get(character).unwrap().0,
shotgun.bullet_speed,
shotgun.bullets_damage,
velocities.get(character).unwrap().0,
character,
);
insert_channel.iter_write(bullets.into_iter());
}
}
}
}
// FPS
ui.primitives.push(Primitive {
kind: PrimitiveKind::Text(Text {
position: Point2::new(w / 7.0, h / 20.0),
text: format!("FPS: {}", dev_info.fps).to_string(),
color: (1.0, 1.0, 1.0, 1.0),
font_size: 1.0,
}),
with_projection: false,
});
// stats
ui.primitives.push(Primitive {
kind: PrimitiveKind::Text(Text {
position: Point2::new(w - w / 7.0, h / 20.0),
text: format!("Score: {}", progress.score).to_string(),
color: (1.0, 1.0, 1.0, 1.0),
font_size: 1.0,
}),
with_projection: false,
});
ui.primitives.push(Primitive {
kind: PrimitiveKind::Text(Text {
position: Point2::new(w - w / 7.0, h / 20.0),
text: format!("$ {}", macro_game.coins).to_string(),
color: (1.0, 1.0, 1.0, 1.0),
font_size: 1.0,
}),
with_projection: false,
});
ui.primitives.push(Primitive {
kind: PrimitiveKind::Text(Text {
position: Point2::new(w - w / 7.0, h / 7.0 + h / 20.0),
text: format!("Wave: {}", current_wave.id).to_string(),
color: (1.0, 1.0, 1.0, 1.0),
font_size: 1.0,
}),
with_projection: false,
});
let side_bullets_cnt = side_bullet_abilities.count();
let double_coins_cnt = double_coins_abilities.count();
let double_exp_cnt = double_exp_abilities.count();
let icon_size = w / 20.0;
struct Ability {
pub icon: AtlasImage,
pub text: String,
};
let mut abilities = vec![];
if double_coins_cnt > 0 {
let ability = Ability {
icon: preloaded_images.double_coin,
text: format!("x{}", double_coins_cnt).to_string(),
};
abilities.push(ability);
}
if double_exp_cnt > 0 {
let ability = Ability {
icon: preloaded_images.double_exp,
text: format!("x{}", double_exp_cnt).to_string(),
};
abilities.push(ability);
}
if side_bullets_cnt > 0 {
let ability = Ability {
icon: preloaded_images.side_bullet_ability,
text: format!("+{}", side_bullets_cnt).to_string(),
};
abilities.push(ability);
}
for (i, ability) in abilities.iter().enumerate() {
let x_pos = w - w / 7.0;
let y_pos = (i as f32 + 1.0) * h / 7.0 + h / 20.0;
ui.primitives.push(Primitive {
kind: PrimitiveKind::Picture(Picture {
position: Point2::new(x_pos, y_pos),
width: icon_size,
height: icon_size,
image: ability.icon,
}),
with_projection: false,
});
ui.primitives.push(Primitive {
kind: PrimitiveKind::Text(Text {
position: Point2::new(
x_pos + 2.0 * icon_size,
y_pos + icon_size / 2.0,
),
text: ability.text.clone(),
color: (1.0, 1.0, 1.0, 1.0),
font_size: 1.0,
}),
with_projection: false,
});
}
let (_character, _) =
(&entities, &character_markers).join().next().unwrap();
// "UI" things
// experience and level bars
let experiencebar_w = w / 5.0;
let experiencebar_h = h / 100.0;
let experience_position =
Point2::new(w / 2.0 - experiencebar_w / 2.0, h - h / 20.0);
let experience_bar = Rectangle {
position: experience_position,
width: (progress.experience as f32
/ progress.current_max_experience() as f32)
* experiencebar_w,
height: experiencebar_h,
color: pallete.experience_color.clone(),
};
let border = d / 200f32;
ui.primitives.push(Primitive {
kind: PrimitiveKind::Picture(Picture {
position: experience_position
+ Vector2::new(-border / 2.0, -border / 2.0),
width: experiencebar_w + border,
height: experiencebar_h + border,
image: preloaded_images.bar,
}),
with_projection: false,
});
ui.primitives.push(Primitive {
kind: PrimitiveKind::Picture(Picture {
position: experience_position
+ Vector2::new(-border / 2.0, -border / 2.0),
width: (progress.experience as f32
/ progress.current_max_experience() as f32)
* experiencebar_w,
height: experiencebar_h,
image: preloaded_images.bar,
}),
with_projection: false,
});
ui.primitives.push(Primitive {
kind: PrimitiveKind::Rectangle(experience_bar),
with_projection: false,
});
if spawned_upgrades.len() > 0 {
// {
let (upgrade_bar_w, upgrade_bar_h) = (w / 3f32, h / 10.0);
ui.primitives.push(Primitive {
kind: PrimitiveKind::Picture(Picture {
position: Point2::new(
w / 2.0 - upgrade_bar_w / 2.0,
h - h / 20.0 - upgrade_bar_h,
),
width: upgrade_bar_w,
height: upgrade_bar_h,
image: preloaded_images.upg_bar,
}),
with_projection: false,
});
}
let (lifebar_w, lifebar_h) = (w / 4f32, h / 50.0);
let health_y = h / 40.0;
let shields_y = health_y + h / 13.0;
for (life, shield, _character) in
(&lifes, &shields, &character_markers).join()
{
{
// upgrade bar
let border = d / 200f32;
let (health_back_w, health_back_h) =
(lifebar_w + border, lifebar_h + border);
ui.primitives.push(Primitive {
kind: PrimitiveKind::Picture(Picture {
position: Point2::new(
w / 2.0 - health_back_w / 2.0,
health_y - border / 2.0,
),
width: health_back_w,
height: health_back_h,
image: preloaded_images.bar,
}),
with_projection: false,
});
let (health_back_w, health_back_h) =
(lifebar_w + border, lifebar_h + border);
ui.primitives.push(Primitive {
kind: PrimitiveKind::Picture(Picture {
position: Point2::new(
w / 2.0 - health_back_w / 2.0,
shields_y - border / 2.0,
),
width: health_back_w,
height: health_back_h,
image: preloaded_images.bar,
}),
with_projection: false,
});
}
let lifes_bar = Rectangle {
position: Point2::new(w / 2.0 - lifebar_w / 2.0, health_y),
width: (life.0 as f32 / ship_stats.max_health as f32)
* lifebar_w,
height: lifebar_h,
color: pallete.life_color.clone(),
};
let shields_bar = Rectangle {
position: Point2::new(w / 2.0 - lifebar_w / 2.0, shields_y),
width: (shield.0 as f32 / ship_stats.max_shield as f32)
* lifebar_w,
height: lifebar_h,
color: pallete.shield_color,
};
ui.primitives.push(Primitive {
kind: PrimitiveKind::Rectangle(shields_bar),
with_projection: false,
});
ui.primitives.push(Primitive {
kind: PrimitiveKind::Rectangle(lifes_bar),
with_projection: false,
});
}
}
}
|
use std::io::{Error as IoError, Read, Seek, SeekFrom};
use bbs::prelude::{DeterministicPublicKey, PoKOfSignature};
use bbs::{
keys::PublicKey, signature::Signature, ProofNonce, SignatureMessage, G1_COMPRESSED_SIZE,
};
use super::block::{Block, SignatureEntry, MESSAGES_MAX};
use super::header::{header_messages, RegistryHeader, HEADER_MESSAGES};
use super::util::read_fixed;
pub struct NonRevCredential {
pub registry_type: String,
pub registry_uri: String,
pub timestamp: u64,
pub interval: u32,
pub block_size: u16,
pub dpk: DeterministicPublicKey,
pub level: u16,
pub nonrev: Block,
pub start: u32,
pub index: u32,
pub signature: Signature,
}
impl NonRevCredential {
pub(crate) fn new(
header: &RegistryHeader<'_>,
entry: &SignatureEntry,
slot_index: u32,
) -> Self {
let index = if entry.level == 0 {
slot_index
} else {
slot_index / (entry.count as u32)
};
Self {
registry_type: header.registry_type.to_string(),
registry_uri: header.registry_uri.to_string(),
timestamp: header.timestamp,
interval: header.interval,
block_size: header.block_size,
dpk: header.dpk,
level: entry.level,
nonrev: entry.nonrev,
start: entry.start,
index,
signature: entry.signature(header.e, header.s),
}
}
#[inline]
pub fn indices(&self) -> impl IntoIterator<Item = u32> {
self.nonrev
.indices(self.start, self.block_size as usize, true)
}
#[inline]
pub fn unique_indices(&self) -> impl IntoIterator<Item = u32> {
self.nonrev
.indices(self.start, self.block_size as usize, false)
}
pub fn header_messages(&self) -> [SignatureMessage; HEADER_MESSAGES] {
header_messages(
&self.registry_type,
&self.registry_uri,
self.timestamp,
self.interval,
)
}
pub fn create_pok_of_signature(
&self,
pk: &PublicKey,
blinding: ProofNonce,
) -> (PoKOfSignature, usize) {
self.nonrev.create_pok_of_signature(
self.header_messages(),
self.start,
self.block_size,
self.level,
self.index,
blinding,
pk,
&self.signature,
)
}
pub fn public_key(&self) -> PublicKey {
self.dpk
.to_public_key(HEADER_MESSAGES + (self.block_size as usize))
.unwrap()
}
pub fn messages(&self) -> heapless::Vec<SignatureMessage, MESSAGES_MAX> {
let mut messages = heapless::Vec::<SignatureMessage, MESSAGES_MAX>::new();
messages.extend(
header_messages(
&self.registry_type,
&self.registry_uri,
self.timestamp,
self.interval,
)
.iter()
.copied(),
);
messages.extend(
self.nonrev
.index_messages(self.start, self.block_size, self.level),
);
messages
}
}
pub struct RegistryReader<'r, R> {
header: RegistryHeader<'r>,
reader: TakeReset<R>,
}
impl<R: Read> RegistryReader<'static, R> {
pub fn new(mut reader: R) -> Result<Self, IoError> {
let (header, _) = RegistryHeader::read(&mut reader)?;
let entries_len = u64::from_be_bytes(read_fixed(&mut reader)?);
if header.levels != 2 {}
Ok(Self {
header,
reader: TakeReset::new(reader, entries_len),
})
}
}
impl<'r, R: Read> RegistryReader<'r, R> {
pub fn header(&self) -> &RegistryHeader<'r> {
&self.header
}
#[inline]
pub fn public_key(&self) -> PublicKey {
self.header.public_key()
}
pub fn entry_count(self) -> Result<u32, IoError> {
SignatureIterator::new(self.reader, self.header.block_size, self.header.levels)
.entry_count()
}
pub fn entry_count_reset(&mut self) -> Result<u32, IoError>
where
R: Seek,
{
let result =
SignatureIterator::new(&mut self.reader, self.header.block_size, self.header.levels)
.entry_count()?;
self.reader.reset()?;
Ok(result)
}
pub fn find_credential(self, slot_index: u32) -> Result<Option<NonRevCredential>, IoError> {
SignatureIterator::new(self.reader, self.header.block_size, self.header.levels)
.find_credential(&self.header, slot_index)
}
pub fn find_credential_reset(
&mut self,
slot_index: u32,
) -> Result<Option<NonRevCredential>, IoError>
where
R: Seek,
{
let result =
SignatureIterator::new(&mut self.reader, self.header.block_size, self.header.levels)
.find_credential(&self.header, slot_index)?;
self.reader.reset()?;
Ok(result)
}
}
impl<'r, R: Read> IntoIterator for RegistryReader<'r, R> {
type Item = Result<SignatureEntry, IoError>;
type IntoIter = SignatureIterator<TakeReset<R>>;
fn into_iter(self) -> Self::IntoIter {
SignatureIterator::new(self.reader, self.header.block_size, self.header.levels)
}
}
pub struct TakeReset<R> {
inner: R,
pos: u64,
limit: u64,
}
impl<R: Read> TakeReset<R> {
pub fn new(reader: R, limit: u64) -> Self {
Self {
inner: reader,
pos: 0,
limit,
}
}
}
impl<R: Read> Read for TakeReset<R> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, IoError> {
let max = buf.len().min((self.limit - self.pos) as usize);
let len = self.inner.read(&mut buf[..max])?;
self.pos += len as u64;
Ok(len)
}
}
impl<R: Seek> TakeReset<R> {
fn reset(&mut self) -> Result<(), IoError> {
if self.pos != 0 {
self.inner.seek(SeekFrom::Current(-(self.pos as i64)))?;
self.pos = 0;
}
Ok(())
}
}
pub trait DoneRead: Read {
fn is_done(&self) -> bool;
}
impl<R: Read> DoneRead for TakeReset<R> {
fn is_done(&self) -> bool {
self.pos == self.limit
}
}
impl<'r, R: DoneRead> DoneRead for &'r mut R {
fn is_done(&self) -> bool {
(&**self).is_done()
}
}
#[derive(Debug)]
pub struct SignatureIterator<R: DoneRead> {
reader: Option<R>,
active_offset: u32,
active_level: u16,
active_count: u16,
block_size: u16,
}
impl<R: DoneRead> SignatureIterator<R> {
#[inline]
pub(crate) fn new(reader: R, block_size: u16, levels: u16) -> Self {
let reader = if levels == 2 && block_size <= 64 && block_size > 0 && block_size % 8 == 0 {
Some(reader)
} else {
// not supported
None
};
Self {
reader,
active_offset: 0,
active_level: 0,
active_count: 0,
block_size,
}
}
}
impl<R: DoneRead> SignatureIterator<R> {
pub fn entry_count(&mut self) -> Result<u32, IoError> {
let mut count = 0;
for entry in self {
entry?;
count += 1;
}
Ok(count)
}
pub(crate) fn find_entry(
&mut self,
slot_index: u32,
) -> Result<Option<SignatureEntry>, IoError> {
let block_index = slot_index / (self.block_size as u32);
if let Some(mut reader) = self.reader.take() {
while !reader.is_done() {
let entry = self.read_next(&mut reader)?;
if entry.level == 0 {
if let Some(true) = entry.contains_index(slot_index) {
return Ok(Some(entry));
}
} else if entry.level == 1 {
if let Some(true) = entry.contains_index(block_index) {
return Ok(Some(entry));
}
}
}
}
Ok(None)
}
pub(crate) fn find_credential(
&mut self,
header: &RegistryHeader<'_>,
slot_index: u32,
) -> Result<Option<NonRevCredential>, IoError> {
if let Some(entry) = self.find_entry(slot_index)? {
Ok(Some(NonRevCredential::new(header, &entry, slot_index)))
} else {
Ok(None)
}
}
#[inline]
fn read_next(&mut self, reader: &mut R) -> Result<SignatureEntry, IoError> {
if self.active_count == 0 {
let offs: [u8; 4] = read_fixed(&mut *reader)?;
self.active_offset = u32::from_be_bytes(offs);
let level: [u8; 2] = read_fixed(&mut *reader)?;
self.active_level = u16::from_be_bytes(level);
let count: [u8; 2] = read_fixed(&mut *reader)?;
self.active_count = u16::from_be_bytes(count);
}
let nonrev = Block::read(&mut *reader, self.block_size)?;
let mut sig_a = [0u8; G1_COMPRESSED_SIZE];
reader.read_exact(sig_a.as_mut())?;
let entry = SignatureEntry {
nonrev,
start: self.active_offset,
count: self.block_size,
level: self.active_level,
sig_a,
};
self.active_count -= 1;
self.active_offset += 1;
Ok(entry)
}
}
impl<R: DoneRead> Iterator for SignatureIterator<R> {
type Item = Result<SignatureEntry, IoError>;
fn next(&mut self) -> Option<Self::Item> {
if let Some(mut reader) = self.reader.take() {
let result = self.read_next(&mut reader);
if result.is_ok() && !reader.is_done() {
self.reader.replace(reader);
}
Some(result)
} else {
None
}
}
}
#[test]
fn test_take_reset() {
use std::io::Cursor;
let buf = [0u8, 1u8, 2u8, 3u8];
let mut tr = TakeReset::new(Cursor::new(&buf[..]), 4);
let mut cp = [0u8; 4];
tr.read_exact(&mut cp[..]).unwrap();
assert_eq!(cp, buf);
assert!(tr.is_done());
tr.reset().unwrap();
assert!(!tr.is_done());
tr.read_exact(&mut cp[..]).unwrap();
assert_eq!(cp, buf);
assert!(tr.is_done());
}
|
use lib::*;
#[derive(Debug)]
pub enum Error {
UnknownSignature,
NoLengthForSignature,
NoFallback,
ResultCantFit,
UnexpectedEnd,
InvalidPadding,
InvalidUtf8,
}
pub type Hash = [u8; 32];
/// Converts u32 to right aligned array of 32 bytes.
pub fn pad_u32(value: u32) -> Hash {
let mut padded = [0u8; 32];
padded[28] = (value >> 24) as u8;
padded[29] = (value >> 16) as u8;
padded[30] = (value >> 8) as u8;
padded[31] = value as u8;
padded
}
/// Converts u64 to right aligned array of 32 bytes.
pub fn pad_u64(value: u64) -> Hash {
let mut padded = [0u8; 32];
padded[24] = (value >> 56) as u8;
padded[25] = (value >> 48) as u8;
padded[26] = (value >> 40) as u8;
padded[27] = (value >> 32) as u8;
padded[28] = (value >> 24) as u8;
padded[29] = (value >> 16) as u8;
padded[30] = (value >> 8) as u8;
padded[31] = value as u8;
padded
}
/// Converts i64 to right aligned array of 32 bytes.
pub fn pad_i64(value: i64) -> Hash {
if value >= 0 {
return pad_u64(value as u64);
}
let mut padded = [0xffu8; 32];
padded[24] = (value >> 56) as u8;
padded[25] = (value >> 48) as u8;
padded[26] = (value >> 40) as u8;
padded[27] = (value >> 32) as u8;
padded[28] = (value >> 24) as u8;
padded[29] = (value >> 16) as u8;
padded[30] = (value >> 8) as u8;
padded[31] = value as u8;
padded
}
/// Converts i32 to right aligned array of 32 bytes.
pub fn pad_i32(value: i32) -> Hash {
if value >= 0 {
return pad_u32(value as u32);
}
let mut padded = [0xffu8; 32];
padded[28] = (value >> 24) as u8;
padded[29] = (value >> 16) as u8;
padded[30] = (value >> 8) as u8;
padded[31] = value as u8;
padded
}
pub fn as_u32(slice: &Hash) -> Result<u32, Error> {
if !slice[..28].iter().all(|x| *x == 0) {
return Err(Error::InvalidPadding);
}
let result = ((slice[28] as u32) << 24) +
((slice[29] as u32) << 16) +
((slice[30] as u32) << 8) +
(slice[31] as u32);
Ok(result)
}
pub fn as_i32(slice: &Hash) -> Result<i32, Error> {
let is_negative = slice[0] & 0x80 != 0;
if !is_negative {
return Ok(as_u32(slice)? as i32);
}
// only negative path here
if !slice[1..28].iter().all(|x| *x == 0xff) {
return Err(Error::InvalidPadding);
}
let result = ((slice[28] as u32) << 24) +
((slice[29] as u32) << 16) +
((slice[30] as u32) << 8) +
(slice[31] as u32);
Ok(-(result as i32))
}
pub fn as_u64(slice: &Hash) -> Result<u64, Error> {
if !slice[..24].iter().all(|x| *x == 0) {
return Err(Error::InvalidPadding);
}
let result =
((slice[24] as u64) << 56) +
((slice[25] as u64) << 48) +
((slice[26] as u64) << 40) +
((slice[27] as u64) << 32) +
((slice[28] as u64) << 24) +
((slice[29] as u64) << 16) +
((slice[30] as u64) << 8) +
(slice[31] as u64);
Ok(result)
}
pub fn as_i64(slice: &Hash) -> Result<i64, Error> {
let is_negative = slice[0] & 0x80 != 0;
if !is_negative {
return Ok(as_u64(slice)? as i64);
}
// only negative path here
if !slice[1..28].iter().all(|x| *x == 0xff) {
return Err(Error::InvalidPadding);
}
let result =
((slice[24] as u64) << 56) +
((slice[25] as u64) << 48) +
((slice[26] as u64) << 40) +
((slice[27] as u64) << 32) +
((slice[28] as u64) << 24) +
((slice[29] as u64) << 16) +
((slice[30] as u64) << 8) +
(slice[31] as u64);
Ok(-(result as i64))
}
pub fn as_bool(slice: &Hash) -> Result<bool, Error> {
if !slice[..31].iter().all(|x| *x == 0) {
return Err(Error::InvalidPadding);
}
Ok(slice[31] == 1)
}
|
#[doc = "Register `SYSCFG_IOCTRLCLRR` reader"]
pub type R = crate::R<SYSCFG_IOCTRLCLRR_SPEC>;
#[doc = "Register `SYSCFG_IOCTRLCLRR` writer"]
pub type W = crate::W<SYSCFG_IOCTRLCLRR_SPEC>;
#[doc = "Field `HSLVEN_TRACE` reader - HSLVEN_TRACE"]
pub type HSLVEN_TRACE_R = crate::BitReader;
#[doc = "Field `HSLVEN_TRACE` writer - HSLVEN_TRACE"]
pub type HSLVEN_TRACE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HSLVEN_QUADSPI` reader - HSLVEN_QUADSPI"]
pub type HSLVEN_QUADSPI_R = crate::BitReader;
#[doc = "Field `HSLVEN_QUADSPI` writer - HSLVEN_QUADSPI"]
pub type HSLVEN_QUADSPI_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HSLVEN_ETH` reader - HSLVEN_ETH"]
pub type HSLVEN_ETH_R = crate::BitReader;
#[doc = "Field `HSLVEN_ETH` writer - HSLVEN_ETH"]
pub type HSLVEN_ETH_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HSLVEN_SDMMC` reader - HSLVEN_SDMMC"]
pub type HSLVEN_SDMMC_R = crate::BitReader;
#[doc = "Field `HSLVEN_SDMMC` writer - HSLVEN_SDMMC"]
pub type HSLVEN_SDMMC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HSLVEN_SPI` reader - HSLVEN_SPI"]
pub type HSLVEN_SPI_R = crate::BitReader;
#[doc = "Field `HSLVEN_SPI` writer - HSLVEN_SPI"]
pub type HSLVEN_SPI_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - HSLVEN_TRACE"]
#[inline(always)]
pub fn hslven_trace(&self) -> HSLVEN_TRACE_R {
HSLVEN_TRACE_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - HSLVEN_QUADSPI"]
#[inline(always)]
pub fn hslven_quadspi(&self) -> HSLVEN_QUADSPI_R {
HSLVEN_QUADSPI_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - HSLVEN_ETH"]
#[inline(always)]
pub fn hslven_eth(&self) -> HSLVEN_ETH_R {
HSLVEN_ETH_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - HSLVEN_SDMMC"]
#[inline(always)]
pub fn hslven_sdmmc(&self) -> HSLVEN_SDMMC_R {
HSLVEN_SDMMC_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - HSLVEN_SPI"]
#[inline(always)]
pub fn hslven_spi(&self) -> HSLVEN_SPI_R {
HSLVEN_SPI_R::new(((self.bits >> 4) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - HSLVEN_TRACE"]
#[inline(always)]
#[must_use]
pub fn hslven_trace(&mut self) -> HSLVEN_TRACE_W<SYSCFG_IOCTRLCLRR_SPEC, 0> {
HSLVEN_TRACE_W::new(self)
}
#[doc = "Bit 1 - HSLVEN_QUADSPI"]
#[inline(always)]
#[must_use]
pub fn hslven_quadspi(&mut self) -> HSLVEN_QUADSPI_W<SYSCFG_IOCTRLCLRR_SPEC, 1> {
HSLVEN_QUADSPI_W::new(self)
}
#[doc = "Bit 2 - HSLVEN_ETH"]
#[inline(always)]
#[must_use]
pub fn hslven_eth(&mut self) -> HSLVEN_ETH_W<SYSCFG_IOCTRLCLRR_SPEC, 2> {
HSLVEN_ETH_W::new(self)
}
#[doc = "Bit 3 - HSLVEN_SDMMC"]
#[inline(always)]
#[must_use]
pub fn hslven_sdmmc(&mut self) -> HSLVEN_SDMMC_W<SYSCFG_IOCTRLCLRR_SPEC, 3> {
HSLVEN_SDMMC_W::new(self)
}
#[doc = "Bit 4 - HSLVEN_SPI"]
#[inline(always)]
#[must_use]
pub fn hslven_spi(&mut self) -> HSLVEN_SPI_W<SYSCFG_IOCTRLCLRR_SPEC, 4> {
HSLVEN_SPI_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 IO control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`syscfg_ioctrlclrr::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 [`syscfg_ioctrlclrr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SYSCFG_IOCTRLCLRR_SPEC;
impl crate::RegisterSpec for SYSCFG_IOCTRLCLRR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`syscfg_ioctrlclrr::R`](R) reader structure"]
impl crate::Readable for SYSCFG_IOCTRLCLRR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`syscfg_ioctrlclrr::W`](W) writer structure"]
impl crate::Writable for SYSCFG_IOCTRLCLRR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets SYSCFG_IOCTRLCLRR to value 0"]
impl crate::Resettable for SYSCFG_IOCTRLCLRR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::{
collections::HashMap,
fs::read_dir,
io::{self, Write},
process::Command,
time::Instant,
};
use rand::{seq::SliceRandom, thread_rng};
use statistical::{mean, standard_deviation};
const REPS_DEFAULT: usize = 2;
const ITERS: usize = 2;
#[inline(never)]
fn time(benchmark: &str) -> String {
let mut bin = Command::new(format!("target/release/{}", benchmark));
let before = Instant::now();
for _ in 0..ITERS {
bin.output().expect(&format!("Couldn't run {}", benchmark));
}
let d = Instant::now() - before;
String::from(format!(
"{:?}",
d.as_secs() as f64 + d.subsec_nanos() as f64 * 1e-9
))
}
fn mean_ci(d: &Vec<f64>) -> (f64, f64) {
let m = mean(d);
let sd = standard_deviation(d, None);
// Calculate a 99% confidence based on the mean and standard deviation.
(m, 2.58 * (sd / (d.len() as f64).sqrt()))
}
fn main() {
let bmark_names = read_dir("benchmarks")
.unwrap()
.map(|x| {
x.unwrap()
.path()
.file_stem()
.unwrap()
.to_str()
.unwrap()
.to_owned()
})
.collect::<Vec<_>>();
let mut bmark_data: HashMap<_, Vec<f64>> = HashMap::new();
for bn in &bmark_names {
bmark_data.insert(bn, vec![]);
}
let mut rng = thread_rng();
let mut done = 0;
let reps = REPS_DEFAULT;
while done < bmark_names.len() * reps {
// Randomly select a benchmark to run next
let bn = loop {
let cnd = bmark_names.choose(&mut rng).unwrap();
if bmark_data[cnd].len() < reps {
break cnd;
}
};
let stdout = time(&bn);
let t = stdout.trim().parse::<f64>().unwrap();
bmark_data.get_mut(&bn).unwrap().push(t);
done += 1;
print!(".");
io::stdout().flush().ok();
}
println!();
let mut bmark_names_sorted = bmark_names.clone();
bmark_names_sorted.sort();
for bn in &bmark_names_sorted {
let (mean, ci) = mean_ci(&bmark_data[&bn]);
println!("{}: {:.3} +/- {:.4}", bn, mean, ci);
}
}
|
extern crate ci_test;
extern crate redis;
extern crate postgres;
use ci_test::{add_two, fetch_an_integer};
use postgres::{Connection, TlsMode};
fn main() {
let conn = Connection::connect("postgres://postgres@postgres", TlsMode::None).unwrap();
loop {
println!("{:?}", add_two(2));
let result = fetch_an_integer().unwrap();
println!("{:?}", result);
}
} |
//! Tests auto-converted from "sass-spec/spec/libsass-todo-tests"
#[allow(unused)]
use super::rsass;
mod errors;
|
use std::process::Output;
use std::fmt::Display;
extern crate term;
use std::io::prelude::*;
pub enum MessageType {
Stdout,
Stderr
}
pub fn print_message(message: String, message_type: MessageType) {
let mut stdout_terminal = term::stdout().unwrap();
let mut stderr_terminal = term::stderr().unwrap();
stderr_terminal.fg(term::color::RED).unwrap();
stdout_terminal.fg(term::color::GREEN).unwrap();
match message_type {
MessageType::Stdout => {
writeln!(stdout_terminal, "{}", message).unwrap();
},
MessageType::Stderr => {
writeln!(stderr_terminal, "{}", message).unwrap();
}
}
stderr_terminal.reset().unwrap();
stdout_terminal.reset().unwrap();
}
pub fn print_shellout<T: Display>(thing: &T, shellout: &Output) {
println!("Executed {}", thing);
print_output(&shellout);
}
fn print_output(shellout: &Output) {
let exit_status = shellout.status;
match exit_status.success() {
true => {
print_message(format!("==> {:?}", String::from_utf8_lossy(&shellout.stdout)), MessageType::Stdout);
},
false => {
print_message(format!("==> {:?}", String::from_utf8_lossy(&shellout.stderr)), MessageType::Stderr);
}
}
}
|
use crate::utils::lines_from_file;
use lazy_static::lazy_static;
use regex::Regex;
use std::time::Instant;
pub fn main() {
let start = Instant::now();
assert_eq!(part_1_test(), 5);
// println!("part_1 {:?}", part_1());
assert_eq!(part_2_test(), 8);
println!("part_2 {:?}", part_2());
let duration = start.elapsed();
println!("Finished after {:?}", duration);
}
fn part_2() -> i16 {
let entries = lines_from_file("src/day_08/input.txt");
compute_acc_after_termination(entries)
}
fn part_2_test() -> i16 {
let entries = lines_from_file("src/day_08/input-test.txt");
compute_acc_after_termination(entries)
}
fn part_1() -> i16 {
let entries = lines_from_file("src/day_08/input.txt");
compute_acc_before_infinite(entries)
}
fn part_1_test() -> i16 {
let entries = lines_from_file("src/day_08/input-test.txt");
compute_acc_before_infinite(entries)
}
fn compute_acc_after_termination(entries: Vec<String>) -> i16 {
let instructions: Vec<Instruction> = entries
.iter()
.map(|entry| entry_to_instruction(entry))
.collect();
let mut i: i16 = 0;
let mut index_executed_list: Vec<i16> = vec![];
let mut acc: i16 = 0;
let mut change_operation_index: i16 = 0;
loop {
while !index_executed_list.contains(&i) {
if i as usize == instructions.len() {
return acc;
}
index_executed_list.push(i);
let instruction = &instructions[i as usize];
match instruction.op.as_str() {
"acc" => {
acc += instruction.val;
i += 1;
}
"jmp" => {
if i == change_operation_index {
i += 1
} else {
i += instruction.val;
}
}
"nop" => {
if i == change_operation_index {
i += instruction.val;
} else {
i += 1
}
}
_ => {
i += 1;
}
}
}
change_operation_index += 1;
acc = 0;
i = 0;
index_executed_list = vec![];
}
}
fn compute_acc_before_infinite(entries: Vec<String>) -> i16 {
let instructions: Vec<Instruction> = entries
.iter()
.map(|entry| entry_to_instruction(entry))
.collect();
let mut i: i16 = 0;
let mut index_executed_list: Vec<i16> = vec![];
let mut acc: i16 = 0;
while !index_executed_list.contains(&i) {
index_executed_list.push(i);
let instruction = &instructions[i as usize];
match instruction.op.as_str() {
"acc" => {
acc += instruction.val;
i += 1;
}
"jmp" => {
i += instruction.val;
}
_ => {
i += 1;
}
}
}
acc
}
#[derive(Debug)]
struct Instruction {
op: String,
val: i16,
}
fn entry_to_instruction(entry: &str) -> Instruction {
lazy_static! {
static ref RE: Regex = Regex::new(r"^(?P<op>acc|nop|jmp)\s(?P<val>.*)$").unwrap();
}
let caps = RE.captures(entry).unwrap();
Instruction {
op: caps["op"].to_string(),
val: caps["val"].parse().unwrap(),
}
}
|
//! PCI Drivers
use crate::arch::x86;
pub trait HostBusBridge {
fn pci_cs_read(&self, bus: u8, device: u8, func: u8, register: u8) -> u32;
fn pci_cs_write(&self, bus: u8, device: u8, func: u8, register: u8, val: u32);
}
pub struct x86PIO;
pub fn x86_pio_calculate_addr(bus: u8, device: u8, func: u8, register: u8) -> u32 {
assert!(device < 32);
assert!(func < 8);
assert!(register & 0b11 == 0);
(1u32 << 31)
| ((bus as u32) << 16)
| ((device as u32) << 11)
| ((func as u32) << 8)
| ((register as u32) & !0b11)
}
impl HostBusBridge for x86PIO {
fn pci_cs_read(&self, bus: u8, device: u8, func: u8, register: u8) -> u32 {
let addr = x86_pio_calculate_addr(bus, device, func, register);
x86::intrinsics::outl(0xCF8, addr);
x86::intrinsics::inl(0xCFC)
}
fn pci_cs_write(&self, bus: u8, device: u8, func: u8, register: u8, val: u32) {
let addr = x86_pio_calculate_addr(bus, device, func, register);
x86::intrinsics::outl(0xCF8, addr);
x86::intrinsics::outl(0xCFC, val)
}
}
|
/*
* 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 clap::Parser;
use reverie::syscalls::Displayable;
use reverie::syscalls::Syscall;
use reverie::Error;
use reverie::Guest;
use reverie::Tool;
use reverie_util::CommonToolArguments;
#[derive(Default)]
struct StraceTool {}
#[reverie::tool]
impl Tool for StraceTool {
type GlobalState = ();
type ThreadState = ();
async fn handle_syscall_event<T: Guest<Self>>(
&self,
guest: &mut T,
syscall: Syscall,
) -> Result<i64, Error> {
eprintln!(
"[pid {}] {} = ?",
guest.tid(),
syscall.display_with_outputs(&guest.memory()),
);
guest.tail_inject(syscall).await
}
}
#[tokio::main]
async fn main() -> Result<(), Error> {
let args = CommonToolArguments::from_args();
let log_guard = args.init_tracing();
let tracer = reverie_ptrace::TracerBuilder::<StraceTool>::new(args.into())
.spawn()
.await?;
let (status, _) = tracer.wait().await?;
drop(log_guard); // Flush logs before exiting.
status.raise_or_exit()
}
|
use std::sync::Arc;
use actix_web::{error, web, HttpResponse, Result};
use arc_swap::ArcSwap;
use chrono::{DateTime, Duration, Utc};
use once_cell::sync::Lazy;
use rand::Rng;
use reqwest::Client;
use serde::Deserialize;
pub fn configure(cfg: &mut web::ServiceConfig) {
cfg.service(web::resource("/{file}").route(web::get().to(get_latest_script_file)));
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum ScriptFile {
User,
Meta,
}
impl ScriptFile {
fn from_request(request: &str) -> Option<Self> {
Some(match request {
"qc-ext.latest.user.js" => Self::User,
"qc-ext.latest.meta.js" => Self::Meta,
_ => return None,
})
}
fn github_filename(self) -> &'static str {
match self {
Self::User => "qc-ext.user.js",
Self::Meta => "qc-ext.meta.js",
}
}
}
pub(crate) async fn get_latest_script_file(file: web::Path<String>) -> Result<HttpResponse> {
let script_file = ScriptFile::from_request(&file).ok_or_else(|| {
error::ErrorBadRequest(format!("{file} is not a valid release file name"))
})?;
let jitter = rand::thread_rng().gen_range(-20..20);
let cache = SCRIPT_CACHE.load();
let cache_expired = cache.expiration - Utc::now() <= Duration::seconds(jitter);
if !cache_expired {
if let Some(cached_file) = match script_file {
ScriptFile::User => cache.user.as_deref(),
ScriptFile::Meta => cache.meta.as_deref(),
} {
return Ok(HttpResponse::Ok()
.content_type("text/javascript; charset=utf-8")
.body(cached_file.to_owned()));
}
}
let releases_response = Client::new()
.get("https://api.github.com/repos/Questionable-Content-Extensions/client/releases/latest")
.header(
"User-Agent",
"https://github.com/Questionable-Content-Extensions/server",
)
.send()
.await
.map_err(error::ErrorInternalServerError)?;
let releases: Releases = releases_response
.json()
.await
.map_err(error::ErrorInternalServerError)?;
let requested_asset_url = releases
.assets
.into_iter()
.find(|a| a.name == script_file.github_filename())
.ok_or_else(|| {
error::ErrorNotFound(format!(
"According to GitHub, there is no latest release of {}! \
Hopefully this is a transient error, try again in a few minutes.",
file
))
})?
.browser_download_url;
let asset_response = Client::new()
.get(requested_asset_url)
.header(
"User-Agent",
"https://github.com/Questionable-Content-Extensions/server",
)
.send()
.await
.map_err(error::ErrorInternalServerError)?;
let asset = asset_response
.text()
.await
.map_err(error::ErrorInternalServerError)?;
let new_cache = if cache_expired {
// Start a new cache
ScriptCache {
expiration: Utc::now() + Duration::hours(1),
user: if script_file == ScriptFile::User {
Some(asset.clone())
} else {
None
},
meta: if script_file == ScriptFile::Meta {
Some(asset.clone())
} else {
None
},
}
} else {
// Cache wasn't expired, but we still had to fetch the asset
// which means it was a cache miss, so add the missing asset
// to the existing cache
let mut new_cache = (**cache).clone();
if script_file == ScriptFile::User {
new_cache.user = Some(asset.clone());
} else {
new_cache.meta = Some(asset.clone());
}
new_cache
};
SCRIPT_CACHE.compare_and_swap(cache, Arc::new(new_cache));
Ok(HttpResponse::Ok()
.content_type("text/javascript; charset=utf-8")
.body(asset))
}
#[derive(Debug, Deserialize)]
struct Releases {
assets: Vec<Asset>,
}
#[derive(Debug, Deserialize)]
struct Asset {
name: String,
browser_download_url: String,
}
#[derive(Clone, Debug)]
struct ScriptCache {
expiration: DateTime<Utc>,
user: Option<String>,
meta: Option<String>,
}
static SCRIPT_CACHE: Lazy<ArcSwap<ScriptCache>> = Lazy::new(|| {
ArcSwap::from_pointee(ScriptCache {
expiration: Utc::now() - Duration::days(1),
user: None,
meta: None,
})
});
|
extern crate rusthub;
extern crate rustc_serialize;
use rusthub::notifications;
use rustc_serialize::json;
#[test]
#[ignore]
fn decode_token_response() {
let response = notifications::get_notifications_basic("username", "aaaaaaaaaxaaaaaaaaaxaaaaaaaaaxaaaaaaaaax");
println!("{:#?}", response.unwrap());
}
#[test]
#[ignore]
fn encode_decode_notifications() {
// This assumes you have unread notifications with the supplied oauth token
let response: notifications::NotificationResponse = notifications::get_notifications_oauth("aaaaaaaaaxaaaaaaaaaxaaaaaaaaaxaaaaaaaaax").unwrap();
assert!(response.notifications.is_some());
let notifications: notifications::Notifications = response.notifications.unwrap().unwrap();
let json_str = json::encode(¬ifications).unwrap();
json::decode::<notifications::Notifications>(&json_str).unwrap();
} |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Account {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<AccountIdentity>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AccountUpdate {
#[serde(flatten)]
pub update_resource: UpdateResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<AccountIdentity>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AccountIdentity {
#[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")]
pub principal_id: Option<String>,
#[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<account_identity::Type>,
}
pub mod account_identity {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
SystemAssigned,
None,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AccountList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Account>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConfigurationProfileAssignmentList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<ConfigurationProfileAssignment>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConfigurationProfileAssignment {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ConfigurationProfileAssignmentProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConfigurationProfileAssignmentProperties {
#[serde(rename = "configurationProfile", default, skip_serializing_if = "Option::is_none")]
pub configuration_profile: Option<configuration_profile_assignment_properties::ConfigurationProfile>,
#[serde(rename = "targetId", default, skip_serializing_if = "Option::is_none")]
pub target_id: Option<String>,
#[serde(rename = "accountId", default, skip_serializing_if = "Option::is_none")]
pub account_id: Option<String>,
#[serde(rename = "configurationProfilePreferenceId", default, skip_serializing_if = "Option::is_none")]
pub configuration_profile_preference_id: Option<String>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<configuration_profile_assignment_properties::ProvisioningState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub compliance: Option<ConfigurationProfileAssignmentCompliance>,
}
pub mod configuration_profile_assignment_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ConfigurationProfile {
#[serde(rename = "Azure virtual machine best practices – Dev/Test")]
AzureVirtualMachineBestPracticesDevTest,
#[serde(rename = "Azure virtual machine best practices – Production")]
AzureVirtualMachineBestPracticesProduction,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Succeeded,
Failed,
Created,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConfigurationProfileAssignmentCompliance {
#[serde(rename = "updateStatus", default, skip_serializing_if = "Option::is_none")]
pub update_status: Option<configuration_profile_assignment_compliance::UpdateStatus>,
}
pub mod configuration_profile_assignment_compliance {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum UpdateStatus {
Succeeded,
Failed,
Created,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConfigurationProfilePreference {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ConfigurationProfilePreferenceProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConfigurationProfilePreferenceUpdate {
#[serde(flatten)]
pub update_resource: UpdateResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ConfigurationProfilePreferenceProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConfigurationProfilePreferenceProperties {
#[serde(rename = "vmBackup", default, skip_serializing_if = "Option::is_none")]
pub vm_backup: Option<ConfigurationProfilePreferenceVmBackup>,
#[serde(rename = "antiMalware", default, skip_serializing_if = "Option::is_none")]
pub anti_malware: Option<ConfigurationProfilePreferenceAntiMalware>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConfigurationProfilePreferenceVmBackup {
#[serde(rename = "timeZone", default, skip_serializing_if = "Option::is_none")]
pub time_zone: Option<String>,
#[serde(rename = "instantRpRetentionRangeInDays", default, skip_serializing_if = "Option::is_none")]
pub instant_rp_retention_range_in_days: Option<i32>,
#[serde(rename = "retentionPolicy", default, skip_serializing_if = "Option::is_none")]
pub retention_policy: Option<String>,
#[serde(rename = "schedulePolicy", default, skip_serializing_if = "Option::is_none")]
pub schedule_policy: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConfigurationProfilePreferenceAntiMalware {
#[serde(rename = "enableRealTimeProtection", default, skip_serializing_if = "Option::is_none")]
pub enable_real_time_protection: Option<configuration_profile_preference_anti_malware::EnableRealTimeProtection>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exclusions: Option<serde_json::Value>,
#[serde(rename = "runScheduledScan", default, skip_serializing_if = "Option::is_none")]
pub run_scheduled_scan: Option<configuration_profile_preference_anti_malware::RunScheduledScan>,
#[serde(rename = "scanType", default, skip_serializing_if = "Option::is_none")]
pub scan_type: Option<configuration_profile_preference_anti_malware::ScanType>,
#[serde(rename = "scanDay", default, skip_serializing_if = "Option::is_none")]
pub scan_day: Option<String>,
#[serde(rename = "scanTimeInMinutes", default, skip_serializing_if = "Option::is_none")]
pub scan_time_in_minutes: Option<String>,
}
pub mod configuration_profile_preference_anti_malware {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EnableRealTimeProtection {
True,
False,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RunScheduledScan {
True,
False,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ScanType {
Quick,
Full,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConfigurationProfilePreferenceList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<ConfigurationProfilePreference>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "isDataAction", default, skip_serializing_if = "Option::is_none")]
pub is_data_action: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<operation::Display>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<operation::Properties>,
}
pub mod operation {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Display {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "statusCode", default, skip_serializing_if = "Option::is_none")]
pub status_code: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Operation>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateResource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorDetail>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorDetail {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<ErrorDetail>,
#[serde(rename = "additionalInfo", default, skip_serializing_if = "Vec::is_empty")]
pub additional_info: Vec<ErrorAdditionalInfo>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorAdditionalInfo {
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub info: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TrackedResource {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
pub location: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProxyResource {
#[serde(flatten)]
pub resource: Resource,
}
|
use std::fmt;
use std::fmt::Write;
use std::ops;
use rand::{thread_rng, Rng};
#[derive(Copy, Clone)]
pub struct Vec3 {
pub x: f32,
pub y: f32,
pub z: f32,
}
impl Vec3 {
pub fn new() -> Vec3 {
Vec3 { x: 0_f32, y: 0_f32, z: 0_f32 }
}
pub fn one() -> Vec3 {
Vec3 { x: 1_f32, y: 1_f32, z: 1_f32 }
}
pub fn random() -> Vec3 {
Vec3 { x: thread_rng().gen(), y: thread_rng().gen(), z: thread_rng().gen() }
}
pub fn random_min_max(min: f32, max: f32) -> Vec3 {
Vec3 {
x: thread_rng().gen_range(min..max),
y: thread_rng().gen_range(min..max),
z: thread_rng().gen_range(min..max),
}
}
pub fn new_filled(x: f32, y: f32, z: f32) -> Vec3 {
Vec3 { x, y, z }
}
pub fn reflect(lhs: &Vec3, rhs: &Vec3) -> Vec3 {
*lhs - *rhs * 2f32 * lhs.dot(rhs)
}
pub fn refract(uv: &Vec3, n: &Vec3, etai_over_etat: f32) -> Vec3 {
let cos_theta = f32::min(-uv.dot(n), 1.0);
let r_out_perp = (*uv + (*n * cos_theta)) * etai_over_etat;
let r_out_parallel = *n * -f32::sqrt(f32::abs(1.0 - r_out_perp.length_squared()));
r_out_perp + r_out_parallel
}
pub fn near_zero(&self) -> bool {
f32::abs(self.x) < f32::EPSILON && f32::abs(self.y) < f32::EPSILON && f32::abs(self.z) < f32::EPSILON
}
pub fn length_squared(&self) -> f32 {
self.x * self.x + self.y * self.y + self.z * self.z
}
pub fn length(&self) -> f32 {
f32::sqrt(self.length_squared())
}
pub fn normalize(&self) -> Vec3 {
let l: f32 = self.length();
Vec3::new_filled(self.x / l, self.y / l, self.z / l)
}
pub fn dot(&self, rhs: &Vec3) -> f32 {
return self.x * rhs.x + self.y * rhs.y + self.z * rhs.z;
}
pub fn cross(&self, rhs: &Vec3) -> Vec3 {
Vec3::new_filled(self.y * rhs.z - self.z * rhs.y,
self.z * rhs.x - self.x * rhs.z,
self.x * rhs.y - self.y * rhs.x)
}
}
impl fmt::Display for Vec3 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.x.to_string().as_str())?;
f.write_char(' ')?;
f.write_str(self.y.to_string().as_str())?;
f.write_char(' ')?;
f.write_str(self.z.to_string().as_str())?;
Ok(())
}
}
impl ops::Add<Vec3> for Vec3 {
type Output = Vec3;
fn add(self, rhs: Vec3) -> Self::Output {
Vec3::new_filled(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
}
}
impl ops::AddAssign<Vec3> for Vec3 {
fn add_assign(&mut self, rhs: Vec3) {
self.x = self.x + rhs.x;
self.y = self.y + rhs.y;
self.z = self.z + rhs.z;
}
}
impl ops::Sub<Vec3> for Vec3 {
type Output = Vec3;
fn sub(self, rhs: Vec3) -> Self::Output {
Vec3::new_filled(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
}
}
impl ops::SubAssign<Vec3> for Vec3 {
fn sub_assign(&mut self, rhs: Vec3) {
self.x = self.x - rhs.x;
self.y = self.y - rhs.y;
self.z = self.z - rhs.z;
}
}
impl ops::Neg for Vec3 {
type Output = Vec3;
fn neg(self) -> Self::Output {
Vec3 { x: -self.x, y: -self.y, z: -self.z }
}
}
impl ops::Mul<f32> for Vec3 {
type Output = Vec3;
fn mul(self, rhs: f32) -> Self::Output {
Vec3::new_filled(self.x * rhs, self.y * rhs, self.z * rhs)
}
}
impl ops::MulAssign<f32> for Vec3 {
fn mul_assign(&mut self, rhs: f32) {
self.x = self.x * rhs;
self.y = self.y * rhs;
self.z = self.z * rhs;
}
}
impl ops::Mul<Vec3> for Vec3 {
type Output = Vec3;
fn mul(self, rhs: Vec3) -> Self::Output {
Vec3::new_filled(self.x * rhs.x, self.y * rhs.y, self.z * rhs.z)
}
} |
#[doc = "Register `CCVALR` reader"]
pub type R = crate::R<CCVALR_SPEC>;
#[doc = "Field `ANSRC1` reader - compensation value for the NMOS transistor This value is provided by the cell and must be interpreted by the processor to compensate the slew rate in the functional range."]
pub type ANSRC1_R = crate::FieldReader;
#[doc = "Field `APSRC1` reader - compensation value for the PMOS transistor This value is provided by the cell and must be interpreted by the processor to compensate the slew rate in the functional range."]
pub type APSRC1_R = crate::FieldReader;
#[doc = "Field `ANSRC2` reader - Compensation value for the NMOS transistor This value is provided by the cell and must be interpreted by the processor to compensate the slew rate in the functional range."]
pub type ANSRC2_R = crate::FieldReader;
#[doc = "Field `APSRC2` reader - compensation value for the PMOS transistor This value is provided by the cell and must be interpreted by the processor to compensate the slew rate in the functional range."]
pub type APSRC2_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:3 - compensation value for the NMOS transistor This value is provided by the cell and must be interpreted by the processor to compensate the slew rate in the functional range."]
#[inline(always)]
pub fn ansrc1(&self) -> ANSRC1_R {
ANSRC1_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 4:7 - compensation value for the PMOS transistor This value is provided by the cell and must be interpreted by the processor to compensate the slew rate in the functional range."]
#[inline(always)]
pub fn apsrc1(&self) -> APSRC1_R {
APSRC1_R::new(((self.bits >> 4) & 0x0f) as u8)
}
#[doc = "Bits 8:11 - Compensation value for the NMOS transistor This value is provided by the cell and must be interpreted by the processor to compensate the slew rate in the functional range."]
#[inline(always)]
pub fn ansrc2(&self) -> ANSRC2_R {
ANSRC2_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bits 12:15 - compensation value for the PMOS transistor This value is provided by the cell and must be interpreted by the processor to compensate the slew rate in the functional range."]
#[inline(always)]
pub fn apsrc2(&self) -> APSRC2_R {
APSRC2_R::new(((self.bits >> 12) & 0x0f) as u8)
}
}
#[doc = "SBS compensation cell for I/Os value register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccvalr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CCVALR_SPEC;
impl crate::RegisterSpec for CCVALR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ccvalr::R`](R) reader structure"]
impl crate::Readable for CCVALR_SPEC {}
#[doc = "`reset()` method sets CCVALR to value 0x88"]
impl crate::Resettable for CCVALR_SPEC {
const RESET_VALUE: Self::Ux = 0x88;
}
|
// https://www.investopedia.com/articles/active-trading/101014/basics-algorithmic-trading-concepts-and-examples.asp
use rust_decimal::Decimal;
use alpaca_client::client::{Client, AccountType};
pub struct TradeDecision {
pub name: String,
pub confidence: Decimal
}
pub struct Stock {
pub symbol: String,
pub exchange: String,
}
pub(crate) trait TradingStrategy {
fn name(&self) -> String;
fn evaluate_stock(&self, _: Stock) -> TradeDecision;
fn get_client() -> Client {
return alpaca_client::client::Client::new("".parse().unwrap(), "".parse().unwrap(), AccountType::PAPER);
}
}
|
use crate::mem::mapper::{Mapper, RAM_BANK_SIZE, ROM_BANK_SIZE};
pub struct Mbc1Mapper {
/// Mapped to the ROM area. Up to 2 MiB in size.
rom: Box<[u8]>,
/// Mapped to the RAM area. Up to 32 KiB in size.
ram: Box<[u8]>,
current_rom_bank: u8,
current_ram_bank: u8,
ram_enabled: bool,
ram_banking_enabled: bool,
has_battery: bool,
/// True is SRAM has been written to since the last time it was saved.
ram_modified: bool,
}
impl Mbc1Mapper {
pub fn new(rom: Box<[u8]>, ram: Box<[u8]>, has_battery: bool) -> Mbc1Mapper {
assert!(rom.len() <= 2 << 20);
assert!(rom.len().is_power_of_two());
assert!(ram.len() <= 32 << 10);
assert!(ram.is_empty() || ram.len().is_power_of_two());
Mbc1Mapper {
rom: rom,
ram: ram,
current_rom_bank: 1,
current_ram_bank: 0,
ram_enabled: false,
ram_banking_enabled: false,
has_battery: has_battery,
ram_modified: false,
}
}
fn rom_mask(&self) -> usize {
self.rom.len() - 1
}
fn ram_mask(&self) -> usize {
self.ram.len() - 1
}
}
impl Mapper for Mbc1Mapper {
fn read_rom(&self, address: u16) -> u8 {
let bank = if address & 0x4000 == 0 {
0
} else {
self.current_rom_bank
};
let offset = bank as usize * ROM_BANK_SIZE + (address & 0x3FFF) as usize;
self.rom[offset & self.rom_mask()]
}
fn write_rom(&mut self, address: u16, data: u8) {
match address >> 13 & 0b11 {
0 => {
// RAM enable
self.ram_enabled = data & 0xF == 0xA;
}
1 => {
// ROM bank
let mut new_bank = data & 0x1F;
if new_bank == 0 {
new_bank = 1;
}
self.current_rom_bank = (self.current_rom_bank & !0x1F) | new_bank;
}
2 => {
// RAM bank / upper ROM bank
let new_bank = data & 0x3;
if self.ram_banking_enabled {
self.current_ram_bank = new_bank;
} else {
self.current_rom_bank = (self.current_rom_bank & !0x60) | (new_bank << 5);
}
}
3 => {
// ROM/RAM mode
self.ram_banking_enabled = data & 0x1 == 0x1;
if self.ram_banking_enabled {
self.current_rom_bank &= 0x1F;
} else {
self.current_ram_bank = 0;
}
}
_ => unreachable!(),
}
}
fn read_ram(&self, address: u16) -> u8 {
if self.ram_enabled && !self.ram.is_empty() {
let offset =
self.current_ram_bank as usize * RAM_BANK_SIZE + (address & 0x1FFF) as usize;
self.ram[offset & self.ram_mask()]
} else {
0xFF
}
}
fn write_ram(&mut self, address: u16, data: u8) {
if self.ram_enabled && !self.ram.is_empty() {
let offset =
self.current_ram_bank as usize * RAM_BANK_SIZE + (address & 0x1FFF) as usize;
let ram_mask = self.ram_mask();
self.ram[offset & ram_mask] = data;
self.ram_modified = true;
}
}
fn save_battery(&mut self) -> Vec<u8> {
if self.has_battery && self.ram_modified {
self.ram_modified = false;
Vec::from(&*self.ram)
} else {
Vec::new()
}
}
}
|
use crate::blockchain::block::Block;
use crate::blockchain::verifier::Verifier;
pub mod block;
pub mod proof;
pub mod transaction;
pub mod verifier;
pub mod smart_contract;
#[derive(Debug)]
pub struct Blockchain {
pub chain: Vec<Block>,
verificator: Verifier,
}
impl Default for Blockchain {
fn default() -> Blockchain {
Blockchain {
chain: vec![Block{
..Default::default()
}], // genesis block
verificator: Verifier{}
}
}
}
impl Blockchain {
pub fn last_block(&self) -> Option<&Block> {
self.chain.last()
}
pub fn mine_block(self) -> Self{
unimplemented!()
}
pub fn verify_all_transactions(&self){
unimplemented!()
}
pub fn verify_chain(&self) -> bool{
let GENESIS_INDEX = 0;
for (index, block) in self.chain.iter().enumerate() {
if index == 0 { continue }
let previous_block = self.chain[index-1].to_string();
if block.previous_hash != self.verificator.hash_string_sha256(previous_block) {
if block.index == GENESIS_INDEX {
continue
}
return false
}
}
return true
}
pub fn get_chain(&self) {
// return blockchain as JSON
}
}
#[cfg(test)]
mod tests {
use crate::blockchain::block::Block;
use crate::blockchain::Blockchain;
use crate::blockchain::proof::Proof;
use crate::blockchain::transaction::Transaction;
#[test]
pub fn verity_chain(){
let tx = Transaction::new("Alice".to_string(),"Bob".to_string(), 1.29);
let mut blockchain: Blockchain = Blockchain{
..Default::default()
};
let genesis_block = blockchain.last_block().unwrap();
let genesis_hash = blockchain.verificator.hash_block(genesis_block);
let block = Block::new(1, genesis_hash, Proof{value: "100".to_string()}, vec![tx]);
blockchain.chain.push(block);
assert_eq!(blockchain.chain.len(), 2);
assert_eq!(blockchain.verify_chain(), true);
let tx2 = Transaction::new("Alice".to_string(),"Bob".to_string(), 1.23);
let previous_block = blockchain.last_block().unwrap();
let previous_hash = blockchain.verificator.hash_block(previous_block);
let block2 = Block::new(1, previous_hash, Proof{value: "100".to_string()}, vec![tx2]);
blockchain.chain.push(block2);
assert_eq!(blockchain.chain.len(), 3);
assert_eq!(blockchain.verify_chain(), true);
// try to hack
let tx3 = Transaction::new("Alice".to_string(),"Bob".to_string(), 1.23);
let random_hash = "5a6fbeb03b7c8c25ce5e477ddacee17772301c43f34a426fe6c569f6909a06c746".as_bytes().to_vec();
let block3 = Block::new(1, random_hash, Proof{value: "100".to_string()}, vec![tx3]);
blockchain.chain.push(block3);
assert_eq!(blockchain.chain.len(), 4);
assert_eq!(blockchain.verify_chain(), false);
}
}
|
extern crate httparse;
//use httparse::*;
use std::collections::VecDeque;
use std::io;
// use std::io::prelude::*;
use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
use std::rc::Rc;
// use byteorder::{BigEndian, ByteOrder};
use bytes::{Buf, BufMut, Bytes, BytesMut};
use mio::net::TcpStream;
use mio::unix::UnixReady;
use mio::{Poll, PollOpt, Ready, Token};
use std::fmt;
use std::net::Shutdown;
use std::str;
const READ_WRITE_BUF_CAP: usize = 65536;
#[allow(dead_code)]
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Proto {
NONE = 1,
HTTP,
HTTPS,
HTTP2,
WS,
WSS,
}
impl fmt::Display for Proto {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let printable = match *self {
Proto::HTTP => "HTTP",
Proto::HTTPS => "HTTPS",
Proto::HTTP2 => "HTTP2",
Proto::WS => "WS",
Proto::WSS => "WSS",
_ => "NONE",
};
write!(f, "{}", printable)
}
}
/// A stateful wrapper around a non-blocking stream. This connection is not
/// the SERVER connection. This connection represents the client connections
/// _accepted_ by the SERVER connection.
pub struct Connection {
// handle to the accepted socket
sock: TcpStream,
// token used to register with the poller
pub token: Token,
// set of events we are interested in
interest: Ready,
buf: Option<Bytes>,
mut_buf: Option<BytesMut>,
// messages waiting to be sent out
send_queue: VecDeque<Rc<Vec<u8>>>,
// track whether a read received `WouldBlock` and store the number of
// byte we are supposed to read
// read_continuation: Option<u64>,
// track whether a write received `WouldBlock`
write_continuation: bool,
// keep the protocol used in connection
proto: Proto,
}
const MAGIC_METHODS: [&str; 9] = [
"OPT", "GET", "POS", "PUT", "DEL", "HEA", "TRA", "CON", "PAT",
]; // names: [&str; 3]
impl Connection {
pub fn new(sock: TcpStream, token: Token) -> Connection {
Connection {
sock: sock,
token: token,
interest: Ready::from(UnixReady::hup()),
buf: None,
mut_buf: Some(BytesMut::with_capacity(READ_WRITE_BUF_CAP)),
send_queue: VecDeque::with_capacity(32),
// read_continuation: None,
write_continuation: false,
proto: Proto::NONE,
}
}
// fn read_request_head<T: Read>(stream: T) -> Vec<u8> {
// let mut reader = BufReader::new(stream);
// let mut buff = Vec::new();
// let mut read_bytes = reader
// .read_until(b'\n', &mut buff)
// .expect("reading from stream won't fail");
// while read_bytes > 0 {
// read_bytes = reader.read_until(b'\n', &mut buff).unwrap();
// if read_bytes == 2 && &buff[(buff.len() - 2)..] == b"\r\n" {
// break;
// }
// }
// return buff;
// }
pub fn hup(&mut self, poll: &mut Poll, dereg: bool) -> io::Result<()> {
match self.sock.shutdown(Shutdown::Both) {
Ok(_) => debug!("SHUTDOWN CONNECTION"),
Err(e) => {
if e.kind() != ErrorKind::NotConnected {
panic!("FAILED SHUTDOWN CONNECTION: {}", e)
}
}
};
if dereg {
match poll.deregister(&self.sock) {
Err(e) => debug!("error hanging up sock: {}", e), // TODO: always fails
Ok(_) => (),
}
}
Ok(())
}
/// Handle read event from poller.
///
/// The Handler must continue calling until None is returned.
///
/// The recieve buffer is sent back to `Server` so the message can be broadcast to all
/// listening connections.
pub fn readable(&mut self, poll: &mut Poll) -> io::Result<Option<Vec<u8>>> {
// let local_addr = self.sock.local_addr().unwrap();
// let peer_addr = self.sock.peer_addr().unwrap();
// debug!(
// "PROTOCOL {} ADDR {}:{} -> {}",
// self.proto,
// local_addr.ip(),
// local_addr.port(),
// peer_addr,
// );
let mut buf = self.mut_buf.take().unwrap();
match self.sock.read(unsafe { buf.bytes_mut() }) {
Ok(n) => {
// println!("CONN : we read {} bytes!", n);
unsafe {
buf.advance_mut(n);
}
// Detect the proto is unsecure by MAGIC three bytes of HTTP proto when connection initiated
if self.proto == Proto::NONE {
let is_plain = {
let tri = String::from_utf8_lossy(&buf[0..3]);
let ret = match MAGIC_METHODS.iter().find(|&&magic| magic == tri) {
Some(_) => true,
None => false,
};
ret
};
if is_plain {
// SHOULD TO CHECK "Connection: Upgrade" for websocket
self.proto = Proto::HTTP;
}
trace!("ACHTUNG!!! IS PLAIN {}", is_plain);
trace!("{:?}",buf);
//=====================
let mut headers = [httparse::EMPTY_HEADER; 16];
let mut req = httparse::Request::new(&mut headers);
let res = req.parse(&buf).unwrap();
if res.is_partial() {
trace!("{:?}",req);
match req.method {
Some(ref method) => {
trace!("{:?}",method);
},
None => {
}
}
match req.path {
Some(ref path) => {
trace!("{:?}",path);
},
None => {
}
}
} else {
trace!("request partial {:?}",req);
}
//---------------------
}
// println!("LEN {} {}", buf.remaining_mut(), buf.capacity());
// reuse the buffer for the response
// self.buf = Some(buf.flip());
self.mut_buf = Some(buf); // DV STUB... REMOVE IT
self.interest.remove(Ready::readable());
self.interest.insert(Ready::writable());
}
Err(e) => {
println!("not implemented; client err={:?}", e);
self.interest.remove(Ready::readable());
}
}
// // UFCS: resolve "multiple applicable items in scope [E0034]" error
// let sock_ref = <TcpStream as Read>::by_ref(&mut self.sock);
// // Read header
// let mut reader = BufReader::new(sock_ref);
// let mut buff = Vec::new();
// let mut read_bytes = reader
// .read_until(b'\n', &mut buff)
// .expect("reading from stream won't fail");
// while read_bytes > 0 {
// read_bytes = reader.read_until(b'\n', &mut buff).unwrap();
// if read_bytes == 2 && &buff[(buff.len() - 2)..] == b"\r\n" {
// break;
// }
// }
// // let s = match str::from_utf8(&buff) {
// // Ok(v) => v,
// // Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
// // };
// // println!("REQUEST: \n{}", s);
// let mut headers = [httparse::EMPTY_HEADER; 16];
// let mut req = httparse::Request::new(&mut headers);
// let _ = req.parse(&buff);
// // println!("HTTP VERSION HTTP 1.{:?}", req.version.unwrap());
// let host = match req.headers.iter().find(|&&header| header.name == "Host") {
// Some(header) => str::from_utf8(header.value).unwrap(),
// None => "",
// };
// // let method = Method::from_str(req.method.unwrap());
// let path = req.path.unwrap();
// println!("HOST {:?} {:?} {}\n", host, method.unwrap(), path);
// println!("HOST {:?} {}\n", host, path);
// for (_i, elem) in req.headers.iter_mut().enumerate() {
// let s = match str::from_utf8(elem.value) {
// Ok(v) => v,
// Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
// };
// println!("HEADER {:?} {:?}", elem.name, s)
// }
// self.interest.insert(Ready::writable());
// self.interest.remove(Ready::readable());
let _ = self.reregister(poll);
let msg = b"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n<html><body>Hello world,peter</body></html>\r\n";
Ok(Some(msg.to_vec()))
}
/// Handle a writable event from the poller.
///
/// Send one message from the send queue to the client. If the queue is empty, remove interest
/// in write events.
/// TODO: Figure out if sending more than one message is optimal. Maybe we should be trying to
/// flush until the kernel sends back EAGAIN?
pub fn writable(&mut self, poll: &mut Poll) -> io::Result<()> {
// self.send_queue
// .pop_front()
// .ok_or(Error::new(ErrorKind::Other, "Could not pop send queue"))
// .and_then(|buf| self.write_message(buf))?;
// if self.send_queue.is_empty() {
// self.interest.remove(Ready::writable());
// }
self.interest.insert(Ready::readable());
self.interest.remove(Ready::writable());
let _ = self.reregister(poll);
Ok(())
}
fn write_message(&mut self, buf: Rc<Vec<u8>>) -> io::Result<()> {
// println!("MESSAGE {:?}", String::from_utf8_lossy(&buf));
let len = buf.len();
match self.sock.write(&*buf) {
Ok(n) => {
debug!("CONN : we wrote {} bytes", n);
// if we wrote a partial message, then put remaining part of message back
// into the queue so we can try again
if n < len {
let remaining = Rc::new(buf[n..].to_vec());
self.send_queue.push_front(remaining);
self.write_continuation = true;
} else {
self.write_continuation = false;
}
Ok(())
}
Err(e) => {
if e.kind() == ErrorKind::WouldBlock {
debug!("client flushing buf; WouldBlock");
// put message back into the queue so we can try again
self.send_queue.push_front(buf);
self.write_continuation = true;
Ok(())
} else {
error!("Failed to send buffer for {:?}, error: {}", self.token, e);
Err(e)
}
}
}
}
/// Queue an outgoing message to the client.
///
/// This will cause the connection to register interests in write events with the poller.
/// The connection can still safely have an interest in read events. The read and write buffers
/// operate independently of each other.
pub fn send_message(&mut self, message: Rc<Vec<u8>>) -> io::Result<()> {
trace!("connection send_message; token={:?}", self.token);
// if the queue is empty then try and write. if we get WouldBlock the message will get
// queued up for later. if the queue already has items in it, then we know that we got
// WouldBlock from a previous write, so queue it up and wait for the next write event.
if self.send_queue.is_empty() {
self.write_message(message)?;
} else {
self.send_queue.push_back(message);
}
if !self.send_queue.is_empty() && !self.interest.is_writable() {
self.interest.insert(Ready::writable());
}
Ok(())
}
/// Register interest in read events with poll.
///
/// This will let our connection accept reads starting next poller tick.
pub fn register(&mut self, poll: &mut Poll) -> io::Result<()> {
trace!("connection register; token={:?}", self.token);
self.interest.insert(Ready::readable());
poll.register(
&self.sock,
self.token,
self.interest,
PollOpt::edge() | PollOpt::oneshot(),
).or_else(|e| {
error!("Failed to register {:?}, {:?}", self.token, e);
Err(e)
})
}
/// Re-register interest in read events with poll.
pub fn reregister(&mut self, poll: &mut Poll) -> io::Result<()> {
trace!("connection reregister; token={:?}", self.token);
poll.reregister(
&self.sock,
self.token,
self.interest,
PollOpt::edge() | PollOpt::oneshot(),
).or_else(|e| {
error!("Failed to reregister {:?}, {:?}", self.token, e);
Err(e)
})
}
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// DashboardList : Your Datadog Dashboards.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DashboardList {
#[serde(rename = "author", skip_serializing_if = "Option::is_none")]
pub author: Option<Box<crate::models::Creator>>,
/// Date of creation of the dashboard list.
#[serde(rename = "created", skip_serializing_if = "Option::is_none")]
pub created: Option<String>,
/// The number of dashboards in the list.
#[serde(rename = "dashboard_count", skip_serializing_if = "Option::is_none")]
pub dashboard_count: Option<i64>,
/// The ID of the dashboard list.
#[serde(rename = "id", skip_serializing_if = "Option::is_none")]
pub id: Option<i64>,
/// Whether or not the list is in the favorites.
#[serde(rename = "is_favorite", skip_serializing_if = "Option::is_none")]
pub is_favorite: Option<bool>,
/// Date of last edition of the dashboard list.
#[serde(rename = "modified", skip_serializing_if = "Option::is_none")]
pub modified: Option<String>,
/// The name of the dashboard list.
#[serde(rename = "name")]
pub name: String,
/// The type of dashboard list.
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
pub _type: Option<String>,
}
impl DashboardList {
/// Your Datadog Dashboards.
pub fn new(name: String) -> DashboardList {
DashboardList {
author: None,
created: None,
dashboard_count: None,
id: None,
is_favorite: None,
modified: None,
name,
_type: None,
}
}
}
|
use crossterm::{execute, queue};
use std::io::{Stdout, Write};
pub type Result<T> = std::result::Result<T, crossterm::ErrorKind>;
pub fn read() -> Result<Event> {
match crossterm::event::read() {
Ok(r) => Ok(r.into()),
Err(e) => Err(e),
}
}
pub fn move_to(stdout: &mut Stdout, loc: (u16, u16)) -> Result<()> {
queue!(stdout, crossterm::cursor::MoveTo(loc.0, loc.1))?;
Ok(())
}
pub fn enter_raw_mode(stdout: &mut Stdout) -> Result<()> {
crossterm::terminal::enable_raw_mode()?;
execute!(
stdout,
crossterm::terminal::EnterAlternateScreen,
crossterm::cursor::Show,
crossterm::cursor::MoveTo(0, 0),
crossterm::style::ResetColor,
)?;
Ok(())
}
pub fn exit_raw_mode(stdout: &mut Stdout) -> Result<()> {
execute!(
stdout,
crossterm::terminal::LeaveAlternateScreen,
crossterm::style::ResetColor,
)?;
crossterm::terminal::disable_raw_mode()?;
Ok(())
}
pub fn terminal_size() -> Result<(u16, u16)> {
Ok(crossterm::terminal::size()?)
}
pub fn render(stdout: &mut Stdout, width: &u16, grid: &[char], queued: &[usize]) -> Result<()> {
let mut slice: String;
queue!(
stdout,
crossterm::cursor::Hide,
crossterm::cursor::SavePosition
)?;
for line_num in queued {
slice = grid[*line_num..*width as usize + line_num].iter().collect();
queue!(
stdout,
crossterm::cursor::MoveTo(0, *line_num as u16 / width),
crossterm::style::Print(slice)
)?;
}
queue!(
stdout,
crossterm::cursor::Show,
crossterm::cursor::RestorePosition
)?;
stdout.flush()?;
Ok(())
}
pub fn poll(timeout: std::time::Duration) -> Result<bool> {
Ok(crossterm::event::poll(timeout)?)
}
#[derive(Eq, PartialEq, Hash, Clone)]
pub enum Direction {
Up(u16),
Down(u16),
Left(u16),
Right(u16),
}
#[derive(Eq, PartialEq, Hash, Clone)]
pub enum EditorEvent {
// Cursor Movement,
Cursor(Direction),
// Scroll Take 2 Direction's (Scroll Direction, Cursor Direction)
Scroll(Direction, Direction),
// Change Modes,
ModeNormal,
ModeCommand,
ModeInsert,
// Exit Program,
Quit,
}
pub enum Event {
Key(KeyEvent),
Mouse, //(MouseEvent), TODO: This Needs to hold a Mouse Event
Resize(u16, u16),
}
impl From<crossterm::event::Event> for Event {
fn from(event: crossterm::event::Event) -> Self {
match event {
crossterm::event::Event::Key(k) => Event::Key(k.into()),
crossterm::event::Event::Mouse(_) => Event::Mouse,
crossterm::event::Event::Resize(w, h) => Event::Resize(w, h),
}
}
}
#[derive(Eq, PartialEq, Hash)]
pub struct KeyEvent {
pub code: KeyCode,
pub modifier: KeyModifier,
}
impl KeyEvent {
pub fn new(code: KeyCode, modifier: KeyModifier) -> Self {
Self { code, modifier }
}
}
impl From<crossterm::event::KeyEvent> for KeyEvent {
fn from(key: crossterm::event::KeyEvent) -> Self {
let code = match key.code {
crossterm::event::KeyCode::Backspace => KeyCode::Backspace,
crossterm::event::KeyCode::Enter => KeyCode::Enter,
crossterm::event::KeyCode::Left => KeyCode::Left,
crossterm::event::KeyCode::Right => KeyCode::Right,
crossterm::event::KeyCode::Up => KeyCode::Up,
crossterm::event::KeyCode::Down => KeyCode::Down,
crossterm::event::KeyCode::Home => KeyCode::Home,
crossterm::event::KeyCode::End => KeyCode::End,
crossterm::event::KeyCode::PageUp => KeyCode::PageUp,
crossterm::event::KeyCode::PageDown => KeyCode::PageDown,
crossterm::event::KeyCode::Tab => KeyCode::Tab,
crossterm::event::KeyCode::BackTab => KeyCode::BackTab,
crossterm::event::KeyCode::Delete => KeyCode::Delete,
crossterm::event::KeyCode::Insert => KeyCode::Insert,
crossterm::event::KeyCode::F(n) => KeyCode::F(n),
crossterm::event::KeyCode::Char(c) => KeyCode::Char(c),
crossterm::event::KeyCode::Null => KeyCode::Null,
crossterm::event::KeyCode::Esc => KeyCode::Esc,
};
let modifier = match key.modifiers {
crossterm::event::KeyModifiers::CONTROL => KeyModifier::Control,
crossterm::event::KeyModifiers::ALT => KeyModifier::Alt,
crossterm::event::KeyModifiers::SHIFT => KeyModifier::Shift,
crossterm::event::KeyModifiers::NONE => KeyModifier::NONE,
_ => KeyModifier::NONE,
};
Self { code, modifier }
}
}
#[derive(Eq, PartialEq, Hash)]
pub enum KeyCode {
Backspace,
Enter,
Left,
Right,
Up,
Down,
Home,
End,
PageUp,
PageDown,
Tab,
BackTab,
Delete,
Insert,
F(u8),
Char(char),
Null,
Esc,
}
#[derive(Eq, PartialEq, Hash)]
pub enum KeyModifier {
Shift,
Alt,
Control,
NONE,
}
|
#[macro_use]
extern crate clap;
extern crate monolith;
use clap::{App, Arg};
use monolith::html::{html_to_dom, print_dom, walk_and_embed_assets};
use monolith::http::{is_valid_url, retrieve_asset};
fn main() {
let command = App::new("monolith")
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.arg(
Arg::with_name("url")
.required(true)
.takes_value(true)
.index(1)
.help("URL to download"),
)
.args_from_usage("-j, --no-js 'Excludes JavaScript'")
.args_from_usage("-i, --no-images 'Removes images'")
.get_matches();
// Process the command
let arg_target = command.value_of("url").unwrap();
let opt_no_js = command.is_present("no-js");
let opt_no_img = command.is_present("no-images");
if is_valid_url(arg_target) {
let data = retrieve_asset(&arg_target, false, "");
let dom = html_to_dom(&data.unwrap());
walk_and_embed_assets(&arg_target, &dom.document, opt_no_js, opt_no_img);
print_dom(&dom.document);
println!(); // Ensure newline at end of output
}
}
|
use std::cmp::Ordering;
use std::collections::HashSet;
use std::fmt;
const INPUT: &str = include_str!("../input");
const MAX_DISTANCE: usize = 10_000;
const UPPERCASE_LETTERS: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const LOWERCASE_LETTERS: &str = "abcdefghijklmnopqrstuvwxyz";
type Result<T> = ::std::result::Result<T, Box<dyn ::std::error::Error>>;
fn main() -> Result<()> {
let parsed_input = parse_input(INPUT)?;
println!("{}", find_part_one_solution(&parsed_input));
println!("{}", find_part_two_solution(&parsed_input, MAX_DISTANCE));
Ok(())
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
struct Point {
x: usize,
y: usize,
}
impl Point {
fn distance_to(&self, other: &Point) -> usize {
let x_distance = if self.x > other.x {
self.x - other.x
} else {
other.x - self.x
};
let y_distance = if self.y > other.y {
self.y - other.y
} else {
other.y - self.y
};
x_distance + y_distance
}
}
#[derive(Debug)]
struct GridCoordinate {
id: usize,
point: Point,
}
struct Grid {
data: Vec<Vec<Option<usize>>>,
x_offset: usize,
y_offset: usize,
coordinates: Vec<GridCoordinate>,
}
impl Grid {
fn from_points(points: &[Point]) -> Self {
let min_x = points.iter().map(|p| p.x).min().unwrap();
let max_x = points.iter().map(|p| p.x).max().unwrap();
let min_y = points.iter().map(|p| p.y).min().unwrap();
let max_y = points.iter().map(|p| p.y).max().unwrap();
let mut data = vec![vec![None; max_x - min_x + 1]; max_y - min_y + 1];
for (index, p) in points.iter().enumerate() {
let Point { x, y } = *p;
data[y - min_y][x - min_x] = Some(index);
}
let coordinates = points
.iter()
.enumerate()
.map(|(index, &point)| GridCoordinate { id: index, point })
.collect();
Grid {
data,
x_offset: min_x,
y_offset: min_y,
coordinates,
}
}
fn fill_areas(&mut self) {
for (i, row) in self.data.iter_mut().enumerate() {
for (j, value) in row.iter_mut().enumerate() {
if value.is_some() {
continue;
}
let current_point = Point {
x: j + self.x_offset,
y: i + self.y_offset,
};
let closest_coordinate = self.coordinates.iter().min_by_strict(|a, b| {
a.point
.distance_to(¤t_point)
.cmp(&b.point.distance_to(¤t_point))
});
*value = closest_coordinate.map(|c| c.id);
}
}
}
fn has_area_reaching_edge(&self, c: &GridCoordinate) -> bool {
let first_column = self.data.iter().map(|row| &row[0]);
let last_column = self.data.iter().map(|row| &row[row.len() - 1]);
let first_row = self.data[0].iter();
let last_row = self.data[self.data.len() - 1].iter();
let edge_points: HashSet<_> = first_column
.chain(last_column)
.chain(first_row)
.chain(last_row)
.filter_map(|v| *v) // Filter out None and map Some(value) to value
.collect();
edge_points.contains(&c.id)
}
fn has_coordinate_at(&self, point: &Point) -> bool {
self.coordinates
.iter()
.map(|c| c.point)
.any(|p| *point == p)
}
fn count_points_with_id(&self, id: usize) -> usize {
self.data
.iter()
.map(|row| row.iter().filter(|&&value| value == Some(id)).count())
.sum()
}
fn count_points_with_max_total_coordinate_distance(&self, max_distance: usize) -> usize {
let mut count = 0;
for (i, row) in self.data.iter().enumerate() {
for j in 0..row.len() {
let current_point = Point {
x: j + self.x_offset,
y: i + self.y_offset,
};
let total_coordinate_distance: usize = self
.coordinates
.iter()
.map(|c| current_point.distance_to(&c.point))
.sum();
if total_coordinate_distance < max_distance {
count += 1;
}
}
}
count
}
}
impl fmt::Debug for Grid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Grid {{ x_offset: {:?}, y_offset: {:?}, coordinates: {:?}, data: \n\n ",
self.x_offset, self.y_offset, self.coordinates
)?;
for column_number in self.x_offset..self.x_offset + self.data[0].len() {
write!(f, "{} ", column_number)?;
}
writeln!(f)?;
for (i, row) in self.data.iter().enumerate() {
let y = i + self.y_offset;
write!(f, "{} ", y)?;
for (j, value) in row.iter().enumerate() {
let x = j + self.x_offset;
write!(
f,
"{} ",
match value {
Some(i) => {
let letters = if self.has_coordinate_at(&Point { x, y }) {
UPPERCASE_LETTERS
} else {
LOWERCASE_LETTERS
};
letters.chars().nth(*i).unwrap_or('*')
}
None => '.',
}
)?;
}
writeln!(f)?;
}
write!(f, "\n}}")
}
}
trait MinByStrictExt: Iterator {
/// Returns the element that has the minimum value.
///
/// If several elements are equally minimum, None is returned.
/// If the iterator is empty, None is returned.
fn min_strict(self) -> Option<Self::Item>
where
Self: Sized,
Self::Item: Ord,
{
self.min_by_strict(|a, b| a.cmp(b))
}
/// Returns the element that gives the minimum value with respect to the specified comparison function.
///
/// If several elements are equally minimum, None is returned.
/// If the iterator is empty, None is returned.
fn min_by_strict<F>(self, mut compare: F) -> Option<Self::Item>
where
F: FnMut(&Self::Item, &Self::Item) -> Ordering,
Self: Sized,
{
let (min, count) = self.fold((None, 0), |(current_min, count), item| match current_min {
None => (Some(item), 1),
Some(min) => match compare(&item, &min) {
Ordering::Less => (Some(item), 1),
Ordering::Equal => (Some(min), count + 1),
Ordering::Greater => (Some(min), count),
},
});
if count == 1 {
min
} else {
None
}
}
}
impl<I: Iterator> MinByStrictExt for I {}
fn parse_input(input: &str) -> Result<Vec<Point>> {
input
.trim()
.split('\n')
.map(|line| {
let parsed_line: Result<Vec<_>> = line
.split(", ")
.map(|s| s.parse().map_err(Box::from))
.collect();
match parsed_line {
Ok(values) => Ok(Point {
x: values[0],
y: values[1],
}),
Err(e) => Err(e),
}
})
.collect()
}
fn find_part_one_solution(points: &[Point]) -> usize {
let mut grid = Grid::from_points(points);
grid.fill_areas();
grid.coordinates
.iter()
.filter(|c| !grid.has_area_reaching_edge(&c))
.map(|c| grid.count_points_with_id(c.id))
.max()
.expect("No solution found")
}
fn find_part_two_solution(points: &[Point], max_distance: usize) -> usize {
let grid = Grid::from_points(points);
grid.count_points_with_max_total_coordinate_distance(max_distance)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn it_parses_input_correctly() {
let sample_input = "1, 1\n1, 6\n8, 3\n3, 4\n5, 5\n8, 9\n";
assert_eq!(parse_input(sample_input).unwrap(), get_sample_input());
}
#[test]
fn it_finds_correct_part_one_solution() {
let sample_input = get_sample_input();
assert_eq!(find_part_one_solution(&sample_input), 17);
}
#[test]
fn it_finds_correct_part_two_solution() {
let sample_input = get_sample_input();
assert_eq!(find_part_two_solution(&sample_input, 32), 16);
}
#[test]
fn point_distance_to_returns_correct_result() {
let a = Point { x: 0, y: 0 };
let b = Point { x: 1, y: 1 };
let c = Point { x: 5, y: 10 };
assert_eq!(a.distance_to(&b), 2);
assert_eq!(a.distance_to(&c), 15);
assert_eq!(b.distance_to(&a), 2);
assert_eq!(b.distance_to(&c), 13);
}
#[test]
fn min_by_strict_returns_correct_result() {
let a = [1, 2, 3];
let b = [1, 1, 3];
let c: Vec<i32> = vec![];
let d = [3, 3, 1];
assert_eq!(a.iter().min_by_strict(|a, b| a.cmp(&b)), Some(&1));
assert_eq!(b.iter().min_by_strict(|a, b| a.cmp(&b)), None);
assert_eq!(c.iter().min_by_strict(|a, b| a.cmp(&b)), None);
assert_eq!(d.iter().min_by_strict(|a, b| a.cmp(&b)), Some(&1));
}
fn get_sample_input() -> [Point; 6] {
[
Point { x: 1, y: 1 },
Point { x: 1, y: 6 },
Point { x: 8, y: 3 },
Point { x: 3, y: 4 },
Point { x: 5, y: 5 },
Point { x: 8, y: 9 },
]
}
}
|
use bytes::Bytes;
use futures::Future;
use tokio::sync::{broadcast, mpsc};
use tokio_stream::{wrappers::ReceiverStream, StreamExt, StreamMap};
use tracing::error;
use uuid::Uuid;
use crate::broadcast_stream::BroadcastStream;
use crate::connection::{
DataStream,
Message::{self, *},
NewConnection,
};
const CHANNEL_CAPACITY: usize = 10;
pub struct Coordinator {
incoming: StreamMap<Uuid, ReceiverStream<Message>>,
broadcast_sender: broadcast::Sender<(Uuid, Bytes)>,
}
impl Coordinator {
pub fn new() -> Coordinator {
let (sender, _) = broadcast::channel(CHANNEL_CAPACITY);
Coordinator {
incoming: StreamMap::new(),
broadcast_sender: sender,
}
}
pub async fn run(mut self) {
while let Some((sender, message)) = self.incoming.next().await {
match message {
Data(bytes) => {
if let Err(err) = self.broadcast_sender.send((sender, bytes)) {
error!("Send error: {:?}", err);
}
}
NewConnection(nc) => {
tokio::spawn(self.add_connection(nc));
}
}
}
}
pub fn add_connection(
&mut self,
nc: NewConnection,
) -> impl Future<Output = ()> + Send + 'static {
let (input_sender, input_receiver) = mpsc::channel(CHANNEL_CAPACITY);
// Deliver messages to this Connection
let output_receiver = BroadcastStream::new(self.broadcast_sender.subscribe());
let id = Uuid::new_v4();
let output_receiver = filter_receiver(output_receiver, id);
// Listen for messages produced by this Connection
self.incoming
.insert(id, ReceiverStream::new(input_receiver));
// Return the Connection future
nc(input_sender, output_receiver)
}
}
pub fn filter_receiver(receiver: BroadcastStream<(Uuid, Bytes)>, id: Uuid) -> DataStream {
Box::new(receiver.filter_map(move |received| {
let (msg_id, data) = received.ok()?;
if msg_id == id {
None
} else {
Some(data)
}
}))
}
#[cfg(test)]
mod tests {
use futures::stream;
use tokio::join;
use crate::connection::*;
use crate::coordinator::*;
#[tokio::test]
async fn no_conns_succeeds() {
let c = Coordinator::new();
c.run().await;
}
#[tokio::test]
async fn send_succeeds() {
let mut coord = Coordinator::new();
let send_stream = Box::pin(stream::once(async { Data(Bytes::from("somestr")) }));
let (send1, mut recv1) = futures::channel::mpsc::unbounded();
let (send2, mut recv2) = futures::channel::mpsc::unbounded();
let conn1 = coord.add_connection(stream_connection::new(send_stream, send1));
let conn2 = coord.add_connection(stream_connection::new(stream::empty(), send2));
let (_, _, _, data1, data2) = join!(conn1, conn2, coord.run(), recv1.next(), recv2.next());
assert_eq!(data1, None);
assert_eq!(data2, Some(Bytes::from("somestr")));
}
}
|
fn main() {
cbm8032_to_vulkan::run();
}
|
use component::{Component, Position};
use entity::factory::FactoryEntities;
mod _const;
mod component;
mod entity;
mod system;
fn main() {
let mut factory_entities = FactoryEntities::new();
let character = factory_entities.create_character();
let character_position = system::position::get(character);
system::print(&Component::Position(character_position.clone()));
let mut_character_position: &mut Position = system::position::get_mutable(character);
let new_character_position = Position { x: 6, y: 66 };
system::position::move_vec(mut_character_position, &new_character_position);
system::position::move_frontward(mut_character_position, None);
system::position::move_left(mut_character_position, None);
let character_position = system::position::get(character);
system::print(&Component::Position(character_position.clone()));
let mut_character_health = system::health::get_mutable(character);
system::health::hit_once(mut_character_health, None);
let character_health = system::health::get(character);
system::print(&Component::Health(character_health.clone()));
}
|
use either::Either;
use itertools::Itertools;
use llvm_ir::function::{FunctionAttribute, ParameterAttribute};
use llvm_ir::instruction;
use llvm_ir::module::{Alignment, Endianness, Mangling, PointerLayout};
use llvm_ir::terminator;
use llvm_ir::types::{FPType, NamedStructDef, Typed};
#[cfg(feature = "llvm-9-or-greater")]
use llvm_ir::HasDebugLoc;
use llvm_ir::{
Constant, ConstantRef, Instruction, IntPredicate, Module, Name, Operand, Terminator, Type,
};
use std::convert::TryInto;
use std::path::{Path, PathBuf};
fn init_logging() {
// capture log messages with test harness
let _ = env_logger::builder().is_test(true).try_init();
}
const BC_DIR: &str = "tests/basic_bc/";
// Test against bitcode compiled with the same version of LLVM
fn llvm_bc_dir() -> PathBuf {
if cfg!(feature = "llvm-8") {
Path::new(BC_DIR).join("llvm8")
} else if cfg!(feature = "llvm-9") {
Path::new(BC_DIR).join("llvm9")
} else if cfg!(feature = "llvm-10") {
Path::new(BC_DIR).join("llvm10")
} else if cfg!(feature = "llvm-11") {
Path::new(BC_DIR).join("llvm11")
} else if cfg!(feature = "llvm-12") {
Path::new(BC_DIR).join("llvm12")
} else if cfg!(feature = "llvm-13") {
Path::new(BC_DIR).join("llvm13")
} else if cfg!(feature = "llvm-14") {
Path::new(BC_DIR).join("llvm14")
} else if cfg!(feature = "llvm-15") {
Path::new(BC_DIR).join("llvm15")
} else {
unimplemented!("new llvm version?")
}
}
// Test against bitcode compiled with the same version of LLVM
fn cxx_llvm_bc_dir() -> PathBuf {
if cfg!(feature = "llvm-8") {
Path::new(BC_DIR).join("cxx-llvm8")
} else if cfg!(feature = "llvm-9") {
Path::new(BC_DIR).join("cxx-llvm9")
} else if cfg!(feature = "llvm-10") {
Path::new(BC_DIR).join("cxx-llvm10")
} else if cfg!(feature = "llvm-11") {
Path::new(BC_DIR).join("cxx-llvm11")
} else if cfg!(feature = "llvm-12") {
Path::new(BC_DIR).join("cxx-llvm12")
} else if cfg!(feature = "llvm-13") {
Path::new(BC_DIR).join("cxx-llvm13")
} else if cfg!(feature = "llvm-14") {
Path::new(BC_DIR).join("cxx-llvm14")
} else if cfg!(feature = "llvm-15") {
Path::new(BC_DIR).join("cxx-llvm15")
} else {
unimplemented!("new llvm version?")
}
}
fn rust_bc_dir() -> PathBuf {
Path::new(BC_DIR).join("rust")
}
#[test]
fn hellobc() {
init_logging();
let path = llvm_bc_dir().join("hello.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
assert_eq!(&module.name, &path.to_str().unwrap());
assert_eq!(module.source_file_name, "hello.c");
#[cfg(feature = "llvm-10-or-lower")]
assert_eq!(
module.target_triple,
Some("x86_64-apple-macosx10.16.0".into())
);
#[cfg(any(feature = "llvm-11", feature = "llvm-12", feature = "llvm-13"))]
assert_eq!(
module.target_triple,
Some("x86_64-apple-macosx11.0.0".into())
);
#[cfg(feature = "llvm-14-or-greater")]
assert_eq!(
module.target_triple,
Some("x86_64-apple-macosx12.0.0".into())
);
assert_eq!(module.functions.len(), 1);
let func = &module.functions[0];
assert_eq!(func.name, "main");
assert_eq!(func.parameters.len(), 0);
assert_eq!(func.is_var_arg, false);
assert_eq!(func.return_type, module.types.int(32));
assert_eq!(func.basic_blocks.len(), 1);
let bb = &func.basic_blocks[0];
assert_eq!(bb.name, Name::Number(0));
assert_eq!(bb.instrs.len(), 0);
let ret: &terminator::Ret = &bb
.term
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Terminator should be a Ret but is {:?}", &bb.term));
assert_eq!(
ret.return_operand,
Some(Operand::ConstantOperand(ConstantRef::new(Constant::Int {
bits: 32,
value: 0
})))
);
assert_eq!(&ret.to_string(), "ret i32 0");
#[cfg(feature = "llvm-9-or-greater")]
{
// this file was compiled without debuginfo, so nothing should have a debugloc
assert_eq!(func.debugloc, None);
assert_eq!(ret.debugloc, None);
}
}
// this test relates to the version of the file compiled with debuginfo
#[cfg(feature = "llvm-9-or-greater")]
#[test]
fn hellobcg() {
init_logging();
let path = llvm_bc_dir().join("hello.bc-g");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
assert_eq!(&module.name, &path.to_str().unwrap());
assert_eq!(module.source_file_name, "hello.c");
let debug_filename = "hello.c";
let debug_directory = "/Users/craig/llvm-ir/tests/basic_bc"; // this is what appears in the checked-in copy of hello.bc-g
let func = &module.functions[0];
assert_eq!(func.name, "main");
let debugloc = func
.get_debug_loc()
.as_ref()
.expect("Expected main() to have a debugloc");
assert_eq!(debugloc.line, 3);
assert_eq!(debugloc.col, None);
assert_eq!(debugloc.filename, debug_filename);
assert_eq!(
debugloc.directory.as_ref().map(|s| s.as_str()),
Some(debug_directory)
);
let bb = &func.basic_blocks[0];
let ret: &terminator::Ret = &bb
.term
.clone()
.try_into()
.unwrap_or_else(|_| panic!("Terminator should be a Ret but is {:?}", &bb.term));
let debugloc = ret
.get_debug_loc()
.as_ref()
.expect("expected the Ret to have a debugloc");
assert_eq!(debugloc.line, 4);
assert_eq!(debugloc.col, Some(3));
assert_eq!(debugloc.filename, debug_filename);
assert_eq!(
debugloc.directory.as_ref().map(|s| s.as_str()),
Some(debug_directory)
);
assert_eq!(&ret.to_string(), "ret i32 0 (with debugloc)");
}
#[test]
#[allow(clippy::cognitive_complexity)]
fn loopbc() {
init_logging();
let path = llvm_bc_dir().join("loop.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
// get function and check info on it
assert_eq!(module.functions.len(), 1);
let func = &module.functions[0];
assert_eq!(func.name, "loop");
assert_eq!(func.parameters.len(), 2);
assert_eq!(func.is_var_arg, false);
assert_eq!(func.return_type, module.types.void());
assert_eq!(
module.type_of(func),
module.types.func_type(
module.types.void(),
vec![module.types.i32(), module.types.i32()],
false,
)
);
assert_eq!(module.get_func_by_name("loop"), Some(func));
// get parameters and check info on them
let param0 = &func.parameters[0];
let param1 = &func.parameters[1];
assert_eq!(param0.name, Name::Number(0));
assert_eq!(param1.name, Name::Number(1));
assert_eq!(param0.ty, module.types.i32());
assert_eq!(param1.ty, module.types.i32());
assert_eq!(module.type_of(param0), module.types.i32());
assert_eq!(module.type_of(param1), module.types.i32());
// get basic blocks and check their names
// different LLVM versions end up with different numbers of basic blocks for this function
#[cfg(feature = "llvm-9-or-lower")]
let bbs = {
assert_eq!(func.basic_blocks.len(), 6);
let bb2 = &func.basic_blocks[0];
let bb7 = &func.basic_blocks[1];
let bb10 = &func.basic_blocks[2];
let bb14 = &func.basic_blocks[3];
let bb19 = &func.basic_blocks[4];
let bb22 = &func.basic_blocks[5];
assert_eq!(bb2.name, Name::Number(2));
assert_eq!(bb7.name, Name::Number(7));
assert_eq!(bb10.name, Name::Number(10));
assert_eq!(bb14.name, Name::Number(14));
assert_eq!(bb19.name, Name::Number(19));
assert_eq!(bb22.name, Name::Number(22));
assert_eq!(func.get_bb_by_name(&Name::Number(2)), Some(bb2));
assert_eq!(func.get_bb_by_name(&Name::Number(19)), Some(bb19));
vec![bb2, bb7, bb10, bb14, bb19, bb22]
};
#[cfg(feature = "llvm-10")]
let bbs = {
assert_eq!(func.basic_blocks.len(), 4);
let bb2 = &func.basic_blocks[0];
let bb7 = &func.basic_blocks[1];
let bb12 = &func.basic_blocks[2];
let bb21 = &func.basic_blocks[3];
assert_eq!(bb2.name, Name::Number(2));
assert_eq!(bb7.name, Name::Number(7));
assert_eq!(bb12.name, Name::Number(12));
assert_eq!(bb21.name, Name::Number(21));
assert_eq!(func.get_bb_by_name(&Name::Number(2)), Some(bb2));
assert_eq!(func.get_bb_by_name(&Name::Number(12)), Some(bb12));
vec![bb2, bb7, bb12, bb21]
};
#[cfg(feature = "llvm-11")]
let bbs = {
assert_eq!(func.basic_blocks.len(), 4);
let bb2 = &func.basic_blocks[0];
let bb7 = &func.basic_blocks[1];
let bb14 = &func.basic_blocks[2];
let bb24 = &func.basic_blocks[3];
assert_eq!(bb2.name, Name::Number(2));
assert_eq!(bb7.name, Name::Number(7));
assert_eq!(bb14.name, Name::Number(14));
assert_eq!(bb24.name, Name::Number(24));
assert_eq!(func.get_bb_by_name(&Name::Number(2)), Some(bb2));
assert_eq!(func.get_bb_by_name(&Name::Number(14)), Some(bb14));
vec![bb2, bb7, bb14, bb24]
};
#[cfg(feature = "llvm-12")]
let bbs = {
assert_eq!(func.basic_blocks.len(), 8); // LLVM 12+ seems to do some unrolling in this example that previous LLVMs didn't
let bb2 = &func.basic_blocks[0];
let bb7 = &func.basic_blocks[1];
let bb12 = &func.basic_blocks[2];
let bb17 = &func.basic_blocks[3];
let bb19 = &func.basic_blocks[4];
let bb47 = &func.basic_blocks[7];
// actually have 8 BBs, but we only use the first five and the last one
assert_eq!(bb2.name, Name::Number(2));
assert_eq!(bb7.name, Name::Number(7));
assert_eq!(bb12.name, Name::Number(12));
assert_eq!(bb17.name, Name::Number(17));
assert_eq!(bb19.name, Name::Number(19));
assert_eq!(bb47.name, Name::Number(47));
vec![bb2, bb7, bb12, bb17, bb19, bb47]
};
#[cfg(feature = "llvm-13")]
let bbs = {
assert_eq!(func.basic_blocks.len(), 9);
let bb2 = &func.basic_blocks[0];
let bb6 = &func.basic_blocks[1];
let bb12 = &func.basic_blocks[3];
let bb17 = &func.basic_blocks[4];
let bb19 = &func.basic_blocks[5];
let bb47 = &func.basic_blocks[8];
// actually have 9 BBs, but we only use these selected 6
assert_eq!(bb2.name, Name::Number(2));
assert_eq!(bb6.name, Name::Number(6));
assert_eq!(bb12.name, Name::Number(12));
assert_eq!(bb17.name, Name::Number(17));
assert_eq!(bb19.name, Name::Number(19));
assert_eq!(bb47.name, Name::Number(47));
vec![bb2, bb6, bb12, bb17, bb19, bb47]
};
#[cfg(feature = "llvm-14")]
let bbs = {
assert_eq!(func.basic_blocks.len(), 8);
let bb2 = &func.basic_blocks[0];
let bb7 = &func.basic_blocks[1];
let bb11 = &func.basic_blocks[2];
let bb16 = &func.basic_blocks[3];
let bb18 = &func.basic_blocks[4];
let bb46 = &func.basic_blocks[7];
// actually have 8 BBs, but we only use the first five and the last one
assert_eq!(bb2.name, Name::Number(2));
assert_eq!(bb7.name, Name::Number(7));
assert_eq!(bb11.name, Name::Number(11));
assert_eq!(bb16.name, Name::Number(16));
assert_eq!(bb18.name, Name::Number(18));
assert_eq!(bb46.name, Name::Number(46));
vec![bb2, bb7, bb11, bb16, bb18, bb46]
};
#[cfg(feature = "llvm-15-or-greater")]
let bbs = {
assert_eq!(func.basic_blocks.len(), 8);
let bb2 = &func.basic_blocks[0];
let bb7 = &func.basic_blocks[1];
let bb11 = &func.basic_blocks[2];
let bb16 = &func.basic_blocks[3];
let bb18 = &func.basic_blocks[4];
let bb46 = &func.basic_blocks[7];
// actually have 8 BBs, but we only use the first five and the last one
assert_eq!(bb2.name, Name::Number(2));
assert_eq!(bb7.name, Name::Number(6));
assert_eq!(bb11.name, Name::Number(9));
assert_eq!(bb16.name, Name::Number(14));
assert_eq!(bb18.name, Name::Number(16));
assert_eq!(bb46.name, Name::Number(44));
vec![bb2, bb7, bb11, bb16, bb18, bb46]
};
// check details about the instructions in basic block %2
let alloca: &instruction::Alloca = &bbs[0].instrs[0]
.clone()
.try_into()
.expect("Should be an alloca");
assert_eq!(alloca.dest, Name::Number(3));
let allocated_type = module.types.array_of(module.types.i32(), 10);
assert_eq!(alloca.allocated_type, allocated_type);
assert_eq!(
alloca.num_elements,
Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 32, value: 1 })) // One element, which is an array of 10 elements. Not 10 elements, each of which are i32.
);
assert_eq!(alloca.alignment, 16);
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(
module.type_of(alloca),
module.types.pointer_to(allocated_type.clone()),
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(module.type_of(alloca), module.types.pointer());
assert_eq!(module.type_of(&alloca.num_elements), module.types.i32());
assert_eq!(&alloca.to_string(), "%3 = alloca [10 x i32], align 16");
#[cfg(feature = "llvm-14-or-lower")] // LLVM 15+ does not require bitcasts in this function
{
let bitcast: &instruction::BitCast = &bbs[0].instrs[1]
.clone()
.try_into()
.expect("Should be a bitcast");
assert_eq!(bitcast.dest, Name::Number(4));
assert_eq!(bitcast.to_type, module.types.pointer_to(module.types.i8()));
assert_eq!(
bitcast.operand,
Operand::LocalOperand {
name: Name::Number(3),
ty: module.types.pointer_to(allocated_type.clone())
}
);
assert_eq!(
module.type_of(bitcast),
module.types.pointer_to(module.types.i8())
);
assert_eq!(
module.type_of(&bitcast.operand),
module.types.pointer_to(allocated_type.clone())
);
assert_eq!(&bitcast.to_string(), "%4 = bitcast [10 x i32]* %3 to i8*");
}
#[cfg(feature = "llvm-14-or-lower")]
let lifetimestart: &instruction::Call = &bbs[0].instrs[2]
.clone()
.try_into()
.expect("Should be a call");
#[cfg(feature = "llvm-15-or-greater")]
let lifetimestart: &instruction::Call = &bbs[0].instrs[1]
.clone()
.try_into()
.expect("Should be a call");
if let Either::Right(Operand::ConstantOperand(cref)) = &lifetimestart.function {
if let Constant::GlobalReference { ref name, ref ty } = cref.as_ref() {
assert!(matches!(
module.type_of(&lifetimestart.function).as_ref(),
Type::PointerType { .. }
)); // lifetimestart.function should be a constant function pointer
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(name.as_str(), "llvm.lifetime.start.p0i8");
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(name.as_str(), "llvm.lifetime.start.p0");
if let Type::FuncType {
result_type,
param_types,
is_var_arg,
} = ty.as_ref()
{
assert_eq!(result_type, &module.types.void());
assert_eq!(
param_types,
&vec![
module.types.i64(),
#[cfg(feature = "llvm-14-or-lower")]
module.types.pointer_to(module.types.i8()),
#[cfg(feature = "llvm-15-or-greater")]
module.types.pointer(),
]
);
assert_eq!(*is_var_arg, false);
} else {
panic!("lifetimestart.function has unexpected type {:?}", ty);
}
} else {
panic!(
"lifetimestart.function not a GlobalReference as expected; it is actually another kind of Constant: {:?}",
cref
);
}
} else {
panic!(
"lifetimestart.function not a GlobalReference as expected; it is actually {:?}",
&lifetimestart.function
);
}
let arg0 = &lifetimestart
.arguments
.get(0)
.expect("Expected an argument 0");
let arg1 = &lifetimestart
.arguments
.get(1)
.expect("Expected an argument 1");
assert_eq!(
arg0.0,
Operand::ConstantOperand(ConstantRef::new(Constant::Int {
bits: 64,
value: 40
}))
);
#[cfg(feature = "llvm-14-or-lower")]
let arg1_expected_name = Name::Number(4);
#[cfg(feature = "llvm-15-or-greater")]
let arg1_expected_name = Name::Number(3);
#[cfg(feature = "llvm-14-or-lower")]
let arg1_expected_ty = module.types.pointer_to(module.types.i8());
#[cfg(feature = "llvm-15-or-greater")]
let arg1_expected_ty = module.types.pointer();
assert_eq!(
arg1.0,
Operand::LocalOperand {
name: arg1_expected_name,
ty: arg1_expected_ty,
}
);
assert_eq!(arg0.1, vec![]); // should have no parameter attributes
assert_eq!(arg1.1.len(), 1); // should have one parameter attribute
assert_eq!(lifetimestart.dest, None);
#[cfg(feature = "llvm-14-or-lower")]
let expected_fmt = "call @llvm.lifetime.start.p0i8(i64 40, i8* %4)";
#[cfg(feature = "llvm-15-or-greater")]
let expected_fmt = "call @llvm.lifetime.start.p0(i64 40, ptr %3)";
assert_eq!(&lifetimestart.to_string(), expected_fmt);
#[cfg(feature = "llvm-14-or-lower")]
let memset: &instruction::Call = &bbs[0].instrs[3]
.clone()
.try_into()
.expect("Should be a call");
#[cfg(feature = "llvm-15-or-greater")]
let memset: &instruction::Call = &bbs[0].instrs[2]
.clone()
.try_into()
.expect("Should be a call");
if let Either::Right(Operand::ConstantOperand(cref)) = &memset.function {
if let Constant::GlobalReference { ref name, ref ty } = cref.as_ref() {
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(name.as_str(), "llvm.memset.p0i8.i64");
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(name.as_str(), "llvm.memset.p0.i64");
if let Type::FuncType {
result_type,
param_types,
is_var_arg,
} = ty.as_ref()
{
assert_eq!(result_type, &module.types.void());
assert_eq!(
param_types,
&vec![
#[cfg(feature = "llvm-14-or-lower")]
module.types.pointer_to(module.types.i8()),
#[cfg(feature = "llvm-15-or-greater")]
module.types.pointer(),
module.types.i8(),
module.types.i64(),
module.types.bool()
]
);
assert_eq!(*is_var_arg, false);
} else {
panic!("memset.function has unexpected type {:?}", ty);
}
} else {
panic!(
"memset.function not a GlobalReference as expected; it is actually another kind of Constant: {:?}",
cref
);
}
} else {
panic!(
"memset.function not a GlobalReference as expected; it is actually {:?}",
memset.function
);
}
assert_eq!(memset.arguments.len(), 4);
#[cfg(feature = "llvm-14-or-lower")]
let memset_arg0_expected_name = Name::Number(4);
#[cfg(feature = "llvm-15-or-greater")]
let memset_arg0_expected_name = Name::Number(3);
#[cfg(feature = "llvm-14-or-lower")]
let memset_arg0_expected_ty = module.types.pointer_to(module.types.i8());
#[cfg(feature = "llvm-15-or-greater")]
let memset_arg0_expected_ty = module.types.pointer();
assert_eq!(
memset.arguments[0].0,
Operand::LocalOperand {
name: memset_arg0_expected_name,
ty: memset_arg0_expected_ty,
}
);
assert_eq!(
memset.arguments[1].0,
Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 8, value: 0 }))
);
assert_eq!(
memset.arguments[2].0,
Operand::ConstantOperand(ConstantRef::new(Constant::Int {
bits: 64,
value: 40
}))
);
assert_eq!(
memset.arguments[3].0,
Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 1, value: 1 }))
);
assert_eq!(memset.arguments[0].1.len(), 2); // should have two parameter attributes
#[cfg(feature = "llvm-14-or-lower")]
let expected_fmt = "call @llvm.memset.p0i8.i64(i8* %4, i8 0, i64 40, i1 true)";
#[cfg(feature = "llvm-15-or-greater")]
let expected_fmt = "call @llvm.memset.p0.i64(ptr %3, i8 0, i64 40, i1 true)";
assert_eq!(&memset.to_string(), expected_fmt);
#[cfg(feature = "llvm-12-or-lower")]
{
let add: &instruction::Add = &bbs[0].instrs[4]
.clone()
.try_into()
.expect("Should be an add");
assert_eq!(
add.operand0,
Operand::LocalOperand {
name: Name::Number(1),
ty: module.types.i32()
}
);
assert_eq!(
add.operand1,
Operand::ConstantOperand(ConstantRef::new(Constant::Int {
bits: 32,
value: 0x0000_0000_FFFF_FFFF
}))
);
assert_eq!(add.dest, Name::Number(5));
assert_eq!(module.type_of(add), module.types.i32());
assert_eq!(&add.to_string(), "%5 = add i32 %1, i32 -1");
}
#[cfg(feature = "llvm-13")]
{
let add: &instruction::Add = &bbs[1].instrs[0]
.clone()
.try_into()
.expect("Should be an add");
assert_eq!(
add.operand0,
Operand::LocalOperand {
name: Name::Number(0),
ty: module.types.i32()
}
);
assert_eq!(
add.operand1,
Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 32, value: 3 }))
);
assert_eq!(add.dest, Name::Number(7));
assert_eq!(module.type_of(add), module.types.i32());
assert_eq!(&add.to_string(), "%7 = add i32 %0, i32 3");
}
#[cfg(feature = "llvm-14-or-greater")]
{
let add: &instruction::Add = &bbs[1].instrs[0]
.clone()
.try_into()
.expect("Should be an add");
assert_eq!(
add.operand0,
Operand::LocalOperand {
name: Name::Number(0),
ty: module.types.i32()
}
);
assert_eq!(
add.operand1,
Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 32, value: 3 }))
);
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(add.dest, Name::Number(8));
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(add.dest, Name::Number(7));
assert_eq!(module.type_of(add), module.types.i32());
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(&add.to_string(), "%8 = add i32 %0, i32 3");
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(&add.to_string(), "%7 = add i32 %0, i32 3");
}
#[cfg(feature = "llvm-12-or-lower")]
{
let icmp: &instruction::ICmp = &bbs[0].instrs[5]
.clone()
.try_into()
.expect("Should be an icmp");
assert_eq!(icmp.predicate, IntPredicate::ULT);
assert_eq!(
icmp.operand0,
Operand::LocalOperand {
name: Name::Number(5),
ty: module.types.i32()
}
);
assert_eq!(
icmp.operand1,
Operand::ConstantOperand(ConstantRef::new(Constant::Int {
bits: 32,
value: 10
}))
);
assert_eq!(module.type_of(icmp), module.types.bool());
assert_eq!(&icmp.to_string(), "%6 = icmp ult i32 %5, i32 10");
}
#[cfg(feature = "llvm-13")]
{
let icmp: &instruction::ICmp = &bbs[0].instrs[4]
.clone()
.try_into()
.expect("Should be an icmp");
assert_eq!(icmp.predicate, IntPredicate::SLT);
assert_eq!(
icmp.operand0,
Operand::LocalOperand {
name: Name::Number(1),
ty: module.types.i32()
}
);
assert_eq!(
icmp.operand1,
Operand::ConstantOperand(ConstantRef::new(Constant::Int {
bits: 32,
value: 11
}))
);
assert_eq!(module.type_of(icmp), module.types.bool());
assert_eq!(&icmp.to_string(), "%5 = icmp slt i32 %1, i32 11");
}
#[cfg(feature = "llvm-14-or-greater")]
{
#[cfg(feature = "llvm-14-or-lower")]
let icmp: &instruction::ICmp = &bbs[0].instrs[5]
.clone()
.try_into()
.expect("Should be an icmp");
#[cfg(feature = "llvm-15-or-greater")]
let icmp: &instruction::ICmp = &bbs[0].instrs[4]
.clone()
.try_into()
.expect("Should be an icmp");
assert_eq!(icmp.predicate, IntPredicate::ULT);
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(
icmp.operand0,
Operand::LocalOperand {
name: Name::Number(5),
ty: module.types.i32()
}
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(
icmp.operand0,
Operand::LocalOperand {
name: Name::Number(4),
ty: module.types.i32()
}
);
assert_eq!(
icmp.operand1,
Operand::ConstantOperand(ConstantRef::new(Constant::Int {
bits: 32,
value: 10
}))
);
assert_eq!(module.type_of(icmp), module.types.bool());
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(&icmp.to_string(), "%6 = icmp ult i32 %5, i32 10");
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(&icmp.to_string(), "%5 = icmp ult i32 %4, i32 10");
}
let condbr: &terminator::CondBr = &bbs[0].term.clone().try_into().expect("Should be a condbr");
#[cfg(feature = "llvm-12-or-lower")]
let expected_condition_op = Name::Number(6);
#[cfg(feature = "llvm-13")]
let expected_condition_op = Name::Number(5);
#[cfg(feature = "llvm-14")]
let expected_condition_op = Name::Number(6);
#[cfg(feature = "llvm-15-or-greater")]
let expected_condition_op = Name::Number(5);
assert_eq!(
condbr.condition,
Operand::LocalOperand {
name: expected_condition_op.clone(),
ty: module.types.bool()
}
);
#[cfg(feature = "llvm-12-or-lower")]
let expected_true_dest = Name::Number(7);
#[cfg(feature = "llvm-13")]
let expected_true_dest = Name::Number(6);
#[cfg(feature = "llvm-14")]
let expected_true_dest = Name::Number(7);
#[cfg(feature = "llvm-15-or-greater")]
let expected_true_dest = Name::Number(6);
assert_eq!(condbr.true_dest, expected_true_dest);
let expected_false_dest = if cfg!(feature = "llvm-9-or-lower") {
Name::Number(22)
} else if cfg!(feature = "llvm-10") {
Name::Number(21)
} else if cfg!(feature = "llvm-11") {
Name::Number(24)
} else if cfg!(feature = "llvm-12") || cfg!(feature = "llvm-13") {
Name::Number(47)
} else if cfg!(feature = "llvm-14") {
Name::Number(46)
} else {
Name::Number(44)
};
assert_eq!(condbr.false_dest, expected_false_dest);
assert_eq!(module.type_of(condbr), module.types.void());
assert_eq!(
&condbr.to_string(),
&format!(
"br i1 {}, label {}, label {}",
expected_condition_op,
expected_true_dest,
expected_false_dest,
),
);
// check details about certain instructions in basic block %7
// not sure why LLVM 10+ puts a ZExt here instead of SExt. Maybe it can prove it's equivalent?
// in LLVM 12+, the ZExt is in a different block
#[cfg(feature = "llvm-9-or-lower")]
let ext: &instruction::SExt = &bbs[1].instrs[1]
.clone()
.try_into()
.expect("Should be a SExt");
#[cfg(feature = "llvm-10")]
let ext: &instruction::ZExt = &bbs[1].instrs[1]
.clone()
.try_into()
.expect("Should be a ZExt");
#[cfg(feature = "llvm-11")]
let ext: &instruction::ZExt = &bbs[1].instrs[3]
.clone()
.try_into()
.expect("Should be a ZExt");
#[cfg(feature = "llvm-12-or-greater")]
let ext: &instruction::ZExt = &bbs[2].instrs[0]
.clone()
.try_into()
.expect("Should be a ZExt");
let ext_input = if cfg!(feature = "llvm-10-or-lower") {
Name::Number(1)
} else if cfg!(any(feature = "llvm-11", feature = "llvm-12")) {
Name::Number(10)
} else {
Name::Number(1)
};
let ext_dest = if cfg!(feature = "llvm-10-or-lower") {
Name::Number(9)
} else if cfg!(feature = "llvm-11") {
Name::Number(11)
} else if cfg!(feature = "llvm-12") || cfg!(feature = "llvm-13") {
Name::Number(13)
} else if cfg!(feature = "llvm-14") {
Name::Number(12)
} else {
Name::Number(10)
};
assert_eq!(
ext.operand,
Operand::LocalOperand {
name: ext_input,
ty: module.types.i32()
}
);
assert_eq!(ext.to_type, module.types.i64());
assert_eq!(ext.dest, ext_dest);
assert_eq!(module.type_of(ext), module.types.i64());
#[cfg(feature = "llvm-9-or-lower")]
assert_eq!(&ext.to_string(), "%9 = sext i32 %1 to i64");
#[cfg(feature = "llvm-10")]
assert_eq!(&ext.to_string(), "%9 = zext i32 %1 to i64");
#[cfg(feature = "llvm-11")]
assert_eq!(&ext.to_string(), "%11 = zext i32 %10 to i64");
#[cfg(feature = "llvm-12")]
assert_eq!(&ext.to_string(), "%13 = zext i32 %10 to i64");
#[cfg(feature = "llvm-13")]
assert_eq!(&ext.to_string(), "%13 = zext i32 %1 to i64");
#[cfg(feature = "llvm-14")]
assert_eq!(&ext.to_string(), "%12 = zext i32 %1 to i64");
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(&ext.to_string(), "%10 = zext i32 %1 to i64");
#[cfg(feature = "llvm-9-or-lower")]
{
// LLVM 10 and 11 don't have a Br in this function
let br: &terminator::Br = &bbs[1].term.clone().try_into().expect("Should be a Br");
assert_eq!(br.dest, Name::Number(10));
assert_eq!(&br.to_string(), "br label %10");
}
#[cfg(feature = "llvm-12-or-greater")]
{
let br: &terminator::Br = &bbs[3].term.clone().try_into().expect("Should be a Br");
#[cfg(any(feature = "llvm-12", feature = "llvm-13"))]
{
assert_eq!(br.dest, Name::Number(19));
assert_eq!(&br.to_string(), "br label %19");
}
#[cfg(feature = "llvm-14")]
{
assert_eq!(br.dest, Name::Number(18));
assert_eq!(&br.to_string(), "br label %18");
}
#[cfg(feature = "llvm-15-or-greater")]
{
assert_eq!(br.dest, Name::Number(16));
assert_eq!(&br.to_string(), "br label %16");
}
}
// check details about certain instructions in basic block %10 (LLVM 9-) / %12 (LLVM 10) / %14 (LLVM 11) / %19 (LLVM 12+)
#[cfg(feature = "llvm-11-or-lower")]
let phi: &instruction::Phi = &bbs[2].instrs[0]
.clone()
.try_into()
.expect("Should be a Phi");
#[cfg(feature = "llvm-12-or-greater")]
let phi: &instruction::Phi = &bbs[4].instrs[0]
.clone()
.try_into()
.expect("Should be a Phi");
let phi_dest = if cfg!(feature = "llvm-9-or-lower") {
Name::Number(11)
} else if cfg!(feature = "llvm-10") {
Name::Number(13)
} else if cfg!(feature = "llvm-11") {
Name::Number(15)
} else if cfg!(any(feature = "llvm-12", feature = "llvm-13")) {
Name::Number(20)
} else if cfg!(feature = "llvm-14") {
Name::Number(19)
} else {
Name::Number(17)
};
assert_eq!(phi.dest, phi_dest);
assert_eq!(phi.to_type, module.types.i64());
#[cfg(feature = "llvm-9-or-lower")]
assert_eq!(
phi.incoming_values,
vec![
(
Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 64, value: 0 })),
Name::Number(7)
),
(
Operand::LocalOperand {
name: Name::Number(20),
ty: module.types.i64()
},
Name::Number(19)
),
]
);
#[cfg(feature = "llvm-10")]
assert_eq!(
phi.incoming_values,
vec![
(
Operand::LocalOperand {
name: Name::Number(19),
ty: module.types.i64()
},
Name::Number(12)
),
(
Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 64, value: 1 })),
Name::Number(7)
),
]
);
#[cfg(feature = "llvm-11")]
assert_eq!(
phi.incoming_values,
vec![
(
Operand::LocalOperand {
name: Name::Number(22),
ty: module.types.i64()
},
Name::Number(14)
),
(
Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 64, value: 1 })),
Name::Number(7)
),
]
);
#[cfg(any(feature = "llvm-12", feature = "llvm-13"))]
assert_eq!(
phi.incoming_values,
vec![
(
Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 64, value: 1 })),
Name::Number(17)
),
(
Operand::LocalOperand {
name: Name::Number(34),
ty: module.types.i64()
},
Name::Number(19)
),
]
);
#[cfg(feature = "llvm-14")]
assert_eq!(
phi.incoming_values,
vec![
(
Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 64, value: 1 })),
Name::Number(16)
),
(
Operand::LocalOperand {
name: Name::Number(33),
ty: module.types.i64()
},
Name::Number(18)
),
]
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(
phi.incoming_values,
vec![
(
Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 64, value: 1 })),
Name::Number(14)
),
(
Operand::LocalOperand {
name: Name::Number(31),
ty: module.types.i64()
},
Name::Number(16)
),
]
);
#[cfg(feature = "llvm-9-or-lower")]
assert_eq!(
&phi.to_string(),
"%11 = phi i64 [ i64 0, %7 ], [ i64 %20, %19 ]"
);
#[cfg(feature = "llvm-10")]
assert_eq!(
&phi.to_string(),
"%13 = phi i64 [ i64 %19, %12 ], [ i64 1, %7 ]"
);
#[cfg(feature = "llvm-11")]
assert_eq!(
&phi.to_string(),
"%15 = phi i64 [ i64 %22, %14 ], [ i64 1, %7 ]"
);
#[cfg(any(feature = "llvm-12", feature = "llvm-13"))]
assert_eq!(
&phi.to_string(),
"%20 = phi i64 [ i64 1, %17 ], [ i64 %34, %19 ]"
);
#[cfg(feature = "llvm-14")]
assert_eq!(
&phi.to_string(),
"%19 = phi i64 [ i64 1, %16 ], [ i64 %33, %18 ]"
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(
&phi.to_string(),
"%17 = phi i64 [ i64 1, %14 ], [ i64 %31, %16 ]"
);
#[cfg(feature = "llvm-11-or-lower")]
let gep: &instruction::GetElementPtr = &bbs[2].instrs[1]
.clone()
.try_into()
.expect("Should be a gep");
#[cfg(feature = "llvm-12-or-greater")]
let gep: &instruction::GetElementPtr = &bbs[4].instrs[2]
.clone()
.try_into()
.expect("Should be a gep");
#[cfg(feature = "llvm-14-or-lower")]
let gep_addr_expected_ty = module.types.pointer_to(allocated_type.clone());
#[cfg(feature = "llvm-15-or-greater")]
let gep_addr_expected_ty = module.types.pointer();
assert_eq!(
gep.address,
Operand::LocalOperand {
name: Name::Number(3),
ty: gep_addr_expected_ty,
}
);
let gep_dest = if cfg!(feature = "llvm-9-or-lower") {
Name::Number(12)
} else if cfg!(feature = "llvm-10") {
Name::Number(14)
} else if cfg!(feature = "llvm-11") {
Name::Number(16)
} else if cfg!(feature = "llvm-12") || cfg!(feature = "llvm-13") {
Name::Number(22)
} else if cfg!(feature = "llvm-14") {
Name::Number(21)
} else {
Name::Number(19)
};
assert_eq!(gep.dest, gep_dest);
assert_eq!(gep.in_bounds, true);
let index = if cfg!(feature = "llvm-9-or-lower") {
Name::Number(11)
} else if cfg!(feature = "llvm-10") {
Name::Number(13)
} else if cfg!(feature = "llvm-11") {
Name::Number(15)
} else if cfg!(feature = "llvm-12") || cfg!(feature = "llvm-13") {
Name::Number(20)
} else if cfg!(feature = "llvm-14") {
Name::Number(19)
} else {
Name::Number(17)
};
assert_eq!(
gep.indices,
vec![
Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 64, value: 0 })),
Operand::LocalOperand {
name: index,
ty: module.types.i64()
},
]
);
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(
module.type_of(gep),
module.types.pointer_to(module.types.i32())
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(module.type_of(gep), module.types.pointer());
#[cfg(feature = "llvm-9-or-lower")]
assert_eq!(
&gep.to_string(),
"%12 = getelementptr inbounds [10 x i32]* %3, i64 0, i64 %11"
);
#[cfg(feature = "llvm-10")]
assert_eq!(
&gep.to_string(),
"%14 = getelementptr inbounds [10 x i32]* %3, i64 0, i64 %13"
);
#[cfg(feature = "llvm-11")]
assert_eq!(
&gep.to_string(),
"%16 = getelementptr inbounds [10 x i32]* %3, i64 0, i64 %15"
);
#[cfg(any(feature = "llvm-12", feature = "llvm-13"))]
assert_eq!(
&gep.to_string(),
"%22 = getelementptr inbounds [10 x i32]* %3, i64 0, i64 %20"
);
#[cfg(feature = "llvm-14")]
assert_eq!(
&gep.to_string(),
"%21 = getelementptr inbounds [10 x i32]* %3, i64 0, i64 %19"
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(
&gep.to_string(),
"%19 = getelementptr inbounds ptr %3, i64 0, i64 %17"
);
#[cfg(feature = "llvm-11-or-lower")]
let store_inst = &bbs[2].instrs[2];
#[cfg(feature = "llvm-12-or-greater")]
let store_inst = &bbs[4].instrs[3];
let store: &instruction::Store = &store_inst.clone().try_into().expect("Should be a store");
let address = if cfg!(feature = "llvm-9-or-lower") {
Name::Number(12)
} else if cfg!(feature = "llvm-10") {
Name::Number(14)
} else if cfg!(feature = "llvm-11") {
Name::Number(16)
} else if cfg!(feature = "llvm-12") || cfg!(feature = "llvm-13") {
Name::Number(22)
} else if cfg!(feature = "llvm-14") {
Name::Number(21)
} else {
Name::Number(19)
};
#[cfg(feature = "llvm-14-or-lower")]
let address_ty = module.types.pointer_to(module.types.i32());
#[cfg(feature = "llvm-15-or-greater")]
let address_ty = module.types.pointer();
assert_eq!(
store.address,
Operand::LocalOperand {
name: address,
ty: address_ty,
}
);
#[cfg(feature = "llvm-12-or-lower")]
assert_eq!(
store.value,
Operand::LocalOperand {
name: Name::Number(8),
ty: module.types.i32()
}
);
#[cfg(feature = "llvm-13")]
assert_eq!(
store.value,
Operand::LocalOperand {
name: Name::Number(7),
ty: module.types.i32()
}
);
#[cfg(feature = "llvm-14")]
assert_eq!(
store.value,
Operand::LocalOperand {
name: Name::Number(8),
ty: module.types.i32()
}
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(
store.value,
Operand::LocalOperand {
name: Name::Number(7),
ty: module.types.i32()
}
);
assert_eq!(store.volatile, true);
assert_eq!(store.alignment, 4);
assert_eq!(module.type_of(store), module.types.void());
assert_eq!(store_inst.is_atomic(), false);
#[cfg(feature = "llvm-9-or-lower")]
assert_eq!(
&store.to_string(),
"store volatile i32 %8, i32* %12, align 4"
);
#[cfg(feature = "llvm-10")]
assert_eq!(
&store.to_string(),
"store volatile i32 %8, i32* %14, align 4"
);
#[cfg(feature = "llvm-11")]
assert_eq!(
&store.to_string(),
"store volatile i32 %8, i32* %16, align 4"
);
#[cfg(feature = "llvm-12")]
assert_eq!(
&store.to_string(),
"store volatile i32 %8, i32* %22, align 4"
);
#[cfg(feature = "llvm-13")]
assert_eq!(
&store.to_string(),
"store volatile i32 %7, i32* %22, align 4"
);
#[cfg(feature = "llvm-14")]
assert_eq!(
&store.to_string(),
"store volatile i32 %8, i32* %21, align 4"
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(
&store.to_string(),
"store volatile i32 %7, ptr %19, align 4"
);
// and finally other instructions of types we haven't seen yet
let load_inst: &Instruction = if cfg!(feature = "llvm-9-or-lower") {
&bbs[3].instrs[2]
} else if cfg!(feature = "llvm-10") {
&bbs[2].instrs[5]
} else if cfg!(feature = "llvm-11") {
&bbs[2].instrs[6]
} else {
&bbs[4].instrs[7]
};
let load: &instruction::Load = &load_inst.clone().try_into().expect("Should be a load");
let load_addr = if cfg!(feature = "llvm-10-or-lower") {
Name::Number(16)
} else if cfg!(feature = "llvm-11") {
Name::Number(19)
} else if cfg!(feature = "llvm-12") || cfg!(feature = "llvm-13") {
Name::Number(25)
} else if cfg!(feature = "llvm-14") {
Name::Number(24)
} else {
Name::Number(22)
};
#[cfg(feature = "llvm-14-or-lower")]
let load_addr_expected_ty = module.types.pointer_to(module.types.i32());
#[cfg(feature = "llvm-15-or-greater")]
let load_addr_expected_ty = module.types.pointer();
assert_eq!(
load.address,
Operand::LocalOperand {
name: load_addr,
ty: load_addr_expected_ty,
}
);
#[cfg(feature = "llvm-10-or-lower")]
assert_eq!(load.dest, Name::Number(17));
#[cfg(feature = "llvm-11")]
assert_eq!(load.dest, Name::Number(20));
#[cfg(any(feature = "llvm-12", feature = "llvm-13"))]
assert_eq!(load.dest, Name::Number(26));
#[cfg(feature = "llvm-14")]
assert_eq!(load.dest, Name::Number(25));
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(load.dest, Name::Number(23));
assert_eq!(load.volatile, true);
assert_eq!(load.alignment, 4);
assert_eq!(module.type_of(load), module.types.i32());
assert_eq!(load_inst.is_atomic(), false);
#[cfg(feature = "llvm-10-or-lower")]
assert_eq!(&load.to_string(), "%17 = load volatile i32* %16, align 4");
#[cfg(feature = "llvm-11")]
assert_eq!(&load.to_string(), "%20 = load volatile i32* %19, align 4");
#[cfg(any(feature = "llvm-12", feature = "llvm-13"))]
assert_eq!(&load.to_string(), "%26 = load volatile i32* %25, align 4");
#[cfg(feature = "llvm-14")]
assert_eq!(&load.to_string(), "%25 = load volatile i32* %24, align 4");
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(&load.to_string(), "%23 = load volatile i32, ptr %22, align 4");
let ret: &Terminator = if cfg!(feature = "llvm-9-or-lower") {
&bbs[5].term
} else if cfg!(feature = "llvm-10") || cfg!(feature = "llvm-11") {
&bbs[3].term
} else {
&bbs[5].term
};
let ret: &terminator::Ret = &ret.clone().try_into().expect("Should be a ret");
assert_eq!(ret.return_operand, None);
assert_eq!(module.type_of(ret), module.types.void());
assert_eq!(&ret.to_string(), "ret void");
}
#[test]
fn switchbc() {
init_logging();
let path = llvm_bc_dir().join("switch.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
assert_eq!(module.functions.len(), 1);
let func = &module.functions[0];
assert_eq!(func.name, "has_a_switch");
let bb = &func.basic_blocks[0];
let switch: &terminator::Switch = &bb.term.clone().try_into().expect("Should be a switch");
assert_eq!(
switch.operand,
Operand::LocalOperand {
name: Name::Number(0),
ty: module.types.i32()
}
);
assert_eq!(switch.dests.len(), 9);
assert_eq!(
switch.dests[0],
(
ConstantRef::new(Constant::Int { bits: 32, value: 0 }),
Name::Number(12)
)
);
assert_eq!(
switch.dests[1],
(
ConstantRef::new(Constant::Int { bits: 32, value: 1 }),
Name::Number(2)
)
);
assert_eq!(
switch.dests[2],
(
ConstantRef::new(Constant::Int {
bits: 32,
value: 13
}),
Name::Number(3)
)
);
assert_eq!(
switch.dests[3],
(
ConstantRef::new(Constant::Int {
bits: 32,
value: 26
}),
Name::Number(4)
)
);
assert_eq!(
switch.dests[4],
(
ConstantRef::new(Constant::Int {
bits: 32,
value: 33
}),
Name::Number(5)
)
);
assert_eq!(
switch.dests[5],
(
ConstantRef::new(Constant::Int {
bits: 32,
value: 142
}),
Name::Number(6)
)
);
assert_eq!(
switch.dests[6],
(
ConstantRef::new(Constant::Int {
bits: 32,
value: 1678
}),
Name::Number(7)
)
);
assert_eq!(
switch.dests[7],
(
ConstantRef::new(Constant::Int {
bits: 32,
value: 88
}),
Name::Number(8)
)
);
assert_eq!(
switch.dests[8],
(
ConstantRef::new(Constant::Int {
bits: 32,
value: 101
}),
Name::Number(9)
)
);
assert_eq!(switch.default_dest, Name::Number(10));
assert_eq!(
&switch.to_string(),
"switch i32 %0, label %10 [ i32 0, label %12; i32 1, label %2; i32 13, label %3; i32 26, label %4; i32 33, label %5; i32 142, label %6; i32 1678, label %7; i32 88, label %8; i32 101, label %9; ]",
);
let phibb = &func
.get_bb_by_name(&Name::Number(12))
.expect("Failed to find bb %12");
let phi: &instruction::Phi = &phibb.instrs[0].clone().try_into().expect("Should be a phi");
assert_eq!(phi.incoming_values.len(), 10);
assert_eq!(
&phi.to_string(),
"%13 = phi i32 [ i32 -1, %10 ], [ i32 -3, %9 ], [ i32 0, %8 ], [ i32 77, %7 ], [ i32 -33, %6 ], [ i32 1, %5 ], [ i32 -5, %4 ], [ i32 -7, %3 ], [ i32 5, %2 ], [ i32 3, %1 ]",
);
assert_eq!(
module.get_func_decl_by_name("has_a_switch"),
None,
"has_a_switch should be a defined function, not a decl"
);
let decl = module
.get_func_decl_by_name("puts")
.expect("there should be a puts declaration");
assert_eq!(decl.name, "puts");
assert_eq!(decl.return_type, module.types.i32());
assert_eq!(decl.parameters.len(), 1);
#[cfg(feature = "llvm-14-or-lower")]
let param_0_expected_ty = module.types.pointer_to(module.types.i8());
#[cfg(feature = "llvm-15-or-greater")]
let param_0_expected_ty = module.types.pointer();
assert_eq!(
module.type_of(&decl.parameters[0]),
param_0_expected_ty,
);
}
#[test]
fn variablesbc() {
init_logging();
let path = llvm_bc_dir().join("variables.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
assert_eq!(module.global_vars.len(), 1);
let var = &module.global_vars[0];
assert_eq!(var.name, "global");
assert_eq!(var.is_constant, false);
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(var.ty, module.types.pointer_to(module.types.i32()));
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(var.ty, module.types.pointer());
assert_eq!(
var.initializer,
Some(ConstantRef::new(Constant::Int { bits: 32, value: 5 }))
);
assert_eq!(var.alignment, 4);
#[cfg(feature = "llvm-9-or-greater")]
assert!(var.get_debug_loc().is_none()); // this file was compiled without debuginfo
assert_eq!(module.functions.len(), 1);
let func = &module.functions[0];
assert_eq!(func.name, "variables");
let bb = &func.basic_blocks[0];
let store: &instruction::Store = &bb.instrs[2].clone().try_into().expect("Should be a store");
#[cfg(feature = "llvm-14-or-lower")]
let store_addr_expected_ty = module.types.pointer_to(module.types.i32());
#[cfg(feature = "llvm-15-or-greater")]
let store_addr_expected_ty = module.types.pointer();
assert_eq!(
store.address,
Operand::LocalOperand {
name: Name::Number(3),
ty: store_addr_expected_ty,
}
);
assert_eq!(module.type_of(store), module.types.void());
#[cfg(feature = "llvm-14-or-lower")]
let expected_fmt = "store volatile i32 %0, i32* %3, align 4";
#[cfg(feature = "llvm-15-or-greater")]
let expected_fmt = "store volatile i32 %0, ptr %3, align 4";
assert_eq!(&store.to_string(), expected_fmt);
#[cfg(feature = "llvm-14-or-lower")]
let load: &instruction::Load = &bb.instrs[8].clone().try_into().expect("Should be a load");
#[cfg(feature = "llvm-15-or-greater")]
let load: &instruction::Load = &bb.instrs[6].clone().try_into().expect("Should be a load");
#[cfg(feature = "llvm-14-or-lower")]
let load_addr_expected_ty = module.types.pointer_to(module.types.i32());
#[cfg(feature = "llvm-15-or-greater")]
let load_addr_expected_ty = module.types.pointer();
assert_eq!(
load.address,
Operand::LocalOperand {
name: Name::Number(4),
ty: load_addr_expected_ty,
}
);
assert_eq!(module.type_of(load), module.types.i32());
#[cfg(feature = "llvm-14-or-lower")]
let expected_fmt = "%8 = load volatile i32* %4, align 4";
#[cfg(feature = "llvm-15-or-greater")]
let expected_fmt = "%6 = load volatile i32, ptr %4, align 4";
assert_eq!(&load.to_string(), expected_fmt);
#[cfg(feature = "llvm-14-or-lower")]
let global_load: &instruction::Load =
&bb.instrs[14].clone().try_into().expect("Should be a load");
#[cfg(feature = "llvm-15-or-greater")]
let global_load: &instruction::Load =
&bb.instrs[12].clone().try_into().expect("Should be a load");
assert_eq!(
global_load.address,
Operand::ConstantOperand(ConstantRef::new(Constant::GlobalReference {
name: "global".into(),
ty: module.types.i32()
}))
);
assert_eq!(module.type_of(global_load), module.types.i32());
#[cfg(feature = "llvm-14-or-lower")]
let expected_fmt = "%12 = load volatile i32* @global, align 4";
#[cfg(feature = "llvm-15-or-greater")]
let expected_fmt = "%10 = load volatile i32, ptr @global, align 4";
assert_eq!(&global_load.to_string(), expected_fmt);
#[cfg(feature = "llvm-14-or-lower")]
let global_store: &instruction::Store =
&bb.instrs[16].clone().try_into().expect("Should be a store");
#[cfg(feature = "llvm-15-or-greater")]
let global_store: &instruction::Store =
&bb.instrs[14].clone().try_into().expect("Should be a store");
assert_eq!(
global_store.address,
Operand::ConstantOperand(ConstantRef::new(Constant::GlobalReference {
name: "global".into(),
ty: module.types.i32()
}))
);
assert_eq!(module.type_of(global_store), module.types.void());
#[cfg(feature = "llvm-14-or-lower")]
let expected_fmt = "store volatile i32 %13, i32* @global, align 4";
#[cfg(feature = "llvm-15-or-greater")]
let expected_fmt = "store volatile i32 %11, ptr @global, align 4";
assert_eq!(&global_store.to_string(), expected_fmt);
assert_eq!(
module.get_func_decl_by_name("variables"),
None,
"variables should be a defined function, not a decl"
);
let decl = module
.get_func_decl_by_name("malloc")
.expect("there should be a malloc declaration");
assert_eq!(decl.name, "malloc");
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(decl.return_type, module.types.pointer_to(module.types.i8()));
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(decl.return_type, module.types.pointer());
assert!(decl
.return_attributes
.contains(&ParameterAttribute::NoAlias));
assert_eq!(decl.parameters.len(), 1);
assert_eq!(module.type_of(&decl.parameters[0]), module.types.i64());
#[cfg(feature = "llvm-12-or-lower")]
assert_eq!(decl.parameters[0].attributes, vec![]);
#[cfg(feature = "llvm-13-or-greater")]
assert_eq!(
decl.parameters[0].attributes,
vec![ParameterAttribute::NoUndef]
);
}
// this test relates to the version of the file compiled with debuginfo
#[cfg(feature = "llvm-9-or-greater")]
#[test]
fn variablesbcg() {
init_logging();
let path = llvm_bc_dir().join("variables.bc-g");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let debug_filename = "variables.c";
let debug_directory = "/Users/craig/llvm-ir/tests/basic_bc"; // this is what appears in the checked-in copy of variables.bc-g
// really all we want to check is the debugloc of the global variable.
// other debuginfo stuff is covered in other tests
assert_eq!(module.global_vars.len(), 1);
let var = &module.global_vars[0];
assert_eq!(var.name, "global");
let debugloc = var
.get_debug_loc()
.as_ref()
.expect("expected the global to have a debugloc");
assert_eq!(debugloc.line, 5);
assert_eq!(debugloc.col, None); // only `Instruction`s and `Terminator`s get column numbers
assert_eq!(debugloc.filename, debug_filename);
assert_eq!(
debugloc.directory.as_ref().map(|s| s.as_str()),
Some(debug_directory)
);
}
// this test checks for regression on issue #4
#[test]
fn issue4() {
init_logging();
let path = llvm_bc_dir().join("issue_4.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
assert_eq!(module.functions.len(), 1);
let func = &module.functions[0];
// not part of issue 4 proper, but let's check that we have the correct number of function attributes
let expected_num_function_attributes = if cfg!(feature = "llvm-8-or-lower") {
21
} else if cfg!(feature = "llvm-9") {
// LLVM 9+ adds the attribute "nofree"
22
} else if cfg!(feature = "llvm-10") || cfg!(feature = "llvm-11") {
// LLVM 10+ seems to have combined the two attributes
// "no-frame-pointer-elim=true" and "no-frame-pointer-elim-non-leaf"
// into a single attribute, "frame-pointer=all"
21
} else if cfg!(feature = "llvm-12") {
// LLVM 12+ adds "willreturn"
22
} else if cfg!(feature = "llvm-13") || cfg!(feature = "llvm-14") {
// LLVM 13+ adds "mustprogress" and "nosync"
// LLVM 13+ removes the following string attributes:
// "disable-tail-calls=false"
// "less-precise-fpmad=false"
// "no-infs-fp-math=false"
// "no-jump-tables=false"
// "no-nans-fp-math=false"
// "no-signed-zeroes-fp-math=false"
// "unsafe-fp-math=false"
// "use-soft-float=false"
// for a net of -6 attributes
16
} else if cfg!(feature = "llvm-15-or-greater") {
// LLVM 15+ adds "argmemonly"
17
} else {
panic!("Shouldn't reach this")
};
assert_eq!(
func.function_attributes.len(),
expected_num_function_attributes,
"Expected {} function attributes but have {}: {:?}",
expected_num_function_attributes,
func.function_attributes.len(),
func.function_attributes
);
// and that all but 6 of them are StringAttributes (5 of them for LLVM 8; 7 for LLVM 12; 9 for LLVM 13/14; 10 for LLVM 15+)
let expected_num_enum_attrs = if cfg!(feature = "llvm-8-or-lower") {
5 // missing "nofree"
} else if cfg!(feature = "llvm-9") || cfg!(feature = "llvm-10") || cfg!(feature = "llvm-11") {
6
} else if cfg!(feature = "llvm-12") {
7 // adds "willreturn"
} else if cfg!(feature = "llvm-13") || cfg!(feature = "llvm-14") {
9 // adds "mustprogress" and "nosync"
} else if cfg!(feature = "llvm-15-or-greater") {
10 // adds "argmemonly"
} else {
panic!("Shouldn't reach this")
};
let string_attrs = func.function_attributes.iter().filter(|attr| {
if let FunctionAttribute::StringAttribute { .. } = attr {
true
} else {
false
}
});
assert_eq!(
string_attrs.count(),
expected_num_function_attributes - expected_num_enum_attrs
);
// now check that the first parameter has 3 attributes (4 in LLVM 11/12/13, 5 in LLVM 14) and the second parameter has 0
assert_eq!(func.parameters.len(), 2);
let first_param_attrs = &func.parameters[0].attributes;
#[cfg(feature = "llvm-10-or-lower")]
assert_eq!(first_param_attrs.len(), 3);
#[cfg(any(feature = "llvm-11", feature = "llvm-12", feature = "llvm-13"))]
assert_eq!(first_param_attrs.len(), 4);
#[cfg(any(feature = "llvm-14-or-greater"))]
assert_eq!(first_param_attrs.len(), 5);
let second_param_attrs = &func.parameters[1].attributes;
#[cfg(feature = "llvm-13-or-lower")]
assert_eq!(second_param_attrs.len(), 0);
#[cfg(feature = "llvm-14-or-greater")]
assert_eq!(second_param_attrs.len(), 1); // LLVM 14+ adds 'noundef' to the second param
// and that one of the parameter attributes is SRet
#[cfg(feature = "llvm-11-or-lower")]
let is_sret = |attr: &ParameterAttribute| match attr {
ParameterAttribute::SRet => true,
_ => false,
};
#[cfg(feature = "llvm-12-or-greater")]
let is_sret = |attr: &ParameterAttribute| match attr {
ParameterAttribute::SRet(_) => true,
_ => false,
};
assert!(first_param_attrs.iter().any(is_sret));
}
#[test]
fn rustbc() {
// This tests against the checked-in rust.bc, which was generated from the checked-in rust.rs with rustc 1.39.0
init_logging();
let path = rust_bc_dir().join("rust.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let func = module
.get_func_by_name("_ZN4rust9rust_loop17h3ed0672b8cf44eb1E")
.expect("Failed to find function");
assert_eq!(func.parameters.len(), 3);
assert_eq!(func.parameters[0].name, Name::from("a"));
assert_eq!(func.parameters[1].name, Name::from("b"));
assert_eq!(func.parameters[2].name, Name::from("v"));
assert_eq!(func.parameters[0].ty, module.types.i64());
assert_eq!(func.parameters[1].ty, module.types.i64());
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(
func.parameters[2].ty,
module
.types
.pointer_to(module.types.named_struct("alloc::vec::Vec<isize>"))
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(func.parameters[2].ty, module.types.pointer());
let startbb = func
.get_bb_by_name(&Name::from("start"))
.expect("Failed to find bb 'start'");
let alloca_iter: &instruction::Alloca = &startbb.instrs[5]
.clone()
.try_into()
.expect("Should be an alloca");
assert_eq!(alloca_iter.dest, Name::from("iter"));
#[cfg(feature = "llvm-14-or-lower")]
let expected_fmt = "%iter = alloca { i64*, i64* }, align 8";
#[cfg(feature = "llvm-15-or-greater")]
let expected_fmt = "%iter = alloca { ptr, ptr }, align 8";
assert_eq!(&alloca_iter.to_string(), expected_fmt);
let alloca_sum: &instruction::Alloca = &startbb.instrs[6]
.clone()
.try_into()
.expect("Should be an alloca");
assert_eq!(alloca_sum.dest, Name::from("sum"));
assert_eq!(&alloca_sum.to_string(), "%sum = alloca i64, align 8");
let store: &instruction::Store = &startbb.instrs[7]
.clone()
.try_into()
.expect("Should be a store");
#[cfg(feature = "llvm-14-or-lower")]
let store_addr_expected_ty = module.types.pointer_to(module.types.i64());
#[cfg(feature = "llvm-15-or-greater")]
let store_addr_expected_ty = module.types.pointer();
assert_eq!(
store.address,
Operand::LocalOperand {
name: Name::from("sum"),
ty: store_addr_expected_ty,
}
);
#[cfg(feature = "llvm-14-or-lower")]
let expected_fmt = "store i64 0, i64* %sum, align 8";
#[cfg(feature = "llvm-15-or-greater")]
let expected_fmt = "store i64 0, ptr %sum, align 8";
assert_eq!(&store.to_string(), expected_fmt);
let call: &instruction::Call = &startbb.instrs[8]
.clone()
.try_into()
.expect("Should be a call");
#[cfg(feature = "llvm-14-or-lower")]
let param_type = module
.types
.pointer_to(module.types.named_struct("alloc::vec::Vec<isize>"));
#[cfg(feature = "llvm-15-or-greater")]
let param_type = module.types.pointer();
let ret_type = module.types.struct_of(
vec![
#[cfg(feature = "llvm-14-or-lower")]
module
.types
.pointer_to(module.types.array_of(module.types.i64(), 0)),
#[cfg(feature = "llvm-15-or-greater")]
module.types.pointer(),
module.types.i64(),
],
false,
);
if let Either::Right(Operand::ConstantOperand(cref)) = &call.function {
if let Constant::GlobalReference { ref name, ref ty } = cref.as_ref() {
assert_eq!(name.as_str(), "_ZN68_$LT$alloc..vec..Vec$LT$T$GT$$u20$as$u20$core..ops..deref..Deref$GT$5deref17h378128d7d9378466E");
match ty.as_ref() {
Type::FuncType {
result_type,
param_types,
is_var_arg,
} => {
assert_eq!(result_type, &ret_type);
assert_eq!(¶m_types[0], ¶m_type);
assert_eq!(*is_var_arg, false);
},
_ => panic!("Expected called global to have FuncType, but got {:?}", ty),
}
assert_eq!(module.type_of(call), ret_type);
} else {
panic!(
"call.function not a GlobalReference as expected; it is actually another kind of Constant: {:?}",
cref
);
}
} else {
panic!(
"call.function not a GlobalReference as expected; it is actually {:?}",
call.function
);
}
assert_eq!(call.arguments.len(), 1);
assert_eq!(
call.arguments[0].0,
Operand::LocalOperand {
name: Name::from("v"),
ty: param_type,
}
);
assert_eq!(call.dest, Some(Name::Number(0)));
#[cfg(feature = "llvm-14-or-lower")]
let expected_fmt = "%0 = call @_ZN68_$LT$alloc..vec..Vec$LT$T$GT$$u20$as$u20$core..ops..deref..Deref$GT$5deref17h378128d7d9378466E(%alloc::vec::Vec<isize>* %v)";
#[cfg(feature = "llvm-15-or-greater")]
let expected_fmt = "%0 = call @_ZN68_$LT$alloc..vec..Vec$LT$T$GT$$u20$as$u20$core..ops..deref..Deref$GT$5deref17h378128d7d9378466E(ptr %v)";
assert_eq!(&call.to_string(), expected_fmt);
#[cfg(feature = "llvm-9-or-greater")]
{
// this file was compiled without debuginfo, so nothing should have a debugloc
assert!(func.get_debug_loc().is_none());
assert!(alloca_iter.get_debug_loc().is_none());
assert!(alloca_sum.get_debug_loc().is_none());
assert!(store.get_debug_loc().is_none());
assert!(call.get_debug_loc().is_none());
}
}
// this test relates to the version of the file compiled with debuginfo
#[cfg(feature = "llvm-9-or-greater")]
#[test]
fn rustbcg() {
init_logging();
let path = rust_bc_dir().join("rust.bc-g");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let debug_filename = "rust.rs";
let debug_directory = "/Users/craig/llvm-ir/tests/basic_bc"; // this is what appears in the checked-in copy of rust.bc-g
let func = module
.get_func_by_name("_ZN4rust9rust_loop17h3ed0672b8cf44eb1E")
.expect("Failed to find function");
let debugloc = func
.get_debug_loc()
.as_ref()
.expect("Expected function to have a debugloc");
assert_eq!(debugloc.line, 3);
assert_eq!(debugloc.col, None);
assert_eq!(debugloc.filename, debug_filename);
assert_eq!(
debugloc.directory.as_ref().map(|s| s.as_str()),
Some(debug_directory)
);
let startbb = func
.get_bb_by_name(&Name::from("start"))
.expect("Failed to find bb 'start'");
// the first 17 instructions in the function should not have debuglocs - they are just setting up the stack frame
for i in 0..17 {
assert!(startbb.instrs[i].get_debug_loc().is_none());
}
let store_debugloc = startbb.instrs[31]
.get_debug_loc()
.as_ref()
.expect("Expected this store to have a debugloc");
assert_eq!(store_debugloc.line, 4);
assert_eq!(store_debugloc.col, Some(18));
assert_eq!(store_debugloc.filename, debug_filename);
assert_eq!(
debugloc.directory.as_ref().map(|s| s.as_str()),
Some(debug_directory)
);
#[cfg(feature = "llvm-14-or-lower")]
let expected_fmt = "store i64 0, i64* %sum, align 8 (with debugloc)";
#[cfg(feature = "llvm-15-or-greater")]
let expected_fmt = "store i64 0, ptr %sum, align 8 (with debugloc)";
assert_eq!(
&startbb.instrs[31].to_string(),
expected_fmt
);
let call_debugloc = startbb.instrs[33]
.get_debug_loc()
.as_ref()
.expect("Expected this call to have a debugloc");
assert_eq!(call_debugloc.line, 5);
assert_eq!(call_debugloc.col, Some(13));
assert_eq!(call_debugloc.filename, debug_filename);
assert_eq!(
debugloc.directory.as_ref().map(|s| s.as_str()),
Some(debug_directory)
);
#[cfg(feature = "llvm-14-or-lower")]
let expected_fmt = "%4 = call @_ZN68_$LT$alloc..vec..Vec$LT$T$GT$$u20$as$u20$core..ops..deref..Deref$GT$5deref17h378128d7d9378466E(%alloc::vec::Vec<isize>* %3) (with debugloc)";
#[cfg(feature = "llvm-15-or-greater")]
let expected_fmt = "%4 = call @_ZN68_$LT$alloc..vec..Vec$LT$T$GT$$u20$as$u20$core..ops..deref..Deref$GT$5deref17h378128d7d9378466E(ptr %3) (with debugloc)";
assert_eq!(&startbb.instrs[33].to_string(), expected_fmt);
}
#[test]
fn simple_linked_list() {
init_logging();
let path = llvm_bc_dir().join("linkedlist.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let struct_name: String = "struct.SimpleLinkedList".into();
let structty = module.types.named_struct(&struct_name);
match structty.as_ref() {
Type::NamedStructType { name } => {
assert_eq!(name, &struct_name);
},
ty => panic!(
"Expected {} to be NamedStructType, but got {:?}",
struct_name, ty
),
}
let structty_inner = match module.types.named_struct_def(&struct_name) {
None => panic!(
"Failed to find {} with module.types.named_struct_def(); have names {:?}",
struct_name,
module.types.all_struct_names().collect::<Vec<_>>()
),
Some(NamedStructDef::Opaque) => panic!("{} should not be an opaque type", struct_name),
Some(NamedStructDef::Defined(ty)) => ty,
};
if let Type::StructType { element_types, .. } = structty_inner.as_ref() {
assert_eq!(element_types.len(), 2);
assert_eq!(element_types[0], module.types.i32());
#[cfg(feature = "llvm-14-or-lower")]
if let Type::PointerType { pointee_type, .. } = element_types[1].as_ref() {
if let Type::NamedStructType { name } = pointee_type.as_ref() {
assert_eq!(name, &struct_name);
} else {
panic!(
"Expected pointee type to be a NamedStructType, got {:?}",
pointee_type
);
}
} else {
panic!(
"Expected inner type to be a PointerType, got {:?}",
element_types[1]
);
}
#[cfg(feature = "llvm-15-or-greater")]
assert!(matches!(
element_types[1].as_ref(),
Type::PointerType { .. }
));
} else {
panic!(
"Expected {} to be a StructType, got {:?}",
struct_name, structty
);
}
let func = module
.get_func_by_name("simple_linked_list")
.expect("Failed to find function");
let alloca: &instruction::Alloca = &func.basic_blocks[0].instrs[1]
.clone()
.try_into()
.expect("Should be an alloca");
if let Type::NamedStructType { name } = alloca.allocated_type.as_ref() {
assert_eq!(name, &struct_name);
} else {
panic!(
"Expected alloca.allocated_type to be a NamedStructType, got {:?}",
alloca.allocated_type
);
}
assert_eq!(
&alloca.to_string(),
"%3 = alloca %struct.SimpleLinkedList, align 8"
);
// LLVM 15 has no need for the SomeOpaqueStruct due to opaque pointer types
#[cfg(feature = "llvm-14-or-lower")]
{
let struct_name: String = "struct.SomeOpaqueStruct".into();
let structty = module.types.named_struct(&struct_name);
match structty.as_ref() {
Type::NamedStructType { name } => {
assert_eq!(name, &struct_name);
},
ty => panic!(
"Expected {} to be a NamedStructType, but got {:?}",
struct_name, ty
),
}
match module.types.named_struct_def(&struct_name) {
None => panic!(
"Failed to find {} with module.types.named_struct_def(); have names {:?}",
struct_name,
module.types.all_struct_names().collect::<Vec<_>>()
),
Some(NamedStructDef::Opaque) => (),
Some(NamedStructDef::Defined(def)) => panic!(
"{} should be an opaque type; got def {:?}",
struct_name, def
),
}
}
let func = module
.get_func_by_name("takes_opaque_struct")
.expect("Failed to find function");
let paramty = &func.parameters[0].ty;
#[cfg(feature = "llvm-14-or-lower")]
match paramty.as_ref() {
Type::PointerType { pointee_type, .. } => match pointee_type.as_ref() {
Type::NamedStructType { name } => {
assert_eq!(name, "struct.SomeOpaqueStruct");
},
ty => panic!(
"Expected parameter type to be pointer to named struct, but got pointer to {:?}",
ty
),
},
_ => panic!(
"Expected parameter type to be pointer type, but got {:?}",
paramty
),
};
#[cfg(feature = "llvm-15-or-greater")]
assert!(matches!(paramty.as_ref(), Type::PointerType { .. }));
}
// this test relates to the version of the file compiled with debuginfo
#[cfg(feature = "llvm-9-or-greater")]
#[test]
fn simple_linked_list_g() {
init_logging();
let path = llvm_bc_dir().join("linkedlist.bc-g");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let debug_filename = "linkedlist.c";
let debug_directory = "/Users/craig/llvm-ir/tests/basic_bc"; // this is what appears in the checked-in copy of linkedlist.bc-g
let func = module
.get_func_by_name("simple_linked_list")
.expect("Failed to find function");
let debugloc = func
.get_debug_loc()
.as_ref()
.expect("expected simple_linked_list to have a debugloc");
assert_eq!(debugloc.line, 8);
assert_eq!(debugloc.col, None);
assert_eq!(debugloc.filename, debug_filename);
assert_eq!(
debugloc.directory.as_ref().map(|s| s.as_str()),
Some(debug_directory)
);
// the first seven instructions shouldn't have debuglocs - they are just setting up the stack frame
for i in 0..7 {
assert!(func.basic_blocks[0].instrs[i].get_debug_loc().is_none());
}
// the eighth instruction should have a debugloc
let debugloc = func.basic_blocks[0].instrs[7]
.get_debug_loc()
.as_ref()
.expect("expected this instruction to have a debugloc");
assert_eq!(debugloc.line, 8);
assert_eq!(debugloc.col, Some(28));
assert_eq!(debugloc.filename, debug_filename);
assert_eq!(
debugloc.directory.as_ref().map(|s| s.as_str()),
Some(debug_directory)
);
assert_eq!(
&func.basic_blocks[0].instrs[7].to_string(),
"call @llvm.dbg.declare(<metadata>, <metadata>, <metadata>) (with debugloc)",
);
// the tenth instruction should have a different debugloc
let debugloc = func.basic_blocks[0].instrs[9]
.get_debug_loc()
.as_ref()
.expect("expected this instruction to have a debugloc");
assert_eq!(debugloc.line, 9);
assert_eq!(debugloc.col, Some(34));
assert_eq!(debugloc.filename, debug_filename);
assert_eq!(
debugloc.directory.as_ref().map(|s| s.as_str()),
Some(debug_directory)
);
#[cfg(feature = "llvm-14-or-lower")]
let expected_fmt = "%8 = getelementptr inbounds %struct.SimpleLinkedList* %3, i32 0, i32 0 (with debugloc)";
#[cfg(feature = "llvm-15-or-greater")]
let expected_fmt = "%8 = getelementptr inbounds ptr %3, i32 0, i32 0 (with debugloc)";
assert_eq!(&func.basic_blocks[0].instrs[9].to_string(), expected_fmt);
}
#[test]
fn indirectly_recursive_type() {
init_logging();
let path = llvm_bc_dir().join("linkedlist.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let struct_name_a: String = "struct.NodeA".into();
let aty = module.types.named_struct(&struct_name_a);
match aty.as_ref() {
Type::NamedStructType { name } => {
assert_eq!(name, &struct_name_a);
},
ty => panic!(
"Expected {} to be a NamedStructType, but got {:?}",
struct_name_a, ty
),
}
let aty_inner = match module.types.named_struct_def(&struct_name_a) {
None => panic!(
"Failed to find {} with module.types.named_struct_def(); have names {:?}",
struct_name_a,
module.types.all_struct_names().collect::<Vec<_>>()
),
Some(NamedStructDef::Opaque) => panic!("{} should not be an opaque type", &struct_name_a),
Some(NamedStructDef::Defined(ty)) => ty,
};
let struct_name_b: String = "struct.NodeB".into();
let bty = module.types.named_struct(&struct_name_b);
match bty.as_ref() {
Type::NamedStructType { name } => {
assert_eq!(name, &struct_name_b);
},
ty => panic!(
"Expected {} to be a NamedStructType, but got {:?}",
struct_name_b, ty
),
}
let bty_inner = match module.types.named_struct_def(&struct_name_b) {
None => panic!(
"Failed to find {} with module.types.named_struct_def(); have names {:?}",
struct_name_b,
module.types.all_struct_names().collect::<Vec<_>>()
),
Some(NamedStructDef::Opaque) => panic!("{} should not be an opaque type", &struct_name_b),
Some(NamedStructDef::Defined(ty)) => ty,
};
if let Type::StructType { element_types, .. } = aty_inner.as_ref() {
assert_eq!(element_types.len(), 2);
assert_eq!(element_types[0], module.types.i32());
#[cfg(feature = "llvm-14-or-lower")]
if let Type::PointerType { pointee_type, .. } = element_types[1].as_ref() {
if let Type::NamedStructType { name } = pointee_type.as_ref() {
assert_eq!(name, &struct_name_b);
} else {
panic!(
"Expected pointee type to be a NamedStructType, got {:?}",
pointee_type.as_ref()
);
}
} else {
panic!(
"Expected inner type to be a PointerType, got {:?}",
element_types[1]
);
}
#[cfg(feature = "llvm-15-or-greater")]
assert!(matches!(
element_types[1].as_ref(),
Type::PointerType { .. }
));
} else {
panic!(
"Expected NodeA inner type to be a StructType, got {:?}",
aty
);
}
if let Type::StructType { element_types, .. } = bty_inner.as_ref() {
assert_eq!(element_types.len(), 2);
assert_eq!(element_types[0], module.types.i32());
#[cfg(feature = "llvm-14-or-lower")]
if let Type::PointerType { pointee_type, .. } = element_types[1].as_ref() {
if let Type::NamedStructType { name } = pointee_type.as_ref() {
assert_eq!(name, &struct_name_a);
} else {
panic!(
"Expected pointee type to be a NamedStructType, got {:?}",
pointee_type.as_ref()
);
}
} else {
panic!(
"Expected inner type to be a PointerType, got {:?}",
element_types[1]
);
}
#[cfg(feature = "llvm-15-or-greater")]
assert!(matches!(
element_types[1].as_ref(),
Type::PointerType { .. }
));
} else {
panic!(
"Expected NodeB inner type to be a StructType, got {:?}",
bty
);
}
let func = module
.get_func_by_name("indirectly_recursive_type")
.expect("Failed to find function");
let alloca_a: &instruction::Alloca = &func.basic_blocks[0].instrs[1]
.clone()
.try_into()
.expect("Should be an alloca");
let alloca_b: &instruction::Alloca = &func.basic_blocks[0].instrs[2]
.clone()
.try_into()
.expect("Should be an alloca");
if let Type::NamedStructType { name } = alloca_a.allocated_type.as_ref() {
assert_eq!(name, &struct_name_a);
} else {
panic!(
"Expected alloca_a.allocated_type to be a NamedStructType, got {:?}",
alloca_a.allocated_type
);
}
if let Type::NamedStructType { name } = alloca_b.allocated_type.as_ref() {
assert_eq!(name, &struct_name_b);
} else {
panic!(
"Expected alloca_b.allocated_type to be a NamedStructType, got {:?}",
alloca_b.allocated_type
);
}
assert_eq!(&alloca_a.to_string(), "%3 = alloca %struct.NodeA, align 8");
assert_eq!(&alloca_b.to_string(), "%4 = alloca %struct.NodeB, align 8");
}
#[test]
fn param_and_func_attributes() {
let _ = env_logger::builder().is_test(true).try_init(); // capture log messages with test harness
let path = llvm_bc_dir().join("param_and_func_attributes.ll.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
// Return attributes
let zeroext_fn = module.get_func_by_name("f.zeroext").unwrap();
assert_eq!(zeroext_fn.return_attributes.len(), 1);
assert_eq!(zeroext_fn.return_attributes[0], ParameterAttribute::ZeroExt);
let signext_fn = module.get_func_by_name("f.signext").unwrap();
assert_eq!(signext_fn.return_attributes.len(), 1);
assert_eq!(signext_fn.return_attributes[0], ParameterAttribute::SignExt);
let inreg_fn = module.get_func_by_name("f.inreg").unwrap();
assert_eq!(inreg_fn.return_attributes.len(), 1);
assert_eq!(inreg_fn.return_attributes[0], ParameterAttribute::InReg);
let noalias_fn = module.get_func_by_name("f.noalias").unwrap();
assert_eq!(noalias_fn.return_attributes.len(), 1);
assert_eq!(noalias_fn.return_attributes[0], ParameterAttribute::NoAlias);
let nonnull_fn = module.get_func_by_name("f.nonnull").unwrap();
assert_eq!(nonnull_fn.return_attributes.len(), 1);
assert_eq!(nonnull_fn.return_attributes[0], ParameterAttribute::NonNull);
let deref4_fn = module.get_func_by_name("f.dereferenceable4").unwrap();
assert_eq!(deref4_fn.return_attributes.len(), 1);
assert_eq!(
deref4_fn.return_attributes[0],
ParameterAttribute::Dereferenceable(4)
);
let deref8_fn = module.get_func_by_name("f.dereferenceable8").unwrap();
assert_eq!(deref8_fn.return_attributes.len(), 1);
assert_eq!(
deref8_fn.return_attributes[0],
ParameterAttribute::Dereferenceable(8)
);
let deref4ornull_fn = module
.get_func_by_name("f.dereferenceable4_or_null")
.unwrap();
assert_eq!(deref4ornull_fn.return_attributes.len(), 1);
assert_eq!(
deref4ornull_fn.return_attributes[0],
ParameterAttribute::DereferenceableOrNull(4)
);
let deref8ornull_fn = module
.get_func_by_name("f.dereferenceable8_or_null")
.unwrap();
assert_eq!(deref8ornull_fn.return_attributes.len(), 1);
assert_eq!(
deref8ornull_fn.return_attributes[0],
ParameterAttribute::DereferenceableOrNull(8)
);
// Parameter attributes
let f = module.get_func_by_name("f.param.zeroext").unwrap();
assert_eq!(f.parameters.len(), 1);
let param = &f.parameters[0];
assert_eq!(param.attributes.len(), 1);
assert_eq!(param.attributes[0], ParameterAttribute::ZeroExt);
let f = module.get_func_by_name("f.param.signext").unwrap();
assert_eq!(f.parameters.len(), 1);
let param = &f.parameters[0];
assert_eq!(param.attributes.len(), 1);
assert_eq!(param.attributes[0], ParameterAttribute::SignExt);
let f = module.get_func_by_name("f.param.inreg").unwrap();
assert_eq!(f.parameters.len(), 1);
let param = &f.parameters[0];
assert_eq!(param.attributes.len(), 1);
assert_eq!(param.attributes[0], ParameterAttribute::InReg);
let f = module.get_func_by_name("f.param.byval").unwrap();
assert_eq!(f.parameters.len(), 1);
let param = &f.parameters[0];
assert_eq!(param.attributes.len(), 1);
#[cfg(feature = "llvm-8-or-lower")]
assert_eq!(param.attributes[0], ParameterAttribute::ByVal);
#[cfg(all(feature = "llvm-9-or-greater", feature = "llvm-11-or-lower"))]
assert_eq!(param.attributes[0], ParameterAttribute::UnknownAttribute);
#[cfg(feature = "llvm-12-or-greater")]
match ¶m.attributes[0] {
ParameterAttribute::ByVal(ty) => match ty.as_ref() {
Type::StructType {
element_types,
is_packed: false,
} => {
assert_eq!(element_types.len(), 2);
},
ty => panic!("Expected a StructType with is_packed=false, got {:?}", ty),
},
attr => panic!("Expected a ByVal, got {:?}", attr),
}
let f = module.get_func_by_name("f.param.inalloca").unwrap();
assert_eq!(f.parameters.len(), 1);
let param = &f.parameters[0];
assert_eq!(param.attributes.len(), 1);
#[cfg(feature = "llvm-12-or-lower")]
assert_eq!(param.attributes[0], ParameterAttribute::InAlloca);
#[cfg(feature = "llvm-13-or-greater")]
match ¶m.attributes[0] {
ParameterAttribute::InAlloca(ty) => match ty.as_ref() {
Type::IntegerType { bits: 8 } => {},
ty => panic!("Expected i8, got {:?}", ty),
},
attr => panic!("Expected an InAlloca, got {:?}", attr),
}
let f = module.get_func_by_name("f.param.sret").unwrap();
assert_eq!(f.parameters.len(), 1);
let param = &f.parameters[0];
assert_eq!(param.attributes.len(), 1);
#[cfg(feature = "llvm-11-or-lower")]
assert_eq!(param.attributes[0], ParameterAttribute::SRet);
#[cfg(feature = "llvm-12-or-greater")]
match ¶m.attributes[0] {
ParameterAttribute::SRet(ty) => match ty.as_ref() {
Type::IntegerType { bits: 8 } => {},
ty => panic!("Expected i8, got {:?}", ty),
},
attr => panic!("Expected an SRet, got {:?}", attr),
}
let f = module.get_func_by_name("f.param.noalias").unwrap();
assert_eq!(f.parameters.len(), 1);
let param = &f.parameters[0];
assert_eq!(param.attributes.len(), 1);
assert_eq!(param.attributes[0], ParameterAttribute::NoAlias);
let f = module.get_func_by_name("f.param.nocapture").unwrap();
assert_eq!(f.parameters.len(), 1);
let param = &f.parameters[0];
assert_eq!(param.attributes.len(), 1);
assert_eq!(param.attributes[0], ParameterAttribute::NoCapture);
let f = module.get_func_by_name("f.param.nest").unwrap();
assert_eq!(f.parameters.len(), 1);
let param = &f.parameters[0];
assert_eq!(param.attributes.len(), 1);
assert_eq!(param.attributes[0], ParameterAttribute::Nest);
let f = module.get_func_by_name("f.param.returned").unwrap();
assert_eq!(f.parameters.len(), 1);
let param = &f.parameters[0];
assert_eq!(param.attributes.len(), 1);
assert_eq!(param.attributes[0], ParameterAttribute::Returned);
let f = module.get_func_by_name("f.param.nonnull").unwrap();
assert_eq!(f.parameters.len(), 1);
let param = &f.parameters[0];
assert_eq!(param.attributes.len(), 1);
assert_eq!(param.attributes[0], ParameterAttribute::NonNull);
let f = module.get_func_by_name("f.param.dereferenceable").unwrap();
assert_eq!(f.parameters.len(), 1);
let param = &f.parameters[0];
assert_eq!(param.attributes.len(), 1);
assert_eq!(param.attributes[0], ParameterAttribute::Dereferenceable(4));
let f = module
.get_func_by_name("f.param.dereferenceable_or_null")
.unwrap();
assert_eq!(f.parameters.len(), 1);
let param = &f.parameters[0];
assert_eq!(param.attributes.len(), 1);
assert_eq!(
param.attributes[0],
ParameterAttribute::DereferenceableOrNull(4)
);
// Function attributes
let f = module.get_func_by_name("f.alignstack4").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::AlignStack(4));
let f = module.get_func_by_name("f.alignstack8").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::AlignStack(8));
let f = module.get_func_by_name("f.alwaysinline").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::AlwaysInline);
let f = module.get_func_by_name("f.cold").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::Cold);
let f = module.get_func_by_name("f.convergent").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::Convergent);
let f = module.get_func_by_name("f.inlinehint").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::InlineHint);
let f = module.get_func_by_name("f.jumptable").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::JumpTable);
let f = module.get_func_by_name("f.minsize").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::MinimizeSize);
let f = module.get_func_by_name("f.naked").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::Naked);
let f = module.get_func_by_name("f.nobuiltin").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::NoBuiltin);
let f = module.get_func_by_name("f.noduplicate").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::NoDuplicate);
let f = module.get_func_by_name("f.noimplicitfloat").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::NoImplicitFloat);
let f = module.get_func_by_name("f.nonlazybind").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::NonLazyBind);
let f = module.get_func_by_name("f.noredzone").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::NoRedZone);
let f = module.get_func_by_name("f.noreturn").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::NoReturn);
let f = module.get_func_by_name("f.nounwind").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::NoUnwind);
let f = module.get_func_by_name("f.optnone").unwrap();
assert_eq!(f.function_attributes.len(), 2);
assert_eq!(f.function_attributes[0], FunctionAttribute::NoInline);
assert_eq!(f.function_attributes[1], FunctionAttribute::OptNone);
let f = module.get_func_by_name("f.optsize").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::OptSize);
let f = module.get_func_by_name("f.readnone").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::ReadNone);
let f = module.get_func_by_name("f.readonly").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::ReadOnly);
let f = module.get_func_by_name("f.returns_twice").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::ReturnsTwice);
let f = module.get_func_by_name("f.safestack").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::SafeStack);
let f = module.get_func_by_name("f.sanitize_address").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::SanitizeAddress);
let f = module.get_func_by_name("f.sanitize_memory").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::SanitizeMemory);
let f = module.get_func_by_name("f.sanitize_thread").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::SanitizeThread);
let f = module.get_func_by_name("f.ssp").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::StackProtect);
let f = module.get_func_by_name("f.sspreq").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::StackProtectReq);
let f = module.get_func_by_name("f.sspstrong").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(
f.function_attributes[0],
FunctionAttribute::StackProtectStrong
);
let f = module.get_func_by_name("f.thunk").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(
f.function_attributes[0],
FunctionAttribute::StringAttribute {
kind: "thunk".into(),
value: "".into()
}
);
let f = module.get_func_by_name("f.uwtable").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::UWTable);
let f = module.get_func_by_name("f.kvpair").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(
f.function_attributes[0],
FunctionAttribute::StringAttribute {
kind: "cpu".into(),
value: "cortex-a8".into()
}
);
let f = module.get_func_by_name("f.norecurse").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::NoRecurse);
let f = module.get_func_by_name("f.inaccessiblememonly").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(
f.function_attributes[0],
FunctionAttribute::InaccessibleMemOnly
);
let f = module
.get_func_by_name("f.inaccessiblemem_or_argmemonly")
.unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(
f.function_attributes[0],
FunctionAttribute::InaccessibleMemOrArgMemOnly
);
let f = module.get_func_by_name("f.strictfp").unwrap();
assert_eq!(f.function_attributes.len(), 1);
assert_eq!(f.function_attributes[0], FunctionAttribute::StrictFP);
}
#[cfg(feature = "llvm-11-or-greater")]
#[test]
fn float_types() {
init_logging();
let path = llvm_bc_dir().join("float_types.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let f = module.get_func_by_name("takes_half").unwrap();
assert_eq!(
module.type_of(f.parameters.get(0).unwrap()),
module.types.fp(FPType::Half)
);
let f = module.get_func_by_name("takes_bfloat").unwrap();
assert_eq!(
module.type_of(f.parameters.get(0).unwrap()),
module.types.fp(FPType::BFloat)
);
let f = module.get_func_by_name("takes_float").unwrap();
assert_eq!(
module.type_of(f.parameters.get(0).unwrap()),
module.types.fp(FPType::Single)
);
let f = module.get_func_by_name("takes_double").unwrap();
assert_eq!(
module.type_of(f.parameters.get(0).unwrap()),
module.types.fp(FPType::Double)
);
let f = module.get_func_by_name("takes_fp128").unwrap();
assert_eq!(
module.type_of(f.parameters.get(0).unwrap()),
module.types.fp(FPType::FP128)
);
let f = module.get_func_by_name("takes_x86_fp80").unwrap();
assert_eq!(
module.type_of(f.parameters.get(0).unwrap()),
module.types.fp(FPType::X86_FP80)
);
let f = module.get_func_by_name("takes_ppc_fp128").unwrap();
assert_eq!(
module.type_of(f.parameters.get(0).unwrap()),
module.types.fp(FPType::PPC_FP128)
);
let f = module.get_func_by_name("returns_half").unwrap();
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(
f.return_type,
module.types.pointer_to(module.types.fp(FPType::Half))
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(f.return_type, module.types.pointer());
let f = module.get_func_by_name("returns_bfloat").unwrap();
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(
f.return_type,
module.types.pointer_to(module.types.fp(FPType::BFloat))
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(f.return_type, module.types.pointer());
let f = module.get_func_by_name("returns_float").unwrap();
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(
f.return_type,
module.types.pointer_to(module.types.fp(FPType::Single))
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(f.return_type, module.types.pointer());
let f = module.get_func_by_name("returns_double").unwrap();
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(
f.return_type,
module.types.pointer_to(module.types.fp(FPType::Double))
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(f.return_type, module.types.pointer());
let f = module.get_func_by_name("returns_fp128").unwrap();
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(
f.return_type,
module.types.pointer_to(module.types.fp(FPType::FP128))
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(f.return_type, module.types.pointer());
let f = module.get_func_by_name("returns_x86_fp80").unwrap();
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(
f.return_type,
module.types.pointer_to(module.types.fp(FPType::X86_FP80))
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(f.return_type, module.types.pointer());
let f = module.get_func_by_name("returns_ppc_fp128").unwrap();
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(
f.return_type,
module.types.pointer_to(module.types.fp(FPType::PPC_FP128))
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(f.return_type, module.types.pointer());
}
#[test]
fn datalayouts() {
init_logging();
let path = llvm_bc_dir().join("hello.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let data_layout = &module.data_layout;
#[cfg(feature = "llvm-10-or-greater")]
{
assert_eq!(
&data_layout.layout_str,
"e-m:o-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
);
assert_eq!(&data_layout.endianness, &Endianness::LittleEndian);
assert_eq!(&data_layout.mangling, &Some(Mangling::MachO));
assert_eq!(
data_layout.alignments.ptr_alignment(270),
&PointerLayout {
size: 32,
alignment: Alignment { abi: 32, pref: 32 },
index_size: 32
}
);
assert_eq!(
data_layout.alignments.ptr_alignment(271),
&PointerLayout {
size: 32,
alignment: Alignment { abi: 32, pref: 32 },
index_size: 32
}
);
assert_eq!(
data_layout.alignments.ptr_alignment(272),
&PointerLayout {
size: 64,
alignment: Alignment { abi: 64, pref: 64 },
index_size: 64
}
);
assert_eq!(
data_layout.alignments.ptr_alignment(0),
&PointerLayout {
size: 64,
alignment: Alignment { abi: 64, pref: 64 },
index_size: 64
}
);
assert_eq!(
data_layout.alignments.ptr_alignment(33),
&PointerLayout {
size: 64,
alignment: Alignment { abi: 64, pref: 64 },
index_size: 64
}
);
assert_eq!(
data_layout.alignments.int_alignment(64),
&Alignment { abi: 64, pref: 64 }
);
assert_eq!(
data_layout.alignments.int_alignment(7),
&Alignment { abi: 8, pref: 8 }
);
assert_eq!(
data_layout.alignments.int_alignment(26),
&Alignment { abi: 32, pref: 32 }
);
assert_eq!(
data_layout.alignments.int_alignment(123456),
&Alignment { abi: 64, pref: 64 }
);
assert_eq!(
data_layout.alignments.fp_alignment(FPType::Double),
&Alignment { abi: 64, pref: 64 }
);
assert_eq!(
data_layout.alignments.fp_alignment(FPType::X86_FP80),
&Alignment {
abi: 128,
pref: 128
}
);
assert_eq!(
data_layout
.native_int_widths
.as_ref()
.unwrap()
.iter()
.copied()
.sorted()
.collect::<Vec<_>>(),
vec![8, 16, 32, 64]
);
assert_eq!(data_layout.stack_alignment, Some(128));
}
#[cfg(feature = "llvm-9-or-lower")]
{
assert_eq!(
&data_layout.layout_str,
"e-m:o-i64:64-f80:128-n8:16:32:64-S128"
);
assert_eq!(&data_layout.endianness, &Endianness::LittleEndian);
assert_eq!(&data_layout.mangling, &Some(Mangling::MachO));
assert_eq!(
data_layout.alignments.ptr_alignment(0),
&PointerLayout {
size: 64,
alignment: Alignment { abi: 64, pref: 64 },
index_size: 64
}
);
assert_eq!(
data_layout.alignments.ptr_alignment(33),
&PointerLayout {
size: 64,
alignment: Alignment { abi: 64, pref: 64 },
index_size: 64
}
);
assert_eq!(
data_layout.alignments.int_alignment(64),
&Alignment { abi: 64, pref: 64 }
);
assert_eq!(
data_layout.alignments.int_alignment(7),
&Alignment { abi: 8, pref: 8 }
);
assert_eq!(
data_layout.alignments.int_alignment(26),
&Alignment { abi: 32, pref: 32 }
);
assert_eq!(
data_layout.alignments.int_alignment(123456),
&Alignment { abi: 64, pref: 64 }
);
assert_eq!(
data_layout.alignments.fp_alignment(FPType::Double),
&Alignment { abi: 64, pref: 64 }
);
assert_eq!(
data_layout.alignments.fp_alignment(FPType::X86_FP80),
&Alignment {
abi: 128,
pref: 128
}
);
assert_eq!(
data_layout
.native_int_widths
.as_ref()
.unwrap()
.iter()
.copied()
.sorted()
.collect::<Vec<_>>(),
vec![8, 16, 32, 64]
);
assert_eq!(data_layout.stack_alignment, Some(128));
}
assert_eq!(
data_layout.alignments.type_alignment(&module.types.int(26)),
&Alignment { abi: 32, pref: 32 }
);
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(
data_layout
.alignments
.type_alignment(&module.types.pointer_in_addr_space(module.types.int(32), 2)),
&Alignment { abi: 64, pref: 64 }
);
#[cfg(feature = "llvm-15-or-greater")]
assert_eq!(
data_layout
.alignments
.type_alignment(&module.types.pointer_in_addr_space(2)),
&Alignment { abi: 64, pref: 64 }
);
#[cfg(feature = "llvm-14-or-lower")]
assert_eq!(
data_layout
.alignments
.type_alignment(&module.types.pointer_to(module.types.func_type(
module.types.void(),
vec![],
false
))),
&Alignment { abi: 64, pref: 64 }
);
}
#[test]
fn throw() {
let _ = env_logger::builder().is_test(true).try_init(); // capture log messages with test harness
let path = cxx_llvm_bc_dir().join("throw.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
// See https://github.com/cdisselkoen/llvm-ir/pull/30
for func in module.functions {
for block in func.basic_blocks {
if let Terminator::Invoke(i) = block.term {
i.get_type(&module.types);
}
}
}
}
/*
#[test]
fn fences() {
init_logging();
let path = llvm_bc_dir().join("fences.ll.bc");
let module = Module::from_bc_path(&path).expect("Failed to parse module");
let f = module.get_func_by_name("fences").unwrap();
let block = &f.basic_blocks[0];
let seq_cst: &instruction::Fence = &block.instrs[0].clone().try_into().expect("Should be a fence");
assert_eq!(seq_cst.atomicity.mem_ordering, MemoryOrdering::SequentiallyConsistent);
let acq: &instruction::Fence = &block.instrs[1].clone().try_into().expect("Should be a fence");
assert_eq!(acq.atomicity.mem_ordering, MemoryOrdering::Acquire);
let rel: &instruction::Fence = &block.instrs[2].clone().try_into().expect("Should be a fence");
assert_eq!(rel.atomicity.mem_ordering, MemoryOrdering::Release);
let acq_rel: &instruction::Fence = &block.instrs[3].clone().try_into().expect("Should be a fence");
assert_eq!(acq_rel.atomicity.mem_ordering, MemoryOrdering::AcquireRelease);
let syncscope: &instruction::Fence = &block.instrs[4].clone().try_into().expect("Should be a fence");
assert_eq!(syncscope.atomicity.mem_ordering, MemoryOrdering::SequentiallyConsistent);
assert_eq!(syncscope.atomicity.synch_scope, SynchronizationScope::SingleThread);
}
*/
|
#![cfg(feature = "derive")]
use anyhow::Result;
use itertools::Itertools as _;
use pcd_rs::{
DataKind, DynRecord, Field, PcdDeserialize, PcdSerialize, Reader, Schema, ValueKind, WriterInit,
};
#[derive(Debug, PcdDeserialize, PcdSerialize, PartialEq)]
pub struct Point {
#[pcd(rename = "new_x")]
x: f32,
y: [u8; 3],
z: i32,
}
#[test]
fn write_ascii_static() -> Result<()> {
let path = "test_files/dump_ascii_static.pcd";
let dump_points = vec![
Point {
x: 3.14159,
y: [2, 1, 7],
z: -5,
},
Point {
x: -0.0,
y: [254, 6, 98],
z: 7,
},
Point {
x: 5.6,
y: [4, 0, 111],
z: -100000,
},
];
let mut writer = WriterInit {
width: 300,
height: 1,
viewpoint: Default::default(),
data_kind: DataKind::Ascii,
schema: None,
}
.create(path)?;
for point in &dump_points {
writer.push(point)?;
}
writer.finish()?;
let reader = Reader::open(path)?;
let load_points: Vec<Point> = reader.try_collect()?;
assert_eq!(dump_points, load_points);
std::fs::remove_file(path)?;
Ok(())
}
#[test]
fn write_binary_static() -> Result<()> {
let path = "test_files/dump_binary_static.pcd";
let dump_points = vec![
Point {
x: 3.14159,
y: [2, 1, 7],
z: -5,
},
Point {
x: -0.0,
y: [254, 6, 98],
z: 7,
},
Point {
x: 5.6,
y: [4, 0, 111],
z: -100000,
},
];
let mut writer = WriterInit {
width: 300,
height: 1,
viewpoint: Default::default(),
data_kind: DataKind::Binary,
schema: None,
}
.create(path)?;
for point in &dump_points {
writer.push(point)?;
}
writer.finish()?;
let reader = Reader::open(path)?;
let load_points: Vec<Point> = reader.try_collect()?;
assert_eq!(dump_points, load_points);
std::fs::remove_file(path)?;
Ok(())
}
#[test]
fn write_ascii_untyped() -> Result<()> {
let path = "test_files/dump_ascii_untyped.pcd";
let dump_points = vec![
DynRecord(vec![
Field::F32(vec![3.14159]),
Field::U8(vec![2, 1, 7]),
Field::I32(vec![-5]),
]),
DynRecord(vec![
Field::F32(vec![-0.0]),
Field::U8(vec![254, 6, 98]),
Field::I32(vec![7]),
]),
DynRecord(vec![
Field::F32(vec![5.6]),
Field::U8(vec![4, 0, 111]),
Field::I32(vec![-100000]),
]),
];
let schema = Schema::from_iter([
("x", ValueKind::F32, 1),
("y", ValueKind::U8, 3),
("z", ValueKind::I32, 1),
]);
let mut writer = WriterInit {
width: 300,
height: 1,
viewpoint: Default::default(),
data_kind: DataKind::Ascii,
schema: Some(schema),
}
.create(path)?;
for point in &dump_points {
writer.push(point)?;
}
writer.finish()?;
let reader: Reader<DynRecord, _> = Reader::open(path)?;
let load_points = reader.collect::<Result<Vec<_>>>()?;
assert_eq!(dump_points, load_points);
std::fs::remove_file(path)?;
Ok(())
}
#[test]
fn write_binary_untyped() -> Result<()> {
let path = "test_files/dump_binary_untyped.pcd";
let dump_points = vec![
DynRecord(vec![
Field::F32(vec![3.14159]),
Field::U8(vec![2, 1, 7]),
Field::I32(vec![-5]),
]),
DynRecord(vec![
Field::F32(vec![-0.0]),
Field::U8(vec![254, 6, 98]),
Field::I32(vec![7]),
]),
DynRecord(vec![
Field::F32(vec![5.6]),
Field::U8(vec![4, 0, 111]),
Field::I32(vec![-100000]),
]),
];
let schema = Schema::from_iter([
("x", ValueKind::F32, 1),
("y", ValueKind::U8, 3),
("z", ValueKind::I32, 1),
]);
let mut writer = WriterInit {
width: 300,
height: 1,
viewpoint: Default::default(),
data_kind: DataKind::Binary,
schema: Some(schema),
}
.create(path)?;
for point in &dump_points {
writer.push(point)?;
}
writer.finish()?;
let reader = Reader::open(path)?;
let load_points: Vec<DynRecord> = reader.try_collect()?;
assert_eq!(dump_points, load_points);
std::fs::remove_file(path)?;
Ok(())
}
|
// Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use address::Address;
use cid::Cid;
use encoding::Cbor;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use vm::Serialized;
/// Constructor parameters
pub struct ConstructorParams {
pub network_name: String,
}
impl Serialize for ConstructorParams {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
[&self.network_name].serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ConstructorParams {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let [network_name]: [String; 1] = Deserialize::deserialize(deserializer)?;
Ok(Self { network_name })
}
}
/// Exec Params
pub struct ExecParams {
pub code_cid: Cid,
pub constructor_params: Serialized,
}
impl Serialize for ExecParams {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(&self.code_cid, &self.constructor_params).serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ExecParams {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (code_cid, constructor_params) = Deserialize::deserialize(deserializer)?;
Ok(Self {
code_cid,
constructor_params,
})
}
}
/// Exec Return value
pub struct ExecReturn {
/// ID based address for created actor
pub id_address: Address,
/// Reorg safe address for actor
pub robust_address: Address,
}
impl Cbor for ExecReturn {}
impl Serialize for ExecReturn {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(&self.id_address, &self.robust_address).serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ExecReturn {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (id_address, robust_address) = Deserialize::deserialize(deserializer)?;
Ok(Self {
id_address,
robust_address,
})
}
}
|
mod modules;
fn main() {
println!("hello");
modules::hoge();
modules::hello_world::greet();
modules::greet();
}
|
use std::sync::Arc;
use std::marker::PhantomData;
use std::{fmt, mem, borrow, cmp, hash};
use std::ops::Deref;
/// Slightly bigger and slower than RMBA, but same functionality.
/// Mostly used just to verify correctness of the real RMBA.
#[derive(Debug)]
pub enum SlowRMBA<'a, T: 'a + ?Sized> {
Ref(&'a T),
RefMut(&'a mut T),
Box(Box<T>),
Arc(Arc<T>),
}
impl<'a, T: 'a + ?Sized> SlowRMBA<'a, T> {
/// Will return a clone if it contains a Arc<T> or &T, or None if it is a Box<T> or &mut T
pub fn try_clone(&self) -> Option<SlowRMBA<'a, T>> {
match self {
&SlowRMBA::Ref(ref t) => Some(SlowRMBA::Ref(t)),
&SlowRMBA::Arc(ref t) => Some(SlowRMBA::Arc(t.clone())),
_ => None,
}
}
/// Will return a &mut to inner contents if it contains a &mut T, a Box<T> or if the Arc<T> is unique. Otherwise returns None.
pub fn get_mut(&mut self) -> Option<&mut T> {
match self {
&mut SlowRMBA::RefMut(ref mut t) => Some(t),
&mut SlowRMBA::Box(ref mut t) => Some(t),
&mut SlowRMBA::Arc(ref mut t) => Arc::get_mut(t),
_ => None,
}
}
}
impl<'a, T: 'a + ?Sized> Deref for SlowRMBA<'a, T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
match self {
&SlowRMBA::Ref(ref t) => t,
&SlowRMBA::RefMut(ref t) => t,
&SlowRMBA::Box(ref t) => t,
&SlowRMBA::Arc(ref t) => t,
}
}
}
/// RMBA can store an &T, a &mut T, a Box<T> or an Arc<T>.
/// It will panic if you try to store a struct that's not 32 bit aligned.
///
/// Note: Drop flags were removed in 1.13-nightly. If you run an earlier version,
/// size might be larger than a single pointer due to the drop flag.
///
/// # Example
/// ```
/// use reffers::RMBA;
/// use std::{iter, sync};
///
/// // Uses Box if only one clone is needed, otherwise uses Arc.
/// fn make_a_few<'a, T>(t: T, count: usize) -> Vec<RMBA<'a, T>> {
/// match count {
/// 0 => vec![],
/// 1 => vec![RMBA::new_box(t)],
/// _ => iter::repeat(sync::Arc::new(t))
/// .take(count).map(|a| RMBA::from(a)).collect()
/// }
/// }
/// ```
pub struct RMBA<'a, T: 'a + ?Sized>(*const T, PhantomData<SlowRMBA<'a, T>>);
impl<'a, T: 'a> RMBA<'a, T> {
pub fn new_box(t: T) -> RMBA<'a, T> { Box::new(t).into() }
}
unsafe impl<'a, T: 'a + ?Sized + Send + Sync> Send for RMBA<'a, T> {}
impl<'a, T: 'a + ?Sized> RMBA<'a, T> {
#[inline]
fn unpack(&self) -> (*const T, usize) {
let mut p = self.0;
let f: *mut usize = (&mut p) as *mut _ as *mut usize;
unsafe {
let g = *f & 3;
*f = *f & (!3);
(p, g)
}
}
fn make(mut p: *const T, add: usize) -> RMBA<'a, T> {
let f: *mut usize = (&mut p) as *mut _ as *mut usize;
debug_assert!(add <= 3);
unsafe {
assert!(*f & 3 == 0);
*f = *f + add;
};
RMBA(p, PhantomData)
}
// Turns an already unpacked *const T into an Arc<T>.
// Relies on how Arc is done internally, and no checking done!
// Must be forgotten after use!
unsafe fn arc(mut p: *const T) -> Arc<T> {
use std::sync::atomic::AtomicUsize;
let f: *mut usize = (&mut p) as *mut _ as *mut usize;
*f = *f - 2*mem::size_of::<AtomicUsize>();
mem::transmute(p)
}
pub fn new<A: Into<RMBA<'a, T>>>(t: A) -> RMBA<'a, T> { t.into() }
/// Will return a clone if it contains a Arc<T> or &T, or None if it is a Box<T> or &mut T
pub fn try_clone(&self) -> Option<RMBA<'a, T>> {
match self.unpack() {
(_, 0) => Some(RMBA(self.0, PhantomData)),
(p, 2) => unsafe {
let a = Self::arc(p);
let r = Some(a.clone().into());
mem::forget(a);
r
},
_ => None,
}
}
/// Will return a &mut to inner contents if it contains a &mut T, a Box<T> or if the Arc<T> is unique. Otherwise returns None.
pub fn get_mut(&mut self) -> Option<&mut T> {
match self.unpack() {
(p, 1) => unsafe {
let mut b = Box::<T>::from_raw(p as *mut T);
let z: *mut T = &mut *b;
mem::forget(b);
Some(&mut *z)
},
(p, 2) => unsafe {
let mut a = Self::arc(p);
let r = mem::transmute(Arc::get_mut(&mut a));
mem::forget(a);
r
},
(p, 3) => unsafe { Some(&mut *(p as *mut T)) },
_ => None,
}
}
}
impl<'a, T: 'a + ?Sized> From<&'a T> for RMBA<'a, T> {
fn from(t: &'a T) -> RMBA<'a, T> { RMBA::make(t as *const T, 0) }
}
impl<'a, T: 'a + ?Sized> From<&'a mut T> for RMBA<'a, T> {
fn from(t: &'a mut T) -> RMBA<'a, T> { RMBA::make(t as *const T, 3) }
}
impl<'a, T: 'a + ?Sized> From<Box<T>> for RMBA<'a, T> {
fn from(t: Box<T>) -> RMBA<'a, T> { RMBA::make(Box::into_raw(t) as *const T, 1) }
}
impl<'a, T: 'a + ?Sized> From<Arc<T>> for RMBA<'a, T> {
fn from(t: Arc<T>) -> RMBA<'a, T> {
let z = RMBA::make(&*t, 2);
// debug_assert_eq!(unsafe { Self::arc(z.unpack().0) }, &t as *const Arc<T>);
mem::forget(t);
z
}
}
impl<'a, T: 'a + ?Sized> fmt::Debug for RMBA<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "RMBA({})", match self.unpack().1 { 0 => "&", 1 => "Box", 2 => "Arc", 3 => "&mut", _ => unreachable!() })
}
}
impl<'a, T: 'a + ?Sized> Deref for RMBA<'a, T> {
type Target = T;
#[inline]
fn deref(&self) -> &T { unsafe { &*self.unpack().0 }}
}
unsafe impl<'a, T: 'a + ?Sized> crate::StableDeref for RMBA<'a, T> {}
impl<'a, T: 'a + ?Sized> Drop for RMBA<'a, T> {
fn drop(&mut self) {
match self.unpack() {
(_, 0) => {},
(p, 1) => unsafe { let _ = Box::<T>::from_raw(p as *mut T); },
(p, 2) => unsafe { let _ = Self::arc(p); },
(_, 3) => {},
_ => unreachable!(),
}
}
}
impl<'a, T: 'a + ?Sized> AsRef<T> for RMBA<'a, T> {
fn as_ref(&self) -> &T {
&*self
}
}
impl<'a, T: 'a + ?Sized> borrow::Borrow<T> for RMBA<'a, T> {
fn borrow(&self) -> &T {
&*self
}
}
impl<'a, T: 'a + ?Sized + hash::Hash> hash::Hash for RMBA<'a, T> {
#[inline]
fn hash<H>(&self, state: &mut H) where H: hash::Hasher { (**self).hash(state) }
}
impl<'a, T: 'a + ?Sized + PartialEq> PartialEq for RMBA<'a, T> {
#[inline]
fn eq(&self, other: &Self) -> bool { **self == **other }
#[inline]
fn ne(&self, other: &Self) -> bool { **self != **other }
}
impl<'a, T: 'a + ?Sized + Eq> Eq for RMBA<'a, T> {}
impl<'a, T: 'a + ?Sized + PartialOrd> PartialOrd for RMBA<'a, T> {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { (**self).partial_cmp(&**other) }
#[inline]
fn lt(&self, other: &Self) -> bool { **self < **other }
#[inline]
fn le(&self, other: &Self) -> bool { **self <= **other }
#[inline]
fn gt(&self, other: &Self) -> bool { **self > **other }
#[inline]
fn ge(&self, other: &Self) -> bool { **self >= **other }
}
impl<'a, T: ?Sized + Ord> Ord for RMBA<'a, T> {
#[inline]
fn cmp(&self, other: &Self) -> cmp::Ordering { (**self).cmp(&**other) }
}
#[test]
fn rmba_fat() {
trait Dummy { fn foo(&self) -> i32; }
impl Dummy for u8 { fn foo(&self) -> i32 { *self as i32 } }
impl Dummy for i32 { fn foo(&self) -> i32 { *self } }
let z: SlowRMBA<dyn Dummy> = SlowRMBA::Box(Box::new(9u8));
let r: RMBA<dyn Dummy> = (Box::new(9i32) as Box<dyn Dummy>).into();
let a: RMBA<dyn Dummy> = (Arc::new(17i32) as Arc<dyn Dummy>).into();
assert_eq!(r.foo(), z.foo());
assert_eq!(a.try_clone().unwrap().foo(), 17i32);
}
#[test]
fn rmba_box() {
let mut z = RMBA::new_box(78);
assert!(z.try_clone().is_none());
assert_eq!(*z, 78);
*z.get_mut().unwrap() = 73;
assert_eq!(*z, 73);
assert!(z > RMBA::new_box(72));
assert!(z < RMBA::new_box(74));
assert!(z == RMBA::new(Arc::new(73)));
assert!(z != RMBA::new_box(75));
}
#[test]
fn rmba_arc() {
let mut a = Arc::new(53);
let mut f = RMBA::new(a.clone());
{
let f2: &i32 = &f;
assert_eq!(53, *f2);
}
assert!(f.get_mut().is_none());
assert!(Arc::get_mut(&mut a).is_none());
let z = f.try_clone().unwrap();
drop(f);
assert!(Arc::get_mut(&mut a).is_none());
drop(z);
assert!(Arc::get_mut(&mut a).is_some());
}
#[test]
#[should_panic]
fn rmba_unaligned() {
let b = vec![5u8, 7u8];
let _ = RMBA::new(&b[0]); // Either of these two will fail - u8 is not 32 bit aligned
let _ = RMBA::new(&b[1]);
}
#[test]
fn rmba_typical() {
struct Dummy {
a: Arc<i32>,
b: RMBA<'static, i32>,
}
let z = Arc::new(5i32);
let d = Dummy { a: z.clone(), b: RMBA::new(z) };
assert_eq!(&*d.b, &5i32);
assert_eq!(&*d.a, &5i32);
}
#[test]
fn rmba_sizes() {
use std::mem::size_of;
assert_eq!(size_of::<&i32>(), size_of::<RMBA<i32>>());
assert!(size_of::<RMBA<i32>>() < size_of::<SlowRMBA<i32>>());
}
|
mod auth;
mod common;
mod inbound;
mod outbound;
mod relay;
mod server;
mod utils;
use anyhow::{Context, Result};
use clap::{AppSettings, Clap};
use log::error;
use utils::{config, logger};
#[derive(Clap)]
#[clap(version, author, about)]
#[clap(setting = AppSettings::ColoredHelp)]
struct Opts {
#[clap(short, long, default_value = "config.toml")]
config: String,
#[clap(long, default_value = "info", env = "LOGLEVEL")]
log_level: String,
}
async fn start(config: &str) -> Result<()> {
let config = config::load(config).context("Failed to parse config")?;
server::start(config)
.await
.context("Failed to start service")?;
Ok(())
}
#[tokio::main]
async fn main() -> Result<()> {
let opts = Opts::parse();
logger::setup_logger(opts.log_level.as_str())?;
if let Err(e) = start(opts.config.as_str()).await {
error!("{:?}", e);
}
Ok(())
}
|
extern crate cribbage;
use serde::{Deserialize, Serialize};
use std::io::{Read, Write};
use std::net;
use std::sync::mpsc;
// Simply sends the message to the client and guarantees its arrival
fn simple_notification(
client_stream: &mut net::TcpStream,
game_handler_transmitter: &mpsc::Sender<super::messages::ClientToGame>,
message: super::messages::GameToClient,
) {
client_stream
.write(&bincode::serialize(&message).unwrap())
.unwrap();
client_stream.flush().unwrap();
game_handler_transmitter
.send(super::messages::ClientToGame::TransmissionReceived)
.unwrap();
}
// Polls for a Confirmation message from the client and forwards it to the game handler when it is
// received
fn confirmation_request(
client_stream: &mut net::TcpStream,
game_handler_transmitter: &mpsc::Sender<super::messages::ClientToGame>,
message: super::messages::GameToClient,
) {
let mut packet_from_client = [0 as u8; 256];
let mut has_sent_confirmation = false;
while !has_sent_confirmation {
simple_notification(client_stream, game_handler_transmitter, message.clone());
client_stream.read(&mut packet_from_client).unwrap();
let client_to_game: super::messages::ClientToGame =
bincode::deserialize(&packet_from_client).unwrap();
match client_to_game {
super::messages::ClientToGame::Confirmation => {
game_handler_transmitter
.send(super::messages::ClientToGame::Confirmation)
.unwrap();
has_sent_confirmation = true;
}
_ => {
packet_from_client = [0 as u8; 256];
}
}
}
}
// Handles input and output to each client
pub fn handle_client(
// The TCP stream the handler takes for the client given when spawning the thread
mut client_stream: net::TcpStream,
// The transmitter used to send messages to the game thread; shared with the other clients
game_handler_transmitter: mpsc::Sender<super::messages::ClientToGame>,
game_handler_receiver: mpsc::Receiver<super::messages::GameToClient>,
) {
let mut is_disconncted = false;
game_handler_transmitter
.send(super::messages::ClientToGame::Greeting)
.unwrap();
// While the connection is accepted
while !is_disconncted {
// Forward message from receiver to the client then wait for client response
match game_handler_receiver.recv() {
// When all the maximum number of players has been connected and the connection is
// denied
Ok(super::messages::GameToClient::DeniedTableFull) => {
simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::DeniedTableFull,
);
}
// Accepts the player's name
// TODO Confirm name is not already in use
Ok(super::messages::GameToClient::WaitName) => {
let mut packet_from_client = [0 as u8; 256];
let mut valid_name = false;
while !valid_name {
simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::WaitName,
);
client_stream.read(&mut packet_from_client).unwrap();
let client_to_game: super::messages::ClientToGame =
bincode::deserialize(&packet_from_client).unwrap();
match client_to_game {
super::messages::ClientToGame::Name(name) => {
valid_name = true;
game_handler_transmitter
.send(super::messages::ClientToGame::Name(name))
.unwrap();
}
_ => {
packet_from_client = [0 as u8; 256];
}
};
}
}
Ok(super::messages::GameToClient::PlayerJoinNotification { name, number, of }) => {
simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::PlayerJoinNotification { name, number, of },
)
}
Ok(super::messages::GameToClient::WaitInitialCut) => confirmation_request(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::WaitInitialCut,
),
Ok(super::messages::GameToClient::InitialCutResult { name, card }) => {
simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::InitialCutResult { name, card },
);
}
Ok(super::messages::GameToClient::InitialCutSuccess(name)) => {
simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::InitialCutSuccess(name),
);
}
Ok(super::messages::GameToClient::InitialCutFailure) => {
simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::InitialCutFailure,
);
}
Ok(super::messages::GameToClient::WaitDeal) => {
confirmation_request(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::WaitDeal,
);
}
Ok(super::messages::GameToClient::Dealing) => {
simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::Dealing,
);
}
Ok(super::messages::GameToClient::DealtHand(hand)) => {
simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::DealtHand(hand),
);
}
Ok(super::messages::GameToClient::WaitDiscardOne) => {
let mut packet_from_client = [0 as u8; 256];
simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::WaitDiscardOne,
);
// Check for input from the client and forward DiscardPlaced messages
client_stream.set_nonblocking(true).unwrap();
let mut received_discard_message = false;
while !received_discard_message {
match client_stream.read(&mut packet_from_client) {
Ok(_) => {
let client_to_game: super::messages::ClientToGame =
bincode::deserialize(&packet_from_client).unwrap();
match client_to_game {
super::messages::ClientToGame::DiscardOne { index } => {
game_handler_transmitter
.send(super::messages::ClientToGame::DiscardOne { index })
.unwrap();
received_discard_message = true;
packet_from_client = [0 as u8; 256];
}
_ => {
packet_from_client = [0 as u8; 256];
}
}
}
_ => {}
};
match game_handler_receiver.try_recv() {
Ok(super::messages::GameToClient::DiscardPlacedOne(name)) => simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::DiscardPlacedOne(name),
),
Ok(_) => println!("Invalid message to client when trying to receive a DiscardPlacedOne message"),
_ => {},
};
}
client_stream.set_nonblocking(false).unwrap();
}
Ok(super::messages::GameToClient::WaitDiscardTwo) => {
let mut packet_from_client = [0 as u8; 256];
simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::WaitDiscardTwo,
);
// Check for input from the client and forward DiscardPlaced messages
client_stream.set_nonblocking(true).unwrap();
let mut received_discard_message = false;
while !received_discard_message {
match client_stream.read(&mut packet_from_client) {
Ok(_) => {
let client_to_game: super::messages::ClientToGame =
bincode::deserialize(&packet_from_client).unwrap();
match client_to_game {
super::messages::ClientToGame::DiscardTwo {
index_one,
index_two,
} => {
game_handler_transmitter
.send(super::messages::ClientToGame::DiscardTwo {
index_one,
index_two,
})
.unwrap();
received_discard_message = true;
packet_from_client = [0 as u8; 256];
}
_ => {
packet_from_client = [0 as u8; 256];
}
}
}
_ => {}
};
match game_handler_receiver.try_recv() {
Ok(super::messages::GameToClient::DiscardPlacedTwo(name)) => simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::DiscardPlacedTwo(name),
),
Ok(_) => println!("Invalid message to client when trying to receive a DiscardPlacedTwo message"),
_ => {},
};
}
client_stream.set_nonblocking(false).unwrap();
}
Ok(super::messages::GameToClient::DiscardPlacedOne(name)) => simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::DiscardPlacedOne(name),
),
Ok(super::messages::GameToClient::DiscardPlacedTwo(name)) => simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::DiscardPlacedTwo(name),
),
Ok(super::messages::GameToClient::AllDiscards) => {
simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::AllDiscards,
);
}
Ok(super::messages::GameToClient::CutStarter(name, card)) => {
println!("Sending CutStarter");
simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::CutStarter(name, card),
);
println!("Sent CutStarter");
}
Ok(super::messages::GameToClient::WaitCutStarter) => {
confirmation_request(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::WaitCutStarter,
);
}
Ok(super::messages::GameToClient::Disconnect) => {
is_disconncted = true;
simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::Disconnect,
);
}
_ => {
println!("Unexpected message from game handler");
simple_notification(
&mut client_stream,
&game_handler_transmitter,
super::messages::GameToClient::Error(String::from(
"Unexpected message from game handler",
)),
);
is_disconncted = true;
}
}
}
}
|
use crate::math::{Mat2d, Rect, Vec2};
use core::ecs::Entity;
use std::collections::HashMap;
#[derive(Debug, Default)]
pub struct CompositeTransformCache {
matrix: HashMap<Entity, Mat2d>,
matrix_inverse: HashMap<Entity, Mat2d>,
}
impl CompositeTransformCache {
pub fn matrix(&self, entity: Entity) -> Option<Mat2d> {
self.matrix.get(&entity).copied()
}
pub fn inverse_matrix(&self, entity: Entity) -> Option<Mat2d> {
self.matrix_inverse.get(&entity).copied()
}
pub fn insert(&mut self, entity: Entity, matrix: Mat2d) {
self.matrix.insert(entity, matrix);
self.matrix_inverse
.insert(entity, (!matrix).unwrap_or_default());
}
pub fn remove(&mut self, entity: Entity) {
self.matrix.remove(&entity);
self.matrix_inverse.remove(&entity);
}
pub fn clear(&mut self) {
self.matrix.clear();
self.matrix_inverse.clear();
}
}
#[derive(Debug, Default)]
pub struct CompositeCameraCache {
pub(crate) last_view_size: Vec2,
pub(crate) world_transforms: HashMap<Entity, Mat2d>,
pub(crate) world_inverse_transforms: HashMap<Entity, Mat2d>,
}
impl CompositeCameraCache {
pub fn last_view_size(&self) -> Vec2 {
self.last_view_size
}
pub fn screen_to_world_space(&self, entity: Entity, point: Vec2) -> Option<Vec2> {
self.world_inverse_transforms
.get(&entity)
.map(|m| *m * point)
}
pub fn world_to_screen_space(&self, entity: Entity, point: Vec2) -> Option<Vec2> {
self.world_transforms.get(&entity).map(|m| *m * point)
}
pub fn world_transform(&self, entity: Entity) -> Option<Mat2d> {
self.world_transforms.get(&entity).cloned()
}
pub fn world_inverse_transform(&self, entity: Entity) -> Option<Mat2d> {
self.world_inverse_transforms.get(&entity).cloned()
}
pub fn world_both_transforms(&self, entity: Entity) -> Option<(Mat2d, Mat2d)> {
if let Some(t) = self.world_transforms.get(&entity) {
if let Some(i) = self.world_inverse_transforms.get(&entity) {
return Some((*t, *i));
}
}
None
}
pub fn calculate_view_box(&self, entity: Entity) -> Option<Rect> {
let m = self.world_inverse_transforms.get(&entity)?;
let p1 = *m * Vec2::new(0.0, 0.0);
let p2 = *m * Vec2::new(self.last_view_size.x, 0.0);
let p3 = *m * self.last_view_size;
let p4 = *m * Vec2::new(0.0, self.last_view_size.y);
Rect::bounding(&[p1, p2, p3, p4])
}
pub fn calculate_world_size(&self, entity: Entity) -> Option<Vec2> {
let m = self.world_inverse_transforms.get(&entity)?;
let p1 = *m * Vec2::new(0.0, 0.0);
let p2 = *m * Vec2::new(self.last_view_size.x, 0.0);
let p3 = *m * Vec2::new(0.0, self.last_view_size.y);
Some(Vec2::new((p2 - p1).magnitude(), (p3 - p1).magnitude()))
}
}
|
mod binary;
mod decoder;
mod types;
mod instructions;
use binary::module::Module;
use binary::module::Section;
use binary::*;
use binary::exportsection::ExportSection;
use decoder::Decoder;
use std::fs::File;
use std::io;
use std::io::BufReader;
use std::io::Read;
fn main() {
let wasm = File::open("./add.wasm").unwrap();
let reader = BufReader::new(wasm);
let mut decoder = Decoder::new(reader);
if let Ok(module) = Module::decode(&mut decoder) {
println!("{:?}", "Module decoded successfully");
for section in module.sections {
if let Section::Export(exportsection) = section {
let ExportSection(exports) = exportsection;
println!("First export name {}", exports[0].name);
}
}
};
}
|
pub mod file;
pub mod url_parser;
pub mod url_util;
pub mod date_util; |
// Copyright 2017 rust-ipfs-api Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//
use clap::{App, ArgMatches};
use command::EXPECTED_API;
use ipfs_api::IpfsClient;
use tokio_core::reactor::Core;
pub fn signature<'a, 'b>() -> App<'a, 'b> {
clap_app!(
@subcommand bitswap =>
(@setting SubcommandRequiredElseHelp)
(@subcommand ledger =>
(about: "Show the current ledger for a peer")
(@arg PEER: +required "Peer to inspect")
)
(@subcommand stat =>
(about: "Show some diagnostic information on the bitswap agent")
)
(@subcommand unwant =>
(about: "Remove a given block from your wantlist")
(@arg KEY: +required "Key of the block to remove")
)
(@subcommand wantlist =>
(about: "Shows blocks currently on the wantlist")
)
)
}
pub fn handle(core: &mut Core, client: &IpfsClient, args: &ArgMatches) {
match args.subcommand() {
("ledger", Some(args)) => {
let peer = args.value_of("PEER").unwrap();
let ledger = core.run(client.bitswap_ledger(&peer)).expect(EXPECTED_API);
println!("");
println!(" peer : {}", ledger.peer);
println!(" value : {}", ledger.value);
println!(" sent : {}", ledger.sent);
println!(" recv : {}", ledger.recv);
println!(" exchanged : {}", ledger.exchanged);
println!("");
}
("stat", _) => {
let stat = core.run(client.bitswap_stat()).expect(EXPECTED_API);
println!("");
println!(" provide_buf_len : {}", stat.provide_buf_len);
println!(" wantlist :");
for want in stat.wantlist {
println!(" {}", want);
}
println!(" peers :");
for peer in stat.peers {
println!(" {}", peer);
}
println!(" blocks_received : {}", stat.blocks_received);
println!(" data_received : {}", stat.data_received);
println!(" blocks_sent : {}", stat.blocks_sent);
println!(" data_sent : {}", stat.data_sent);
println!(" dup_blks_received : {}", stat.dup_blks_received);
println!(" dup_data_received : {}", stat.dup_data_received);
println!("");
}
("unwant", Some(args)) => {
let key = args.value_of("KEY").unwrap();
core.run(client.bitswap_unwant(&key)).expect(EXPECTED_API);
println!("");
println!(" OK");
println!("");
}
("wantlist", Some(args)) => {
let peer = args.value_of("PEER");
let wantlist = core.run(client.bitswap_wantlist(peer)).expect(EXPECTED_API);
println!("");
println!(" wantlist :");
for key in wantlist.keys {
println!(" {}", key);
}
println!("");
}
_ => unreachable!(),
}
}
|
use sqlparser::ast::Statement;
use sqlparser::dialect::Dialect;
use sqlparser::parser::{Parser as SqlParser, ParserError};
pub mod collector;
pub mod rewriter;
pub struct Parser {}
impl Parser {
/// Parse SQL using our CSVDialect
pub fn parse_sql(str: &str) -> Result<Vec<Statement>, ParserError> {
SqlParser::parse_sql(&CsvDialect, str)
}
}
#[derive(Debug, Default)]
/// SQL Dialect based off of SQLite dialect but allowing common path characters to be used as well
pub struct CsvDialect;
impl Dialect for CsvDialect {
fn is_delimited_identifier_start(&self, ch: char) -> bool {
ch == '`' || ch == '"' || ch == '['
}
#[allow(clippy::nonminimal_bool)]
fn is_identifier_start(&self, ch: char) -> bool {
// See https://www.sqlite.org/draft/tokenreq.html
('a'..='z').contains(&ch)
|| ('A'..='Z').contains(&ch)
|| ch == '_'
|| ch == '$'
|| ('\u{007f}'..='\u{ffff}').contains(&ch)
|| ch == '_'
|| ch == '_'
|| ch == '.'
|| ch == '/'
}
fn is_identifier_part(&self, ch: char) -> bool {
self.is_identifier_start(ch) || ('0'..='9').contains(&ch)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_parses_sql_with_filenames_for_tables() {
let sql = "select * from ./foo.csv";
let ast = Parser::parse_sql(sql).unwrap();
assert_eq!(ast[0].to_string(), "SELECT * FROM ./foo.csv");
println!("AST: {:?}", ast)
}
#[test]
fn it_parses_sql_with_filenames_for_tables_in_subqueries() {
let sql = "select * from (select * from ./foo.csv)";
let ast = Parser::parse_sql(sql).unwrap();
assert_eq!(
ast[0].to_string(),
"SELECT * FROM (SELECT * FROM ./foo.csv)"
);
println!("AST: {:?}", ast)
}
#[test]
fn it_parses_sql_with_backticks_around_columns_with_spaces() {
let sql = "select * from (select ` foo bar` from ./file.csv)";
let ast = Parser::parse_sql(sql).unwrap();
assert_eq!(
ast[0].to_string(),
"SELECT * FROM (SELECT ` foo bar` FROM ./file.csv)"
);
println!("AST: {:?}", ast)
}
#[test]
fn it_parses_sql_files_with_spaces_with_backticks_around_filename() {
let sql = "select * from (select foo from `./file with spaces.csv`)";
let ast = Parser::parse_sql(sql).unwrap();
assert_eq!(
ast[0].to_string(),
"SELECT * FROM (SELECT foo FROM `./file with spaces.csv`)"
);
println!("AST: {:?}", ast)
}
}
|
pub mod screens;
use oxygengine::user_interface::raui::core::prelude::*;
pub fn setup(app: &mut Application) {
app.register_component("intro", screens::intro::intro);
app.register_component("loading", screens::loading::loading);
app.register_component("menu", screens::menu::menu);
app.register_component("gui", screens::gui::gui);
}
|
extern crate rand;
extern crate time;
extern crate crypto;
extern crate nix;
use rand::{Rng, SeedableRng, StdRng};
use rand::distributions::{IndependentSample, Range};
use crypto::md5::Md5;
use crypto::digest::Digest;
use nix::sys::statfs::statfs;
use nix::sys::statfs::vfs::Statfs;
use std::cmp;
use std::path::Path;
use std::path::PathBuf;
use std::fs;
use std::fs::metadata;
use std::fs::File;
use std::io;
use std::io::{Read, Write};
use std::vec::Vec;
use std::process::exit;
use std::env;
use nix::sys::signal;
static mut exit_please: bool = false;
extern fn handle_sigint(_:i32) {
unsafe {
exit_please = true;
}
}
fn disk_usage(path : &str) -> (u64, u64) {
let mut fs = Statfs {f_bavail: 0, f_bfree: 0, f_type: 0, f_frsize: 0,
f_ffree: 0, f_namelen: 0, f_fsid: 0, f_blocks: 0,
f_files: 0, f_spare: [0,0,0,0,0], f_bsize: 0};
statfs(path, &mut fs).unwrap();
let free = (fs.f_bsize as u64 * fs.f_bfree) as u64;
let total = (fs.f_bsize as u64 * fs.f_blocks) as u64;
(total, free)
}
fn rs(seed: usize, file_size: usize) -> String {
let s: &[_] = &[seed];
let mut rng: StdRng = SeedableRng::from_seed(s);
rng.gen_ascii_chars().take(file_size).collect()
}
fn md5_sum(data: &str) -> String {
let mut hasher = Md5::new();
hasher.input_str(data);
hasher.result_str()
}
fn is_directory(path: &str) -> bool {
match metadata(path) {
Ok(n) => n.is_dir(),
Err(_) => false,
}
}
fn run(directory: &str) {
let mut files_created = Vec::new();
let mut num_files_created = 0;
let mut total_bytes: u64 = 0;
let mut l_exit = false;
while l_exit == false {
match create_file(directory, None, None) {
Ok((f_created, size)) => {
num_files_created += 1;
total_bytes += size as u64;
files_created.push(f_created);
},
Err(_) => {
println!("Full, verify and delete sequence starting...");
// Walk the list, verifying every file
for f in &files_created {
if let Err(_) = verify_file(f) {
println!("File {} not validating!", f.display());
println!("We created {} files with a total of {} bytes!",
num_files_created, total_bytes);
exit(1);
}
}
// Delete every other file
let count = files_created.len();
for i in (0..count).rev().filter(|&x| x % 2 == 0) {
let file_to_delete = files_created.remove(i);
//println!("Deleting file {}", file_to_delete);
let error_msg = format!("Error: Unable to remove file {}!",
file_to_delete.display());
fs::remove_file(file_to_delete).expect(&error_msg);
}
},
}
unsafe {
l_exit = exit_please;
}
}
println!("We created {} files with a total of {} bytes!",
num_files_created, total_bytes);
}
fn create_file(directory: &str, seed: Option<usize>, file_size: Option<usize>) -> io::Result<(PathBuf, u64)> {
let (f_total, f_free) = disk_usage(directory);
let l_file_size = match file_size {
Some(size) => size,
None => {
let between = Range::new(512, 1024*1024*8);
let mut rng = rand::thread_rng();
let available = (f_total as f64 * 0.5) as u64;
if f_free <= available {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("f_free {} <= available {}", f_free, available)));
}
let tmp_file_size = between.ind_sample(&mut rng);
cmp::min((f_free - available) as usize, tmp_file_size)
}
};
let l_seed = match seed {
Some(seed) => seed,
None => time::get_time().sec as usize,
};
let data = rs(l_seed, l_file_size);
let file_hash = md5_sum(&data[..]);
//Build the file name
let file_name = format!("{}-{}-{}", file_hash, l_seed, l_file_size);
let file_name_hash = md5_sum(&file_name[..]);
//Build full file name and path
let mut final_name = PathBuf::from(directory);
final_name.push(format!("{}:{}:integrity", file_name, file_name_hash));
let final_name = {
if !final_name.exists() {
final_name
} else {
match (0..50)
.map(|num| final_name.with_file_name(
format!("{}.{}", final_name.display(), num)))
.find(|pathbuf| !pathbuf.exists()) {
Some(x) => x,
None => return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("Could not generate unique name for {}",
final_name.display())))
}
}
};
let mut f = try!(File::create(&final_name));
f.write_all(data.as_bytes()).expect("Shorted write?");
Ok((final_name, l_file_size as u64))
}
fn verify_file(full_file_name: &Path) -> io::Result<()> {
// First verify the meta data is intact
let f_name = Path::new(full_file_name).file_name().unwrap().to_str().unwrap();
let parts = f_name.split(":").collect::<Vec<&str>>();
let name = parts[0];
let meta_hash = parts[1];
let extension = parts[2];
// Check extension
if extension.starts_with("integrity") != true {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("File extension {} does not end in \"integrity*\"!",
full_file_name.display())));
}
// Check metadata
let f_hash = md5_sum(name);
if meta_hash != f_hash {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("File {} meta data not valid! (stored = {}, calculated = {})",
full_file_name.display(), meta_hash, f_hash)));
}
let name_parts = name.split("-").collect::<Vec<&str>>();
let file_data_hash = name_parts[0];
let meta_size = name_parts[2].parse::<u64>().unwrap();
let file_size = try!(metadata(full_file_name)).len();
if meta_size != file_size {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("File {} incorrect size! (expected = {}, current = {})\n",
full_file_name.display(), meta_size, file_size)));
}
// Read in the data
let mut data = String::new();
let mut f = try!(File::open(full_file_name));
f.read_to_string(&mut data).expect("Shorted read?");
// Generate the md5
let calculated = md5_sum(&data);
// Compare md5
if file_data_hash != calculated {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("File {} md5 miss-match! (expected = {}, current = {})",
full_file_name.display(), file_data_hash, calculated)));
}
Ok(())
}
fn syntax() {
let prg = &env::args().nth(0).unwrap();
println!("Usage: {} \n[-h] [-vf <file> | -r <directory> |-rc \
<directory> <seed> <size>]\n", prg);
exit(1);
}
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
syntax();
}
let sig_action = signal::SigAction::new(
signal::SigHandler::Handler(handle_sigint),
signal::SaFlag::empty(),
signal::SigSet::empty());
unsafe {
signal::sigaction(signal::SIGINT, &sig_action).
expect("Unable to install signal handler!");
}
if args[1] == "-r" && args.len() == 3 {
// Run test
let d = &args[2];
if is_directory(d) {
run(d);
} else {
println!("{} is not a directory!", d);
exit(1);
}
} else if args[1] == "-vf" && args.len() == 3 {
// Verify file
let f = PathBuf::from(&args[2]);
if let Err(_) = verify_file(&f) {
println!("File {} corrupt [ERROR]!\n", f.display());
exit(2);
}
println!("File {} validates [OK]!\n", f.display());
exit(0);
} else if args[1] == "-rc" && args.len() == 5 {
// Re-create a file
let d = &args[2];
if is_directory(d) == false {
println!("{} is not a directory!", d);
exit(1);
}
let seed = args[3].parse::<usize>().unwrap();
let file_size = args[4].parse::<usize>().unwrap();
if let Ok((f, _)) = create_file(d, Some(seed), Some(file_size)) {
println!("File recreated as {}" , f.display());
exit(0);
}
exit(1);
} else if args[1] == "-h"{
syntax();
} else {
syntax();
}
}
|
use clap::clap_app;
use rustbust::fuzz;
use std::error::Error;
fn main() -> Result<(), Box<Error>> {
let matches = clap_app!(fuzz =>
(about: "Fuzzes a webpage, but in a fail-safe and parallel way")
(version: "0.1.0")
(@arg URL: +required "URL to fuzz")
(@arg source: -s --source +takes_value +required "Wordlist (file/directory) to use. Uses ./common.txt by default")
(@arg parallel_count: -p --parallel_count +takes_value "Set number of parallel requests")
(@arg outfile: -o --outfile +takes_value "Set the file to write output to")
)
.get_matches();
let url = matches.value_of("URL").unwrap();
let url = if url.chars().nth(url.len() - 1) == Some('/') {
&url[0..url.len() - 1]
} else {
url
};
fuzz(
url,
matches.value_of("source").unwrap(),
matches.value_of("parallel_count"),
matches.value_of("outfile"),
)?;
Ok(())
}
|
mod codec;
mod handshake;
pub use self::{codec::ApCodec, handshake::handshake};
use std::io;
use futures_util::{SinkExt, StreamExt};
use num_traits::FromPrimitive;
use protobuf::{self, Message};
use thiserror::Error;
use tokio::net::TcpStream;
use tokio_util::codec::Framed;
use url::Url;
use crate::{authentication::Credentials, packet::PacketType, version, Error};
use crate::protocol::keyexchange::{APLoginFailed, ErrorCode};
pub type Transport = Framed<TcpStream, ApCodec>;
fn login_error_message(code: &ErrorCode) -> &'static str {
pub use ErrorCode::*;
match code {
ProtocolError => "Protocol error",
TryAnotherAP => "Try another access point",
BadConnectionId => "Bad connection ID",
TravelRestriction => "Travel restriction",
PremiumAccountRequired => "Premium account required",
BadCredentials => "Bad credentials",
CouldNotValidateCredentials => "Could not validate credentials",
AccountExists => "Account exists",
ExtraVerificationRequired => "Extra verification required",
InvalidAppKey => "Invalid app key",
ApplicationBanned => "Application banned",
}
}
#[derive(Debug, Error)]
pub enum AuthenticationError {
#[error("Login failed with reason: {}", login_error_message(.0))]
LoginFailed(ErrorCode),
#[error("invalid packet {0}")]
Packet(u8),
#[error("transport returned no data")]
Transport,
}
impl From<AuthenticationError> for Error {
fn from(err: AuthenticationError) -> Self {
match err {
AuthenticationError::LoginFailed(_) => Error::permission_denied(err),
AuthenticationError::Packet(_) => Error::unimplemented(err),
AuthenticationError::Transport => Error::unavailable(err),
}
}
}
impl From<APLoginFailed> for AuthenticationError {
fn from(login_failure: APLoginFailed) -> Self {
Self::LoginFailed(login_failure.error_code())
}
}
pub async fn connect(host: &str, port: u16, proxy: Option<&Url>) -> io::Result<Transport> {
let socket = crate::socket::connect(host, port, proxy).await?;
handshake(socket).await
}
pub async fn authenticate(
transport: &mut Transport,
credentials: Credentials,
device_id: &str,
) -> Result<Credentials, Error> {
use crate::protocol::authentication::{APWelcome, ClientResponseEncrypted, CpuFamily, Os};
let cpu_family = match std::env::consts::ARCH {
"blackfin" => CpuFamily::CPU_BLACKFIN,
"arm" | "arm64" => CpuFamily::CPU_ARM,
"ia64" => CpuFamily::CPU_IA64,
"mips" => CpuFamily::CPU_MIPS,
"ppc" => CpuFamily::CPU_PPC,
"ppc64" => CpuFamily::CPU_PPC_64,
"sh" => CpuFamily::CPU_SH,
"x86" => CpuFamily::CPU_X86,
"x86_64" => CpuFamily::CPU_X86_64,
_ => CpuFamily::CPU_UNKNOWN,
};
let os = match std::env::consts::OS {
"android" => Os::OS_ANDROID,
"freebsd" | "netbsd" | "openbsd" => Os::OS_FREEBSD,
"ios" => Os::OS_IPHONE,
"linux" => Os::OS_LINUX,
"macos" => Os::OS_OSX,
"windows" => Os::OS_WINDOWS,
_ => Os::OS_UNKNOWN,
};
let mut packet = ClientResponseEncrypted::new();
packet
.login_credentials
.mut_or_insert_default()
.set_username(credentials.username);
packet
.login_credentials
.mut_or_insert_default()
.set_typ(credentials.auth_type);
packet
.login_credentials
.mut_or_insert_default()
.set_auth_data(credentials.auth_data);
packet
.system_info
.mut_or_insert_default()
.set_cpu_family(cpu_family);
packet.system_info.mut_or_insert_default().set_os(os);
packet
.system_info
.mut_or_insert_default()
.set_system_information_string(format!(
"librespot-{}-{}",
version::SHA_SHORT,
version::BUILD_ID
));
packet
.system_info
.mut_or_insert_default()
.set_device_id(device_id.to_string());
packet.set_version_string(format!("librespot {}", version::SEMVER));
let cmd = PacketType::Login;
let data = packet.write_to_bytes()?;
transport.send((cmd as u8, data)).await?;
let (cmd, data) = transport
.next()
.await
.ok_or(AuthenticationError::Transport)??;
let packet_type = FromPrimitive::from_u8(cmd);
let result = match packet_type {
Some(PacketType::APWelcome) => {
let welcome_data = APWelcome::parse_from_bytes(data.as_ref())?;
let reusable_credentials = Credentials {
username: welcome_data.canonical_username().to_owned(),
auth_type: welcome_data.reusable_auth_credentials_type(),
auth_data: welcome_data.reusable_auth_credentials().to_owned(),
};
Ok(reusable_credentials)
}
Some(PacketType::AuthFailure) => {
let error_data = APLoginFailed::parse_from_bytes(data.as_ref())?;
Err(error_data.into())
}
_ => {
trace!(
"Did not expect {:?} AES key packet with data {:#?}",
cmd,
data
);
Err(AuthenticationError::Packet(cmd))
}
};
Ok(result?)
}
|
pub fn run() {
let age = 21;
let knows_person_of_age: bool = true;
if age >= 21 || knows_person_of_age {
println!("Give a beer");
} else {
println!("Give a candy");
}
//Short hand if
let is_of_age = if age >= 21 { true } else { false };
println!("is Of age : {}", is_of_age);
}
|
use reqwest::Client;
use crate::storage::request_text;
#[derive(Serialize, Deserialize, Debug)]
pub struct Request {
// id: String,
pub url: String,
// unique_key: String,
// method: String,
// payload: String,
// retry: bool,
// retry_count: i32,
// error_messages: Vec<String>,
// headers: HashMap<String, String>,
// user_data: HashMap<String, String>,
// handled_at: String
}
impl Request {
pub fn new(url: String) -> Self {
Request {
url
}
}
pub async fn fetch(&self, client: &Client) -> String {
request_text(&client, &self.url).await.unwrap_or_else(|err| {
debugln!("{}", err);
"".to_owned()
})
}
}
impl Clone for Request {
fn clone(&self) -> Self {
Request {
url: self.url.clone()
}
}
}
|
// ObjectVersions
#![forbid(unsafe_code)]
#![deny(missing_docs)]
use anyhow::Result;
use std::str::FromStr;
/// `ObjectVersions` represents which objects we're going to sum when
/// operating in S3 mode.
#[derive(Debug)]
pub enum ObjectVersions {
/// Sum size of all object versions (both `Current` and `NonCurrent`)
All,
/// Sum only size of current objects
Current,
/// Sum only size of in-progress multipart uploads
Multipart,
/// Sum only size of non-current objects
NonCurrent,
}
/// This converts from the string argument we receive from the command line to
/// our enum type.
impl FromStr for ObjectVersions {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"all" => Ok(Self::All),
"current" => Ok(Self::Current),
"multipart" => Ok(Self::Multipart),
"non-current" => Ok(Self::NonCurrent),
_ => Err("no match"),
}
}
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// SloHistoryMetricsSeriesMetadataUnit : An Object of metric units.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SloHistoryMetricsSeriesMetadataUnit {
/// The family of metric unit, for example `bytes` is the family for `kibibyte`, `byte`, and `bit` units.
#[serde(rename = "family", skip_serializing_if = "Option::is_none")]
pub family: Option<String>,
/// The ID of the metric unit.
#[serde(rename = "id", skip_serializing_if = "Option::is_none")]
pub id: Option<i64>,
/// The unit of the metric, for instance `byte`.
#[serde(rename = "name", skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// The plural Unit of metric, for instance `bytes`.
#[serde(rename = "plural", skip_serializing_if = "Option::is_none")]
pub plural: Option<String>,
/// The scale factor of metric unit, for instance `1.0`.
#[serde(rename = "scale_factor", skip_serializing_if = "Option::is_none")]
pub scale_factor: Option<f64>,
/// A shorter and abbreviated version of the metric unit, for instance `B`.
#[serde(rename = "short_name", skip_serializing_if = "Option::is_none")]
pub short_name: Option<String>,
}
impl SloHistoryMetricsSeriesMetadataUnit {
/// An Object of metric units.
pub fn new() -> SloHistoryMetricsSeriesMetadataUnit {
SloHistoryMetricsSeriesMetadataUnit {
family: None,
id: None,
name: None,
plural: None,
scale_factor: None,
short_name: None,
}
}
}
|
use crossbeam::queue::MsQueue;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Arc;
pub struct GenerationItem<T> {
generation: usize,
item: T,
}
pub struct Pool<T> {
queue: Arc<MsQueue<GenerationItem<T>>>,
freshest_generation: AtomicUsize,
next_generation: AtomicUsize,
}
impl<T> Pool<T> {
pub fn new() -> Pool<T> {
let queue = Arc::new(MsQueue::new());
Pool {
queue,
freshest_generation: AtomicUsize::default(),
next_generation: AtomicUsize::default(),
}
}
pub fn publish_new_generation(&self, items: Vec<T>) {
let next_generation = self.next_generation.fetch_add(1, Ordering::SeqCst) + 1;
for item in items {
let gen_item = GenerationItem {
item,
generation: next_generation,
};
self.queue.push(gen_item);
}
self.advertise_generation(next_generation);
}
/// At the exit of this method,
/// - freshest_generation has a value greater or equal than generation
/// - freshest_generation has a value that has been advertised
/// - freshest_generation has)
fn advertise_generation(&self, generation: usize) {
// not optimal at all but the easiest to read proof.
loop {
let former_generation = self.freshest_generation.load(Ordering::Acquire);
if former_generation >= generation {
break;
}
self.freshest_generation.compare_and_swap(
former_generation,
generation,
Ordering::SeqCst,
);
}
}
fn generation(&self) -> usize {
self.freshest_generation.load(Ordering::Acquire)
}
pub fn acquire(&self) -> LeasedItem<T> {
let generation = self.generation();
loop {
let gen_item = self.queue.pop();
if gen_item.generation >= generation {
return LeasedItem {
gen_item: Some(gen_item),
recycle_queue: Arc::clone(&self.queue),
};
} else {
// this searcher is obsolete,
// removing it from the pool.
}
}
}
}
pub struct LeasedItem<T> {
gen_item: Option<GenerationItem<T>>,
recycle_queue: Arc<MsQueue<GenerationItem<T>>>,
}
impl<T> Deref for LeasedItem<T> {
type Target = T;
fn deref(&self) -> &T {
&self.gen_item
.as_ref()
.expect("Unwrapping a leased item should never fail")
.item // unwrap is safe here
}
}
impl<T> DerefMut for LeasedItem<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.gen_item
.as_mut()
.expect("Unwrapping a mut leased item should never fail")
.item // unwrap is safe here
}
}
impl<T> Drop for LeasedItem<T> {
fn drop(&mut self) {
let gen_item: GenerationItem<T> = mem::replace(&mut self.gen_item, None)
.expect("Unwrapping a leased item should never fail");
self.recycle_queue.push(gen_item);
}
}
#[cfg(test)]
mod tests {
use super::Pool;
use std::iter;
#[test]
fn test_pool() {
let items10: Vec<usize> = iter::repeat(10).take(10).collect();
let pool = Pool::new();
pool.publish_new_generation(items10);
for _ in 0..20 {
assert_eq!(*pool.acquire(), 10);
}
let items11: Vec<usize> = iter::repeat(11).take(10).collect();
pool.publish_new_generation(items11);
for _ in 0..20 {
assert_eq!(*pool.acquire(), 11);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.