text stringlengths 8 4.13M |
|---|
use std::time::Instant;
use regex::Regex;
const INPUT: &str = include_str!("../input.txt");
fn read_input() -> impl Iterator<Item = (String, usize, usize, usize, usize)> {
let re = Regex::new(r"(?P<command>turn off|turn on|toggle) (?P<x1>\d+),(?P<y1>\d+) through (?P<x2>\d+),(?P<y2>\d+)").unwrap();
INPUT.lines().map(move |line| {
let caps = re.captures(line).unwrap();
let command = caps["command"].into();
let x1: usize = caps["x1"].parse().unwrap();
let y1: usize = caps["y1"].parse().unwrap();
let x2: usize = caps["x2"].parse().unwrap();
let y2: usize = caps["y2"].parse().unwrap();
(command, x1, y1, x2, y2)
})
}
fn part1() -> usize {
let mut lights = vec![vec![false; 1000]; 1000];
for (command, x1, y1, x2, y2) in read_input() {
for row in lights.iter_mut().take(x2 + 1).skip(x1) {
for light in row.iter_mut().take(y2 + 1).skip(y1) {
*light = match command.as_ref() {
"turn on" => true,
"turn off" => false,
"toggle" => !*light,
_ => unreachable!(),
}
}
}
}
lights.iter().flatten().filter(|&&light| light).count()
}
fn part2() -> u64 {
let mut lights = vec![vec![0u64; 1000]; 1000];
for (command, x1, y1, x2, y2) in read_input() {
for light_row in lights.iter_mut().take(x2 + 1).skip(x1) {
for light in light_row.iter_mut().take(y2 + 1).skip(y1) {
match command.as_ref() {
"turn on" => *light += 1,
"turn off" => *light = light.saturating_sub(1),
"toggle" => *light += 2,
_ => unreachable!(),
};
}
}
}
lights.iter().flatten().sum()
}
fn main() {
let start = Instant::now();
println!("part 1: {}", part1());
println!("part 1 took {}ms", (Instant::now() - start).as_millis());
let start = Instant::now();
println!("part 2: {}", part2());
println!("part 2 took {}ms", (Instant::now() - start).as_millis());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part1() {
assert_eq!(part1(), 400410);
}
#[test]
fn test_part2() {
assert_eq!(part2(), 15343601);
}
}
|
use std::sync::Arc;
use super::{Pages, Pagination};
use crate::{core::Context, embeds::PinnedEmbed, util::osu::ScoreOrder, BotResult};
use rosu_v2::prelude::{Score, User};
use twilight_model::channel::Message;
pub struct PinnedPagination {
ctx: Arc<Context>,
msg: Message,
pages: Pages,
user: User,
scores: Vec<Score>,
sort_by: ScoreOrder,
}
impl PinnedPagination {
pub fn new(
msg: Message,
user: User,
scores: Vec<Score>,
sort_by: ScoreOrder,
ctx: Arc<Context>,
) -> Self {
Self {
pages: Pages::new(5, scores.len()),
msg,
user,
scores,
ctx,
sort_by,
}
}
}
#[async_trait]
impl Pagination for PinnedPagination {
type PageData = PinnedEmbed;
fn msg(&self) -> &Message {
&self.msg
}
fn pages(&self) -> Pages {
self.pages
}
fn pages_mut(&mut self) -> &mut Pages {
&mut self.pages
}
fn single_step(&self) -> usize {
self.pages.per_page
}
async fn build_page(&mut self) -> BotResult<Self::PageData> {
let scores = self
.scores
.iter()
.skip(self.pages.index)
.take(self.pages.per_page);
let fut = PinnedEmbed::new(
&self.user,
scores,
&self.ctx,
self.sort_by,
(self.page(), self.pages.total_pages),
);
Ok(fut.await)
}
}
|
// ARMv7M-M Memory Model
use std::ops::{ Index, IndexMut };
/// Addressable registers
pub enum Register {
// Thumb16 addressable
R0, R1, R2, R3,
R4, R5, R6, R7,
// Thumb32 addressable
R8, R9, R10, R11, R12,
// Stack Pointer
SPM,
SPP,
// Link Register
LR,
// Program Counter
// PC is defined to be the address of the current instruction.
// The offset of 4 bytes is applied to it by the register access functions.
PC,
// Program status registers
APSR,
IPSR,
EPSR,
}
pub struct RegisterBank {
registers: [u32; ::std::u8::MAX as usize],
}
impl RegisterBank {
pub fn new() -> RegisterBank {
RegisterBank {
registers: [0; ::std::u8::MAX as usize]
}
}
}
impl Index<Register> for RegisterBank {
type Output = u32;
fn index(&self, idx: Register) -> &Self::Output {
&self.registers[idx as usize]
}
}
impl IndexMut<Register> for RegisterBank {
fn index_mut(&mut self, idx: Register) -> &mut Self::Output {
&mut self.registers[idx as usize]
}
}
/// Memory
///
///
/// The following is taken from the ARMv7-M Architecture Reference Manual:
///
/// This address space is regarded as consisting of 2^30 32-bit words, each of whose addresses is word-aligned, meaning
/// that the address is divisible by 4. The word whose word-aligned address is A consists of the four bytes with
/// addresses A, A+1, A+2, and A+3. The address space can also be considered as consisting of 2^31 16-bit halfwords,
/// each of whose addresses is halfword-aligned, meaning that the address is divisible by 2. The halfword whose
/// halfword-aligned address is A consists of the two bytes with addresses A and A+1.
///
/// Address calculations are normally performed using ordinary integer instructions. This means that they normally
/// wrap around if they overflow or underflow the address space. Another way of describing this is that any address
/// calculation is reduced modulo 2^32 .
///
/// Normal sequential execution of instructions effectively calculates:
/// (address_of_current_instruction) + (2 or 4) /*16- and 32-bit instr mix*/
/// after each instruction to determine which instruction to execute next. If this calculation overflows the top of the
/// address space, the result is UNPREDICTABLE . In ARMv7-M this condition cannot occur because the top of memory
/// is defined to always have the Execute Never (XN) memory attribute associated with it. See The system address map
/// on page B3-592 for more details. An access violation will be reported if this scenario occurs.
///
/// All memory addresses used in ARMv7-M are physical addresses (PAs).
///
///
///
/// SYSTEM ADDRESS MAP (B3.1 pg. 592)
/// The architecture assigns physical addresses for use as event entry points (vectors), system control, and
/// configuration. The event entry points are all defined relative to a table base address, that is configured to an
/// IMPLEMENTATION DEFINED value on reset, and then maintained in an address space reserved for system
/// configuration and control. To meet this and other system needs, the address space 0xE0000000 to 0xFFFFFFFF is
/// RESERVED for system-level use.
///
/// | Address | Name | Device type | XN? | Cache | Description |
/// | [0x00000000 -> 0x1FFFFFFF] | Code | Normal | - | WT | Typically ROM or flash memory. |
/// | [0x20000000 -> 0x3FFFFFFF] | SRAM | Normal | - | WBWA | SRAM region typically used for on-chip RAM. |
/// | [0x40000000 -> 0x5FFFFFFF] | Peripheral | Device | XN | - | On-chip peripheral address space. |
macro_rules! kb {
($v:expr) => {
($v as usize) * 1024usize
};
}
#[derive(Debug)]
pub struct Memory {
raw_pinned: Pin<Box<[u8]>>,
}
use std::pin::Pin;
impl Memory {
pub fn alloc(size: usize) -> Memory {
let aligned_size = Memory::align_with(size, kb!(4));
let boxed = vec![0u8; aligned_size].into_boxed_slice();
let pinned = Pin::new(boxed);
println!("[Memory] Requested {} bytes, allocated {} bytes", size, aligned_size);
Memory {
raw_pinned: pinned
}
}
pub fn read_u16(&self, address: usize) -> u16 {
unsafe {
std::mem::transmute::<[u8; 2], u16>([self.raw_pinned[address], self.raw_pinned[address+1]]).to_le()
}
}
// todo: return result type for error handling
pub fn write_bytes(&mut self, address: usize, bytes: &[u8]) {
let len = bytes.len();
let total_len = address + len;
let allocated_len = self.raw_pinned.as_ref().len();
println!("[Memory] Write {} bytes beginning at address {:#X}", len, address);
//println!("[Memory] Total/Allocated length: {}/{}", total_len, allocated_len);
assert!(total_len <= allocated_len);
for (i, byte) in bytes.iter().enumerate() {
self.raw_pinned.as_mut()[address + i] = *byte;
}
}
pub fn allocated_bytes(&self) -> usize {
self.raw_pinned.as_ref().len()
}
fn align_with(value: usize, align: usize) -> usize {
if align == 0 {
value
} else {
((value + align - 1) / align) * align
}
}
}
|
extern crate rand;
use std::io;
use std::num;
use rand::Rng;
fn main() {
const MAX : usize = 256;
let mut freq = [0; MAX];
let mut rng = rand::thread_rng();
for _ in 0..MAX*16384 {
let n = rng.gen_range(0, MAX);
freq[n] += 1;
}
let mut tdiff = 0;
for i in 0..MAX {
let diff = freq[i] - 16384;
tdiff += diff;
println!("{:3}: {:4}", i, diff);
}
println!("{}", tdiff);
}
|
use crate::{
codegen::{
builder::value,
unit::{Mutability, Slot},
AatbeModule, CompileError, ValueTypePair,
},
fmt::AatbeFmt,
ty::LLVMTyInCtx,
};
use parser::ast::{AtomKind, Expression, PrimitiveType, AST};
pub fn const_atom(module: &AatbeModule, atom: &AtomKind) -> Option<ValueTypePair> {
match atom {
AtomKind::StringLiteral(string) => Some(value::str(module, string.as_ref())),
AtomKind::CharLiteral(ch) => Some(value::char(module, *ch)),
AtomKind::Integer(val, PrimitiveType::Int(size)) => {
Some(value::sint(module, size.clone(), *val))
}
AtomKind::Integer(val, PrimitiveType::UInt(size)) => {
Some(value::uint(module, size.clone(), *val))
}
AtomKind::Floating(val, PrimitiveType::Float(size)) => {
Some(value::floating(module, size.clone(), *val))
}
AtomKind::Cast(box AtomKind::Integer(val, _), PrimitiveType::Char) => {
Some(value::char(module, *val as u8 as char))
}
AtomKind::Unary(op, box AtomKind::Integer(val, PrimitiveType::Int(size)))
if op == &String::from("-") =>
{
Some(value::sint(module, size.clone(), (-(*val as i64)) as u64))
}
AtomKind::Unary(op, box AtomKind::Integer(val, PrimitiveType::UInt(size)))
if op == &String::from("-") =>
{
Some(value::uint(module, size.clone(), (-(*val as i64)) as u64))
}
AtomKind::Parenthesized(box atom) => fold_expression(module, atom),
_ => panic!("ICE fold_atom {:?}", atom),
}
}
fn fold_expression(module: &AatbeModule, expr: &Expression) -> Option<ValueTypePair> {
match expr {
Expression::Atom(atom) => const_atom(module, atom),
_ => panic!("ICE fold_expression {:?}", expr),
}
}
pub fn fold_constant(module: &mut AatbeModule, ast: &AST) -> Option<Slot> {
match ast {
AST::Global {
ty:
PrimitiveType::NamedType {
name,
ty: Some(box ty),
},
value,
export: _,
} => fold_expression(module, value)
.and_then(|val| {
if val.prim() != ty.inner() {
module.add_error(CompileError::AssignMismatch {
expected_ty: ty.fmt(),
found_ty: val.prim().fmt(),
value: value.fmt(),
var: name.clone(),
});
None
} else {
Some(val)
}
})
.map(|val| {
let val_ref = module
.llvm_module_ref()
.add_global(ty.llvm_ty_in_ctx(module), name.as_ref());
module.llvm_module_ref().set_initializer(val_ref, *val);
Slot::Variable {
mutable: Mutability::Global,
name: name.clone(),
ty: val.prim().clone(),
value: val_ref,
}
}),
AST::Constant {
ty:
PrimitiveType::NamedType {
name,
ty: Some(box ty),
},
value,
export: _,
} => fold_expression(module, value)
.and_then(|val| {
if val.prim() != ty.inner() {
module.add_error(CompileError::AssignMismatch {
expected_ty: ty.fmt(),
found_ty: val.prim().fmt(),
value: value.fmt(),
var: name.clone(),
});
None
} else {
Some(val)
}
})
.map(|val| Slot::Variable {
mutable: Mutability::Constant,
name: name.clone(),
ty: val.prim().clone(),
value: *val,
}),
_ => unreachable!(),
}
}
|
use std::cmp::{max, min};
use std::fs;
use std::ops::RangeInclusive;
type Cuboid = [RangeInclusive<isize>; 3];
type RebootInstruction = (bool, Cuboid);
fn main() {
let filename = "input/input.txt";
let instructions = parse_input_file(filename);
println!("instructions: {:?}", instructions);
println!();
// Maintain two sets: positive regions and negative regions:
// Accumulate intersections with positive regions, add intersections to negative regions
// Accumulate intersections with negative regions, add intersections to positive regions
// If a cuboid region is turning on, then
// - Add cuboid to positive region
let mut positive_regions: Vec<Cuboid> = Vec::new();
let mut negative_regions: Vec<Cuboid> = Vec::new();
let sum_volumes = |regions: &Vec<Cuboid>| regions.iter().map(volume).sum();
for (toggle, cuboid) in instructions {
let agg_intersections = |regions: &Vec<Cuboid>| {
regions
.iter()
.filter_map(|pr| intersection(&cuboid, pr))
.collect()
};
let positive_intersections: Vec<Cuboid> = agg_intersections(&positive_regions);
let negative_intersections: Vec<Cuboid> = agg_intersections(&negative_regions);
negative_regions.extend(positive_intersections);
positive_regions.extend(negative_intersections);
if toggle {
positive_regions.push(cuboid);
}
}
let positive_volume: usize = sum_volumes(&positive_regions);
let negative_volume: usize = sum_volumes(&negative_regions);
println!("positive_volume: {:?}", positive_volume);
println!("negative_volume: {:?}", negative_volume);
println!("total_volume: {}", positive_volume - negative_volume);
let init_cuboid: Cuboid = [-50..=50, -50..=50, -50..=50];
let regions_in_init = |regions: &Vec<Cuboid>| {
regions
.iter()
.filter_map(|r| intersection(r, &init_cuboid))
.collect()
};
let positive_regions_in_init: Vec<Cuboid> = regions_in_init(&positive_regions);
let negative_regions_in_init: Vec<Cuboid> = regions_in_init(&negative_regions);
let positive_volume_in_init: usize = sum_volumes(&positive_regions_in_init);
let negative_volume_in_init: usize = sum_volumes(&negative_regions_in_init);
println!("positive_volume_in_init: {:?}", positive_volume_in_init);
println!("negative_volume_in_init: {:?}", negative_volume_in_init);
println!(
"total_volume in init: {}",
positive_volume_in_init - negative_volume_in_init
);
}
// aka count_voxels
fn volume(cuboid: &Cuboid) -> usize {
cuboid
.iter()
.map(|r| usize::try_from((r.end() - r.start() + 1).abs()).unwrap())
.product()
}
// These would be great in an impl block, but impling over a type alias isn't possible, and alternatives (tuple struct & trait impl) are clunky
fn intersection(this: &Cuboid, that: &Cuboid) -> Option<Cuboid> {
let x_start = max(this[0].start(), that[0].start());
let x_end = min(this[0].end(), that[0].end());
let y_start = max(this[1].start(), that[1].start());
let y_end = min(this[1].end(), that[1].end());
let z_start = max(this[2].start(), that[2].start());
let z_end = min(this[2].end(), that[2].end());
if x_start > x_end || y_start > y_end || z_start > z_end {
None
} else {
Some([*x_start..=*x_end, *y_start..=*y_end, *z_start..=*z_end])
}
}
fn parse_input_file(filename: &str) -> Vec<RebootInstruction> {
let file_contents = fs::read_to_string(filename).unwrap();
file_contents
.split('\n')
.map(|s| {
let mut space_split = s.split_whitespace();
let toggle: bool = space_split.next().unwrap() == "on";
let get_range = |r: &str| {
let mut range_iter = r[2..].split("..");
let start: isize = range_iter.next().unwrap().parse().unwrap();
let end: isize = range_iter.next().unwrap().parse().unwrap();
start..=end
};
let mut axis_split = space_split.next().unwrap().split(',');
let x_range = get_range(axis_split.next().unwrap());
let y_range = get_range(axis_split.next().unwrap());
let z_range = get_range(axis_split.next().unwrap());
(toggle, [x_range, y_range, z_range])
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
fn cube(r: RangeInclusive<isize>) -> Cuboid {
[r.clone(), r.clone(), r]
}
#[test]
fn test_intersection() {
let tests = HashMap::from([
// non-overlapping
((cube(0..=2), cube(3..=6)), None),
// overlap one voxel
((cube(0..=2), cube(2..=3)), Some(cube(2..=2))),
// overlap edge
(
(cube(0..=3), [3..=6, 0..=3, 0..=3]),
Some([3..=3, 0..=3, 0..=3]),
),
// second greater
((cube(0..=3), cube(1..=4)), Some(cube(1..=3))),
// first greater
((cube(1..=4), cube(0..=3)), Some(cube(1..=3))),
// first encapsulated
((cube(0..=5), cube(1..=3)), Some(cube(1..=3))),
// second encapsulated
((cube(1..=3), cube(0..=5)), Some(cube(1..=3))),
]);
for ((a, b), expected_intersection) in tests {
println!("{:?}", (&a, &b));
let actual_intersection = intersection(&a, &b);
assert_eq!(actual_intersection, expected_intersection);
}
}
}
|
/// Represents a matrix in row-major order
// [[1,2,3],[1,2,3]]
//
pub type Matrix = Vec<Vec<f32>>;
/// Computes the product of the inputs `mat1` and `mat2`.
pub fn mat_mult(mat1: &Matrix, mat2: &Matrix) -> Matrix {
let (r1, c1) = size(mat1);
let (r2, c2) = size(mat2);
if r1 != c2 { panic!("Can't dot multiply these mismatched matrices"); }
let mut res: Vec<Vec<f32>> = Vec::new();
(0..r1).fold(res, |mut macc, nextr| {
let row = (0..c2).fold(Vec::new(), |mut acc, nextc| {
// woof. When to build/copy, when to pass by ref?
let val = mat_combine(extractrow(mat1, nextr), &extractcol(mat2, nextc));
acc.push(val);
acc
});
macc.push(row);
macc
})
}
fn mat_combine(r: &Vec<f32>, c: &Vec<f32>) -> f32 {
(0..r.len()).fold(0.0, |acc, n| {
acc + (r[n] * c[n])
})
}
fn extractrow(mat: &Matrix, idx: usize) -> &Vec<f32> {
&(mat[idx])
}
fn extractcol(mat: &Matrix, idx: usize) -> Vec<f32> {
let mut col: Vec<f32> = Vec::new();
for row in mat {
col.push(row[idx]);
}
col
}
fn size(mat: &Matrix) -> (usize, usize) {
(num_rows(mat), num_cols(mat))
}
fn num_rows(mat: &Matrix) -> usize {
mat.len()
}
fn num_cols(mat: &Matrix) -> usize {
if mat.len() > 0 {
mat[0].len()
} else {
0
}
}
|
/*
chapter 4
syntax and semantics
loop
*/
// this code will give this warning:
/*
warning: denote infinite loops with loop { ... },
#[warn(while_true)] on by default
*/
fn main() {
while true {
println!("i am stuck in the infinite loop \
again, so, please, help me a second time");
}
}
// output should be:
/*
*/
|
//! Http context command handlers
//!
//! Contains actors that handles commands for HTTP endpoint
use actix_rt::time::timeout;
use actix_web::{http, web, HttpResponse};
use drogue_cloud_endpoint_common::{command::Commands, error::HttpEndpointError};
use drogue_cloud_service_common::Id;
use std::time::Duration;
const HEADER_COMMAND: &str = "command";
pub async fn wait_for_command(
commands: web::Data<Commands>,
id: Id,
ttd: Option<u64>,
) -> Result<HttpResponse, HttpEndpointError> {
match ttd {
Some(ttd) if ttd > 0 => {
let mut receiver = commands.subscribe(id.clone()).await;
match timeout(Duration::from_secs(ttd), receiver.recv()).await {
Ok(Some(cmd)) => {
commands.unsubscribe(&id).await;
Ok(HttpResponse::Ok()
.insert_header((HEADER_COMMAND, cmd.command))
.body(cmd.payload.unwrap_or_default()))
}
_ => {
commands.unsubscribe(&id).await;
Ok(HttpResponse::build(http::StatusCode::ACCEPTED).finish())
}
}
}
_ => Ok(HttpResponse::build(http::StatusCode::ACCEPTED).finish()),
}
}
|
//! Module for all [`Handoff`]-related items.
pub mod handoff_list;
mod tee;
mod vector;
use std::any::Any;
use std::cell::RefMut;
pub use tee::TeeingHandoff;
pub use vector::VecHandoff;
/// Trait representing something which we can attempt to give an item to.
pub trait TryCanReceive<T> {
// TODO(mingwei): Isn't used.
/// Try to give a value to the handoff, may return an error if full, representing backpressure.
fn try_give(&self, item: T) -> Result<T, T>;
}
/// Trait representing somethign which we can give an item to.
pub trait CanReceive<T> {
// TODO: represent backpressure in this return value.
/// Give a value to the handoff.
fn give(&self, item: T) -> T;
}
/// A handle onto the metadata part of a [Handoff], with no element type.
pub trait HandoffMeta: Any {
/// Helper to cast an instance of `HandoffMeta` to [`Any`]. In general you cannot cast between
/// traits, including [`Any`], but this helper method works around that limitation.
///
/// For implementors: the body of this method will generally just be `{ self }`.
fn any_ref(&self) -> &dyn Any;
// TODO(justin): more fine-grained info here.
/// Return if the handoff is empty.
fn is_bottom(&self) -> bool;
}
/// Trait for handoffs to implement.
pub trait Handoff: Default + HandoffMeta {
/// Inner datastructure type.
type Inner;
/// Take the inner datastructure, similar to [`std::mem::take`].
fn take_inner(&self) -> Self::Inner;
/// Take the inner datastructure by swapping input and output buffers.
///
/// For better performance over [`Self::take_inner`].
fn borrow_mut_swap(&self) -> RefMut<Self::Inner>;
/// See [`CanReceive::give`].
fn give<T>(&self, item: T) -> T
where
Self: CanReceive<T>,
{
<Self as CanReceive<T>>::give(self, item)
}
/// See [`TryCanReceive::try_give`].
fn try_give<T>(&self, item: T) -> Result<T, T>
where
Self: TryCanReceive<T>,
{
<Self as TryCanReceive<T>>::try_give(self, item)
}
}
/// Wrapper around `IntoIterator` to avoid trait impl conflicts.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Iter<I>(pub I)
where
I: IntoIterator;
impl<I> IntoIterator for Iter<I>
where
I: IntoIterator,
{
type Item = I::Item;
type IntoIter = I::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
|
use multihash::{wrap, Code, Multihash, MultihashDigest, Sha3_512};
#[test]
fn to_u64() {
assert_eq!(<u64>::from(Code::Keccak256), 0x1b);
assert_eq!(<u64>::from(Code::Custom(0x1234)), 0x1234);
}
#[test]
fn from_u64() {
assert_eq!(Code::from(0xb220), Code::Blake2b256);
assert_eq!(Code::from(0x0011_2233), Code::Custom(0x0011_2233));
}
#[test]
fn hasher() {
let expected = Sha3_512::digest(b"abcdefg");
let hasher = Code::Sha3_512.hasher().unwrap();
assert_eq!(hasher.digest(b"abcdefg"), expected);
assert!(Code::Custom(0x2222).hasher().is_none());
}
#[test]
fn custom_multihash_digest() {
#[derive(Clone, Debug)]
struct SameHash;
impl MultihashDigest for SameHash {
fn code(&self) -> Code {
Code::Custom(0x9999)
}
fn digest(&self, _data: &[u8]) -> Multihash {
let data = b"alwaysthesame";
wrap(Self.code(), data)
}
fn input(&mut self, _data: &[u8]) {}
fn result(self) -> Multihash {
Self::digest(&self, &[])
}
fn result_reset(&mut self) -> Multihash {
Self::digest(&self, &[])
}
fn reset(&mut self) {}
}
let my_hash = SameHash.digest(b"abc");
assert_eq!(my_hash.digest(), b"alwaysthesame");
}
|
//! Project changelog (YEAR-MONTH-DAY)
/// Release 0.0.4 (2017-11-08)
///
/// * Partially sketched out a transfer matrix addressing issue#23
/// * Simplified the complicated extension/build system resolving issue#25
/// * The new extension/build system allows for framework specific backends.
/// * Worked on a OpenCL solution to issue#16
/// * Removed ndarray as it's not needed, which closes issue#20
/// * Mapped memory process doesn't work well with ndarray + reshaping a tensor means reshaping
/// the native array
/// * Lazy synchronization via auto-sync has been fully integrated
/// * Implemented logic around pinned memory with unpinned memory fallback
pub mod r0_0_4 {}
/// Release 0.0.3 (2017-03-04)
///
/// * Implemented an OpenCL API wrapper
/// * Partially implemented a CUDA API wrapper
/// * Partially implemented native support
/// * Worked on a fallback mechanism (see issue#15)
/// * No longer requires framework related feature flags (from the original Collenchyma project)
/// * No longer requires backends parameterized by a framework
/// * New memory access API
/// * Implemented auto-sync
/// * Use a tensor lib (ndarray) as the underlying native memory representation
/// * Add `Bundle` logic
/// * Removed `IBinary`/`HashMap` technique. Use structs instead
pub mod r0_0_3 {} |
fn add(i:i32, j:i32) -> i32 {
i + j
}
fn main() {
let i = 3;
let j = 4;
println!("sum of {} and {} is: {}", i, j, add(i,j));
}
|
use petgraph::graph::Graph;
use petgraph::graph::NodeIndex;
use petgraph::graphmap::DiGraphMap;
use petgraph::graphmap::GraphMap;
use petgraph::visit::DfsPostOrder;
use petgraph::visit::IntoNodeReferences;
use petgraph::visit::NodeRef;
use petgraph::Incoming;
use petgraph::Outgoing;
use petgraph::Undirected;
fn main() {}
// #[derive(Clone, Debug)]
// struct N<'n> {
// name: String,
// children: Vec<&'n N<'n>>,
// }
// impl<'n> N<'n> {
// fn of(name: &str) -> N<'n> {
// N {
// name: name.to_string(),
// children: Vec::new(),
// }
// }
// }
// #[derive(Clone, Debug)]
// struct Node {
// name: String,
// children: Vec<Node>,
// }
// impl Node {
// fn of(name: &str) -> Node {
// Node {
// name: name.to_string(),
// children: Vec::new(),
// }
// }
// }
// fn find(from: Node, name: &String) -> Option<Node> {
// if from.name.eq(name) {
// return Some(from);
// }
// // depth-first
// for child in from.children {
// if child.name.eq(name) {
// return Some(child);
// } else {
// let found = find(child, name);
// if found.is_some() {
// return found;
// }
// }
// }
// return None;
// }
//
// fn find<'a, 'b>(from: &'a mut N<'a>, name: &'b String) -> Option<&'a mut N<'a>> {
// if from.name.eq(name) {
// return Some(from);
// }
// // depth-first
// for child in from.children.iter_mut() {
// if child.name.eq(name) {
// return Some(child);
// } else {
// let found = find(child, name);
// if found.is_some() {
// return found;
// }
// }
// }
// return None;
// }
fn parse<'a>(data: Vec<&'a str>) -> DiGraphMap<&'a str, ()> {
let mut graph = DiGraphMap::new();
data.iter().for_each(|edge| {
// parse parts from string
let parts: Vec<&str> = edge.split(")").collect();
let from = parts[0];
let to = parts[1];
graph.add_node(from);
graph.add_node(to);
graph.add_edge(from, to, ());
});
return graph;
}
#[derive(Debug)]
struct Dist {
idx: NodeIndex<usize>,
dist: i32,
}
fn checksum(graph: DiGraphMap<&str, ()>) -> i32 {
// "direct and indirect orbits"
// aka for each leaf node, the length of its path to root
let g = graph.into_graph::<usize>();
let mut stack = Vec::new();
// init stack with root
let root = g
.node_references()
.filter(|n| n.weight().eq(&"COM"))
.next()
.expect("x");
stack.push(Dist {
idx: root.id(),
dist: 0,
});
let mut acc = 0;
while let Some(curr) = stack.pop() {
println!(
"{:?} -> {:?}",
curr,
g.neighbors(curr.idx)
.map(|x| x.index())
.collect::<Vec<usize>>()
);
acc += curr.dist;
for child in g.neighbors(curr.idx) {
stack.push(Dist {
idx: child,
dist: curr.dist + 1,
})
}
}
acc
}
fn parent(graph: &Graph<&str, ()>, node: NodeIndex) -> Option<NodeIndex> {
return graph.neighbors_directed(node, Incoming).next();
}
fn ancestors<'a>(graph: &Graph<&'a str, ()>, src: &str) -> Vec<NodeIndex> {
let (node, _) = graph
.node_references()
.filter(|n| n.weight().eq(&src))
.next()
.expect("x");
let mut path = Vec::new();
let mut n = node;
while let Some(p) = parent(graph, n) {
println!("an {:?}", n);
path.push(p);
n = p;
}
return path;
}
// i'd want this to be generic, but idk that yet
fn closest_common_ancestor<'a>(
a: &'a Vec<NodeIndex>,
b: &'a Vec<NodeIndex>,
) -> Option<&'a NodeIndex> {
for x in a {
for y in b {
if x.eq(&y) {
return Some(&x);
}
}
}
return None;
}
// aka shortest path
fn min_orbrital_transfers<'a, 'b>(graph: &Graph<&'a str, ()>, src: &str, dest: &str) -> i32 {
let (src_n, _) = graph
.node_references()
.filter(|n| n.weight().eq(&src))
.next()
.expect("x");
let (dest_n, _) = graph
.node_references()
.filter(|n| n.weight().eq(&dest))
.next()
.expect("x");
// find common ancestor
let src_ancestors = ancestors(graph, src);
let dest_ancestors = ancestors(graph, dest);
println!("s {:?} {:?}", src_n, src_ancestors);
println!("d {:?} {:?}", dest_n, dest_ancestors);
let concestor =
closest_common_ancestor(&src_ancestors, &dest_ancestors).expect("missing concestor");
println!("c {:?}", concestor);
let mut path = Vec::new();
// add up src_ancestors to concestor, then down dest_ancestors from concestor
let mut s_a = src_ancestors.iter();
while let Some(n) = s_a.next() {
path.push(n);
if n.eq(&concestor) {
break;
}
}
let mut d_a_r = dest_ancestors.clone();
d_a_r.reverse();
let mut d_a = d_a_r.iter();
let mut in_path = false;
while let Some(n) = d_a.next() {
if in_path {
path.push(n);
}
if n.eq(&concestor) {
in_path = true;
}
}
println!("path {:?}", path);
// let ps = path
// .iter()
// .map(|x| graph.node_weight(**x).expect(""))
// .join(", ");
// println!("path {:?}", ps);
for x in path.clone() {
println!("{:?}", graph.node_weight(*x));
}
// let mut stack = Vec::new();
// // from a node, go up to its parent
// let parent = graph.neighbors_directed(root, Incoming).next().expect("parent");
// let children = graph.neighbors_directed(parent, Outgoing);
// if children.any(|n| graph.node_weight(n).expect("node").eq(&dest)) {
// return stack;
// }
// return 1;
return path.len() as i32 - 1;
}
#[cfg(test)]
mod tests {
use super::*;
use petgraph::graphmap::DiGraphMap;
#[test]
fn ex_1() {
let data = [
"COM)B", "B)C", "C)D", "D)E", "E)F", "B)G", "G)H", "D)I", "E)J", "J)K", "K)L",
]
.to_vec();
println!("{:?}", parse(data.clone()));
assert_eq!(42, checksum(parse(data.clone())));
}
#[test]
fn part_1() {
let data = [
"DGS)1HY", "FYY)13C", "RPN)9C5", "NNV)CVR", "BVN)BCH", "39R)BPR", "43R)CPB", "XFB)J3X",
"LS3)D2Z", "8KB)XX5", "MDK)2YB", "NFX)8GF", "KV6)T6S", "ZDP)163", "CM4)453", "FR8)ZV2",
"FQG)QXG", "ZLY)G8X", "81Q)GKB", "V33)QBG", "BXZ)724", "T4W)XJ4", "BM6)CW1", "W5P)HWD",
"3LQ)1BF", "7R1)GL2", "1KM)R91", "J19)55D", "VW9)PFT", "S9F)393", "ZR3)TVM", "KM9)K5D",
"B7P)ZFJ", "G2Q)C7N", "9C7)QTH", "BS2)7NB", "5QV)K91", "L1Y)VX5", "PBY)XFL", "TC8)B7P",
"T7C)5WZ", "6HZ)NRW", "FPT)C75", "FRK)R9F", "RXL)WPB", "LSG)SYB", "WZ5)86T", "6NG)C6C",
"VHQ)P2S", "CCN)3PP", "Y8H)ZLY", "3V6)XBW", "GGS)3HX", "FK6)VTV", "2M1)LNP", "3WK)BVF",
"T2W)HRB", "C2T)XSR", "HVF)N5T", "MPK)X68", "X1H)HXJ", "SD1)CG7", "ZLL)T4W", "VHS)2G7",
"HKC)CJF", "DW1)F82", "LWP)C3M", "7KH)S8C", "TTP)BVM", "JCM)3HJ", "RBT)9XB", "7CG)7B6",
"Y8B)MX2", "724)Z38", "6V6)TR7", "6CP)67M", "DNV)9MG", "Q83)2BQ", "KX1)MJC", "HDT)RSV",
"HG6)9NW", "Y74)S14", "N56)NRN", "G8P)XH4", "VK7)R7C", "CB5)S7X", "NFW)P89", "8VG)RLN",
"GJB)JYR", "BQX)G73", "TWQ)Y74", "K57)DGD", "NLY)1SZ", "VF8)BTV", "JGX)489", "MYZ)LVD",
"WXN)DJR", "6G2)2BG", "3M5)J4S", "7BD)F3Q", "W8M)6FC", "6J4)4DD", "7Y1)1P7", "GMJ)46H",
"G5C)V86", "147)WLR", "TJM)FM7", "DN4)QV6", "V76)8HY", "QCX)R5D", "LNK)9ZP", "TF7)JL3",
"9ZX)DV2", "G5V)FYY", "LJC)B88", "6DW)2TB", "LMT)THC", "M61)R2B", "8JL)QW1", "5VP)6CP",
"TLL)RXL", "422)2FG", "9KG)ZLD", "9ML)1WW", "N38)PCP", "PZ3)8K1", "VV4)G6V", "NWW)7MM",
"HSV)JBZ", "XBM)XXQ", "XSR)PND", "LVD)17P", "VNM)KJZ", "K2Z)3Q3", "ZZQ)86H", "SQS)3FD",
"428)85T", "G54)B62", "V33)899", "TRV)JKT", "BDG)HJQ", "HG6)DGX", "1MB)6NY", "6NY)P6P",
"VQQ)2ZJ", "5G5)ZYJ", "JP6)QV7", "ZZN)85G", "VRC)TFL", "K7D)ZZQ", "VSG)MJX", "1TL)CYK",
"8HM)CWD", "SQV)VRC", "SYX)K5H", "9MG)8HM", "RSV)CMQ", "TLH)KCF", "THL)37P", "WYW)4NQ",
"8ML)F2P", "ZR1)SAN", "4VB)52R", "BPR)F5T", "426)FBB", "4B8)DKL", "LYP)Q5B", "HB2)VC7",
"93T)3PY", "3HJ)B7D", "6DH)7NY", "8RZ)LVW", "JL4)98M", "4DD)HVH", "M93)SCH", "DRS)3R1",
"BTN)689", "B7D)RB6", "VX5)3SF", "9KH)L26", "BMT)NHG", "HQW)4Z7", "W5J)YTT", "ZR3)DVT",
"V6W)S5W", "NRN)MY4", "FN5)HP6", "THY)LL4", "9SQ)425", "6BJ)JDM", "2TY)LX4", "BKD)9BC",
"1R9)P1V", "8K1)CR5", "68H)72R", "7H1)NWD", "WQZ)MC2", "T4W)1Z2", "SPB)X7P", "B4V)2R4",
"QG2)DZ9", "BKD)WC1", "V36)VLY", "W9B)TMQ", "ZG6)BJL", "XS3)FB9", "7B6)CQJ", "KD4)HXB",
"DBM)1K5", "82F)18S", "M74)NJB", "HJQ)G34", "KVK)YYZ", "L44)KDB", "KNM)DD8", "TVM)XC9",
"9SB)CRN", "TR7)5VN", "HYP)K6C", "8BC)ZZN", "WC1)SYL", "P14)7LJ", "1MP)11X", "SYL)P6X",
"ZQ3)GD3", "R6F)4WY", "TRD)2SY", "F2P)C4Z", "DSW)VPL", "KWN)8LG", "45F)ZCL", "MR5)LQT",
"DL1)DS4", "KJZ)WWP", "4SN)263", "TT2)9W2", "CVW)SLM", "Y6Q)FXS", "FN7)43F", "MZ5)PX5",
"KTV)KLD", "1N9)M1R", "GHS)F73", "6CJ)RTN", "S9B)6SL", "C7N)WBB", "QKX)CHT", "FP4)K1M",
"XZY)124", "R7C)JXH", "8TX)B17", "7HP)F3R", "KW2)6R9", "6J4)P25", "9RW)GH7", "NRW)K2S",
"BBR)KM9", "7BD)5SJ", "WTQ)NNQ", "L5S)KQG", "GGW)GVM", "94M)1MB", "F2C)QWY", "97N)ZCS",
"3VX)Y8H", "51L)8LP", "WXZ)YZ1", "MJC)ZG6", "8GW)SXR", "PNR)6J4", "G6V)W16", "XNT)BDH",
"7QG)4PZ", "QX4)75Z", "5M5)CFS", "BHN)HCS", "2M1)NCD", "43F)HYP", "C45)Y7Y", "LJK)THL",
"DW1)GJB", "ZZZ)JMQ", "DLM)T2F", "38X)N6X", "8VC)K6F", "5CP)V59", "RXL)3NN", "7NB)LQY",
"QMB)G9R", "NNQ)PMN", "NZX)9H8", "TCQ)2BF", "1DD)SJ3", "K6F)YN9", "ZV2)MPW", "VHQ)GN4",
"5K8)BM6", "Y28)FK6", "NPR)DKD", "57N)M5N", "15L)FHN", "8DV)N56", "3PP)BZY", "5LC)4W7",
"K6C)9M1", "CPT)6YS", "LQ9)NYC", "JXH)G7M", "NWS)45F", "Q9N)PHD", "QH2)GJM", "K93)SDT",
"3FD)YX6", "8BD)SH6", "QBG)X47", "K2S)8VG", "5D4)JPK", "HL6)S9F", "K3S)YBL", "JP6)XCT",
"ZQ7)XT5", "C7L)26C", "YQ4)WVN", "73F)LJC", "HYF)KW2", "N1M)426", "ZVQ)K2Z", "T6T)JS2",
"XXW)7NC", "5DV)2RW", "SXB)28F", "XC9)NGM", "LVW)JKV", "7VP)4CB", "PFT)1FL", "VTV)1SP",
"163)MZ5", "489)8P1", "QRD)3V6", "7XM)5JJ", "VM5)86K", "F3R)DSR", "JG7)JKL", "JJQ)KTV",
"CCD)2L8", "55J)2GG", "N6X)LYT", "PPQ)B84", "P5G)43R", "2CL)TTP", "QWF)2WD", "YYW)3YT",
"9GL)VF8", "VRH)1Q5", "669)5BH", "NWP)5V7", "KV7)5XF", "P9W)254", "LKB)CPL", "7FB)M2H",
"YH7)NL2", "FBM)KK7", "PJ9)SR6", "SB4)BM3", "LPR)MH9", "41C)TLB", "PBG)SMC", "8N6)582",
"TQ4)D4C", "2NJ)TZL", "PKC)MYZ", "427)YFZ", "GMJ)BGP", "FB9)1KM", "NPR)6BQ", "9C5)VJH",
"8MR)SPB", "CTV)KNG", "M2P)N85", "BWJ)YBB", "F97)HSV", "XCT)D1G", "1SP)HW1", "V7Y)8X4",
"BZY)378", "R42)9B8", "G9R)7BD", "WG6)1YC", "W89)5MJ", "1Z7)ZT9", "5ZT)TC9", "PY5)D4G",
"J4T)JYY", "NWD)5CP", "2FM)MP9", "1S3)FF2", "DGD)5WX", "GWC)LPR", "H98)GQF", "WHD)NGP",
"85S)6Q4", "WSL)2QH", "3V6)W85", "YVP)GFS", "9NW)H57", "BF8)MMH", "F3Q)7XM", "ZT9)7MP",
"ZCF)VHS", "XPX)DPM", "XSQ)W2G", "B7D)9KH", "79H)M2P", "LZ8)77S", "2JF)XTD", "H47)2JF",
"LYT)SQV", "3YQ)S58", "8B8)85B", "L49)KV7", "3JF)D7F", "96M)FMY", "QQV)TRD", "YVH)2KK",
"8KC)K3V", "4D2)STW", "1P7)HBH", "9XB)M9M", "Q99)8PN", "JYY)WJW", "4LC)GB6", "2TR)Y4H",
"B4N)FGP", "6PJ)5JB", "SMG)Q9N", "2YR)FMP", "6ND)W5P", "YYZ)GY4", "Y7Q)251", "H5R)YYW",
"1FY)Y7Q", "SXR)5YG", "PFL)NCT", "D61)Z5K", "2KL)V76", "62F)6DW", "J3Y)YOU", "NGM)78Y",
"X7P)GKT", "BTN)ZVQ", "121)PQ6", "MPK)W89", "LV9)WVG", "TZV)BXZ", "3S3)LWP", "CGQ)CZF",
"N6X)CCN", "XJ4)3WK", "SR6)1RV", "GD3)F78", "JW6)GKL", "P8T)6K2", "HZ7)WSH", "6V5)PG9",
"R9C)J3Y", "PJC)G3V", "5Y4)63K", "4M5)7W3", "2BF)23M", "LX6)TWM", "526)KV6", "LK7)YVH",
"576)9ML", "6D9)4HZ", "6VC)HQP", "CFS)119", "TC9)3BP", "CBX)DSW", "JMQ)LG6", "QTB)8GW",
"VWD)JWN", "3PY)JHL", "ZZQ)TZV", "6SL)BRX", "GD7)51L", "Y2T)9FS", "TGF)976", "6PP)WT1",
"JHL)9W9", "SMJ)99W", "ZL1)MJ5", "RSW)6KQ", "DD7)M86", "SLM)2VQ", "M9J)HMW", "5VN)ZQ3",
"8G5)JPH", "MFR)YVP", "WXG)TWQ", "2QH)LBP", "15R)7YR", "K17)7VX", "QZQ)YQ4", "QZF)WFT",
"2B1)D4Q", "STW)V21", "ZDX)669", "8Y7)6V6", "KDY)DN4", "DVT)LHZ", "2WD)6M5", "S2B)YV7",
"3SF)3LQ", "DCR)NG1", "R91)CQW", "MJQ)LMT", "ST3)YDW", "4T3)4Y4", "3VT)26D", "3HR)31P",
"BSF)HHP", "VL2)3H4", "TVM)C3Y", "9M1)45N", "PQ6)MR5", "G6G)6F1", "Y74)Z1Z", "F5T)LSK",
"WV5)KPZ", "2VQ)22G", "582)KZQ", "5RX)8M1", "YFZ)F2C", "QMV)DBM", "THC)WHW", "P2P)19H",
"DHM)2CL", "PCP)XZ5", "7NY)JGX", "FR1)NBT", "HHD)K11", "31T)HVF", "JCM)B2S", "1QB)QQV",
"VPL)JF5", "C4Z)YBN", "5DH)74L", "VY2)R8D", "46H)MZ1", "DTN)JG7", "NY2)DZ8", "KPZ)6G2",
"SZ3)RLZ", "TMQ)NFW", "HQH)4GR", "MMC)TLH", "B4N)4XK", "2ZQ)JWW", "2YM)QMT", "G73)FN7",
"GN4)KJK", "P6P)XNT", "YFZ)C7L", "P1V)GMK", "P2S)2RB", "QXG)2KL", "W89)FQS", "DLS)1MP",
"MHX)44H", "C2T)3QM", "W86)T6T", "MCN)X9M", "M2P)57N", "SCH)GHP", "XH4)576", "9FS)PKC",
"R8D)D2N", "ZQX)37J", "LN8)BRM", "HWD)ZK6", "LBP)53C", "YX6)7KF", "5QW)SBM", "LXH)KVK",
"263)G3L", "B1G)XTY", "3BP)FPT", "CWD)5TM", "TNB)L5S", "6XC)WPS", "7QK)G5V", "CSR)B69",
"YHG)5XK", "6K2)ZTH", "C7T)QZQ", "NBN)FVW", "8P1)QJ6", "GFS)SMJ", "W2G)G6G", "VDR)4YD",
"25M)MDK", "YDW)QTB", "LNN)FHY", "DPM)2F8", "899)S4M", "F73)VHQ", "5D3)6NG", "F85)ST3",
"Q8N)81J", "XBW)5LC", "85M)51G", "M1F)76Z", "8LP)NY1", "21C)P5K", "T6T)41C", "Z59)9H1",
"VC7)M8V", "Q5B)CGQ", "JYR)CBX", "3RL)WKP", "BQ2)LX1", "8LL)TTM", "MC7)3M5", "L4Z)11N",
"RPZ)9DJ", "119)DPY", "XK7)SZ3", "3CS)ZR3", "3PN)WYW", "LL4)5V9", "HSJ)SKF", "PTP)K17",
"MPW)X4Y", "LRM)CFY", "V3G)W9B", "SBR)PJ6", "KYQ)Q9S", "WQ4)CCD", "N25)2BZ", "Z5K)XSQ",
"D4G)9V1", "LX1)MW5", "RB5)XJR", "W29)LKV", "CTG)HLP", "3Q3)QZF", "9BC)BTR", "P9B)ZSN",
"PLY)Z4B", "CBX)X1H", "L64)QMW", "T96)LGD", "399)8G5", "LG6)HQW", "Y5J)31F", "G8X)FCN",
"Y44)ZCF", "8X4)B12", "NL2)5G5", "4YD)XK7", "Z8K)CPT", "LRH)6YQ", "R9F)NHC", "86T)K57",
"QLQ)HLJ", "VKQ)YPQ", "BC3)9VB", "9F6)46L", "74X)39R", "Z1T)WVM", "WXN)V3D", "976)SYR",
"MW5)42P", "LMT)P9W", "JPK)H3J", "ZCS)B6N", "XTD)FXH", "PHD)FP4", "TCC)T7C", "RJ3)QD6",
"PM7)VM5", "K3V)2JH", "HCS)3WZ", "1HY)ZPY", "VRL)HQL", "HLH)BMT", "4NW)ZQX", "1M1)L4R",
"FVW)9KG", "PKD)JL4", "FCN)5QW", "731)VG6", "GP7)ZZZ", "GCM)D8F", "5DV)RVS", "QJK)PB9",
"67M)KXH", "VVD)B6S", "ZLD)CXQ", "5BP)N25", "3NN)M93", "SVJ)Y4C", "TRW)VK7", "LN9)85Z",
"Z9J)94M", "9WS)85S", "9V1)LX6", "NY1)59Y", "1RV)4K2", "33D)3S3", "3HX)9T1", "9ZP)4BV",
"R5D)K6B", "DLW)LJK", "6YQ)CH7", "QHQ)VSG", "CG7)V36", "85G)HPV", "LQ9)9BR", "7F2)VRR",
"29L)62F", "Q9S)2D1", "PWY)8DV", "WPS)S8G", "FB3)7HH", "1YL)HG7", "S8C)RPN", "F57)WNY",
"YBL)HSJ", "C75)QRD", "WP9)LM1", "HG7)QH2", "N5R)6DH", "TWM)LWS", "LRH)FBM", "78G)WVL",
"MH9)1N9", "YS1)QJM", "G3L)TCC", "BTV)314", "XDL)TCQ", "6MW)389", "MYZ)TQ6", "CHT)BF8",
"37V)JQW", "QKL)T2W", "DJR)D4R", "CRK)G2Q", "S4M)B4V", "NRN)9F6", "BRM)465", "5JJ)CFM",
"75Z)82F", "W8Q)ZQ7", "X68)31T", "QW1)Q6V", "PYY)1JW", "6B4)NG5", "NQ6)RL1", "GHP)731",
"CQW)427", "4W7)39N", "XF7)VW9", "MTY)1PP", "BV1)S4Q", "4CJ)JW6", "52R)DTL", "453)WBK",
"HPV)BLQ", "JH9)DCR", "JSF)NZX", "FCG)W8Q", "YJH)BC3", "JKV)NQZ", "RLZ)5D3", "9H8)8BD",
"DGX)Q76", "MJX)QZV", "9SB)NL9", "B7Y)5VP", "689)9GR", "NS5)Q83", "K5D)9SQ", "QJ6)L64",
"254)HHD", "WYQ)J19", "6BQ)QKX", "6VC)6TY", "5V7)4SS", "378)NWP", "L9B)VPH", "JBZ)8KB",
"1SZ)F57", "8T6)JSF", "2D1)M74", "HVH)1M1", "446)7HP", "9VB)DW1", "9MM)RPZ", "1PV)8T6",
"11N)121", "WPB)YH7", "MLD)DHM", "VLK)D74", "HJZ)9HP", "53C)3GQ", "MBB)SWM", "SNN)5TN",
"CR5)BTN", "1FL)YQP", "PMN)PJC", "R3J)68S", "NG5)P5G", "1X2)WT2", "BPF)PW5", "MX7)6ND",
"H57)CSR", "CHJ)P14", "P5D)YS1", "QN6)ZQN", "4SS)BQX", "FG2)WQ4", "HG3)5SS", "SH6)S2W",
"Y4H)SYP", "6TY)8TX", "J4Z)TJM", "STZ)WHD", "2BQ)BMV", "N56)1Z7", "CZF)NJK", "MJ5)5PZ",
"KK7)93T", "CMQ)DLW", "Z1Z)L1Y", "8SM)NPR", "5V9)L4Z", "P7Q)5K8", "NHC)CKH", "X47)PNR",
"4J8)KPD", "SZD)2ZQ", "K48)7FB", "FMP)39P", "3XL)YJT", "T3R)M2B", "K11)P3F", "NNK)5CV",
"J3X)BQ2", "5JB)PY5", "XHQ)R3S", "9KH)GY8", "7W1)VDQ", "7MM)T2C", "V59)K76", "ZVN)RKJ",
"N6J)B7M", "QZV)SBR", "DPC)X6T", "ZSD)SVJ", "5PZ)NS5", "DBH)V7Y", "8J1)N1M", "QNB)S5L",
"7LJ)DD7", "SYR)NPS", "CH7)Y2T", "YMP)NNV", "95P)G8P", "7HH)LLJ", "4MB)JXG", "68S)P4Z",
"58H)J1L", "P8R)B7Y", "HXJ)5BP", "MQJ)4XP", "85B)TDZ", "J1W)R42", "D8F)7F2", "T99)CVW",
"WK2)PBG", "W16)W5J", "CG7)LBK", "JPH)Y6Q", "B69)3YQ", "ZFJ)JJQ", "5XF)SS7", "NBT)FBK",
"JXG)TNB", "JL3)FR8", "BHG)GHS", "YZQ)GMJ", "LN9)NWS", "WHW)3NP", "M2B)KT3", "Z9L)J4T",
"R67)M4Y", "GKT)M43", "TF2)BV1", "HMW)BWJ", "ZJQ)HB2", "WXR)SZD", "8WX)5DH", "BM3)KD4",
"WVG)RBT", "YFD)ZKL", "8C6)8VC", "2JH)DJ5", "NQZ)P7Q", "86K)8LL", "MHX)K48", "1JW)STF",
"KQJ)6PP", "NG1)3VT", "C7T)VVD", "N3W)2TY", "5CV)GXR", "CQJ)55J", "J2T)526", "RW8)LF3",
"CJF)PXW", "4PZ)R4B", "Y3T)W6T", "X4Y)1QB", "51L)5D4", "Z4B)DL1", "1PP)1W5", "LLJ)5RX",
"5ZG)WK2", "6PR)8KC", "RB6)2ZV", "R4R)B1G", "Q76)W8M", "5MJ)4LC", "S58)1DN", "5J4)B47",
"TTM)2YM", "JF6)YYS", "HL7)M37", "XXQ)FG2", "YN9)FGR", "121)NJV", "B6N)1DD", "SWM)VQQ",
"MZN)LN8", "B9X)GCM", "NHP)6D9", "JWW)PFL", "D7F)LTG", "BLQ)B16", "6M5)9FC", "WG9)WJK",
"GL2)5QV", "1W5)VDT", "GQF)QNB", "Y7Q)446", "LKV)VKQ", "YQP)VS5", "SDT)CTG", "K91)XGP",
"9GR)CRD", "F78)BVN", "MB5)FR1", "KT3)96M", "GY4)WFX", "2ZJ)LQB", "251)3HR", "9C5)BS2",
"MS2)QGV", "1DN)2M1", "ZMZ)BHG", "TNX)PBY", "FDH)LXH", "2ZV)147", "HHP)2BL", "MRW)4NW",
"SYP)HQH", "389)3PN", "ZKL)33D", "D4P)6MW", "6YQ)QHQ", "8Y8)S48", "9W9)85M", "LBK)MJS",
"GHB)DGS", "G7M)MPK", "HZG)399", "P5K)DM4", "72R)26Q", "VVD)97N", "4CB)BMD", "5XW)R9C",
"7T3)6TP", "BRX)W86", "TQV)TNX", "8K1)RSW", "MJS)H5R", "3HJ)QKL", "WBK)4CZ", "WFX)1TL",
"V76)TQ4", "NCD)X5S", "HTQ)428", "TQ6)MLD", "N85)R2D", "DKW)25M", "J4S)71W", "BTR)JP6",
"124)QLQ", "67M)ZVN", "XV1)DLM", "1Z2)15R", "TDZ)112", "JH9)CM4", "YTT)WXZ", "HRB)15L",
"65J)3KZ", "CPB)L9B", "JD3)V9J", "3NN)1VC", "2T5)XPX", "KQG)VGD", "LHZ)TLL", "S7T)BPY",
"VDT)ZDX", "1RW)21C", "SBV)M9J", "L1Y)V6W", "CYK)T3R", "YLM)N6J", "XT2)9WQ", "LTG)4B8",
"J3X)XVH", "7YR)K32", "ZSN)RGM", "NYC)29L", "P6X)HYF", "7KM)7R1", "58H)RMJ", "JKT)WXR",
"FVW)V79", "RL1)TRV", "WT1)J7R", "MKM)BPF", "HW1)KX1", "MP9)6X1", "LQB)L6P", "D4Q)Y44",
"5SJ)K7D", "TZL)YZQ", "DSR)3JF", "17P)9C7", "COM)KYQ", "S14)LVB", "DS4)FDH", "KZQ)79H",
"71W)7QK", "7HZ)CHJ", "NGP)WRM", "8M1)79F", "YYS)Y28", "RTN)PPQ", "WT2)8Y7", "YJT)R3J",
"3H4)1RW", "T9Q)DLS", "6GJ)WZ5", "HBH)8BC", "LNP)2TR", "5TN)HMQ", "2RB)NTV", "GVM)YWL",
"SBM)1S3", "BGP)QX4", "WC1)LKB", "J7R)BFX", "2TB)9YC", "2KK)GGW", "WXR)LRH", "V86)QHC",
"NPS)Z9L", "18S)V33", "CKH)MC7", "5DH)BBR", "2RW)SYX", "CPL)MRW", "ZTP)XLC", "NFX)SD3",
"TRW)NQ6", "WKP)Z8K", "HHP)JCM", "SVJ)VL2", "TRZ)HG6", "SKF)RJ3", "FF8)Z9J", "NT2)GHB",
"HLH)DPC", "FGP)JD3", "2G7)RB5", "L4R)4VB", "14D)5XW", "XPR)9MQ", "P3F)P5D", "4JM)QCX",
"361)NXD", "6SJ)8N6", "393)68H", "QKX)7CG", "1V6)7KM", "QMT)8B8", "X5S)37V", "FXH)HL7",
"NL9)K3S", "WYW)BR6", "K7C)168", "9HP)VNM", "S48)FB3", "WBB)74X", "DKL)LS3", "SD3)JL5",
"6X1)Q99", "WVN)2YR", "G3V)QMV", "4DD)9M6", "4WY)MQJ", "PWY)PYY", "FF2)VLK", "J1L)Q8G",
"B9X)WQZ", "28F)DV3", "K76)Y8B", "TFL)PWY", "HQP)WYQ", "3R1)L9H", "HQL)TF2", "QW1)VV4",
"446)73F", "4CZ)JXC", "HPK)5ZT", "S7X)3CS", "KPD)CRK", "3X8)FV7", "G7G)5ZG", "SMG)C7T",
"ZK6)4CJ", "TL3)9RW", "6SJ)LZ8", "8XT)TF7", "81J)839", "LL4)B4N", "ZQ7)S2B", "8HY)3XJ",
"X6T)4MB", "2JH)3VX", "SYB)NLY", "B62)1LD", "9YC)6PB", "2WP)WG6", "MY4)RW8", "13C)HDT",
"NHP)9WS", "9PZ)BKD", "NBQ)261", "NJV)HPF", "323)KNM", "L26)SQS", "NXD)422", "SJ5)B1Q",
"JS2)DFL", "7W3)1YS", "QD6)MX7", "HLP)D6F", "Y5J)3RL", "3YT)2B1", "K5H)J2T", "GH7)J1W",
"C3Y)G54", "7RN)5J4", "6YS)NFX", "31P)LN9", "P77)MKM", "MMH)ZLL", "HXB)9GL", "59Y)FRK",
"RB5)LNN", "MZ1)TT2", "9W2)CCV", "WNH)PTP", "XFL)G9W", "NFW)PJ9", "K7D)M1F", "GB6)T99",
"BMD)361", "WNY)HNZ", "P25)WNH", "Q6V)YJH", "S2W)7QG", "QLQ)TQV", "W85)NHP", "CPP)8WX",
"M37)PZ3", "XX5)2LQ", "CY1)6HZ", "PW5)7W1", "5XK)SB4", "CXQ)DKW", "N38)WV5", "M5N)Y5J",
"VRR)FP7", "CFM)HZ7", "NCD)6V5", "NY1)P8R", "51G)R67", "168)L44", "B84)4SN", "3QM)Y77",
"RKJ)FN5", "9MQ)GD7", "JF5)VY2", "BCH)TQ7", "FM7)YMP", "KCF)4J8", "5WZ)VDR", "44H)MJV",
"6SL)LNK", "45N)QG2", "B88)Y3T", "QWY)7RN", "FBB)6VC", "9H1)WG9", "VG6)PLY", "15R)PKD",
"M43)9PZ", "D2Z)38X", "FHY)KDY", "78Y)GZT", "2SY)8JL", "DPY)C4F", "NJK)FCG", "XTY)N5R",
"QY4)XF7", "4HZ)ZTP", "STF)VRL", "11X)JF6", "2GG)ZJQ", "WRM)N4H", "17X)XHQ", "S5L)SNN",
"K9Z)SJ5", "D74)6PJ", "QMB)1X2", "26C)2NJ", "VLY)R6F", "2BZ)CB5", "46L)1YL", "B2S)WP9",
"669)MHX", "LF3)WHF", "7NC)8SM", "1NR)T56", "DV3)Q8N", "D72)S9B", "TCD)GB9", "3WZ)QN6",
"4LC)XXW", "N5T)HTQ", "GMP)323", "K32)2Z6", "DKL)XFB", "2TR)ZSD", "6PB)ZDP", "L6G)TY9",
"FNX)58H", "D4R)JH9", "PG9)P8T", "TQ7)ZL1", "KM5)6KV", "6DW)9ZX", "H3J)8ML", "7W1)V3G",
"LVB)SD1", "2LQ)6CJ", "HP6)3XL", "99W)K9Z", "YV7)5Y4", "QTH)1NR", "LQY)9MM", "4BV)NNK",
"5ZT)LK7", "LM1)K93", "8LG)THY", "LQT)Z2X", "M4Y)B9X", "JXC)NBQ", "DKD)G5C", "R9Y)2T5",
"PMN)8C6", "XJR)MZN", "839)7Y1", "3KZ)78G", "26D)RC9", "XZ5)6GJ", "PCP)TL3", "1VC)8Y8",
"FXS)2FM", "1YS)M78", "85Z)GWC", "GY8)S7T", "PX5)TX2", "NJB)8MR", "2YB)PM7", "GZT)WMC",
"1VL)R4R", "SMC)785", "S9B)CTV", "2FG)H47", "HMQ)1PV", "FHN)C45", "B17)WSL", "GB9)ZR1",
"BFX)8XT", "T49)KQJ", "4NQ)G7G", "4XK)S39", "WT1)GMP", "314)7H1", "B16)TC8", "JDM)QBT",
"CRN)NBN", "CW1)6B4", "T6S)6PR", "KNG)MBB", "2R4)YHG", "VJH)GTX", "3PH)XT2", "J4Z)WXN",
"8GF)WTQ", "JSF)4BM", "6TP)14D", "Z38)N38", "BDH)HPK", "4XP)BDG", "QV7)NT2", "2JF)WXG",
"WHD)DBH", "WLR)XDL", "9FS)XBM", "NCT)DBV", "JQW)HG3", "GKL)6XC", "B6S)TY1", "H8R)2ZW",
"D1G)LQ9", "YZ1)8J1", "TY9)FF8", "2L8)MMC", "Z2X)3P6", "F82)CY1", "S39)LSG", "GJM)MS2",
"TLB)DRS", "KJK)D4P", "9FC)K7C", "GT6)QHR", "9WQ)M61", "BMV)D72", "WVM)YFD", "N4H)W29",
"ZV2)R9Y", "QHR)GP7", "465)X8K", "X9M)2H7", "4V3)LST", "T2C)MCN", "Y77)NY2", "WVM)SXB",
"2Z6)FQG", "1YC)22K", "WSH)J4Z", "Q8G)N3W", "DJ5)NWW", "4BM)TRZ", "9M6)STZ", "S5W)95P",
"WVL)P9M", "KXH)KM5", "2R1)7VP", "DZ9)YLM", "M1R)6KL", "6KL)QY4", "4K2)XV1", "6FC)X7S",
"CFY)TRW", "WHF)1VL", "DV2)H8R", "XGP)5DV", "BVF)7KH", "TC8)P2P", "TX2)H98", "TY1)4JM",
"FSN)VRH", "XT5)TGF", "XLC)3PH", "T2F)YPT", "YDW)SMG", "LSK)KWN", "77S)BSF", "TX2)MJQ",
"QTB)4T3", "MX2)HJZ", "BJL)Z59", "YBB)4V3", "1LD)4M5", "RVS)LRM", "DBV)6BJ", "3YQ)L49",
"K1M)6SJ", "C6C)GT6", "V79)D61", "6Q4)Z1S", "2BG)8RZ", "SBV)HKC", "WJK)QMB", "X7S)C2T",
"D6F)7HZ", "39N)17X", "M1R)FSN", "9BR)65J", "7HP)ZMZ", "M2H)VWD", "DD8)T96", "M78)4NB",
"FMY)HZG", "19H)MTY", "Q5B)LV9", "4GR)DNV", "WFT)8D1", "HPF)HLH", "PND)CPP", "XVH)1R9",
"LWS)Z1T", "HPK)BHN", "63K)XPR", "5SS)V93", "V9J)F97", "9MM)MFR", "WWP)9SB", "1WW)SBV",
"S4Q)3X8", "W6T)P9B", "22K)K8G", "3XJ)5M5", "8PN)2R1", "SJ3)4D2", "X7S)1V6", "QV6)L6G",
"R3S)LYP", "425)MB5", "86H)HL6", "31F)XZY", "B7M)XS3", "9DJ)7K5", "DFL)F85", "MJV)DTN",
"8LL)7T3", "HDT)TCD", "4Y4)2WP", "GKB)QWF", "98M)FNX", "2ZW)81Q", "4Z7)1FY", "GXR)QJK",
"5YG)T49", "C3M)R8R", "4XK)P77", "GMK)GGS", "5BH)T9Q",
]
.to_vec();
println!("{:?}", parse(data.clone()));
assert_eq!(227612, checksum(parse(data.clone())));
assert_eq!(
4,
min_orbrital_transfers(&parse(data.clone()).into_graph(), "YOU", "SAN")
);
}
#[test]
fn ex_2() {
let mut gr = DiGraphMap::<&str, &str>::new();
gr.add_node("a");
gr.add_node("b");
gr.add_node("a");
gr.add_edge("a", "b", "1");
println!("{:?}", gr);
}
#[test]
fn ex_3() {
let data = [
"COM)B", "B)C", "C)D", "D)E", "E)F", "B)G", "G)H", "D)I", "E)J", "J)K", "K)L", "K)YOU",
"I)SAN",
]
.to_vec();
assert_eq!(
4,
min_orbrital_transfers(&parse(data.clone()).into_graph(), "YOU", "SAN")
);
}
}
|
//! `Secret<T>` wrapper type for more carefully handling secret values
//! (e.g. passwords, cryptographic keys, access tokens or other credentials)
//!
//!
//! ### Usage
//! ```
//! use redactedsecret::{Secret, SecretString, SecretVec, SecretBox};
//! ```
//!
//!
//! ### Examples
//!
//! 1. Create a `Secret` on any type (Generic Type)
//! ```
//! use redactedsecret::{Secret, ExposeSecret};
//!
//! let dummy_PIN = Secret::new(1234);
//!
//! assert_eq!(dummy_PIN.expose_secret().to_owned(), 1234);
//! ```
//!
//! 2. Create a string from `SecretString`
//! ```
//! use redactedsecret::{SecretString, ExposeSecret};
//!
//! let dummy_PIN = SecretString::new("I am a string PIN".to_owned());
//!
//! assert_eq!(dummy_PIN.expose_secret().to_owned(), "I am a string PIN".to_owned());
//! ```
//!
//! 3. Create a Boxed type from a `SecretBox` type
//! ```
//! use redactedsecret::{Secret, ExposeSecret};
//!
//! let dummy_PIN = Box::new(Secret::new(1234));
//!
//! assert_eq!(dummy_PIN.expose_secret().to_owned(), 1234);
//! ```
//!
//! 4. Create a vector from a `SecretVec`
//! ```
//! use redactedsecret::{SecretVec, ExposeSecret};
//!
//! let dummy_PIN = SecretVec::new(vec![1234]);
//!
//! assert_eq!(dummy_PIN.expose_secret().to_owned(), vec![1234]);
//! ```
#![no_std]
#![deny(
missing_docs,
rust_2018_idioms,
trivial_casts,
unused_lifetimes,
unused_qualifications,
missing_doc_code_examples
)]
#![forbid(unsafe_code)]
#![doc(html_root_url = "https://docs.rs/secrecy/0.4.0")]
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "alloc")]
/// ### Usage
/// ```
/// use redactedsecret::SecretBox;
/// ```
mod boxed;
#[cfg(feature = "bytes")]
/// ### Usage
/// ```
/// use redactedsecret::Secret;
/// ```
mod bytes;
#[cfg(feature = "alloc")]
/// ### Usage
/// ```
/// use redactedsecret::SecretString;
/// ```
mod string;
#[cfg(feature = "alloc")]
/// ### Usage
/// ```
/// use redactedsecret::SecretVec;
/// ```
mod vec;
#[cfg(feature = "alloc")]
/// ### Usage
/// ```
/// use redactedsecret::{SecretBox, SecretString, SecretVec};
/// ```
pub use self::{boxed::SecretBox, string::SecretString, vec::SecretVec};
#[cfg(feature = "bytes")]
pub use self::bytes::{SecretBytes, SecretBytesMut};
use core::fmt::{self, Debug};
#[cfg(feature = "serde")]
use serde::{de, ser, Deserialize, Serialize};
use zeroize::Zeroize;
/// Wrapper type for values that contains secrets, which attempts to limit
/// accidental exposure and ensure secrets are wiped from memory when dropped.
/// (e.g. passwords, cryptographic keys, access tokens or other credentials)
///
/// Access to the secret inner value occurs through the `ExposeSecret` trait,
/// which provides an `expose_secret()` method for accessing the inner secret
/// value.
///
/// pub struct Secret<S>
/// where
/// S: Zeroize,
/// {
/// /// Inner secret value
/// inner_secret: S,
/// }
///
/// ### Usage
/// ```
/// use redactedsecret::{Secret, ExposeSecret};
///
/// let data = Secret::new("Data".to_owned());
/// /// Show the contents housed inside the `Secret`
/// let new_data = data.expose_secret();
/// ```
pub struct Secret<S>
where
S: Zeroize,
{
/// Inner secret value
#[allow(missing_doc_code_examples)]
inner_secret: S,
}
#[allow(missing_doc_code_examples)]
impl<S> PartialEq for Secret<S>
where
S: Zeroize + PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.expose_secret() == other.expose_secret()
}
}
/// ### Usage
/// ```
/// use redactedsecret::Secret;
/// ```
impl<S> Secret<S>
where
S: Zeroize,
{
/// Take ownership of a secret value
/// ### Usage
/// ```
/// use redactedsecret::Secret;
///
/// let data = Secret::new("Data".to_owned());
/// ```
pub fn new(secret: S) -> Self {
Secret {
inner_secret: secret,
}
}
}
/// ### Usage
/// ```
/// use redactedsecret::{Secret, ExposeSecret};
/// ```
impl<S> ExposeSecret<S> for Secret<S>
where
S: Zeroize,
{
/// Expose the contents inside a `Secret`
/// ### Usage
/// ```
/// use redactedsecret::{Secret, ExposeSecret};
///
/// let data = Secret::new("Data".to_owned());
/// /// Show the contents housed inside the `Secret`
/// let new_data = data.expose_secret();
/// ```
fn expose_secret(&self) -> &S {
&self.inner_secret
}
}
/// ### Usage
/// ```
/// use redactedsecret::Secret;
/// ```
impl<S> Clone for Secret<S>
where
S: CloneableSecret,
{
/// ### Usage
/// ```
/// use redactedsecret::Secret;
///
/// let data = Secret::new("Data".to_owned());
/// /// Clone the variable
/// let new_data = data.clone();
/// ```
fn clone(&self) -> Self {
Secret {
inner_secret: self.inner_secret.clone(),
}
}
}
/// ### Usage
/// ```
/// use redactedsecret::Secret;
/// ```
impl<S> Debug for Secret<S>
where
S: Zeroize + DebugSecret,
{
/// ### Usage
/// ```
/// use redactedsecret::Secret;
///
/// dbg!(Secret::new("foo".to_owned()));
/// ```
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Secret({})", S::debug_secret())
}
}
#[allow(missing_doc_code_examples)]
impl<S> Drop for Secret<S>
where
S: Zeroize,
{
fn drop(&mut self) {
// Zero the secret out from memory
self.inner_secret.zeroize();
}
}
/// Marker trait for secrets which are allowed to be cloned
/// ### Usage
/// ```
/// use redactedsecret::CloneableSecret;
/// ```
pub trait CloneableSecret: Clone + Zeroize {}
/// Expose a reference to an inner secret
/// ### Usage
/// ```
/// use redactedsecret::ExposeSecret;
/// ```
pub trait ExposeSecret<S> {
/// Expose secret
/// ### Usage
/// ```
/// use redactedsecret::{SecretString, ExposeSecret};
///
/// let data = SecretString::new("Foo".to_owned());
/// // Expose the contents of a `Secret`
/// dbg!(data.expose_secret());
/// ```
fn expose_secret(&self) -> &S;
}
/// Debugging trait which is specialized for handling secret values
/// ### Usage
/// ```
/// use redactedsecret::DebugSecret;
/// ```
pub trait DebugSecret {
/// Information about what the secret contains.
///
/// Static so as to discourage unintentional secret exposure.
/// ### Usage
/// ```
/// use redactedsecret::{SecretString, DebugSecret};
///
/// let data = SecretString::new("Foo".to_owned());
/// ```
fn debug_secret() -> &'static str {
"R3DACT3D::<GENERIC::S3CR3T"
}
}
/// Marker trait for secrets which can be serialized directly by `serde`.
/// Since this provides a non-explicit exfiltration path for secrets,
/// types must explicitly opt into this.
///
/// If you are working with a `SecretString`, `SecretVec`, etc. type, they
/// do *NOT* impl this trait by design. Instead, if you really want to have
/// `serde` automatically serialize those types, use the `serialize_with`
/// attribute to specify a serializer that exposes the secret:
///
/// <https://serde.rs/field-attrs.html#serialize_with>
#[cfg(feature = "serde")]
pub trait SerializableSecret: Serialize {}
#[cfg(feature = "serde")]
impl<'de, T> Deserialize<'de> for Secret<T>
where
T: Zeroize + Clone + DebugSecret + de::DeserializeOwned + Sized,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
T::deserialize(deserializer).map(Secret::new)
}
}
#[cfg(feature = "serde")]
impl<T> Serialize for Secret<T>
where
T: Zeroize + DebugSecret + Serialize + Sized,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
self.expose_secret().serialize(serializer)
}
}
|
use unicode_segmentation::UnicodeSegmentation;
use widget::Widget;
use Size;
#[derive(Debug, PartialEq, Clone)]
pub struct Text {
pub lines: Vec<String>,
pub style: Option<String>,
}
impl Widget for Text {
fn render_content(&self, size: Size) -> Option<Vec<String>> {
let lines: Vec<String> = self.lines
.iter()
.flat_map(|l| l.lines())
.flat_map(|l| {
let letters: Vec<&str> = UnicodeSegmentation::graphemes(l, true).collect();
letters
.chunks(size.width)
.map(|ls| ls.concat())
.collect::<Vec<String>>()
.into_iter()
})
.collect();
let loglen = lines.len();
let lines = if loglen > size.height {
lines.clone().split_off(loglen - size.height)
} else {
lines.clone()
};
Some(lines)
}
fn render_style(&self) -> Option<String> {
self.style.clone()
}
}
impl Text {
pub fn new(lines: Vec<String>) -> Text {
Text { lines, style: None }
}
pub fn new_styled(lines: Vec<String>, s: &str) -> Text {
let style = Some(s.to_owned());
Text { lines, style }
}
pub fn push(&mut self, s: String) {
self.lines.extend(s.lines().map(|l| l.to_owned()));
}
pub fn set(&mut self, s: &str) {
self.lines = s.lines().map(|l| l.to_owned()).collect();
}
}
|
#![warn(clippy::all)]
pub extern crate las as las_rs;
pub mod ascii;
pub mod base;
pub mod las;
pub mod tiles3d;
|
use amethyst::{
assets::{AssetStorage, Loader, ProgressCounter},
ecs::prelude::World,
renderer::{
PngFormat, SpriteSheet, SpriteSheetHandle, Texture,
TextureMetadata, SpriteSheetFormat, TextureHandle,
},
};
/// TODO: implement BmpFormat, JpgFormat, ...
pub fn load_image_png(
world: &mut World,
path: String,
) -> TextureHandle {
let loader = world.read_resource::<Loader>();
let texture_storage = world.read_resource::<AssetStorage<Texture,>>();
loader.load(
path,
PngFormat,
TextureMetadata::srgb_scale(),
(),
&texture_storage,
)
}
/// TODO: implement BmpFormat, JpgFormat, ...
pub fn load_image_png_tracked(
world: &mut World,
path: String,
progress_counter_ref: &mut ProgressCounter
) -> TextureHandle {
let loader = world.read_resource::<Loader>();
let texture_storage = world.read_resource::<AssetStorage<Texture,>>();
loader.load(
path,
PngFormat,
TextureMetadata::srgb_scale(),
progress_counter_ref,
&texture_storage,
)
}
pub fn load_spritesheet(
world: &mut World,
base_path: String,
) -> SpriteSheetHandle {
#[cfg(feature = "debug")]
debug!("Loading spritesheet without ProgressCounter.");
let mut image_path = std::string::String::from(base_path.clone());
image_path.push_str(".png");
let mut sheet_path = std::string::String::from(base_path);
sheet_path.push_str(".ron");
let texture_handle = load_image_png(
world,
image_path
);
let loader = world.read_resource::<Loader>();
let sprite_sheet_storage = world.read_resource::<AssetStorage<SpriteSheet,>>();
loader.load(
sheet_path,
SpriteSheetFormat,
texture_handle,
(),
&sprite_sheet_storage
)
}
pub fn load_spritesheet_tracked(
world: &mut World,
base_path: String,
progress_counter_ref: &mut ProgressCounter,
) -> SpriteSheetHandle {
#[cfg(feature = "debug")]
debug!("Loading spritesheet with ProgressCounter.");
let mut image_path = base_path.clone();
image_path.push_str(".png");
let mut sheet_path = base_path;
sheet_path.push_str(".ron");
let texture_handle = load_image_png_tracked(
world,
image_path,
progress_counter_ref,
);
let loader = world.read_resource::<Loader>();
let sprite_sheet_storage = world.read_resource::<AssetStorage<SpriteSheet,>>();
loader.load(
sheet_path,
SpriteSheetFormat,
texture_handle,
progress_counter_ref,
&sprite_sheet_storage
)
}
|
mod ring1 {
pub mod ring2 {
pub mod ring3 {
pub fn test() {
println!("{:?}", "test");
}
pub fn halo() {
println!("{:?}", "halo");
}
}
}
}
// use {self}
use ring1::ring2::{
self, // 这个代表 ring2 自己
ring3::{
self, // 这个代表 ring3 自己
test,
},
};
fn main() {
ring2::ring3::halo();
ring3::halo();
test();
}
|
// _ _
// | |_| |__ ___ ___ __ _
// | __| '_ \ / _ \/ __/ _` |
// | |_| | | | __/ (_| (_| |
// \__|_| |_|\___|\___\__,_|
//
// licensed under the MIT license <http://opensource.org/licenses/MIT>
//
// crypt.rs
// defintions of the AES encryption, decryption, and PBKDF2 key derivation
// functions required to read and write encrypted profiles.
use std::iter::repeat;
use crypto::{symmetriccipher, buffer, aes, blockmodes};
use crypto::buffer::{ReadBuffer, WriteBuffer, BufferResult};
use crypto::pbkdf2::pbkdf2;
use crypto::hmac::Hmac;
use crypto::sha2::Sha256;
use crypto::digest::Digest;
use crypto::fortuna::Fortuna;
use rand::{SeedableRng, Rng};
// ALL the encryption functions thx rust-crypto ^_^
pub fn encrypt(data: &[u8], key: &[u8]) -> Result<Vec<u8>, symmetriccipher::SymmetricCipherError> {
let mut iv = [0u8; 16];
let mut f: Fortuna = SeedableRng::from_seed(data);
f.fill_bytes(&mut iv);
let mut encryptor =
aes::cbc_encryptor(aes::KeySize::KeySize256, key, &iv, blockmodes::PkcsPadding);
let mut final_result = Vec::<u8>::new();
final_result.extend_from_slice(&iv);
let mut read_buffer = buffer::RefReadBuffer::new(data);
let mut buffer = [0; 4096];
let mut write_buffer = buffer::RefWriteBuffer::new(&mut buffer);
loop {
let result = try!(encryptor.encrypt(&mut read_buffer, &mut write_buffer, true));
final_result.extend(write_buffer.take_read_buffer().take_remaining());
if let BufferResult::BufferUnderflow = result {
break;
}
}
Ok(final_result)
}
pub fn decrypt(encrypted_data: &[u8],
key: &[u8])
-> Result<Vec<u8>, symmetriccipher::SymmetricCipherError> {
let iv = &encrypted_data[0..16];
let mut decryptor =
aes::cbc_decryptor(aes::KeySize::KeySize256, key, iv, blockmodes::PkcsPadding);
let mut final_result = Vec::<u8>::new();
let mut read_buffer = buffer::RefReadBuffer::new(&encrypted_data[16..]);
let mut buffer = [0; 4096];
let mut write_buffer = buffer::RefWriteBuffer::new(&mut buffer);
loop {
let result = try!(decryptor.decrypt(&mut read_buffer, &mut write_buffer, true));
final_result.extend(write_buffer.take_read_buffer().take_remaining());
if let BufferResult::BufferUnderflow = result {
break;
}
}
Ok(final_result)
}
pub fn password_to_key(p: &str) -> Vec<u8> {
// yehh.... idk
let mut salt_sha = Sha256::new();
salt_sha.input(p.as_bytes());
let salt = salt_sha.result_str();
let mut mac = Hmac::new(Sha256::new(), p.as_bytes());
let mut key: Vec<u8> = repeat(0).take(32).collect();
pbkdf2(&mut mac, salt.as_bytes(), 2056, key.as_mut_slice());
key
}
|
extern crate dirs;
extern crate rusqlite;
use rusqlite::NO_PARAMS;
use rusqlite::{Connection, Error, Result};
#[path = "../constants/mod.rs"]
mod constants;
use constants::{DATABASE_FILE};
pub mod account;
static CREATE_PASSWORDS_TABLE_Q: &str = "create table if not exists passwords ( id integer primary key, account text not null, username text not null, password text not null, inserted_at text, updated_at text, unique (account, username))";
pub fn initialize() -> Result<Connection> {
let home = get_home_directory()?;
let conn = Connection::open(home + DATABASE_FILE)?;
conn.execute(CREATE_PASSWORDS_TABLE_Q, NO_PARAMS)?;
Ok(conn)
}
fn get_home_directory() -> Result<String> {
match dirs::home_dir() {
Some(home) => Ok(home.display().to_string()),
None => Err(Error::InvalidQuery),
}
}
#[derive(Debug)]
pub struct Account {
pub name: String,
pub username: String,
pub password: String,
}
|
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ExactTermType {
/// exact-match.
///
/// `'wild`: Items that include wild.
Exact,
/// prefix-exact-match
///
/// `^music`: Items that start with music.
PrefixExact,
/// suffix-exact-match
///
/// `.mp3$`: Items that end with .mp3
SuffixExact,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ExactTerm {
pub ty: ExactTermType,
pub word: String,
}
impl ExactTerm {
pub fn new(ty: ExactTermType, word: String) -> Self {
Self { ty, word }
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum InverseTermType {
/// inverse-exact-match
///
/// `!fire`: Items that do not include fire
InverseExact,
/// inverse-prefix-exact-match
///
/// `!^music`: Items that do not start with music
InversePrefixExact,
/// inverse-suffix-exact-match
///
/// `!.mp3$`: Items that do not end with .mp3
InverseSuffixExact,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct InverseTerm {
pub ty: InverseTermType,
pub word: String,
}
impl InverseTerm {
pub fn new(ty: InverseTermType, word: String) -> Self {
Self { ty, word }
}
/// Returns true if the full line of given `item` matches the inverse term.
pub fn match_full_line(&self, full_search_line: &str) -> bool {
let query = self.word.as_str();
let trimmed = full_search_line.trim();
match self.ty {
InverseTermType::InverseExact => trimmed.contains(query),
InverseTermType::InversePrefixExact => trimmed.starts_with(query),
InverseTermType::InverseSuffixExact => trimmed.ends_with(query),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum FuzzyTermType {
/// fuzzy-match.
///
/// `sbtrkt`: Items that match sbtrkt.
Fuzzy,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct FuzzyTerm {
pub ty: FuzzyTermType,
pub word: String,
}
impl FuzzyTerm {
pub fn new(ty: FuzzyTermType, word: String) -> Self {
Self { ty, word }
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum TermType {
/// Items that match in fuzzy.
Fuzzy(FuzzyTermType),
/// Items that match something.
Exact(ExactTermType),
/// Items that do not match something.
Inverse(InverseTermType),
}
impl TermType {
pub fn is_inverse(&self) -> bool {
matches!(self, Self::Inverse(_))
}
pub fn is_exact(&self) -> bool {
matches!(self, Self::Exact(_))
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SearchTerm {
pub ty: TermType,
pub word: String,
}
impl SearchTerm {
pub fn new(ty: TermType, word: String) -> Self {
Self { ty, word }
}
pub fn is_inverse_term(&self) -> bool {
self.ty.is_inverse()
}
pub fn is_exact_term(&self) -> bool {
self.ty.is_exact()
}
}
impl From<&str> for SearchTerm {
fn from(s: &str) -> Self {
let (ty, word) = if let Some(stripped) = s.strip_prefix('\'') {
(TermType::Exact(ExactTermType::Exact), stripped)
} else if let Some(stripped) = s.strip_prefix('^') {
(TermType::Exact(ExactTermType::PrefixExact), stripped)
} else if let Some(stripped) = s.strip_prefix('!') {
if let Some(double_stripped) = stripped.strip_prefix('^') {
(
TermType::Inverse(InverseTermType::InversePrefixExact),
double_stripped,
)
} else if let Some(double_stripped) = stripped.strip_suffix('$') {
(
TermType::Inverse(InverseTermType::InverseSuffixExact),
double_stripped,
)
} else {
(TermType::Inverse(InverseTermType::InverseExact), stripped)
}
} else if let Some(stripped) = s.strip_suffix('$') {
(TermType::Exact(ExactTermType::SuffixExact), stripped)
} else {
(TermType::Fuzzy(FuzzyTermType::Fuzzy), s)
};
Self {
ty,
word: word.into(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_term_should_work() {
use TermType::*;
let query = "aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$";
let terms = query.split_whitespace().map(Into::into).collect::<Vec<_>>();
let expected = vec![
SearchTerm::new(Fuzzy(FuzzyTermType::Fuzzy), "aaa".into()),
SearchTerm::new(Exact(ExactTermType::Exact), "bbb".into()),
SearchTerm::new(Exact(ExactTermType::PrefixExact), "ccc".into()),
SearchTerm::new(Exact(ExactTermType::SuffixExact), "ddd".into()),
SearchTerm::new(Inverse(InverseTermType::InverseExact), "eee".into()),
SearchTerm::new(Inverse(InverseTermType::InverseExact), "'fff".into()),
SearchTerm::new(Inverse(InverseTermType::InversePrefixExact), "ggg".into()),
SearchTerm::new(Inverse(InverseTermType::InverseSuffixExact), "hhh".into()),
];
for (expected, got) in expected.iter().zip(terms.iter()) {
assert_eq!(expected, got);
}
}
}
|
use std::env;
use std::path::PathBuf;
fn main() {
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap_or("".to_string()));
tonic_build::configure()
.file_descriptor_set_path(out_dir.join("chat_descriptor.bin"))
.compile(&["../proto/chat.proto"], &["../proto"])
.unwrap();
}
|
use std::env;
use clap::{App, SubCommand, Arg};
use kvs::{Result, KvError, KvStore};
use std::process::exit;
fn main() -> Result<()> {
let kvs_app = App::new("kvs")
.version(env!("CARGO_PKG_VERSION"))
.subcommand(
SubCommand::with_name("get")
.arg(Arg::with_name("<KEY>").help("ENTER A KEY").required(true))
)
.subcommand(
SubCommand::with_name("set")
.arg(Arg::with_name("<KEY>").help("ENTER A KEY").required(true))
.arg(Arg::with_name("<VALUE>").help("ENTER A VALUE").required(true))
)
.subcommand(
SubCommand::with_name("rm")
.arg(Arg::with_name("<KEY>").help("ENTER A KEY").required(true))
)
.get_matches();
match kvs_app.subcommand() {
("get", Some(matches)) => {
let k = matches.value_of("<KEY>").expect("<KEY> argument is missing");
let mut kv = KvStore::open(env::current_dir()?)?;
if let Some(v) = kv.get(k.to_owned())? {
println!("{}", v);
} else {
println!("Key not found");
}
},
("rm", Some(matches)) => {
let k = matches.value_of("<KEY>").expect("<KEY> argument is missing");
let mut kv = KvStore::open(env::current_dir()?)?;
match kv.remove(k.to_string()) {
Ok(()) => (),
Err(KvError::KeyNotFound) => {
println!("Key not found");
exit(1);
},
Err(e) => return Err(e),
}
}
("set", Some(matches)) => {
let k = matches.value_of("<KEY>").expect("<KEY> argument is missing");
let v = matches.value_of("<VALUE>").expect("<VALUE> argument is missing");
let mut kv = KvStore::open(env::current_dir()?)?;
kv.set(k.to_owned(), v.to_owned())?;
}
_ => unreachable!()
}
Ok(())
}
|
// 2019-04-05
// Les Closures permettent de... j'ai pas encore compris
// Nous sommes dans une salle de sport et l'utilisateur demande à l'algorithme de
// lui créer un programme d'entraînement. L'algorithme a deux arguments :
// l'intensité des efforts à fournir
// un nombre aléatoire pour amener de la variété dans le programme de sport
use std::thread;
use std::time::Duration;
fn main() {
// On skipe l'invite utilisateur et la génération du nombre aléatoire
// On les hardcode, arbitrairement
let simulated_user_specified_value = 10;
let simulated_random_number = 7;
generate_workout(
simulated_user_specified_value,
simulated_random_number,
)
}
// Cette fonction simule un temps de calcul de deux secondes
// Elle prends un nombre et renvoie exactement le même.
// Pourquoi intensity ? C'est un nombre rentré par l'utilisateur pour choisir
// la quantité d'efforts qu'il veut fournir à la salle de sport.
fn simulated_expensive_calculation(intensity: u32) -> u32 {
println!("On y passe du temps...");
thread::sleep(Duration::from_secs(2));
intensity
}
// Voici l'algorithme un peu bidon qui génère un programme de sport
// Il prend les deux arguments : l'intensité donnée par l'utilisateur, et
// un nombre aléatoire (les deux sont hardcoded de toute façon)
// On y appelle beaucoup la fonction qui simule un temps de calcul.
fn generate_workout(intensity: u32, random_number:u32) {
// Voici une closure !
// Son paramètre est rédigé entre des pipes verticales (|), comme dans Ruby
// Ensuite, des accolades pour le contenu (pas obligatoire si une seule
// déclaration). Comme dans une fonction, la dernière ligne renvoie une
// valeur.
// ATTENTION ! cet 'expensive_closure' ne continue pas la valeur retour,
// mais contient la DÉFINITION de cette fonction anonyme.
// La closure permet de stocker du code et de s'en servir ailleurs ;-)
// let expensive_closure = |num| {
// println!("On y passe du temps...");
// thread::sleep(Duration::from_secs(2));
// num
// };
// On POURRAIT indiquer les type de donnée ainsi :
// let expensive_closure = |num: u32| -> u32 {}
// mais ça serait redondant, le compilateur ne l'exige pas. Il infère.
// Mais on ne pourra pas utiliser une même closure avec des types différents
// Créons une instance du struct Cacher avec sa méthode new(), qui prend en
// argument une closure que nous définissons ici et qui a pour but principal
// de mettre le thread sur pause
let mut expensive_result = Cacher::new(|num| {
println!("On y passe du temps...");
thread::sleep(Duration::from_secs(2));
num
});
if intensity < 25 {
println!(
"Aujourd'hui, faites {} pompes !",
// Ceci appelle la fonction value() qui prend intensity comme argument
// Cette fonction est logée dans le struct Cacher, dont expensive_result
// est une instance
expensive_result.value(intensity)
);
println!(
"Ensuite, faites {} tractions !",
// On appelle cette fonction une deuxième fois, et comme la valeur
// existe déjà, on n'a pas besoin d'attendre les deux secondes
expensive_result.value(intensity)
);
} else {
if random_number == 3 {
println!("Faites une pause aujourd'hui ! Restez hydraté !");
} else {
println!(
"Aujourd'hui, courrez {} minutes !",
expensive_result.value(intensity)
);
}
}
}
// We can create a struct that will hold
// the closure
// and the the resulting value of calling the closure
// Le struct exécutera la closure (fermeture) seulement si on a besoin de la
// valeur retour, et il la CACHERA au reste du code, qui n'en sera pas
// responsable.
// Ce struct va gérer lui-même ses valeurs, qui peuvent rester privées.
struct Cacher<T>
// T est une CLOSURE qui doit implémenter le TRAIT Fn(u32) -> u32
where T: Fn(u32) -> u32
{
calculation: T, // la closure elle-même
value: Option<u32>, // la valeur qui sera produite par la closure
}
impl<T> Cacher<T>
where T: Fn(u32) -> u32
{
// cette fonction new() crée une instance du struct Cacher
// Elle prend en argument une closure
// Et retourne une instance de Cacher qui contient la closure et un None
fn new(calculation: T) -> Cacher<T> {
Cacher {
calculation, // cette variable est une closure !
value: None,
}
}
// Cette fonction value() doit renvoyer une valeur
fn value(&mut self, arg: u32) -> u32 {
// Elle vérifie ce que contient le champ 'value'
match self.value {
// S'il contient une valeur, on la renvoie
Some(v) => v,
// Et en cas de None,
None => {
// on exécute la fermeture (closure) 'calculation' contenue
// dans le struct, avec comme le même argument que la fonction
let v = (self.calculation)(arg);
// On attribue cette valeur au champ 'value' du struct
self.value = Some(v);
// on retourne cette valeur
v
}
}
}
}
|
#[macro_use]
extern crate log;
mod lexer;
mod parser;
use lexer::Token;
fn main() {
let string = "(add 2 (subtract 4 2))";
let tokens: Vec<Token> = lexer::tokenizer(string);
println!("Tokens: {:?}", tokens);
}
|
/*
Copyright (c) 2023 Uber Technologies, Inc.
<p>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
<p>http://www.apache.org/licenses/LICENSE-2.0
<p>Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language governing permissions and
limitations under the License.
*/
use std::collections::HashMap;
use crate::models::{
capture_group_patterns::CGPattern, filter::FilterBuilder, rule_graph::RuleGraphBuilder,
};
use crate::{edges, piranha_rule};
#[test]
#[should_panic(
expected = "Invalid Filter Argument. `at_least` or `at_most` is set, but `contains` is empty !!!"
)]
fn test_filter_bad_arg_at_least() {
FilterBuilder::default().at_least(2).build();
}
#[test]
#[should_panic(
expected = "Invalid Filter Argument. `at_least` or `at_most` is set, but `contains` is empty !!!"
)]
fn test_filter_bad_arg_at_most() {
FilterBuilder::default().at_least(5).build();
}
#[test]
#[should_panic(
expected = "Invalid Filter Argument. `contains` and `not_contains` cannot be set at the same time !!! Please use two filters instead."
)]
fn test_filter_bad_arguments_contains_not_contains() {
FilterBuilder::default()
.contains(CGPattern::new(String::from("(if_statement) @if_stmt")))
.not_contains(vec![CGPattern::new(String::from("(for_statement) @for"))])
.build();
}
#[test]
#[should_panic(
expected = "Invalid Filter Argument. `at_least` should be less than or equal to `at_most` !!!"
)]
fn test_filter_bad_range() {
FilterBuilder::default()
.contains(CGPattern::new(String::from("(if_statement) @if_stmt")))
.at_least(5)
.at_most(4)
.build();
}
#[test]
#[should_panic(expected = "Cannot parse")]
fn test_filter_syntactically_incorrect_contains() {
FilterBuilder::default()
.contains(CGPattern::new(String::from("(if_statement @if_stmt")))
.build();
}
#[test]
#[should_panic(expected = "Cannot parse")]
fn test_filter_syntactically_incorrect_not_contains() {
FilterBuilder::default()
.not_contains(vec![CGPattern::new(String::from("(if_statement @if_stmt"))])
.build();
}
#[test]
#[should_panic(expected = "Cannot parse")]
fn test_filter_syntactically_incorrect_enclosing_node() {
FilterBuilder::default()
.enclosing_node(CGPattern::new(String::from("(if_statement @if_stmt")))
.build();
}
#[test]
#[should_panic(expected = "Cannot parse")]
fn test_filter_syntactically_incorrect_not_enclosing_node() {
FilterBuilder::default()
.not_enclosing_node(CGPattern::new(String::from("(if_statement @if_stmt")))
.build();
}
#[test]
#[should_panic(expected = "Cannot parse")]
fn test_rule_graph_incorrect_query() {
RuleGraphBuilder::default()
.rules(vec![
piranha_rule! {name = "Test rule", query = "(if_statement"},
])
.build();
}
#[test]
#[should_panic(
expected = "The child/sibling count operator is not compatible with (not) enclosing node and (not) contains operator"
)]
fn test_filter_bad_arg_contains_n_children() {
FilterBuilder::default()
.enclosing_node(CGPattern::new("(method_declaration) @i".to_string()))
.child_count(2)
.build();
}
#[test]
#[should_panic(
expected = "The child/sibling count operator is not compatible with (not) enclosing node and (not) contains operator"
)]
fn test_filter_bad_arg_contains_n_sibling() {
FilterBuilder::default()
.enclosing_node(CGPattern::new("(method_declaration) @i".to_string()))
.sibling_count(2)
.build();
}
#[test]
fn test_df_warnings() {
let rule_graph = RuleGraphBuilder::default()
.rules(vec![
piranha_rule! {name = "Test rule", query = "(local_variable_declaration
(variable_declarator name: (_) @name ) @i)"},
piranha_rule! {name = "Other rule", query = "((local_variable_declaration
type: (_) @other_type
(variable_declarator name: (_) @other_name ) @other_i)
(#eq? @other_type @type)
(#neq? @other_name @name))", is_seed_rule = false},
]).edges(vec![edges! {from = "Test rule", to = ["Other rule"], scope = "Method"}])
.build();
let empty_substitution: HashMap<String, String> = HashMap::new();
let warnings = rule_graph.analyze(&empty_substitution);
assert_eq!(warnings.len(), 1);
}
#[test]
fn test_quoted_predicates() {
let rule_graph = RuleGraphBuilder::default()
.rules(vec![piranha_rule! {name = "Test rule", query = "(
(local_variable_declaration
(variable_declarator name: (_) @name) @i)
(#eq? @name \"\"@stale_flag_name\"\"))"}])
.edges(vec![])
.build();
let mut substitutions: HashMap<String, String> = HashMap::new();
substitutions.insert("stale_flag_name".to_string(), "some_value".to_string());
let warnings = rule_graph.analyze(&substitutions);
assert_eq!(warnings.len(), 0);
}
|
#![no_std]
#![feature(start)]
#![no_main]
use ferr_os_librust::io;
extern crate alloc;
use alloc::vec::Vec;
use alloc::{format, string::String};
#[no_mangle]
pub extern "C" fn _start(heap_address: u64, heap_size: u64, args: u64, args_number: u64) {
ferr_os_librust::allocator::init(heap_address, heap_size);
let arguments = ferr_os_librust::env::retrieve_arguments(args_number, args);
main(arguments);
}
#[inline(never)]
fn main(args: Vec<String>) {
match args.get(1) {
None => print_loop(),
Some(s_1) => unsafe { main_loop(s_1) },
}
}
fn print_loop() {
loop {
let res = io::read_to_string(io::STD_IN, 512);
io::_print(&res);
}
}
unsafe fn main_loop(pattern: &String) {
let mut line = 0;
let mut remaining = String::new();
loop {
let mut inc = String::new();
inc.push_str(&remaining);
inc.push_str(&io::read_to_string(io::STD_IN, 512));
remaining.clear();
let mut splitted = inc.split('\n').collect::<Vec<&str>>();
if splitted.len() > 0 {
remaining.push_str(&splitted.pop().expect("Could not chop off truc"));
}
for s in splitted.iter() {
if s.contains(pattern) {
let mut res = format!("{}: ", line);
res.push_str(s);
res.push('\n');
io::_print(&res);
}
line += 1;
}
}
} |
extern crate cuticula;
extern crate modifier;
#[cfg(test)]
mod image_spec {
use cuticula::{ Set, Transformer, Image };
use cuticula::image::{ Resize, Crop };
use std::path::Path;
fn expected_result() -> Vec<u32> {
vec![255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0]
}
// Additional Alpha Channel for GIF
fn expected_result_gif() -> Vec<u32> {
vec![255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0]
}
fn expected_result_resize() -> Vec<u32> { vec![191, 191, 191] }
fn expected_result_crop() -> Vec<u32> { vec![255, 255, 255] }
#[test]
fn it_works_for_png() {
let path = Path::new("tests/assets/test_image.png");
let img = Image::from_path(&path);
assert_eq!(expected_result(), img.transform(1).unwrap());
}
#[test]
#[should_panic]
fn it_works_not_for_progressive_jpeg() {
let path = Path::new("tests/assets/test_image.jpeg");
let img = Image::from_path(&path);
assert_eq!(expected_result(), img.transform(1).unwrap());
}
#[test]
fn it_works_for_baseline_jpeg() {
let path = Path::new("tests/assets/test_image.baseline.jpeg");
let img = Image::from_path(&path);
assert_eq!(expected_result(), img.transform(1).unwrap());
}
#[test]
fn it_works_for_gif() {
let path = Path::new("tests/assets/test_image.gif");
let img = Image::from_path(&path);
assert_eq!(expected_result_gif(), img.transform(1).unwrap());
}
#[test]
fn it_works_for_bmp() {
let path = Path::new("tests/assets/test_image.bmp");
let img = Image::from_path(&path);
assert_eq!(expected_result(), img.transform(1).unwrap());
}
#[test]
fn it_works_to_resize() {
let path = Path::new("tests/assets/test_image.png");
let mut img = Image::from_path(&path);
let resize = Resize { width: 1, height: 1 };
img = img.set(resize);
assert_eq!(expected_result_resize(), img.transform(1).unwrap());
}
#[test]
fn it_works_to_crop() {
let path = Path::new("tests/assets/test_image.png");
let mut img = Image::from_path(&path);
let crop = Crop { x: 0, y: 0, width: 1, height: 1 };
img = img.set(crop);
assert_eq!(expected_result_crop(), img.transform(1).unwrap());
}
}
|
fn main() {
let mut fd = libc::pollfd{fd: 0, events: 0, revents: 0};
loop {
let _ = unsafe{libc::poll(&mut fd, 1, -1)};
}
}
|
#![warn(missing_docs)]
use super::ops::tee::TEE;
use super::ops::union::UNION;
use super::{GraphNodeId, HydroflowGraph};
fn find_unary_ops<'a>(
graph: &'a HydroflowGraph,
op_name: &'static str,
) -> impl 'a + Iterator<Item = GraphNodeId> {
graph
.node_ids()
.filter(move |&node_id| {
graph
.node_op_inst(node_id)
.map_or(false, |op_inst| op_name == op_inst.op_constraints.name)
})
.filter(|&node_id| {
1 == graph.node_degree_in(node_id) && 1 == graph.node_degree_out(node_id)
})
}
/// Removes missing unions and tees. Must be applied BEFORE subgraph partitioning.
pub fn eliminate_extra_unions_tees(graph: &mut HydroflowGraph) {
let extra_ops = find_unary_ops(graph, UNION.name)
.chain(find_unary_ops(graph, TEE.name))
.collect::<Vec<_>>();
for extra_op in extra_ops {
graph.remove_intermediate_node(extra_op);
}
}
|
use crate::ram::Ram;
use std::fmt;
pub const PROGRAM_START: u16 = 0x200;
pub struct Cpu {
vx: [u8; 16],
pc: u16,
i: u16,
prev_pc: u16,
stack: Vec<u16>,
}
impl Cpu {
pub fn new() -> Cpu {
Cpu {
vx: [0; 16],
pc: PROGRAM_START,
i: 0,
prev_pc: 0,
stack: Vec::<u16>::new(),
}
}
pub fn run_instruction(&mut self, ram: &mut Ram) {
let hi = ram.read_byte(self.pc) as u16;
let lo = ram.read_byte(self.pc + 1) as u16;
let opcode: u16 = (hi << 8) | lo;
println!("instruction read:{:#X} hi:{:#X} lo:{:#X}", opcode, hi, lo);
let nnn = opcode & 0x0FFF;
let nn = (opcode & 0x0FF) as u8;
let n = (opcode & 0x00F) as u8;
let x = ((opcode & 0x0F00) >> 8) as u8;
let y = ((opcode & 0x00F0) >> 4) as u8;
println!(
"nnn: {:?}, nn: {:?}, n: {:?}, x: {}, y: {}",
nnn, nn, n, x, y
);
if self.prev_pc == self.pc {
panic!("Please increment PC!");
}
self.prev_pc = self.pc;
match (opcode & 0xF000) >> 12 {
0x1 => {
// GOTO NNN
self.pc = nnn;
}
0x2 => {
self.stack.push(nnn);
self.pc = nnn;
}
0x3 => {
let vx = self.read_reg_vx(x);
if vx == nn {
self.pc += 4;
} else {
self.pc += 2;
}
}
0x6 => {
// SET VX to NN
self.write_reg_vx(x, nn);
self.pc += 2;
}
0x7 => {
// add nn to vx
let vx = self.read_reg_vx(x);
self.write_reg_vx(x, vx.wrapping_add(nn));
self.pc += 2;
}
0x8 => {
match n {
0 => {
let mut v= self.read_reg_vx(x);
vx = self.write_reg_vx(x, y);
}
_ => panic!("Instruction inconnue {:#X}:{:#X}", self.pc, opcode),
}
}
0xA => {
// SET I TO NNN
self.i = nnn;
self.pc += 2;
}
0xD => {
// Drawing sprite draw(vx,vy,n)
self.debug_draw_sprite(ram, x, y, n);
self.pc += 2;
}
0xF => {
let vx = self.read_reg_vx(x);
self.i += vx as u16;
self.pc += 2;
}
_ => panic!("Instruction inconnue {:#X}:{:#X}", self.pc, opcode),
}
}
fn debug_draw_sprite(&self, ram: &mut Ram, x: u8, y: u8, height: u8) {
println!("Draw a sprite at x:{:?} y:{:?}", x, y);
for y in 0..height {
let mut b = ram.read_byte(self.i + y as u16);
for _ in 0..8 {
match (b & 0b1000_0000) >> 7 {
0 => print!("_"),
1 => print!("#"),
_ => unreachable!()
}
b = b << 1;
}
print!("\n")
}
print!("\n")
}
pub fn write_reg_vx(&mut self, index: u8, value: u8) {
self.vx[index as usize] = value;
}
pub fn read_reg_vx(&mut self, index: u8) -> u8 {
self.vx[index as usize]
}
}
impl fmt::Debug for Cpu {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\n pc: {:#X}\n", self.pc);
write!(f, " vx: ");
for item in self.vx.iter() {
write!(f, "{:#X} ", *item);
}
write!(f, "\n");
write!(f, " i: {:#X}", self.i)
}
}
|
extern crate xml;
use crate::component2::{Component};
use std::io::BufWriter;
use xml::{EventReader, EventWriter, EmitterConfig, reader::XmlEvent, writer::events::XmlEvent as XmlEventW};
use std::error::Error;
fn props_from_xml(parser: &mut XMLParser) -> Result<(String, String), Box<Error>> {
let start_tag = parser.next().ok_or("bad props")?;
let body = parser.next().ok_or("bad props")?;
let end_tag = parser.next().ok_or("bad props")?;
let mut name = String::new();
let mut val = String::new();
match start_tag? {
XmlEvent::StartElement {name: _, attributes: attr, namespace: _} => {
name += attr.iter().find(|x| x.name.local_name == "name").map(|on| &on.value[..]).ok_or("no name on props")?;
},
_ => { return Err("bad props".into()); }
};
match body? {
XmlEvent::Characters(c) => {
val += &c[..];
},
_ => { return Err("bad props".into()); }
}
match end_tag? {
XmlEvent::EndElement {name: n} => {
if &n.local_name[..] != "property" { return Err("bad props".into()); }
},
_ => { return Err("bad props".into()); }
}
Ok((name, val))
}
type XMLParser<'a> = std::iter::Peekable<xml::reader::Events<&'a[u8]>>;
impl Component {
fn from_xml(parser: &mut XMLParser) -> Result<Component, Box<Error>> {
let mut c = Component::empty();
while let Some(e) = parser.peek().map(|x| x.clone()) {
match e? {
XmlEvent::StartElement {name: n, attributes: attr, namespace: _} => {
match &n.local_name[..] {
"object" => {
c.class = attr.iter().find(|x| x.name.local_name == "class").map(|on| on.value.clone()).unwrap_or("".to_string());
c.id = attr.iter().find(|x| x.name.local_name == "id").map(|on| on.value.clone()).unwrap_or("".to_string());
},
"property" => {
let p = props_from_xml(parser)?;
c.properties.insert(p.0, p.1);
},
"child" => {
parser.next();
let child = Component::from_xml(parser)?;
c.children.v.push(child.id.clone());
c.children.m.insert(child.id.clone(), child);
}
_ => {}
};
},
XmlEvent::EndElement {name: n} => {
if &n.local_name[..] == "object" {
return Ok(c);
}
}
_ => {}
}
parser.next();
}
Ok(c)
}
pub fn from_xml_string(xml_str: &str) -> Result<Component, Box<Error>> {
let rdr = EventReader::from_str(xml_str);
let mut parser = rdr.into_iter().peekable();
let mut c = Component::empty();
while let Some(tag) = parser.peek().map(|x| x.clone()) {
match tag? {
XmlEvent::StartElement {name: n, attributes: _, namespace: _} => {
match &n.local_name[..] {
"object" => {
c = Component::from_xml(&mut parser)?;
},
_ => {}
};
},
XmlEvent::EndElement {name: _} => {},
_ => {}
}
parser.next();
}
Ok(c)
}
fn to_xml(&self, wtr: &mut EventWriter<BufWriter<Vec<u8>>>) -> Result<(), Box<Error>> {
let start = XmlEventW::start_element("object").attr("id", &self.id[..]).attr("class", &self.class[..]);
wtr.write(start)?;
for (k,v) in self.properties.iter() {
wtr.write(XmlEventW::start_element("property").attr("name", &k[..]))?;
wtr.write(XmlEventW::characters(&v[..]))?;
wtr.write(XmlEventW::end_element())?;
};
for child_id in self.children.v.iter() {
wtr.write(XmlEventW::start_element("child"))?;
self.children.m[child_id].to_xml(wtr)?;
wtr.write(XmlEventW::end_element())?;
}
wtr.write(XmlEventW::end_element())?;
Ok(())
}
pub fn to_xml_string(&self) -> Result<String, Box<Error>> {
let buf: Vec<u8> = Vec::new();
let config = EmitterConfig { write_document_declaration: false, perform_indent: true, ..EmitterConfig::new() };
let mut wtr = EventWriter::new_with_config(BufWriter::new(buf), config);
wtr.write(XmlEventW::start_element("interface"))?;
self.to_xml(&mut wtr)?;
wtr.write(XmlEventW::end_element())?;
String::from_utf8(wtr.into_inner().into_inner()?).map_err(|e| e.into())
}
}
|
use crate::ast::expressions::{self, primitives, statements, tables, variables};
use crate::ast::stack;
use crate::interpreter::cache;
use std::collections::VecDeque;
use std::rc::Rc;
use std::cell::RefCell;
#[derive(Debug)]
pub struct Closure {
pub params: VecDeque<Box<dyn expressions::Expression>>,
pub varargs: bool,
pub body: Rc<Box<dyn expressions::Expression>>,
}
impl expressions::Expression for Closure {}
/// Closure expression.
/// Note: Our parameter parser already remove braces and in case we have no parameters, pushed empty
/// namelist and Nona as vargargs on top of stask, so we just need to pick them up.
impl Closure {
// ‘(’ [parlist] ‘)’ block end
pub fn new(stack: &mut stack::Stack) {
// We've remove braces before
let (_end, body, ellipsis, params, _function) =
stack_unpack!(stack, single, single, optional, repetition, single);
stack.push_single(Box::new(Closure {
params,
varargs: ellipsis.is_some(),
body: Rc::new(body),
}));
}
}
#[derive(Debug)]
pub struct Function;
/// Function, which is basically an assignment of a closure to a name.
/// Also performs rearrangment of parameters and method name if it's a method.
impl Function {
pub fn new(stack: &mut stack::Stack) {
// This looks like a lot of terminals, but we need them to desugar method
let (_end, body, ellipsis, mut params, methodname, mut object, _function) =
stack_unpack!(stack, single, single, optional, repetition, optional, single, single);
// Check if have method name. If so, we make another indexing and add `self` argument
if let Some(method) = methodname {
// Function name
object = Box::new(tables::Indexing {
object,
index: method,
cache: RefCell::new(cache::Cache::default()),
});
// Prepend `self` parameter to the parameters
params.push_front(Box::new(primitives::String("self".to_string())));
}
let closure = Box::new(Closure {
params,
varargs: ellipsis.is_some(),
body: Rc::new(body),
}) as Box<dyn expressions::Expression>;
stack.push_single(Box::new(variables::Assignment {
varlist: vec![object].into(),
explist: vec![closure].into(),
}));
}
}
#[derive(Debug)]
pub struct FunctionParameters;
impl FunctionParameters {
/// Each new name in parameters list will append itself to the parameters list
pub fn new_name(stack: &mut stack::Stack) {
let (name, _comma, mut namelist) = stack_unpack!(stack, single, single, repetition);
namelist.push_back(name);
stack.push_repetition(namelist);
}
/// This is ellipsis after varargs. Accoridng to grammar we can get here in two ways:
/// - after namelist;
/// - after another ellipsis.
/// Second one is invalid. So we check if we have repetitions on top. And later construct parameters itself.
pub fn new_namelist_varargs(stack: &mut stack::Stack) {
// Pop ellipsis and comma
let (_ellipsis, _comma) = stack_unpack!(stack, single, single);
let namelist = stack.pop_repetition();
FunctionParameters::finalize_parameters_parsing(stack, namelist, true);
}
/// Final namelist function. We either had namelist or namelist followed by ellipsis.VecDeque
/// In case of ellipsis, we already have proper expression on stack. In case we have namelist on stack,
/// we create new function parameters object.
pub fn new_namelist(stack: &mut stack::Stack) {
// This is in case we had only namelist
if let stack::Element::Repetition(_) = stack.peek() {
let namelist = stack.pop_repetition();
FunctionParameters::finalize_parameters_parsing(stack, namelist, false);
}
// Otherwise we already had ellipsis after namelist, which properly created parameters. Ignore
}
pub fn new_single_varargs(stack: &mut stack::Stack) {
// Ellipsis
stack.pop_single();
FunctionParameters::finalize_parameters_parsing(stack, VecDeque::new(), true);
}
/// Helper function to push parameters and indicator of varargs
/// After method execution, stack will contains parameters list and optional ellipsis expression
fn finalize_parameters_parsing(
stack: &mut stack::Stack,
namelist: VecDeque<Box<dyn expressions::Expression>>,
varargs: bool,
) {
stack.push_repetition(namelist);
stack.push_optional(if varargs {
Some(Box::new(statements::Statement::Ellipsis))
} else {
None
});
}
}
#[derive(Debug)]
pub struct Funcall {
pub object: Box<dyn expressions::Expression>,
pub args: VecDeque<Box<dyn expressions::Expression>>,
pub method: Option<Box<dyn expressions::Expression>>,
}
impl expressions::Expression for Funcall {}
impl Funcall {
pub fn new(stack: &mut stack::Stack) {
let (args, object) = stack_unpack!(stack, repetition, single);
stack.push_single(Box::new(Funcall {
object,
args,
method: None,
}))
}
pub fn new_self(stack: &mut stack::Stack) {
let (args, method, _colon, object) =
stack_unpack!(stack, repetition, single, single, single);
stack.push_single(Box::new(Funcall {
object,
args,
method: Some(method),
}))
}
pub fn new_args(stack: &mut stack::Stack) {
let _rbrace = stack.pop_single();
if let stack::Element::Repetition(_) = stack.peek() {
// Had some args
let (arguments, _lbrace) = stack_unpack!(stack, repetition, single);
stack.push_repetition(arguments);
} else {
// No args. Push empty vec
let _lbrace = stack.pop_single();
stack.push_repetition(VecDeque::new());
}
}
}
|
use std::env;
use std::fs;
use std::path::Path;
use std::collections::HashMap;
#[derive(Copy,Clone,Debug)]
struct AuntSue<'a>{
id:i32,
prop:& 'a str,
count:i32
}
fn read_sue_list(filename:&str)->String{
let fpath = Path::new(filename);
let abspath = env::current_dir()
.unwrap()
.into_boxed_path()
.join(fpath);
let sues = fs::read_to_string(abspath)
.expect("Error reading list!");
return sues;
}
fn make_ticker_tape<'a>()->HashMap<& 'a str,i32>{
let mut ticker_tape:HashMap<&str,i32> = HashMap::new();
ticker_tape.insert("children", 3);
ticker_tape.insert("cats", 7);
ticker_tape.insert("samoyeds", 2);
ticker_tape.insert("pomeranians", 3);
ticker_tape.insert("akitas", 0);
ticker_tape.insert("vizslas", 0);
ticker_tape.insert("goldfish", 5);
ticker_tape.insert("trees", 3);
ticker_tape.insert("cars", 2);
ticker_tape.insert("perfumes", 1);
return ticker_tape;
}
fn make_sue_list(sues:&str) ->HashMap<i32,Vec<AuntSue>>{
let mut aunt_sues:HashMap<i32,Vec<AuntSue>>=HashMap::new();
for sue in sues.lines(){
let props:Vec<&str> = sue.split(|c:char| !c.is_alphanumeric())
.filter(|&x| !x.is_empty())
.collect();
for i in 1..props.len(){
match props[i].parse::<i32>(){
Ok(_) => continue,
Err(_) => {
let sue_id = props[1].parse::<i32>().unwrap();
let prop_count =props[i+1].parse::<i32>().unwrap();
if !aunt_sues.contains_key(&sue_id) {
aunt_sues.insert(sue_id, Vec::new());
}
let new_aunt = AuntSue{
id:sue_id,
prop:props[i],
count:prop_count
};
aunt_sues.get_mut(&sue_id).unwrap().push(new_aunt);
}
}
}
}
return aunt_sues;
}
fn find_matching_sue(aunt_sues:HashMap<i32,Vec<AuntSue>> , ticker_tape:HashMap<&str,i32>, is_outdated:bool)->i32{
let (mut last_index, mut match_id) = (0,0);
for (i,props) in &aunt_sues{
let mut match_index = 0;
for prop in props.iter(){
if is_outdated{
if *ticker_tape.get(&prop.prop).unwrap() == prop.count{
match_index+=1;
}
continue;
}
match prop.prop{
"trees" | "cats" => {
if *ticker_tape.get(&prop.prop).unwrap() < prop.count{
match_index+=1;
}
},
"pomeranians" | "goldfish" => {
if *ticker_tape.get(&prop.prop).unwrap() > prop.count{
match_index+=1;
}
},
_ => {
if *ticker_tape.get(&prop.prop).unwrap() == prop.count{
match_index+=1;
}
}
}
}
if last_index < match_index{
last_index=match_index;
match_id= *i;
//println!("{} {} {}", match_index, last_index, match_id);
}
}
return match_id;
}
pub fn run(){
let sues = read_sue_list("inputs/day-16.txt");
let ticker_tape = make_ticker_tape();
let aunts = make_sue_list(&sues);
let aunt_sue = find_matching_sue(aunts.clone(), ticker_tape.clone(),true);
let real_aunt_sue = find_matching_sue(aunts.clone(), ticker_tape.clone(),false);
println!("\n-- Day 16: Aunt Sue --");
println!("\n👩\tAunt Sue: {0:<39} \n\n🙋♀️\tReal Aunt Sue: {1:<34}\n", aunt_sue,real_aunt_sue);
println!("\n-- DONE --\n");
} |
#![allow(dead_code, unused_imports, unused_variables)]
use std::collections::{HashMap,HashSet};
const DATA: &'static str = include_str!("../../../data/06");
fn main() {
let points: Vec<(isize, isize)> = DATA
.lines()
.map(|line| line.split(", ").map(|n| n.parse::<isize>().unwrap()))
.map(|mut line| (line.next().unwrap(), line.next().unwrap()))
.collect();
println!("Part 01: {}", part1(&points));
println!("Part 02: {}", part2(&points));
}
fn part1(points: &Vec<(isize, isize)>) -> usize {
let mut areas = points.iter().fold(HashMap::new(), |mut acc, xy| {
acc.insert(*xy, 0);
acc
});
let ((min_x, max_x), (min_y, max_y)) = bounds(&points, 2);
let mut infinites = HashSet::<(isize, isize)>::new();
for x in min_x..=max_x {
for y in min_x..=max_y {
let mut min_distance = 10_000;
let mut closest = None;
for &(a, b) in areas.keys() {
let distance = (a - x).abs() + (b - y).abs();
if distance <= min_distance {
min_distance = distance;
closest = Some((a, b))
} else if distance == min_distance {
closest = None;
}
}
if let Some(coords) = closest {
*areas.entry(coords).or_insert(0) += 1;
if x == min_x || x == max_x || y == min_y || y == max_x {
infinites.insert(coords);
}
}
}
}
let max = areas
.iter()
.filter(|area| !infinites.contains(&area.0))
.max_by_key(|&(a, b)| b);
*max.unwrap().1
}
fn part2(input: &Vec<(isize, isize)>) -> usize {
let ((min_x, max_x), (min_y, max_y)) = bounds(input, 2);
let limit = 10_000;
let mut count = 0;
for x in min_x..=max_x {
for y in min_y..=max_y {
let total_distance: isize = input
.iter()
.map(|(a, b)| (a - x).abs() + (b - y).abs())
.sum();
if total_distance < limit {
count += 1;
}
}
}
count
}
fn bounds(points: &Vec<(isize, isize)>, margin: isize) -> ((isize, isize), (isize, isize)) {
let min_x = *points.iter().map(|(x, _)| x).min().unwrap();
let max_x = *points.iter().map(|(x, _)| x).max().unwrap();
let min_y = *points.iter().map(|(_, y)| y).min().unwrap();
let max_y = *points.iter().map(|(_, y)| y).max().unwrap();
((min_x - margin, max_x + margin), (min_y - margin, max_y + margin))
}
|
use super::{Backend, Component, Frame, State};
use tui::{
layout::Rect,
style::{Color, Style},
widgets::{Block, Borders, List, ListItem},
};
pub struct FormulaeList;
impl Component for FormulaeList {
fn render_to(frame: &mut Frame<Backend>, layout: Rect, state: &mut State) {
let packages_list = List::new(
state
.formulae
.iter()
.map(|formula| {
let symbol = if state.is_formula_selected(&formula.name) {
"✓"
} else {
"-"
};
ListItem::new(format!("{} {}", symbol, formula.name))
})
.collect::<Vec<_>>(),
)
.highlight_style(
Style::default()
.bg(Color::Blue)
.fg(Color::Rgb(255, 255, 255)),
)
.block(
Block::default()
.title(format!("Formulae({}) [↑↓]", state.formulae.len()))
.borders(Borders::ALL),
);
frame.render_stateful_widget(packages_list, layout, &mut state.selected_formula);
}
}
|
pub mod ppu;
pub mod screen;
|
use crate::{WIDTH, HEIGHT, VF, Chip8};
use crate::screen::{Point, Buffer, Screen};
use rand::{Rng, rngs::ThreadRng};
/// (0nnn - SYS addr)
/// Jump to a machine code routine at nnn.
///
/// This instruction is only used on the old computers on which Chip-8 was originally implemented.
/// It is ignored by modern interpreters.
pub fn sys_jump_to_routine(chip8: &mut Chip8, opcode: u16) {
}
/// (00E0 - CLS)
/// Clear the display.
pub fn cls_clear_display(chip8: &mut Chip8, _opcode: u16) {
println!("Clear display");
chip8.display.clear();
}
/// (00EE - RET)
/// Return from a subroutine.
///
/// The interpreter sets the program counter to the address at the top of the stack, then
/// subtracts 1 from the stack pointer.
pub fn ret_return_from_subroutine(chip8: &mut Chip8, _opcode: u16) {
chip8.pc = chip8.stack[chip8.sp as usize];
chip8.sp -= 1;
}
/// (1nnn - JP addr)
/// Jump to location nnn.
///
/// The interpreter sets the program counter to nnn.
pub fn jp_jump_to_address(chip8: &mut Chip8, opcode: u16) {
chip8.pc = opcode & 0x0FFF;
println!("Jump to location {:#X?}", chip8.pc);
}
/// (2nnn - CALL addr)
/// Call subroutine at nnn.
///
/// The interpreter increments the stack pointer, then puts the current PC on the top of
/// the stack. The PC is then set to nnn.
pub fn call_subroutine(chip8: &mut Chip8, opcode: u16) {
let subroutine = opcode & 0x0FFF;
println!("Add pc {:#X?} to stack, run subroutine at {:#X?}",
chip8.pc, subroutine);
chip8.sp += 1;
chip8.stack[chip8.sp as usize] = chip8.pc;
chip8.pc = subroutine;
}
/// (3xkk - SE Vx, byte)
/// Skip next instruction if Vx = kk.
///
/// The interpreter compares register Vx to kk, and if they are equal, increments the program
/// counter by 2.
pub fn se_register_byte(chip8: &mut Chip8, opcode: u16) {
let v_x = decode_register_x(opcode) as usize;
let kk = decode_byte(opcode);
let x = chip8.registers[v_x];
if x == kk {
chip8.pc += 2;
}
}
/// (4xkk - SNE Vx, byte)
/// Skip next instruction if Vx != kk.
///
/// The interpreter compares register Vx to kk, and if they are not equal, increments
/// the program counter by 2.
pub fn sne_skip_not_equal(chip8: &mut Chip8, opcode: u16) {
let v_x = decode_register_x(opcode) as usize;
let kk = decode_byte(opcode);
let x = chip8.registers[v_x];
if x != kk {
chip8.pc += 2;
}
}
/// (5xy0 - SE Vx, Vy)
/// Skip next instruction if Vx = Vy.
///
/// The interpreter compares register Vx to register Vy, and if they are equal,
/// increments the program counter by 2.
pub fn se_registers(chip8: &mut Chip8, opcode: u16) {
let (v_x, v_y) = decode_registers(opcode);
let x = chip8.registers[v_x as usize];
let y = chip8.registers[v_y as usize];
if x == y {
chip8.pc += 2;
}
}
/// (6xkk - LD Vx, byte)
/// Set Vx = kk.
///
/// The interpreter puts the value kk into register Vx.
pub fn ld_register_byte(chip8: &mut Chip8, opcode: u16) {
let v_x = decode_register_x(opcode) as usize;
let kk = decode_byte(opcode);
println!("Setting register V{:X?} to {:#X?}", v_x, kk);
chip8.registers[v_x] = kk;
}
/// (7xkk - ADD Vx, byte)
/// Set Vx = Vx + kk.
///
/// Adds the value kk to the value of register Vx, then stores the result in Vx.
pub fn add_register_byte(chip8: &mut Chip8, opcode: u16) {
let v_x = decode_register_x(opcode) as usize;
let kk = decode_byte(opcode);
let value = chip8.registers[v_x];
println!("Adding value {:#X?} to V{:X?} ({:#X?})", kk, v_x, value);
chip8.registers[v_x] = value.wrapping_add(kk);
}
/// (8xy0 - LD Vx, Vy)
/// Set Vx = Vy.
///
/// Stores the value of register Vy in register Vx.
pub fn ld_registers(chip8: &mut Chip8, opcode: u16) {
let (v_x, v_y) = decode_registers(opcode);
let y = chip8.registers[v_y as usize];
chip8.registers[v_x as usize] = y;
}
/// (8xy1 - OR Vx, Vy)
/// Set Vx = Vx OR Vy.
///
/// Performs a bitwise OR on the values of Vx and Vy, then stores the result in Vx.
/// A bitwise OR compares the corrseponding bits from two values, and if either bit is 1,
/// then the same bit in the result is also 1. Otherwise, it is 0.
pub fn or_registers(chip8: &mut Chip8, opcode: u16) {
let (v_x, v_y) = decode_registers(opcode);
let x = chip8.registers[v_x as usize];
let y = chip8.registers[v_y as usize];
chip8.registers[v_x as usize] = x | y;
}
/// (8xy2 - AND Vx, Vy)
/// Set Vx = Vx AND Vy.
///
/// Performs a bitwise AND on the values of Vx and Vy, then stores the result in Vx.
/// A bitwise AND compares the corrseponding bits from two values, and if both bits are 1,
/// then the same bit in the result is also 1. Otherwise, it is 0.
pub fn and_registers(chip8: &mut Chip8, opcode: u16) {
let (v_x, v_y) = decode_registers(opcode);
let x = chip8.registers[v_x as usize];
let y = chip8.registers[v_y as usize];
chip8.registers[v_x as usize] = x & y;
}
/// (8xy3 - XOR Vx, Vy)
/// Set Vx = Vx XOR Vy.
///
/// Performs a bitwise exclusive OR on the values of Vx and Vy, then stores the result
/// in Vx. An exclusive OR compares the corrseponding bits from two values, and if
/// the bits are not both the same, then the corresponding bit in the result is set to 1.
/// Otherwise, it is 0.
pub fn xor_registers(chip8: &mut Chip8, opcode: u16) {
let (v_x, v_y) = decode_registers(opcode);
let x = chip8.registers[v_x as usize];
let y = chip8.registers[v_y as usize];
chip8.registers[v_x as usize] = x ^ y;
}
/// (8xy4 - ADD Vx, Vy)
/// Set Vx = Vx + Vy, set VF = carry.
///
/// The values of Vx and Vy are added together. If the result is greater than
/// 8 bits (i.e., > 255,) VF is set to 1, otherwise 0. Only the lowest 8 bits
/// of the result are kept, and stored in Vx.
pub fn add_registers(chip8: &mut Chip8, opcode: u16) {
let (v_x, v_y) = decode_registers(opcode);
let x = chip8.registers[v_x as usize];
let y = chip8.registers[v_y as usize];
let (sum, overflow) = x.overflowing_add(y);
chip8.registers[v_x as usize] = sum;
chip8.registers[VF] = overflow as u8;
}
/// (8xy5 - SUB Vx, Vy)
/// Set Vx = Vx - Vy, set VF = NOT borrow.
///
/// If Vx > Vy, then VF is set to 1, otherwise 0. Then Vy is subtracted from Vx, and
/// the results stored in Vx.
pub fn sub_registers(chip8: &mut Chip8, opcode: u16) {
let (v_x, v_y) = decode_registers(opcode);
let x = chip8.registers[v_x as usize];
let y = chip8.registers[v_y as usize];
chip8.registers[v_x as usize] = x - y;
chip8.registers[VF] = (x > y) as u8;
}
/// (8xy6 - SHR Vx {, Vy})
/// Set Vx = Vx SHR 1.
///
/// If the least-significant bit of Vx is 1, then VF is set to 1, otherwise 0. Then Vx
/// is divided by 2.
pub fn shr_registers(chip8: &mut Chip8, opcode: u16) {
let v_x = decode_register_x(opcode) as usize;
let lsb = chip8.registers[v_x] & 0b00000001;
chip8.registers[VF] = lsb;
chip8.registers[v_x] = (chip8.registers[v_x] - lsb) / 2
}
/// (8xy7 - SUBN Vx, Vy)
/// Set Vx = Vy - Vx, set VF = NOT borrow.
///
/// If Vy > Vx, then VF is set to 1, otherwise 0. Then Vx is subtracted from Vy, and
/// the results stored in Vx.
pub fn subn_registers(chip8: &mut Chip8, opcode: u16) {
let (v_x, v_y) = decode_registers(opcode);
let x = chip8.registers[v_x as usize];
let y = chip8.registers[v_y as usize];
chip8.registers[v_x as usize] = y - x;
chip8.registers[VF] = (y > x) as u8;
}
/// (8xyE - SHL Vx {, Vy})
/// Set Vx = Vx SHL 1.
///
/// If the most-significant bit of Vx is 1, then VF is set to 1, otherwise to 0. Then Vx
/// is multiplied by 2.
pub fn shl_registers(chip8: &mut Chip8, opcode: u16) {
let v_x = decode_register_x(opcode) as usize;
let msb = chip8.registers[v_x] & 0b00000001;
chip8.registers[VF] = msb;
chip8.registers[v_x] = chip8.registers[v_x] * 2
}
/// (9xy0 - SNE Vx, Vy)
/// Skip next instruction if Vx != Vy.
///
/// The values of Vx and Vy are compared, and if they are not equal, the program counter
/// is increased by 2.
pub fn sne_registers(chip8: &mut Chip8, opcode: u16) {
let (v_x, v_y) = decode_registers(opcode);
if chip8.registers[v_x as usize] != chip8.registers[v_y as usize] {
chip8.pc += 2;
}
}
/// (Annn - LD I, addr)
/// Set I = nnn.
///
/// The value of register I is set to nnn.
pub fn ld_i_byte(chip8: &mut Chip8, opcode: u16) {
chip8.i = opcode & 0x0FFF;
println!("Set I to {:#X?}", chip8.i);
}
/// (Bnnn - JP V0, addr)
/// Jump to location nnn + V0.
///
/// The program counter is set to nnn plus the value of V0.
pub fn jp_bnnn(chip8: &mut Chip8, opcode: u16) {
let nnn = decode_short(opcode);
let v0 = (chip8.registers[0]) as u16;
chip8.pc = nnn + v0;
println!("Set Program Counter to {:#X?}", chip8.pc);
}
/// (Cxkk - RND Vx, byte)
/// Set Vx = random byte AND kk.
///
/// The interpreter generates a random number from 0 to 255, which is then ANDed with
/// the value kk. The results are stored in Vx. See instruction 8xy2 for more information
/// on AND.
pub fn rnd(chip8: &mut Chip8, opcode: u16) {
let x = decode_register_x(opcode);
let kk = decode_byte(opcode);
let random: u8 = chip8.rng.gen();
println!("Sample {}", random);
chip8.registers[x as usize] = random & kk;
}
/// (Dxyn - DRW Vx, Vy, n)
/// Display n-byte sprite starting at memory location I at (Vx, Vy), set VF = collision.
///
/// The interpreter reads n bytes from memory, starting at the address stored in I.
/// These bytes are then displayed as sprites on screen at coordinates (Vx, Vy).
/// Sprites are XORed onto the existing screen. If this causes any pixels to be erased,
/// VF is set to 1, otherwise it is set to 0. If the sprite is positioned so part of it
/// is outside the coordinates of the display, it wraps around to the opposite side of
/// the screen. See instruction 8xy3 for more information on XOR, and section 2.4,
/// Display, for more information on the Chip-8 screen and sprites.
pub fn drw_draw_sprite(chip8: &mut Chip8, opcode: u16) {
let (v_x, v_y) = decode_registers(opcode);
let n = (opcode & 0x000F) as u8;
let x = chip8.registers[v_x as usize] as usize;
let y = chip8.registers[v_y as usize] as usize;
let start = chip8.i as usize;
let end = start + n as usize;
let read = &chip8.memory[start..end];
println!("At position ({}, {}), draw:", x, y);
for byte in read {
println!("{:08b}", byte);
}
/*
for byte in 0u8..n {
let idx = (y as usize + byte as usize) * WIDTH + x as usize;
let bits = binary_to_vec(read[byte as usize]);
println!("{:08b}, {:?}", byte, bits);
for (jdx, bit) in bits.iter().enumerate() {
println!("{}, {}", jdx, bit);
chip8.display[idx+jdx] = *bit as u32 * 255;
}
}
*/
chip8.display.blit(&binary_to_buffer(read.to_vec()), Point::new(x, y));
}
/// (Ex9E - SKP Vx)
/// Skip next instruction if key with the value of Vx is pressed.
///
/// Checks the keyboard, and if the key corresponding to the value of Vx is currently
/// in the down position, PC is increased by 2.
pub fn skp_skip_pressed(chip8: &mut Chip8, opcode: u16) {}
/// (ExA1 - SKNP Vx)
/// Skip next instruction if key with the value of Vx is not pressed.
///
/// Checks the keyboard, and if the key corresponding to the value of Vx is currently in
/// the up position, PC is increased by 2.
pub fn sknp_skip_not_pressed(chip8: &mut Chip8, opcode: u16) {}
/// (Fx07 - LD Vx, DT)
/// Set Vx = delay timer value.
///
/// The value of DT is placed into Vx.
pub fn ld_get_delay_timer(chip8: &mut Chip8, opcode: u16) {
let v_x = (chip8.opcode & 0x0F00) >> 8;
chip8.registers[v_x as usize] = chip8.delay_timer;
}
/// (Fx0A - LD Vx, K)
/// Wait for a key press, store the value of the key in Vx.
///
/// All execution stops until a key is pressed, then the value of that key is stored in Vx.
pub fn ld_wait_for_key(chip8: &mut Chip8, opcode: u16) {}
/// (Fx15 - LD DT, Vx)
/// Set delay timer = Vx.
///
/// DT is set equal to the value of Vx.
pub fn ld_set_delay_timer(chip8: &mut Chip8, opcode: u16) {}
/// (Fx18 - LD ST, Vx)
/// Set sound timer = Vx.
///
/// ST is set equal to the value of Vx.
pub fn ld_set_sound_timer(chip8: &mut Chip8, opcode: u16) {}
/// (Fx1E - ADD I, Vx)
/// Set I = I + Vx.
///
/// The values of I and Vx are added, and the results are stored in I.
pub fn add_to_i(chip8: &mut Chip8, opcode: u16) {}
/// (Fx29 - LD F, Vx)
/// Set I = location of sprite for digit Vx.
///
/// The value of I is set to the location for the hexadecimal sprite corresponding to
/// the value of Vx. See section 2.4, Display, for more information on
/// the Chip-8 hexadecimal font.
pub fn ld_i_to_sprite(chip8: &mut Chip8, opcode: u16) {}
/// (Fx33 - LD B, Vx)
/// Store BCD representation of Vx in memory locations I, I+1, and I+2.
///
/// The interpreter takes the decimal value of Vx, and places the hundreds digit in
/// memory at location in I, the tens digit at location I+1, and the ones digit at
/// location I+2.
pub fn ld_bcd(chip8: &mut Chip8, opcode: u16) {
let v_x = decode_register_x(opcode) as usize;
let mut x = chip8.registers[v_x];
let hundreds = x - x % 100;
x -= hundreds;
let tens = x - x % 10;
let ones = x - tens;
println!("{}", chip8.registers[v_x]);
println!("{}, {}, {}", hundreds, tens, ones);
}
/// (Fx55 - LD [I], Vx)
/// Store registers V0 through Vx in memory starting at location I.
///
/// The interpreter copies the values of registers V0 through Vx into memory, starting
/// at the address in I.
pub fn ld_store_registers(chip8: &mut Chip8, opcode: u16) {
let v_x = decode_register_x(opcode);
let i = chip8.i as usize;
for (idx, register) in (v_x..16).enumerate() {
println!("{}, {}", idx, register);
chip8.memory[i + idx] = chip8.registers[register as usize];
}
}
/// (Fx65 - LD Vx, [I])
/// Read registers V0 through Vx from memory starting at location I.
///
/// The interpreter reads values from memory starting at location I into registers
/// V0 through Vx.
pub fn ld_read_registers(chip8: &mut Chip8, opcode: u16) {
}
fn decode_register_x(opcode: u16) -> u8 {
let v_x = (opcode & 0x0F00) >> 8;
v_x as u8
}
fn decode_register_y(opcode: u16) -> u8 {
let v_y = (opcode & 0x00F0) >> 4;
v_y as u8
}
fn decode_registers(opcode: u16) -> (u8, u8) {
(decode_register_x(opcode), decode_register_y(opcode))
}
fn decode_byte(opcode: u16) -> u8 {
(opcode & 0x00FF) as u8
}
fn decode_short(opcode: u16) -> u16 {
(opcode & 0x0FFF)
}
fn binary_to_vec(mut binary: u8) -> Vec<u8> {
let mut values = Vec::new();
for _ in 0..8 {
values.push((binary & 0b10000000) >> 7);
binary = binary << 1;
}
return values;
}
fn binary_to_buffer(binary: Vec<u8>) -> Buffer {
let mut pixels = Vec::new();
let height = binary.len();
for bin in binary {
for pixel in binary_to_vec(bin) {
pixels.push(pixel as u32 * 255);
}
}
Buffer::new(8, height, Some(pixels))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_decode_short() {
let result = decode_short(0xABCD);
let expected = 0xBCD;
assert_eq!(result, expected);
}
#[test]
fn test_binary_to_vec() {
let result = binary_to_vec(0b00101010);
let expected = vec!(0, 0, 1, 0, 1, 0, 1, 0);
assert_eq!(result, expected);
}
}
|
#[doc = "Reader of register DDRCTRL_ADDRMAP9"]
pub type R = crate::R<u32, super::DDRCTRL_ADDRMAP9>;
#[doc = "Writer for register DDRCTRL_ADDRMAP9"]
pub type W = crate::W<u32, super::DDRCTRL_ADDRMAP9>;
#[doc = "Register DDRCTRL_ADDRMAP9 `reset()`'s with value 0"]
impl crate::ResetValue for super::DDRCTRL_ADDRMAP9 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `ADDRMAP_ROW_B2`"]
pub type ADDRMAP_ROW_B2_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `ADDRMAP_ROW_B2`"]
pub struct ADDRMAP_ROW_B2_W<'a> {
w: &'a mut W,
}
impl<'a> ADDRMAP_ROW_B2_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f);
self.w
}
}
#[doc = "Reader of field `ADDRMAP_ROW_B3`"]
pub type ADDRMAP_ROW_B3_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `ADDRMAP_ROW_B3`"]
pub struct ADDRMAP_ROW_B3_W<'a> {
w: &'a mut W,
}
impl<'a> ADDRMAP_ROW_B3_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8);
self.w
}
}
#[doc = "Reader of field `ADDRMAP_ROW_B4`"]
pub type ADDRMAP_ROW_B4_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `ADDRMAP_ROW_B4`"]
pub struct ADDRMAP_ROW_B4_W<'a> {
w: &'a mut W,
}
impl<'a> ADDRMAP_ROW_B4_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 16)) | (((value as u32) & 0x0f) << 16);
self.w
}
}
#[doc = "Reader of field `ADDRMAP_ROW_B5`"]
pub type ADDRMAP_ROW_B5_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `ADDRMAP_ROW_B5`"]
pub struct ADDRMAP_ROW_B5_W<'a> {
w: &'a mut W,
}
impl<'a> ADDRMAP_ROW_B5_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 24)) | (((value as u32) & 0x0f) << 24);
self.w
}
}
impl R {
#[doc = "Bits 0:3 - ADDRMAP_ROW_B2"]
#[inline(always)]
pub fn addrmap_row_b2(&self) -> ADDRMAP_ROW_B2_R {
ADDRMAP_ROW_B2_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 8:11 - ADDRMAP_ROW_B3"]
#[inline(always)]
pub fn addrmap_row_b3(&self) -> ADDRMAP_ROW_B3_R {
ADDRMAP_ROW_B3_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bits 16:19 - ADDRMAP_ROW_B4"]
#[inline(always)]
pub fn addrmap_row_b4(&self) -> ADDRMAP_ROW_B4_R {
ADDRMAP_ROW_B4_R::new(((self.bits >> 16) & 0x0f) as u8)
}
#[doc = "Bits 24:27 - ADDRMAP_ROW_B5"]
#[inline(always)]
pub fn addrmap_row_b5(&self) -> ADDRMAP_ROW_B5_R {
ADDRMAP_ROW_B5_R::new(((self.bits >> 24) & 0x0f) as u8)
}
}
impl W {
#[doc = "Bits 0:3 - ADDRMAP_ROW_B2"]
#[inline(always)]
pub fn addrmap_row_b2(&mut self) -> ADDRMAP_ROW_B2_W {
ADDRMAP_ROW_B2_W { w: self }
}
#[doc = "Bits 8:11 - ADDRMAP_ROW_B3"]
#[inline(always)]
pub fn addrmap_row_b3(&mut self) -> ADDRMAP_ROW_B3_W {
ADDRMAP_ROW_B3_W { w: self }
}
#[doc = "Bits 16:19 - ADDRMAP_ROW_B4"]
#[inline(always)]
pub fn addrmap_row_b4(&mut self) -> ADDRMAP_ROW_B4_W {
ADDRMAP_ROW_B4_W { w: self }
}
#[doc = "Bits 24:27 - ADDRMAP_ROW_B5"]
#[inline(always)]
pub fn addrmap_row_b5(&mut self) -> ADDRMAP_ROW_B5_W {
ADDRMAP_ROW_B5_W { w: self }
}
}
|
#![recursion_limit = "1024"]
#[macro_use]
extern crate error_chain;
extern crate alto;
extern crate clap;
extern crate colored;
extern crate env_logger;
extern crate gstreamer as gst;
#[macro_use]
extern crate log;
extern crate pitch_calc;
extern crate termion;
extern crate ultrastar_txt;
// extern crate hyper;
// extern crate hyper_native_tls;
extern crate regex;
extern crate reqwest;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate glib;
mod content_providers;
mod draw;
mod pitch;
mod server_interface;
use crate::content_providers::get_url_content_provider;
use std::io::{stdout, Write};
use std::path::PathBuf;
use crate::gst::MessageView;
use crate::gst::prelude::*;
use clap::{App, Arg, ArgGroup};
use termion::screen::AlternateScreen;
use alto::{Alto, Capture, Mono};
use std::thread;
use std::sync::{Arc, Mutex};
use pitch_calc::*;
mod errors {
error_chain!{}
}
use crate::errors::*;
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const AUTHOR: &'static str = env!("CARGO_PKG_AUTHORS");
struct CustomData {
playbin: gst::Element, // Our one and only element
playing: bool, // Are we in the PLAYING state?
terminate: bool, // Should we terminate execution?
duration: gst::ClockTime, // How long does this media last, in nanoseconds
}
fn main() {
if let Err(ref e) = run() {
use std::io::Write;
let stderr = &mut ::std::io::stderr();
let errmsg = "Error writing to stderr";
writeln!(stderr, "error: {}", e).expect(errmsg);
for e in e.iter().skip(1) {
writeln!(stderr, "caused by: {}", e).expect(errmsg);
}
// The backtrace is not always generated. Try to run this example
// with `RUST_BACKTRACE=1`.
if let Some(backtrace) = e.backtrace() {
writeln!(stderr, "backtrace: {:?}", backtrace).expect(errmsg);
}
::std::process::exit(1);
}
}
const SAMPLE_RATE: u32 = 44_100;
const FRAMES: i32 = 2048;
fn run() -> Result<()> {
let _ = env_logger::init();
// manage command line arguments using clap
let matches = App::new("usrs-cli")
.version(VERSION)
.author(AUTHOR)
.about("An Ultrastar song player for the command line written in rust")
// xor: either local or search, but not both
.group(ArgGroup::with_name("content_providers").args(&["local", "search"]).required(true))
.args(&[
Arg::with_name("local")
.value_name("TXT")
.short("l")
.long("local")
.help("the song file to play"),
Arg::with_name("search")
.value_name("KEYWORD")
.short("s")
.long("search")
.help("a keyword to search on the server"),
Arg::with_name("play")
.requires("search") //<
.value_name("INDEX")
.short("p")
.long("play")
.help("index from search list to play")
// TODO: add validation (value should be an int!)
])
.get_matches();
println!("Ultrastar CLI player {} by @man0lis", VERSION);
let tempfile = if let Some(keyword) = matches.value_of("search") {
// did we get a `play` argument as well?
if let Some(index) = matches.value_of("play") {
let index = index.parse::<usize>().chain_err(|| "index has to be an integer")?;
let url = server_interface::search(keyword, Some(index))?.unwrap();
Some(server_interface::download_file(url)
.chain_err(|| "could not download .txt file")?)
} else {
// this is an exit point!
server_interface::search(keyword, None)?;
return Ok(());
}
} else {
None
};
// TODO: download text file into /tmp
// TODO: maybe use crate `tempfile` for this?
// TODO: pass this tmp path to ultrastar_txt
// get path from tempfile or command line arguments.
// unwrap should not fail because tempfile is none => no `search` was done => `local` argument is required
let song_filepath: PathBuf = match &tempfile {
Some(file) => PathBuf::from(file.path()),
None => PathBuf::from(matches.value_of("local").unwrap())
};
// parse txt file
let txt_song = ultrastar_txt::parse_txt_song(song_filepath)
.chain_err(|| "could not parse song file")?;
let header = txt_song.header;
let lines = txt_song.lines;
// prepare song
let bpms = header.bpm / 60.0 / 1000.0;
let gap = header.gap.unwrap_or(0.0);
let mut line_iter = lines.into_iter();
let mut current_line = line_iter.next();
let mut next_line = line_iter.next();
// construct path and uri to audio file
let audio_path = header.audio_path;
let content_provider = get_url_content_provider(&audio_path);
// set up openal for capture
let alto = Alto::load_default().chain_err(|| "could not load openal default implementation")?;
let cap_dev = alto.default_capture().unwrap();
let mut capture: Capture<Mono<i16>> = alto.open_capture(Some(&cap_dev), SAMPLE_RATE, FRAMES)
.chain_err(|| "could not open default capture device")?;
// reference counted mutex for current deteced note
let detected_note = Arc::new(Mutex::new(Some(LetterOctave(Letter::C, 2))));
let detected_note_capture = detected_note.clone();
// thread that handels audio buffers from openal the audio buffer
let capture_thread = move || {
capture.start();
loop {
let mut samples_len = capture.samples_len();
let mut buffer_i16: Vec<i16> = vec![0; FRAMES as usize];
while samples_len < buffer_i16.len() as i32 {
samples_len = capture.samples_len();
thread::sleep(std::time::Duration::from_millis(1));
}
capture
.capture_samples(&mut buffer_i16)
.chain_err(|| "could not capture samples")
.unwrap();
let buffer_f32: Vec<_> = buffer_i16
.iter()
.map(|x| (*x as f32) / (std::i16::MAX as f32) * 2.0)
.collect();
let max_volume = pitch::get_max_amplitude(buffer_f32.as_ref());
let mut dominant_note = detected_note_capture.lock().unwrap();
*dominant_note = if max_volume > 0.1 {
Some(pitch::get_dominant_note(
buffer_f32.as_ref(),
SAMPLE_RATE as f64,
))
} else {
None
};
}
};
// initialize GStreamer
gst::init().unwrap();
// create the playbin element
let playbin = gst::ElementFactory::make("playbin", Some("playbin"))
.chain_err(|| "failed to create playbin element")?;
// set the URI to play
for url in content_provider.urls() {
playbin
.set_property("uri", &url)
.chain_err(|| "can't set uri property on playbin")?;
break
}
// disable video and subtitle, if they exist
// according to: https://github.com/sdroege/gstreamer-rs/blob/4117c01ff2c9ce9b46b8f63315af4dc284788e9b/examples/src/bin/playbin.rs#L27-L35
let flags = playbin
.get_property("flags")
.chain_err(|| "can't get playbin flags")?;
let flags_class = ::glib::FlagsClass::new(flags.type_()).unwrap();
let flags = flags_class.builder_with_value(flags).unwrap()
.unset_by_nick("text")
.unset_by_nick("video")
.build()
.unwrap();
playbin
.set_property("flags", &flags)
.chain_err(|| "can't set playbin flags")?;
println!("Playing {} by {}...\n", header.title, header.artist);
// Start playing
let ret = playbin.set_state(gst::State::Playing);
assert!(ret.is_ok());
// connect to the bus
let bus = playbin.get_bus().unwrap();
let mut custom_data = CustomData {
playbin: playbin,
playing: false,
terminate: false,
duration: gst::CLOCK_TIME_NONE,
};
thread::spawn(capture_thread);
// get access to terminal
//let stdin = stdin();
//let mut stdout = stdout();
let mut stdout = AlternateScreen::from(stdout());
// clear screen
write!(stdout, "{}", termion::clear::All).chain_err(|| "could not write to stdout")?;
// begin main loop
while !custom_data.terminate {
let msg = bus.timed_pop(10 * gst::MSECOND);
match msg {
Some(msg) => {
handle_message(&mut custom_data, &msg);
}
None => {
if custom_data.playing {
let position = custom_data
.playbin
.query_position()
.unwrap_or(gst::CLOCK_TIME_NONE);
// If we didn't know it yet, query the stream duration
if custom_data.duration == gst::CLOCK_TIME_NONE {
custom_data.duration = custom_data
.playbin
.query_duration()
.unwrap_or(gst::CLOCK_TIME_NONE);
}
// get note from capture thread
let dominant_note = detected_note.lock().unwrap().clone();
// calculate current beat
let position_ms = position.mseconds().unwrap_or(0) as f32;
// don't know why I need the 4.0 but its in the
// original game and its not working without it
let beat = (position_ms - gap) * (bpms * 4.0);
let next_line_start = if next_line.is_some() {
next_line.clone().unwrap().start
} else {
// last line reached, make next if always fail
beat as i32 + 100
};
if beat > next_line_start as f32 {
// reprint current line to avoid stale highlights
if let &Some(ref line) = ¤t_line {
write!(
stdout,
"{}",
draw::generate_screen(line, beat + 100.0, dominant_note)?
).chain_err(|| "could not write to stdout")?;
}
if next_line.is_some() {
current_line = next_line;
};
next_line = line_iter.next();
// clear screen
write!(stdout, "{}", termion::clear::All)
.chain_err(|| "could not write to stdout")?;
}
// print current lyric line
if let &Some(ref line) = ¤t_line {
write!(
stdout,
"{}",
draw::generate_screen(line, beat, dominant_note)?
).chain_err(|| "could not write to stdout")?;
}
}
}
}
}
// end main loop
// Shutdown pipeline
let ret = custom_data.playbin.set_state(gst::State::Null);
assert!(ret.is_ok());
println!("");
Ok(())
}
fn handle_message(custom_data: &mut CustomData, msg: &gst::GstRc<gst::MessageRef>) {
match msg.view() {
MessageView::Error(err) => {
error!(
"Error received from element {:?}: {} ({:?})",
msg.get_src().map(|s| s.get_path_string()),
err.get_error(),
err.get_debug()
);
custom_data.terminate = true;
}
MessageView::Eos(..) => {
info!("End-Of-Stream reached.");
custom_data.terminate = true;
}
MessageView::DurationChanged(_) => {
// The duration has changed, mark the current one as invalid
custom_data.duration = gst::CLOCK_TIME_NONE;
}
MessageView::StateChanged(state) => if msg.get_src()
.map(|s| s == custom_data.playbin)
.unwrap_or(false)
{
let new_state = state.get_current();
let old_state = state.get_old();
info!(
"Pipeline state changed from {:?} to {:?}",
old_state, new_state
);
custom_data.playing = new_state == gst::State::Playing;
},
_ => (),
}
}
|
use super::*;
use mathic::*;
pub struct SubGenerator {
scratch_gpr: Reg,
left_fpr: FPReg,
right_fpr: FPReg,
result: Reg,
left: Reg,
right: Reg,
}
impl MathICGenerator for SubGenerator {
fn generate_inline(
&mut self,
jit: &mut JIT<'_>,
state: &mut MathICGenerationState,
profile: Option<&ArithProfile>,
) -> MathICResult {
let mut lhs = ObservedType::default().with_int32();
let mut rhs = ObservedType::default().with_int32();
if let Some(profile) = profile {
lhs = profile.lhs_observed_type();
rhs = profile.rhs_observed_type();
}
if lhs.is_only_non_number() && rhs.is_only_non_number() {
log!("Non number operation, do not generate code");
return MathICResult::DontGenerate;
}
if lhs.is_only_number() && rhs.is_only_number() {
state
.slow_path_jumps
.push(jit.branch_if_not_number(self.left, true));
state
.slow_path_jumps
.push(jit.branch_if_not_number(self.right, true));
state
.slow_path_jumps
.push(jit.branch_if_int32(self.left, true));
state
.slow_path_jumps
.push(jit.branch_if_int32(self.right, true));
jit.unbox_double_non_destructive(self.left, self.left_fpr, self.scratch_gpr);
jit.unbox_double_non_destructive(self.right, self.right_fpr, self.scratch_gpr);
jit.masm.sub_double_rr(self.right_fpr, self.left_fpr);
jit.box_double(self.left_fpr, self.result, true);
return MathICResult::GenFastPath;
}
if lhs.is_only_int32() && rhs.is_only_int32() {
state
.slow_path_jumps
.push(jit.branch_if_not_int32(self.left, true));
state
.slow_path_jumps
.push(jit.branch_if_not_int32(self.right, true));
jit.masm.move_rr(self.left, self.scratch_gpr);
state.slow_path_jumps.push(jit.masm.branch_sub32(
ResultCondition::Overflow,
self.right,
self.scratch_gpr,
));
jit.box_int32(self.scratch_gpr, self.result, true);
return MathICResult::GenFastPath;
}
MathICResult::GenFullSnippet
}
fn generate_fastpath(
&mut self,
jit: &mut JIT<'_>,
end_jump_list: &mut JumpList,
slow_path_jump_list: &mut JumpList,
arith_profile: Option<&mut ArithProfile>,
should_profile: bool,
) -> bool {
let left_not_int = jit.branch_if_not_int32(self.left, true);
let right_not_int = jit.branch_if_not_int32(self.right, true);
jit.masm.move_rr(self.left, self.scratch_gpr);
slow_path_jump_list.push(jit.masm.branch_sub32(
ResultCondition::Overflow,
self.right,
self.scratch_gpr,
));
jit.box_int32(self.scratch_gpr, self.result, true);
end_jump_list.push(jit.masm.jump());
left_not_int.link(&mut jit.masm);
slow_path_jump_list.push(jit.branch_if_not_number(self.left, true));
slow_path_jump_list.push(jit.branch_if_not_number(self.right, true));
jit.unbox_double_non_destructive(self.left, self.left_fpr, self.scratch_gpr);
let right_is_double = jit.branch_if_not_int32(self.right, true);
jit.masm.convert_int32_to_double(self.right, self.right_fpr);
let right_was_integer = jit.masm.jump();
right_not_int.link(&mut jit.masm);
slow_path_jump_list.push(jit.branch_if_not_number(self.right, true));
//let right_not_int = jit.branch_if_not_int32(self.right, true);
jit.masm.convert_int32_to_double(self.left, self.left_fpr);
right_is_double.link(&mut jit.masm);
jit.masm.convert_int32_to_double(self.right, self.right_fpr);
right_was_integer.link(&mut jit.masm);
jit.masm.sub_double_rr(self.right_fpr, self.left_fpr);
if should_profile {
if let Some(profile) = arith_profile {
profile.emit_set_double(jit);
}
}
jit.box_double(self.left_fpr, self.result, true);
true
}
}
impl BinaryMathICGenerator for SubGenerator {
fn new(
result: Reg,
left: Reg,
right: Reg,
left_fpr: FPReg,
right_fpr: FPReg,
scratch_gpr: Reg,
_scratch_fp: FPReg,
) -> Self {
Self {
scratch_gpr,
left,
right,
result,
left_fpr,
right_fpr,
}
}
}
|
pub fn parse(text: &str) -> Option<Vec<Instruction>> {
let instructions: Vec<Instruction> = text.lines()
.map(|s| match parse_line(s) {
Some(instructions) => instructions,
None => vec![],
})
.fold(vec![], |mut collector, mut inst| {
collector.append(&mut inst);
collector
});
if instructions.len() == 0 {
return None;
} else {
return Some(instructions);
}
}
pub fn parse_line(text: &str) -> Option<Vec<Instruction>> {
let tokens: Vec<String> = text.split_whitespace().map(|s| s.to_owned()).collect();
if tokens.len() < 2 {
return None;
}
if tokens[0].to_lowercase() != "@grahamcofborg" {
return None;
}
let commands: Vec<&[String]> = tokens
.split(|token| token.to_lowercase() == "@grahamcofborg")
.filter(|token| token.len() > 0)
.collect();
let mut instructions: Vec<Instruction> = vec![];
for command in commands {
let (left, right) = command.split_at(1);
match left[0].as_ref() {
"build" => {
let attrs = right.to_vec();
if attrs.len() > 0 {
instructions.push(Instruction::Build(Subset::Nixpkgs, attrs));
}
}
"test" => {
instructions.push(Instruction::Build(
Subset::NixOS,
right
.into_iter()
.map(|attr| format!("tests.{}", attr))
.collect(),
));
}
"eval" => instructions.push(Instruction::Eval),
_ => {}
}
}
return Some(instructions);
}
#[derive(PartialEq, Debug)]
pub enum Instruction {
Build(Subset, Vec<String>),
Eval,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub enum Subset {
Nixpkgs,
NixOS,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_empty() {
assert_eq!(None, parse(""));
}
#[test]
fn valid_trailing_instruction() {
assert_eq!(
Some(vec![Instruction::Eval]),
parse(
"/cc @grahamc for ^^
@GrahamcOfBorg eval",
)
);
}
#[test]
fn bogus_comment() {
assert_eq!(None, parse(":) :) :) @grahamcofborg build hi"));
}
#[test]
fn bogus_build_comment_empty_list() {
assert_eq!(None, parse("@grahamcofborg build"));
}
#[test]
fn eval_comment() {
assert_eq!(Some(vec![Instruction::Eval]), parse("@grahamcofborg eval"));
}
#[test]
fn eval_and_build_comment() {
assert_eq!(
Some(vec![
Instruction::Eval,
Instruction::Build(
Subset::Nixpkgs,
vec![String::from("foo")]
),
]),
parse("@grahamcofborg eval @grahamcofborg build foo")
);
}
#[test]
fn build_and_eval_and_build_comment() {
assert_eq!(
Some(vec![
Instruction::Build(
Subset::Nixpkgs,
vec![String::from("bar")]
),
Instruction::Eval,
Instruction::Build(
Subset::Nixpkgs,
vec![String::from("foo")]
),
]),
parse(
"
@grahamcofborg build bar
@grahamcofborg eval
@grahamcofborg build foo",
)
);
}
#[test]
fn complex_comment_with_paragraphs() {
assert_eq!(
Some(vec![
Instruction::Build(
Subset::Nixpkgs,
vec![String::from("bar")]
),
Instruction::Eval,
Instruction::Build(
Subset::Nixpkgs,
vec![String::from("foo")]
),
]),
parse(
"
I like where you're going with this PR, so let's try it out!
@grahamcofborg build bar
I noticed though that the target branch was broken, which should be fixed. Let's eval again.
@grahamcofborg eval
Also, just in case, let's try foo
@grahamcofborg build foo",
)
);
}
#[test]
fn build_and_eval_comment() {
assert_eq!(
Some(vec![
Instruction::Build(
Subset::Nixpkgs,
vec![String::from("foo")]
),
Instruction::Eval,
]),
parse("@grahamcofborg build foo @grahamcofborg eval")
);
}
#[test]
fn build_comment() {
assert_eq!(
Some(vec![
Instruction::Build(
Subset::Nixpkgs,
vec![String::from("foo"), String::from("bar")]
),
]),
parse(
"@GrahamCOfBorg build foo bar
baz",
)
);
}
#[test]
fn test_comment() {
assert_eq!(
Some(vec![
Instruction::Build(
Subset::NixOS,
vec![
String::from("tests.foo"),
String::from("tests.bar"),
String::from("tests.baz"),
]
),
]),
parse("@GrahamCOfBorg test foo bar baz")
);
}
#[test]
fn build_comment_newlines() {
assert_eq!(
Some(vec![
Instruction::Build(
Subset::Nixpkgs,
vec![
String::from("foo"),
String::from("bar"),
String::from("baz"),
]
),
]),
parse("@GrahamCOfBorg build foo bar baz")
);
}
#[test]
fn build_comment_lower() {
assert_eq!(
Some(vec![
Instruction::Build(
Subset::Nixpkgs,
vec![
String::from("foo"),
String::from("bar"),
String::from("baz"),
]
),
]),
parse("@grahamcofborg build foo bar baz")
);
}
#[test]
fn build_comment_lower_package_case_retained() {
assert_eq!(
Some(vec![
Instruction::Build(
Subset::Nixpkgs,
vec![
String::from("foo"),
String::from("bar"),
String::from("baz.Baz"),
]
),
]),
parse("@grahamcofborg build foo bar baz.Baz")
);
}
}
|
use crate::{event_builder::EventBuilder, EnumEventData};
use crate::{Entity, Event};
use chrono::Utc;
use uuid::Uuid;
/// Generic event builder for an action specified by its EventData
#[derive(Debug)]
pub struct ActionEventBuilder<EDENUM>
where
EDENUM: EnumEventData,
{
payload: EDENUM,
session_id: Option<Uuid>,
}
impl<EDENUM> ActionEventBuilder<EDENUM>
where
EDENUM: EnumEventData,
{
/// DOCS
pub fn build<E: Entity>(self, entity: &Option<E>) -> Event<EDENUM> {
Event {
id: Uuid::new_v4(),
event_type: String::from(self.payload.event_type()),
entity_type: E::entity_type(),
entity_id: entity.as_ref().map_or(Uuid::new_v4(), |e| e.entity_id()),
session_id: self.session_id,
purger_id: None,
created_at: Utc::now(),
purged_at: None,
data: Some(self.payload),
}
}
}
impl<EDENUM> EventBuilder<EDENUM> for ActionEventBuilder<EDENUM>
where
EDENUM: EnumEventData,
{
/// Create a new event builder with a given event data payload
fn new(payload: EDENUM) -> Self {
Self {
payload,
session_id: None,
}
}
/// Set the session ID field of the event
fn session_id(mut self, session_id: Uuid) -> Self {
self.session_id = Some(session_id);
self
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - QUADSPI control register"]
pub quadspi_cr: QUADSPI_CR,
#[doc = "0x04 - QUADSPI device configuration register"]
pub quadspi_dcr: QUADSPI_DCR,
#[doc = "0x08 - QUADSPI status register"]
pub quadspi_sr: QUADSPI_SR,
#[doc = "0x0c - QUADSPI flag clear register"]
pub quadspi_fcr: QUADSPI_FCR,
#[doc = "0x10 - QUADSPI data length register"]
pub quadspi_dlr: QUADSPI_DLR,
#[doc = "0x14 - QUADSPI communication configuration register"]
pub quadspi_ccr: QUADSPI_CCR,
#[doc = "0x18 - QUADSPI address register"]
pub quadspi_ar: QUADSPI_AR,
#[doc = "0x1c - QUADSPI alternate bytes registers"]
pub quadspi_abr: QUADSPI_ABR,
#[doc = "0x20 - QUADSPI data register"]
pub quadspi_dr: QUADSPI_DR,
#[doc = "0x24 - QUADSPI polling status mask register"]
pub quadspi_psmkr: QUADSPI_PSMKR,
#[doc = "0x28 - QUADSPI polling status match register"]
pub quadspi_psmar: QUADSPI_PSMAR,
#[doc = "0x2c - QUADSPI polling interval register"]
pub quadspi_pir: QUADSPI_PIR,
#[doc = "0x30 - QUADSPI low-power timeout register"]
pub quadspi_lptr: QUADSPI_LPTR,
_reserved13: [u8; 956usize],
#[doc = "0x3f0 - QUADSPI HW configuration register"]
pub quadspi_hwcfgr: QUADSPI_HWCFGR,
#[doc = "0x3f4 - QUADSPI version register"]
pub quadspi_verr: QUADSPI_VERR,
#[doc = "0x3f8 - QUADSPI identification register"]
pub quadspi_ipidr: QUADSPI_IPIDR,
#[doc = "0x3fc - QUADSPI size identification register"]
pub quadspi_sidr: QUADSPI_SIDR,
}
#[doc = "QUADSPI control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_cr](quadspi_cr) module"]
pub type QUADSPI_CR = crate::Reg<u32, _QUADSPI_CR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_CR;
#[doc = "`read()` method returns [quadspi_cr::R](quadspi_cr::R) reader structure"]
impl crate::Readable for QUADSPI_CR {}
#[doc = "`write(|w| ..)` method takes [quadspi_cr::W](quadspi_cr::W) writer structure"]
impl crate::Writable for QUADSPI_CR {}
#[doc = "QUADSPI control register"]
pub mod quadspi_cr;
#[doc = "QUADSPI device configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_dcr](quadspi_dcr) module"]
pub type QUADSPI_DCR = crate::Reg<u32, _QUADSPI_DCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_DCR;
#[doc = "`read()` method returns [quadspi_dcr::R](quadspi_dcr::R) reader structure"]
impl crate::Readable for QUADSPI_DCR {}
#[doc = "`write(|w| ..)` method takes [quadspi_dcr::W](quadspi_dcr::W) writer structure"]
impl crate::Writable for QUADSPI_DCR {}
#[doc = "QUADSPI device configuration register"]
pub mod quadspi_dcr;
#[doc = "QUADSPI status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_sr](quadspi_sr) module"]
pub type QUADSPI_SR = crate::Reg<u32, _QUADSPI_SR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_SR;
#[doc = "`read()` method returns [quadspi_sr::R](quadspi_sr::R) reader structure"]
impl crate::Readable for QUADSPI_SR {}
#[doc = "QUADSPI status register"]
pub mod quadspi_sr;
#[doc = "QUADSPI flag clear register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_fcr](quadspi_fcr) module"]
pub type QUADSPI_FCR = crate::Reg<u32, _QUADSPI_FCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_FCR;
#[doc = "`read()` method returns [quadspi_fcr::R](quadspi_fcr::R) reader structure"]
impl crate::Readable for QUADSPI_FCR {}
#[doc = "`write(|w| ..)` method takes [quadspi_fcr::W](quadspi_fcr::W) writer structure"]
impl crate::Writable for QUADSPI_FCR {}
#[doc = "QUADSPI flag clear register"]
pub mod quadspi_fcr;
#[doc = "QUADSPI data length register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_dlr](quadspi_dlr) module"]
pub type QUADSPI_DLR = crate::Reg<u32, _QUADSPI_DLR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_DLR;
#[doc = "`read()` method returns [quadspi_dlr::R](quadspi_dlr::R) reader structure"]
impl crate::Readable for QUADSPI_DLR {}
#[doc = "`write(|w| ..)` method takes [quadspi_dlr::W](quadspi_dlr::W) writer structure"]
impl crate::Writable for QUADSPI_DLR {}
#[doc = "QUADSPI data length register"]
pub mod quadspi_dlr;
#[doc = "QUADSPI communication configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_ccr](quadspi_ccr) module"]
pub type QUADSPI_CCR = crate::Reg<u32, _QUADSPI_CCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_CCR;
#[doc = "`read()` method returns [quadspi_ccr::R](quadspi_ccr::R) reader structure"]
impl crate::Readable for QUADSPI_CCR {}
#[doc = "`write(|w| ..)` method takes [quadspi_ccr::W](quadspi_ccr::W) writer structure"]
impl crate::Writable for QUADSPI_CCR {}
#[doc = "QUADSPI communication configuration register"]
pub mod quadspi_ccr;
#[doc = "QUADSPI address register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_ar](quadspi_ar) module"]
pub type QUADSPI_AR = crate::Reg<u32, _QUADSPI_AR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_AR;
#[doc = "`read()` method returns [quadspi_ar::R](quadspi_ar::R) reader structure"]
impl crate::Readable for QUADSPI_AR {}
#[doc = "`write(|w| ..)` method takes [quadspi_ar::W](quadspi_ar::W) writer structure"]
impl crate::Writable for QUADSPI_AR {}
#[doc = "QUADSPI address register"]
pub mod quadspi_ar;
#[doc = "QUADSPI alternate bytes registers\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_abr](quadspi_abr) module"]
pub type QUADSPI_ABR = crate::Reg<u32, _QUADSPI_ABR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_ABR;
#[doc = "`read()` method returns [quadspi_abr::R](quadspi_abr::R) reader structure"]
impl crate::Readable for QUADSPI_ABR {}
#[doc = "`write(|w| ..)` method takes [quadspi_abr::W](quadspi_abr::W) writer structure"]
impl crate::Writable for QUADSPI_ABR {}
#[doc = "QUADSPI alternate bytes registers"]
pub mod quadspi_abr;
#[doc = "QUADSPI data register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_dr](quadspi_dr) module"]
pub type QUADSPI_DR = crate::Reg<u32, _QUADSPI_DR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_DR;
#[doc = "`read()` method returns [quadspi_dr::R](quadspi_dr::R) reader structure"]
impl crate::Readable for QUADSPI_DR {}
#[doc = "`write(|w| ..)` method takes [quadspi_dr::W](quadspi_dr::W) writer structure"]
impl crate::Writable for QUADSPI_DR {}
#[doc = "QUADSPI data register"]
pub mod quadspi_dr;
#[doc = "QUADSPI polling status mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_psmkr](quadspi_psmkr) module"]
pub type QUADSPI_PSMKR = crate::Reg<u32, _QUADSPI_PSMKR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_PSMKR;
#[doc = "`read()` method returns [quadspi_psmkr::R](quadspi_psmkr::R) reader structure"]
impl crate::Readable for QUADSPI_PSMKR {}
#[doc = "`write(|w| ..)` method takes [quadspi_psmkr::W](quadspi_psmkr::W) writer structure"]
impl crate::Writable for QUADSPI_PSMKR {}
#[doc = "QUADSPI polling status mask register"]
pub mod quadspi_psmkr;
#[doc = "QUADSPI polling status match register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_psmar](quadspi_psmar) module"]
pub type QUADSPI_PSMAR = crate::Reg<u32, _QUADSPI_PSMAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_PSMAR;
#[doc = "`read()` method returns [quadspi_psmar::R](quadspi_psmar::R) reader structure"]
impl crate::Readable for QUADSPI_PSMAR {}
#[doc = "`write(|w| ..)` method takes [quadspi_psmar::W](quadspi_psmar::W) writer structure"]
impl crate::Writable for QUADSPI_PSMAR {}
#[doc = "QUADSPI polling status match register"]
pub mod quadspi_psmar;
#[doc = "QUADSPI polling interval register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_pir](quadspi_pir) module"]
pub type QUADSPI_PIR = crate::Reg<u32, _QUADSPI_PIR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_PIR;
#[doc = "`read()` method returns [quadspi_pir::R](quadspi_pir::R) reader structure"]
impl crate::Readable for QUADSPI_PIR {}
#[doc = "`write(|w| ..)` method takes [quadspi_pir::W](quadspi_pir::W) writer structure"]
impl crate::Writable for QUADSPI_PIR {}
#[doc = "QUADSPI polling interval register"]
pub mod quadspi_pir;
#[doc = "QUADSPI low-power timeout register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_lptr](quadspi_lptr) module"]
pub type QUADSPI_LPTR = crate::Reg<u32, _QUADSPI_LPTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_LPTR;
#[doc = "`read()` method returns [quadspi_lptr::R](quadspi_lptr::R) reader structure"]
impl crate::Readable for QUADSPI_LPTR {}
#[doc = "`write(|w| ..)` method takes [quadspi_lptr::W](quadspi_lptr::W) writer structure"]
impl crate::Writable for QUADSPI_LPTR {}
#[doc = "QUADSPI low-power timeout register"]
pub mod quadspi_lptr;
#[doc = "QUADSPI HW configuration register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_hwcfgr](quadspi_hwcfgr) module"]
pub type QUADSPI_HWCFGR = crate::Reg<u32, _QUADSPI_HWCFGR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_HWCFGR;
#[doc = "`read()` method returns [quadspi_hwcfgr::R](quadspi_hwcfgr::R) reader structure"]
impl crate::Readable for QUADSPI_HWCFGR {}
#[doc = "QUADSPI HW configuration register"]
pub mod quadspi_hwcfgr;
#[doc = "QUADSPI version register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_verr](quadspi_verr) module"]
pub type QUADSPI_VERR = crate::Reg<u32, _QUADSPI_VERR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_VERR;
#[doc = "`read()` method returns [quadspi_verr::R](quadspi_verr::R) reader structure"]
impl crate::Readable for QUADSPI_VERR {}
#[doc = "QUADSPI version register"]
pub mod quadspi_verr;
#[doc = "QUADSPI identification register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_ipidr](quadspi_ipidr) module"]
pub type QUADSPI_IPIDR = crate::Reg<u32, _QUADSPI_IPIDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_IPIDR;
#[doc = "`read()` method returns [quadspi_ipidr::R](quadspi_ipidr::R) reader structure"]
impl crate::Readable for QUADSPI_IPIDR {}
#[doc = "QUADSPI identification register"]
pub mod quadspi_ipidr;
#[doc = "QUADSPI size identification register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [quadspi_sidr](quadspi_sidr) module"]
pub type QUADSPI_SIDR = crate::Reg<u32, _QUADSPI_SIDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _QUADSPI_SIDR;
#[doc = "`read()` method returns [quadspi_sidr::R](quadspi_sidr::R) reader structure"]
impl crate::Readable for QUADSPI_SIDR {}
#[doc = "QUADSPI size identification register"]
pub mod quadspi_sidr;
|
use std::fmt::Display;
use bonsaidb_core::schema::CollectionName;
use serde::{Deserialize, Serialize};
use self::{integrity_scanner::IntegrityScan, mapper::Map};
#[derive(Debug, Serialize, Deserialize)]
pub struct ViewEntry {
pub view_version: u64,
pub key: Vec<u8>,
pub mappings: Vec<EntryMapping>,
pub reduced_value: Vec<u8>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct EntryMapping {
pub source: u64,
pub value: Vec<u8>,
}
pub mod integrity_scanner;
pub mod mapper;
pub fn view_entries_tree_name(view_name: &impl Display) -> String {
format!("view.{}", view_name)
}
/// Used to store Document ID -> Key mappings, so that when a document is updated, we can remove the old entry.
pub fn view_document_map_tree_name(view_name: &impl Display) -> String {
format!("view.{}.document-map", view_name)
}
pub fn view_invalidated_docs_tree_name(view_name: &impl Display) -> String {
format!("view.{}.invalidated", view_name)
}
pub fn view_omitted_docs_tree_name(view_name: &impl Display) -> String {
format!("view.{}.omitted", view_name)
}
pub fn view_versions_tree_name(collection: &CollectionName) -> String {
format!("view-versions.{}", collection)
}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub enum Task {
IntegrityScan(IntegrityScan),
ViewMap(Map),
}
|
#![feature(alloc_system)]
extern crate alloc_system;
extern crate fuse;
extern crate libc;
#[cfg(feature = "logging")]
extern crate log;
#[cfg(feature = "logging")]
extern crate simplelog;
extern crate tempdir;
extern crate time;
extern crate zip;
mod event;
mod fs;
use fs::AppImageFileSystem;
use std::env;
use std::fs::read_link;
use std::os::unix::process::ExitStatusExt;
use std::process::{exit, Command};
use std::thread;
use tempdir::TempDir;
macro_rules! printerr {
($fmt:expr) => {
use std::io::{stderr, Write};
let _ = writeln!(stderr(), $fmt);
};
($fmt:expr, $($arg:tt)*) => {
use std::io::{stderr, Write};
let _ = writeln!(stderr(), $fmt, $($arg)*);
};
}
fn run() -> i32 {
#[cfg(feature = "logging")]
let _ = simplelog::TermLogger::init(log::LogLevelFilter::Debug, simplelog::Config::default());
// Open this binary as an AppImage file system.
let file_system = match AppImageFileSystem::open_self() {
Some(v) => v,
None => {
printerr!("Cannot read AppImage filesystem, binary could be corrupt.");
return 70;
},
};
// Prepare a temporary directory to mount the file system image to.
let mount_dir = match TempDir::new("appimage") {
Ok(v) => v,
Err(_) => {
printerr!("Failed to create mount directory.");
return 75;
},
};
let mount_path = mount_dir.path().to_path_buf();
// Mount the filesystem image in a background thread.
let ready = file_system.ready();
let session = unsafe {
match fuse::spawn_mount(file_system, &mount_path, &[]) {
Ok(s) => s,
Err(e) => {
printerr!("Failed to mount FUSE file system: {}", e);
return 71;
},
}
};
// Some useful variable for the client application.
env::set_var("APPIMAGE", read_link("/proc/self/exe").unwrap());
env::set_var("APPDIR", mount_dir.path());
let mut app_run_path = mount_dir.path().to_path_buf();
app_run_path.push("AppRun");
// Wait for the file system to be initialized.
ready.wait();
// Run the client application and capture the exit status.
let status = match Command::new(&app_run_path).args(env::args()).status() {
Ok(s) => s,
Err(e) => {
printerr!("Failed to execute {:?}: {}", app_run_path, e);
return 70;
},
};
// thread::sleep_ms(60000);
// Unmount the file system and remove the mount directory.
drop(session);
drop(mount_dir);
// Return the exit status of the client application. If the application was terminated via a signal, instead return
// 128 + signum.
status.code().unwrap_or(128 + status.signal().unwrap_or(0))
}
fn main() {
exit(run());
}
|
use crate::lib::environment::Environment;
use crate::lib::error::DfxResult;
use crate::lib::nns_types::account_identifier::{AccountIdentifier, Subaccount};
use crate::lib::nns_types::icpts::ICPTs;
use crate::lib::nns_types::{
BlockHeight, CyclesResponse, Memo, NotifyCanisterArgs, SendArgs, CYCLE_MINTER_CANISTER_ID,
LEDGER_CANISTER_ID,
};
use crate::lib::provider::create_agent_environment;
use crate::lib::root_key::fetch_root_key_if_needed;
use crate::lib::waiter::waiter_with_timeout;
use crate::util::expiry_duration;
use anyhow::anyhow;
use candid::{Decode, Encode};
use clap::Clap;
use ic_types::principal::Principal;
use std::str::FromStr;
use tokio::runtime::Runtime;
const SEND_METHOD: &str = "send_dfx";
const NOTIFY_METHOD: &str = "notify_dfx";
mod account_id;
mod balance;
mod create_canister;
mod notify;
mod top_up;
mod transfer;
/// Ledger commands.
#[derive(Clap)]
#[clap(name("ledger"))]
pub struct LedgerOpts {
/// Override the compute network to connect to. By default, the local network is used.
#[clap(long)]
network: Option<String>,
#[clap(subcommand)]
subcmd: SubCommand,
}
#[derive(Clap)]
enum SubCommand {
AccountId(account_id::AccountIdOpts),
Balance(balance::BalanceOpts),
CreateCanister(create_canister::CreateCanisterOpts),
Notify(notify::NotifyOpts),
TopUp(top_up::TopUpOpts),
Transfer(transfer::TransferOpts),
}
pub fn exec(env: &dyn Environment, opts: LedgerOpts) -> DfxResult {
let agent_env = create_agent_environment(env, opts.network.clone())?;
let runtime = Runtime::new().expect("Unable to create a runtime");
runtime.block_on(async {
match opts.subcmd {
SubCommand::AccountId(v) => account_id::exec(&agent_env, v).await,
SubCommand::Balance(v) => balance::exec(&agent_env, v).await,
SubCommand::CreateCanister(v) => create_canister::exec(&agent_env, v).await,
SubCommand::Notify(v) => notify::exec(&agent_env, v).await,
SubCommand::TopUp(v) => top_up::exec(&agent_env, v).await,
SubCommand::Transfer(v) => transfer::exec(&agent_env, v).await,
}
})
}
fn get_icpts_from_args(
amount: Option<String>,
icp: Option<String>,
e8s: Option<String>,
) -> DfxResult<ICPTs> {
if amount.is_none() {
let icp = match icp {
Some(s) => {
// validated by e8s_validator
let icps = s.parse::<u64>().unwrap();
ICPTs::from_icpts(icps).map_err(|err| anyhow!(err))?
}
None => ICPTs::from_e8s(0),
};
let icp_from_e8s = match e8s {
Some(s) => {
// validated by e8s_validator
let e8s = s.parse::<u64>().unwrap();
ICPTs::from_e8s(e8s)
}
None => ICPTs::from_e8s(0),
};
let amount = icp + icp_from_e8s;
Ok(amount.map_err(|err| anyhow!(err))?)
} else {
Ok(ICPTs::from_str(&amount.unwrap())
.map_err(|err| anyhow!("Could not add ICPs and e8s: {}", err))?)
}
}
async fn send_and_notify(
env: &dyn Environment,
memo: Memo,
amount: ICPTs,
fee: ICPTs,
to_subaccount: Option<Subaccount>,
max_fee: ICPTs,
) -> DfxResult<CyclesResponse> {
let ledger_canister_id = Principal::from_text(LEDGER_CANISTER_ID)?;
let cycle_minter_id = Principal::from_text(CYCLE_MINTER_CANISTER_ID)?;
let agent = env
.get_agent()
.ok_or_else(|| anyhow!("Cannot get HTTP client from environment."))?;
fetch_root_key_if_needed(env).await?;
let to = AccountIdentifier::new(cycle_minter_id.clone(), to_subaccount);
let result = agent
.update(&ledger_canister_id, SEND_METHOD)
.with_arg(Encode!(&SendArgs {
memo,
amount,
fee,
from_subaccount: None,
to,
created_at_time: None,
})?)
.call_and_wait(waiter_with_timeout(expiry_duration()))
.await?;
let block_height = Decode!(&result, BlockHeight)?;
println!("Transfer sent at BlockHeight: {}", block_height);
let result = agent
.update(&ledger_canister_id, NOTIFY_METHOD)
.with_arg(Encode!(&NotifyCanisterArgs {
block_height,
max_fee,
from_subaccount: None,
to_canister: cycle_minter_id,
to_subaccount,
})?)
.call_and_wait(waiter_with_timeout(expiry_duration()))
.await?;
let result = Decode!(&result, CyclesResponse)?;
Ok(result)
}
|
/// Permutator. I don't recommend that you use this interface for obtaining the
/// permutations because in order to make the permute function as fast as
/// possible, safety was thrown away. That being said, HeapPermutor can be
/// faster than the iterator because it isn't required to create a new Vec for
/// each yield. In practice it's about a 0.5ns speed gain and extra
/// responsibility. So unless you need it, I can't recommend it.
pub struct HeapPermutor {
finished: bool,
index: usize,
stack: Vec<usize>,
}
impl HeapPermutor {
/// Create a new heap permutor. The stack size argument should be the size
/// of the Vec that's going to be permuted.
pub fn new<'b>(size: usize) -> HeapPermutor {
HeapPermutor {
finished: false,
index: 1,
stack: Vec::with_capacity(size),
}
}
// /// Using permute on a Vec not of length size(from HeapPermutor::new) will
// /// result in undefined behaviour.
// /// # Contract
// /// - Never modify the struct field values unless you know what you're doing
// /// - Ensure that the `source.len()` is equal to `self.stack.len()`
// ///
// pub unsafe fn permute<T>(&mut self, source: &mut Vec<T>) {
// }
#[inline]
pub fn finished(&self) -> bool {
self.finished
}
}
use crate::{Permutor, Permutable};
/// Heap permute implementation
impl Permutor for HeapPermutor {
fn permute(&mut self, source: &mut impl Permutable) {
let stack = self.stack.as_mut_ptr();
while self.index < source.length() {
unsafe {
if *stack.add(self.index) < self.index {
// Swap based on index parity
if self.index % 2 == 0 {
source.switch(0, self.index);
} else {
source.switch(*stack.add(self.index), self.index);
}
// Increment loop counter
*stack.add(self.index) += 1;
// "Simulate recursive call reaching the base case by bringing the pointer to the base case analog in the array"
self.index = 1;
return;
} else {
// Loop terminated, reset state and simulate stack pop
*stack.add(self.index) = 0;
self.index += 1;
}
}
}
// We managed to reach the end of the function, looping is done, and we have completed a cycle of permutation
self.finished = true;
}
}
|
// https://www.codewars.com/kata/weight-for-weight
use std::cmp::Ordering;
fn order_weight(s: &str) -> String {
let weight = |x: &str| x.chars().map(|c| c.to_digit(10).unwrap()).sum::<u32>();
let mut nums: Vec<&str> = s
.split_whitespace()
.collect();
nums.sort_unstable_by(|a, b| {
let res = weight(a).cmp(&weight(b));
match res {
Ordering::Equal => a.cmp(b),
_ => res
}
});
nums.join(" ")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_order_weight() {
let tests = vec![
("100", "100"),
("100 101", "100 101"),
("101 100", "100 101"),
("103 123 4444 99 2000", "2000 103 123 4444 99"),
("2000 10003 1234000 44444444 9999 11 11 22 123", "11 11 2000 10003 22 123 1234000 44444444 9999"),
];
for test in tests {
assert_eq!(order_weight(&test.0), test.1);
}
}
}
|
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::collections::LookupMap;
use near_sdk::json_types::{U128, U64};
use near_sdk::wee_alloc::WeeAlloc;
use near_sdk::{env, near_bindgen};
#[global_allocator]
static ALLOC: WeeAlloc = WeeAlloc::INIT;
pub type Base64String = String;
const VERSION: u128 = 0;
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct MockV3Aggregator {
pub decimals: u128,
pub latest_answer: u128,
pub latest_timestamp: u128,
pub latest_round: u128,
pub get_answer: LookupMap<u128, u128>,
pub get_timestamp: LookupMap<u128, u128>,
get_started_at: LookupMap<u128, u128>,
}
impl Default for MockV3Aggregator {
fn default() -> Self {
panic!("MockV3Aggregator should be initialized before usage");
}
}
/**
* @title MockV3Aggregator
* @notice Based on the FluxAggregator contract
* @notice Use this contract when you need to test
* other contract's ability to read data from an
* aggregator contract, but how the aggregator got
* its answer is unimportant
*/
#[near_bindgen]
impl MockV3Aggregator {
#[init]
pub fn new(_decimals: U128, _initial_answer: U128) -> Self {
let mut result = Self {
decimals: _decimals.into(),
latest_answer: 0,
latest_timestamp: 0,
latest_round: 0,
get_answer: LookupMap::new(b"get_answer".to_vec()),
get_timestamp: LookupMap::new(b"get_timestamp".to_vec()),
get_started_at: LookupMap::new(b"get_started_at".to_vec()),
};
result.update_answer(_initial_answer);
result
}
pub fn update_answer(&mut self, _answer: U128) {
let new_round: u128 = self.latest_round + 1;
let current_timestamp: u64 = env::block_timestamp();
let transformed_answer: u128 = _answer.into();
self.latest_answer = transformed_answer;
self.latest_timestamp = u128::from(current_timestamp);
self.latest_round = new_round;
let get_answer = self.get_answer.get(&new_round);
if get_answer.is_none() {
self.get_answer.insert(&new_round, &transformed_answer);
} else {
self.get_answer.remove(&new_round);
self.get_answer.insert(&new_round, &transformed_answer);
}
let get_timestamp = self.get_timestamp.get(&new_round);
if get_timestamp.is_none() {
self.get_timestamp
.insert(&new_round, &u128::from(current_timestamp));
} else {
self.get_timestamp.remove(&new_round);
self.get_timestamp
.insert(&new_round, &u128::from(current_timestamp));
}
let get_started_at = self.get_started_at.get(&new_round);
if get_started_at.is_none() {
self.get_started_at
.insert(&new_round, &u128::from(current_timestamp));
} else {
self.get_started_at.remove(&new_round);
self.get_started_at
.insert(&new_round, &u128::from(current_timestamp));
}
}
pub fn update_round_data(
&mut self,
_round_id: U128,
_answer: U128,
_timestamp: U128,
_started_at: U128,
) {
let transformed_round: u128 = _round_id.into();
let transformed_timestamp: u128 = u128::from(env::block_timestamp());
let transformed_answer: u128 = _answer.into();
let transformed_started_at: u128 = _started_at.into();
self.latest_answer = transformed_answer;
self.latest_timestamp = transformed_timestamp;
self.latest_round = transformed_round;
let get_answer = self.get_answer.get(&transformed_round);
if get_answer.is_none() {
self.get_answer.insert(&transformed_round, &transformed_answer);
} else {
self.get_answer.remove(&transformed_round);
self.get_answer
.insert(&transformed_round, &transformed_answer);
}
let get_timestamp = self.get_timestamp.get(&transformed_round);
if get_timestamp.is_none() {
self.get_timestamp.insert(&transformed_round, &transformed_timestamp);
} else {
self.get_timestamp.remove(&transformed_round);
self.get_timestamp
.insert(&transformed_round, &transformed_timestamp);
}
let get_started_at = self.get_started_at.get(&transformed_round);
if get_started_at.is_none() {
self.get_started_at.insert(&transformed_round, &transformed_started_at);
} else {
self.get_started_at.remove(&transformed_round);
self.get_started_at
.insert(&transformed_round, &transformed_started_at);
}
}
pub fn get_round_data(&self, _round_id: U128) -> (u128, u128, u128, u128, u128) {
let round_id: u128 = u128::from(_round_id);
let answer = self.get_answer.get(&round_id);
if answer.is_none() {
env::panic(b"Answer not available");
}
let started_at = self.get_started_at.get(&round_id);
if started_at.is_none() {
env::panic(b"Timestamp not available");
}
let timestamp = self.get_timestamp.get(&round_id);
if timestamp.is_none() {
env::panic(b"Timestamp not available");
}
return (
round_id,
answer.unwrap(),
started_at.unwrap(),
timestamp.unwrap(),
round_id
);
}
pub fn latest_round_data(&self) -> (u128, u128, u128, u128, u128) {
let answer = self.get_answer.get(&self.latest_round);
if answer.is_none() {
env::panic(b"Answer not available");
}
let started_at = self.get_started_at.get(&self.latest_round);
if started_at.is_none() {
env::panic(b"Timestamp not available");
}
let timestamp = self.get_timestamp.get(&self.latest_round);
if timestamp.is_none() {
env::panic(b"Timestamp not available");
}
return (
self.latest_round,
answer.unwrap(),
started_at.unwrap(),
timestamp.unwrap(),
self.latest_round,
);
}
pub fn latest_answer(&self) -> u128 {
self.latest_answer
}
pub fn latest_timestamp(&self) -> u128 {
self.latest_timestamp
}
pub fn latest_round(&self) -> u128 {
self.latest_round
}
pub fn get_answer(&self, _round_id: U128) -> u128 {
let round_id: u128 = u128::from(_round_id);
let answer = self.get_answer.get(&round_id);
if answer.is_none() {
env::panic(b"Answer not available");
}
answer.unwrap()
}
pub fn get_timestamp(&self, _round_id: U128) -> u128 {
let round_id: u128 = u128::from(_round_id);
let timestamp = self.get_timestamp.get(&round_id);
if timestamp.is_none() {
env::panic(b"timestamp not available");
}
timestamp.unwrap()
}
pub fn get_description(&self) -> String {
String::from("v0.6/tests/MockV3Aggregator.sol")
}
pub fn get_decimals(&self) -> u128 {
self.decimals
}
pub fn get_version(&self) -> u128 {
VERSION
}
}
|
//! nock implements a nock interpreter.
// Copyright (2017) Jeremy A. Wall.
//
// 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 parser::{Noun, ParseError, atom};
use std::error;
use std::fmt;
use std::fmt::Display;
use std::collections::VecDeque;
make_error!(NockError, "NockError: {}\n");
impl From<ParseError> for NockError {
fn from(err: ParseError) -> Self {
Self::new_with_cause("AST Parse Error", Box::new(err))
}
}
fn slice_to_noun(nouns: &[Noun]) -> Result<Noun, NockError> {
if nouns.len() > 1 {
Ok(Noun::Cell(nouns.iter().cloned().collect()))
} else if nouns.len() == 1 {
Ok(nouns[0].clone())
} else {
Err(NockError::new("!! Nock Empty Cell"))
}
}
/// # Algorithm
/// Nock calculates tree addresses using an algorithm like so:
/// * 1 is the root of the tree.
/// * the right child or head of a node is 2n.
/// * the left child or tail is 2n+1.
///
/// We construct a path through a nock cell given an address by
/// following the following rules. The parent of a node address
/// is always that address divided by 2. For each parent address we
/// we calculate we check for whether it is odd or not. If the
/// address is even then we know that that address was a head
/// node and store true in that path. If the address was odd
/// then we know that that node was a tail and we output false.
///
/// This way when we follow a path we know which part of the tree
/// we should recurse down.
///
/// # Examples:
///
/// ### Given an address of 6
/// 6 is the head of 3
/// 3 is the tail of 1
///
/// Which yields a path of [false, true]
fn make_tree_path(addr: u64) -> Vec<bool> {
let mut ret = VecDeque::new();
let mut next = addr;
loop {
ret.push_front(next % 2 == 0);
next = next / 2;
if next <= 1 {
break;
}
}
let range = 0..ret.len();
let path = ret.drain(range).collect();
return path;
}
fn fas(subj: &Noun, addr: u64) -> Result<Noun, NockError> {
if addr == 0 {
return Err(NockError::new("!! Invalid slot address 0"));
}
if addr == 1 {
return Ok(subj.clone());
}
if addr == 2 {
return Ok(try!(subj.head()).clone());
}
if addr == 3 {
return slice_to_noun(try!(subj.tail()));
}
let path = make_tree_path(addr);
let mut subject = subj.clone();
for take_head in path {
subject = if take_head {
try!(subject.head()).clone()
} else {
try!(slice_to_noun(try!(subject.tail())))
}
}
Ok(subject)
}
#[cfg(test)]
#[test]
fn test_simple_fas() {
// /[1 [531 25 99]] is [531 25 99];
let cases = vec![(cell!(atom(531), atom(25), atom(99)), 1,
cell!(atom(531), atom(25), atom(99))),
// /[2 [531 25 99]] is 531;
(cell!(atom(531), atom(25), atom(99)), 2,
atom(531)),
// /[3 [531 25 99]] is [25 99];
(cell!(atom(531), atom(25), atom(99)), 3,
cell!(atom(25), atom(99))),
// /[6 [531 25 99]] is 25;
(cell!(atom(531), atom(25), atom(99)), 6,
atom(25)),
(cell!(atom(531), cell!(atom(25), atom(26)), atom(99)), 6,
cell!(atom(25), atom(26))),
(cell!(atom(531), cell!(atom(25), atom(26)), atom(99)), 12,
atom(25)),
(cell!(atom(531), cell!(atom(25), atom(26)), atom(99)), 13,
atom(26)),
];
for (subj, addr, expected) in cases {
assert_eq!(expected, fas(&subj, addr).unwrap());
}
// [12 [531 25 99]] crashes
}
#[cfg(test)]
#[test]
#[should_panic]
fn test_fas_crash() {
let cell = cell!(atom(531), atom(25), atom(99));
// We expect an error here so we crash.
fas(&cell, 12).unwrap();
}
// Returns 1 false for an Noun::Atom and 0 true for a Noun::Cell.
fn wut(noun: Noun) -> Noun {
match noun {
Noun::Atom(_) => atom(1),
Noun::Cell(_) => atom(0),
}
}
// lus increments a Noun::Atom but crashes for a Noun::Cell.
fn lus(noun: Noun) -> Result<Noun, NockError> {
match noun {
Noun::Atom(a) => Ok(atom(a + 1)),
Noun::Cell(_) => Err(NockError::new("!! Can't increment a cell")),
}
}
#[cfg(test)]
#[test]
fn test_lus() {
assert_eq!(lus(atom(1)).expect("Should be able to increment an atom"), atom(2));
}
#[cfg(test)]
#[test]
#[should_panic]
fn test_lus_crash() {
lus(cell!(atom(1), atom(2))).unwrap();
}
fn cmp_noun(a: &Noun, b: &[Noun]) -> Noun {
let truthy = atom(0);
let falsy = atom(1);
match a {
&Noun::Cell(ref list) => {
if b.len() == 1 {
if let Noun::Cell(ref list) = b[0] {
return cmp_noun(a, &list);
}
}
if list.len() != b.len() {
return falsy;
}
for (i, n) in list.iter().enumerate() {
if cmp_noun(n, &b[i..i+1]) == falsy {
return falsy;
}
}
return truthy;
}
&Noun::Atom(a) => {
if b.len() == 1 {
if let Noun::Atom(b) = b[0] {
if a == b {
return truthy;
}
}
}
return falsy;
}
}
}
// tis compares a Noun::Cell's head and tail Nouns for equality.
fn tis(noun: Noun) -> Result<Noun, NockError> {
match noun {
Noun::Atom(_) => Err(NockError::new("!! Can't compaire Atom like a cell")),
Noun::Cell(list) => {
if list.len() >= 2 {
Ok(cmp_noun(&list[0], &list[1..]))
} else {
Err(NockError::new("!! Can't compare a cell of only one Noun"))
}
}
}
}
#[cfg(test)]
#[test]
fn test_tis() {
assert_eq!(
tis(cell!(atom(1), atom(1))).expect("Should be able to compare a Noun::Cell"),
atom(0));
assert_eq!(
tis(cell!(atom(0), atom(1))).expect("Should be able to compare a Noun::Cell"),
atom(1));
assert_eq!(
tis(cell!(atom(0), cell!(atom(1), atom(2)))).expect("Should be able to compare a Noun::Cell"),
atom(1));
assert_eq!(
tis(cell!(cell!(atom(1), atom(2)), cell!(atom(1), atom(2))))
.expect("Should be able to compare a Noun::Cell"),
atom(0));
assert_eq!(
tis(cell!(cell!(atom(1), cell!(atom(2), atom(3)), atom(4)),
cell!(atom(1), cell!(atom(2), atom(3)), atom(4))))
.expect("Should be able to compare a Noun::Cell"),
atom(0));
}
#[cfg(test)]
#[test]
#[should_panic]
fn test_tis_crash_atom() {
tis(atom(1)).unwrap();
}
#[cfg(test)]
#[test]
#[should_panic]
fn test_tis_crash_cell() {
tis(cell!(atom(1))).unwrap();
}
/// compute computes a nock expression of type [subj formula] or atom
pub fn compute(noun: Noun) -> Result<Noun, NockError> {
match &noun {
&Noun::Atom(_) => nock_internal(&Noun::Atom(0), noun.clone()),
&Noun::Cell(ref list) => {
if list.len() >= 2 {
nock_internal(try!(noun.head()), try!(slice_to_noun(try!(noun.tail()))))
} else {
Err(NockError::new("!! Invalid Nock Expression"))
}
}
}
}
/// Evaluates a nock formula against a subj.
///
/// The head of the formula is expected to be a Noun::Atom or a Noun::Cell that
/// computes to a Noun::Atom with one of the following values.
///
/// * 0 fas or slot the nock tree addressing algorithm. expects an atom crashes
/// if it isn't.
/// * 1 return the tail unmodified a sort of nock identity function.
/// * 2 compute the nock evaluation of the tail against the subject.
/// * 3 wut or nock operation ? which returns the atom 1 if the tail is an atom
/// or the atom 0 if it's a cell.
/// * 4 lus increment the atom in the tail. crash if it's not an atom.
/// * 5 tis return 0 if the head and the tail of a cell are equal. 1 otherwise.
/// * 6 the nock macro for if then else.
/// * 7 \*[a 7 b c] -> *[a 2 b 1 c]
/// * 8 \*[a 8 b c] -> *[a 7 [[7 [0 1] b] 0 1] c]
/// * 9 \*[a 9 b c] -> *[a 7 c 2 [0 1] 0 b]
/// * 10
/// * \*[a 10 b c] -> *[a c]
/// * \*[a 10 [b c] d] -> *[a 8 c 7 [0 3] d]
/// * Anything else is a nock crash.
fn nock_internal(subj: &Noun, formula: Noun) -> Result<Noun, NockError> {
match formula {
Noun::Atom(_) => return Err(NockError::new(format!("!! Nock Infinite Loop"))),
cell => {
match try!(cell.head()) {
&Noun::Atom(a) => {
// We expect an instruction from 0 to 10
match a {
0 => {
let tail = try!(slice_to_noun(try!(cell.tail())));
if let Noun::Atom(b) = tail {
return fas(subj, b);
} else {
return Err(NockError::new(format!("!! not a slot index {}", tail)));
}
}
1 => {
return Ok(try!(slice_to_noun(try!(cell.tail()))));
}
2 => {
return Ok(try!(nock_internal(subj,
try!(slice_to_noun(try!(cell.tail()))))));
}
3 => {
return Ok(wut(try!(nock_internal(subj,
try!(slice_to_noun(
try!(cell.tail())))))));
}
4 => {
let tail_noun = try!(slice_to_noun(try!(cell.tail())));
if let Noun::Cell(_) = tail_noun {
return Ok(try!(lus(try!(nock_internal(subj, tail_noun)))));
}
return Ok(try!(lus(tail_noun)));
}
5 => {
return Ok(try!(tis(try!(slice_to_noun(try!(cell.tail()))))));
}
// macros
6 => {
let tail = try!(cell.tail());
if tail.len() < 3 {
return Err(NockError::new("!! Need 3 Nouns for macro 6"));
}
let b = tail[0].clone();
let c = tail[1].clone();
let d = try!(slice_to_noun(&tail[2..]));
// *[a 6 b c d] *[a 2 [0 1] 2 [1 c d] [1 0] 2 [1 2 3] [1 0] 4 4 b]
let formula = cell!(atom(2),
// [0 1]
cell!(atom(0), atom(1)),
// 2
atom(2),
// [1 c d]
cell!(atom(1), c, d),
// [1 0]
cell!(atom(1), atom(0)),
// 2
atom(2),
// [1 2 3]
cell!(atom(1), atom(2), atom(3)),
// [1 0]
cell!(atom(1), atom(0)),
// 4 4 b]
atom(4),
atom(4),
b);
return nock_internal(subj, formula);
}
7 => {
let tail = try!(cell.tail());
if tail.len() < 2 {
return Err(NockError::new("!! Need 2 Nouns for macro 7"));
}
let b = tail[0].clone();
let c = tail[1].clone();
// *[a 7 b c] -> *[a 2 b 1 c]
let formula = cell!(atom(2), b, atom(1), c);
return nock_internal(subj, formula);
}
8 => {
let tail = try!(cell.tail());
if tail.len() < 2 {
return Err(NockError::new("!! Need 2 Nouns for macro 8"));
}
let b = tail[0].clone();
let c = tail[1].clone();
// *[a 8 b c] *[a 7 [[7 [0 1] b] 0 1] c]
let formula = cell!(atom(7),
cell!(cell!(atom(7), cell!(atom(0), atom(1)), b),
atom(0),
atom(1)),
c);
return nock_internal(subj, formula);
}
9 => {
let tail = try!(cell.tail());
if tail.len() < 2 {
return Err(NockError::new("!! Need 2 Nouns for macro 9"));
}
let b = tail[0].clone();
let c = tail[1].clone();
// *[a 9 b c] *[a 7 c 2 [0 1] 0 b]
let formula =
cell!(atom(7), c, atom(2), cell!(atom(0), atom(1)), atom(0), b);
return nock_internal(subj, formula);
}
10 => {
let tail = try!(cell.tail());
if tail.len() < 2 {
return Err(NockError::new("!! Need at least 2 Nouns for macro 6"));
}
let b = tail[0].clone();
let c = tail[1].clone();
match b {
Noun::Atom(_) => {
// *[a 10 b c] *[a c]
// b is discarded.
return nock_internal(subj, c);
}
Noun::Cell(list) => {
let d = c;
// b is discarded.
let c = try!(slice_to_noun(&list[1..]));
// *[a 10 [b c] d] *[a 8 c 7 [0 3] d]
let formula =
cell!(atom(8), c, atom(7), cell!(atom(0), atom(3)), d);
return nock_internal(subj, formula);
}
}
}
_ => {
return Err(NockError::new(format!("!! Unknown Nock instruction {}",
a)));
}
}
}
head_formula => {
let head = try!(nock_internal(subj, head_formula.clone()));
let new_formula = try!(slice_to_noun(try!(cell.tail())));
let tail_noun = try!(nock_internal(subj, new_formula));
return Ok(cell!(head, tail_noun));
}
}
}
}
}
|
use std::cmp::Ordering;
#[derive(Debug, Serialize, Deserialize)]
pub struct Entry<T, U> {
pub key: T,
pub value: U,
}
impl<T, U> Ord for Entry<T, U>
where
T: Ord,
{
fn cmp(&self, other: &Entry<T, U>) -> Ordering {
self.key.cmp(&other.key)
}
}
impl<T, U> PartialOrd for Entry<T, U>
where
T: Ord,
{
fn partial_cmp(&self, other: &Entry<T, U>) -> Option<Ordering> {
Some(self.key.cmp(&other.key))
}
}
impl<T, U> PartialEq for Entry<T, U>
where
T: Ord,
{
fn eq(&self, other: &Entry<T, U>) -> bool {
self.key == other.key
}
}
impl<T, U> Eq for Entry<T, U> where T: Ord {}
|
#![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 PolicyAssignmentProperties {
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(rename = "policyDefinitionId", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
#[serde(rename = "notScopes", default, skip_serializing_if = "Vec::is_empty")]
pub not_scopes: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metadata: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PolicySku {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tier: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PolicyAssignment {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<PolicyAssignmentProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<PolicySku>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<Identity>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PolicyAssignmentListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PolicyAssignment>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Identity {
#[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<identity::Type>,
}
pub mod identity {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
SystemAssigned,
None,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(rename = "httpStatus", default, skip_serializing_if = "Option::is_none")]
pub http_status: Option<String>,
#[serde(rename = "errorCode", default, skip_serializing_if = "Option::is_none")]
pub error_code: Option<String>,
#[serde(rename = "errorMessage", default, skip_serializing_if = "Option::is_none")]
pub error_message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PolicyDefinitionProperties {
#[serde(rename = "policyType", default, skip_serializing_if = "Option::is_none")]
pub policy_type: Option<policy_definition_properties::PolicyType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mode: Option<String>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "policyRule", default, skip_serializing_if = "Option::is_none")]
pub policy_rule: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metadata: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
}
pub mod policy_definition_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PolicyType {
NotSpecified,
BuiltIn,
Custom,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PolicyDefinition {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<PolicyDefinitionProperties>,
#[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 PolicyDefinitionListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PolicyDefinition>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PolicySetDefinitionProperties {
#[serde(rename = "policyType", default, skip_serializing_if = "Option::is_none")]
pub policy_type: Option<policy_set_definition_properties::PolicyType>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metadata: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
#[serde(rename = "policyDefinitions")]
pub policy_definitions: Vec<PolicyDefinitionReference>,
}
pub mod policy_set_definition_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PolicyType {
NotSpecified,
BuiltIn,
Custom,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PolicyDefinitionReference {
#[serde(rename = "policyDefinitionId", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PolicySetDefinition {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<PolicySetDefinitionProperties>,
#[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 PolicySetDefinitionListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PolicySetDefinition>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
|
use delay_timer::cron_clock::{Schedule, ScheduleIteratorOwned};
use delay_timer::prelude::*;
use std::str::FromStr;
use std::sync::atomic::{
AtomicUsize,
Ordering::{Acquire, Release},
};
use std::sync::{
atomic::{AtomicI32, AtomicU64},
Arc,
};
use std::thread::{self, park_timeout};
use std::time::Duration;
use smol::Timer;
#[test]
fn go_works() {
// Coordinates the inner-Runtime with the external(test-thread) clock.
let expression = "0/2 * * * * * *";
let mut schedule_itertor: ScheduleIteratorOwned<Local> = Schedule::from_str(expression)
.unwrap()
.upcoming_owned(Local);
// schedule_itertor.next();
let mut next_exec_time;
let mut current_time;
let mut park_time = 2_000_000u64;
let delay_timer = DelayTimer::new();
let share_num = Arc::new(AtomicUsize::new(0));
let share_num_bunshin = share_num.clone();
let body = move |_| {
share_num_bunshin.fetch_add(1, Release);
create_default_delay_task_handler()
};
let task = TaskBuilder::default()
.set_frequency(Frequency::CountDown(3, expression))
.set_task_id(1)
.spawn(body)
.unwrap();
delay_timer.add_task(task).unwrap();
let mut i = 0;
for _ in 0..3 {
debug_assert_eq!(i, share_num.load(Acquire));
park_timeout(Duration::from_micros(park_time + 1_000_000));
//Testing, whether the mission is performing as expected.
i = i + 1;
// Coordinates the inner-Runtime with the external(test-thread) clock.(200_000 is a buffer.)
next_exec_time = dbg!(schedule_itertor.next().unwrap().timestamp_millis()) as u128 * 1000;
current_time = get_timestamp_micros();
park_time = next_exec_time
.checked_sub(current_time)
.unwrap_or(1_000_000) as u64;
}
}
#[test]
fn test_maximun_parallel_runable_num() {
let delay_timer = DelayTimer::new();
let share_num = Arc::new(AtomicU64::new(0));
let share_num_bunshin = share_num.clone();
let body = create_async_fn_body!((share_num_bunshin){
dbg!();
share_num_bunshin_ref.fetch_add(1, Release);
Timer::after(Duration::from_secs(9)).await;
share_num_bunshin_ref.fetch_sub(1, Release);
});
let task = TaskBuilder::default()
.set_frequency_by_candy(CandyFrequency::CountDown(4, CandyCron::Secondly))
.set_task_id(1)
.set_maximun_parallel_runable_num(3)
.spawn(body)
.unwrap();
delay_timer.add_task(task).unwrap();
for i in 1..=6 {
park_timeout(Duration::from_micros(1_000_000 * i));
//Testing, whether the mission is performing as expected.
debug_assert!(dbg!(share_num.load(Acquire)) <= i);
}
}
#[test]
fn tests_countdown() {
let delay_timer = DelayTimer::new();
let share_num = Arc::new(AtomicI32::new(3));
let share_num_bunshin = share_num.clone();
let body = move |_| {
share_num_bunshin.fetch_sub(1, Release);
create_default_delay_task_handler()
};
let task = TaskBuilder::default()
.set_frequency(Frequency::CountDown(3, "0/2 * * * * * *"))
.set_task_id(1)
.spawn(body)
.unwrap();
delay_timer.add_task(task).unwrap();
let mut i = 0;
loop {
i = i + 1;
park_timeout(Duration::from_secs(3));
if i == 6 {
//The task runs 3 times, once per second, and after 6 seconds it goes down to 0 at most.
assert_eq!(0, share_num.load(Acquire));
break;
}
}
}
#[test]
fn inspect_struct() {
use tokio::runtime::Runtime;
println!("Task size :{:?}", std::mem::size_of::<Task>());
println!("Frequency size :{:?}", std::mem::size_of::<Frequency>());
println!("TaskBuilder size :{:?}", std::mem::size_of::<TaskBuilder>());
println!("DelayTimer size :{:?}", std::mem::size_of::<DelayTimer>());
println!("Runtime size :{:?}", std::mem::size_of::<Runtime>());
println!(
"ScheduleIteratorOwned size :{:?}",
std::mem::size_of::<cron_clock::ScheduleIteratorOwned<cron_clock::Utc>>()
);
let mut s = cron_clock::Schedule::from_str("* * * * * * *")
.unwrap()
.upcoming_owned(cron_clock::Utc);
let mut s1 = s.clone();
println!("{:?}, {:?}", s.next(), s1.next());
thread::sleep(Duration::from_secs(1));
println!("{:?}, {:?}", s.next(), s1.next());
let mut s2 = s1.clone();
thread::sleep(Duration::from_secs(1));
println!("{:?}, {:?}", s.next(), s2.next());
}
|
// https://github.com/rust-lang/rfcs/pull/2522
#![feature(type_ascription)]
use failure::Error;
use itertools::{process_results, FoldWhile, Itertools};
use maplit::hashset;
use std::fs;
fn main() -> Result<(), Error> {
println!("day 1, part 1 = {}", solve_day1_part1()?);
println!("day 1, part 2 = {}", solve_day1_part2()?);
Ok(())
}
// https://adventofcode.com/2018/day/1
fn solve_day1_part1() -> Result<i32, Error> {
let input = fs::read_to_string("input/day-1")?;
input.lines().try_fold(0, |frequency, shift| {
// type ascription is needed here as [i32 + ?] is ambiguous
// turbo-fish could be used instead (as in [parse::<i32>])
Ok(frequency + (shift.parse()?: i32))
})
}
// https://adventofcode.com/2018/day/1#part2
fn solve_day1_part2() -> Result<i32, Error> {
let input = fs::read_to_string("input/day-1")?;
let mut seen = hashset![0];
Ok(process_results(
input.lines().cycle().map(str::parse),
|mut iter| {
iter.fold_while(0, |frequency, shift: i32| {
let frequency = frequency + shift;
if seen.insert(frequency) {
FoldWhile::Continue(frequency)
} else {
// computed frequency has been seen before
FoldWhile::Done(frequency)
}
})
.into_inner()
},
)?)
}
|
#[doc = "Register `FDCAN_TTLGT` reader"]
pub type R = crate::R<FDCAN_TTLGT_SPEC>;
#[doc = "Field `LT` reader - LT"]
pub type LT_R = crate::FieldReader<u16>;
#[doc = "Field `GT` reader - GT"]
pub type GT_R = crate::FieldReader<u16>;
impl R {
#[doc = "Bits 0:15 - LT"]
#[inline(always)]
pub fn lt(&self) -> LT_R {
LT_R::new((self.bits & 0xffff) as u16)
}
#[doc = "Bits 16:31 - GT"]
#[inline(always)]
pub fn gt(&self) -> GT_R {
GT_R::new(((self.bits >> 16) & 0xffff) as u16)
}
}
#[doc = "FDCAN TT local and global time register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fdcan_ttlgt::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct FDCAN_TTLGT_SPEC;
impl crate::RegisterSpec for FDCAN_TTLGT_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`fdcan_ttlgt::R`](R) reader structure"]
impl crate::Readable for FDCAN_TTLGT_SPEC {}
#[doc = "`reset()` method sets FDCAN_TTLGT to value 0"]
impl crate::Resettable for FDCAN_TTLGT_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//! Base traits for different implementations of JSONPath execution engines.
//!
//! Defines the [`Engine`] trait that provides different ways of retrieving
//! query results from input bytes, as well as [`Compiler`] which provides
//! a standalone entry point for compiling a [`JsonPathQuery`] into an [`Engine`].
pub mod error;
mod head_skipping;
pub mod main;
mod tail_skipping;
pub use main::MainEngine as RsonpathEngine;
use self::error::EngineError;
use crate::{
input::Input,
query::{automaton::Automaton, error::CompilerError, JsonPathQuery},
result::{Match, MatchCount, MatchIndex, Sink},
};
/// An engine that can run its query on a given input.
pub trait Engine {
/// Find the number of matches on the given [`Input`].
///
/// The result is equivalent to using [`matches`](Engine::matches) and counting the matches,
/// but in general is much more time and memory efficient.
///
/// # Errors
/// An appropriate [`EngineError`] is returned if the JSON input is malformed
/// and the syntax error is detected.
///
/// **Please note** that detecting malformed JSONs is not guaranteed.
/// Some glaring errors like mismatched braces or double quotes are raised,
/// but in general **the result of an engine run on an invalid JSON is undefined**.
/// It _is_ guaranteed that the computation terminates and does not panic.
fn count<I>(&self, input: &I) -> Result<MatchCount, EngineError>
where
I: Input;
/// Find the starting indices of matches on the given [`Input`] and write them to the [`Sink`].
///
/// The result is equivalent to using [`matches`](Engine::matches) and extracting the
/// [`Match::span.start_idx`],
/// but in general is much more time and memory efficient.
///
/// # Errors
/// An appropriate [`EngineError`] is returned if the JSON input is malformed
/// and the syntax error is detected.
///
/// **Please note** that detecting malformed JSONs is not guaranteed.
/// Some glaring errors like mismatched braces or double quotes are raised,
/// but in general **the result of an engine run on an invalid JSON is undefined**.
/// It _is_ guaranteed that the computation terminates and does not panic.
fn indices<I, S>(&self, input: &I, sink: &mut S) -> Result<(), EngineError>
where
I: Input,
S: Sink<MatchIndex>;
/// Find all matches on the given [`Input`] and write them to the [`Sink`].
///
/// # Errors
/// An appropriate [`EngineError`] is returned if the JSON input is malformed
/// and the syntax error is detected.
///
/// **Please note** that detecting malformed JSONs is not guaranteed.
/// Some glaring errors like mismatched braces or double quotes are raised,
/// but in general **the result of an engine run on an invalid JSON is undefined**.
/// It _is_ guaranteed that the computation terminates and does not panic.
fn matches<I, S>(&self, input: &I, sink: &mut S) -> Result<(), EngineError>
where
I: Input,
S: Sink<Match>;
}
/// An engine that can be created by compiling a [`JsonPathQuery`].
pub trait Compiler {
/// Concrete type of the [`Engines`](`Engine`) created,
/// parameterized with the lifetime of the input query.
type E<'q>: Engine + 'q;
/// Compile a [`JsonPathQuery`] into an [`Engine`].c
///
/// # Errors
/// An appropriate [`CompilerError`] is returned if the compiler
/// cannot handle the query.
fn compile_query(query: &JsonPathQuery) -> Result<Self::E<'_>, CompilerError>;
/// Turn a compiled [`Automaton`] into an [`Engine`].
fn from_compiled_query(automaton: Automaton<'_>) -> Self::E<'_>;
}
|
pub mod aead_poly1305;
pub mod chacha20poly1305;
pub mod salsa20;
pub mod chacha20;
pub mod poly1305;
pub mod hmac_sha2_256;
pub mod sha2_256;
pub mod sha2_384;
pub mod sha2_512;
pub mod ed25519;
pub mod curve25519;
pub mod hacl_policies;
pub mod nacl;
|
//
// Copyright 2020 The Project Oak Authors
//
// 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 super::Interceptor;
use log::error;
use oak_abi::proto::oak::identity::SignedChallenge;
use oak_sign::KeyPair;
use prost::Message;
use tonic::{metadata::MetadataValue, Code, Request, Status};
/// Intercepts gRPC requests and authenticates the client with the provided [`KeyPair`].
pub struct AuthInterceptor {
/// Key pair to use for authentication.
///
/// Ideally this would just be a reference instead of an actual value, but
/// [`tonic::Interceptor::new`] requires a `'static` lifetime, so it would need to be cloned
/// anyway in order to be used.
key_pair: KeyPair,
}
impl AuthInterceptor {
pub fn create(key_pair: KeyPair) -> Self {
Self { key_pair }
}
}
impl Interceptor for AuthInterceptor {
fn process(&self, request: Request<()>) -> Result<Request<()>, Status> {
let mut request = request;
let signature =
oak_sign::SignatureBundle::create(oak_abi::OAK_CHALLENGE.as_bytes(), &self.key_pair)
.map_err(|err| Status::new(Code::InvalidArgument, format!("{:?}", err)))?;
// Signed challenge
let signed_challenge = SignedChallenge {
signed_hash: signature.signed_hash,
public_key: self.key_pair.public_key_der().map_err(|err| {
error!("could not parse public key: {:?}", err);
tonic::Status::internal("could not parse public key")
})?,
};
let mut signed_challenge_bytes = Vec::new();
signed_challenge
.encode(&mut signed_challenge_bytes)
.map_err(|err| {
error!("could not encode signed challenge to protobuf: {:?}", err);
tonic::Status::internal("could not encode signed challenge to protobuf")
})?;
request.metadata_mut().insert_bin(
oak_abi::OAK_SIGNED_CHALLENGE_GRPC_METADATA_KEY,
MetadataValue::from_bytes(&signed_challenge_bytes),
);
Ok(request)
}
}
impl From<AuthInterceptor> for tonic::Interceptor {
fn from(interceptor: AuthInterceptor) -> Self {
tonic::Interceptor::new(move |request: Request<()>| interceptor.process(request))
}
}
|
mod empty;
pub use empty::*;
|
#[macro_use]
extern crate ispc;
extern crate embree_rs;
extern crate cgmath;
extern crate tobj;
extern crate docopt;
#[macro_use]
extern crate serde_derive;
extern crate rayon;
mod tile;
use std::path::Path;
use std::mem;
use std::ptr;
use cgmath::{Vector3, Vector4, InnerSpace};
use embree_rs::{Device, Geometry, IntersectContext, RayN, RayHitN, Scene,
TriangleMesh, CommittedScene};
use docopt::Docopt;
use rayon::prelude::*;
use tile::Tile;
ispc_module!(crescent);
static USAGE: &'static str = "
Usage:
crescent <objfile> [OPTIONS]
crescent (-h | --help)
Options:
-o <path> Specify the output file or directory to save the image or frames.
Supported formats are PNG, JPG and PPM.
--eye=<x,y,z> Specify the eye position for the camera.
--at=<x,y,z> Specify the position to point the camera at.
--up=<x,y,z> Specify the camera up vector.
-h, --help Show this message.
";
static WIDTH: usize = 512;
static HEIGHT: usize = 512;
#[derive(Deserialize)]
struct Args {
arg_objfile: String,
flag_eye: Option<String>,
flag_at: Option<String>,
flag_up: Option<String>,
flag_o: Option<String>,
}
fn parse_vec_arg(s: &str) -> Vec<f32> {
s.split(",").map(|x| x.parse::<f32>().unwrap()).collect()
}
fn main() {
let args: Args = Docopt::new(USAGE).and_then(|d| d.deserialize()).unwrap_or_else(|e| e.exit());
let device = Device::new();
let (models, _) = tobj::load_obj(&Path::new(&args.arg_objfile[..])).unwrap();
let mut tri_geoms = Vec::new();
for m in models.iter() {
let mesh = &m.mesh;
println!("Mesh has {} triangles and {} verts",
mesh.indices.len() / 3, mesh.positions.len() / 3);
let mut tris = TriangleMesh::unanimated(&device,
mesh.indices.len() / 3,
mesh.positions.len() / 3);
{
let mut verts = tris.vertex_buffer.map();
let mut tris = tris.index_buffer.map();
for i in 0..mesh.positions.len() / 3 {
verts[i] = Vector4::new(mesh.positions[i * 3],
mesh.positions[i * 3 + 1],
mesh.positions[i * 3 + 2],
0.0);
}
for i in 0..mesh.indices.len() / 3 {
tris[i] = Vector3::new(mesh.indices[i * 3],
mesh.indices[i * 3 + 1],
mesh.indices[i * 3 + 2]);
}
}
let mut tri_geom = Geometry::Triangle(tris);
tri_geom.commit();
tri_geoms.push(tri_geom);
}
let mut scene = Scene::new(&device);
let mut mesh_ids = Vec::with_capacity(models.len());
for g in tri_geoms.drain(0..) {
let id = scene.attach_geometry(g);
mesh_ids.push(id);
}
let rtscene = scene.commit();
// Make the image tiles to distribute rendering work
// TODO: Non-multiple of tile size images
let tile_size = (32, 32);
let mut tiles = Vec::new();
for j in 0..HEIGHT / tile_size.1 {
for i in 0..HEIGHT / tile_size.0 {
tiles.push(Tile::new(tile_size, (i * tile_size.0, j * tile_size.1)));
}
}
// TODO: Interactive viewer similar to rtobj
// Render the tiles
tiles.par_iter_mut().for_each(|mut tile| render_tile(&mut tile, &rtscene, &models, &mesh_ids));
// Now write the tiles into the final framebuffer to save out
let mut final_image = vec![0; WIDTH * HEIGHT * 3];
for t in tiles.iter() {
for j in 0..t.dims.1 {
let y = j + t.pos.1;
for i in 0..t.dims.0 {
let x = i + t.pos.0;
final_image[(x + y * WIDTH) * 3] = t.srgb[(i + j * t.dims.0) * 3];
final_image[(x + y * WIDTH) * 3 + 1] = t.srgb[(i + j * t.dims.0) * 3 + 1];
final_image[(x + y * WIDTH) * 3 + 2] = t.srgb[(i + j * t.dims.0) * 3 + 2];
}
}
}
let out_path =
if let Some(path) = args.flag_o {
path
} else {
String::from("crescent.png")
};
match image::save_buffer(&out_path[..], &final_image[..], WIDTH as u32, HEIGHT as u32,
image::RGB(8)) {
Ok(_) => println!("Rendered image saved to {}", out_path),
Err(e) => panic!("Error saving image: {}", e),
};
}
fn render_tile(tile: &mut Tile, rtscene: &CommittedScene,
models: &Vec<tobj::Model>, mesh_ids: &Vec<u32>) {
let mut intersection_ctx = IntersectContext::coherent();
// Generate a stream of rays for the entire tile
let mut rays = RayN::new(tile.dims.0 * tile.dims.1);
unsafe {
// TODO: Camera parameters
let mut sys_rays = rays.as_raynp();
crescent::generate_primary_rays(mem::transmute(&mut sys_rays),
tile.pos.0 as u32, tile.pos.1 as u32,
WIDTH as u32, HEIGHT as u32,
tile.dims.0 as u32, tile.dims.1 as u32);
}
let mut ray_hit = RayHitN::new(rays);
rtscene.intersect_stream_soa(&mut intersection_ctx, &mut ray_hit);
unsafe {
let mesh = &models[0].mesh;
let normals = if mesh.normals.is_empty() { ptr::null() } else { mesh.normals.as_ptr() };
crescent::shade_ray_stream(mem::transmute(&mut ray_hit.as_rayhitnp()),
tile.dims.0 as u32, tile.dims.1 as u32,
mesh.indices.as_ptr(),
mesh.positions.as_ptr(),
normals,
tile.img.as_mut_ptr());
crescent::image_to_srgb(tile.img.as_ptr(), tile.srgb.as_mut_ptr(),
tile.dims.0 as i32, tile.dims.1 as i32);
}
}
|
extern crate log;
extern crate specs;
extern crate simple_logger;
extern crate airmash_server;
use std::env;
use specs::Entity;
use airmash_server::*;
use airmash_server::protocol::GameType;
struct EmptyGameMode;
impl GameMode for EmptyGameMode {
fn assign_team(&mut self, player: Entity) -> Team {
Team(player.id() as u16)
}
fn spawn_pos(&mut self, _: Entity, _: Team) -> Position {
Position::default()
}
fn gametype(&self) -> GameType {
GameType::FFA
}
fn room(&self) -> String {
"matrix".to_owned()
}
}
fn main() {
simple_logger::init_with_level(log::Level::Info).unwrap();
env::set_var("RUST_BACKTRACE", "1");
AirmashServer::new("0.0.0.0:3501")
.with_engine()
.with_gamemode(EmptyGameMode)
.run();
}
|
extern crate cursive;
extern crate glob;
extern crate regex;
extern crate pretty_env_logger;
#[macro_use] extern crate log;
use cursive::Cursive;
use cursive::traits::Scrollable;
use cursive::views::Dialog;
use cursive::views::SelectView;
use glob::glob;
use regex::Regex;
use std::env;
use std::collections::HashSet;
use std::fs;
use std::process::Command;
use std::process::Stdio;
use std::str;
fn main() {
pretty_env_logger::init();
let manpath = Command::new("man").arg("--path").output().expect("unable to get man path");
let mut listed_link_targets = HashSet::new();
let re = Regex::new(r"man[^/]+/(.+?)\.([^.]+)(\.gz)?$").unwrap();
for page in env::args().skip(1) {
let mut section_select = SelectView::new();
for manprefix in manpath.stdout.split(|c| *c == b':').map(|p| str::from_utf8(p).unwrap()) {
debug!("Scanning {}", manprefix);
let pattern = format!("{}/man*/{}.*", manprefix, page);
let paths = glob(pattern.as_str()).expect("Pattern error");
for path in paths {
match path {
Ok(p) => {
match fs::canonicalize(p.clone()) {
Ok(link_target) => {
if listed_link_targets.contains(&link_target) {
if link_target == p {
debug!("Skipping already present {}", p.display());
} else {
debug!("Skipping already present {} (pointing to {})", p.display(), link_target.display());
}
} else {
if link_target == p {
debug!("Adding {}", p.display());
} else {
debug!("Adding {} (pointing to {})", p.display(), link_target.display());
}
let file = format!("{}", link_target.display());
let c = re.captures(file.as_str()).unwrap();
let page = format!("{}", c.get(1).map_or("", |m| m.as_str()));
let section = format!("{}", c.get(2).map_or("", |m| m.as_str()));
let label = format!("{} ({})", page, section);
section_select.add_item(label, (file,));
listed_link_targets.insert(link_target);
}
}
Err(e) => {
error!("Unable to canonicalize {}:\n{}", p.display(), e);
}
}
}
// Inaccessible directories are simply ignored,
// as man viewer probably cannot reach them either.
Err(_) => {}
};
}
}
section_select.set_on_submit(|s, &(ref file,)| {
s.quit();
Command::new("man")
.arg(file)
.stdout(Stdio::inherit())
.stdin(Stdio::inherit())
.stderr(Stdio::inherit())
.output()
.expect("failed to execute process");
});
let mut siv = Cursive::default();
siv.add_layer(Dialog::around(section_select.scrollable()).title("Which section do you wish to open?"));
siv.run();
}
}
|
#[doc = "Register `MACSTNR` reader"]
pub type R = crate::R<MACSTNR_SPEC>;
#[doc = "Field `TSSS` reader - Timestamp subseconds The value in this field has the subsecond representation of time, with an accuracy of 0.46 ns. When TSCTRLSSR is set in Timestamp control Register (ETH_MACTSCR), each bit represents 1 ns. The maximum value is 0x3B9A_C9FF after which it rolls-over to zero."]
pub type TSSS_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:30 - Timestamp subseconds The value in this field has the subsecond representation of time, with an accuracy of 0.46 ns. When TSCTRLSSR is set in Timestamp control Register (ETH_MACTSCR), each bit represents 1 ns. The maximum value is 0x3B9A_C9FF after which it rolls-over to zero."]
#[inline(always)]
pub fn tsss(&self) -> TSSS_R {
TSSS_R::new(self.bits & 0x7fff_ffff)
}
}
#[doc = "System time nanoseconds register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`macstnr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct MACSTNR_SPEC;
impl crate::RegisterSpec for MACSTNR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`macstnr::R`](R) reader structure"]
impl crate::Readable for MACSTNR_SPEC {}
#[doc = "`reset()` method sets MACSTNR to value 0"]
impl crate::Resettable for MACSTNR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2017 The developers of rdma-core. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT.
pub struct Context(pub(crate) *mut ibv_context, ibv_device_attr_ex);
impl Drop for Context
{
#[inline(always)]
fn drop(&mut self)
{
self.0.destroy();
}
}
impl Context
{
#[inline(always)]
fn new(pointer: *mut ibv_context) -> Self
{
debug_assert!(!pointer.is_null(), "pointer is null");
Context(pointer, pointer.extendedAttributes())
}
#[inline(always)]
pub fn port<'a>(&'a self, portNumber: u8) -> Port<'a>
{
debug_assert!(portNumber < self.numberOfPhysicalPorts(), "portNumber '{}' exceeds maximum number of ports '{}'", portNumber, self.numberOfPhysicalPorts());
Port::new(self, portNumber)
}
#[inline(always)]
pub fn data(&self) -> ibv_context
{
self.0.data()
}
/// See <https://linux.die.net/man/3/ibv_query_device> for explanations of fields of ibv_device_attr
#[inline(always)]
pub fn attributes(&self) -> &ibv_device_attr
{
&self.1.orig_attr
}
#[inline(always)]
pub fn extendedAttributes(&self) -> &ibv_device_attr_ex
{
&self.1
}
#[inline(always)]
pub fn queryRealTimeRawClock(&self) -> timespec
{
self.0.queryRealTimeRawClock()
}
#[inline(always)]
pub fn deviceHasCapability(&self, capability: ibv_device_cap_flags) -> bool
{
self.attributes().deviceHasCapability(capability)
}
#[inline(always)]
pub fn numberOfCompletionVectors(&self) -> u32
{
self.0.numberOfCompletionVectors()
}
#[inline(always)]
pub fn commandRawFd(&self) -> RawFd
{
self.0.commandRawFd()
}
#[inline(always)]
pub fn asyncRawFd(&self) -> RawFd
{
self.0.asyncRawFd()
}
#[inline(always)]
pub fn numberOfPhysicalPorts(&self) -> u8
{
self.attributes().numberOfPhysicalPorts()
}
/// See <https://linux.die.net/man/3/ibv_get_async_event>
#[inline(always)]
pub fn blockOnAsynchronousEvent(&self) -> AsynchronousEvent
{
AsynchronousEvent(self.0.blockOnAsynchronousEvent())
}
#[inline(always)]
pub fn allocateProtectionDomain<'a>(&'a self) -> ProtectionDomain<'a>
{
ProtectionDomain::new(self.0.allocateProtectionDomain(), self)
}
#[inline(always)]
pub fn createExtendedReliableConnectionDomainWithoutInode<'a>(&'a self) -> ExtendedReliableConnectionDomain<'a>
{
let pointer = self.openExtendedReliableConnectionDomainInternal(-1, true, false);
if unlikely(pointer.is_null())
{
let errno = errno();
panic!("{} failed with error number '{}' ('{}')", stringify!($function), errno.0, errno);
}
ExtendedReliableConnectionDomain
{
pointer: pointer,
context: self,
}
}
#[inline(always)]
fn openExtendedReliableConnectionDomainInternal<'a>(&'a self, fileDescriptor: RawFd, create: bool, exclusive: bool) -> *mut ibv_xrcd
{
const IBV_XRCD_INIT_ATTR_FD: u32 = 1;
const IBV_XRCD_INIT_ATTR_OFLAGS: u32 = 2;
const AllCurrentFields: u32 = IBV_XRCD_INIT_ATTR_FD | IBV_XRCD_INIT_ATTR_OFLAGS;
let mut openFlags = 0;
if create
{
openFlags = openFlags | O_CREAT;
}
if exclusive
{
openFlags = openFlags | O_EXCL;
}
if unlikely(fileDescriptor == -1 && !create)
{
panic!("create must be true if fileDescriptor is -1");
}
if unlikely(fileDescriptor == -1 && exclusive)
{
panic!("exclusive must be false if fileDescriptor is -1");
}
let mut attributes = ibv_xrcd_init_attr
{
comp_mask: AllCurrentFields,
fd: fileDescriptor,
oflags: openFlags,
};
unsafe { rust_ibv_open_xrcd(self.0, &mut attributes) }
}
// /// NOTE: This implementation is almost certainly currently broken
// /// The created object should be used as part of ibv_create_qp_ex() to enable dispatching of incoming packets based on some RX hash configuration.
// #[inline(always)]
// pub fn createReceiveWorkQueueIndirectionTable<'a>(&'a self, size: PowerOfTwoThirtyTwoBit) -> ReceiveWorkQueueIndirectionTable<'a>
// {
// let sizeU32 = size.as_u32();
//
// let mut indirectionTable = Vec::with_capacity(sizeU32 as usize);
//
// let mut attributes = ibv_rwq_ind_table_init_attr
// {
// log_ind_tbl_size: sizeU32,
// ind_tbl: indirectionTable.as_mut_ptr(),
// comp_mask: 0,
// };
//
// let pointer = panic_on_null!(rust_ibv_create_rwq_ind_table, self.0, &mut attributes);
// ReceiveWorkQueueIndirectionTable
// {
// pointer: pointer,
// context: self,
// indirectionTable: indirectionTable,
// }
// }
}
|
extern crate regex;
use regex::Regex;
use std::env;
use std::process;
fn print_usage_and_exit() {
println!("Usage: tun HOST:PORT");
println!("--------------------");
println!("Forwards localhost:PORT to HOST:PORT via SSH tunnel.");
process::exit(1);
}
fn main() {
if env::args().count() != 2 { print_usage_and_exit(); }
let arg = env::args().nth(1).unwrap();
let re = Regex::new(r"(.*):(\d+)").unwrap();
let captures_opt = re.captures(&arg);
if captures_opt.is_none() { print_usage_and_exit(); }
let captures = captures_opt.unwrap();
let host = &captures[1];
let port = &captures[2];
let status = process::Command::new("ssh")
.arg("-N")
.arg("-L")
.arg(format!("{port}:localhost:{port}", port=port))
.arg(host)
.status();
match status {
Ok(exit_status) => {
if exit_status.success() { process::exit(0); }
match exit_status.code() {
Some(exit_code) => { process::exit(exit_code); }
None => {}
}
}
Err(e) => {
println!("{}", e);
process::exit(2);
}
}
}
|
use exporter::Cake;
// This function will make compilation fail if T does not implement Cake.
fn assert_is_cake<T: Cake>() {}
mod a {
use super::*;
// This struct name starts with a Vowel, so the Cake proc_macro will
// generate a NewSchoolCake struct, followed by its Cake trait
// implementation.
#[derive(Cake)]
struct A;
// This functions checks at compile-time that Cake is implemented for
// NewSchoolCake.
fn test_cake_implementation() {
// Here, we get the following error:
//
// error[E0277]: the trait bound `a::NewSchoolCake: core::Cake` is not satisfied
// --> user/src/lib.rs:18:26
// |
// 4 | fn assert_is_cake<T: Cake>() {}
// | ---- required by this bound in `assert_is_cake`
// ...
// 28 | assert_is_cake::<NewSchoolCake>();
// | ^^^^^^^^^^^^^ the trait `core::Cake` is not implemented for `a::NewSchoolCake`
assert_is_cake::<NewSchoolCake>();
}
}
mod b {
use super::*;
// This struct name starts with a consonant, so the Cake proc_macro will
// generate the Cake trait implemetation of OldSchoolCake, followed by the
// OldSchoolCake declaration.
#[derive(Cake)]
struct B;
// This functions checks at compile-time that Cake is implemented for
// OldSchoolCake.
fn test_cake_implementation() {
assert_is_cake::<OldSchoolCake>();
}
}
|
//! Implements the Tockloader protocol.
//!
//! TockOS applications are loaded with `tockloader`.
//! This speaks to the TockOS bootloader using a specific
//! protocol. This crate implements that protocol so
//! that you can write future tockloader compatible bootloaders
//! in Rust!
#![no_std]
// ****************************************************************************
//
// Imports
//
// ****************************************************************************
extern crate byteorder;
use byteorder::{LittleEndian, ByteOrder};
pub mod prelude {
pub use super::Encoder;
}
// ****************************************************************************
//
// Public Types
//
// ****************************************************************************
/// Commands supported by the protocol. A bootloader will decode these and a
/// flash tool will encode them.
#[derive(Debug, PartialEq)]
pub enum Command<'a> {
/// Send a PING to the bootloader. It will drop its hp buffer and send
/// back a PONG.
Ping,
/// Get info about the bootloader. The result is one byte of length, plus
/// length bytes of string, followed by 192-length zeroes.
Info,
/// Get the Unique ID. Result is 8 bytes of unique ID (but I'm not sure
/// what the result code should be).
Id,
/// Reset all TX and RX buffers.
Reset,
/// Erase a page. The RX buffer should contain the address of the start of
/// the 512 byte page. Any non-page-aligned addresses will result in
/// RES_BADADDR. This command is not required before writing a page, it is
/// just an optimisation. It is particularly quick for already empty pages.
ErasePage { address: u32 },
/// Write a page in internal flash. The RX buffer should contain the 4
/// byte address of the start of the page, followed by 512 bytes of page.
WritePage { address: u32, data: &'a [u8] },
/// Erase a block of pages in ex flash. The RX buffer should contain the
/// address of the start of the block. Each block is 8 pages, so 2048
/// bytes.
EraseExBlock { address: u32 },
/// Write a page to ex flash. The RX buffer should contain the address of
/// the start of the 256 byte page, followed by 256 bytes of page.
WriteExPage { address: u32, data: &'a [u8] },
/// Get the length and CRC of the RX buffer. The response is two bytes of
/// little endian length, followed by 4 bytes of crc32.
CrcRxBuffer,
/// Read a range from internal flash. The RX buffer should contain a 4
/// byte address followed by 2 bytes of length. The response will be
/// length bytes long.
ReadRange { address: u32, length: u16 },
/// Read a range from external flash. The RX buffer should contain a 4
/// byte address followed by 2 bytes of length. The response will be
/// length bytes long.
ExReadRange { address: u32, length: u16 },
/// Write a payload attribute. The RX buffer should contain a one byte
/// index, 8 bytes of key (null padded), one byte of value length, and
/// valuelength value bytes. valuelength must be less than or equal to 55.
/// The value may contain nulls.
///
/// The attribute index must be less than 16.
SetAttr {
index: u8,
key: &'a [u8],
value: &'a [u8],
},
/// Get a payload attribute. The RX buffer should contain a 1 byte index.
/// The result is 8 bytes of key, 1 byte of value length, and 55 bytes of
/// potential value. You must discard 55-valuelength bytes from the end
/// yourself.
GetAttr { index: u8 },
/// Get the CRC of a range of internal flash. The RX buffer should contain
/// a four byte address and a four byte range. The result will be a four
/// byte crc32.
CrcIntFlash { address: u32, length: u32 },
/// Get the CRC of a range of external flash. The RX buffer should contain
/// a four byte address and a four byte range. The result will be a four
/// byte crc32.
CrcExtFlash { address: u32, length: u32 },
/// Erase a page in external flash. The RX buffer should contain a 4 byte
/// address pointing to the start of the 256 byte page.
EraseExPage { address: u32 },
/// Initialise the external flash chip. This sets the page size to 256b.
ExtFlashInit,
/// Go into an infinite loop with the 32khz clock present on pin PA19
/// (GP6) this is used for clock calibration.
ClockOut,
/// Write the flash user pages (first 4 bytes is first page, second 4
/// bytes is second page, little endian).
WriteFlashUserPages { page1: u32, page2: u32 },
/// Change the baud rate of the bootloader. The first byte is 0x01 to set
/// a new baud rate. The next 4 bytes are the new baud rate. To allow the
/// bootloader to verify that the new baud rate works, the host must call
/// this command again with the first byte of 0x02 and the next 4 bytes of
/// the new baud rate. If the next command does not match this, the
/// bootloader will revert to the old baud rate.
ChangeBaud { mode: BaudMode, baud: u32 },
}
/// Reponses supported by the protocol. A bootloader will encode these
/// and a flash tool will decode them.
#[derive(Debug, PartialEq)]
pub enum Response<'a> {
Overflow, // RES_OVERFLOW
Pong, // RES_PONG
BadAddress, // RES_BADADDR
InternalError, // RES_INTERROR
BadArguments, // RES_BADARGS
Ok, // RES_OK
Unknown, // RES_UNKNOWN
ExtFlashTimeout, // RES_XFTIMEOUT
ExtFlashPageError, // RES_XFEPE ??
CrcRxBuffer { length: u16, crc: u32 }, // RES_CRCRX
ReadRange { data: &'a [u8] }, // RES_RRANGE
ExReadRange { data: &'a [u8] }, // RES_XRRANGE
GetAttr { key: &'a [u8], value: &'a [u8] }, // RES_GATTR
CrcIntFlash { crc: u32 }, // RES_CRCIF
CrcExtFlash { crc: u32 }, // RES_CRCXF
Info { info: &'a [u8] }, // RES_INFO
ChangeBaudFail, // RES_CHANGE_BAUD_FAIL
}
#[derive(Debug, PartialEq)]
pub enum Error {
/// We got a command we didn't understand.
UnknownCommand,
/// We didn't like the arguments given with a command.
BadArguments,
/// The user didn't call `set_payload_len` yet we
/// got a response of unbounded length.
UnsetLength,
/// The user called `set_payload_len` yet we
/// got a response of bounded length.
SetLength,
/// The buffer passed by the user wasn't large enough for the packet.
BufferTooSmall,
}
/// The `ComandDecoder` takes bytes and gives you `Command`s.
pub struct CommandDecoder {
state: DecoderState,
buffer: [u8; 520],
count: usize,
}
/// The `ResponseDecoder` takes bytes and gives you `Responses`s.
pub struct ResponseDecoder {
state: DecoderState,
buffer: [u8; 520],
count: usize,
needed: Option<usize>,
}
/// The `CommandEncoder` takes a `Command` and gives you bytes.
pub struct CommandEncoder<'a> {
command: &'a Command<'a>,
count: usize,
sent_escape: bool,
}
/// The `ResponseEncoder` takes a `Response` and gives you bytes.
pub struct ResponseEncoder<'a> {
response: &'a Response<'a>,
count: usize,
sent_escape: bool,
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum BaudMode {
Set, // 0x01
Verify, // 0x02
}
// ****************************************************************************
//
// Public Data
//
// ****************************************************************************
// None
// ****************************************************************************
//
// Private Types
//
// ****************************************************************************
enum DecoderState {
Loading,
Escape,
}
// ****************************************************************************
//
// Private Data
//
// ****************************************************************************
const ESCAPE_CHAR: u8 = 0xFC;
const CMD_PING: u8 = 0x01;
const CMD_INFO: u8 = 0x03;
const CMD_ID: u8 = 0x04;
const CMD_RESET: u8 = 0x05;
const CMD_EPAGE: u8 = 0x06;
const CMD_WPAGE: u8 = 0x07;
const CMD_XEBLOCK: u8 = 0x08;
const CMD_XWPAGE: u8 = 0x09;
const CMD_CRCRX: u8 = 0x10;
const CMD_RRANGE: u8 = 0x11;
const CMD_XRRANGE: u8 = 0x12;
const CMD_SATTR: u8 = 0x13;
const CMD_GATTR: u8 = 0x14;
const CMD_CRCIF: u8 = 0x15;
const CMD_CRCEF: u8 = 0x16;
const CMD_XEPAGE: u8 = 0x17;
const CMD_XFINIT: u8 = 0x18;
const CMD_CLKOUT: u8 = 0x19;
const CMD_WUSER: u8 = 0x20;
const CMD_CHANGE_BAUD: u8 = 0x21;
const RES_OVERFLOW: u8 = 0x10;
const RES_PONG: u8 = 0x11;
const RES_BADADDR: u8 = 0x12;
const RES_INTERROR: u8 = 0x13;
const RES_BADARGS: u8 = 0x14;
const RES_OK: u8 = 0x15;
const RES_UNKNOWN: u8 = 0x16;
const RES_XFTIMEOUT: u8 = 0x17;
const RES_XFEPE: u8 = 0x18;
const RES_CRCRX: u8 = 0x19;
const RES_RRANGE: u8 = 0x20;
const RES_XRRANGE: u8 = 0x21;
const RES_GATTR: u8 = 0x22;
const RES_CRCIF: u8 = 0x23;
const RES_CRCXF: u8 = 0x24;
const RES_INFO: u8 = 0x25;
const RES_CHANGE_BAUD_FAIL: u8 = 0x26;
const MAX_INDEX: u8 = 16;
const KEY_LEN: usize = 8;
const MAX_ATTR_LEN: usize = 55;
const INT_PAGE_SIZE: usize = 512;
const EXT_PAGE_SIZE: usize = 256;
const MAX_INFO_LEN: usize = 192;
// ****************************************************************************
//
// Public Impl/Functions/Modules
//
// ****************************************************************************
pub trait Encoder: Iterator<Item = u8> {
fn reset(&mut self);
/// Encode to bytes, storing them in the given buffer.
/// Returns the amount of buffer space used.
fn write(&mut self, buffer: &mut [u8]) -> usize {
for i in 0..buffer.len() {
if let Some(ch) = self.next() {
// Copy over byte
buffer[i] = ch;
} else {
// We're finished outputting bytes
return i;
}
}
// Got to the end - whole buffer used
return buffer.len();
}
}
impl CommandDecoder {
/// Create a new `CommandDecoder`.
///
/// The decoder is fed bytes with the `receive` method.
pub fn new() -> CommandDecoder {
CommandDecoder {
state: DecoderState::Loading,
buffer: [0u8; 520],
count: 0,
}
}
/// Decode a whole buffers worth of bytes.
///
/// Due to lifetime problems, the decoded `Command`s are sent via `callback` rather
/// than being returned.
pub fn read<F>(&mut self, buffer: &[u8], callback: F) -> Result<(), Error>
where
F: Fn(&Command),
{
for ch in buffer {
match self.receive(*ch) {
Err(e) => return Err(e),
Ok(None) => {}
Ok(Some(ref cmd)) => callback(cmd),
}
}
Ok(())
}
/// Empty the RX buffer.
pub fn reset(&mut self) {
self.count = 0;
}
/// Process incoming bytes.
///
/// The decoder is fed bytes with the `receive` method. If not enough
/// bytes have been seen, this function returns `None`. Once enough bytes
/// have been seen, it returns `Ok(Some(Command))` containing the decoded
/// Command. It returns `Err` if it doesn't like the byte received.
pub fn receive(&mut self, ch: u8) -> Result<Option<Command>, Error> {
match self.state {
DecoderState::Loading => self.handle_loading(ch),
DecoderState::Escape => self.handle_escape(ch),
}
}
fn load_char(&mut self, ch: u8) {
if self.count < self.buffer.len() {
self.buffer[self.count] = ch;
self.count = self.count + 1;
}
}
fn handle_loading(&mut self, ch: u8) -> Result<Option<Command>, Error> {
if ch == ESCAPE_CHAR {
self.state = DecoderState::Escape;
} else {
self.load_char(ch);
}
Ok(None)
}
fn handle_escape(&mut self, ch: u8) -> Result<Option<Command>, Error> {
self.state = DecoderState::Loading;
let result: Result<Option<Command>, Error> = match ch {
ESCAPE_CHAR => {
// Double escape means just load an escape
self.load_char(ch);
Ok(None)
}
CMD_PING => Ok(Some(Command::Ping)),
CMD_INFO => Ok(Some(Command::Info)),
CMD_ID => Ok(Some(Command::Id)),
CMD_RESET => Ok(Some(Command::Reset)),
CMD_EPAGE => {
let num_expected_bytes: usize = 4;
if self.count == num_expected_bytes {
let address = LittleEndian::read_u32(&self.buffer[0..4]);
Ok(Some(Command::ErasePage { address }))
} else {
Err(Error::BadArguments)
}
}
CMD_WPAGE => {
let num_expected_bytes: usize = INT_PAGE_SIZE + 4;
if self.count == num_expected_bytes {
let payload = &self.buffer[0..num_expected_bytes];
let address = LittleEndian::read_u32(&payload[0..4]);
Ok(Some(Command::WritePage {
address,
data: &payload[4..num_expected_bytes],
}))
} else {
Err(Error::BadArguments)
}
}
CMD_XEBLOCK => {
let num_expected_bytes: usize = 4;
if self.count == num_expected_bytes {
let address = LittleEndian::read_u32(&self.buffer[0..4]);
Ok(Some(Command::EraseExBlock { address }))
} else {
Err(Error::BadArguments)
}
}
CMD_XWPAGE => {
let num_expected_bytes: usize = EXT_PAGE_SIZE + 4;
if self.count == num_expected_bytes {
let payload = &self.buffer[0..num_expected_bytes];
let address = LittleEndian::read_u32(&payload[0..4]);
Ok(Some(Command::WriteExPage {
address,
data: &payload[4..num_expected_bytes],
}))
} else {
Err(Error::BadArguments)
}
}
CMD_CRCRX => Ok(Some(Command::CrcRxBuffer)),
CMD_RRANGE => {
let num_expected_bytes: usize = 6;
if self.count == num_expected_bytes {
let address = LittleEndian::read_u32(&self.buffer[0..4]);
let length = LittleEndian::read_u16(&self.buffer[4..6]);
Ok(Some(Command::ReadRange { address, length }))
} else {
Err(Error::BadArguments)
}
}
CMD_XRRANGE => {
let num_expected_bytes: usize = 6;
if self.count == num_expected_bytes {
let address = LittleEndian::read_u32(&self.buffer[0..4]);
let length = LittleEndian::read_u16(&self.buffer[4..6]);
Ok(Some(Command::ExReadRange { address, length }))
} else {
Err(Error::BadArguments)
}
}
CMD_SATTR => {
let num_expected_bytes: usize = 10;
if self.count >= num_expected_bytes {
let index = self.buffer[0];
let key = &self.buffer[1..9];
let length = self.buffer[9] as usize;
if self.count == (num_expected_bytes + length) {
let value = &self.buffer[10..10 + length];
Ok(Some(Command::SetAttr { index, key, value }))
} else {
Err(Error::BadArguments)
}
} else {
Err(Error::BadArguments)
}
}
CMD_GATTR => {
let num_expected_bytes: usize = 1;
if self.count == num_expected_bytes {
let index = self.buffer[0];
Ok(Some(Command::GetAttr { index }))
} else {
Err(Error::BadArguments)
}
}
CMD_CRCIF => {
let num_expected_bytes: usize = 8;
if self.count == num_expected_bytes {
let address = LittleEndian::read_u32(&self.buffer[0..4]);
let length = LittleEndian::read_u32(&self.buffer[4..8]);
Ok(Some(Command::CrcIntFlash { address, length }))
} else {
Err(Error::BadArguments)
}
}
CMD_CRCEF => {
let num_expected_bytes: usize = 8;
if self.count == num_expected_bytes {
let address = LittleEndian::read_u32(&self.buffer[0..4]);
let length = LittleEndian::read_u32(&self.buffer[4..8]);
Ok(Some(Command::CrcExtFlash { address, length }))
} else {
Err(Error::BadArguments)
}
}
CMD_XEPAGE => {
let num_expected_bytes: usize = 4;
if self.count == num_expected_bytes {
let address = LittleEndian::read_u32(&self.buffer[0..4]);
Ok(Some(Command::EraseExPage { address }))
} else {
Err(Error::BadArguments)
}
}
CMD_XFINIT => Ok(Some(Command::ExtFlashInit)),
CMD_CLKOUT => Ok(Some(Command::ClockOut)),
CMD_WUSER => {
let num_expected_bytes: usize = 8;
if self.count == num_expected_bytes {
let page1 = LittleEndian::read_u32(&self.buffer[0..4]);
let page2 = LittleEndian::read_u32(&self.buffer[4..8]);
Ok(Some(Command::WriteFlashUserPages { page1, page2 }))
} else {
Err(Error::BadArguments)
}
}
CMD_CHANGE_BAUD => {
let num_expected_bytes: usize = 5;
if self.count == num_expected_bytes {
let mode = self.buffer[0];
let baud = LittleEndian::read_u32(&self.buffer[1..5]);
match mode {
0x01 => Ok(Some(Command::ChangeBaud {
mode: BaudMode::Set,
baud,
})),
0x02 => Ok(Some(Command::ChangeBaud {
mode: BaudMode::Verify,
baud,
})),
_ => Err(Error::BadArguments),
}
} else {
Err(Error::BadArguments)
}
}
_ => Ok(None),
};
// A command or error signifies the end of the buffer
if let Ok(Some(_)) = result {
self.count = 0;
} else if let Err(_) = result {
self.count = 0;
}
result
}
}
impl ResponseDecoder {
/// Create a new `ResponseDecoder`.
///
/// The decoder is fed bytes with the `receive` method.
pub fn new() -> ResponseDecoder {
ResponseDecoder {
state: DecoderState::Loading,
buffer: [0u8; 520],
count: 0,
needed: None,
}
}
/// Decode a whole buffers worth of bytes.
///
/// Due to lifetime problems, the decoded `Response`s are sent via `callback` rather
/// than being returned.
pub fn read<F>(&mut self, buffer: &[u8], callback: F) -> Result<(), Error>
where
F: Fn(&Response),
{
for ch in buffer {
match self.receive(*ch) {
Err(e) => return Err(e),
Ok(None) => {}
Ok(Some(ref cmd)) => callback(cmd),
}
}
Ok(())
}
/// Empty the RX buffer.
pub fn reset(&mut self) {
self.count = 0;
}
/// Process incoming bytes.
///
/// The decoder is fed bytes with the `receive` method. If not enough
/// bytes have been seen, this function returns `None`. Once enough bytes
/// have been seen, it returns `Some(Response)` containing the
/// decoded Response.
pub fn receive(&mut self, ch: u8) -> Result<Option<Response>, Error> {
match self.state {
DecoderState::Loading => self.handle_loading(ch),
DecoderState::Escape => self.handle_escape(ch),
}
}
/// Set the expected length of an unbounded message. This
/// depends entirely on the last command you sent.
pub fn set_payload_len(&mut self, length: usize) -> Result<(), Error> {
match self.needed {
Some(_) => Err(Error::SetLength),
None => {
self.needed = Some(length + 1);
Ok(())
}
}
}
fn load_char(&mut self, ch: u8) -> Result<Option<Response>, Error> {
if self.count < self.buffer.len() {
self.buffer[self.count] = ch;
self.count = self.count + 1;
}
if self.needed == Some(self.count) {
let result = match self.buffer[0] {
RES_CRCRX => {
let length = LittleEndian::read_u16(&self.buffer[1..3]);
let crc = LittleEndian::read_u32(&self.buffer[3..7]);
Ok(Some(Response::CrcRxBuffer { length, crc }))
}
RES_RRANGE => {
let data = &self.buffer[1..self.count];
Ok(Some(Response::ReadRange { data }))
}
RES_XRRANGE => {
let data = &self.buffer[1..self.count];
Ok(Some(Response::ExReadRange { data }))
}
RES_GATTR => {
let key = &self.buffer[1..9];
let length = self.buffer[9] as usize;
if (9 + length) <= self.count {
let value = &self.buffer[10..(10 + length)];
Ok(Some(Response::GetAttr { key, value }))
} else {
Err(Error::BadArguments)
}
}
RES_CRCIF => {
let crc = LittleEndian::read_u32(&self.buffer[1..5]);
Ok(Some(Response::CrcIntFlash { crc }))
}
RES_CRCXF => {
let crc = LittleEndian::read_u32(&self.buffer[1..5]);
Ok(Some(Response::CrcExtFlash { crc }))
}
RES_INFO => {
let length: usize = self.buffer[1] as usize;
if length + 1 < self.count {
let info = &self.buffer[2..length + 2];
Ok(Some(Response::Info { info }))
} else {
Err(Error::BadArguments)
}
}
_ => Err(Error::UnknownCommand),
};
self.needed = None;
self.count = 0;
result
} else {
Ok(None)
}
}
fn handle_loading(&mut self, ch: u8) -> Result<Option<Response>, Error> {
if ch == ESCAPE_CHAR {
self.state = DecoderState::Escape;
Ok(None)
} else {
self.load_char(ch)
}
}
fn handle_escape(&mut self, ch: u8) -> Result<Option<Response>, Error> {
self.state = DecoderState::Loading;
match ch {
ESCAPE_CHAR => {
// Double escape means just load an escape
self.load_char(ch)
}
RES_PONG => {
self.count = 0;
self.needed = None;
Ok(Some(Response::Pong))
}
RES_OVERFLOW => {
self.count = 0;
self.needed = None;
Ok(Some(Response::Overflow))
}
RES_BADADDR => {
self.count = 0;
self.needed = None;
Ok(Some(Response::BadAddress))
}
RES_INTERROR => {
self.count = 0;
self.needed = None;
Ok(Some(Response::InternalError))
}
RES_BADARGS => {
self.count = 0;
self.needed = None;
Ok(Some(Response::BadArguments))
}
RES_OK => {
self.count = 0;
self.needed = None;
Ok(Some(Response::Ok))
}
RES_UNKNOWN => {
self.count = 0;
self.needed = None;
Ok(Some(Response::Unknown))
}
RES_XFTIMEOUT => {
self.count = 0;
self.needed = None;
Ok(Some(Response::ExtFlashTimeout))
}
RES_XFEPE => {
self.count = 0;
self.needed = None;
Ok(Some(Response::ExtFlashPageError))
}
RES_CHANGE_BAUD_FAIL => {
self.count = 0;
self.needed = None;
Ok(Some(Response::ChangeBaudFail))
}
RES_CRCRX => {
self.set_payload_len(6)?;
self.load_char(ch)?;
Ok(None)
}
RES_RRANGE => {
if self.needed.is_none() {
Err(Error::UnsetLength)
} else {
self.load_char(ch)?;
Ok(None)
}
}
RES_XRRANGE => {
if self.needed.is_none() {
Err(Error::UnsetLength)
} else {
self.load_char(ch)?;
Ok(None)
}
}
RES_GATTR => {
self.set_payload_len(1 + KEY_LEN + MAX_ATTR_LEN)?;
self.load_char(ch)?;
Ok(None)
}
RES_CRCIF => {
self.set_payload_len(4)?;
self.load_char(ch)?;
Ok(None)
}
RES_CRCXF => {
self.set_payload_len(4)?;
self.load_char(ch)?;
Ok(None)
}
RES_INFO => {
// length + data
self.set_payload_len(1 + MAX_INFO_LEN)?;
self.load_char(ch)?;
Ok(None)
}
_ => Ok(None),
}
}
}
impl<'a> CommandEncoder<'a> {
/// Create a new `CommandEncoder`.
///
/// The encoder takes a reference to a `Command` to encode. The `next` method
/// will then supply the encoded bytes one at a time.
pub fn new(command: &'a Command) -> Result<CommandEncoder<'a>, Error> {
// We have to accept slices rather than arrays, so bounds check them
// all now to save surprises later.
match command {
&Command::WritePage { address: _, data } => {
if data.len() != INT_PAGE_SIZE {
return Err(Error::BadArguments);
}
}
&Command::WriteExPage { address: _, data } => {
if data.len() != EXT_PAGE_SIZE {
return Err(Error::BadArguments);
}
}
&Command::SetAttr { index, key, value } => {
if index > MAX_INDEX {
return Err(Error::BadArguments);
}
if key.len() != KEY_LEN {
return Err(Error::BadArguments);
}
if value.len() > MAX_ATTR_LEN {
return Err(Error::BadArguments);
}
}
_ => {}
};
Ok(CommandEncoder {
command: command,
count: 0,
sent_escape: false,
})
}
/// Reset the `CommandEncoder`, so that next time you call `self.next()`
/// you get the first byte again.
pub fn reset(&mut self) {
self.count = 0;
self.sent_escape = false;
}
fn render_byte(&mut self, byte: u8) -> (usize, Option<u8>) {
if byte == ESCAPE_CHAR {
if self.sent_escape {
self.sent_escape = false;
(1, Some(ESCAPE_CHAR))
} else {
self.sent_escape = true;
(0, Some(ESCAPE_CHAR))
}
} else {
self.sent_escape = false;
(1, Some(byte))
}
}
fn render_u16(&mut self, idx: usize, value: u16) -> (usize, Option<u8>) {
match idx {
0 => self.render_byte(value as u8),
1 => self.render_byte((value >> 8) as u8),
_ => (0, None),
}
}
fn render_u32(&mut self, idx: usize, value: u32) -> (usize, Option<u8>) {
match idx {
0 => self.render_byte(value as u8),
1 => self.render_byte((value >> 8) as u8),
2 => self.render_byte((value >> 16) as u8),
3 => self.render_byte((value >> 24) as u8),
_ => (0, None),
}
}
fn render_buffer(&mut self, idx: usize, page_size: usize, data: &[u8]) -> (usize, Option<u8>) {
if (idx < data.len()) && (idx < page_size) {
self.render_byte(data[idx])
} else if idx < page_size {
self.render_byte(0x00) // pad short data with nulls
} else {
(0, None)
}
}
fn render_basic_cmd(&mut self, count: usize, cmd: u8) -> (usize, Option<u8>) {
match count {
0 => (1, Some(ESCAPE_CHAR)), // Escape
1 => (1, Some(cmd)), // Command
_ => (0, None),
}
}
fn render_erasepage_cmd(&mut self, address: u32) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...3 => self.render_u32(count, address),
_ => self.render_basic_cmd(count - 4, CMD_EPAGE),
}
}
fn render_writepage_cmd(&mut self, address: u32, data: &[u8]) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...3 => self.render_u32(count, address),
4...515 => self.render_buffer(count - 4, INT_PAGE_SIZE, data),
_ => self.render_basic_cmd(count - 516, CMD_WPAGE),
}
}
fn render_eraseexblock(&mut self, address: u32) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...3 => self.render_u32(count, address),
_ => self.render_basic_cmd(count - 4, CMD_XEBLOCK),
}
}
fn render_writeexpage(&mut self, address: u32, data: &[u8]) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...3 => self.render_u32(count, address),
4...259 => self.render_buffer(count - 4, EXT_PAGE_SIZE, data),
_ => self.render_basic_cmd(count - (EXT_PAGE_SIZE + 4), CMD_XWPAGE),
}
}
fn render_readrange(&mut self, address: u32, length: u16) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...3 => self.render_u32(count, address),
4...5 => self.render_u16(count - 4, length),
_ => self.render_basic_cmd(count - 6, CMD_RRANGE),
}
}
fn render_exreadrange(&mut self, address: u32, length: u16) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...3 => self.render_u32(count, address),
4...5 => self.render_u16(count - 4, length),
_ => self.render_basic_cmd(count - 6, CMD_XRRANGE),
}
}
fn render_setattr(&mut self, index: u8, key: &[u8], value: &[u8]) -> (usize, Option<u8>) {
let count = self.count;
let max_len = if value.len() > MAX_ATTR_LEN {
MAX_ATTR_LEN
} else {
value.len()
};
match count {
0 => self.render_byte(index),
1...8 => self.render_buffer(count - 1, KEY_LEN, key),
9 => self.render_byte(max_len as u8),
x if (max_len > 0) && (x < (max_len + 10)) => {
self.render_buffer(x - 10, max_len, value)
}
_ => self.render_basic_cmd(count - (10 + max_len), CMD_SATTR),
}
}
fn render_getattr(&mut self, index: u8) -> (usize, Option<u8>) {
let count = self.count;
match count {
0 => self.render_byte(index),
_ => self.render_basic_cmd(count - 1, CMD_GATTR),
}
}
fn render_crcintflash(&mut self, address: u32, length: u32) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...3 => self.render_u32(count, address),
4...7 => self.render_u32(count - 4, length),
_ => self.render_basic_cmd(count - 8, CMD_CRCIF),
}
}
fn render_crcextflash(&mut self, address: u32, length: u32) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...3 => self.render_u32(count, address),
4...7 => self.render_u32(count - 4, length),
_ => self.render_basic_cmd(count - 8, CMD_CRCEF),
}
}
fn render_eraseexpage(&mut self, address: u32) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...3 => self.render_u32(count, address),
_ => self.render_basic_cmd(count - 4, CMD_XEPAGE),
}
}
fn render_writeflashuserpages(&mut self, page1: u32, page2: u32) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...3 => self.render_u32(count, page1),
4...7 => self.render_u32(count - 4, page2),
_ => self.render_basic_cmd(count - 8, CMD_WUSER),
}
}
fn render_changebaud(&mut self, mode: BaudMode, baud: u32) -> (usize, Option<u8>) {
let count = self.count;
match count {
0 => {
self.render_byte(match mode {
BaudMode::Set => 0x01,
BaudMode::Verify => 0x02,
})
}
1...4 => self.render_u32(count - 1, baud),
_ => self.render_basic_cmd(count - 5, CMD_CHANGE_BAUD),
}
}
}
impl<'a> Iterator for CommandEncoder<'a> {
type Item = u8;
/// Supply the next encoded byte. Once all the bytes have been emitted, it
/// returns `None` forevermore.
fn next(&mut self) -> Option<u8> {
let count = self.count;
let (inc, result) = match self.command {
&Command::Ping => self.render_basic_cmd(count, CMD_PING),
&Command::Info => self.render_basic_cmd(count, CMD_INFO),
&Command::Id => self.render_basic_cmd(count, CMD_ID),
&Command::Reset => self.render_basic_cmd(count, CMD_RESET),
&Command::ErasePage { address } => self.render_erasepage_cmd(address),
&Command::WritePage { address, data } => self.render_writepage_cmd(address, data),
&Command::EraseExBlock { address } => self.render_eraseexblock(address),
&Command::WriteExPage { address, data } => self.render_writeexpage(address, data),
&Command::CrcRxBuffer => self.render_basic_cmd(count, CMD_CRCRX),
&Command::ReadRange { address, length } => self.render_readrange(address, length),
&Command::ExReadRange { address, length } => self.render_exreadrange(address, length),
&Command::SetAttr { index, key, value } => self.render_setattr(index, key, value),
&Command::GetAttr { index } => self.render_getattr(index),
&Command::CrcIntFlash { address, length } => self.render_crcintflash(address, length),
&Command::CrcExtFlash { address, length } => self.render_crcextflash(address, length),
&Command::EraseExPage { address } => self.render_eraseexpage(address),
&Command::ExtFlashInit => self.render_basic_cmd(count, CMD_XFINIT),
&Command::ClockOut => self.render_basic_cmd(count, CMD_CLKOUT),
&Command::WriteFlashUserPages { page1, page2 } => {
self.render_writeflashuserpages(page1, page2)
}
&Command::ChangeBaud { mode, baud } => self.render_changebaud(mode, baud),
};
self.count = self.count + inc;
result
}
}
impl<'a> Encoder for CommandEncoder<'a> {
/// Reset the `Encoder`, so that next time you call `self.next()`
/// you get the first byte again.
fn reset(&mut self) {
self.count = 0;
self.sent_escape = false;
}
}
impl<'a> ResponseEncoder<'a> {
/// Create a new `ResponseEncoder`.
///
/// The encoder takes a reference to a `Command` to encode. The `next` method
/// will then supply the encoded bytes one at a time.
pub fn new(response: &'a Response) -> Result<ResponseEncoder<'a>, Error> {
match response {
&Response::GetAttr { key, value } => {
if key.len() != KEY_LEN {
return Err(Error::BadArguments);
}
if value.len() > MAX_ATTR_LEN {
return Err(Error::BadArguments);
}
}
&Response::Info { info } => {
if info.len() > MAX_INFO_LEN {
return Err(Error::BadArguments);
}
}
_ => {}
}
Ok(ResponseEncoder {
response: response,
count: 0,
sent_escape: false,
})
}
fn render_byte(&mut self, byte: u8) -> (usize, Option<u8>) {
if byte == ESCAPE_CHAR {
if self.sent_escape {
self.sent_escape = false;
(1, Some(ESCAPE_CHAR))
} else {
self.sent_escape = true;
(0, Some(ESCAPE_CHAR))
}
} else {
(1, Some(byte))
}
}
fn render_crc_rx_buffer(&mut self, length: u16, crc: u32) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...1 => self.render_header(count, RES_CRCRX),
2...3 => self.render_u16(count - 2, length),
4...7 => self.render_u32(count - 4, crc),
_ => (0, None),
}
}
fn render_read_range(&mut self, data: &[u8]) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...1 => self.render_header(count, RES_RRANGE),
x if x < data.len() + 2 => self.render_byte(data[x - 2]),
_ => (0, None),
}
}
fn render_ex_read_range(&mut self, data: &[u8]) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...1 => self.render_header(count, RES_XRRANGE),
x if x - 2 < data.len() => self.render_byte(data[x - 2]),
_ => (0, None),
}
}
fn render_get_attr(&mut self, key: &[u8], value: &[u8]) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...1 => self.render_header(count, RES_GATTR),
2...9 => self.render_buffer(count - 2, 8, key),
10 => self.render_byte(value.len() as u8),
_ => self.render_buffer(count - 11, MAX_ATTR_LEN, value),
}
}
fn render_crc_int_flash(&mut self, crc: u32) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...1 => self.render_header(count, RES_CRCIF),
_ => self.render_u32(count - 2, crc),
}
}
fn render_crc_ex_flash(&mut self, crc: u32) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...1 => self.render_header(count, RES_CRCXF),
_ => self.render_u32(count - 2, crc),
}
}
fn render_info(&mut self, info: &[u8]) -> (usize, Option<u8>) {
let count = self.count;
match count {
0...1 => self.render_header(count, RES_INFO),
2 => self.render_byte(info.len() as u8),
_ => self.render_buffer(count - 3, MAX_INFO_LEN, info),
}
}
fn render_u16(&mut self, idx: usize, value: u16) -> (usize, Option<u8>) {
match idx {
0 => self.render_byte(value as u8),
1 => self.render_byte((value >> 8) as u8),
_ => (0, None),
}
}
fn render_u32(&mut self, idx: usize, value: u32) -> (usize, Option<u8>) {
match idx {
0 => self.render_byte(value as u8),
1 => self.render_byte((value >> 8) as u8),
2 => self.render_byte((value >> 16) as u8),
3 => self.render_byte((value >> 24) as u8),
_ => (0, None),
}
}
fn render_buffer(&mut self, idx: usize, page_size: usize, data: &[u8]) -> (usize, Option<u8>) {
if (idx < data.len()) && (idx < page_size) {
self.render_byte(data[idx])
} else if idx < page_size {
self.render_byte(0x00) // pad short data with nulls
} else {
(0, None)
}
}
fn render_header(&mut self, count: usize, cmd: u8) -> (usize, Option<u8>) {
match count {
0 => (1, Some(ESCAPE_CHAR)), // Escape
1 => (1, Some(cmd)), // Command
_ => (0, None),
}
}
}
impl<'a> Encoder for ResponseEncoder<'a> {
fn reset(&mut self) {
self.count = 0;
self.sent_escape = false;
}
}
impl<'a> Iterator for ResponseEncoder<'a> {
type Item = u8;
/// Supply the next encoded byte. Once all the bytes have been emitted, it
/// returns `None` forevermore.
fn next(&mut self) -> Option<u8> {
let count = self.count;
let (inc, result) = match self.response {
&Response::Overflow => self.render_header(count, RES_OVERFLOW),
&Response::Pong => self.render_header(count, RES_PONG),
&Response::BadAddress => self.render_header(count, RES_BADADDR),
&Response::InternalError => self.render_header(count, RES_INTERROR),
&Response::BadArguments => self.render_header(count, RES_BADARGS),
&Response::Ok => self.render_header(count, RES_OK),
&Response::Unknown => self.render_header(count, RES_UNKNOWN),
&Response::ExtFlashTimeout => self.render_header(count, RES_XFTIMEOUT),
&Response::ExtFlashPageError => self.render_header(count, RES_XFEPE),
&Response::CrcRxBuffer { length, crc } => self.render_crc_rx_buffer(length, crc),
&Response::ReadRange { data } => self.render_read_range(data),
&Response::ExReadRange { data } => self.render_ex_read_range(data),
&Response::GetAttr { key, value } => self.render_get_attr(key, value),
&Response::CrcIntFlash { crc } => self.render_crc_int_flash(crc),
&Response::CrcExtFlash { crc } => self.render_crc_ex_flash(crc),
&Response::Info { info } => self.render_info(info),
&Response::ChangeBaudFail => self.render_header(count, RES_CHANGE_BAUD_FAIL),
};
self.count = self.count + inc;
result
}
}
// ****************************************************************************
//
// Private Impl/Functions/Modules
//
// ****************************************************************************
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decode_cmd_ping() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None));
match p.receive(CMD_PING) {
Ok(Some(Command::Ping)) => {}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_ping() {
let cmd = Command::Ping;
let mut e = CommandEncoder::new(&cmd).unwrap();
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_PING));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_info() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None));
match p.receive(CMD_INFO) {
Ok(Some(Command::Info)) => {}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_info() {
let cmd = Command::Info;
let mut e = CommandEncoder::new(&cmd).unwrap();
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_INFO));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_id() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None));
match p.receive(CMD_ID) {
Ok(Some(Command::Id)) => {}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_id() {
let cmd = Command::Id;
let mut e = CommandEncoder::new(&cmd).unwrap();
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_ID));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_reset() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None));
match p.receive(CMD_RESET) {
Ok(Some(Command::Reset)) => {}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_reset() {
let cmd = Command::Reset;
let mut e = CommandEncoder::new(&cmd).unwrap();
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_RESET));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_erase_page() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(0xEF), Ok(None));
assert_eq!(p.receive(0xBE), Ok(None));
assert_eq!(p.receive(0xAD), Ok(None));
assert_eq!(p.receive(0xDE), Ok(None));
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_EPAGE) {
Ok(Some(Command::ErasePage { address })) => {
assert_eq!(address, 0xDEADBEEF);
}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_erase_page() {
let cmd = Command::ErasePage { address: 0xDEADBEEF };
let mut e = CommandEncoder::new(&cmd).unwrap();
// 4 byte address, little-endian
assert_eq!(e.next(), Some(0xEF));
assert_eq!(e.next(), Some(0xBE));
assert_eq!(e.next(), Some(0xAD));
assert_eq!(e.next(), Some(0xDE));
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_EPAGE));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_write_page() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(0xEF), Ok(None));
assert_eq!(p.receive(0xBE), Ok(None));
assert_eq!(p.receive(0xAD), Ok(None));
assert_eq!(p.receive(0xDE), Ok(None));
for i in 0..INT_PAGE_SIZE {
let datum = i as u8;
assert_eq!(p.receive(datum), Ok(None));
if datum == ESCAPE_CHAR {
assert_eq!(p.receive(datum), Ok(None));
}
}
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_WPAGE) {
Ok(Some(Command::WritePage {
address,
data: ref page,
})) => {
assert_eq!(address, 0xDEADBEEF);
assert_eq!(page.len(), INT_PAGE_SIZE);
for i in 0..INT_PAGE_SIZE {
let datum = i as u8;
assert_eq!(datum, page[i as usize]);
}
}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_write_page() {
let mut buffer = [0xBBu8; INT_PAGE_SIZE];
buffer[0] = 0xAA;
buffer[INT_PAGE_SIZE - 1] = 0xCC;
let cmd = Command::WritePage {
address: 0xDEADBEEF,
data: &buffer,
};
let mut e = CommandEncoder::new(&cmd).unwrap();
// 4 byte address, little-endian
assert_eq!(e.next(), Some(0xEF));
assert_eq!(e.next(), Some(0xBE));
assert_eq!(e.next(), Some(0xAD));
assert_eq!(e.next(), Some(0xDE));
// first byte of data
assert_eq!(e.next(), Some(0xAA));
for _ in 1..(INT_PAGE_SIZE - 1) {
assert_eq!(e.next(), Some(0xBB));
}
// last byte of data
assert_eq!(e.next(), Some(0xCC));
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_WPAGE));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_erase_block() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(0xEF), Ok(None));
assert_eq!(p.receive(0xBE), Ok(None));
assert_eq!(p.receive(0xAD), Ok(None));
assert_eq!(p.receive(0xDE), Ok(None));
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_XEBLOCK) {
Ok(Some(Command::EraseExBlock { address })) => {
assert_eq!(address, 0xDEADBEEF);
}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_erase_block() {
let cmd = Command::EraseExBlock { address: 0xDEADBEEF };
let mut e = CommandEncoder::new(&cmd).unwrap();
// 4 byte address, little-endian
assert_eq!(e.next(), Some(0xEF));
assert_eq!(e.next(), Some(0xBE));
assert_eq!(e.next(), Some(0xAD));
assert_eq!(e.next(), Some(0xDE));
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_XEBLOCK));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_write_ex_page() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(0xEF), Ok(None));
assert_eq!(p.receive(0xBE), Ok(None));
assert_eq!(p.receive(0xAD), Ok(None));
assert_eq!(p.receive(0xDE), Ok(None));
for i in 0..EXT_PAGE_SIZE {
let datum = i as u8;
assert_eq!(p.receive(datum), Ok(None));
if datum == ESCAPE_CHAR {
assert_eq!(p.receive(datum), Ok(None));
}
}
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_XWPAGE) {
Ok(Some(Command::WriteExPage {
address,
data: ref page,
})) => {
assert_eq!(address, 0xDEADBEEF);
assert_eq!(page.len(), EXT_PAGE_SIZE);
for i in 0..EXT_PAGE_SIZE {
let datum = i as u8;
assert_eq!(datum, page[i as usize]);
}
}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_write_ex_page() {
let mut buffer = [0xBBu8; EXT_PAGE_SIZE];
buffer[0] = 0xAA;
buffer[EXT_PAGE_SIZE - 1] = 0xCC;
let cmd = Command::WriteExPage {
address: 0xDEADBEEF,
data: &buffer,
};
let mut e = CommandEncoder::new(&cmd).unwrap();
// 4 byte address, little-endian
assert_eq!(e.next(), Some(0xEF));
assert_eq!(e.next(), Some(0xBE));
assert_eq!(e.next(), Some(0xAD));
assert_eq!(e.next(), Some(0xDE));
// first byte of data
assert_eq!(e.next(), Some(0xAA));
for _ in 1..(EXT_PAGE_SIZE - 1) {
assert_eq!(e.next(), Some(0xBB));
}
// last byte of data
assert_eq!(e.next(), Some(0xCC));
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_XWPAGE));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn encode_cmd_crcrx() {
let cmd = Command::CrcRxBuffer;
let mut e = CommandEncoder::new(&cmd).unwrap();
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_CRCRX));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_crcrx() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_CRCRX) {
Ok(Some(Command::CrcRxBuffer)) => {}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_rrange() {
let cmd = Command::ReadRange {
address: 0xDEADBEEF,
length: 0x1234,
};
let mut e = CommandEncoder::new(&cmd).unwrap();
// 4 byte address, little-endian
assert_eq!(e.next(), Some(0xEF));
assert_eq!(e.next(), Some(0xBE));
assert_eq!(e.next(), Some(0xAD));
assert_eq!(e.next(), Some(0xDE));
// 2 byte length
assert_eq!(e.next(), Some(0x34));
assert_eq!(e.next(), Some(0x12));
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_RRANGE));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_rrange() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(0xEF), Ok(None));
assert_eq!(p.receive(0xBE), Ok(None));
assert_eq!(p.receive(0xAD), Ok(None));
assert_eq!(p.receive(0xDE), Ok(None));
assert_eq!(p.receive(0x34), Ok(None));
assert_eq!(p.receive(0x12), Ok(None));
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_RRANGE) {
Ok(Some(Command::ReadRange { address, length })) => {
assert_eq!(address, 0xDEADBEEF);
assert_eq!(length, 0x1234);
}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_xrrange() {
let cmd = Command::ExReadRange {
address: 0xDEADBEEF,
length: 0x1234,
};
let mut e = CommandEncoder::new(&cmd).unwrap();
// 4 byte address, little-endian
assert_eq!(e.next(), Some(0xEF));
assert_eq!(e.next(), Some(0xBE));
assert_eq!(e.next(), Some(0xAD));
assert_eq!(e.next(), Some(0xDE));
// 2 byte length
assert_eq!(e.next(), Some(0x34));
assert_eq!(e.next(), Some(0x12));
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_XRRANGE));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_xrrange() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(0xEF), Ok(None));
assert_eq!(p.receive(0xBE), Ok(None));
assert_eq!(p.receive(0xAD), Ok(None));
assert_eq!(p.receive(0xDE), Ok(None));
assert_eq!(p.receive(0x34), Ok(None));
assert_eq!(p.receive(0x12), Ok(None));
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_XRRANGE) {
Ok(Some(Command::ExReadRange { address, length })) => {
assert_eq!(address, 0xDEADBEEF);
assert_eq!(length, 0x1234);
}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_sattr() {
let r = Command::SetAttr {
index: MAX_INDEX,
key: &[0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77],
value: &[0xAA, 0xBB, 0xCC, 0xDD],
};
let mut e = CommandEncoder::new(&r).unwrap();
assert_eq!(e.next(), Some(MAX_INDEX));
assert_eq!(e.next(), Some(0x00));
assert_eq!(e.next(), Some(0x11));
assert_eq!(e.next(), Some(0x22));
assert_eq!(e.next(), Some(0x33));
assert_eq!(e.next(), Some(0x44));
assert_eq!(e.next(), Some(0x55));
assert_eq!(e.next(), Some(0x66));
assert_eq!(e.next(), Some(0x77));
assert_eq!(e.next(), Some(0x04));
assert_eq!(e.next(), Some(0xAA));
assert_eq!(e.next(), Some(0xBB));
assert_eq!(e.next(), Some(0xCC));
assert_eq!(e.next(), Some(0xDD));
// Commands don't seem to need padding
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_SATTR));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_sattr() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(MAX_INDEX), Ok(None));
assert_eq!(p.receive(0x00), Ok(None));
assert_eq!(p.receive(0x11), Ok(None));
assert_eq!(p.receive(0x22), Ok(None));
assert_eq!(p.receive(0x33), Ok(None));
assert_eq!(p.receive(0x44), Ok(None));
assert_eq!(p.receive(0x55), Ok(None));
assert_eq!(p.receive(0x66), Ok(None));
assert_eq!(p.receive(0x77), Ok(None));
assert_eq!(p.receive(0x04), Ok(None));
assert_eq!(p.receive(0xAA), Ok(None));
assert_eq!(p.receive(0xBB), Ok(None));
assert_eq!(p.receive(0xCC), Ok(None));
assert_eq!(p.receive(0xDD), Ok(None));
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_SATTR) {
Ok(Some(Command::SetAttr { index, key, value })) => {
assert_eq!(index, MAX_INDEX);
assert_eq!(key, [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77]);
assert_eq!(value, [0xAA, 0xBB, 0xCC, 0xDD]);
}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_gattr() {
let r = Command::GetAttr { index: MAX_INDEX };
let mut e = CommandEncoder::new(&r).unwrap();
assert_eq!(e.next(), Some(MAX_INDEX));
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_GATTR));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_gattr() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(MAX_INDEX), Ok(None));
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_GATTR) {
Ok(Some(Command::GetAttr { index })) => {
assert_eq!(index, MAX_INDEX);
}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_crcif() {
let cmd = Command::CrcIntFlash {
address: 0xDEADBEEF,
length: 0x12345678,
};
let mut e = CommandEncoder::new(&cmd).unwrap();
// 4 byte address, little-endian
assert_eq!(e.next(), Some(0xEF));
assert_eq!(e.next(), Some(0xBE));
assert_eq!(e.next(), Some(0xAD));
assert_eq!(e.next(), Some(0xDE));
// 4 byte length
assert_eq!(e.next(), Some(0x78));
assert_eq!(e.next(), Some(0x56));
assert_eq!(e.next(), Some(0x34));
assert_eq!(e.next(), Some(0x12));
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_CRCIF));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_crcif() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(0xEF), Ok(None));
assert_eq!(p.receive(0xBE), Ok(None));
assert_eq!(p.receive(0xAD), Ok(None));
assert_eq!(p.receive(0xDE), Ok(None));
assert_eq!(p.receive(0x78), Ok(None));
assert_eq!(p.receive(0x56), Ok(None));
assert_eq!(p.receive(0x34), Ok(None));
assert_eq!(p.receive(0x12), Ok(None));
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_CRCIF) {
Ok(Some(Command::CrcIntFlash { address, length })) => {
assert_eq!(address, 0xDEADBEEF);
assert_eq!(length, 0x12345678);
}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_crcef() {
let cmd = Command::CrcExtFlash {
address: 0xDEADBEEF,
length: 0x12345678,
};
let mut e = CommandEncoder::new(&cmd).unwrap();
// 4 byte address, little-endian
assert_eq!(e.next(), Some(0xEF));
assert_eq!(e.next(), Some(0xBE));
assert_eq!(e.next(), Some(0xAD));
assert_eq!(e.next(), Some(0xDE));
// 4 byte length
assert_eq!(e.next(), Some(0x78));
assert_eq!(e.next(), Some(0x56));
assert_eq!(e.next(), Some(0x34));
assert_eq!(e.next(), Some(0x12));
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_CRCEF));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_crcef() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(0xEF), Ok(None));
assert_eq!(p.receive(0xBE), Ok(None));
assert_eq!(p.receive(0xAD), Ok(None));
assert_eq!(p.receive(0xDE), Ok(None));
assert_eq!(p.receive(0x78), Ok(None));
assert_eq!(p.receive(0x56), Ok(None));
assert_eq!(p.receive(0x34), Ok(None));
assert_eq!(p.receive(0x12), Ok(None));
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_CRCEF) {
Ok(Some(Command::CrcExtFlash { address, length })) => {
assert_eq!(address, 0xDEADBEEF);
assert_eq!(length, 0x12345678);
}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_xepage() {
let cmd = Command::EraseExPage { address: 0xDEADBEEF };
let mut e = CommandEncoder::new(&cmd).unwrap();
// 4 byte address, little-endian
assert_eq!(e.next(), Some(0xEF));
assert_eq!(e.next(), Some(0xBE));
assert_eq!(e.next(), Some(0xAD));
assert_eq!(e.next(), Some(0xDE));
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_XEPAGE));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_xepage() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(0xEF), Ok(None));
assert_eq!(p.receive(0xBE), Ok(None));
assert_eq!(p.receive(0xAD), Ok(None));
assert_eq!(p.receive(0xDE), Ok(None));
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_XEPAGE) {
Ok(Some(Command::EraseExPage { address })) => {
assert_eq!(address, 0xDEADBEEF);
}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_xfinit() {
let cmd = Command::ExtFlashInit {};
let mut e = CommandEncoder::new(&cmd).unwrap();
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_XFINIT));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_xfinit() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_XFINIT) {
Ok(Some(Command::ExtFlashInit)) => {}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_clkout() {
let cmd = Command::ClockOut {};
let mut e = CommandEncoder::new(&cmd).unwrap();
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_CLKOUT));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_clkout() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_CLKOUT) {
Ok(Some(Command::ClockOut)) => {}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_wuser() {
let cmd = Command::WriteFlashUserPages {
page1: 0xDEADBEEF,
page2: 0x12345678,
};
let mut e = CommandEncoder::new(&cmd).unwrap();
// 4 byte address, little-endian
assert_eq!(e.next(), Some(0xEF));
assert_eq!(e.next(), Some(0xBE));
assert_eq!(e.next(), Some(0xAD));
assert_eq!(e.next(), Some(0xDE));
// 4 byte length
assert_eq!(e.next(), Some(0x78));
assert_eq!(e.next(), Some(0x56));
assert_eq!(e.next(), Some(0x34));
assert_eq!(e.next(), Some(0x12));
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_WUSER));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_wuser() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(0xEF), Ok(None));
assert_eq!(p.receive(0xBE), Ok(None));
assert_eq!(p.receive(0xAD), Ok(None));
assert_eq!(p.receive(0xDE), Ok(None));
assert_eq!(p.receive(0x78), Ok(None));
assert_eq!(p.receive(0x56), Ok(None));
assert_eq!(p.receive(0x34), Ok(None));
assert_eq!(p.receive(0x12), Ok(None));
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_WUSER) {
Ok(Some(Command::WriteFlashUserPages { page1, page2 })) => {
assert_eq!(page1, 0xDEADBEEF);
assert_eq!(page2, 0x12345678);
}
e => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn encode_cmd_change_baud() {
let cmd = Command::ChangeBaud {
mode: BaudMode::Set,
baud: 0xDEADBEEF,
};
let mut e = CommandEncoder::new(&cmd).unwrap();
// Mode
assert_eq!(e.next(), Some(0x01));
// 4 byte baud (0x0001 C200)
assert_eq!(e.next(), Some(0xEF));
assert_eq!(e.next(), Some(0xBE));
assert_eq!(e.next(), Some(0xAD));
assert_eq!(e.next(), Some(0xDE));
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(CMD_CHANGE_BAUD));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn decode_cmd_change_baud() {
let mut p = CommandDecoder::new();
assert_eq!(p.receive(0x01), Ok(None));
assert_eq!(p.receive(0xEF), Ok(None));
assert_eq!(p.receive(0xBE), Ok(None));
assert_eq!(p.receive(0xAD), Ok(None));
assert_eq!(p.receive(0xDE), Ok(None));
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_CHANGE_BAUD) {
Ok(Some(Command::ChangeBaud { mode, baud })) => {
assert_eq!(mode, BaudMode::Set);
assert_eq!(baud, 0xDEADBEEF);
}
e => panic!("Did not expect: {:?}", e),
}
assert_eq!(p.receive(0x02), Ok(None));
assert_eq!(p.receive(0xEF), Ok(None));
assert_eq!(p.receive(0xBE), Ok(None));
assert_eq!(p.receive(0xAD), Ok(None));
assert_eq!(p.receive(0xDE), Ok(None));
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None)); // Escape
match p.receive(CMD_CHANGE_BAUD) {
Ok(Some(Command::ChangeBaud { mode, baud })) => {
assert_eq!(mode, BaudMode::Verify);
assert_eq!(baud, 0xDEADBEEF);
}
e => panic!("Did not expect: {:?}", e),
}
}
// Responses
fn check_rsp_generic(response: Response, cmd: u8) {
let mut p = ResponseDecoder::new();
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None));
match p.receive(cmd) {
Ok(Some(ref x)) if x == &response => {}
e => panic!("Did not expect: {:?}", e),
}
let mut e = ResponseEncoder::new(&response).unwrap();
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(cmd));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn check_rsp_overflow() {
check_rsp_generic(Response::Overflow, RES_OVERFLOW);
}
#[test]
fn check_rsp_pong() {
check_rsp_generic(Response::Pong, RES_PONG);
}
#[test]
fn check_rsp_badaddress() {
check_rsp_generic(Response::BadAddress, RES_BADADDR);
}
#[test]
fn check_rsp_internalerror() {
check_rsp_generic(Response::InternalError, RES_INTERROR);
}
#[test]
fn check_rsp_badarguments() {
check_rsp_generic(Response::BadArguments, RES_BADARGS);
}
#[test]
fn check_rsp_ok() {
check_rsp_generic(Response::Ok, RES_OK);
}
#[test]
fn check_rsp_unknown() {
check_rsp_generic(Response::Unknown, RES_UNKNOWN);
}
#[test]
fn check_rsp_exflashtimeout() {
check_rsp_generic(Response::ExtFlashTimeout, RES_XFTIMEOUT);
}
#[test]
fn check_rsp_exflashpageerror() {
check_rsp_generic(Response::ExtFlashPageError, RES_XFEPE);
}
#[test]
fn check_rsp_changebaudfail() {
check_rsp_generic(Response::ChangeBaudFail, RES_CHANGE_BAUD_FAIL);
}
#[test]
fn check_rsp_crc_rx() {
let mut p = ResponseDecoder::new();
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None));
assert_eq!(p.receive(RES_CRCRX), Ok(None));
// Length
assert_eq!(p.receive(0x34), Ok(None));
assert_eq!(p.receive(0x12), Ok(None));
// CRC
assert_eq!(p.receive(0xEF), Ok(None));
assert_eq!(p.receive(0xBE), Ok(None));
assert_eq!(p.receive(0xAD), Ok(None));
assert_eq!(
p.receive(0xDE),
Ok(Some(Response::CrcRxBuffer {
length: 0x1234,
crc: 0xDEADBEEF,
}))
);
let r = Response::CrcRxBuffer {
length: 0x1234,
crc: 0xDEADBEEF,
};
let mut e = ResponseEncoder::new(&r).unwrap();
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(RES_CRCRX));
assert_eq!(e.next(), Some(0x34));
assert_eq!(e.next(), Some(0x12));
assert_eq!(e.next(), Some(0xEF));
assert_eq!(e.next(), Some(0xBE));
assert_eq!(e.next(), Some(0xAD));
assert_eq!(e.next(), Some(0xDE));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn check_rsp_rrange() {
let mut p = ResponseDecoder::new();
p.set_payload_len(4).unwrap();
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None));
assert_eq!(p.receive(RES_RRANGE), Ok(None));
// four bytes of data
assert_eq!(p.receive(0x00), Ok(None));
assert_eq!(p.receive(0x11), Ok(None));
assert_eq!(p.receive(0x22), Ok(None));
assert_eq!(
p.receive(0x33),
Ok(Some(
Response::ReadRange { data: &[0x00, 0x11, 0x22, 0x33] },
))
);
let r = Response::ReadRange { data: &[0x00, 0x11, 0x22, 0x33] };
let mut e = ResponseEncoder::new(&r).unwrap();
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(RES_RRANGE));
assert_eq!(e.next(), Some(0x00));
assert_eq!(e.next(), Some(0x11));
assert_eq!(e.next(), Some(0x22));
assert_eq!(e.next(), Some(0x33));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn check_rsp_xrrange() {
let mut p = ResponseDecoder::new();
p.set_payload_len(4).unwrap();
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None));
assert_eq!(p.receive(RES_XRRANGE), Ok(None));
// four bytes of data
assert_eq!(p.receive(0x00), Ok(None));
assert_eq!(p.receive(0x11), Ok(None));
assert_eq!(p.receive(0x22), Ok(None));
assert_eq!(
p.receive(0x33),
Ok(Some(
Response::ExReadRange { data: &[0x00, 0x11, 0x22, 0x33] },
))
);
let r = Response::ExReadRange { data: &[0x00, 0x11, 0x22, 0x33] };
let mut e = ResponseEncoder::new(&r).unwrap();
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(RES_XRRANGE));
assert_eq!(e.next(), Some(0x00));
assert_eq!(e.next(), Some(0x11));
assert_eq!(e.next(), Some(0x22));
assert_eq!(e.next(), Some(0x33));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn check_rsp_get_attr() {
let mut p = ResponseDecoder::new();
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None));
assert_eq!(p.receive(RES_GATTR), Ok(None));
// eight bytes of key
assert_eq!(p.receive(0x00), Ok(None));
assert_eq!(p.receive(0x11), Ok(None));
assert_eq!(p.receive(0x22), Ok(None));
assert_eq!(p.receive(0x33), Ok(None));
assert_eq!(p.receive(0x44), Ok(None));
assert_eq!(p.receive(0x55), Ok(None));
assert_eq!(p.receive(0x66), Ok(None));
assert_eq!(p.receive(0x77), Ok(None));
// Length byte
assert_eq!(p.receive(0x04), Ok(None));
// length bytes of data
assert_eq!(p.receive(0xAA), Ok(None));
assert_eq!(p.receive(0xBB), Ok(None));
assert_eq!(p.receive(0xCC), Ok(None));
assert_eq!(p.receive(0xDD), Ok(None));
// 55 - length bytes of padding
for _ in 4..MAX_ATTR_LEN - 1 {
assert_eq!(p.receive(0xFF), Ok(None));
}
assert_eq!(
p.receive(0xFF),
Ok(Some(Response::GetAttr {
key: &[0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77],
value: &[0xAA, 0xBB, 0xCC, 0xDD],
}))
);
let r = Response::GetAttr {
key: &[0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77],
value: &[0xAA, 0xBB, 0xCC, 0xDD],
};
let mut e = ResponseEncoder::new(&r).unwrap();
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(RES_GATTR));
assert_eq!(e.next(), Some(0x00));
assert_eq!(e.next(), Some(0x11));
assert_eq!(e.next(), Some(0x22));
assert_eq!(e.next(), Some(0x33));
assert_eq!(e.next(), Some(0x44));
assert_eq!(e.next(), Some(0x55));
assert_eq!(e.next(), Some(0x66));
assert_eq!(e.next(), Some(0x77));
assert_eq!(e.next(), Some(0x04));
assert_eq!(e.next(), Some(0xAA));
assert_eq!(e.next(), Some(0xBB));
assert_eq!(e.next(), Some(0xCC));
assert_eq!(e.next(), Some(0xDD));
for _ in 4..MAX_ATTR_LEN {
assert!(e.next().is_some());
}
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn check_rsp_crc_int_flash() {
let mut p = ResponseDecoder::new();
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None));
assert_eq!(p.receive(RES_CRCIF), Ok(None));
// CRC
assert_eq!(p.receive(0xEF), Ok(None));
assert_eq!(p.receive(0xBE), Ok(None));
assert_eq!(p.receive(0xAD), Ok(None));
assert_eq!(
p.receive(0xDE),
Ok(Some(Response::CrcIntFlash { crc: 0xDEADBEEF }))
);
let r = Response::CrcIntFlash { crc: 0xDEADBEEF };
let mut e = ResponseEncoder::new(&r).unwrap();
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(RES_CRCIF));
assert_eq!(e.next(), Some(0xEF));
assert_eq!(e.next(), Some(0xBE));
assert_eq!(e.next(), Some(0xAD));
assert_eq!(e.next(), Some(0xDE));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn check_rsp_crc_ext_flash() {
let mut p = ResponseDecoder::new();
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None));
assert_eq!(p.receive(RES_CRCXF), Ok(None));
// CRC
assert_eq!(p.receive(0xEF), Ok(None));
assert_eq!(p.receive(0xBE), Ok(None));
assert_eq!(p.receive(0xAD), Ok(None));
assert_eq!(
p.receive(0xDE),
Ok(Some(Response::CrcExtFlash { crc: 0xDEADBEEF }))
);
let r = Response::CrcExtFlash { crc: 0xDEADBEEF };
let mut e = ResponseEncoder::new(&r).unwrap();
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(RES_CRCXF));
assert_eq!(e.next(), Some(0xEF));
assert_eq!(e.next(), Some(0xBE));
assert_eq!(e.next(), Some(0xAD));
assert_eq!(e.next(), Some(0xDE));
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn check_rsp_info() {
let mut p = ResponseDecoder::new();
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None));
assert_eq!(p.receive(RES_INFO), Ok(None));
// length
assert_eq!(p.receive(0x08), Ok(None));
// eight bytes of data
assert_eq!(p.receive(0x00), Ok(None));
assert_eq!(p.receive(0x11), Ok(None));
assert_eq!(p.receive(0x22), Ok(None));
assert_eq!(p.receive(0x33), Ok(None));
assert_eq!(p.receive(0x44), Ok(None));
assert_eq!(p.receive(0x55), Ok(None));
assert_eq!(p.receive(0x66), Ok(None));
assert_eq!(p.receive(0x77), Ok(None));
// pad up to 191 bytes
for _ in 8..MAX_INFO_LEN - 1 {
assert_eq!(p.receive(0x00), Ok(None));
}
// final padding byte
assert_eq!(
p.receive(0x00),
Ok(Some(Response::Info {
info: &[0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77],
}))
);
// Check follow-on command
assert_eq!(p.receive(ESCAPE_CHAR), Ok(None));
assert_eq!(p.receive(RES_PONG), Ok(Some(Response::Pong)));
let r = Response::Info { info: &[0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77] };
let mut e = ResponseEncoder::new(&r).unwrap();
assert_eq!(e.next(), Some(ESCAPE_CHAR));
assert_eq!(e.next(), Some(RES_INFO));
// length
assert_eq!(e.next(), Some(0x08));
// data
assert_eq!(e.next(), Some(0x00));
assert_eq!(e.next(), Some(0x11));
assert_eq!(e.next(), Some(0x22));
assert_eq!(e.next(), Some(0x33));
assert_eq!(e.next(), Some(0x44));
assert_eq!(e.next(), Some(0x55));
assert_eq!(e.next(), Some(0x66));
assert_eq!(e.next(), Some(0x77));
// padding
for _ in 8..MAX_INFO_LEN {
assert_eq!(e.next(), Some(0x00));
}
assert_eq!(e.next(), None);
assert_eq!(e.next(), None);
}
#[test]
fn check_response_write() {
let r = Response::Pong;
// More than large enough
let mut e = ResponseEncoder::new(&r).unwrap();
let mut buffer = [0xFFu8; 4];
assert_eq!(e.write(&mut buffer), 2);
assert_eq!(&buffer[0..4], &[ESCAPE_CHAR, RES_PONG, 0xFF, 0xFF]);
// Too small - do it in pieces
e.reset();
buffer[0] = 0xFF;
assert_eq!(e.write(&mut buffer[0..1]), 1);
assert_eq!(buffer[0], ESCAPE_CHAR);
buffer[0] = 0xFF;
assert_eq!(e.write(&mut buffer[0..1]), 1);
assert_eq!(buffer[0], RES_PONG);
assert_eq!(e.write(&mut buffer[0..1]), 0);
// perfectly sized
e.reset();
for b in buffer.iter_mut() {
*b = 0xFF
}
assert_eq!(e.write(&mut buffer[0..2]), 2);
assert_eq!(&buffer[0..2], &[ESCAPE_CHAR, RES_PONG]);
}
#[test]
fn check_command_write() {
let r = Command::Ping;
let mut e = CommandEncoder::new(&r).unwrap();
let mut buffer = [0xFFu8; 4];
// More than large enough
assert_eq!(e.write(&mut buffer), 2);
assert_eq!(&buffer[0..4], &[ESCAPE_CHAR, CMD_PING, 0xFF, 0xFF]);
// Too small - do it in pieces
e.reset();
buffer[0] = 0xFF;
assert_eq!(e.write(&mut buffer[0..1]), 1);
assert_eq!(buffer[0], ESCAPE_CHAR);
buffer[0] = 0xFF;
assert_eq!(e.write(&mut buffer[0..1]), 1);
assert_eq!(buffer[0], CMD_PING);
assert_eq!(e.write(&mut buffer[0..1]), 0);
// perfectly sized
e.reset();
for b in buffer.iter_mut() {
*b = 0xFF
}
assert_eq!(e.write(&mut buffer[0..2]), 2);
assert_eq!(&buffer[0..2], &[ESCAPE_CHAR, CMD_PING]);
}
#[test]
fn check_command_decode_buffer() {
let mut p = CommandDecoder::new();
let buffer = [
0xEFu8,
0xBE,
0xAD,
0xDE,
0x78,
0x56,
0x34,
0x12,
ESCAPE_CHAR,
CMD_CRCIF,
];
let callback = |x: &Command| match x {
&Command::CrcIntFlash { address, length } => {
assert_eq!(address, 0xDEADBEEF);
assert_eq!(length, 0x12345678);
}
_ => panic!("Bad command {:?}", x),
};
match p.read(&buffer, callback) {
Ok(_) => {}
Err(e) => panic!("Did not expect: {:?}", e),
}
}
#[test]
fn check_response_decode_buffer() {
let mut p = ResponseDecoder::new();
let buffer = [ESCAPE_CHAR, RES_CRCXF, 0xEF, 0xBE, 0xAD, 0xDE];
let callback = |x: &Response| match x {
&Response::CrcExtFlash { crc } => {
assert_eq!(crc, 0xDEADBEEF);
}
_ => panic!("Bad command {:?}", x),
};
match p.read(&buffer, callback) {
Ok(_) => {}
Err(e) => panic!("Did not expect: {:?}", e),
}
}
}
// ****************************************************************************
//
// End Of File
//
// ****************************************************************************
|
use crate::er::{self, Result};
use crate::project::ProjectConfig;
use crate::utils::{self, CliEnv};
use failure::format_err;
use std::path::{Path, PathBuf};
use crate::server::{SyncSet, SyncBase, SyncSentCache, SshConn};
use crate::jitsi_env_file;
use std::fs;
/// Creates config folders in project, .env file used with docker
pub fn setup_project(env: &CliEnv, project: &mut ProjectConfig) -> Result<()> {
let jitsi_config_dir = project.dir_and(env, ".jitsi-meet-cfg");
fs::create_dir_all(&jitsi_config_dir)?;
for config_sub in &["web/letsencrypt", "transcripts", "prosody", "jicofo", "jvb"] {
fs::create_dir_all(jitsi_config_dir.join(config_sub))?;
}
// .env file
let tz = "Europe/Oslo".to_string();
let local_config = jitsi_env_file::JitsiEnvConfig {
config_dir: jitsi_config_dir.to_string_lossy().to_string(),
tz: tz.clone(),
public_url: "localhost".to_string(),
letsencrypt: None,
http_port: 7000,
https_port: 7443
};
let local_content = jitsi_env_file::write_env_file(local_config)?;
let mut env_file = fs::File::create(project.dir_and(env, ".env"))?;
use std::io::Write;
env_file.write_all(local_content.as_bytes())?;
Ok(())
}
pub fn setup_project_prod(env: &CliEnv, project: &mut ProjectConfig) -> Result<()> {
let server = project.require_server(env)?;
let conn = SshConn::connect_server(env, &server)?;
// todo: This crashes with code/viddler/server (oops)
let server_project_dir = server.home_dir_and(&format!("projects/{}", project.name));
let jitsi_config_dir = server_project_dir.join(".jitsi-meet-cfg");
for config_sub in &["web/letsencrypt", "transcripts", "prosody", "jicofo", "jvb"] {
// not quite optimal but
conn.exec(format!("mkdir -p {}", jitsi_config_dir.join(config_sub).to_string_lossy()))?;
}
let tz = "Europe/Oslo".to_string();
use std::io::Write;
// .env
let (letsencrypt, public_url) = if let Some(domain) = &project.domain {
let letsencrypt = Some(jitsi_env_file::JitsiEnvConfigLetsEncrypt {
domain: domain.to_owned(),
email: "viddler.no@gmail.com".to_string()
});
(letsencrypt, format!("https://{}", domain))
} else {
(None, format!("http://{}", server.url))
};
let prod_config = jitsi_env_file::JitsiEnvConfig {
config_dir: jitsi_config_dir.to_string_lossy().to_string(),
tz,
public_url,
letsencrypt,
http_port: 80,
https_port: 443
};
let prod_content = jitsi_env_file::write_env_file(prod_config)?;
let env_local = project.dir_and(env, ".env.prod");
let mut env_file = fs::File::create(&env_local)?;
env_file.write_all(prod_content.as_bytes())?;
// Transfer file to prod with name '.env'
SyncSet::from_file(
SyncBase::local(env_local),
SyncBase::remote(server_project_dir.join(".env"), &conn.sftp()?),
false,
SyncSentCache::None
)?.sync_plain()?;
Ok(())
}
|
use speedy::{Endianness, Readable, Writable};
/// Identifies the endianness used to encapsulate the Submessage, the
/// presence of optional elements with in the Submessage, and possibly
/// modifies the interpretation of the Submessage. There are
/// 8 possible flags. The first flag (index 0) identifies the
/// endianness used to encapsulate the Submessage. The remaining
/// flags are interpreted differently depending on the kind
/// of Submessage and are described separately for each Submessage.
#[derive(Debug, PartialOrd, PartialEq, Ord, Eq, Readable, Writable)]
pub struct SubmessageFlag {
pub flags: u8,
}
impl SubmessageFlag {
/// Indicates endianness
pub fn endianness_flag(&self) -> speedy::Endianness {
if self.is_flag_set(0x01) {
Endianness::LittleEndian
} else {
Endianness::BigEndian
}
}
pub fn set_flag(&mut self, mask: u8) {
self.flags |= mask;
}
pub fn clear_flag(&mut self, mask: u8) {
self.flags &= !mask;
}
pub fn is_flag_set(&self, mask: u8) -> bool {
self.flags & mask != 0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn endianness_flag() {
assert_eq!(
Endianness::BigEndian,
SubmessageFlag { flags: 0x00 }.endianness_flag()
);
assert_eq!(
Endianness::LittleEndian,
SubmessageFlag { flags: 0x01 }.endianness_flag()
);
}
#[test]
fn correct_bits_order() {
let submessage_flag = SubmessageFlag {
flags: 0b10110100_u8,
};
assert!(!submessage_flag.is_flag_set(0b0000_0001));
assert!(!submessage_flag.is_flag_set(0b0000_0010));
assert!(submessage_flag.is_flag_set(0b0000_0100));
assert!(!submessage_flag.is_flag_set(0b0000_1000));
assert!(submessage_flag.is_flag_set(0b0001_0000));
assert!(submessage_flag.is_flag_set(0b0010_0000));
assert!(!submessage_flag.is_flag_set(0b0100_0000));
assert!(submessage_flag.is_flag_set(0b1000_0000));
}
#[test]
fn helper_functions_test() {
for x in 0..7 {
let mut flags = SubmessageFlag { flags: 0x00 };
let bit = u8::from(2).pow(x);
assert!(!flags.is_flag_set(bit));
flags.set_flag(bit);
assert!(flags.is_flag_set(bit));
flags.clear_flag(bit);
assert!(!flags.is_flag_set(bit));
}
}
serialization_test!(type = SubmessageFlag,
{
submessage_flag,
SubmessageFlag { flags: 0b10110100_u8 },
le = [0b10110100_u8],
be = [0b10110100_u8]
});
}
|
use signal_msg::{self, SignalReceiver, SignalSender};
fn main() {
let (signal_sender, signal_receiver) = signal_msg::new();
signal_sender.prepare_signals();
println!("Waiting for a signal...");
let sig = signal_receiver.listen();
println!("Got signal: {:?}", sig.unwrap());
}
|
use std::sync::Arc;
use futures::future;
use futures::sink::SinkExt;
use tokio::net::UnixStream;
use tokio_util::codec::{Framed, LinesCodec};
use persist_core::error::Error;
use persist_core::protocol::{Response, RestoreRequest, RestoreResponse};
use crate::server::State;
pub async fn handle(
state: Arc<State>,
conn: &mut Framed<UnixStream, LinesCodec>,
req: RestoreRequest,
) -> Result<(), Error> {
let futures = req.specs.into_iter().map(|spec| async {
let name = spec.name.clone();
let res = state.clone().start(spec).await;
let error = res.err().map(|err| err.to_string());
Ok::<_, Error>(RestoreResponse { name, error })
});
let responses = future::try_join_all(futures).await?;
let response = Response::Restore(responses);
let serialized = json::to_string(&response)?;
conn.send(serialized).await?;
Ok(())
}
|
use actix_identity::IdentityPolicy;
use actix_session::UserSession;
use actix_web::Error;
use futures::future::{ready, Ready};
use std::rc::Rc;
struct SessionIdentityInner {
key: String,
}
pub struct SessionIdentiyPolicy(Rc<SessionIdentityInner>);
impl SessionIdentiyPolicy {
pub fn new() -> SessionIdentiyPolicy {
SessionIdentiyPolicy(Rc::new(SessionIdentityInner {
key: "Identity".to_string(),
}))
}
pub fn key(mut self, value: &str) -> SessionIdentiyPolicy {
Rc::get_mut(&mut self.0).unwrap().key = value.into();
self
}
}
impl IdentityPolicy for SessionIdentiyPolicy {
type Future = Ready<Result<Option<String>, Error>>;
type ResponseFuture = Ready<Result<(), Error>>;
fn from_request(&self, req: &mut actix_web::dev::ServiceRequest) -> Self::Future {
let session = req.get_session();
let key = &self.0.key;
ready(session.get::<String>(key).or(Ok(None)))
}
fn to_response<B>(
&self,
identity: Option<String>,
changed: bool,
response: &mut actix_web::dev::ServiceResponse<B>,
) -> Self::ResponseFuture {
let session = response.request().get_session();
let key = &self.0.key;
let ret = if changed {
session.set(key, identity)
} else {
Ok(())
};
ready(ret)
}
}
|
use super::*;
use std::io::Read;
use super::bytecode::{Op, OpIterator};
pub struct CodeSection<'a> {
pub count: u32,
pub entries_raw: &'a [u8],
}
pub struct CodeIterator<'a> {
count: u32,
iter: &'a [u8]
}
pub struct FunctionBody<'a> {
pub local_count: usize,
pub body: &'a [u8],
}
pub struct FunctionIterator<'a> {
local_count: usize,
opiter: Option<OpIterator<'a>>,
iter: &'a [u8],
}
pub enum FunctionPart<'a> {
Local(Local),
Op(Op<'a>),
}
pub struct Local {
pub count: u32,
pub ty: ValueType,
}
impl<'a> CodeSection<'a> {
pub fn entries(&self) -> CodeIterator<'a> {
CodeIterator {
count: self.count,
iter: self.entries_raw
}
}
}
impl<'a> Iterator for CodeIterator<'a> {
type Item = Result<FunctionBody<'a>, Error>;
fn next(&mut self) -> Option<Self::Item> {
if self.count == 0 {
return None
}
self.count -= 1;
let body_size = try_opt!(read_varuint(&mut self.iter)) as usize;
let mut body = {
let res = &self.iter[..body_size];
self.iter = &self.iter[body_size..];
res
};
let local_count = try_opt!(read_varuint(&mut body)) as usize;
Some(Ok(FunctionBody {
local_count: local_count,
body: body,
}))
}
}
impl<'a> FunctionBody<'a> {
pub fn contents(&self) -> FunctionIterator<'a> {
FunctionIterator {
local_count: self.local_count,
opiter: None,
iter: self.body
}
}
}
impl<'a> Iterator for FunctionIterator<'a> {
type Item = Result<FunctionPart<'a>, Error>;
fn next(&mut self) -> Option<Self::Item> {
if self.local_count == 0 && self.opiter.is_none() {
self.opiter = Some(OpIterator::new(self.iter))
}
if let Some(ref mut iter) = self.opiter {
return iter.next().map(|x| x.map(FunctionPart::Op))
}
self.local_count -= 1;
let count = try_opt!(read_varuint(&mut self.iter)) as u32;
let mut ty = [0; 1];
try_opt!((&mut self.iter).read_exact(&mut ty));
let ty = try_opt!(ValueType::from_int(ty[0]).ok_or(Error::UnknownVariant("value type")));
Some(Ok(FunctionPart::Local(Local {
count: count,
ty: ty,
})))
}
}
|
extern crate byteorder;
use self::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian, ByteOrder};
const MAGIC: &'static [u8] = b"tsrust.wal.0000\n";
const MAGIC_LEN: usize = 16;
use ::std::io::{BufWriter,BufReader};
use ::std::path::{Path,PathBuf};
use std::io::Write;
use std::io::Read;
use wal::MemoryWal;
/// Write files in our WAL file format
///
/// The WAL files are written and discarded
/// once data for the WAL's generation is written
/// and synced to the block file.
///
/// The WAL files are read only on startup
/// to regenerate the in-memory WAL data.
pub struct DiskWalWriter
{
file: BufWriter<::std::fs::File>,
}
impl DiskWalWriter
{
/// create a file inside of `dir`
/// for data of the given generation
pub fn new(generation: u64, dir: &Path)
-> (DiskWalWriter, PathBuf)
{
for idx in 0..10000
{
let filename =
{
use ::std::time::SystemTime;
let now = SystemTime::now();
let d = now.duration_since(
::std::time::UNIX_EPOCH
).unwrap();
format!(
"blocks-{}{}-{}.wal",
d.as_secs(),
d.subsec_nanos(),
idx,
)
};
let filepath = dir.join(&filename);
let fileres = ::std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(filepath.clone());
if let Ok(file) = fileres
{
let mut file = BufWriter::new(file);
file.write_all(MAGIC).unwrap();
file.write_u64::<BigEndian>(generation).unwrap();
let z = &[0u8; 512-MAGIC_LEN-8];
file.write_all(z).unwrap();
file.flush().unwrap();
return (
DiskWalWriter
{
file: file,
},
filepath,
);
}
}
panic!("failed to create wal file");
}
/// write a single record, with its magic number
pub fn write(&mut self, position: u64, data: &[u8])
{
self.file.write_i32::<BigEndian>(0x07010503).unwrap();
self.file.write_u64::<BigEndian>(position).unwrap();
self.file.write_u64::<BigEndian>(data.len() as u64).unwrap();
self.file.write_all(data).unwrap();
}
}
/// Mark the file as completed, sync the file, and finally close it
impl Drop for DiskWalWriter
{
fn drop(&mut self)
{
self.file.write_i32::<BigEndian>(0x0d011e00).unwrap();
self.file.flush().unwrap();
self.file.get_ref().sync_all().unwrap();
}
}
/// Read a file written by the `DiskWalWriter`.
///
/// This code is run only on startup to restore the
/// last state after a shutdown with its committed
/// but unmerged transactions.
pub struct DiskWalReader
{
filename: PathBuf,
file: BufReader<::std::fs::File>,
generation: u64,
}
impl DiskWalReader
{
pub fn open(filename: &Path) -> DiskWalReader
{
let mut file = BufReader::new(
::std::fs::File::open(filename).unwrap()
);
let mut header = [0u8; 512];
file.read_exact(&mut header).unwrap();
if !header.starts_with(&MAGIC)
{ panic!("invalid wal file: {:?}", filename); }
let generation =
BigEndian::read_u64(&header[MAGIC.len()..MAGIC.len()+8]);
DiskWalReader
{
filename: filename.to_path_buf(),
file: file,
generation: generation,
}
}
pub fn read_into(&mut self, into: &mut MemoryWal)
{
let ref mut f = self.file;
let mut buf = vec!();
loop
{
let code = f.read_u32::<BigEndian>();
if let Err(e) = code.as_ref()
{
// this is a sign the program was exited before
// this wal file was fully written.
// It's ok to apply the changes so far
// because the meta db ensures they're not used
if e.kind() == ::std::io::ErrorKind::UnexpectedEof
{ break; }
}
let code = code.unwrap();
if code == 0x0d011e00
{ break; }
else if code == 0x07010503
{
let position = f.read_u64::<BigEndian>();
if let Err(e) = position.as_ref()
{
if e.kind() == ::std::io::ErrorKind::UnexpectedEof
{ break; }
}
let position = position.unwrap();
let len = f.read_u64::<BigEndian>();
if let Err(e) = len.as_ref()
{
if e.kind() == ::std::io::ErrorKind::UnexpectedEof
{ break; }
}
let len = len.unwrap();
buf.resize(len as usize, 0u8);
let e = f.read_exact(&mut buf);
if let Err(e) = e
{
if e.kind() == ::std::io::ErrorKind::UnexpectedEof
{ break; }
}
into.write(position as usize, &buf);
}
else
{
panic!("invalid wal file: {:?}", self.filename);
}
}
}
pub fn generation(&self) -> u64
{
self.generation
}
}
|
use crate::controls::{Adapted, Control, HasLabel};
use crate::sdk;
use crate::types::{adapter, AsAny, Adapter, Spawnable};
use std::any::Any;
use std::marker::PhantomData;
pub struct StringVecAdapter<C: HasLabel + Spawnable> {
items: Vec<String>,
on_item_change: Option<sdk::AdapterInnerCallback>,
_marker: PhantomData<C>,
}
impl<C: HasLabel + Spawnable> From<Vec<String>> for StringVecAdapter<C> {
fn from(a: Vec<String>) -> Self {
StringVecAdapter { items: a, on_item_change: None, _marker: PhantomData }
}
}
impl<C: HasLabel + Spawnable> StringVecAdapter<C> {
pub fn new() -> Self {
Self::from(Vec::new())
}
pub fn with_iterator<'a, T, I>(i: I) -> Self where T: AsRef<str>, I: Iterator<Item=T> {
let mut t = Self::new();
for item in i {
t.items.push(String::from(item.as_ref()));
}
t
}
pub fn with_into_iterator<'a, T, I>(i: I) -> Self where T: AsRef<str>, I: IntoIterator<Item=T> {
Self::with_iterator(i.into_iter())
}
pub fn text_at(&self, i: usize) -> Option<&String> {
self.items.get(i)
}
pub fn text_at_mut(&mut self, i: usize) -> Option<&mut String> {
self.items.get_mut(i)
}
pub fn push<T: AsRef<str>>(&mut self, arg: T) {
let i = self.items.len();
self.items.push(String::from(arg.as_ref()));
if let Some(ref mut cb) = self.on_item_change.as_mut() {
cb.on_item_change(adapter::Change::Added(&[i], adapter::Node::Leaf))
}
}
pub fn pop(&mut self) -> Option<String> {
let t = self.items.pop();
let i = self.items.len();
if let Some(ref mut cb) = self.on_item_change.as_mut() {
cb.on_item_change(adapter::Change::Removed(&[i]))
}
t
}
}
impl<C: HasLabel + Spawnable> AsAny for StringVecAdapter<C> {
#[inline]
fn as_any(&self) -> &dyn Any {
self
}
#[inline]
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
#[inline]
fn into_any(self: Box<Self>) -> Box<dyn Any> {
self
}
}
impl<C: HasLabel + Spawnable> Adapter for StringVecAdapter<C> {
fn len_at(&self, indexes: &[usize]) -> Option<usize> {
if indexes.len() == 0 {
Some(self.items.len())
} else {
None
}
}
fn node_at(&self, indexes: &[usize]) -> Option<adapter::Node> {
if indexes.len() == 1 {
Some(adapter::Node::Leaf)
} else {
None
}
}
fn spawn_item_view(&mut self, indexes: &[usize], _parent: &dyn Adapted) -> Option<Box<dyn Control>> {
if indexes.len() == 1 {
let mut control = C::spawn();
control.as_any_mut().downcast_mut::<C>().unwrap().set_label(self.items[indexes[0]].as_str().into());
Some(control)
} else {
None
}
}
fn for_each<'a, 'b:'a, 'c: 'b>(&'c self, f: &'a mut dyn adapter::FnNodeItem) {
let mut iter = self.items.iter().enumerate();
while let Some((index, _item)) = iter.next() {
f(&[index], &adapter::Node::Leaf);
}
}
}
impl<C: HasLabel + Spawnable> sdk::AdapterInner for StringVecAdapter<C> {
fn on_item_change(&mut self, cb: Option<sdk::AdapterInnerCallback>) {
self.on_item_change = cb;
}
}
|
use std::path::PosixPath;
use monster::{Skeleton, Mummy, Monster, SkeletonTy, MummyTy};
#[deriving(ToStr,Eq)]
pub enum Cell {
Floor = 0,
Wall,
Door,
Mummy,
Skeleton
}
pub struct Level {
priv monsters: ~[~Monster],
priv cell_data: ~[~[Cell]]
}
impl Level {
pub fn new (monsters: ~[~Monster], data: ~[~[Cell]]) -> Level {
Level {monsters: monsters, cell_data: data}
}
}
pub fn load_level(path: &PosixPath) -> Level {
use std::io::File;
use std::io::BufferedReader;
let reader = match File::open(path) {
Some(r) => r,
None => fail!("Couldn't open file")
};
let reader = BufferedReader::new(reader);
// let lines_as_str = reader.read_lines();
let mut monster = ~[];
let level_data = reader.lines()
.enumerate()
.map(|(i, l)| -> ~[Cell] {
l.chars()
.enumerate()
.map(|(j, b)| -> Cell {
match b {
'1' => Wall,
'0' => Floor,
'2' => Door,
'3' => {
monster.push(Monster::factory(i as int, j as int, MummyTy));
Mummy
}
'4' => {
monster.push(Monster::factory(i as int, j as int, SkeletonTy));
Skeleton
}
_ => fail!("Invalid level file")
}
})
.collect()
})
.collect();
Level::new(monster,level_data)
}
|
fn main()
{
println!("Hello World!");
}//End of main method |
//! # The segmented (`*.sd0`) compression format
//!
//! This format is used to deflate (zlib) the data served from the server to the client,
//! and to use less space in the pack archives.
//!
//! ## Serialization
//!
//! ```text
//! [L:5] 's' 'd' '0' 0x01 0xff
//! repeated:
//! [u32] length V (of the following chunk)
//! [L:V] zlib stream (deflate with zlib header)
//! ```
/// The magic bytes for the sd0 format
pub const MAGIC: &[u8; 5] = b"sd0\x01\xff";
use std::io::Cursor;
pub use flate2::Compression;
pub mod read;
pub mod write;
/// Encode a byte slice into a vector
pub fn encode<B: AsRef<[u8]>>(
data: B,
output: &mut Vec<u8>,
level: Compression,
) -> write::Result<()> {
let input = data.as_ref();
let mut reader = Cursor::new(input);
let writer = Cursor::new(output);
let mut writer = write::SegmentedEncoder::new(writer, level)?;
std::io::copy(&mut reader, &mut writer)?;
Ok(())
}
/// Decode a byte slice into a vector
pub fn decode<B: AsRef<[u8]>>(data: B, output: &mut Vec<u8>) -> read::Result<()> {
let mut writer = Cursor::new(output);
let compressed = Cursor::new(data);
let mut reader = read::SegmentedDecoder::new(compressed)?;
std::io::copy(&mut reader, &mut writer)?;
Ok(())
}
#[cfg(test)]
mod tests {
use crate::sd0::encode;
use super::{decode, Compression};
use std::io;
fn roundtrip(data: &[u8]) -> io::Result<Vec<u8>> {
let mut compressed = Vec::with_capacity(data.len() / 2);
super::encode(data, &mut compressed, Compression::best())?;
let mut decompressed = Vec::with_capacity(data.len());
super::decode(&compressed, &mut decompressed)?;
Ok(decompressed)
}
#[test]
fn test_roundtrip() {
let short = lipsum::lipsum(100);
let test = roundtrip(short.as_bytes()).unwrap();
assert_eq!(&test, short.as_bytes());
}
#[test]
fn test_decode_empty() {
let empty = super::MAGIC;
let mut output = Vec::new();
decode(empty, &mut output).unwrap();
assert_eq!(output.len(), 0);
}
#[test]
fn test_encode_empty() {
let empty = &[];
let mut output = Vec::new();
encode(empty, &mut output, Compression::best()).unwrap();
assert_eq!(output, super::MAGIC);
}
}
|
use anyhow::{anyhow, ensure, Error, Result};
use indexmap::{map::Entry, IndexMap};
use rand::prelude::*;
use std::{
cmp::Ordering,
collections::BinaryHeap,
convert::TryInto,
fmt,
hash::Hash,
io::{stdin, Read},
iter::Peekable,
str::FromStr,
vec,
};
use structopt::StructOpt;
// i took inspiration from
// https://github.com/samueltardieu/pathfinding/blob/main/src/directed/astar.rs
// (mainly: using indexmap (perf!) & efficient astar impl structure)
// because my a* implementation was sooo slow (it was using Rc & RefCell and it's very hard to avoid using these
// unless you have access to indexmap or something like it)
#[derive(Debug, Clone)]
struct SmallestCostHolder {
estimated_cost: usize,
cost: usize,
index: usize,
}
impl PartialEq for SmallestCostHolder {
fn eq(&self, other: &Self) -> bool {
self.estimated_cost.eq(&other.estimated_cost) && self.cost.eq(&other.cost)
}
}
impl Eq for SmallestCostHolder {}
impl PartialOrd for SmallestCostHolder {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for SmallestCostHolder {
fn cmp(&self, other: &Self) -> Ordering {
match other.estimated_cost.cmp(&self.estimated_cost) {
Ordering::Equal => self.cost.cmp(&other.cost),
s => s,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NPuzzleSolver {
tiles: Board,
target: Board,
n: usize,
}
pub struct AStarResult {
pub states: Option<Vec<Board>>,
pub open_set_counter: usize,
pub max_states_in_mem: usize,
}
impl NPuzzleSolver {
pub fn new(n: usize) -> NPuzzleSolver {
assert!(n >= 2);
let mut puzzle = NPuzzleSolver {
n,
tiles: Board::new(n),
target: Board::new(n),
};
puzzle.gen_target();
puzzle
}
pub fn from_str(ite: impl Iterator<Item = char>) -> Result<NPuzzleSolver> {
let mut peekable = ite.peekable();
fn finish_line(peekable: &mut Peekable<impl Iterator<Item = char>>) -> bool {
let mut line_finished = false;
loop {
match peekable.peek() {
Some('#') => {
peekable.next();
while !matches!(peekable.peek(), Some('\n')) {
peekable.next();
}
}
Some('\n') => {
line_finished = true;
peekable.next();
}
Some(' ') | Some('\t') | Some('\r') => {
peekable.next();
}
_ => break line_finished,
}
}
};
fn eat_whitespaces(peekable: &mut Peekable<impl Iterator<Item = char>>) {
while peekable
.peek()
.map_or(false, |c| matches!(c, ' ' | '\t' | '\r'))
{
peekable.next();
}
};
fn eat_number(peekable: &mut Peekable<impl Iterator<Item = char>>) -> Option<u32> {
if !matches!(peekable.peek(), Some('0'..='9')) {
return None;
}
let mut n = 0;
while matches!(peekable.peek(), Some('0'..='9')) {
let c = peekable.next().unwrap();
n = n * 10 + c.to_digit(10).unwrap();
}
Some(n)
};
finish_line(&mut peekable);
let n = eat_number(&mut peekable)
.ok_or_else(|| anyhow!("expected size of puzzle"))?
.try_into()?;
ensure!(n > 2, "size of puzzle must be greater than 2");
let mut puzzle = NPuzzleSolver::new(n);
for y in 0..n {
ensure!(finish_line(&mut peekable), "expected newline");
for x in 0..n {
eat_whitespaces(&mut peekable);
let n = eat_number(&mut peekable).ok_or_else(|| anyhow!("expected number"))?;
puzzle.tiles.0[puzzle.n * y + x] = n.try_into()?;
eat_whitespaces(&mut peekable);
}
}
finish_line(&mut peekable);
ensure!(peekable.peek() == None, "expected EOF");
for num in 0..(n * n) {
ensure!(
puzzle.tiles.0.iter().any(|t| *t as usize == num),
"the number {} is missing from the puzzle",
num
);
}
Ok(puzzle)
}
pub fn random(n: usize, rng: &mut ThreadRng) -> NPuzzleSolver {
let mut puzzle = NPuzzleSolver::new(n);
puzzle.tiles.0.copy_from_slice(&puzzle.target.0);
for _ in 0..128 {
let empty_tile = puzzle.tiles.0.iter().position(|c| *c == 0).unwrap();
let moves = Self::possible_moves(empty_tile, n);
let possible_moves = moves.iter().copied().filter_map(|e| e).collect::<Vec<_>>();
let mv = possible_moves[rng.gen_range(0..possible_moves.len())];
puzzle.tiles.0.swap(empty_tile, mv);
}
puzzle
}
fn gen_target(&mut self) {
let mut x = 0;
let mut y = 0;
let mut direction = 0; // Right, Bottom, Left, Top
for i in 1..(self.n * self.n) {
self.target.0[y * self.n + x] = i as u16;
let change_dir = match direction {
0 if x == self.n - 1 || self.target.0[(y + 0) * self.n + (x + 1)] != 0 => true,
1 if y == self.n - 1 || self.target.0[(y + 1) * self.n + (x + 0)] != 0 => true,
2 if x == 0 || self.target.0[(y + 0) * self.n + (x - 1)] != 0 => true,
3 if y == 0 || self.target.0[(y - 1) * self.n + (x + 0)] != 0 => true,
_ => false,
};
if change_dir {
direction = (direction + 1) % 4;
}
match direction {
0 => x += 1,
1 => y += 1,
2 => x -= 1,
3 => y -= 1,
_ => unreachable!(),
}
}
}
pub fn get_n(&self) -> usize {
self.n
}
pub fn index_to_xy(index: usize, n: usize) -> (usize, usize) {
(index % n, index / n)
}
fn possible_moves(empty_tile: usize, n: usize) -> [Option<usize>; 4] {
[
{
if empty_tile % n == n - 1 {
None
} else {
Some(empty_tile + 1)
}
},
{
if empty_tile % n == 0 {
None
} else {
Some(empty_tile - 1)
}
},
{
if empty_tile / n == n - 1 {
None
} else {
Some(empty_tile + n)
}
},
{
if empty_tile / n == 0 {
None
} else {
Some(empty_tile - n)
}
},
]
}
fn astar_successors(board: &Board, n: usize) -> Vec<Board> {
let empty_tile = board.0.iter().position(|c| *c == 0).unwrap();
let arr = Self::possible_moves(empty_tile, n);
arr.iter()
.copied()
.filter_map(|e| e)
.map(|mv| {
let mut board = board.clone();
board.0.swap(empty_tile, mv);
board
})
.collect()
}
pub fn perform_astar(&mut self, h: Heuristics) -> AStarResult {
let mut to_see = BinaryHeap::new();
let mut open_set_counter = 1; // initial state: 1 node in open set
to_see.push(SmallestCostHolder {
cost: 0,
index: 0,
estimated_cost: 0,
});
let mut parents: IndexMap<Board, (usize, usize)> = IndexMap::default();
parents.insert(self.tiles.clone(), (usize::max_value(), 0));
while let Some(SmallestCostHolder { cost, index, .. }) = to_see.pop() {
let successors = {
let (node, &(_, c)) = parents.get_index(index).unwrap();
if &self.target == node {
// reverse path
let mut vec = Vec::new();
let mut index = index;
while let Some((node, &(ind, _))) = parents.get_index(index) {
index = ind;
vec.push(node.clone());
}
return AStarResult {
states: Some(vec),
open_set_counter,
max_states_in_mem: parents.len(),
};
}
if cost > c {
continue;
}
Self::astar_successors(node, self.n)
};
for successor in successors {
let new_cost = cost + 1; // move_cost = 1
let heu;
let succ_index;
match parents.entry(successor) {
Entry::Vacant(e) => {
heu = h.run_heuristic(e.key(), &self.target, self.n);
succ_index = e.index();
e.insert((index, new_cost));
}
Entry::Occupied(mut e) => {
if e.get().1 > new_cost {
heu = h.run_heuristic(e.key(), &self.target, self.n);
succ_index = e.index();
e.insert((index, new_cost));
} else {
continue;
}
}
}
to_see.push(SmallestCostHolder {
estimated_cost: new_cost + heu,
cost: new_cost,
index: succ_index,
});
open_set_counter += 1;
}
}
AStarResult {
states: None,
open_set_counter,
max_states_in_mem: parents.len(),
}
}
}
impl fmt::Display for NPuzzleSolver {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.tiles)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Board(pub Vec<u16>);
impl Board {
pub fn new(n: usize) -> Board {
Board(vec![0; n * n])
}
}
impl fmt::Display for Board {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let n = (self.0.len() as f64).sqrt() as usize;
let n_width = (*self.0.iter().max().unwrap() as f64).log10() as usize + 1;
let fmt_tile = |t: u16, f: &mut fmt::Formatter<'_>| match t {
0 => write!(f, "{:^width$}", "", width = n_width),
n => write!(f, "{:^width$}", n, width = n_width),
};
for y in 0..n {
if y == 0 {
write!(f, "[")?;
} else {
write!(f, " ")?;
}
write!(f, "[ ")?;
for x in 0..n {
fmt_tile(self.0[y * n + x], f)?;
write!(f, " ")?;
}
write!(f, "]")?;
if y == n - 1 {
write!(f, "]\n")?;
} else {
write!(f, ",\n")?;
}
}
Ok(())
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, StructOpt)]
pub enum Heuristics {
ManhattanDistance,
MisplacedTiles,
EuclideanDistanceSquared,
}
impl FromStr for Heuristics {
type Err = Error;
fn from_str(day: &str) -> Result<Self, Self::Err> {
match day {
"manhattan" => Ok(Heuristics::ManhattanDistance),
"misplaced" => Ok(Heuristics::ManhattanDistance),
"euclidean" => Ok(Heuristics::ManhattanDistance),
_ => Err(anyhow!("Could not parse heuristic")),
}
}
}
impl fmt::Display for Heuristics {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
Heuristics::ManhattanDistance => "manhattan distance",
Heuristics::MisplacedTiles => "number of misplaced tiles",
Heuristics::EuclideanDistanceSquared => "euclidean distance squared",
}
)
}
}
impl Heuristic for Heuristics {
fn run_heuristic(&self, puzzle: &Board, target: &Board, n: usize) -> usize {
match *self {
Heuristics::ManhattanDistance => {
ManhattanDistanceHeuristic.run_heuristic(puzzle, target, n)
}
Heuristics::MisplacedTiles => MisplacedTilesHeuristic.run_heuristic(puzzle, target, n),
Heuristics::EuclideanDistanceSquared => {
EuclideanDistanceSquaredHeuristic.run_heuristic(puzzle, target, n)
}
}
}
}
pub trait Heuristic {
fn run_heuristic(&self, puzzle: &Board, target: &Board, n: usize) -> usize;
}
struct MisplacedTilesHeuristic;
impl Heuristic for MisplacedTilesHeuristic {
fn run_heuristic(&self, puzzle: &Board, target: &Board, _n: usize) -> usize {
puzzle
.0
.iter()
.zip(&target.0)
.filter(|(t, tg)| t != tg)
.count()
}
}
struct ManhattanDistanceHeuristic;
impl Heuristic for ManhattanDistanceHeuristic {
fn run_heuristic(&self, puzzle: &Board, target: &Board, n: usize) -> usize {
let mut res = 0;
for (index, el) in puzzle.0.iter().enumerate() {
let index_tg = target.0.iter().position(|t| t == el).unwrap();
let (x, y) = NPuzzleSolver::index_to_xy(index, n);
let (x_tg, y_tg) = NPuzzleSolver::index_to_xy(index_tg, n);
res +=
((x as isize - x_tg as isize).abs() + (y as isize - y_tg as isize).abs()) as usize;
}
res
}
}
struct EuclideanDistanceSquaredHeuristic;
impl Heuristic for EuclideanDistanceSquaredHeuristic {
fn run_heuristic(&self, puzzle: &Board, target: &Board, n: usize) -> usize {
let mut res = 0;
for (index, el) in puzzle.0.iter().enumerate() {
let index_tg = target.0.iter().position(|t| t == el).unwrap();
let (x, y) = NPuzzleSolver::index_to_xy(index, n);
let (x_tg, y_tg) = NPuzzleSolver::index_to_xy(index_tg, n);
res += ((x as isize - x_tg as isize).pow(2) + (y as isize - y_tg as isize).pow(2))
as usize;
}
res
}
}
#[derive(Debug, Clone, StructOpt)]
#[structopt(name = "example", about = "An example of StructOpt usage.")]
pub struct Args {
/// The heuristic to use (possible values: manhattan, misplaced, euclidean)
#[structopt(short, long, default_value = "manhattan")]
pub heuristic: Heuristics,
/// The size of the puzzle to generate.
///
/// If set, the program will not read the puzzle from stdin, but will create
/// a random puzzle instead.
#[structopt(short, long)]
pub random_size: Option<usize>,
}
fn main() -> Result<()> {
let args = Args::from_args();
let mut puzzle = if let Some(n) = args.random_size {
NPuzzleSolver::random(n, &mut rand::thread_rng())
} else {
println!("Reading puzzle from stdin...");
let mut buf = String::new();
stdin().read_to_string(&mut buf)?;
NPuzzleSolver::from_str(buf.chars())?
};
println!("-- Initial state --\n{}", puzzle.tiles);
println!("Solving...\n");
let heuristic = args.heuristic;
let result = puzzle.perform_astar(heuristic);
if let Some(states) = result.states {
println!("-- Solving sequence --");
for (ind, state) in states.iter().rev().skip(1).enumerate() {
println!("move #{:03}:\n{}", ind + 1, state);
}
println!("-- Summary --");
println!("heuristic: {}", heuristic);
println!("solvable: yes");
println!("number of moves required: {}", states.len() - 1);
println!(
"total number of states ever selected in the open set: {}",
result.open_set_counter
);
println!(
"maximum number of states ever represented in memory at the same time: {}",
result.max_states_in_mem
);
} else {
println!("-- Summary --");
println!("heuristic: {}", heuristic);
println!("solvable: no");
println!("number of moves required: N/A");
println!(
"total number of states ever selected in the open set: {}",
result.open_set_counter
);
println!(
"maximum number of states ever represented in memory at the same time: {}",
result.max_states_in_mem
);
}
Ok(())
}
|
use crate::prelude::*;
#[inline(always)]
pub fn byte_to_hex(b: u8) -> char {
debug_assert!(b < 16);
(if b < 10 { b'0' + b } else { b'a' - 10 + b }) as char
}
pub fn write_u64_to_buffer(buffer: &mut Vec<u8>, mut nr: u64) {
let start_len = buffer.len();
loop {
buffer.push((nr % 10) as u8 + b'0');
if nr < 10 {
break;
}
nr /= 10;
}
(&mut buffer[start_len..]).reverse();
}
pub fn pt1(input: &str) -> Result<String> {
let mut out = String::with_capacity(8);
let mut buffer = Vec::with_capacity(input.len() + 10);
for c in input.chars() {
buffer.push(c as u8);
}
for i in 0u64.. {
buffer.truncate(input.len());
write_u64_to_buffer(&mut buffer, i);
let md5::Digest(bytes) = md5::compute(&buffer);
if bytes[0] == 0 && bytes[1] == 0 && bytes[2] < 16 {
out.push(byte_to_hex(bytes[2]));
if out.len() == 8 {
return Ok(out);
}
}
}
unreachable!()
}
pub fn pt2(input: &str) -> Result<String> {
let mut out = [' '; 8];
let mut fill_count = 0;
let mut buffer = Vec::with_capacity(input.len() + 10);
for c in input.chars() {
buffer.push(c as u8);
}
for i in 0u64.. {
buffer.truncate(input.len());
write_u64_to_buffer(&mut buffer, i);
let md5::Digest(bytes) = md5::compute(&buffer);
if bytes[0] != 0 || bytes[1] != 0 || bytes[2] >= 8 {
continue;
}
if out[bytes[2] as usize] != ' ' {
continue;
}
out[bytes[2] as usize] = byte_to_hex(bytes[3] >> 4);
fill_count += 1;
if fill_count == 8 {
return Ok(out.iter().collect());
}
}
unreachable!()
}
#[test]
#[ignore]
fn day05() -> Result<()> {
{
let mut buffer = vec![b'a', b'b', b'c'];
write_u64_to_buffer(&mut buffer, 1234);
assert_eq!(buffer, vec![b'a', b'b', b'c', b'1', b'2', b'3', b'4']);
}
test_part!(pt1, "abc" => "18f47a30".to_owned());
test_part!(pt2, "abc" => "05ace8e3".to_owned());
Ok(())
}
|
/*
* Slack Web API
*
* One way to interact with the Slack platform is its HTTP RPC-based Web API, a collection of methods requiring OAuth 2.0-based user, bot, or workspace tokens blessed with related OAuth scopes.
*
* The version of the OpenAPI document: 1.7.0
*
* Generated by: https://openapi-generator.tech
*/
use reqwest;
use crate::apis::ResponseContent;
use super::{Error, configuration};
/// struct for typed errors of method `admin_users_assign`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AdminUsersAssignError {
DefaultResponse(::std::collections::HashMap<String, serde_json::Value>),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `admin_users_invite`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AdminUsersInviteError {
DefaultResponse(::std::collections::HashMap<String, serde_json::Value>),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `admin_users_list`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AdminUsersListError {
DefaultResponse(::std::collections::HashMap<String, serde_json::Value>),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `admin_users_remove`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AdminUsersRemoveError {
DefaultResponse(::std::collections::HashMap<String, serde_json::Value>),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `admin_users_set_admin`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AdminUsersSetAdminError {
DefaultResponse(::std::collections::HashMap<String, serde_json::Value>),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `admin_users_set_expiration`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AdminUsersSetExpirationError {
DefaultResponse(::std::collections::HashMap<String, serde_json::Value>),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `admin_users_set_owner`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AdminUsersSetOwnerError {
DefaultResponse(::std::collections::HashMap<String, serde_json::Value>),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `admin_users_set_regular`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AdminUsersSetRegularError {
DefaultResponse(::std::collections::HashMap<String, serde_json::Value>),
UnknownValue(serde_json::Value),
}
/// Add an Enterprise user to a workspace.
pub async fn admin_users_assign(configuration: &configuration::Configuration, token: &str, team_id: &str, user_id: &str, is_restricted: Option<bool>, is_ultra_restricted: Option<bool>, channel_ids: Option<&str>) -> Result<::std::collections::HashMap<String, serde_json::Value>, Error<AdminUsersAssignError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/admin.users.assign", configuration.base_path);
let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
local_var_req_builder = local_var_req_builder.header("token", token.to_string());
if let Some(ref local_var_token) = configuration.oauth_access_token {
local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned());
};
let mut local_var_form_params = std::collections::HashMap::new();
local_var_form_params.insert("team_id", team_id.to_string());
local_var_form_params.insert("user_id", user_id.to_string());
if let Some(local_var_param_value) = is_restricted {
local_var_form_params.insert("is_restricted", local_var_param_value.to_string());
}
if let Some(local_var_param_value) = is_ultra_restricted {
local_var_form_params.insert("is_ultra_restricted", local_var_param_value.to_string());
}
if let Some(local_var_param_value) = channel_ids {
local_var_form_params.insert("channel_ids", local_var_param_value.to_string());
}
local_var_req_builder = local_var_req_builder.form(&local_var_form_params);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<AdminUsersAssignError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Invite a user to a workspace.
pub async fn admin_users_invite(configuration: &configuration::Configuration, token: &str, team_id: &str, email: &str, channel_ids: &str, custom_message: Option<&str>, real_name: Option<&str>, resend: Option<bool>, is_restricted: Option<bool>, is_ultra_restricted: Option<bool>, guest_expiration_ts: Option<&str>) -> Result<::std::collections::HashMap<String, serde_json::Value>, Error<AdminUsersInviteError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/admin.users.invite", configuration.base_path);
let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
local_var_req_builder = local_var_req_builder.header("token", token.to_string());
if let Some(ref local_var_token) = configuration.oauth_access_token {
local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned());
};
let mut local_var_form_params = std::collections::HashMap::new();
local_var_form_params.insert("team_id", team_id.to_string());
local_var_form_params.insert("email", email.to_string());
local_var_form_params.insert("channel_ids", channel_ids.to_string());
if let Some(local_var_param_value) = custom_message {
local_var_form_params.insert("custom_message", local_var_param_value.to_string());
}
if let Some(local_var_param_value) = real_name {
local_var_form_params.insert("real_name", local_var_param_value.to_string());
}
if let Some(local_var_param_value) = resend {
local_var_form_params.insert("resend", local_var_param_value.to_string());
}
if let Some(local_var_param_value) = is_restricted {
local_var_form_params.insert("is_restricted", local_var_param_value.to_string());
}
if let Some(local_var_param_value) = is_ultra_restricted {
local_var_form_params.insert("is_ultra_restricted", local_var_param_value.to_string());
}
if let Some(local_var_param_value) = guest_expiration_ts {
local_var_form_params.insert("guest_expiration_ts", local_var_param_value.to_string());
}
local_var_req_builder = local_var_req_builder.form(&local_var_form_params);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<AdminUsersInviteError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// List users on a workspace
pub async fn admin_users_list(configuration: &configuration::Configuration, token: &str, team_id: &str, cursor: Option<&str>, limit: Option<i32>) -> Result<::std::collections::HashMap<String, serde_json::Value>, Error<AdminUsersListError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/admin.users.list", configuration.base_path);
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
local_var_req_builder = local_var_req_builder.query(&[("team_id", &team_id.to_string())]);
if let Some(ref local_var_str) = cursor {
local_var_req_builder = local_var_req_builder.query(&[("cursor", &local_var_str.to_string())]);
}
if let Some(ref local_var_str) = limit {
local_var_req_builder = local_var_req_builder.query(&[("limit", &local_var_str.to_string())]);
}
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
local_var_req_builder = local_var_req_builder.header("token", token.to_string());
if let Some(ref local_var_token) = configuration.oauth_access_token {
local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned());
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<AdminUsersListError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Remove a user from a workspace.
pub async fn admin_users_remove(configuration: &configuration::Configuration, token: &str, team_id: &str, user_id: &str) -> Result<::std::collections::HashMap<String, serde_json::Value>, Error<AdminUsersRemoveError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/admin.users.remove", configuration.base_path);
let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
local_var_req_builder = local_var_req_builder.header("token", token.to_string());
if let Some(ref local_var_token) = configuration.oauth_access_token {
local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned());
};
let mut local_var_form_params = std::collections::HashMap::new();
local_var_form_params.insert("team_id", team_id.to_string());
local_var_form_params.insert("user_id", user_id.to_string());
local_var_req_builder = local_var_req_builder.form(&local_var_form_params);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<AdminUsersRemoveError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Set an existing guest, regular user, or owner to be an admin user.
pub async fn admin_users_set_admin(configuration: &configuration::Configuration, token: &str, team_id: &str, user_id: &str) -> Result<::std::collections::HashMap<String, serde_json::Value>, Error<AdminUsersSetAdminError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/admin.users.setAdmin", configuration.base_path);
let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
local_var_req_builder = local_var_req_builder.header("token", token.to_string());
if let Some(ref local_var_token) = configuration.oauth_access_token {
local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned());
};
let mut local_var_form_params = std::collections::HashMap::new();
local_var_form_params.insert("team_id", team_id.to_string());
local_var_form_params.insert("user_id", user_id.to_string());
local_var_req_builder = local_var_req_builder.form(&local_var_form_params);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<AdminUsersSetAdminError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Set an expiration for a guest user
pub async fn admin_users_set_expiration(configuration: &configuration::Configuration, token: &str, team_id: &str, user_id: &str, expiration_ts: i32) -> Result<::std::collections::HashMap<String, serde_json::Value>, Error<AdminUsersSetExpirationError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/admin.users.setExpiration", configuration.base_path);
let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
local_var_req_builder = local_var_req_builder.header("token", token.to_string());
if let Some(ref local_var_token) = configuration.oauth_access_token {
local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned());
};
let mut local_var_form_params = std::collections::HashMap::new();
local_var_form_params.insert("team_id", team_id.to_string());
local_var_form_params.insert("user_id", user_id.to_string());
local_var_form_params.insert("expiration_ts", expiration_ts.to_string());
local_var_req_builder = local_var_req_builder.form(&local_var_form_params);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<AdminUsersSetExpirationError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Set an existing guest, regular user, or admin user to be a workspace owner.
pub async fn admin_users_set_owner(configuration: &configuration::Configuration, token: &str, team_id: &str, user_id: &str) -> Result<::std::collections::HashMap<String, serde_json::Value>, Error<AdminUsersSetOwnerError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/admin.users.setOwner", configuration.base_path);
let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
local_var_req_builder = local_var_req_builder.header("token", token.to_string());
if let Some(ref local_var_token) = configuration.oauth_access_token {
local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned());
};
let mut local_var_form_params = std::collections::HashMap::new();
local_var_form_params.insert("team_id", team_id.to_string());
local_var_form_params.insert("user_id", user_id.to_string());
local_var_req_builder = local_var_req_builder.form(&local_var_form_params);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<AdminUsersSetOwnerError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Set an existing guest user, admin user, or owner to be a regular user.
pub async fn admin_users_set_regular(configuration: &configuration::Configuration, token: &str, team_id: &str, user_id: &str) -> Result<::std::collections::HashMap<String, serde_json::Value>, Error<AdminUsersSetRegularError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/admin.users.setRegular", configuration.base_path);
let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
local_var_req_builder = local_var_req_builder.header("token", token.to_string());
if let Some(ref local_var_token) = configuration.oauth_access_token {
local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned());
};
let mut local_var_form_params = std::collections::HashMap::new();
local_var_form_params.insert("team_id", team_id.to_string());
local_var_form_params.insert("user_id", user_id.to_string());
local_var_req_builder = local_var_req_builder.form(&local_var_form_params);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<AdminUsersSetRegularError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
|
use proconio::{fastout, input};
#[fastout]
fn main() {
input! {
n: usize,
mut a_vec: [i64; n],
};
let mut ans: i64 = 0;
for i in 1..n {
let dif = a_vec[i - 1] - a_vec[i];
if dif > 0 {
ans += dif;
a_vec[i] += dif;
}
}
println!("{}", ans);
}
|
// Copyright 2019 The Grin Developers
//
// 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.
//! Controller for wallet.. instantiates and handles listeners (or single-run
//! invocations) as needed.
use crate::api::{self, ApiServer, BasicAuthMiddleware, ResponseFuture, Router, TLSConfig};
use crate::libwallet::{
NodeClient, NodeVersionInfo, Slate, WalletInst, WalletLCProvider, GRIN_BLOCK_HEADER_VERSION,
};
use crate::util::secp::key::SecretKey;
use crate::util::{from_hex, to_base64, Mutex};
use crate::{Error, ErrorKind};
use grin_wallet_api::JsonId;
use grin_wallet_util::OnionV3Address;
use hyper::body;
use hyper::header::HeaderValue;
use hyper::{Body, Request, Response, StatusCode};
use serde::{Deserialize, Serialize};
use serde_json;
use grin_wallet_impls::{
Address, CloseReason, MWCMQPublisher, MWCMQSAddress, MWCMQSubscriber, Publisher, Subscriber,
SubscriptionHandler,
};
use grin_wallet_libwallet::swap::message::Message;
use grin_wallet_libwallet::wallet_lock;
use grin_wallet_util::grin_core::core;
use crate::apiwallet::{
EncryptedRequest, EncryptedResponse, EncryptionErrorResponse, Foreign,
ForeignCheckMiddlewareFn, ForeignRpc, Owner, OwnerRpcV2, OwnerRpcV3,
};
use crate::config::{MQSConfig, TorConfig};
use crate::core::global;
use crate::impls::tor::config as tor_config;
use crate::impls::tor::process as tor_process;
use crate::keychain::Keychain;
use chrono::Utc;
use easy_jsonrpc_mw::{Handler, MaybeReply};
use grin_wallet_impls::tor;
use grin_wallet_libwallet::internal::selection;
use grin_wallet_libwallet::proof::crypto;
use grin_wallet_libwallet::proof::proofaddress;
use grin_wallet_util::grin_core::core::TxKernel;
use grin_wallet_util::grin_p2p;
use grin_wallet_util::grin_p2p::libp2p_connection;
use grin_wallet_util::grin_util::secp::pedersen::Commitment;
use std::collections::HashMap;
use std::net::{SocketAddr, SocketAddrV4};
use std::pin::Pin;
use std::sync::mpsc::Sender;
use std::sync::{Arc, RwLock};
use std::thread;
lazy_static! {
pub static ref MWC_OWNER_BASIC_REALM: HeaderValue =
HeaderValue::from_str("Basic realm=MWC-OwnerAPI").unwrap();
static ref FOREIGN_API_RUNNING: RwLock<bool> = RwLock::new(false);
static ref OWNER_API_RUNNING: RwLock<bool> = RwLock::new(false);
}
pub fn is_foreign_api_running() -> bool {
*FOREIGN_API_RUNNING.read().unwrap()
}
pub fn is_owner_api_running() -> bool {
*OWNER_API_RUNNING.read().unwrap()
}
// This function has to use libwallet errots because of callback and runs on libwallet side
fn check_middleware(
name: ForeignCheckMiddlewareFn,
node_version_info: Option<NodeVersionInfo>,
slate: Option<&Slate>,
) -> Result<(), crate::libwallet::Error> {
match name {
// allow coinbases to be built regardless
ForeignCheckMiddlewareFn::BuildCoinbase => Ok(()),
_ => {
let mut bhv = 2;
if let Some(n) = node_version_info {
bhv = n.block_header_version;
}
if let Some(s) = slate {
if bhv > 3 && s.version_info.block_header_version < GRIN_BLOCK_HEADER_VERSION {
Err(crate::libwallet::ErrorKind::Compatibility(
"Incoming Slate is not compatible with this wallet. \
Please upgrade the node or use a different one."
.into(),
))?;
}
}
Ok(())
}
}
}
/// get the tor address
pub fn get_tor_address<L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
keychain_mask: Arc<Mutex<Option<SecretKey>>>,
) -> Result<String, Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
let mask = keychain_mask.lock();
// eventually want to read a list of service config keys
let mut w_lock = wallet.lock();
let lc = w_lock.lc_provider()?;
let w_inst = lc.wallet_inst()?;
let k = w_inst.keychain((&mask).as_ref())?;
let sec_key = proofaddress::payment_proof_address_dalek_secret(&k, None).map_err(|e| {
ErrorKind::TorConfig(format!("Unable to build key for onion address, {}", e))
})?;
let onion_addr = OnionV3Address::from_private(sec_key.as_bytes())
.map_err(|e| ErrorKind::GenericError(format!("Unable to build Onion address, {}", e)))?;
Ok(format!("{}", onion_addr))
}
/// initiate the tor listener
pub fn init_tor_listener<L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
keychain_mask: Arc<Mutex<Option<SecretKey>>>,
addr: &str,
socks_listener_addr: &str,
libp2p_listener_port: &Option<u16>,
tor_base: Option<&str>,
tor_log_file: &Option<String>,
) -> Result<(tor_process::TorProcess, SecretKey), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
let mut process = tor_process::TorProcess::new();
let mask = keychain_mask.lock();
// eventually want to read a list of service config keys
let mut w_lock = wallet.lock();
let lc = w_lock.lc_provider()?;
let w_inst = lc.wallet_inst()?;
let k = w_inst.keychain((&mask).as_ref())?;
let tor_dir = if tor_base.is_some() {
format!("{}/tor/listener", tor_base.unwrap())
} else {
format!("{}/tor/listener", lc.get_top_level_directory()?)
};
let sec_key = proofaddress::payment_proof_address_secret(&k, None).map_err(|e| {
ErrorKind::TorConfig(format!("Unable to build key for onion address, {}", e))
})?;
let onion_address = OnionV3Address::from_private(&sec_key.0)
.map_err(|e| ErrorKind::TorConfig(format!("Unable to build onion address, {}", e)))?;
warn!(
"Starting TOR Hidden Service for API listener at address {}, binding to {}",
onion_address, addr
);
tor_config::output_tor_listener_config(
&tor_dir,
socks_listener_addr,
addr,
libp2p_listener_port,
&vec![sec_key.clone()],
tor_log_file,
)
.map_err(|e| ErrorKind::TorConfig(format!("Failed to configure tor, {}", e).into()))?;
// Start TOR process
let tor_path = format!("{}/torrc", tor_dir);
process
.torrc_path(&tor_path)
.working_dir(&tor_dir)
.timeout(200)
.completion_percent(100)
.launch()
.map_err(|e| {
ErrorKind::TorProcess(format!("Unable to start tor at {}, {}", tor_path, e).into())
})?;
tor::status::set_tor_address(Some(format!("{}", onion_address)));
Ok((process, sec_key))
}
/// Instantiate wallet Owner API for a single-use (command line) call
/// Return a function containing a loaded API context to call
pub fn owner_single_use<L, F, C, K>(
wallet: Option<Arc<Mutex<Box<dyn WalletInst<'static, L, C, K>>>>>,
keychain_mask: Option<&SecretKey>,
api_context: Option<&mut Owner<L, C, K>>,
f: F,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
F: FnOnce(&mut Owner<L, C, K>, Option<&SecretKey>) -> Result<(), Error>,
C: NodeClient + 'static,
K: Keychain + 'static,
{
match api_context {
Some(c) => f(c, keychain_mask)?,
None => {
let wallet = match wallet {
Some(w) => w,
None => {
return Err(ErrorKind::GenericError(format!(
"Instantiated wallet or Owner API context must be provided"
))
.into())
}
};
f(&mut Owner::new(wallet, None, None), keychain_mask)?
}
}
Ok(())
}
/// Instantiate wallet Foreign API for a single-use (command line) call
/// Return a function containing a loaded API context to call
pub fn foreign_single_use<'a, L, F, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
keychain_mask: Option<SecretKey>,
f: F,
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
F: FnOnce(&mut Foreign<'a, L, C, K>) -> Result<(), Error>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
f(&mut Foreign::new(
wallet,
keychain_mask,
Some(check_middleware),
))?;
Ok(())
}
//The following methods are added to support the mqs feature
fn controller_derive_address_key<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
keychain_mask: Option<&SecretKey>,
) -> Result<SecretKey, Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
wallet_lock!(wallet, w);
let k = w.keychain(keychain_mask)?;
let sec_addr_key = proofaddress::payment_proof_address_secret(&k, None)?;
Ok(sec_addr_key)
}
#[derive(Clone)]
pub struct Controller<L, C, K>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
/// Wallet instance
name: String,
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
publisher: Arc<Mutex<Option<Box<dyn Publisher + Send>>>>,
// mwc-wallet doesn have this field allways None. we don't want mwc-wallet to be able to process them.
// Autoinvoice
max_auto_accept_invoice: Option<u64>,
slate_send_channel: Arc<Mutex<HashMap<uuid::Uuid, Sender<Slate>>>>,
keychain_mask: Arc<Mutex<Option<SecretKey>>>,
// what to do with logs. Print them to console or into the logs
print_to_log: bool,
}
impl<L, C, K> Controller<L, C, K>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
pub fn new(
name: &str,
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K>>>>,
keychain_mask: Arc<Mutex<Option<SecretKey>>>,
max_auto_accept_invoice: Option<u64>,
print_to_log: bool,
) -> Self
where
L: WalletLCProvider<'static, C, K>,
C: NodeClient + 'static,
K: Keychain + 'static,
{
if max_auto_accept_invoice.is_some() && global::is_mainnet() {
panic!("Auto invoicing must be disabled for the mainnet");
}
Self {
name: name.to_string(),
wallet,
publisher: Arc::new(Mutex::new(None)),
max_auto_accept_invoice,
slate_send_channel: Arc::new(Mutex::new(HashMap::new())),
keychain_mask,
print_to_log,
}
}
pub fn clone(&self) -> Self {
Self {
name: self.name.clone(),
wallet: self.wallet.clone(),
publisher: self.publisher.clone(),
max_auto_accept_invoice: self.max_auto_accept_invoice.clone(),
slate_send_channel: self.slate_send_channel.clone(),
keychain_mask: self.keychain_mask.clone(),
print_to_log: self.print_to_log,
}
}
pub fn set_publisher(&self, publisher: Box<dyn Publisher + Send>) {
self.publisher.lock().replace(publisher);
}
fn process_incoming_slate(
&self,
from: &dyn Address,
slate: &mut Slate,
dest_acct_name: Option<&str>,
) -> Result<(), Error> {
let owner_api = Owner::new(self.wallet.clone(), None, None);
let foreign_api = Foreign::new(self.wallet.clone(), None, None);
let mask = self.keychain_mask.lock().clone();
if slate.num_participants > slate.participant_data.len() {
//TODO: this needs to be changed to properly figure out if this slate is an invoice or a send
if slate.tx.inputs().len() == 0 {
// mwc-wallet doesn't support invoices
Err(ErrorKind::DoesNotAcceptInvoices)?;
// reject by default unless wallet is set to auto accept invoices under a certain threshold
let max_auto_accept_invoice = self
.max_auto_accept_invoice
.ok_or(ErrorKind::DoesNotAcceptInvoices)?;
if slate.amount > max_auto_accept_invoice {
Err(ErrorKind::InvoiceAmountTooBig(slate.amount))?;
}
if global::is_mainnet() {
panic!("Auto invoicing must be disabled for the mainnet");
}
//create the args
let params = grin_wallet_libwallet::InitTxArgs {
src_acct_name: None, //it will be set in the implementation layer.
amount: slate.amount,
minimum_confirmations: 10,
max_outputs: 500,
num_change_outputs: 1,
/// If `true`, attempt to use up as many outputs as
/// possible to create the transaction, up the 'soft limit' of `max_outputs`. This helps
/// to reduce the size of the UTXO set and the amount of data stored in the wallet, and
/// minimizes fees. This will generally result in many inputs and a large change output(s),
/// usually much larger than the amount being sent. If `false`, the transaction will include
/// as many outputs as are needed to meet the amount, (and no more) starting with the smallest
/// value outputs.
selection_strategy_is_use_all: false,
message: None,
/// Optionally set the output target slate version (acceptable
/// down to the minimum slate version compatible with the current. If `None` the slate
/// is generated with the latest version.
target_slate_version: None,
/// Number of blocks from current after which TX should be ignored
ttl_blocks: None,
/// If set, require a payment proof for the particular recipient
payment_proof_recipient_address: None,
address: Some(from.get_full_name()),
/// If true, just return an estimate of the resulting slate, containing fees and amounts
/// locked without actually locking outputs or creating the transaction. Note if this is set to
/// 'true', the amount field in the slate will contain the total amount locked, not the provided
/// transaction amount
estimate_only: None,
exclude_change_outputs: Some(false),
minimum_confirmations_change_outputs: 1,
/// Sender arguments. If present, the underlying function will also attempt to send the
/// transaction to a destination and optionally finalize the result
send_args: None,
outputs: None,
// Lack later flag. Require compact slate workflow
late_lock: Some(false),
// other waller recipient for encrypted slatepack.
slatepack_recipient: None,
min_fee: None,
};
*slate = owner_api.process_invoice_tx((&mask).as_ref(), slate, ¶ms)?;
owner_api.tx_lock_outputs(
(&mask).as_ref(),
slate,
Some(from.get_full_name()),
1,
)?;
} else {
let s = foreign_api
.receive_tx(slate, Some(from.get_full_name()), dest_acct_name, None)
.map_err(|e| {
ErrorKind::LibWallet(format!(
"Unable to process incoming slate, receive_tx failed, {}",
e
))
})?;
*slate = s;
}
// Send slate back
self.publisher
.lock()
.as_ref()
.expect("call set_publisher() method!!!")
.post_slate(slate, from)
.map_err(|e| {
self.do_log_error(format!("ERROR: Unable to send slate back, {}", e));
e
})?;
self.do_log_info(format!(
"slate [{}] sent back to [{}] successfully",
slate.id.to_string(),
from.get_stripped()
));
Ok(())
} else {
//request may come to here from owner api or send command
if let Some(slate_sender) = self.slate_send_channel.lock().get(&slate.id) {
//this happens when the request is from sender. Sender just want have a respond back
let slate_immutable = slate.clone();
let _ = slate_sender.send(slate_immutable);
} else {
// Report error. We are not processing any finalization transactions if nobody waiting for that
self.do_log_warn(format!(
"Get back slate {}. Because slate arrive too late, wallet not processing it",
slate.id
));
}
Ok(())
}
}
fn process_incoming_swap_message(
&self,
swapmessage: Message,
) -> Result<Option<Message>, Error> {
let owner_api = Owner::new(self.wallet.clone(), None, None);
let mask = self.keychain_mask.lock().clone();
let msg_str = serde_json::to_string(&swapmessage).map_err(|e| {
ErrorKind::ProcessSwapMessageError(format!(
"Error in processing incoming swap message from mqs, {}",
e
))
})?;
let ack_msg = owner_api.swap_income_message((&mask).as_ref(), msg_str)?;
Ok(ack_msg)
}
fn do_log_info(&self, message: String) {
if self.print_to_log {
info!("{}", message);
} else {
println!("{}", message);
}
}
fn do_log_warn(&self, message: String) {
if self.print_to_log {
warn!("{}", message);
} else {
println!("{}", message);
}
}
fn do_log_error(&self, message: String) {
if self.print_to_log {
error!("{}", message);
} else {
println!("{}", message);
}
}
}
impl<L, C, K> SubscriptionHandler for Controller<L, C, K>
where
L: WalletLCProvider<'static, C, K>,
C: NodeClient + 'static,
K: Keychain + 'static,
{
fn on_open(&self) {
self.do_log_warn(format!("listener started for [{}]", self.name));
}
fn on_slate(&self, from: &dyn Address, slate: &mut Slate) {
let display_from = from.get_stripped();
if slate.num_participants > slate.participant_data.len() {
// Don't print anything, the receive foreign API will do that.
} else {
self.do_log_info(format!(
"slate [{}] received back from [{}] for [{}] MWCs",
slate.id.to_string(),
display_from,
core::amount_to_hr_string(slate.amount, false)
));
};
let result = self.process_incoming_slate(from, slate, None);
//send the message back
match result {
Ok(()) => {}
Err(e) => self.do_log_error(format!("Unable to process incoming slate, {}", e)),
}
}
fn on_swap_message(&self, swap: Message) -> Option<Message> {
let result = self.process_incoming_swap_message(swap);
match result {
Ok(message) => return message,
Err(e) => {
self.do_log_error(format!("{}", e));
None
}
}
}
fn on_close(&self, reason: CloseReason) {
match reason {
CloseReason::Normal => self.do_log_info(format!("listener [{}] stopped", self.name)),
CloseReason::Abnormal(_) => self.do_log_error(format!(
"ERROR: listener [{}] stopped unexpectedly",
self.name
)),
}
}
fn on_dropped(&self) {
self.do_log_info(format!("WARNING: listener [{}] lost connection. it will keep trying to restore connection in the background.", self.name))
}
fn on_reestablished(&self) {
self.do_log_info(format!(
"INFO: listener [{}] reestablished connection.",
self.name
))
}
fn set_notification_channels(&self, slate_id: &uuid::Uuid, slate_send_channel: Sender<Slate>) {
self.slate_send_channel
.lock()
.insert(slate_id.clone(), slate_send_channel);
}
fn reset_notification_channels(&self, slate_id: &uuid::Uuid) {
let _ = self.slate_send_channel.lock().remove(slate_id);
}
}
pub fn init_start_mwcmqs_listener<L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K>>>>,
mqs_config: MQSConfig,
keychain_mask: Arc<Mutex<Option<SecretKey>>>,
wait_for_thread: bool,
) -> Result<(MWCMQPublisher, MWCMQSubscriber), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
warn!("Starting MWCMQS Listener");
//start mwcmqs listener
start_mwcmqs_listener(wallet, mqs_config, wait_for_thread, keychain_mask, true)
.map_err(|e| ErrorKind::GenericError(format!("cannot start mqs listener, {}", e)).into())
}
/// Start the mqs listener
pub fn start_mwcmqs_listener<L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K>>>>,
mqs_config: MQSConfig,
wait_for_thread: bool,
keychain_mask: Arc<Mutex<Option<SecretKey>>>,
print_to_log: bool,
) -> Result<(MWCMQPublisher, MWCMQSubscriber), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
if grin_wallet_impls::adapters::get_mwcmqs_brocker().is_some() {
return Err(
ErrorKind::GenericError("mwcmqs listener is already running".to_string()).into(),
);
}
// make sure wallet is not locked, if it is try to unlock with no passphrase
info!(
"starting mwcmqs listener for {}:{}...",
mqs_config.mwcmqs_domain, mqs_config.mwcmqs_port
);
info!(
"the addres index is {}... ",
proofaddress::get_address_index()
);
let mwcmqs_domain = mqs_config.mwcmqs_domain;
let mwcmqs_port = mqs_config.mwcmqs_port;
let mwcmqs_secret_key =
controller_derive_address_key(wallet.clone(), keychain_mask.lock().as_ref())?;
let mwc_pub_key = crypto::public_key_from_secret_key(&mwcmqs_secret_key)?;
let mwcmqs_address = MWCMQSAddress::new(
proofaddress::ProvableAddress::from_pub_key(&mwc_pub_key),
Some(mwcmqs_domain.clone()),
Some(mwcmqs_port),
);
let controller = Controller::new(
&mwcmqs_address.get_stripped(),
wallet.clone(),
keychain_mask,
None,
print_to_log,
);
let mwcmqs_publisher = MWCMQPublisher::new(
mwcmqs_address.clone(),
&mwcmqs_secret_key,
mwcmqs_domain,
mwcmqs_port,
print_to_log,
Box::new(controller.clone()),
);
// Cross reference, need to setup the secondary pointer
controller.set_publisher(Box::new(mwcmqs_publisher.clone()));
let mwcmqs_subscriber = MWCMQSubscriber::new(&mwcmqs_publisher);
let mut cloned_subscriber = mwcmqs_subscriber.clone();
let thread = thread::Builder::new()
.name("mwcmqs-broker".to_string())
.spawn(move || {
if let Err(e) = cloned_subscriber.start() {
let err_str = format!("Unable to start mwcmqs controller, {}", e);
error!("{}", err_str);
panic!("{}", err_str);
}
})
.map_err(|e| ErrorKind::GenericError(format!("Unable to start mwcmqs broker, {}", e)))?;
// Publishing this running MQS service
crate::impls::init_mwcmqs_access_data(mwcmqs_publisher.clone(), mwcmqs_subscriber.clone());
if wait_for_thread {
let _ = thread.join();
}
Ok((mwcmqs_publisher, mwcmqs_subscriber))
}
/// Listener version, providing same API but listening for requests on a
/// port and wrapping the calls
/// Note keychain mask is only provided here in case the foreign listener is also being used
/// in the same wallet instance
pub fn owner_listener<L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
keychain_mask: Arc<Mutex<Option<SecretKey>>>,
addr: &str,
api_secret: Option<String>,
tls_config: Option<TLSConfig>,
owner_api_include_foreign: Option<bool>,
tor_config: Option<TorConfig>,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
let mut running_foreign = false;
if owner_api_include_foreign.unwrap_or(false) {
running_foreign = true;
}
if *OWNER_API_RUNNING.read().unwrap() {
return Err(
ErrorKind::GenericError("Owner API is already up and running".to_string()).into(),
);
}
if running_foreign && *FOREIGN_API_RUNNING.read().unwrap() {
return Err(
ErrorKind::GenericError("Foreign API is already up and running".to_string()).into(),
);
}
//I don't know why but it seems the warn message in controller.rs will get printed to console.
warn!("owner listener started {}", addr);
let mut router = Router::new();
if api_secret.is_some() {
let api_basic_auth =
"Basic ".to_string() + &to_base64(&("mwc:".to_string() + &api_secret.unwrap()));
let basic_auth_middleware = Arc::new(BasicAuthMiddleware::new(
api_basic_auth,
&MWC_OWNER_BASIC_REALM,
Some("/v2/foreign".into()),
));
router.add_middleware(basic_auth_middleware);
}
let api_handler_v2 = OwnerAPIHandlerV2::new(wallet.clone(), tor_config.clone());
let api_handler_v3 = OwnerAPIHandlerV3::new(
wallet.clone(),
keychain_mask.clone(),
tor_config,
running_foreign,
);
router
.add_route("/v2/owner", Arc::new(api_handler_v2))
.map_err(|e| {
ErrorKind::GenericError(format!("Router failed to add route /v2/owner, {}", e))
})?;
router
.add_route("/v3/owner", Arc::new(api_handler_v3))
.map_err(|e| {
ErrorKind::GenericError(format!("Router failed to add route /v3/owner, {}", e))
})?;
// If so configured, add the foreign API to the same port
if running_foreign {
warn!("Starting HTTP Foreign API on Owner server at {}.", addr);
let foreign_api_handler_v2 = ForeignAPIHandlerV2::new(wallet, keychain_mask);
router
.add_route("/v2/foreign", Arc::new(foreign_api_handler_v2))
.map_err(|e| {
ErrorKind::GenericError(format!("Router failed to add route /v2/foreign, {}", e))
})?;
}
let mut apis = ApiServer::new();
warn!("Starting HTTP Owner API server at {}.", addr);
let socket_addr: SocketAddr = addr.parse().expect("unable to parse socket address");
let api_thread = apis
.start(socket_addr, router, tls_config)
.map_err(|e| ErrorKind::GenericError(format!("API thread failed to start, {}", e)))?;
warn!("HTTP Owner listener started.");
*OWNER_API_RUNNING.write().unwrap() = true;
if running_foreign {
*FOREIGN_API_RUNNING.write().unwrap() = true;
}
let res = api_thread
.join()
.map_err(|e| ErrorKind::GenericError(format!("API thread panicked :{:?}", e)).into());
*OWNER_API_RUNNING.write().unwrap() = false;
if running_foreign {
*FOREIGN_API_RUNNING.write().unwrap() = false;
}
res
}
/// Start libp2p listener thread.
/// stop_mutex allows to stop the thread when value will be 0
pub fn start_libp2p_listener<L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
tor_secret: [u8; 32],
socks_proxy_addr: &str,
libp2p_listen_port: u16,
stop_mutex: std::sync::Arc<std::sync::Mutex<u32>>,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
let node_client = {
wallet_lock!(wallet, w);
w.w2n_client().clone()
};
let tor_addr: SocketAddrV4 = socks_proxy_addr.parse().map_err(|e| {
ErrorKind::GenericError(format!(
"Unable to parse tor socks address {}, {}",
socks_proxy_addr, e
))
})?;
warn!("Starting libp2p listener with port {}", libp2p_listen_port);
thread::Builder::new()
.name("libp2p_node".to_string())
.spawn(move || {
let requested_kernel_cache: RwLock<HashMap<Commitment, (TxKernel, u64)>> =
RwLock::new(HashMap::new());
let last_time_cache_cleanup: RwLock<i64> = RwLock::new(0);
let output_validation_fn =
move |excess: &Commitment| -> Result<Option<TxKernel>, grin_p2p::Error> {
// Tip is needed in order to request from last 24 hours (1440 blocks)
let tip_height = node_client
.get_chain_tip()
.map_err(|e| {
grin_p2p::Error::Libp2pError(format!(
"Unable contact the node to get chain tip, {}",
e
))
})?
.0;
let cur_time = Utc::now().timestamp();
// let's clean cache every 10 minutes. Removing all expired items
{
let mut last_time_cache_cleanup = last_time_cache_cleanup.write().unwrap();
if cur_time - 600 > *last_time_cache_cleanup {
let min_height = tip_height
- libp2p_connection::INTEGRITY_FEE_VALID_BLOCKS
- libp2p_connection::INTEGRITY_FEE_VALID_BLOCKS / 12;
requested_kernel_cache
.write()
.unwrap()
.retain(|_k, v| v.1 > min_height);
*last_time_cache_cleanup = cur_time;
}
}
// Checking if we hit the cache
if let Some(tx) = requested_kernel_cache.read().unwrap().get(excess) {
return Ok(Some(tx.clone().0));
}
// !!! Note, get_kernel_height does iteration through the MMR. That will work until we
// Ban nodes that sent us incorrect excess. For now it should work fine. Normally
// peers reusing the integrity kernels so cache hit should happen most of the time.
match node_client
.get_kernel(
excess,
Some(tip_height - libp2p_connection::INTEGRITY_FEE_VALID_BLOCKS),
None,
)
.map_err(|e| {
grin_p2p::Error::Libp2pError(format!(
"Unable contact the node to get kernel data, {}",
e
))
})? {
Some((tx_kernel, height, _)) => {
requested_kernel_cache
.write()
.unwrap()
.insert(excess.clone(), (tx_kernel.clone(), height));
Ok(Some(tx_kernel))
}
None => Ok(None),
}
};
let validation_fn = Arc::new(output_validation_fn);
loop {
let libp2p_node_runner = libp2p_connection::run_libp2p_node(
tor_addr.port(),
&tor_secret,
libp2p_listen_port as u16,
selection::get_base_fee(),
validation_fn.clone(),
stop_mutex.clone(),
);
info!("Starting gossipsub libp2p server");
let mut rt = tokio::runtime::Runtime::new().unwrap();
match rt.block_on(libp2p_node_runner) {
Ok(_) => info!("libp2p node is exited"),
Err(e) => error!("Unable to start libp2p node, {:?}", e),
}
// Swarm is not valid any more, let's update our global instance.
libp2p_connection::reset_libp2p_swarm();
if *stop_mutex.lock().unwrap() == 0 {
break;
}
}
})
.map_err(|e| {
ErrorKind::GenericError(format!("Unable to start libp2p_node server, {}", e))
})?;
Ok(())
}
/// Listener version, providing same API but listening for requests on a
/// port and wrapping the calls
pub fn foreign_listener<L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
keychain_mask: Arc<Mutex<Option<SecretKey>>>,
addr: &str,
tls_config: Option<TLSConfig>,
use_tor: bool,
socks_proxy_addr: &str,
libp2p_listen_port: &Option<u16>,
tor_log_file: &Option<String>,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
if *FOREIGN_API_RUNNING.read().unwrap() {
return Err(
ErrorKind::GenericError("Foreign API is already up and running".to_string()).into(),
);
}
// Check if wallet has been opened first
{
let mut w_lock = wallet.lock();
let lc = w_lock.lc_provider()?;
let _ = lc.wallet_inst()?;
}
// need to keep in scope while the main listener is running
let tor_info = match use_tor {
true => match init_tor_listener(
wallet.clone(),
keychain_mask.clone(),
addr,
socks_proxy_addr,
libp2p_listen_port,
None,
tor_log_file,
) {
Ok((tp, tor_secret)) => Some((tp, tor_secret)),
Err(e) => {
warn!("Unable to start TOR listener; Check that TOR executable is installed and on your path");
warn!("Tor Error: {}", e);
warn!("Listener will be available via HTTP only");
None
}
},
false => None,
};
let api_handler_v2 = ForeignAPIHandlerV2::new(wallet.clone(), keychain_mask);
let mut router = Router::new();
router
.add_route("/v2/foreign", Arc::new(api_handler_v2))
.map_err(|e| {
ErrorKind::GenericError(format!("Router failed to add route /v2/foreign, {}", e))
})?;
let mut apis = ApiServer::new();
warn!("Starting HTTP Foreign listener API server at {}.", addr);
let socket_addr: SocketAddr = addr.parse().expect("unable to parse socket address");
let api_thread = apis
.start(socket_addr, router, tls_config)
.map_err(|e| ErrorKind::GenericError(format!("API thread failed to start, {}", e)))?;
warn!("HTTP Foreign listener started.");
*FOREIGN_API_RUNNING.write().unwrap() = true;
// Starting libp2p listener
let tor_process = if tor_info.is_some() && libp2p_listen_port.is_some() {
let tor_info = tor_info.unwrap();
let libp2p_listen_port = libp2p_listen_port.unwrap();
start_libp2p_listener(
wallet.clone(),
tor_info.1 .0,
socks_proxy_addr,
libp2p_listen_port,
std::sync::Arc::new(std::sync::Mutex::new(1)), // passing new obj, because we never will stop the libp2p process
)?;
Some(tor_info.0)
} else {
None
};
let res = api_thread
.join()
.map_err(|e| ErrorKind::GenericError(format!("API thread panicked :{:?}", e)).into());
*FOREIGN_API_RUNNING.write().unwrap() = false;
// Stopping tor, we failed to start in any case
if let Some(mut tor_process) = tor_process {
let _ = tor_process.kill();
}
res
}
/// V2 API Handler/Wrapper for owner functions
pub struct OwnerAPIHandlerV2<L, C, K>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
/// Wallet instance
pub wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
pub tor_config: Option<TorConfig>,
}
impl<L, C, K> OwnerAPIHandlerV2<L, C, K>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
/// Create a new owner API handler for GET methods
pub fn new(
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
tor_config: Option<TorConfig>,
) -> OwnerAPIHandlerV2<L, C, K> {
OwnerAPIHandlerV2 { wallet, tor_config }
}
async fn call_api(req: Request<Body>, api: Owner<L, C, K>) -> Result<serde_json::Value, Error> {
let val: serde_json::Value = parse_body(req).await?;
match <dyn OwnerRpcV2>::handle_request(&api, val) {
MaybeReply::Reply(r) => Ok(r),
MaybeReply::DontReply => {
// Since it's http, we need to return something. We return [] because jsonrpc
// clients will parse it as an empty batch response.
Ok(serde_json::json!([]))
}
}
}
async fn handle_post_request(
req: Request<Body>,
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
tor_config: Option<TorConfig>,
) -> Result<Response<Body>, Error> {
let api = Owner::new(wallet, None, tor_config);
//Here is a wrapper to call future from that.
// Issue that we can't call future form future
let handler = move || -> Pin<Box<dyn std::future::Future<Output=Result<serde_json::Value, Error>>>> {
let future = Self::call_api(req, api);
Box::pin(future)
};
let res = crate::executor::RunHandlerInThread::new(handler).await?;
Ok(json_response_pretty(&res))
}
}
impl<L, C, K> api::Handler for OwnerAPIHandlerV2<L, C, K>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
fn post(&self, req: Request<Body>) -> ResponseFuture {
let wallet = self.wallet.clone();
let tor_config = self.tor_config.clone();
Box::pin(async move {
match Self::handle_post_request(req, wallet, tor_config).await {
Ok(r) => Ok(r),
Err(e) => {
error!("Request Error: {:?}", e);
Ok(create_error_response(e))
}
}
})
}
fn options(&self, _req: Request<Body>) -> ResponseFuture {
Box::pin(async { Ok(create_ok_response("{}")) })
}
}
/// V3 API Handler/Wrapper for owner functions, which include a secure
/// mode + lifecycle functions
pub struct OwnerAPIHandlerV3<L, C, K>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
/// Wallet instance
pub wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
/// Handle to Owner API
owner_api: Arc<Owner<L, C, K>>,
/// ECDH shared key
pub shared_key: Arc<Mutex<Option<SecretKey>>>,
/// Keychain mask (to change if also running the foreign API)
pub keychain_mask: Arc<Mutex<Option<SecretKey>>>,
/// Whether we're running the foreign API on the same port, and therefore
/// have to store the mask in-process
pub running_foreign: bool,
}
pub struct OwnerV3Helpers;
impl OwnerV3Helpers {
/// Checks whether a request is to init the secure API
pub fn is_init_secure_api(val: &serde_json::Value) -> bool {
if let Some(m) = val["method"].as_str() {
match m {
"init_secure_api" => true,
_ => false,
}
} else {
false
}
}
/// Checks whether a request is to open the wallet
pub fn is_open_wallet(val: &serde_json::Value) -> bool {
if let Some(m) = val["method"].as_str() {
match m {
"open_wallet" => true,
_ => false,
}
} else {
false
}
}
/// Checks whether a request is an encrypted request
pub fn is_encrypted_request(val: &serde_json::Value) -> bool {
if let Some(m) = val["method"].as_str() {
match m {
"encrypted_request_v3" => true,
_ => false,
}
} else {
false
}
}
/// whether encryption is enabled
pub fn encryption_enabled(key: Arc<Mutex<Option<SecretKey>>>) -> bool {
let share_key_ref = key.lock();
share_key_ref.is_some()
}
/// If incoming is an encrypted request, check there is a shared key,
/// Otherwise return an error value
pub fn check_encryption_started(
key: Arc<Mutex<Option<SecretKey>>>,
) -> Result<(), serde_json::Value> {
match OwnerV3Helpers::encryption_enabled(key) {
true => Ok(()),
false => Err(EncryptionErrorResponse::new(
1,
-32001,
"Encryption must be enabled. Please call 'init_secure_api` first",
)
.as_json_value()),
}
}
/// Update the statically held owner API shared key
pub fn update_owner_api_shared_key(
key: Arc<Mutex<Option<SecretKey>>>,
val: &serde_json::Value,
new_key: Option<SecretKey>,
) {
if let Some(_) = val["result"]["Ok"].as_str() {
let mut share_key_ref = key.lock();
*share_key_ref = new_key;
}
}
/// Update the shared mask, in case of foreign API being run
pub fn update_mask(mask: Arc<Mutex<Option<SecretKey>>>, val: &serde_json::Value) {
if let Some(key) = val["result"]["Ok"].as_str() {
let key_bytes = match from_hex(key) {
Ok(k) => k,
Err(_) => return,
};
let sk = match SecretKey::from_slice(&key_bytes) {
Ok(s) => s,
Err(_) => return,
};
let mut shared_mask_ref = mask.lock();
*shared_mask_ref = Some(sk);
}
}
/// Decrypt an encrypted request
pub fn decrypt_request(
key: Arc<Mutex<Option<SecretKey>>>,
req: &serde_json::Value,
) -> Result<(JsonId, serde_json::Value), serde_json::Value> {
let share_key_ref = key.lock();
if share_key_ref.is_none() {
return Err(EncryptionErrorResponse::new(
1,
-32002,
"Encrypted request internal error",
)
.as_json_value());
}
let shared_key = share_key_ref.as_ref().unwrap();
let enc_req: EncryptedRequest = serde_json::from_value(req.clone()).map_err(|e| {
EncryptionErrorResponse::new(
1,
-32002,
&format!("Encrypted request format error: {}", e),
)
.as_json_value()
})?;
let id = enc_req.id.clone();
let res = enc_req.decrypt(&shared_key).map_err(|e| {
EncryptionErrorResponse::new(1, -32002, &format!("Decryption error: {}", e.kind()))
.as_json_value()
})?;
Ok((id, res))
}
/// Encrypt a response
pub fn encrypt_response(
key: Arc<Mutex<Option<SecretKey>>>,
id: &JsonId,
res: &serde_json::Value,
) -> Result<serde_json::Value, serde_json::Value> {
let share_key_ref = key.lock();
if share_key_ref.is_none() {
return Err(EncryptionErrorResponse::new(
1,
-32002,
"Encrypted response internal error",
)
.as_json_value());
}
let shared_key = share_key_ref.as_ref().unwrap();
let enc_res = EncryptedResponse::from_json(id, res, &shared_key).map_err(|e| {
EncryptionErrorResponse::new(1, -32003, &format!("Encryption Error: {}", e.kind()))
.as_json_value()
})?;
let res = enc_res.as_json_value().map_err(|e| {
EncryptionErrorResponse::new(
1,
-32002,
&format!("Encrypted response format error: {}", e),
)
.as_json_value()
})?;
Ok(res)
}
/// convert an internal error (if exists) as proper JSON-RPC
pub fn check_error_response(val: &serde_json::Value) -> (bool, serde_json::Value) {
// check for string first. This ensures that error messages
// that are just strings aren't given weird formatting
let err_string = if val["result"]["Err"].is_object() {
let mut retval;
let hashed: Result<HashMap<String, String>, serde_json::Error> =
serde_json::from_value(val["result"]["Err"].clone());
retval = match hashed {
Err(e) => {
debug!("Can't cast value to Hashmap<String> {}", e);
None
}
Ok(h) => {
let mut r = "".to_owned();
for (k, v) in h.iter() {
r = format!("{}: {}", k, v);
}
Some(r)
}
};
// Otherwise, see if error message is a map that needs
// to be stringified (and accept weird formatting)
if retval.is_none() {
let hashed: Result<HashMap<String, serde_json::Value>, serde_json::Error> =
serde_json::from_value(val["result"]["Err"].clone());
retval = match hashed {
Err(e) => {
debug!("Can't cast value to Hashmap<Value> {}", e);
None
}
Ok(h) => {
let mut r = "".to_owned();
for (k, v) in h.iter() {
r = format!("{}: {}", k, v);
}
Some(r)
}
}
}
retval
} else if val["result"]["Err"].is_string() {
let parsed = serde_json::from_value::<String>(val["result"]["Err"].clone());
match parsed {
Ok(p) => Some(p),
Err(_) => None,
}
} else {
None
};
match err_string {
Some(s) => {
return (
true,
serde_json::json!({
"jsonrpc": "2.0",
"id": val["id"],
"error": {
"message": s,
"code": -32099
}
}),
)
}
None => (false, val.clone()),
}
}
}
impl<L, C, K> OwnerAPIHandlerV3<L, C, K>
where
L: WalletLCProvider<'static, C, K>,
C: NodeClient + 'static,
K: Keychain + 'static,
{
/// Create a new owner API handler for GET methods
pub fn new(
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
keychain_mask: Arc<Mutex<Option<SecretKey>>>,
tor_config: Option<TorConfig>,
running_foreign: bool,
) -> OwnerAPIHandlerV3<L, C, K> {
let owner_api = Owner::new(wallet.clone(), None, tor_config.clone());
owner_api.set_tor_config(tor_config);
let owner_api = Arc::new(owner_api);
OwnerAPIHandlerV3 {
wallet,
owner_api,
shared_key: Arc::new(Mutex::new(None)),
keychain_mask: keychain_mask,
running_foreign,
}
}
async fn call_api(
req: Request<Body>,
key: Arc<Mutex<Option<SecretKey>>>,
mask: Arc<Mutex<Option<SecretKey>>>,
running_foreign: bool,
api: Arc<Owner<L, C, K>>,
) -> Result<serde_json::Value, Error> {
let mut val: serde_json::Value = parse_body(req).await?;
let mut is_init_secure_api = OwnerV3Helpers::is_init_secure_api(&val);
let mut was_encrypted = false;
let mut encrypted_req_id = JsonId::StrId(String::from(""));
if !is_init_secure_api {
if let Err(v) = OwnerV3Helpers::check_encryption_started(key.clone()) {
return Ok(v);
}
let res = OwnerV3Helpers::decrypt_request(key.clone(), &val);
match res {
Err(e) => return Ok(e),
Ok(v) => {
encrypted_req_id = v.0.clone();
val = v.1;
}
}
was_encrypted = true;
}
// check again, in case it was an encrypted call to init_secure_api
is_init_secure_api = OwnerV3Helpers::is_init_secure_api(&val);
// also need to intercept open/close wallet requests
let is_open_wallet = OwnerV3Helpers::is_open_wallet(&val);
match <dyn OwnerRpcV3>::handle_request(&*api, val) {
MaybeReply::Reply(mut r) => {
let (_was_error, unencrypted_intercept) =
OwnerV3Helpers::check_error_response(&r.clone());
if is_open_wallet && running_foreign {
OwnerV3Helpers::update_mask(mask, &r.clone());
}
if was_encrypted {
let res = OwnerV3Helpers::encrypt_response(
key.clone(),
&encrypted_req_id,
&unencrypted_intercept,
);
r = match res {
Ok(v) => v,
Err(v) => return Ok(v),
}
}
// intercept init_secure_api response (after encryption,
// in case it was an encrypted call to 'init_api_secure')
if is_init_secure_api {
OwnerV3Helpers::update_owner_api_shared_key(
key.clone(),
&unencrypted_intercept,
api.shared_key.lock().clone(),
);
}
Ok(r)
}
MaybeReply::DontReply => {
// Since it's http, we need to return something. We return [] because jsonrpc
// clients will parse it as an empty batch response.
Ok(serde_json::json!([]))
}
}
}
async fn handle_post_request(
req: Request<Body>,
key: Arc<Mutex<Option<SecretKey>>>,
mask: Arc<Mutex<Option<SecretKey>>>,
running_foreign: bool,
api: Arc<Owner<L, C, K>>,
) -> Result<Response<Body>, Error> {
//Here is a wrapper to call future from that.
// Issue that we can't call future form future
let handler = move || -> Pin<Box<dyn std::future::Future<Output=Result<serde_json::Value, Error>>>> {
let future = Self::call_api(req, key, mask, running_foreign, api);
Box::pin(future)
};
let res = crate::executor::RunHandlerInThread::new(handler).await?;
//let res = Self::call_api(req, key, mask, running_foreign, api).await?;
Ok(json_response_pretty(&res))
}
}
impl<L, C, K> api::Handler for OwnerAPIHandlerV3<L, C, K>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
fn post(&self, req: Request<Body>) -> ResponseFuture {
let key = self.shared_key.clone();
let mask = self.keychain_mask.clone();
let running_foreign = self.running_foreign;
let api = self.owner_api.clone();
Box::pin(async move {
match Self::handle_post_request(req, key, mask, running_foreign, api).await {
Ok(r) => Ok(r),
Err(e) => {
error!("Request Error: {:?}", e);
Ok(create_error_response(e))
}
}
})
}
fn options(&self, _req: Request<Body>) -> ResponseFuture {
Box::pin(async { Ok(create_ok_response("{}")) })
}
}
/// V2 API Handler/Wrapper for foreign functions
pub struct ForeignAPIHandlerV2<L, C, K>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
/// Wallet instance
pub wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
/// Keychain mask
pub keychain_mask: Arc<Mutex<Option<SecretKey>>>,
}
impl<L, C, K> ForeignAPIHandlerV2<L, C, K>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
/// Create a new foreign API handler for GET methods
pub fn new(
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
keychain_mask: Arc<Mutex<Option<SecretKey>>>,
) -> ForeignAPIHandlerV2<L, C, K> {
ForeignAPIHandlerV2 {
wallet,
keychain_mask,
}
}
async fn call_api(
req: Request<Body>,
api: Foreign<'static, L, C, K>,
) -> Result<serde_json::Value, Error> {
let val: serde_json::Value = parse_body(req).await?;
match <dyn ForeignRpc>::handle_request(&api, val) {
MaybeReply::Reply(r) => Ok(r),
MaybeReply::DontReply => {
// Since it's http, we need to return something. We return [] because jsonrpc
// clients will parse it as an empty batch response.
Ok(serde_json::json!([]))
}
}
}
async fn handle_post_request(
req: Request<Body>,
mask: Option<SecretKey>,
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
) -> Result<Response<Body>, Error> {
let api = Foreign::new(wallet, mask, Some(check_middleware));
//Here is a wrapper to call future from that.
// Issue that we can't call future form future
let handler = move || -> Pin<Box<dyn std::future::Future<Output=Result<serde_json::Value, Error>>>> {
let future = Self::call_api(req, api);
Box::pin(future)
};
let res = crate::executor::RunHandlerInThread::new(handler).await?;
Ok(json_response_pretty(&res))
}
}
impl<L, C, K> api::Handler for ForeignAPIHandlerV2<L, C, K>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
fn post(&self, req: Request<Body>) -> ResponseFuture {
let mask = self.keychain_mask.lock().clone();
let wallet = self.wallet.clone();
Box::pin(async move {
match Self::handle_post_request(req, mask, wallet).await {
Ok(v) => Ok(v),
Err(e) => {
error!("Request Error: {:?}", e);
Ok(create_error_response(e))
}
}
})
}
fn options(&self, _req: Request<Body>) -> ResponseFuture {
Box::pin(async { Ok(create_ok_response("{}")) })
}
}
// Utility to serialize a struct into JSON and produce a sensible Response
// out of it.
fn _json_response<T>(s: &T) -> Response<Body>
where
T: Serialize,
{
match serde_json::to_string(s) {
Ok(json) => response(StatusCode::OK, json),
Err(e) => response(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unable to parse response object, {}", e),
),
}
}
// pretty-printed version of above
fn json_response_pretty<T>(s: &T) -> Response<Body>
where
T: Serialize,
{
match serde_json::to_string_pretty(s) {
Ok(json) => response(StatusCode::OK, json),
Err(e) => response(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unable to parse response object, {}", e),
),
}
}
fn create_error_response(e: Error) -> Response<Body> {
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header("access-control-allow-origin", "*")
.header(
"access-control-allow-headers",
"Content-Type, Authorization",
)
.body(format!("{}", e).into())
.unwrap()
}
fn create_ok_response(json: &str) -> Response<Body> {
Response::builder()
.status(StatusCode::OK)
.header("access-control-allow-origin", "*")
.header(
"access-control-allow-headers",
"Content-Type, Authorization",
)
.header(hyper::header::CONTENT_TYPE, "application/json")
.body(json.to_string().into())
.unwrap()
}
/// Build a new hyper Response with the status code and body provided.
///
/// Whenever the status code is `StatusCode::OK` the text parameter should be
/// valid JSON as the content type header will be set to `application/json'
fn response<T: Into<Body>>(status: StatusCode, text: T) -> Response<Body> {
let mut builder = Response::builder()
.status(status)
.header("access-control-allow-origin", "*")
.header(
"access-control-allow-headers",
"Content-Type, Authorization",
);
if status == StatusCode::OK {
builder = builder.header(hyper::header::CONTENT_TYPE, "application/json");
}
builder.body(text.into()).unwrap()
}
async fn parse_body<T>(req: Request<Body>) -> Result<T, Error>
where
for<'de> T: Deserialize<'de> + Send + 'static,
{
let body = body::to_bytes(req.into_body())
.await
.map_err(|e| ErrorKind::GenericError(format!("Failed to read request, {}", e)))?;
serde_json::from_reader(&body[..])
.map_err(|e| ErrorKind::GenericError(format!("Invalid request body, {}", e)).into())
}
|
use std::fs::File;
use std::io::prelude::*;
use std::io::{BufReader, LineWriter};
use crate::editor::Editor;
impl Editor {
/// Load the contents of a file into the buffer, overwriting the current
/// contents of the buffer.
pub fn load(&mut self) {
if !self.filename.is_empty() {
// TODO: Persist the reader within an editor, only read when needed
let reader = BufReader::new(File::open(&self.filename).unwrap());
self.buffer = reader.lines().map(|line| line.unwrap()).collect();
self.refresh_all();
}
}
/// Save the contents of the buffer to a file, truncating the file if it
/// exists.
pub fn save(&mut self) {
if !self.filename.is_empty() {
let mut writer = LineWriter::new(File::create(&self.filename).unwrap());
for line in &self.buffer {
writeln!(writer, "{}", line).unwrap();
}
self.print_notice("Saved.");
}
}
}
|
pub fn is_palindrome(x: i32) -> bool {
x.to_string().chars().rev().eq(x.to_string().chars())
}
fn main() {
assert!(is_palindrome(121));
assert!(!is_palindrome(10));
}
|
#[doc = "Register `DTCMCR` reader"]
pub type R = crate::R<DTCMCR_SPEC>;
#[doc = "Register `DTCMCR` writer"]
pub type W = crate::W<DTCMCR_SPEC>;
#[doc = "Field `EN` reader - EN"]
pub type EN_R = crate::BitReader;
#[doc = "Field `EN` writer - EN"]
pub type EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RMW` reader - RMW"]
pub type RMW_R = crate::BitReader;
#[doc = "Field `RMW` writer - RMW"]
pub type RMW_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RETEN` reader - RETEN"]
pub type RETEN_R = crate::BitReader;
#[doc = "Field `RETEN` writer - RETEN"]
pub type RETEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SZ` reader - SZ"]
pub type SZ_R = crate::FieldReader;
#[doc = "Field `SZ` writer - SZ"]
pub type SZ_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>;
impl R {
#[doc = "Bit 0 - EN"]
#[inline(always)]
pub fn en(&self) -> EN_R {
EN_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - RMW"]
#[inline(always)]
pub fn rmw(&self) -> RMW_R {
RMW_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - RETEN"]
#[inline(always)]
pub fn reten(&self) -> RETEN_R {
RETEN_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bits 3:6 - SZ"]
#[inline(always)]
pub fn sz(&self) -> SZ_R {
SZ_R::new(((self.bits >> 3) & 0x0f) as u8)
}
}
impl W {
#[doc = "Bit 0 - EN"]
#[inline(always)]
#[must_use]
pub fn en(&mut self) -> EN_W<DTCMCR_SPEC, 0> {
EN_W::new(self)
}
#[doc = "Bit 1 - RMW"]
#[inline(always)]
#[must_use]
pub fn rmw(&mut self) -> RMW_W<DTCMCR_SPEC, 1> {
RMW_W::new(self)
}
#[doc = "Bit 2 - RETEN"]
#[inline(always)]
#[must_use]
pub fn reten(&mut self) -> RETEN_W<DTCMCR_SPEC, 2> {
RETEN_W::new(self)
}
#[doc = "Bits 3:6 - SZ"]
#[inline(always)]
#[must_use]
pub fn sz(&mut self) -> SZ_W<DTCMCR_SPEC, 3> {
SZ_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 = "Instruction and Data Tightly-Coupled Memory Control Registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dtcmcr::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 [`dtcmcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DTCMCR_SPEC;
impl crate::RegisterSpec for DTCMCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`dtcmcr::R`](R) reader structure"]
impl crate::Readable for DTCMCR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`dtcmcr::W`](W) writer structure"]
impl crate::Writable for DTCMCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DTCMCR to value 0"]
impl crate::Resettable for DTCMCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use core::{fmt, mem, slice};
use std::{panic, ptr};
use std::ffi::CStr;
use std::ffi::CString;
use std::time::Duration;
use libc;
use nix::sys::socket::Ipv4Addr;
use nix::sys::socket::SockAddr;
use nix::sys::time::TimeVal;
mod raw;
#[derive(Debug)]
pub struct DeviceAddress {
pub ip: Ipv4Addr,
pub netmask: Ipv4Addr,
}
#[derive(Debug)]
pub struct Address {
pub addr: SockAddr,
pub netmask: Option<SockAddr>,
pub broadaddr: Option<SockAddr>,
pub dstaddr: Option<SockAddr>,
}
#[derive(Debug)]
pub struct Device {
pub name: String,
pub description: Option<String>,
pub addresses: Vec<Address>,
pub flags: u32,
}
#[derive(Debug)]
pub struct Handle<T> {
handle: *const T
}
impl<T> Handle<T> {
fn as_mut_ptr(&self) -> *mut T {
self.handle as *mut T
}
}
pub type DeviceHandle = Handle<raw::pcap_t>;
pub type DumperHandle = Handle<raw::pcap_dumper_t>;
#[repr(C)]
pub struct PacketHeader {
pub ts: libc::timeval,
pub caplen: u32,
pub len: u32,
}
impl fmt::Debug for PacketHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"PacketHeader {{ ts: {}, caplen: {}, len: {} }}",
TimeVal::from(self.ts),
self.caplen,
self.len)
}
}
#[derive(Debug)]
pub struct PacketCapture<'a> {
pub header: &'a PacketHeader,
pub packet: &'a [u8],
}
fn from_c_string(ptr: *const ::std::os::raw::c_char) -> Option<String> {
if ptr.is_null() {
None
} else {
Some(unsafe { CStr::from_ptr(ptr).to_string_lossy().into_owned() })
}
}
unsafe fn parse_pcap_addr_t(addrs: *const raw::pcap_addr_t) -> Vec<Address> {
let mut addresses = Vec::new();
let mut it = addrs;
while !it.is_null() {
let curr_addr = *it;
SockAddr::from_libc_sockaddr(curr_addr.addr).map(|addr| {
addresses.push(Address {
addr: addr,
netmask: SockAddr::from_libc_sockaddr(curr_addr.netmask),
broadaddr: SockAddr::from_libc_sockaddr(curr_addr.broadaddr),
dstaddr: SockAddr::from_libc_sockaddr(curr_addr.dstaddr),
})
});
it = curr_addr.next;
}
addresses
}
#[deprecated(note = "This interface is obsoleted by pcap_findalldevs")]
pub fn pcap_lookupdev() -> Option<String> {
unsafe {
let mut errbuf = [0i8; raw::PCAP_ERRBUF_SIZE as usize];
let ptr = errbuf.as_mut_ptr();
let name = raw::pcap_lookupdev(ptr);
from_c_string(name)
}
}
pub fn pcap_lookupnet(
device: &str
) -> Result<DeviceAddress, String> {
let mut errbuf = [0i8; raw::PCAP_ERRBUF_SIZE as usize];
let err_ptr = errbuf.as_mut_ptr();
let mut netp: raw::bpf_u_int32 = 0;
let mut maskp: raw::bpf_u_int32 = 0;
let device_c = CString::new(device).unwrap();
unsafe {
if raw::pcap_lookupnet(device_c.as_ptr(), &mut netp, &mut maskp, err_ptr) == 0 {
let netp_ptr: *const libc::in_addr = mem::transmute(&netp);
let maskp_ptr: *const libc::in_addr = mem::transmute(&maskp);
Ok(DeviceAddress {
ip: Ipv4Addr(*netp_ptr),
netmask: Ipv4Addr(*maskp_ptr),
})
} else {
Err(from_c_string(err_ptr).unwrap())
}
}
}
pub fn pcap_lib_version() -> Option<String> {
unsafe {
from_c_string(raw::pcap_lib_version())
}
}
/**
pub fn pcap_freealldevs(arg1: *mut pcap_if_t) {}
pub fn bpf_image(
arg1: *const bpf_insn,
arg2: ::std::os::raw::c_int,
) -> *mut ::std::os::raw::c_char {}
pub fn bpf_dump(arg1: *const bpf_program, arg2: ::std::os::raw::c_int) {}
//TODO
pub fn pcap_get_selectable_fd(arg1: *mut pcap_t) -> ::std::os::raw::c_int {}
**/
/**
pub fn pcap_open_dead(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int) -> *mut pcap_t {}
pub fn pcap_open_dead_with_tstamp_precision(
arg1: ::std::os::raw::c_int,
arg2: ::std::os::raw::c_int,
arg3: u_int,
) -> *mut pcap_t {}
pub fn pcap_open_offline_with_tstamp_precision(
arg1: *const ::std::os::raw::c_char,
arg2: u_int,
arg3: *mut ::std::os::raw::c_char,
) -> *mut pcap_t {}
pub fn pcap_open_offline(
arg1: *const ::std::os::raw::c_char,
arg2: *mut ::std::os::raw::c_char,
) -> *mut pcap_t {
}
pub fn pcap_fopen_offline_with_tstamp_precision(
arg1: *mut FILE,
arg2: u_int,
arg3: *mut ::std::os::raw::c_char,
) -> *mut pcap_t {}
pub fn pcap_fopen_offline(arg1: *mut FILE, arg2: *mut ::std::os::raw::c_char) -> *mut pcap_t {}
**/
pub fn pcap_close(handle: &DeviceHandle) {
unsafe {
raw::pcap_close(handle.as_mut_ptr())
}
}
unsafe extern fn packet_capture_callback<F: Fn(&PacketCapture)>(user: *mut raw::u_char,
header: *const raw::pcap_pkthdr,
packet: *const raw::u_char) {
let packet_capture = from_raw_packet_capture(packet, header);
let cb_state_ptr = unsafe { &mut *(user as *mut CallbackState<F>) };
match *cb_state_ptr {
CallbackState::Callback(ref mut cb_ptr) => {
let callback = cb_ptr as *mut F as *mut raw::u_char;
panic::catch_unwind(|| {
let callback = unsafe { &mut *(callback as *mut F) };
packet_capture.iter().for_each(|p| callback(&p));
});
}
}
}
pub fn pcap_create(
source: &str
) -> Result<DeviceHandle, String> {
let mut errbuf = [0i8; raw::PCAP_ERRBUF_SIZE as usize];
let err_ptr = errbuf.as_mut_ptr();
let device_c = CString::new(source).unwrap();
unsafe {
let handle_ptr = raw::pcap_create(device_c.as_ptr(), err_ptr);
if handle_ptr.is_null() {
Err(from_c_string(err_ptr).unwrap())
} else {
Ok(DeviceHandle { handle: handle_ptr })
}
}
}
pub fn pcap_set_snaplen(
handle: &DeviceHandle,
snaplen: i32,
) -> i32 {
unsafe {
raw::pcap_set_snaplen(handle.as_mut_ptr(), snaplen)
}
}
pub fn pcap_set_promisc(
handle: &DeviceHandle,
promisc: i32,
) -> i32 {
unsafe {
raw::pcap_set_promisc(handle.as_mut_ptr(), promisc)
}
}
pub fn pcap_can_set_rfmon(handle: &DeviceHandle) -> i32 {
unsafe {
raw::pcap_can_set_rfmon(handle.as_mut_ptr())
}
}
pub fn pcap_set_rfmon(handle: &DeviceHandle, rfmon: i32) -> i32 {
unsafe {
raw::pcap_set_rfmon(handle.as_mut_ptr(), rfmon)
}
}
pub fn pcap_set_timeout(
handle: &DeviceHandle,
timeout: Duration,
) -> i32 {
unsafe {
raw::pcap_set_timeout(handle.as_mut_ptr(), timeout.as_millis() as _)
}
}
pub fn pcap_set_tstamp_type(
handle: &DeviceHandle,
tstamp_type: i32,
) -> i32 {
unsafe {
raw::pcap_set_tstamp_type(handle.as_mut_ptr(), tstamp_type)
}
}
pub fn pcap_set_immediate_mode(
handle: &DeviceHandle,
immediate_mode: i32,
) -> i32 {
unsafe {
raw::pcap_set_immediate_mode(handle.as_mut_ptr(), immediate_mode)
}
}
pub fn pcap_set_buffer_size(
handle: &DeviceHandle,
buffer_size: i32,
) -> i32 {
unsafe {
raw::pcap_set_buffer_size(handle.as_mut_ptr(), buffer_size)
}
}
pub fn pcap_set_tstamp_precision(
handle: &DeviceHandle,
tstamp_precision: i32,
) -> i32 {
unsafe {
raw::pcap_set_tstamp_precision(handle.as_mut_ptr(), tstamp_precision)
}
}
pub fn pcap_get_tstamp_precision(handle: &DeviceHandle) -> i32 {
unsafe {
raw::pcap_get_tstamp_precision(handle.as_mut_ptr())
}
}
pub fn pcap_activate(handle: &DeviceHandle) -> i32 {
unsafe {
raw::pcap_activate(handle.as_mut_ptr())
}
}
pub fn pcap_list_tstamp_types(handle: &DeviceHandle) -> Result<Vec<i32>, String> {
let mut tstamp_types_ptr: *mut ::std::os::raw::c_int = ptr::null_mut();
unsafe {
let count = raw::pcap_list_tstamp_types(handle.as_mut_ptr(), &mut tstamp_types_ptr);
if count == raw::PCAP_ERROR {
return Err(pcap_geterr(handle).unwrap());
}
let tstamp_types: &[i32] = slice::from_raw_parts(tstamp_types_ptr, count as usize);
raw::pcap_free_tstamp_types(tstamp_types_ptr);
Result::Ok(Vec::from(tstamp_types))
}
}
/**
pub fn pcap_free_tstamp_types(arg1: *mut ::std::os::raw::c_int) {}
**/
pub fn pcap_tstamp_type_name_to_val(name: &str) -> i32 {
let name_c = CString::new(name).unwrap();
unsafe {
raw::pcap_tstamp_type_name_to_val(name_c.as_ptr())
}
}
pub fn pcap_tstamp_type_val_to_name(val: i32) -> Option<String> {
unsafe {
from_c_string(raw::pcap_tstamp_type_val_to_name(val))
}
}
pub fn pcap_tstamp_type_val_to_description(val: i32) -> Option<String> {
unsafe {
from_c_string(raw::pcap_tstamp_type_val_to_description(val))
}
}
pub fn pcap_open_live(
device: &str,
snaplen: i32,
promisc: i32,
to_ms: i32,
) -> Result<DeviceHandle, String> {
let mut errbuf = [0i8; raw::PCAP_ERRBUF_SIZE as usize];
let err_ptr = errbuf.as_mut_ptr();
let device_c = CString::new(device).unwrap();
unsafe {
let handle_ptr = raw::pcap_open_live(device_c.as_ptr(), snaplen, promisc, to_ms, err_ptr);
if handle_ptr.is_null() {
Err(from_c_string(err_ptr).unwrap())
} else {
Ok(DeviceHandle { handle: handle_ptr })
}
}
}
enum CallbackState<F: Fn(&PacketCapture)> {
Callback(F),
}
//TODO: pass optional user data with the callback
pub fn pcap_loop<F: Fn(&PacketCapture)>(
handle: &DeviceHandle,
count: i32,
callback: F,
) -> i32 {
unsafe {
let mut cb_state = CallbackState::Callback(callback);
let cb_ptr = &mut cb_state as *mut _ as *mut raw::u_char;
raw::pcap_loop(handle.as_mut_ptr(),
count,
Some(packet_capture_callback::<F>),
cb_ptr)
}
}
//TODO: pass optional user data with the callback
pub fn pcap_dispatch<F: Fn(&PacketCapture)>(
handle: &DeviceHandle,
count: i32,
callback: F,
) -> i32 {
unsafe {
let mut cb_state = CallbackState::Callback(callback);
let cb_ptr = &mut cb_state as *mut _ as *mut raw::u_char;
raw::pcap_dispatch(handle.as_mut_ptr(),
count,
Some(packet_capture_callback::<F>),
cb_ptr)
}
}
unsafe fn from_raw_packet_capture<'a>(raw_packet: *const raw::u_char,
raw_header: *const raw::pcap_pkthdr) -> Option<PacketCapture<'a>> {
if raw_packet.is_null() {
None
} else {
let header: &PacketHeader = mem::transmute(&*raw_header);
let packet = core::slice::from_raw_parts(raw_packet, (&*header).len as _);
Some(PacketCapture {
header,
packet,
})
}
}
pub fn pcap_next(handle: &DeviceHandle) -> Option<PacketCapture> {
unsafe {
let mut packet_header: raw::pcap_pkthdr = std::mem::zeroed();
let packet_ptr = raw::pcap_next(handle.as_mut_ptr(), &mut packet_header);
from_raw_packet_capture(packet_ptr, &packet_header)
}
}
pub fn pcap_next_ex(
handle: &DeviceHandle
) -> Result<PacketCapture, i32> {
unsafe {
let mut packet_ptr: *const raw::u_char = ptr::null_mut();
let mut packet_header: *mut raw::pcap_pkthdr = ptr::null_mut();
match raw::pcap_next_ex(handle.as_mut_ptr(), &mut packet_header, &mut packet_ptr) {
1 => {
Ok(from_raw_packet_capture(packet_ptr, packet_header).unwrap())
}
err => {
Err(err)
}
}
}
}
pub fn pcap_breakloop(handle: &DeviceHandle) {
unsafe {
raw::pcap_breakloop(handle.as_mut_ptr())
}
}
/**
pub fn pcap_stats(arg1: *mut pcap_t, arg2: *mut pcap_stat) -> ::std::os::raw::c_int {}
pub fn pcap_setfilter(arg1: *mut pcap_t, arg2: *mut bpf_program) -> ::std::os::raw::c_int {}
pub fn pcap_setdirection(arg1: *mut pcap_t, arg2: pcap_direction_t) -> ::std::os::raw::c_int {}
pub fn pcap_getnonblock(
arg1: *mut pcap_t,
arg2: *mut ::std::os::raw::c_char,
) -> ::std::os::raw::c_int {}
pub fn pcap_setnonblock(
arg1: *mut pcap_t,
arg2: ::std::os::raw::c_int,
arg3: *mut ::std::os::raw::c_char,
) -> ::std::os::raw::c_int {}
pub fn pcap_inject(
arg1: *mut pcap_t,
arg2: *const ::std::os::raw::c_void,
arg3: usize,
) -> ::std::os::raw::c_int {}
pub fn pcap_sendpacket(
arg1: *mut pcap_t,
arg2: *const u_char,
arg3: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int {}
**/
pub fn pcap_statustostr(errnum: i32) -> Option<String> {
unsafe {
from_c_string(raw::pcap_statustostr(errnum))
}
}
pub fn pcap_strerror(errnum: i32) -> Option<String> {
unsafe {
from_c_string(raw::pcap_strerror(errnum))
}
}
pub fn pcap_geterr(handle: &DeviceHandle) -> Option<String> {
unsafe {
from_c_string(raw::pcap_geterr(handle.as_mut_ptr()))
}
}
pub fn pcap_perror(handle: &DeviceHandle, prefix: &str) {
let prefix_c = CString::new(prefix).unwrap();
unsafe {
raw::pcap_perror(handle.as_mut_ptr(), prefix_c.as_ptr())
}
}
/**
pub fn pcap_compile(
arg1: *mut pcap_t,
arg2: *mut bpf_program,
arg3: *const ::std::os::raw::c_char,
arg4: ::std::os::raw::c_int,
arg5: bpf_u_int32,
) -> ::std::os::raw::c_int {}
pub fn pcap_compile_nopcap(
arg1: ::std::os::raw::c_int,
arg2: ::std::os::raw::c_int,
arg3: *mut bpf_program,
arg4: *const ::std::os::raw::c_char,
arg5: ::std::os::raw::c_int,
arg6: bpf_u_int32,
) -> ::std::os::raw::c_int {}
pub fn pcap_freecode(arg1: *mut bpf_program) {}
pub fn pcap_offline_filter(
arg1: *const bpf_program,
arg2: *const pcap_pkthdr,
arg3: *const u_char,
) -> ::std::os::raw::c_int {}
**/
pub fn pcap_datalink(handle: &DeviceHandle) -> i32 {
unsafe {
raw::pcap_datalink(handle.as_mut_ptr())
}
}
pub fn pcap_datalink_ext(handle: &DeviceHandle) -> i32 {
unsafe {
raw::pcap_datalink_ext(handle.as_mut_ptr())
}
}
/**
pub fn pcap_list_datalinks(
arg1: *mut pcap_t,
arg2: *mut *mut ::std::os::raw::c_int,
) -> ::std::os::raw::c_int {}
pub fn pcap_set_datalink(
arg1: *mut pcap_t,
arg2: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int {}
pub fn pcap_free_datalinks(arg1: *mut ::std::os::raw::c_int) {}
**/
pub fn pcap_datalink_name_to_val(name: &str) -> i32 {
let name_c = CString::new(name).unwrap();
unsafe {
raw::pcap_datalink_name_to_val(name_c.as_ptr())
}
}
pub fn pcap_datalink_val_to_name(val: i32) -> Option<String> {
unsafe {
from_c_string(raw::pcap_datalink_val_to_name(val))
}
}
pub fn pcap_datalink_val_to_description(
val: i32,
) -> Option<String> {
unsafe {
from_c_string(raw::pcap_datalink_val_to_description(val))
}
}
pub fn pcap_snapshot(handle: &DeviceHandle) -> i32 {
unsafe {
raw::pcap_snapshot(handle.as_mut_ptr())
}
}
pub fn pcap_is_swapped(handle: &DeviceHandle) -> i32 {
unsafe {
raw::pcap_is_swapped(handle.as_mut_ptr())
}
}
pub fn pcap_major_version(handle: &DeviceHandle) -> i32 {
unsafe {
raw::pcap_major_version(handle.as_mut_ptr())
}
}
pub fn pcap_minor_version(handle: &DeviceHandle) -> i32 {
unsafe {
raw::pcap_minor_version(handle.as_mut_ptr())
}
}
/**
pub fn pcap_file(arg1: *mut pcap_t) -> *mut FILE {}
pub fn pcap_fileno(arg1: *mut pcap_t) -> ::std::os::raw::c_int {}
**/
pub fn pcap_dump_open(
handle: &DeviceHandle,
fname: &str,
) -> Result<DumperHandle, String> {
let fname_c = CString::new(fname).unwrap();
unsafe {
let handle_ptr = raw::pcap_dump_open(handle.as_mut_ptr(), fname_c.as_ptr());
if handle_ptr.is_null() {
Err(pcap_geterr(&handle).unwrap())
} else {
Ok(DumperHandle { handle: handle_ptr })
}
}
}
/**
pub fn pcap_dump_fopen(arg1: *mut pcap_t, fp: *mut FILE) -> *mut pcap_dumper_t {}
pub fn pcap_dump_open_append(
arg1: *mut pcap_t,
arg2: *const ::std::os::raw::c_char,
) -> *mut pcap_dumper_t {}
pub fn pcap_dump_file(arg1: *mut pcap_dumper_t) -> *mut FILE {}
pub fn pcap_dump_ftell(arg1: *mut pcap_dumper_t) -> ::std::os::raw::c_long {}
pub fn pcap_dump_flush(arg1: *mut pcap_dumper_t) -> ::std::os::raw::c_int {}
**/
pub fn pcap_dump_close(dumper: &DumperHandle) {
unsafe {
raw::pcap_dump_close(dumper.as_mut_ptr())
}
}
pub fn pcap_dump(dumper: &DumperHandle, capture: &PacketCapture) {
unsafe {
raw::pcap_dump(dumper.as_mut_ptr() as _,
mem::transmute(capture.header),
capture.packet.as_ptr())
}
}
pub fn pcap_findalldevs() -> Result<Vec<Device>, String> {
unsafe {
let mut errbuf = [0i8; raw::PCAP_ERRBUF_SIZE as usize];
let err_ptr = errbuf.as_mut_ptr();
let mut alldevsp: *mut raw::pcap_if_t = ptr::null_mut();
if raw::pcap_findalldevs(&mut alldevsp, err_ptr) == raw::PCAP_ERROR {
return Err(from_c_string(err_ptr).unwrap());
}
let mut curr_ptr = alldevsp;
let mut devices = vec![];
while !curr_ptr.is_null() {
let curr = &*curr_ptr;
let device = from_c_string(curr.name).map(|name| Device {
name,
description: from_c_string(curr.description),
addresses: parse_pcap_addr_t(curr.addresses),
flags: curr.flags,
});
if device.is_some() {
devices.push(device.unwrap());
}
curr_ptr = curr.next;
}
raw::pcap_freealldevs(alldevsp);
Result::Ok(devices)
}
}
|
#![allow(dead_code)]
use super::models::{FileExtension, FileName};
use super::shared::{ListenerData, Logs};
use maplit::hashmap;
use std::collections::HashMap;
use std::fs::read_dir;
use std::path::Path;
#[derive(Debug, Default)]
pub struct SmartOrganizer<'a> {
pub options: Vec<ListenerData>,
default_options: HashMap<&'a str, Vec<&'a str>>,
presets: Vec<String>,
pub combinations: Vec<HashMap<&'a str, &'a str>>,
}
impl<'a> SmartOrganizer<'a> {
pub fn organize(&mut self) -> Vec<Vec<Logs>> {
// println!("self.options: {:#?}", self.options);
let mut logs: Vec<Vec<Logs>> = Vec::new();
for option in self.options.iter_mut() {
for combination in &self.combinations {
for (_, actions) in &option.action_paths.clone() {
for action in actions {
let option_map = hashmap! {
"type".to_owned() => option.type_.clone(),
"rule".to_owned() => option.rule.clone(),
"action".to_owned() => action.to_owned(),
};
if SmartOrganizer::compare_options(combination, &option_map) {
match &SmartOrganizer::determine_preset(combination)[..] {
"111" | "112" | "113" | "114" | "121" | "122" | "123" | "124" => {
// let
logs.push(FileExtension::new(option).sort());
}
"211" | "212" | "213" | "214" | "221" | "222" | "223" | "224" => {
logs.push(FileName::new(option).sort());
}
_ => {
println!("The other thingy")
}
}
}
}
}
}
}
logs
}
pub fn push(&mut self, listener: ListenerData) {
self.options.push(listener);
}
pub fn replace(&mut self, listener: ListenerData) {
let index = listener.index;
self.options[index] = listener;
}
pub fn remove_at(&mut self, index: usize) {
self.options.remove(index);
for (idx, option) in self.options.iter_mut().enumerate() {
option.index = idx;
}
}
}
impl<'a> SmartOrganizer<'a> {
pub fn new() -> Self {
let default_options: HashMap<&'a str, Vec<&'a str>> = hashmap! {
"type" => vec!["FileExtension-1", "FileName-2"],
"rule" => vec!["Includes-1", "Not Includes-2"],
"action" => vec!["COPY-1", "MOVE-2", "DELETE-3", "UNLINK-4"]
};
let mut combinations: Vec<HashMap<&'a str, &'a str>> = Vec::new();
println!("In the new Function");
for &_type in default_options.get("type").unwrap() {
for &rule in default_options.get("rule").unwrap() {
for &action in default_options.get("action").unwrap() {
let map: HashMap<&'a str, &'a str> = hashmap! {
"type" => _type,
"rule" => rule,
"action" => action
};
combinations.push(map);
}
}
}
Self {
options: Vec::new(),
presets: Vec::new(),
default_options,
combinations,
}
}
}
impl<'a> SmartOrganizer<'a> {
fn split(object: &HashMap<&'a str, &'a str>, key: &'a str) -> Vec<&'a str> {
object.get(key).unwrap().split("-").collect()
}
fn compare_options(
default_option: &HashMap<&'a str, &'a str>,
option: &HashMap<String, String>,
) -> bool {
let default_type = SmartOrganizer::split(default_option, "type")[0];
let default_rule = SmartOrganizer::split(default_option, "rule")[0];
let default_action = SmartOrganizer::split(default_option, "action")[0];
let option_type = option.get("type").unwrap();
let option_rule = option.get("rule").unwrap();
let option_action = option.get("action").unwrap();
if default_type == option_type {
if default_rule == option_rule {
if default_action == option_action {
return true;
}
}
}
false
}
fn determine_preset(combination: &'a HashMap<&'a str, &'a str>) -> String {
let preset = format!(
"{}{}{}",
SmartOrganizer::split(&combination, "type")[1],
SmartOrganizer::split(&combination, "rule")[1],
SmartOrganizer::split(&combination, "action")[1]
);
preset
}
fn dir(path: &'a str) -> Vec<String> {
let directory = read_dir(&Path::new(path));
let mut paths: Vec<String> = vec![];
for dir in directory.unwrap() {
if let Ok(res) = dir {
if let Some(x) = res.path().as_path().to_str() {
paths.push(x.to_owned());
}
}
}
paths
}
}
// Locations to Monitor
// ["/home/h4ck3r/Downloads", "/home/h4ck3r/Desktop"]
// Search Types
// ["Filename", "FileExtension"]
// Conditions
// ["Includes", "Not Includes"]
// Data
// A text to split for whitespace for different types
// Actions to take
// ["MOVE", "UMLINK", "COPY", "DELETE", "NOTIFY"]
// SmartOrganizing is enabled
// enable_smart_organizer: false
|
use crate::arena::Detection;
use crate::geometry::Direction;
use rand::seq::SliceRandom;
use std::collections::HashMap;
pub type Ai = fn(Detection) -> Option<Direction>;
fn walkable_tiles(walk_around: HashMap<Direction, bool>) -> Vec<Direction> {
walk_around
.iter()
.filter(|&(_, &walkable)| walkable)
.map(|(&direction, _)| direction)
.collect()
}
pub fn human_player(_detect: Detection) -> Option<Direction> {
None // TODO: implement with human player action events
}
pub fn random_walk(detect: Detection) -> Option<Direction> {
let walkable_tiles = walkable_tiles(detect.walk_around);
match walkable_tiles.choose(&mut rand::thread_rng()) {
None => None,
Some(dir) => Some(*dir),
}
}
|
extern crate espronceda;
use espronceda::parse::parse_code;
use swc_common::sync::Lrc;
use swc_common::SourceMap;
fn main() -> anyhow::Result<()> {
let source_map: Lrc<SourceMap> = Default::default();
parse_code(&source_map, "function a() {}")?;
Ok(())
}
|
extern crate advent_of_code_2017_day_16;
// use advent_of_code_2017_day_16::*;
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Key register"]
pub iwdg_kr: IWDG_KR,
#[doc = "0x04 - Prescaler register"]
pub iwdg_pr: IWDG_PR,
#[doc = "0x08 - Reload register"]
pub iwdg_rlr: IWDG_RLR,
#[doc = "0x0c - Status register"]
pub iwdg_sr: IWDG_SR,
#[doc = "0x10 - Window register"]
pub iwdg_winr: IWDG_WINR,
_reserved5: [u8; 988usize],
#[doc = "0x3f0 - IWDG hardware configuration register"]
pub iwdg_hwcfgr: IWDG_HWCFGR,
#[doc = "0x3f4 - IWDG version register"]
pub iwdg_verr: IWDG_VERR,
#[doc = "0x3f8 - IWDG identification register"]
pub iwdg_idr: IWDG_IDR,
#[doc = "0x3fc - IWDG size identification register"]
pub iwdg_sidr: IWDG_SIDR,
}
#[doc = "Key register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [iwdg_kr](iwdg_kr) module"]
pub type IWDG_KR = crate::Reg<u32, _IWDG_KR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IWDG_KR;
#[doc = "`read()` method returns [iwdg_kr::R](iwdg_kr::R) reader structure"]
impl crate::Readable for IWDG_KR {}
#[doc = "`write(|w| ..)` method takes [iwdg_kr::W](iwdg_kr::W) writer structure"]
impl crate::Writable for IWDG_KR {}
#[doc = "Key register"]
pub mod iwdg_kr;
#[doc = "Prescaler register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [iwdg_pr](iwdg_pr) module"]
pub type IWDG_PR = crate::Reg<u32, _IWDG_PR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IWDG_PR;
#[doc = "`read()` method returns [iwdg_pr::R](iwdg_pr::R) reader structure"]
impl crate::Readable for IWDG_PR {}
#[doc = "`write(|w| ..)` method takes [iwdg_pr::W](iwdg_pr::W) writer structure"]
impl crate::Writable for IWDG_PR {}
#[doc = "Prescaler register"]
pub mod iwdg_pr;
#[doc = "Reload register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [iwdg_rlr](iwdg_rlr) module"]
pub type IWDG_RLR = crate::Reg<u32, _IWDG_RLR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IWDG_RLR;
#[doc = "`read()` method returns [iwdg_rlr::R](iwdg_rlr::R) reader structure"]
impl crate::Readable for IWDG_RLR {}
#[doc = "`write(|w| ..)` method takes [iwdg_rlr::W](iwdg_rlr::W) writer structure"]
impl crate::Writable for IWDG_RLR {}
#[doc = "Reload register"]
pub mod iwdg_rlr;
#[doc = "Status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [iwdg_sr](iwdg_sr) module"]
pub type IWDG_SR = crate::Reg<u32, _IWDG_SR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IWDG_SR;
#[doc = "`read()` method returns [iwdg_sr::R](iwdg_sr::R) reader structure"]
impl crate::Readable for IWDG_SR {}
#[doc = "Status register"]
pub mod iwdg_sr;
#[doc = "Window register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [iwdg_winr](iwdg_winr) module"]
pub type IWDG_WINR = crate::Reg<u32, _IWDG_WINR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IWDG_WINR;
#[doc = "`read()` method returns [iwdg_winr::R](iwdg_winr::R) reader structure"]
impl crate::Readable for IWDG_WINR {}
#[doc = "`write(|w| ..)` method takes [iwdg_winr::W](iwdg_winr::W) writer structure"]
impl crate::Writable for IWDG_WINR {}
#[doc = "Window register"]
pub mod iwdg_winr;
#[doc = "IWDG hardware configuration register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [iwdg_hwcfgr](iwdg_hwcfgr) module"]
pub type IWDG_HWCFGR = crate::Reg<u32, _IWDG_HWCFGR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IWDG_HWCFGR;
#[doc = "`read()` method returns [iwdg_hwcfgr::R](iwdg_hwcfgr::R) reader structure"]
impl crate::Readable for IWDG_HWCFGR {}
#[doc = "IWDG hardware configuration register"]
pub mod iwdg_hwcfgr;
#[doc = "IWDG version register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [iwdg_verr](iwdg_verr) module"]
pub type IWDG_VERR = crate::Reg<u32, _IWDG_VERR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IWDG_VERR;
#[doc = "`read()` method returns [iwdg_verr::R](iwdg_verr::R) reader structure"]
impl crate::Readable for IWDG_VERR {}
#[doc = "IWDG version register"]
pub mod iwdg_verr;
#[doc = "IWDG identification register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [iwdg_idr](iwdg_idr) module"]
pub type IWDG_IDR = crate::Reg<u32, _IWDG_IDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IWDG_IDR;
#[doc = "`read()` method returns [iwdg_idr::R](iwdg_idr::R) reader structure"]
impl crate::Readable for IWDG_IDR {}
#[doc = "IWDG identification register"]
pub mod iwdg_idr;
#[doc = "IWDG size identification register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [iwdg_sidr](iwdg_sidr) module"]
pub type IWDG_SIDR = crate::Reg<u32, _IWDG_SIDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IWDG_SIDR;
#[doc = "`read()` method returns [iwdg_sidr::R](iwdg_sidr::R) reader structure"]
impl crate::Readable for IWDG_SIDR {}
#[doc = "IWDG size identification register"]
pub mod iwdg_sidr;
|
extern crate chrono;
use chrono::{DateTime, Utc};
use uuid::Uuid;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Post {
summary: String,
contents: String,
author_handle: String,
date_time: DateTime<Utc>,
uuid: Uuid,
}
impl Post {
/*pub fn new(
summary: &str,
contents: &str,
author: &Author,
date_time: DateTime<Utc>,
uuid: Uuid,
) -> Post {
Post {
summary: summary.to_string(),
contents: contents.to_string(),
author_handle: author.handle.clone(),
date_time: date_time,
uuid: uuid,
}
}*/
pub fn from_post(summary: &str, contents: &str, author: &Author) -> Post {
Post {
summary: summary.to_string(),
contents: contents.to_string(),
author_handle: author.handle.clone(),
date_time: chrono::offset::Utc::now(),
uuid: Uuid::new_v4(),
}
}
pub fn uuid(&self) -> &Uuid {
&self.uuid
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Author {
handle: String,
}
impl Author {
pub fn new(handle: &str) -> Author {
Author { handle: handle.to_string() }
}
}
|
extern crate kagura;
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]
pub fn main() {
kagura::run(kagura::Component::new(0, update, render), "app");
}
type State = u64;
enum Msg {
CountUp,
}
struct Sub;
fn update(state: &mut State, msg: &Msg) -> Option<Sub> {
match msg {
Msg::CountUp => {
*state += 1;
}
}
None
}
fn render(state: &State) -> kagura::Html<Msg> {
use kagura::Attributes;
use kagura::Events;
use kagura::Html;
let text = if state % 15 == 0 {
"fizzbuzz".to_string()
} else if state % 5 == 0 {
"buzz".to_string()
} else if state % 3 == 0 {
"fizz".to_string()
} else {
state.to_string()
};
let color = if state % 3 == 0 { "#00f" } else { "#000" };
let bg_color = if state % 5 == 0 { "#f00" } else { "#fff" };
Html::button(
Attributes::new()
.style("color", color)
.style("background-color", bg_color)
.style("width", "10ch")
.style("height", "2rem"),
Events::new().on_click(|_| Msg::CountUp),
vec![Html::unsafe_text(text)],
)
}
|
use crate::prelude::*;
pub trait WorldCommands {
fn spawn_command<T: Component>(&mut self, component: T) -> Entity;
fn spawn_batch_commands<T: Component, I>(&mut self, bundle: I)
where
I: IntoIterator<Item = T>;
fn clear_commands(&mut self);
}
impl WorldCommands for World {
fn spawn_command<T: Component>(&mut self, component: T) -> Entity {
self.spawn((Command, component))
}
fn spawn_batch_commands<T: Component, I>(&mut self, iter: I)
where
I: IntoIterator<Item = T>,
{
self.spawn_batch(iter.into_iter().map(|c| (Command, c)));
}
fn clear_commands(&mut self) {
let entities = self
.query_mut::<&Command>()
.into_iter()
.map(|(entity, _)| entity)
.collect::<Vec<_>>();
for entity in entities {
if let Err(_) = self.despawn(entity) {
console::log(format!("Tried to despawn missing entity: {}", entity.id()));
}
}
}
}
#[derive(Debug)]
struct Command;
|
//! Abstractions for PostgreSQL-specific return codes.
use sqlstate_macros::state;
use crate::Category;
pub mod class;
pub(crate) mod wrapper;
use self::class::*;
/// A representation for a PostgreSQL-specific `SQLSTATE` code.
#[state(non_standard)]
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
#[non_exhaustive]
pub enum SqlState {
#[class("01")]
Warning(Option<Warning>),
#[class("03")]
SqlStatementNotYetComplete(Option<SqlStatementNotYetComplete>),
#[class("08")]
ConnectionException(Option<ConnectionException>),
#[class("0B")]
InvalidTransactionInitiation(Option<InvalidTransactionInitiation>),
#[class("0L")]
InvalidGrantor(Option<InvalidGrantor>),
#[class("22")]
DataException(Option<DataException>),
#[class("23")]
IntegrityConstraintViolation(Option<IntegrityConstraintViolation>),
#[class("25")]
InvalidTransactionState(Option<InvalidTransactionState>),
#[class("28")]
InvalidAuthorizationSpecification(Option<InvalidAuthorizationSpecification>),
#[class("2B")]
DependentPrivilegeDescriptorsExist(Option<DependentPrivilegeDescriptorsExist>),
#[class("39")]
ExternalRoutineInvocationException(Option<ExternalRoutineInvocationException>),
#[class("40")]
TransactionRollback(Option<TransactionRollback>),
#[class("42")]
SyntaxErrorOrAccessRuleViolation(Option<SyntaxErrorOrAccessRuleViolation>),
#[class("53")]
InsufficientResources(Option<InsufficientResources>),
#[class("54")]
ProgramLimitExceeded(Option<ProgramLimitExceeded>),
#[class("55")]
ObjectNotInPrerequisiteState(Option<ObjectNotInPrerequisiteState>),
#[class("57")]
OperatorIntervention(Option<OperatorIntervention>),
#[class("58")]
SystemError(Option<SystemError>),
#[class("72")]
SnapshotFailure(Option<SnapshotFailure>),
#[class("F0")]
ConfigurationFileError(Option<ConfigurationFileError>),
#[class("P0")]
PlPgSqlError(Option<PlPgSqlError>),
#[class("XX")]
InternalError(Option<InternalError>),
}
impl SqlState {
pub fn category(&self) -> Category {
match self {
Self::Warning(_) => Category::Warning,
_ => Category::Exception,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::ParseError;
fn check(state: &str, value: SqlState) {
assert_eq!(state.parse::<SqlState>().unwrap(), value);
}
#[test]
fn class() {
assert_eq!(SqlState::Warning(None).class(), "01");
assert_eq!(SqlState::InternalError(None).class(), "XX");
}
#[test]
fn subclass() {
assert_eq!(SqlState::SnapshotFailure(None).subclass(), None);
assert_eq!(
SqlState::Warning(Some(Warning::DeprecatedFeature)).subclass(),
Some("P01")
);
assert_eq!(
SqlState::InternalError(Some(InternalError::DataCorrupted)).subclass(),
Some("001")
);
}
#[test]
fn category() {
assert_eq!(
SqlState::Warning(Some(Warning::ImplicitZeroBitPadding)).category(),
Category::Warning
);
assert_eq!(
SqlState::InternalError(Some(InternalError::IndexCorrupted)).category(),
Category::Exception
);
}
#[test]
fn invalid_length() {
for i in 0..5 {
assert_eq!(
"0".repeat(i).parse::<SqlState>(),
Err(ParseError::InvalidLength(i))
);
}
}
#[test]
fn empty_class() {
check("0B000", SqlState::InvalidTransactionInitiation(None));
assert_eq!(
"0B001".parse::<SqlState>(),
Err(ParseError::UnknownSubclass(String::from("001"))),
);
}
#[test]
fn unknown_class() {
assert_eq!(
"QQ999".parse::<SqlState>(),
Err(ParseError::UnknownState(String::from("QQ999"))),
);
}
#[test]
fn one_subclass() {
check("F0000", SqlState::ConfigurationFileError(None));
check(
"F0001",
SqlState::ConfigurationFileError(Some(ConfigurationFileError::LockFileExists)),
);
assert_eq!(
"F000F".parse::<SqlState>(),
Err(ParseError::UnknownSubclass(String::from("00F"))),
);
}
#[test]
fn many_subclasses() {
check("57000", SqlState::OperatorIntervention(None));
check(
"57014",
SqlState::OperatorIntervention(Some(OperatorIntervention::QueryCanceled)),
);
check(
"57P01",
SqlState::OperatorIntervention(Some(OperatorIntervention::AdminShutdown)),
);
check(
"57P03",
SqlState::OperatorIntervention(Some(OperatorIntervention::CannotConnectNow)),
);
assert_eq!(
"57FFF".parse::<SqlState>(),
Err(ParseError::UnknownSubclass(String::from("FFF"))),
);
}
}
|
#[test]
fn check_answer_validity() {
assert_eq!(42, 42);
} |
/// [`AlignmentHorizontal`] represents an horizontal alignment of a cell content.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum AlignmentHorizontal {
/// Align to the center.
Center,
/// Align on the left.
Left,
/// Align on the right.
Right,
}
/// [`AlignmentVertical`] represents an vertical alignment of a cell content.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum AlignmentVertical {
/// Align to the center.
Center,
/// Align to the top.
Top,
/// Align to the bottom.
Bottom,
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.