text stringlengths 8 4.13M |
|---|
use bitwise::base64;
use bitwise::hex_rep::ToHexRep;
use challengeinfo::challenge::{Challenge, ChallengeInfo};
pub const INFO1: ChallengeInfo<'static> = ChallengeInfo {
set_number: 1,
challenge_number: 1,
title: "Convert hex to base64",
description: "",
url: "http://cryptopals.com/sets/1/challenges/1",
};
pub const CHALLENGE1: Challenge<'static> = Challenge {
info: INFO1,
func: execute,
};
fn execute() -> String {
let hex_str = String::from("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d");
base64::to_base64(&String::from_utf8(hex_str.to_hex().unwrap()).unwrap())
}
|
fn high_and_low(numbers: &str) {
use std::cmp;
let f = |(max, min), x| (cmp::max(max, x), cmp::min(min, x));
let answer = numbers.split_whitespace().map(|x| x.parse::<i32>().unwrap()).fold((i32::min_value(), i32::max_value()), f);
format!("{} {}", answer.0, answer.1);
}
fn main() {
print!(high_and_low("1 2 3 4 5"));
}
|
use super::*;
use crate::{alloc::Allocator, containers::String};
macro_rules! impl_primitive_ser {
($type:ty, $method:ident) => {
impl Serialize for $type
{
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Err>
{
s.$method(*self)
}
}
};
}
pub struct PrimitiveVisitorError(VisitorType);
impl VisitorError for PrimitiveVisitorError
{
fn unexpected_type(t: VisitorType) -> Self
{
Self(t)
}
}
macro_rules! impl_primitive_de {
($type:ty, $method:ident, $accept:ident) => {
impl<'de> Deserialize<'de> for $type
{
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<$type, D::Err>
{
struct PrimVisitor;
impl<'de> Visitor<'de> for PrimVisitor
{
type Value = $type;
type Err = PrimitiveVisitorError;
fn $accept(self, value: $type) -> Result<Self::Value, Self::Err>
{
Ok(value)
}
}
d.$method(PrimVisitor)
}
}
};
}
impl_primitive_ser!(u8, serialize_u8);
impl_primitive_ser!(u16, serialize_u16);
impl_primitive_ser!(u32, serialize_u32);
impl_primitive_ser!(u64, serialize_u64);
impl_primitive_ser!(i8, serialize_i8);
impl_primitive_ser!(i16, serialize_i16);
impl_primitive_ser!(i32, serialize_i32);
impl_primitive_ser!(i64, serialize_i64);
impl_primitive_ser!(f32, serialize_f32);
impl_primitive_ser!(f64, serialize_f64);
impl_primitive_ser!(&str, serialize_str);
impl_primitive_ser!(bool, serialize_bool);
impl_primitive_de!(u8, deserialize_u8, accept_u8);
impl_primitive_de!(u16, deserialize_u16, accept_u16);
impl_primitive_de!(u32, deserialize_u32, accept_u32);
impl_primitive_de!(u64, deserialize_u64, accept_u64);
impl_primitive_de!(i8, deserialize_i8, accept_i8);
impl_primitive_de!(i16, deserialize_i16, accept_i16);
impl_primitive_de!(i32, deserialize_i32, accept_i32);
impl_primitive_de!(i64, deserialize_i64, accept_i64);
impl_primitive_de!(f32, deserialize_f32, accept_f32);
impl_primitive_de!(f64, deserialize_f64, accept_f64);
impl_primitive_de!(bool, deserialize_bool, accept_bool);
impl<'a, T> Serialize for &'a T
where
T: Serialize,
{
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Err>
{
(**self).serialize(s)
}
}
impl<'a, T> Serialize for &'a mut T
where
T: Serialize,
{
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Err>
{
(**self).serialize(s)
}
}
impl<T> Serialize for [T]
where
T: Serialize,
{
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Err>
{
let mut array_serializer = s.serialize_array(Some(self.len()))?;
for x in self.iter()
{
array_serializer.serialize_element(x)?;
}
array_serializer.end()
}
}
impl<'de: 'a, 'a> Deserialize<'de> for &'a str
{
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<&'de str, D::Err>
{
struct PrimVisitor;
impl<'de> Visitor<'de> for PrimVisitor
{
type Value = &'de str;
type Err = PrimitiveVisitorError;
fn accept_borrowed_str(self, value: &'de str) -> Result<Self::Value, Self::Err>
{
Ok(value)
}
}
d.deserialize_str(PrimVisitor)
}
}
struct StringPrimVisitor<A>
{
alloc: A,
_p: core::marker::PhantomData<A>,
}
impl<'de, A: Allocator + Clone> Visitor<'de> for StringPrimVisitor<A>
{
type Value = String<A>;
type Err = PrimitiveVisitorError;
fn accept_str(self, value: &str) -> Result<Self::Value, Self::Err>
{
Ok(String::from_str_with(value, self.alloc.clone()))
}
fn accept_string<A2: Allocator>(self, value: String<A2>) -> Result<Self::Value, Self::Err>
{
Ok(String::from_str_with(&value, self.alloc.clone()))
}
}
impl<'de: 'a, 'a, A: Allocator + Default + Clone> Deserialize<'de> for String<A>
{
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<String<A>, D::Err>
{
d.deserialize_str(StringPrimVisitor {
alloc: A::default(),
_p: core::marker::PhantomData,
})
}
}
|
extern crate rand;
extern crate rand_xoshiro;
extern crate suffix_utils;
use rand::seq::SliceRandom;
use rand::{Rng, SeedableRng};
use rand_xoshiro::Xoroshiro128StarStar;
#[test]
fn sa_is_works() {
let mut rng: Xoroshiro128StarStar = SeedableRng::seed_from_u64(329);
let alphabet = b"ACGT";
let seq: Vec<_> = (0..1000)
.filter_map(|_| alphabet.choose(&mut rng))
.copied()
.collect();
let naive = suffix_utils::suffix_array::SuffixArray::new_naive(&seq, alphabet);
let sa_is = suffix_utils::suffix_array::SuffixArray::new(&seq, alphabet);
assert_eq!(naive, sa_is);
}
const TEMPLATE_LEN: usize = 10_000;
const TEST_NUM: usize = 100;
const MAX_LEN: usize = 100;
const SEED: u64 = 12910489034;
fn dataset(
seed: u64,
template_len: usize,
test_num: usize,
test_max: usize,
) -> (Vec<u8>, Vec<Vec<u8>>) {
let mut rng: Xoroshiro128StarStar = SeedableRng::seed_from_u64(seed);
let template: Vec<u8> = (0..template_len)
.map(|_| rng.gen_range(0..std::u8::MAX))
.collect();
let tests: Vec<Vec<_>> = (0..test_num)
.map(|_| {
let len = rng.gen_range(1..test_max);
(0..len).map(|_| rng.gen_range(0..std::u8::MAX)).collect()
})
.collect();
(template, tests)
}
#[test]
fn random_check() {
for i in 0..20 {
let (reference, queries) = dataset(SEED + i as u64, TEMPLATE_LEN, TEST_NUM, MAX_LEN);
use suffix_utils::suffix_array::SuffixArray;
let alphabet: Vec<u8> = (0..=std::u8::MAX).collect();
let sa = SuffixArray::new_naive(&reference, &alphabet);
for query in queries {
let have = reference
.windows(query.len())
.any(|w| w == query.as_slice());
assert_eq!(have, sa.search(&reference, &query).is_some());
}
}
}
#[test]
fn random_check_lcp() {
for i in 0..20 {
let (reference, _queries) = dataset(SEED + i as u64, TEMPLATE_LEN, TEST_NUM, MAX_LEN);
use suffix_utils::suffix_array;
use suffix_utils::suffix_array::SuffixArray;
let alphabet: Vec<u8> = (0..=std::u8::MAX).collect();
let sa = SuffixArray::new_naive(&reference, &alphabet);
let isa = sa.inverse();
let lcp = suffix_array::longest_common_prefix(&reference, &sa, &isa);
for i in 2..lcp.len() {
let x = &reference[sa[i - 1]..sa[i - 1] + lcp[i]];
let y = &reference[sa[i]..sa[i] + lcp[i]];
assert_eq!(x, y);
let l = lcp[i];
assert!(
sa[i] + l >= reference.len()
|| sa[i - 1] + l >= reference.len()
|| reference[sa[i] + l] != reference[sa[i - 1] + l]
)
}
}
}
#[test]
fn random_check_suffix_tree() {
for i in 0..2 {
let (reference, _queries) = dataset(SEED + i as u64, TEMPLATE_LEN, TEST_NUM, MAX_LEN);
use suffix_utils::suffix_tree::SuffixTree;
let alphabet: Vec<u8> = (0..=std::u8::MAX).collect();
let st = SuffixTree::new(&reference, &alphabet);
let mut stack = vec![];
stack.push(st.root_idx);
let mut suffix = vec![];
let mut arrived = vec![false; st.nodes.len()];
let mut input = reference.to_vec();
input.push(b'$');
'dfs: while !stack.is_empty() {
let node = *stack.last().unwrap();
if !arrived[node] {
arrived[node] = true;
}
for &(idx, _, _) in st.nodes[node].children.iter() {
if !arrived[idx] {
let position = st.nodes[idx].position_at_text;
let length = st.nodes[idx].label_length_to_parent;
suffix.extend(input[position - length..position].iter().copied());
stack.push(idx);
continue 'dfs;
}
}
let last = stack.pop().unwrap();
if let Some(idx) = st.nodes[last].leaf_label {
assert_eq!(suffix.as_slice(), &input[idx..]);
}
for _ in 0..st.nodes[last].label_length_to_parent {
suffix.pop();
}
}
}
}
#[test]
fn random_check_maximal_repeat() {
for i in 0..2 {
let (reference, _queries) = dataset(SEED + i as u64, TEMPLATE_LEN, TEST_NUM, MAX_LEN);
use suffix_utils::suffix_tree::SuffixTree;
let alphabet: Vec<u8> = (0..=std::u8::MAX).collect();
let st = SuffixTree::new(&reference, &alphabet);
for (starts, len) in st.maximul_repeat(&reference) {
// Check repetitiveness.
let subseq = &reference[starts[0]..starts[0] + len];
assert!(starts.iter().all(|&s| &reference[s..s + len] == subseq));
use std::collections::HashSet;
// Check left-maximality.
if starts.iter().all(|&s| s != 0) {
let starts: HashSet<_> = starts.iter().map(|&s| reference[s - 1]).collect();
assert!(starts.len() > 1);
}
// Check right-maximality.
if starts.iter().all(|&s| s + len < reference.len()) {
let ends: HashSet<_> = starts.iter().map(|&s| reference[s + len]).collect();
assert!(ends.len() > 1);
}
}
}
}
#[test]
fn random_check_bv() {
let mut rng: Xoroshiro128StarStar = SeedableRng::seed_from_u64(12908320);
for _ in 0..2 {
let bitvec: Vec<_> = (0..100000).map(|_| rng.gen()).collect();
let bv = suffix_utils::bitvector::BitVec::new(&bitvec);
for (idx, &b) in bitvec.iter().enumerate() {
assert_eq!(bv.get(idx), b);
}
// Rank check
for idx in 0..bitvec.len() {
// True query.
let rank = bitvec[..idx].iter().filter(|&&b| b).count();
let rank_bv = bv.rank(true, idx);
assert_eq!(rank, rank_bv, "{}\t{}\t{}", idx, rank, rank_bv);
// False query
let rank = bitvec[..idx].iter().filter(|&&b| !b).count();
let rank_bv = bv.rank(false, idx);
assert_eq!(rank, rank_bv, "{}\t{}\t{}", idx, rank, rank_bv);
}
// Check select query.
let number_of_true = bitvec.iter().filter(|&&b| b).count();
let number_of_false = bitvec.len() - number_of_true;
for i in 1..number_of_true {
let mut acc = 0;
let mut pos = 0;
while acc < i {
acc += bitvec[pos] as usize;
pos += 1;
}
let pos_bv = bv.select(true, i);
assert_eq!(pos_bv, pos - 1, "{}\t{}\t{}", i, pos_bv, pos - 1);
}
for i in 1..number_of_false {
let mut acc = 0;
let mut pos = 0;
while acc < i {
acc += !bitvec[pos] as usize;
pos += 1;
}
let pos_bv = bv.select(false, i);
assert_eq!(pos_bv, pos - 1, "{}\t{}\t{}", i, pos_bv, pos - 1);
}
}
}
|
pub mod heap;
pub mod vm;
|
#![cfg_attr(feature = "unstable", feature(test))]
// Launch program : cargo run --release < input/input.txt
// Launch benchmark : cargo +nightly bench --features "unstable"
/*
Benchmark results:
running 5 tests
test tests::test_part_1 ... ignored
test tests::test_part_2 ... ignored
test bench::bench_parse_input ... bench: 55,493 ns/iter (+/- 3,820)
test bench::bench_part_1 ... bench: 60,718 ns/iter (+/- 3,898)
test bench::bench_part_2 ... bench: 189,749 ns/iter (+/- 17,608)
*/
use std::error::Error;
use std::io::{self, Read, Write};
type Result<T> = ::std::result::Result<T, Box<dyn Error>>;
macro_rules! err {
($($tt:tt)*) => { return Err(Box::<dyn Error>::from(format!($($tt)*))) }
}
fn main() -> Result<()> {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
let numbers = parse_input(&input)?;
let preamble = 25;
writeln!(io::stdout(), "Part 1 : {}", part_1(&numbers, preamble)?)?;
writeln!(io::stdout(), "Part 2 : {}", part_2(&numbers, preamble)?)?;
Ok(())
}
fn parse_input(input: &str) -> Result<Vec<usize>> {
let mut numbers: Vec<usize> = vec![];
for line in input.lines() {
numbers.push(line.parse::<usize>()?);
}
Ok(numbers)
}
fn part_1(numbers: &[usize], preamble: usize) -> Result<usize> {
if preamble > numbers.len() {
err!("Not enough numbers for the preamble")
}
let mut current_combinations: Vec<usize> = numbers.iter().take(preamble).copied().collect();
'outer: for &number_to_find in numbers.iter().skip(preamble) {
for i in 0..(current_combinations.len() - 1) {
for j in (i + 1)..current_combinations.len() {
if current_combinations[i] == current_combinations[j] {
continue;
}
if current_combinations[i] + current_combinations[j] == number_to_find {
current_combinations.remove(0);
current_combinations.push(number_to_find);
continue 'outer;
}
}
}
return Ok(number_to_find);
}
err!("No combination in error found")
}
fn part_2(numbers: &[usize], preamble: usize) -> Result<usize> {
let number_to_find = part_1(numbers, preamble)?;
'outer: for i in 0..(numbers.len() - 1) {
let mut current_addition = numbers[i];
for j in (i + 1)..numbers.len() {
current_addition += numbers[j];
if current_addition > number_to_find {
continue 'outer;
} else if current_addition == number_to_find {
return Ok(
numbers[i..=j].iter().min().unwrap() + numbers[i..=j].iter().max().unwrap()
); // Safe unwraps here since there are always at least two numbers in the range
}
}
}
err!("No contiguous series found")
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
fn read_test_file() -> Result<String> {
let mut input = String::new();
File::open("input/test.txt")?.read_to_string(&mut input)?;
Ok(input)
}
#[test]
fn test_part_1() -> Result<()> {
let numbers = parse_input(&read_test_file()?)?;
assert_eq!(part_1(&numbers, 5)?, 127);
Ok(())
}
#[test]
fn test_part_2() -> Result<()> {
let numbers = parse_input(&read_test_file()?)?;
assert_eq!(part_2(&numbers, 5)?, 62);
Ok(())
}
}
#[cfg(all(feature = "unstable", test))]
mod bench {
extern crate test;
use super::*;
use std::fs::File;
use test::Bencher;
fn read_input_file() -> Result<String> {
let mut input = String::new();
File::open("input/input.txt")?.read_to_string(&mut input)?;
Ok(input)
}
#[bench]
fn bench_parse_input(b: &mut Bencher) -> Result<()> {
let input = read_input_file()?;
b.iter(|| test::black_box(parse_input(&input)));
Ok(())
}
#[bench]
fn bench_part_1(b: &mut Bencher) -> Result<()> {
let numbers = parse_input(&read_input_file()?)?;
b.iter(|| test::black_box(part_1(&numbers, 25)));
Ok(())
}
#[bench]
fn bench_part_2(b: &mut Bencher) -> Result<()> {
let numbers = parse_input(&read_input_file()?)?;
b.iter(|| test::black_box(part_2(&numbers, 25)));
Ok(())
}
}
|
use duktape2::prelude::*;
use super::super::super::context::{Context as CrawlContext};
use super::super::super::error::CrawlResult;
use vfs::physical::PhysicalFS;
use conveyor_work::{package::Package};
use super::super::super::work::WorkOutput;
use conveyor::{Result, ConveyorError};
pub(crate) static REQUIRE_JS: &'static str = include_str!("./runtime.js");
pub struct VM {
inner: Context,
ctx: CrawlContext,
pub(crate) script: String,
}
impl VM {
pub fn new<S: AsRef<str>>(mut ctx: CrawlContext, path:S) -> VM {
let duk = Context::new().unwrap();
Require::new()
.env(Environment::from_env().unwrap())
.resolver(
"file",
file_resolver(
PhysicalFS::new("/").unwrap(),
ctx.root().target().env().cwd().to_str().expect("invalid path"),
),
)
.build(&duk)
.expect("require");
{
let requirejs: Function = duk
.push_string(REQUIRE_JS)
.push_string("runtime.js")
.compile(Compile::EVAL).unwrap()
.call(0).unwrap()
.getp().unwrap();
requirejs.call::<_, Function>(duk.push_global_object().getp::<Object>().unwrap()).unwrap();
}
duk.require(path.as_ref()).expect("invalid script");
VM{
inner:duk,
ctx,
script: path.as_ref().to_string(),
}
}
pub fn ctx(&self) -> &CrawlContext {
&self.ctx
}
pub fn run(&self, package:(String, Vec<u8>)) -> Result<Vec<WorkOutput<Package>>> {
let module = self.inner.require(&self.script).unwrap().push();
let function: Function = self.inner.getp().unwrap();
let p_ctor = self.inner.get_global_string("Package").getp::<Function>().unwrap();
let p = p_ctor.construct::<_, Object>((&package.0, package.1.as_slice())).unwrap();
let re = function.call::<_, Array>(p).unwrap();
let pack = parse(&re).unwrap();
// let pack = match deserialize_reference(&re) {
// Err(e) => unimplemented!("could not do"),
// Ok(s) => match s {
// ValueOrBytes::Bytes(bs) => Package::new(package.0, bs),
// ValueOrBytes::Value(v) => {
// println!("{}", serde_json::to_string_pretty(&v).unwrap());
// Package::new(package.0, v)
// },
// }
// };
Ok(pack)
// return Ok(vec![WorkOutput::Result(Ok(pack))])
}
}
fn parse(array: &Array) -> DukResult<Vec<WorkOutput<Package>>> {
let iter = array.iter();
for entry in iter {
let o: Object = entry.to()?;
let w = match o.get::<_, &str>("type")? {
"ok" => {
WorkOutput::Result(Ok(parse_package(&o.get::<_,Object>("package")?)?))
},
"then" => {
WorkOutput::Then(parse_package(&o.get::<_,Object>("package")?)?)
},
"err" => {
unimplemented!("Error {}", o)
}
_ => {
unimplemented!("Error")
}
};
}
Ok(Vec::new())
}
fn parse_package(package: &Object) -> DukResult<Package> {
let name: &str = package.get("name")?;
let content: Reference = package.get("content")?;
let pack = match content.get_type() {
Type::String => Package::new(name, content.to::<&str>()?),
Type::Buffer => Package::new(name, content.to::<&[u8]>()?),
_ => return Err(DukError::new(DukErrorCode::Type, format!("invalid package content type: {:?}", content.get_type()))),
};
Ok(pack)
}
use serde_json::{Value,Number, Map};
#[derive(Debug)]
enum ValueOrBytes {
Value(Value),
Bytes(Vec<u8>),
}
fn decode(ctx: &Context, idx:Idx) -> DukResult<ValueOrBytes> {
let re: Reference = ctx.get(idx)?;
deserialize_reference(&re)
}
fn deserialize_reference2(value: &Reference) -> DukResult<Value> {
let val = match value.get_type() {
Type::Array => {
let re = value.to()?;
deserialize_array(&re)?
},
Type::String => Value::String(value.to()?),
Type::Null | Type::Undefined => Value::Null,
Type::Boolean => Value::Bool(value.to()?),
Type::Number => Value::Number(Number::from_f64(value.to()?).unwrap()),
Type::Object => {
let o:Object = value.to()?;
let iter = o.iter();
let mut out = Map::new();
for e in iter {
out.insert(e.0.to_string(), deserialize_reference2(&e.1)?);
}
Value::Object(out)
}
_ => {
unimplemented!("reference {:?}", value.get_type());
}
};
Ok(val)
}
fn deserialize_reference(value: &Reference) -> DukResult<ValueOrBytes> {
let val = match value.get_type() {
Type::Array => {
let re = value.to()?;
deserialize_array(&re)?
},
Type::String => Value::String(value.to()?),
Type::Null | Type::Undefined => Value::Null,
Type::Boolean => Value::Bool(value.to()?),
Type::Number => Value::Number(Number::from_f64(value.to()?).unwrap()),
Type::Buffer => {
let bs = value.to()?;
return Ok(ValueOrBytes::Bytes(bs));
}
Type::Object => {
let o:Object = value.to()?;
let iter = o.iter();
let mut out = Map::new();
for e in iter {
out.insert(e.0.to_string(), deserialize_reference2(&e.1)?);
}
Value::Object(out)
}
_ => {
unimplemented!("reference {:?}", value.get_type());
}
};
Ok(ValueOrBytes::Value(val))
}
fn deserialize_array(array: &Array) -> DukResult<Value> {
let mut out = Vec::with_capacity(array.len());
for item in array.iter() {
out.push(match deserialize_reference(&item)? {
ValueOrBytes::Value(v) => v,
ValueOrBytes::Bytes(b) => return Err(DukError::new(DukErrorCode::Type, "could not be bytes"))
});
}
Ok(Value::Array(out))
} |
#[doc = "Register `CR2` reader"]
pub type R = crate::R<CR2_SPEC>;
#[doc = "Register `CR2` writer"]
pub type W = crate::W<CR2_SPEC>;
#[doc = "Field `TAMP1NOER` reader - TAMP1NOER"]
pub type TAMP1NOER_R = crate::BitReader<TAMP1NOER_A>;
#[doc = "TAMP1NOER\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TAMP1NOER_A {
#[doc = "0: Tamper x event erases the backup registers"]
Erase = 0,
#[doc = "1: Tamper x event does not erase the backup registers"]
NotErase = 1,
}
impl From<TAMP1NOER_A> for bool {
#[inline(always)]
fn from(variant: TAMP1NOER_A) -> Self {
variant as u8 != 0
}
}
impl TAMP1NOER_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TAMP1NOER_A {
match self.bits {
false => TAMP1NOER_A::Erase,
true => TAMP1NOER_A::NotErase,
}
}
#[doc = "Tamper x event erases the backup registers"]
#[inline(always)]
pub fn is_erase(&self) -> bool {
*self == TAMP1NOER_A::Erase
}
#[doc = "Tamper x event does not erase the backup registers"]
#[inline(always)]
pub fn is_not_erase(&self) -> bool {
*self == TAMP1NOER_A::NotErase
}
}
#[doc = "Field `TAMP1NOER` writer - TAMP1NOER"]
pub type TAMP1NOER_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TAMP1NOER_A>;
impl<'a, REG, const O: u8> TAMP1NOER_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Tamper x event erases the backup registers"]
#[inline(always)]
pub fn erase(self) -> &'a mut crate::W<REG> {
self.variant(TAMP1NOER_A::Erase)
}
#[doc = "Tamper x event does not erase the backup registers"]
#[inline(always)]
pub fn not_erase(self) -> &'a mut crate::W<REG> {
self.variant(TAMP1NOER_A::NotErase)
}
}
#[doc = "Field `TAMP2NOER` reader - TAMP2NOER"]
pub use TAMP1NOER_R as TAMP2NOER_R;
#[doc = "Field `TAMP3NOER` reader - TAMP3NOER"]
pub use TAMP1NOER_R as TAMP3NOER_R;
#[doc = "Field `TAMP2NOER` writer - TAMP2NOER"]
pub use TAMP1NOER_W as TAMP2NOER_W;
#[doc = "Field `TAMP3NOER` writer - TAMP3NOER"]
pub use TAMP1NOER_W as TAMP3NOER_W;
#[doc = "Field `TAMP1MSK` reader - TAMP1MSK"]
pub type TAMP1MSK_R = crate::BitReader<TAMP1MSK_A>;
#[doc = "TAMP1MSK\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TAMP1MSK_A {
#[doc = "0: Tamper x event generates a trigger event and TAMPxF must be cleared by software to allow next tamper event detection"]
ResetBySoftware = 0,
#[doc = "1: Tamper x event generates a trigger event. TAMPxF is masked and internally cleared by hardware. The backup registers are not erased. The tamper x interrupt must not be enabled when TAMP3MSK is set"]
ResetByHardware = 1,
}
impl From<TAMP1MSK_A> for bool {
#[inline(always)]
fn from(variant: TAMP1MSK_A) -> Self {
variant as u8 != 0
}
}
impl TAMP1MSK_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TAMP1MSK_A {
match self.bits {
false => TAMP1MSK_A::ResetBySoftware,
true => TAMP1MSK_A::ResetByHardware,
}
}
#[doc = "Tamper x event generates a trigger event and TAMPxF must be cleared by software to allow next tamper event detection"]
#[inline(always)]
pub fn is_reset_by_software(&self) -> bool {
*self == TAMP1MSK_A::ResetBySoftware
}
#[doc = "Tamper x event generates a trigger event. TAMPxF is masked and internally cleared by hardware. The backup registers are not erased. The tamper x interrupt must not be enabled when TAMP3MSK is set"]
#[inline(always)]
pub fn is_reset_by_hardware(&self) -> bool {
*self == TAMP1MSK_A::ResetByHardware
}
}
#[doc = "Field `TAMP1MSK` writer - TAMP1MSK"]
pub type TAMP1MSK_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TAMP1MSK_A>;
impl<'a, REG, const O: u8> TAMP1MSK_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Tamper x event generates a trigger event and TAMPxF must be cleared by software to allow next tamper event detection"]
#[inline(always)]
pub fn reset_by_software(self) -> &'a mut crate::W<REG> {
self.variant(TAMP1MSK_A::ResetBySoftware)
}
#[doc = "Tamper x event generates a trigger event. TAMPxF is masked and internally cleared by hardware. The backup registers are not erased. The tamper x interrupt must not be enabled when TAMP3MSK is set"]
#[inline(always)]
pub fn reset_by_hardware(self) -> &'a mut crate::W<REG> {
self.variant(TAMP1MSK_A::ResetByHardware)
}
}
#[doc = "Field `TAMP2MSK` reader - TAMP2MSK"]
pub use TAMP1MSK_R as TAMP2MSK_R;
#[doc = "Field `TAMP3MSK` reader - TAMP3MSK"]
pub use TAMP1MSK_R as TAMP3MSK_R;
#[doc = "Field `TAMP2MSK` writer - TAMP2MSK"]
pub use TAMP1MSK_W as TAMP2MSK_W;
#[doc = "Field `TAMP3MSK` writer - TAMP3MSK"]
pub use TAMP1MSK_W as TAMP3MSK_W;
#[doc = "Field `BKERASE` reader - Backup registerserase"]
pub type BKERASE_R = crate::BitReader<BKERASEW_A>;
#[doc = "Backup registerserase\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BKERASEW_A {
#[doc = "1: Reset backup registers"]
Reset = 1,
}
impl From<BKERASEW_A> for bool {
#[inline(always)]
fn from(variant: BKERASEW_A) -> Self {
variant as u8 != 0
}
}
impl BKERASE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<BKERASEW_A> {
match self.bits {
true => Some(BKERASEW_A::Reset),
_ => None,
}
}
#[doc = "Reset backup registers"]
#[inline(always)]
pub fn is_reset(&self) -> bool {
*self == BKERASEW_A::Reset
}
}
#[doc = "Field `BKERASE` writer - Backup registerserase"]
pub type BKERASE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, BKERASEW_A>;
impl<'a, REG, const O: u8> BKERASE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Reset backup registers"]
#[inline(always)]
pub fn reset(self) -> &'a mut crate::W<REG> {
self.variant(BKERASEW_A::Reset)
}
}
#[doc = "Field `TAMP1TRG` reader - TAMP1TRG"]
pub type TAMP1TRG_R = crate::BitReader<TAMP1TRG_A>;
#[doc = "TAMP1TRG\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TAMP1TRG_A {
#[doc = "0: If TAMPFLT != 00 Tamper x input staying low triggers a tamper detection event. If TAMPFLT = 00 Tamper x input rising edge and high level triggers a tamper detection event"]
FilteredLowOrUnfilteredHigh = 0,
#[doc = "1: If TAMPFLT != 00 Tamper x input staying high triggers a tamper detection event. If TAMPFLT = 00 Tamper x input falling edge and low level triggers a tamper detection event"]
FilteredHighOrUnfilteredLow = 1,
}
impl From<TAMP1TRG_A> for bool {
#[inline(always)]
fn from(variant: TAMP1TRG_A) -> Self {
variant as u8 != 0
}
}
impl TAMP1TRG_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TAMP1TRG_A {
match self.bits {
false => TAMP1TRG_A::FilteredLowOrUnfilteredHigh,
true => TAMP1TRG_A::FilteredHighOrUnfilteredLow,
}
}
#[doc = "If TAMPFLT != 00 Tamper x input staying low triggers a tamper detection event. If TAMPFLT = 00 Tamper x input rising edge and high level triggers a tamper detection event"]
#[inline(always)]
pub fn is_filtered_low_or_unfiltered_high(&self) -> bool {
*self == TAMP1TRG_A::FilteredLowOrUnfilteredHigh
}
#[doc = "If TAMPFLT != 00 Tamper x input staying high triggers a tamper detection event. If TAMPFLT = 00 Tamper x input falling edge and low level triggers a tamper detection event"]
#[inline(always)]
pub fn is_filtered_high_or_unfiltered_low(&self) -> bool {
*self == TAMP1TRG_A::FilteredHighOrUnfilteredLow
}
}
#[doc = "Field `TAMP1TRG` writer - TAMP1TRG"]
pub type TAMP1TRG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TAMP1TRG_A>;
impl<'a, REG, const O: u8> TAMP1TRG_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "If TAMPFLT != 00 Tamper x input staying low triggers a tamper detection event. If TAMPFLT = 00 Tamper x input rising edge and high level triggers a tamper detection event"]
#[inline(always)]
pub fn filtered_low_or_unfiltered_high(self) -> &'a mut crate::W<REG> {
self.variant(TAMP1TRG_A::FilteredLowOrUnfilteredHigh)
}
#[doc = "If TAMPFLT != 00 Tamper x input staying high triggers a tamper detection event. If TAMPFLT = 00 Tamper x input falling edge and low level triggers a tamper detection event"]
#[inline(always)]
pub fn filtered_high_or_unfiltered_low(self) -> &'a mut crate::W<REG> {
self.variant(TAMP1TRG_A::FilteredHighOrUnfilteredLow)
}
}
#[doc = "Field `TAMP2TRG` reader - TAMP2TRG"]
pub use TAMP1TRG_R as TAMP2TRG_R;
#[doc = "Field `TAMP3TRG` reader - TAMP3TRG"]
pub use TAMP1TRG_R as TAMP3TRG_R;
#[doc = "Field `TAMP2TRG` writer - TAMP2TRG"]
pub use TAMP1TRG_W as TAMP2TRG_W;
#[doc = "Field `TAMP3TRG` writer - TAMP3TRG"]
pub use TAMP1TRG_W as TAMP3TRG_W;
impl R {
#[doc = "Bit 0 - TAMP1NOER"]
#[inline(always)]
pub fn tamp1noer(&self) -> TAMP1NOER_R {
TAMP1NOER_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - TAMP2NOER"]
#[inline(always)]
pub fn tamp2noer(&self) -> TAMP2NOER_R {
TAMP2NOER_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - TAMP3NOER"]
#[inline(always)]
pub fn tamp3noer(&self) -> TAMP3NOER_R {
TAMP3NOER_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 16 - TAMP1MSK"]
#[inline(always)]
pub fn tamp1msk(&self) -> TAMP1MSK_R {
TAMP1MSK_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - TAMP2MSK"]
#[inline(always)]
pub fn tamp2msk(&self) -> TAMP2MSK_R {
TAMP2MSK_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - TAMP3MSK"]
#[inline(always)]
pub fn tamp3msk(&self) -> TAMP3MSK_R {
TAMP3MSK_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 23 - Backup registerserase"]
#[inline(always)]
pub fn bkerase(&self) -> BKERASE_R {
BKERASE_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - TAMP1TRG"]
#[inline(always)]
pub fn tamp1trg(&self) -> TAMP1TRG_R {
TAMP1TRG_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - TAMP2TRG"]
#[inline(always)]
pub fn tamp2trg(&self) -> TAMP2TRG_R {
TAMP2TRG_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 26 - TAMP3TRG"]
#[inline(always)]
pub fn tamp3trg(&self) -> TAMP3TRG_R {
TAMP3TRG_R::new(((self.bits >> 26) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - TAMP1NOER"]
#[inline(always)]
#[must_use]
pub fn tamp1noer(&mut self) -> TAMP1NOER_W<CR2_SPEC, 0> {
TAMP1NOER_W::new(self)
}
#[doc = "Bit 1 - TAMP2NOER"]
#[inline(always)]
#[must_use]
pub fn tamp2noer(&mut self) -> TAMP2NOER_W<CR2_SPEC, 1> {
TAMP2NOER_W::new(self)
}
#[doc = "Bit 2 - TAMP3NOER"]
#[inline(always)]
#[must_use]
pub fn tamp3noer(&mut self) -> TAMP3NOER_W<CR2_SPEC, 2> {
TAMP3NOER_W::new(self)
}
#[doc = "Bit 16 - TAMP1MSK"]
#[inline(always)]
#[must_use]
pub fn tamp1msk(&mut self) -> TAMP1MSK_W<CR2_SPEC, 16> {
TAMP1MSK_W::new(self)
}
#[doc = "Bit 17 - TAMP2MSK"]
#[inline(always)]
#[must_use]
pub fn tamp2msk(&mut self) -> TAMP2MSK_W<CR2_SPEC, 17> {
TAMP2MSK_W::new(self)
}
#[doc = "Bit 18 - TAMP3MSK"]
#[inline(always)]
#[must_use]
pub fn tamp3msk(&mut self) -> TAMP3MSK_W<CR2_SPEC, 18> {
TAMP3MSK_W::new(self)
}
#[doc = "Bit 23 - Backup registerserase"]
#[inline(always)]
#[must_use]
pub fn bkerase(&mut self) -> BKERASE_W<CR2_SPEC, 23> {
BKERASE_W::new(self)
}
#[doc = "Bit 24 - TAMP1TRG"]
#[inline(always)]
#[must_use]
pub fn tamp1trg(&mut self) -> TAMP1TRG_W<CR2_SPEC, 24> {
TAMP1TRG_W::new(self)
}
#[doc = "Bit 25 - TAMP2TRG"]
#[inline(always)]
#[must_use]
pub fn tamp2trg(&mut self) -> TAMP2TRG_W<CR2_SPEC, 25> {
TAMP2TRG_W::new(self)
}
#[doc = "Bit 26 - TAMP3TRG"]
#[inline(always)]
#[must_use]
pub fn tamp3trg(&mut self) -> TAMP3TRG_W<CR2_SPEC, 26> {
TAMP3TRG_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 = "control register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr2::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 [`cr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CR2_SPEC;
impl crate::RegisterSpec for CR2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`cr2::R`](R) reader structure"]
impl crate::Readable for CR2_SPEC {}
#[doc = "`write(|w| ..)` method takes [`cr2::W`](W) writer structure"]
impl crate::Writable for CR2_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CR2 to value 0"]
impl crate::Resettable for CR2_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
extern crate pest;
#[macro_use]
extern crate pest_derive;
mod binary_tree;
mod binary_tree_2;
mod chapter_1;
mod chapter_2_1;
mod chapter_2_2;
mod chapter_2_3;
mod cons;
mod languages;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
|
use rocket::{get, routes};
use rocket::http::Status;
use rocket::request::{self, FromRequest, Request, State};
use rocket_contrib::json::Json;
use serde::{Serialize, Deserialize};
use mongodb::bson::{doc};
use std::error::Error;
use crate::{db::DB};
use rocket::response::status::BadRequest;
#[derive(Serialize, Deserialize, Debug)]
pub struct Movie {
pub title: String,
pub year: String,
pub plot: String,
}
#[get("/<movie_title>")]
pub fn get_data(movie_title: String) -> Result<Json<Option<Movie>>, BadRequest<mongodb::error::Error>> {
let db = DB::init().map_err(|e| BadRequest(Some(e)))?;
let client = db.client;
// Get the 'movies' collection from the 'sample_mflix' database:
let movies = client.database("rust_mongo").collection_with_type::<Movie>("movies");
let movie = movies
.find_one(
doc! {
"title": movie_title
},
None,
)
.expect("Missing 'Parasite' document.");
format!("Movie: {:?}", movie);
Ok(Json(movie))
}
|
use std::collections::HashMap;
macro_rules! impl_json_value {
({ $($name:tt($for_type:ty)),* $(,)? }) => {
#[derive(Debug)]
pub enum JsonValue {
$($name($for_type),)*
}
$(impl From<$for_type> for JsonValue {
fn from(value: $for_type) -> Self {
Self::$name(value)
}
})*
};
}
pub type Json = HashMap<String, JsonValue>;
impl_json_value!({
String(String),
ISize(isize),
I8(i8),
I16(i16),
I32(i32),
I64(i64),
I128(i128),
F32(f32),
F64(f64),
Bool(bool),
List(Vec<JsonValue>),
Object(Json)
});
#[macro_export]
macro_rules! json {
({ $($key:tt:$value:tt),* $(,)?}) => {{
let mut map = crate::json::Json::new();
$(
map.insert(
$key.to_string(),
crate::json::JsonValue::from(json!($value))
);
)*
map
}};
([ $($item:expr),* ]) => ({
let mut vec = Vec::new();
$(
vec.push(crate::json::JsonValue::from($item));
)*
vec
});
($value:expr) => { $value }
}
|
use serde_json::Value;
use std::{collections::HashMap, time::Duration};
pub const GUARDIAN_DELAY: Duration = Duration::from_millis(100);
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SectionsRoot {
pub response: SectionsResponse,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SectionsResponse {
pub status: String,
pub user_tier: String,
pub total: i64,
pub results: Vec<SectionsResult>,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SectionsResult {
pub id: String,
pub web_title: String,
pub web_url: String,
pub api_url: String,
#[serde(flatten)]
extra: HashMap<String, Value>,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ArticleRoot {
pub response: ArticleResponse,
}
impl crate::HasRecs for ArticleRoot {
fn to_recs(&self) -> Vec<Vec<String>> {
self.response.results.iter().map(|x| x.to_rec()).collect()
}
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ArticleResponse {
pub results: Vec<ArticleResult>,
#[serde(flatten)]
extra: HashMap<String, Value>,
}
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ArticleResult {
pub id: String,
#[serde(rename = "type")]
pub type_field: String,
pub section_id: String,
pub section_name: String,
pub web_publication_date: String,
pub web_title: String,
pub web_url: String,
pub api_url: String,
pub is_hosted: bool,
pub pillar_id: Option<String>,
pub pillar_name: Option<String>,
}
impl ArticleResult {
pub fn to_rec(&self) -> Vec<String> {
return vec![
self.id.to_string(),
self.type_field.to_string(),
self.section_id.to_string(),
self.section_name.to_string(),
self.web_publication_date.to_string(),
self.web_title.to_string(),
self.api_url.to_string(),
self.is_hosted.to_string(),
self.pillar_id.clone().unwrap_or("".to_string()),
];
}
}
|
use crate::rectangle;
use amethyst::{
assets::PrefabData,
core::{math, Transform},
derive::PrefabData,
ecs::{Component, DenseVecStorage, Entity, WriteStorage},
Error,
};
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Copy, Clone, Serialize, PrefabData)]
#[prefab(Component)]
pub struct CollisionBox {
/// Distance from the center to the upper left.
/// Note: probably negative.
pub upper_left_distance: math::Vector2<f32>,
/// Distance from the center to the lower right.
pub lower_right_distance: math::Vector2<f32>,
}
impl CollisionBox {
pub fn rectangle(&self, transform: &Transform) -> math::Vector4<f32> {
let translation = transform.translation().xy();
math::Vector4::new(
translation.x + self.upper_left_distance.x,
translation.y + self.upper_left_distance.y,
translation.x + self.lower_right_distance.x,
translation.y + self.lower_right_distance.y,
)
}
}
impl Component for CollisionBox {
type Storage = DenseVecStorage<Self>;
}
impl rectangle::Rectangle<f32> for CollisionBox {
fn upper_left(&self) -> math::Vector2<f32> {
self.upper_left_distance
}
fn lower_right(&self) -> math::Vector2<f32> {
self.lower_right_distance
}
fn center(&self) -> math::Vector2<f32> {
(self.upper_left_distance + self.lower_right_distance) / 2.0
}
}
pub fn are_colliding(
collision1: &CollisionBox,
transform1: &Transform,
collision2: &CollisionBox,
transform2: &Transform,
) -> bool {
rectangle::overlap(
collision1.rectangle(transform1),
collision2.rectangle(transform2),
)
}
|
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum Error {
CodeSigningConfigNotFoundError(crate::error::CodeSigningConfigNotFoundError),
CodeStorageExceededError(crate::error::CodeStorageExceededError),
CodeVerificationFailedError(crate::error::CodeVerificationFailedError),
EC2AccessDeniedError(crate::error::EC2AccessDeniedError),
EC2ThrottledError(crate::error::EC2ThrottledError),
EC2UnexpectedError(crate::error::EC2UnexpectedError),
EFSIOError(crate::error::EFSIOError),
EFSMountConnectivityError(crate::error::EFSMountConnectivityError),
EFSMountFailureError(crate::error::EFSMountFailureError),
EFSMountTimeoutError(crate::error::EFSMountTimeoutError),
ENILimitReachedError(crate::error::ENILimitReachedError),
InvalidCodeSignatureError(crate::error::InvalidCodeSignatureError),
InvalidParameterValueError(crate::error::InvalidParameterValueError),
InvalidRequestContentError(crate::error::InvalidRequestContentError),
InvalidRuntimeError(crate::error::InvalidRuntimeError),
InvalidSecurityGroupIDError(crate::error::InvalidSecurityGroupIDError),
InvalidSubnetIDError(crate::error::InvalidSubnetIDError),
InvalidZipFileError(crate::error::InvalidZipFileError),
KMSAccessDeniedError(crate::error::KMSAccessDeniedError),
KMSDisabledError(crate::error::KMSDisabledError),
KMSInvalidStateError(crate::error::KMSInvalidStateError),
KMSNotFoundError(crate::error::KMSNotFoundError),
PolicyLengthExceededError(crate::error::PolicyLengthExceededError),
PreconditionFailedError(crate::error::PreconditionFailedError),
ProvisionedConcurrencyConfigNotFoundError(
crate::error::ProvisionedConcurrencyConfigNotFoundError,
),
RequestTooLargeError(crate::error::RequestTooLargeError),
ResourceConflictError(crate::error::ResourceConflictError),
ResourceInUseError(crate::error::ResourceInUseError),
ResourceNotFoundError(crate::error::ResourceNotFoundError),
ResourceNotReadyError(crate::error::ResourceNotReadyError),
ServiceError(crate::error::ServiceError),
SubnetIPAddressLimitReachedError(crate::error::SubnetIPAddressLimitReachedError),
TooManyRequestsError(crate::error::TooManyRequestsError),
UnsupportedMediaTypeError(crate::error::UnsupportedMediaTypeError),
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::CodeSigningConfigNotFoundError(inner) => inner.fmt(f),
Error::CodeStorageExceededError(inner) => inner.fmt(f),
Error::CodeVerificationFailedError(inner) => inner.fmt(f),
Error::EC2AccessDeniedError(inner) => inner.fmt(f),
Error::EC2ThrottledError(inner) => inner.fmt(f),
Error::EC2UnexpectedError(inner) => inner.fmt(f),
Error::EFSIOError(inner) => inner.fmt(f),
Error::EFSMountConnectivityError(inner) => inner.fmt(f),
Error::EFSMountFailureError(inner) => inner.fmt(f),
Error::EFSMountTimeoutError(inner) => inner.fmt(f),
Error::ENILimitReachedError(inner) => inner.fmt(f),
Error::InvalidCodeSignatureError(inner) => inner.fmt(f),
Error::InvalidParameterValueError(inner) => inner.fmt(f),
Error::InvalidRequestContentError(inner) => inner.fmt(f),
Error::InvalidRuntimeError(inner) => inner.fmt(f),
Error::InvalidSecurityGroupIDError(inner) => inner.fmt(f),
Error::InvalidSubnetIDError(inner) => inner.fmt(f),
Error::InvalidZipFileError(inner) => inner.fmt(f),
Error::KMSAccessDeniedError(inner) => inner.fmt(f),
Error::KMSDisabledError(inner) => inner.fmt(f),
Error::KMSInvalidStateError(inner) => inner.fmt(f),
Error::KMSNotFoundError(inner) => inner.fmt(f),
Error::PolicyLengthExceededError(inner) => inner.fmt(f),
Error::PreconditionFailedError(inner) => inner.fmt(f),
Error::ProvisionedConcurrencyConfigNotFoundError(inner) => inner.fmt(f),
Error::RequestTooLargeError(inner) => inner.fmt(f),
Error::ResourceConflictError(inner) => inner.fmt(f),
Error::ResourceInUseError(inner) => inner.fmt(f),
Error::ResourceNotFoundError(inner) => inner.fmt(f),
Error::ResourceNotReadyError(inner) => inner.fmt(f),
Error::ServiceError(inner) => inner.fmt(f),
Error::SubnetIPAddressLimitReachedError(inner) => inner.fmt(f),
Error::TooManyRequestsError(inner) => inner.fmt(f),
Error::UnsupportedMediaTypeError(inner) => inner.fmt(f),
Error::Unhandled(inner) => inner.fmt(f),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::AddLayerVersionPermissionError>> for Error {
fn from(
err: smithy_http::result::SdkError<crate::error::AddLayerVersionPermissionError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::AddLayerVersionPermissionErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::AddLayerVersionPermissionErrorKind::PolicyLengthExceededError(
inner,
) => Error::PolicyLengthExceededError(inner),
crate::error::AddLayerVersionPermissionErrorKind::PreconditionFailedError(
inner,
) => Error::PreconditionFailedError(inner),
crate::error::AddLayerVersionPermissionErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::AddLayerVersionPermissionErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::AddLayerVersionPermissionErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::AddLayerVersionPermissionErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::AddLayerVersionPermissionErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::AddPermissionError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::AddPermissionError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::AddPermissionErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::AddPermissionErrorKind::PolicyLengthExceededError(inner) => {
Error::PolicyLengthExceededError(inner)
}
crate::error::AddPermissionErrorKind::PreconditionFailedError(inner) => {
Error::PreconditionFailedError(inner)
}
crate::error::AddPermissionErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::AddPermissionErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::AddPermissionErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::AddPermissionErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::AddPermissionErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::CreateAliasError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::CreateAliasError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::CreateAliasErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::CreateAliasErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::CreateAliasErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::CreateAliasErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::CreateAliasErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::CreateAliasErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::CreateCodeSigningConfigError>> for Error {
fn from(
err: smithy_http::result::SdkError<crate::error::CreateCodeSigningConfigError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::CreateCodeSigningConfigErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::CreateCodeSigningConfigErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::CreateCodeSigningConfigErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::CreateEventSourceMappingError>> for Error {
fn from(
err: smithy_http::result::SdkError<crate::error::CreateEventSourceMappingError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::CreateEventSourceMappingErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::CreateEventSourceMappingErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::CreateEventSourceMappingErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::CreateEventSourceMappingErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::CreateEventSourceMappingErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::CreateEventSourceMappingErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::CreateFunctionError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::CreateFunctionError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::CreateFunctionErrorKind::CodeSigningConfigNotFoundError(inner) => {
Error::CodeSigningConfigNotFoundError(inner)
}
crate::error::CreateFunctionErrorKind::CodeStorageExceededError(inner) => {
Error::CodeStorageExceededError(inner)
}
crate::error::CreateFunctionErrorKind::CodeVerificationFailedError(inner) => {
Error::CodeVerificationFailedError(inner)
}
crate::error::CreateFunctionErrorKind::InvalidCodeSignatureError(inner) => {
Error::InvalidCodeSignatureError(inner)
}
crate::error::CreateFunctionErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::CreateFunctionErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::CreateFunctionErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::CreateFunctionErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::CreateFunctionErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::CreateFunctionErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::DeleteAliasError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::DeleteAliasError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::DeleteAliasErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::DeleteAliasErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::DeleteAliasErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::DeleteAliasErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::DeleteAliasErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::DeleteCodeSigningConfigError>> for Error {
fn from(
err: smithy_http::result::SdkError<crate::error::DeleteCodeSigningConfigError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::DeleteCodeSigningConfigErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::DeleteCodeSigningConfigErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::DeleteCodeSigningConfigErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::DeleteCodeSigningConfigErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::DeleteCodeSigningConfigErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::DeleteEventSourceMappingError>> for Error {
fn from(
err: smithy_http::result::SdkError<crate::error::DeleteEventSourceMappingError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::DeleteEventSourceMappingErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::DeleteEventSourceMappingErrorKind::ResourceInUseError(inner) => {
Error::ResourceInUseError(inner)
}
crate::error::DeleteEventSourceMappingErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::DeleteEventSourceMappingErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::DeleteEventSourceMappingErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::DeleteEventSourceMappingErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::DeleteFunctionError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::DeleteFunctionError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::DeleteFunctionErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::DeleteFunctionErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::DeleteFunctionErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::DeleteFunctionErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::DeleteFunctionErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::DeleteFunctionErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::DeleteFunctionCodeSigningConfigError>>
for Error
{
fn from(
err: smithy_http::result::SdkError<crate::error::DeleteFunctionCodeSigningConfigError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind {
crate::error::DeleteFunctionCodeSigningConfigErrorKind::CodeSigningConfigNotFoundError(inner) => Error::CodeSigningConfigNotFoundError(inner),
crate::error::DeleteFunctionCodeSigningConfigErrorKind::InvalidParameterValueError(inner) => Error::InvalidParameterValueError(inner),
crate::error::DeleteFunctionCodeSigningConfigErrorKind::ResourceConflictError(inner) => Error::ResourceConflictError(inner),
crate::error::DeleteFunctionCodeSigningConfigErrorKind::ResourceNotFoundError(inner) => Error::ResourceNotFoundError(inner),
crate::error::DeleteFunctionCodeSigningConfigErrorKind::ServiceError(inner) => Error::ServiceError(inner),
crate::error::DeleteFunctionCodeSigningConfigErrorKind::TooManyRequestsError(inner) => Error::TooManyRequestsError(inner),
crate::error::DeleteFunctionCodeSigningConfigErrorKind::Unhandled(inner) => Error::Unhandled(inner),
}
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::DeleteFunctionConcurrencyError>> for Error {
fn from(
err: smithy_http::result::SdkError<crate::error::DeleteFunctionConcurrencyError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::DeleteFunctionConcurrencyErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::DeleteFunctionConcurrencyErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::DeleteFunctionConcurrencyErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::DeleteFunctionConcurrencyErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::DeleteFunctionConcurrencyErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::DeleteFunctionConcurrencyErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::DeleteFunctionEventInvokeConfigError>>
for Error
{
fn from(
err: smithy_http::result::SdkError<crate::error::DeleteFunctionEventInvokeConfigError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind {
crate::error::DeleteFunctionEventInvokeConfigErrorKind::InvalidParameterValueError(inner) => Error::InvalidParameterValueError(inner),
crate::error::DeleteFunctionEventInvokeConfigErrorKind::ResourceNotFoundError(inner) => Error::ResourceNotFoundError(inner),
crate::error::DeleteFunctionEventInvokeConfigErrorKind::ServiceError(inner) => Error::ServiceError(inner),
crate::error::DeleteFunctionEventInvokeConfigErrorKind::TooManyRequestsError(inner) => Error::TooManyRequestsError(inner),
crate::error::DeleteFunctionEventInvokeConfigErrorKind::Unhandled(inner) => Error::Unhandled(inner),
}
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::DeleteLayerVersionError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::DeleteLayerVersionError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::DeleteLayerVersionErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::DeleteLayerVersionErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::DeleteLayerVersionErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::DeleteProvisionedConcurrencyConfigError>>
for Error
{
fn from(
err: smithy_http::result::SdkError<crate::error::DeleteProvisionedConcurrencyConfigError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind {
crate::error::DeleteProvisionedConcurrencyConfigErrorKind::InvalidParameterValueError(inner) => Error::InvalidParameterValueError(inner),
crate::error::DeleteProvisionedConcurrencyConfigErrorKind::ResourceConflictError(inner) => Error::ResourceConflictError(inner),
crate::error::DeleteProvisionedConcurrencyConfigErrorKind::ResourceNotFoundError(inner) => Error::ResourceNotFoundError(inner),
crate::error::DeleteProvisionedConcurrencyConfigErrorKind::ServiceError(inner) => Error::ServiceError(inner),
crate::error::DeleteProvisionedConcurrencyConfigErrorKind::TooManyRequestsError(inner) => Error::TooManyRequestsError(inner),
crate::error::DeleteProvisionedConcurrencyConfigErrorKind::Unhandled(inner) => Error::Unhandled(inner),
}
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::GetAccountSettingsError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::GetAccountSettingsError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::GetAccountSettingsErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::GetAccountSettingsErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::GetAccountSettingsErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::GetAliasError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::GetAliasError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::GetAliasErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::GetAliasErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::GetAliasErrorKind::ServiceError(inner) => Error::ServiceError(inner),
crate::error::GetAliasErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::GetAliasErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::GetCodeSigningConfigError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::GetCodeSigningConfigError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::GetCodeSigningConfigErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::GetCodeSigningConfigErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::GetCodeSigningConfigErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::GetCodeSigningConfigErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::GetEventSourceMappingError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::GetEventSourceMappingError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::GetEventSourceMappingErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::GetEventSourceMappingErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::GetEventSourceMappingErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::GetEventSourceMappingErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::GetEventSourceMappingErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::GetFunctionError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::GetFunctionError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::GetFunctionErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::GetFunctionErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::GetFunctionErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::GetFunctionErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::GetFunctionErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::GetFunctionCodeSigningConfigError>>
for Error
{
fn from(
err: smithy_http::result::SdkError<crate::error::GetFunctionCodeSigningConfigError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::GetFunctionCodeSigningConfigErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::GetFunctionCodeSigningConfigErrorKind::ResourceNotFoundError(
inner,
) => Error::ResourceNotFoundError(inner),
crate::error::GetFunctionCodeSigningConfigErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::GetFunctionCodeSigningConfigErrorKind::TooManyRequestsError(
inner,
) => Error::TooManyRequestsError(inner),
crate::error::GetFunctionCodeSigningConfigErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::GetFunctionConcurrencyError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::GetFunctionConcurrencyError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::GetFunctionConcurrencyErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::GetFunctionConcurrencyErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::GetFunctionConcurrencyErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::GetFunctionConcurrencyErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::GetFunctionConcurrencyErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::GetFunctionConfigurationError>> for Error {
fn from(
err: smithy_http::result::SdkError<crate::error::GetFunctionConfigurationError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::GetFunctionConfigurationErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::GetFunctionConfigurationErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::GetFunctionConfigurationErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::GetFunctionConfigurationErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::GetFunctionConfigurationErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::GetFunctionEventInvokeConfigError>>
for Error
{
fn from(
err: smithy_http::result::SdkError<crate::error::GetFunctionEventInvokeConfigError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::GetFunctionEventInvokeConfigErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::GetFunctionEventInvokeConfigErrorKind::ResourceNotFoundError(
inner,
) => Error::ResourceNotFoundError(inner),
crate::error::GetFunctionEventInvokeConfigErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::GetFunctionEventInvokeConfigErrorKind::TooManyRequestsError(
inner,
) => Error::TooManyRequestsError(inner),
crate::error::GetFunctionEventInvokeConfigErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::GetLayerVersionError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::GetLayerVersionError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::GetLayerVersionErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::GetLayerVersionErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::GetLayerVersionErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::GetLayerVersionErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::GetLayerVersionErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::GetLayerVersionByArnError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::GetLayerVersionByArnError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::GetLayerVersionByArnErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::GetLayerVersionByArnErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::GetLayerVersionByArnErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::GetLayerVersionByArnErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::GetLayerVersionByArnErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::GetLayerVersionPolicyError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::GetLayerVersionPolicyError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::GetLayerVersionPolicyErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::GetLayerVersionPolicyErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::GetLayerVersionPolicyErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::GetLayerVersionPolicyErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::GetLayerVersionPolicyErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::GetPolicyError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::GetPolicyError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::GetPolicyErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::GetPolicyErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::GetPolicyErrorKind::ServiceError(inner) => Error::ServiceError(inner),
crate::error::GetPolicyErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::GetPolicyErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::GetProvisionedConcurrencyConfigError>>
for Error
{
fn from(
err: smithy_http::result::SdkError<crate::error::GetProvisionedConcurrencyConfigError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind {
crate::error::GetProvisionedConcurrencyConfigErrorKind::InvalidParameterValueError(inner) => Error::InvalidParameterValueError(inner),
crate::error::GetProvisionedConcurrencyConfigErrorKind::ProvisionedConcurrencyConfigNotFoundError(inner) => Error::ProvisionedConcurrencyConfigNotFoundError(inner),
crate::error::GetProvisionedConcurrencyConfigErrorKind::ResourceNotFoundError(inner) => Error::ResourceNotFoundError(inner),
crate::error::GetProvisionedConcurrencyConfigErrorKind::ServiceError(inner) => Error::ServiceError(inner),
crate::error::GetProvisionedConcurrencyConfigErrorKind::TooManyRequestsError(inner) => Error::TooManyRequestsError(inner),
crate::error::GetProvisionedConcurrencyConfigErrorKind::Unhandled(inner) => Error::Unhandled(inner),
}
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::InvokeError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::InvokeError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::InvokeErrorKind::EC2AccessDeniedError(inner) => {
Error::EC2AccessDeniedError(inner)
}
crate::error::InvokeErrorKind::EC2ThrottledError(inner) => {
Error::EC2ThrottledError(inner)
}
crate::error::InvokeErrorKind::EC2UnexpectedError(inner) => {
Error::EC2UnexpectedError(inner)
}
crate::error::InvokeErrorKind::EFSIOError(inner) => Error::EFSIOError(inner),
crate::error::InvokeErrorKind::EFSMountConnectivityError(inner) => {
Error::EFSMountConnectivityError(inner)
}
crate::error::InvokeErrorKind::EFSMountFailureError(inner) => {
Error::EFSMountFailureError(inner)
}
crate::error::InvokeErrorKind::EFSMountTimeoutError(inner) => {
Error::EFSMountTimeoutError(inner)
}
crate::error::InvokeErrorKind::ENILimitReachedError(inner) => {
Error::ENILimitReachedError(inner)
}
crate::error::InvokeErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::InvokeErrorKind::InvalidRequestContentError(inner) => {
Error::InvalidRequestContentError(inner)
}
crate::error::InvokeErrorKind::InvalidRuntimeError(inner) => {
Error::InvalidRuntimeError(inner)
}
crate::error::InvokeErrorKind::InvalidSecurityGroupIDError(inner) => {
Error::InvalidSecurityGroupIDError(inner)
}
crate::error::InvokeErrorKind::InvalidSubnetIDError(inner) => {
Error::InvalidSubnetIDError(inner)
}
crate::error::InvokeErrorKind::InvalidZipFileError(inner) => {
Error::InvalidZipFileError(inner)
}
crate::error::InvokeErrorKind::KMSAccessDeniedError(inner) => {
Error::KMSAccessDeniedError(inner)
}
crate::error::InvokeErrorKind::KMSDisabledError(inner) => {
Error::KMSDisabledError(inner)
}
crate::error::InvokeErrorKind::KMSInvalidStateError(inner) => {
Error::KMSInvalidStateError(inner)
}
crate::error::InvokeErrorKind::KMSNotFoundError(inner) => {
Error::KMSNotFoundError(inner)
}
crate::error::InvokeErrorKind::RequestTooLargeError(inner) => {
Error::RequestTooLargeError(inner)
}
crate::error::InvokeErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::InvokeErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::InvokeErrorKind::ResourceNotReadyError(inner) => {
Error::ResourceNotReadyError(inner)
}
crate::error::InvokeErrorKind::ServiceError(inner) => Error::ServiceError(inner),
crate::error::InvokeErrorKind::SubnetIPAddressLimitReachedError(inner) => {
Error::SubnetIPAddressLimitReachedError(inner)
}
crate::error::InvokeErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::InvokeErrorKind::UnsupportedMediaTypeError(inner) => {
Error::UnsupportedMediaTypeError(inner)
}
crate::error::InvokeErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::InvokeAsyncError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::InvokeAsyncError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::InvokeAsyncErrorKind::InvalidRequestContentError(inner) => {
Error::InvalidRequestContentError(inner)
}
crate::error::InvokeAsyncErrorKind::InvalidRuntimeError(inner) => {
Error::InvalidRuntimeError(inner)
}
crate::error::InvokeAsyncErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::InvokeAsyncErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::InvokeAsyncErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::InvokeAsyncErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::ListAliasesError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::ListAliasesError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::ListAliasesErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::ListAliasesErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::ListAliasesErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::ListAliasesErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::ListAliasesErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::ListCodeSigningConfigsError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::ListCodeSigningConfigsError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::ListCodeSigningConfigsErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::ListCodeSigningConfigsErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::ListCodeSigningConfigsErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::ListEventSourceMappingsError>> for Error {
fn from(
err: smithy_http::result::SdkError<crate::error::ListEventSourceMappingsError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::ListEventSourceMappingsErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::ListEventSourceMappingsErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::ListEventSourceMappingsErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::ListEventSourceMappingsErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::ListEventSourceMappingsErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::ListFunctionEventInvokeConfigsError>>
for Error
{
fn from(
err: smithy_http::result::SdkError<crate::error::ListFunctionEventInvokeConfigsError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind {
crate::error::ListFunctionEventInvokeConfigsErrorKind::InvalidParameterValueError(inner) => Error::InvalidParameterValueError(inner),
crate::error::ListFunctionEventInvokeConfigsErrorKind::ResourceNotFoundError(inner) => Error::ResourceNotFoundError(inner),
crate::error::ListFunctionEventInvokeConfigsErrorKind::ServiceError(inner) => Error::ServiceError(inner),
crate::error::ListFunctionEventInvokeConfigsErrorKind::TooManyRequestsError(inner) => Error::TooManyRequestsError(inner),
crate::error::ListFunctionEventInvokeConfigsErrorKind::Unhandled(inner) => Error::Unhandled(inner),
}
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::ListFunctionsError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::ListFunctionsError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::ListFunctionsErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::ListFunctionsErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::ListFunctionsErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::ListFunctionsErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::ListFunctionsByCodeSigningConfigError>>
for Error
{
fn from(
err: smithy_http::result::SdkError<crate::error::ListFunctionsByCodeSigningConfigError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind {
crate::error::ListFunctionsByCodeSigningConfigErrorKind::InvalidParameterValueError(inner) => Error::InvalidParameterValueError(inner),
crate::error::ListFunctionsByCodeSigningConfigErrorKind::ResourceNotFoundError(inner) => Error::ResourceNotFoundError(inner),
crate::error::ListFunctionsByCodeSigningConfigErrorKind::ServiceError(inner) => Error::ServiceError(inner),
crate::error::ListFunctionsByCodeSigningConfigErrorKind::Unhandled(inner) => Error::Unhandled(inner),
}
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::ListLayersError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::ListLayersError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::ListLayersErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::ListLayersErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::ListLayersErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::ListLayersErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::ListLayerVersionsError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::ListLayerVersionsError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::ListLayerVersionsErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::ListLayerVersionsErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::ListLayerVersionsErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::ListLayerVersionsErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::ListLayerVersionsErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::ListProvisionedConcurrencyConfigsError>>
for Error
{
fn from(
err: smithy_http::result::SdkError<crate::error::ListProvisionedConcurrencyConfigsError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind {
crate::error::ListProvisionedConcurrencyConfigsErrorKind::InvalidParameterValueError(inner) => Error::InvalidParameterValueError(inner),
crate::error::ListProvisionedConcurrencyConfigsErrorKind::ResourceNotFoundError(inner) => Error::ResourceNotFoundError(inner),
crate::error::ListProvisionedConcurrencyConfigsErrorKind::ServiceError(inner) => Error::ServiceError(inner),
crate::error::ListProvisionedConcurrencyConfigsErrorKind::TooManyRequestsError(inner) => Error::TooManyRequestsError(inner),
crate::error::ListProvisionedConcurrencyConfigsErrorKind::Unhandled(inner) => Error::Unhandled(inner),
}
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::ListTagsError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::ListTagsError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::ListTagsErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::ListTagsErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::ListTagsErrorKind::ServiceError(inner) => Error::ServiceError(inner),
crate::error::ListTagsErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::ListTagsErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::ListVersionsByFunctionError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::ListVersionsByFunctionError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::ListVersionsByFunctionErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::ListVersionsByFunctionErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::ListVersionsByFunctionErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::ListVersionsByFunctionErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::ListVersionsByFunctionErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::PublishLayerVersionError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::PublishLayerVersionError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::PublishLayerVersionErrorKind::CodeStorageExceededError(inner) => {
Error::CodeStorageExceededError(inner)
}
crate::error::PublishLayerVersionErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::PublishLayerVersionErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::PublishLayerVersionErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::PublishLayerVersionErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::PublishLayerVersionErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::PublishVersionError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::PublishVersionError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::PublishVersionErrorKind::CodeStorageExceededError(inner) => {
Error::CodeStorageExceededError(inner)
}
crate::error::PublishVersionErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::PublishVersionErrorKind::PreconditionFailedError(inner) => {
Error::PreconditionFailedError(inner)
}
crate::error::PublishVersionErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::PublishVersionErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::PublishVersionErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::PublishVersionErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::PublishVersionErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::PutFunctionCodeSigningConfigError>>
for Error
{
fn from(
err: smithy_http::result::SdkError<crate::error::PutFunctionCodeSigningConfigError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind {
crate::error::PutFunctionCodeSigningConfigErrorKind::CodeSigningConfigNotFoundError(inner) => Error::CodeSigningConfigNotFoundError(inner),
crate::error::PutFunctionCodeSigningConfigErrorKind::InvalidParameterValueError(inner) => Error::InvalidParameterValueError(inner),
crate::error::PutFunctionCodeSigningConfigErrorKind::ResourceConflictError(inner) => Error::ResourceConflictError(inner),
crate::error::PutFunctionCodeSigningConfigErrorKind::ResourceNotFoundError(inner) => Error::ResourceNotFoundError(inner),
crate::error::PutFunctionCodeSigningConfigErrorKind::ServiceError(inner) => Error::ServiceError(inner),
crate::error::PutFunctionCodeSigningConfigErrorKind::TooManyRequestsError(inner) => Error::TooManyRequestsError(inner),
crate::error::PutFunctionCodeSigningConfigErrorKind::Unhandled(inner) => Error::Unhandled(inner),
}
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::PutFunctionConcurrencyError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::PutFunctionConcurrencyError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::PutFunctionConcurrencyErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::PutFunctionConcurrencyErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::PutFunctionConcurrencyErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::PutFunctionConcurrencyErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::PutFunctionConcurrencyErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::PutFunctionConcurrencyErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::PutFunctionEventInvokeConfigError>>
for Error
{
fn from(
err: smithy_http::result::SdkError<crate::error::PutFunctionEventInvokeConfigError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::PutFunctionEventInvokeConfigErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::PutFunctionEventInvokeConfigErrorKind::ResourceNotFoundError(
inner,
) => Error::ResourceNotFoundError(inner),
crate::error::PutFunctionEventInvokeConfigErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::PutFunctionEventInvokeConfigErrorKind::TooManyRequestsError(
inner,
) => Error::TooManyRequestsError(inner),
crate::error::PutFunctionEventInvokeConfigErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::PutProvisionedConcurrencyConfigError>>
for Error
{
fn from(
err: smithy_http::result::SdkError<crate::error::PutProvisionedConcurrencyConfigError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind {
crate::error::PutProvisionedConcurrencyConfigErrorKind::InvalidParameterValueError(inner) => Error::InvalidParameterValueError(inner),
crate::error::PutProvisionedConcurrencyConfigErrorKind::ResourceConflictError(inner) => Error::ResourceConflictError(inner),
crate::error::PutProvisionedConcurrencyConfigErrorKind::ResourceNotFoundError(inner) => Error::ResourceNotFoundError(inner),
crate::error::PutProvisionedConcurrencyConfigErrorKind::ServiceError(inner) => Error::ServiceError(inner),
crate::error::PutProvisionedConcurrencyConfigErrorKind::TooManyRequestsError(inner) => Error::TooManyRequestsError(inner),
crate::error::PutProvisionedConcurrencyConfigErrorKind::Unhandled(inner) => Error::Unhandled(inner),
}
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::RemoveLayerVersionPermissionError>>
for Error
{
fn from(
err: smithy_http::result::SdkError<crate::error::RemoveLayerVersionPermissionError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::RemoveLayerVersionPermissionErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::RemoveLayerVersionPermissionErrorKind::PreconditionFailedError(
inner,
) => Error::PreconditionFailedError(inner),
crate::error::RemoveLayerVersionPermissionErrorKind::ResourceNotFoundError(
inner,
) => Error::ResourceNotFoundError(inner),
crate::error::RemoveLayerVersionPermissionErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::RemoveLayerVersionPermissionErrorKind::TooManyRequestsError(
inner,
) => Error::TooManyRequestsError(inner),
crate::error::RemoveLayerVersionPermissionErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::RemovePermissionError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::RemovePermissionError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::RemovePermissionErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::RemovePermissionErrorKind::PreconditionFailedError(inner) => {
Error::PreconditionFailedError(inner)
}
crate::error::RemovePermissionErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::RemovePermissionErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::RemovePermissionErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::RemovePermissionErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::TagResourceError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::TagResourceError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::TagResourceErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::TagResourceErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::TagResourceErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::TagResourceErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::TagResourceErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::TagResourceErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::UntagResourceError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::UntagResourceError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::UntagResourceErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::UntagResourceErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::UntagResourceErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::UntagResourceErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::UntagResourceErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::UntagResourceErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::UpdateAliasError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::UpdateAliasError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::UpdateAliasErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::UpdateAliasErrorKind::PreconditionFailedError(inner) => {
Error::PreconditionFailedError(inner)
}
crate::error::UpdateAliasErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::UpdateAliasErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::UpdateAliasErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::UpdateAliasErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::UpdateAliasErrorKind::Unhandled(inner) => Error::Unhandled(inner),
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::UpdateCodeSigningConfigError>> for Error {
fn from(
err: smithy_http::result::SdkError<crate::error::UpdateCodeSigningConfigError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::UpdateCodeSigningConfigErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::UpdateCodeSigningConfigErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::UpdateCodeSigningConfigErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::UpdateCodeSigningConfigErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::UpdateEventSourceMappingError>> for Error {
fn from(
err: smithy_http::result::SdkError<crate::error::UpdateEventSourceMappingError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::UpdateEventSourceMappingErrorKind::InvalidParameterValueError(
inner,
) => Error::InvalidParameterValueError(inner),
crate::error::UpdateEventSourceMappingErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::UpdateEventSourceMappingErrorKind::ResourceInUseError(inner) => {
Error::ResourceInUseError(inner)
}
crate::error::UpdateEventSourceMappingErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::UpdateEventSourceMappingErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::UpdateEventSourceMappingErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::UpdateEventSourceMappingErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::UpdateFunctionCodeError>> for Error {
fn from(err: smithy_http::result::SdkError<crate::error::UpdateFunctionCodeError>) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind {
crate::error::UpdateFunctionCodeErrorKind::CodeSigningConfigNotFoundError(
inner,
) => Error::CodeSigningConfigNotFoundError(inner),
crate::error::UpdateFunctionCodeErrorKind::CodeStorageExceededError(inner) => {
Error::CodeStorageExceededError(inner)
}
crate::error::UpdateFunctionCodeErrorKind::CodeVerificationFailedError(inner) => {
Error::CodeVerificationFailedError(inner)
}
crate::error::UpdateFunctionCodeErrorKind::InvalidCodeSignatureError(inner) => {
Error::InvalidCodeSignatureError(inner)
}
crate::error::UpdateFunctionCodeErrorKind::InvalidParameterValueError(inner) => {
Error::InvalidParameterValueError(inner)
}
crate::error::UpdateFunctionCodeErrorKind::PreconditionFailedError(inner) => {
Error::PreconditionFailedError(inner)
}
crate::error::UpdateFunctionCodeErrorKind::ResourceConflictError(inner) => {
Error::ResourceConflictError(inner)
}
crate::error::UpdateFunctionCodeErrorKind::ResourceNotFoundError(inner) => {
Error::ResourceNotFoundError(inner)
}
crate::error::UpdateFunctionCodeErrorKind::ServiceError(inner) => {
Error::ServiceError(inner)
}
crate::error::UpdateFunctionCodeErrorKind::TooManyRequestsError(inner) => {
Error::TooManyRequestsError(inner)
}
crate::error::UpdateFunctionCodeErrorKind::Unhandled(inner) => {
Error::Unhandled(inner)
}
},
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::UpdateFunctionConfigurationError>> for Error {
fn from(
err: smithy_http::result::SdkError<crate::error::UpdateFunctionConfigurationError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind {
crate::error::UpdateFunctionConfigurationErrorKind::CodeSigningConfigNotFoundError(inner) => Error::CodeSigningConfigNotFoundError(inner),
crate::error::UpdateFunctionConfigurationErrorKind::CodeVerificationFailedError(inner) => Error::CodeVerificationFailedError(inner),
crate::error::UpdateFunctionConfigurationErrorKind::InvalidCodeSignatureError(inner) => Error::InvalidCodeSignatureError(inner),
crate::error::UpdateFunctionConfigurationErrorKind::InvalidParameterValueError(inner) => Error::InvalidParameterValueError(inner),
crate::error::UpdateFunctionConfigurationErrorKind::PreconditionFailedError(inner) => Error::PreconditionFailedError(inner),
crate::error::UpdateFunctionConfigurationErrorKind::ResourceConflictError(inner) => Error::ResourceConflictError(inner),
crate::error::UpdateFunctionConfigurationErrorKind::ResourceNotFoundError(inner) => Error::ResourceNotFoundError(inner),
crate::error::UpdateFunctionConfigurationErrorKind::ServiceError(inner) => Error::ServiceError(inner),
crate::error::UpdateFunctionConfigurationErrorKind::TooManyRequestsError(inner) => Error::TooManyRequestsError(inner),
crate::error::UpdateFunctionConfigurationErrorKind::Unhandled(inner) => Error::Unhandled(inner),
}
_ => Error::Unhandled(err.into()),
}
}
}
impl From<smithy_http::result::SdkError<crate::error::UpdateFunctionEventInvokeConfigError>>
for Error
{
fn from(
err: smithy_http::result::SdkError<crate::error::UpdateFunctionEventInvokeConfigError>,
) -> Self {
match err {
smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind {
crate::error::UpdateFunctionEventInvokeConfigErrorKind::InvalidParameterValueError(inner) => Error::InvalidParameterValueError(inner),
crate::error::UpdateFunctionEventInvokeConfigErrorKind::ResourceNotFoundError(inner) => Error::ResourceNotFoundError(inner),
crate::error::UpdateFunctionEventInvokeConfigErrorKind::ServiceError(inner) => Error::ServiceError(inner),
crate::error::UpdateFunctionEventInvokeConfigErrorKind::TooManyRequestsError(inner) => Error::TooManyRequestsError(inner),
crate::error::UpdateFunctionEventInvokeConfigErrorKind::Unhandled(inner) => Error::Unhandled(inner),
}
_ => Error::Unhandled(err.into()),
}
}
}
impl std::error::Error for Error {}
|
use std::fmt;
#[derive(Debug)]
pub struct Error {
message: String,
}
impl Error {
pub fn new(s: &str) -> Self {
Error {
message: String::from(s),
}
}
}
impl From<serde_json::Error> for Error {
fn from(error: serde_json::Error) -> Self {
let errstr = error.to_string();
Error { message: errstr }
}
}
impl From<clap::Error> for Error {
fn from(error: clap::Error) -> Self {
let errstr = error.to_string();
Error { message: errstr }
}
}
impl From<rtnetlink::Error> for Error {
fn from(error: rtnetlink::Error) -> Self {
let errstr = error.to_string();
Error { message: errstr }
}
}
impl From<std::num::ParseIntError> for Error {
fn from(error: std::num::ParseIntError) -> Self {
let errstr = error.to_string();
Error { message: errstr }
}
}
impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Self {
let errstr = error.to_string();
Error { message: errstr }
}
}
impl From<tinytemplate::error::Error> for Error {
fn from(error: tinytemplate::error::Error) -> Self {
let errstr = error.to_string();
Error { message: errstr }
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(self)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.message)
}
}
|
use rand::Rng;
use crate::entity::Entity;
use crate::physics::{Bounds, Vector2D};
#[derive(Debug, PartialEq)]
pub enum ParticleType {
BLUE = 0,
RED = 1,
GREEN = 2,
ORANGE = 3,
BROWN = 4,
WHITE = 5,
PURPLE = 6,
PINK = 7
}
pub struct Particle {
bounds: Bounds,
velocity: Vector2D,
pub particle_type: ParticleType,
id: usize,
}
impl Particle {
pub fn new(position : Vector2D, width : f64, height : f64, particle_type: ParticleType, id: usize) -> Self {
let bounds = Bounds::new(position, (width, height));
Self {
bounds,
particle_type,
velocity: get_initial_velocity(),
id,
}
}
pub fn handle_movement(&mut self) {
let new_position: Vector2D = Vector2D::add(self.bounds.get_position(), &self.velocity);
self.bounds.set_position(new_position);
}
pub fn handle_wall_collision(&mut self) {
let position = self.bounds.get_position();
if position.x() < 0.0 {
self.velocity.set_x(self.velocity.x() * -1.0);
}
if position.x() > 800.0 {
self.velocity.set_x(self.velocity.x() * -1.0);
}
if position.y() < 0.0 {
self.velocity.set_y(self.velocity.y() * -1.0);
}
if position.y() > 600.0 {
self.velocity.set_y(self.velocity.y() * -1.0);
}
}
}
impl Entity for Particle {
fn get_bounds(&self) -> &Bounds {
&self.bounds
}
fn get_colour(&self) -> [f32;4] {
match &self.particle_type {
ParticleType::BLUE => [0.0, 0.0, 1.0, 1.0],
ParticleType::RED => [1.0, 0.0, 0.0, 1.0],
ParticleType::GREEN => [0.0, 1.0, 0.0, 1.0],
ParticleType::ORANGE => [1.0, 0.95, 0.0, 1.0],
ParticleType::BROWN => [0.64, 0.16, 0.16, 1.0],
ParticleType::WHITE => [1.0, 1.0, 1.0, 1.0],
ParticleType::PURPLE => [0.9, 0.9, 0.98, 1.0],
ParticleType::PINK => [0.62, 0.16, 0.4, 1.0]
}
}
fn tick(&mut self) {
self.handle_movement();
self.handle_wall_collision();
}
fn get_id(&self) -> usize {
self.id
}
fn get_velocity(&self) -> &Vector2D {
&self.velocity
}
fn set_velocity(&mut self, velocity: Vector2D) {
self.velocity = velocity;
}
fn as_particle(&self) -> &Particle {
&self
}
}
pub fn get_random_particle_type() -> ParticleType {
let mut rng = rand::thread_rng();
let num = rng.gen::<f32>();
match num {
num if num < 0.125 => ParticleType::BLUE,
num if num < 0.25 => ParticleType::RED,
num if num < 0.375 => ParticleType::GREEN,
num if num < 0.5 => ParticleType::ORANGE,
num if num < 0.625 => ParticleType::BROWN,
num if num < 0.75 => ParticleType::WHITE,
num if num < 0.875 => ParticleType::PURPLE,
_ => ParticleType::PINK
}
}
pub fn get_initial_velocity() -> Vector2D {
let mut rng = rand::thread_rng();
let reverse_x = rng.gen::<f64>() > 0.5;
let reverse_y = rng.gen::<f64>() > 0.5;
let multiplier = rng.gen::<f64>() * 5.0;
let mut initial_velocity = Vector2D::new(rng.gen::<f64>() * multiplier, rng.gen::<f64>() * multiplier);
if reverse_x {
initial_velocity.set_x(initial_velocity.x() * -1.0);
}
if reverse_y {
initial_velocity.set_y(initial_velocity.y() * -1.0);
}
initial_velocity
} |
use std::fs::{read_to_string, OpenOptions};
use std::io::Write;
use std::path::Path;
use serde::ser::Serialize;
use serde_json::{from_str, to_string_pretty};
use super::Error;
use crate::Config;
pub fn load<P>(path: P) -> Result<Config, Error>
where
P: AsRef<Path>,
{
let string = read_to_string(path)?;
let config = from_str::<Config>(&string)?;
Ok(config)
}
pub fn save<T, P>(path: P, value: &T) -> Result<(), Error>
where
T: Serialize,
P: AsRef<Path>,
{
let string = to_string_pretty(&value)?;
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(path)?;
file.write_all(string.as_ref())?;
Ok(())
}
|
use std::cell::Cell;
pub type Callback = Box<dyn Fn(usize) -> bool>;
trait CallbackFunc {
fn call(&self) -> Option<bool>;
}
impl CallbackFunc for () {
fn call(&self) -> Option<bool> {
None
}
}
pub(crate) struct EvaluationProgress {
instruction_count: Cell<usize>,
callback: Option<Callback>,
}
impl EvaluationProgress {
pub fn new() -> Self {
EvaluationProgress {
instruction_count: Cell::new(1),
callback: None,
}
}
pub fn with_callback(&mut self, callback: Callback) {
self.callback.replace(callback);
}
pub fn callback(&self) -> Option<bool> {
if let Some(callback) = &self.callback {
Some(callback(self.instruction_count.get()))
} else {
None
}
}
pub fn increment(&self) {
self.instruction_count.set(self.instruction_count.get() + 1);
}
#[inline(always)]
pub fn call_and_increment(&self) -> Option<bool> {
let b = self.callback();
self.increment();
b
}
}
|
extern crate nalgebra as na;
extern crate nalgebra_glm as glm;
pub mod camera;
pub mod lights;
pub mod gltf;
use crate::figure::FigureSet;
use crate::scene::camera::ViewAndProject;
use crate::scene::lights::Light;
use std::fmt::Debug;
use std::sync::Arc;
use std::sync::Mutex;
#[derive(Debug, Clone)]
pub struct Scene<T: ViewAndProject + Sized> {
pub camera: Arc<Mutex<T>>,
pub figures: Vec<FigureSet>,
pub global_scene_id: u32,
pub lights: Vec<Light>,
}
impl<T: ViewAndProject + Sized> Scene<T> {
pub fn create(camera: Arc<Mutex<T>>, figures: Vec<FigureSet>, lights: Vec<Light>) -> Self {
Self {
camera,
figures,
global_scene_id: 1,
lights,
}
}
}
|
#[macro_use]
extern crate easybuffers;
extern crate time;
use easybuffers::helper::{ Table, HyperHelper };
#[derive(PartialEq,Clone,Default,Debug)]
struct TestMessage {
field_0: Option<String>,
field_1: Option<String>,
field_2: Option<bool>,
field_3: Option<String>,
field_4: Option<bool>,
field_5: Option<String>,
field_6: Option<String>,
field_7: Option<u32>,
field_8: Option<String>,
field_9: Option<String>,
field_10: Option<bool>
}
impl TestMessage {
fn print(&mut self) {
let field_0 = &self.field_0;
let field_1 = &self.field_1;
let field_2 = &self.field_2;
let field_3 = &self.field_3;
let field_4 = &self.field_4;
let field_5 = &self.field_5;
let field_6 = &self.field_6;
let field_7 = &self.field_7;
let field_8 = &self.field_8;
let field_9 = &self.field_9;
let field_10 = &self.field_10;
println!(" field_0:{:?},field_1:{:?},field_2:{:?},field_3:{:?},field_4:{:?},field_5:{:?},field_6:{:?},field_7:{:?},field_8:{:?},field_9:{:?},field_10:{:?}",
field_0, field_1, field_2, field_3, field_4, field_5, field_6, field_7, field_8, field_9, field_10);
}
fn instance() -> TestMessage {
Default::default()
}
fn init() -> TestMessage {
TestMessage {
field_0 : None,
field_1 : Some(String::from("message_0")),
field_2 : Some(false),
field_3 : Some(String::from("in")),
field_4 : Some(true),
field_5 : Some(String::from("Rust")),
field_6 : None,
field_7 : Some(700000u32),
field_8 : Some(String::from("message_1")),
field_9 : Some(String::from("without Option")),
field_10 : Some(true)
}
}
}
impl Table for TestMessage {
fn deserialize(bytes: &Vec<u8>, pivot: usize, help_pivot: usize, position: usize, helper: &HyperHelper) -> TestMessage {
let mut instance = TestMessage::instance();
match HyperHelper::child_pivot(bytes, pivot, 0, helper) {
// List 先不考虑
None => (), // 不做任何操作
Some(child_pivot) => {
instance.field_0 = Option::deserialize(bytes, child_pivot, pivot, 0, helper);// 传引用,这样省时间,到需要转换基本数据 才调用 to_vec
}
}
match HyperHelper::child_pivot(bytes, pivot, 1, helper) {
None => (), // 不做任何操作
Some(child_pivot) => {
instance.field_1 = Option::deserialize(bytes, child_pivot, pivot, 1, helper);
}
}
match HyperHelper::child_pivot(bytes, pivot, 2, helper) {
None => (), // 不做任何操作
Some(child_pivot) => {
instance.field_2 = Option::deserialize(bytes, child_pivot, pivot, 2, helper);
}
}
match HyperHelper::child_pivot(bytes, pivot, 3, helper) {
None => (), // 不做任何操作
Some(child_pivot) => {
instance.field_3 = Option::deserialize(bytes, child_pivot, pivot, 3, helper);
}
}
match HyperHelper::child_pivot(bytes, pivot, 4, helper) {
None => (), // 不做任何操作
Some(child_pivot) => {
instance.field_4 = Option::deserialize(bytes, child_pivot, pivot, 4, helper);
}
}
match HyperHelper::child_pivot(bytes, pivot, 5, helper) {
None => (), // 不做任何操作
Some(child_pivot) => {
instance.field_5 = Option::deserialize(bytes, child_pivot, pivot, 5, helper);
}
}
match HyperHelper::child_pivot(bytes, pivot, 6, helper) {
None => (), // 不做任何操作
Some(child_pivot) => {
instance.field_6 = Option::deserialize(bytes, child_pivot, pivot, 6, helper);
}
}
match HyperHelper::child_pivot(bytes, pivot, 7, helper) {
None => (), // 不做任何操作
Some(child_pivot) => {
instance.field_7 = Option::deserialize(bytes, child_pivot, pivot, 7, helper);
}
}
match HyperHelper::child_pivot(bytes, pivot, 8, helper) {
None => (), // 不做任何操作
Some(child_pivot) => {
instance.field_8 = Option::deserialize(bytes, child_pivot, pivot, 8, helper);
}
}
match HyperHelper::child_pivot(bytes, pivot, 9, helper) {
None => (), // 不做任何操作
Some(child_pivot) => {
instance.field_9 = Option::deserialize(bytes, child_pivot, pivot, 9, helper);
}
}
match HyperHelper::child_pivot(bytes, pivot, 10, helper) {
None => (), // 不做任何操作
Some(child_pivot) => {
instance.field_10 = Option::deserialize(bytes, child_pivot, pivot, 10, helper);
}
}
instance
}
fn serialize(&mut self, table: &mut Vec<u8>, pivot_index:usize, position: usize, helper: &HyperHelper) {
let field_num = 11usize; // 需要外部传入
let slot_size = 2; // 需要全局定义
table.push(255u8);
table.append(&mut vec![0u8;(field_num+1)*slot_size+1]);
let child_pivot_index = table.len() - 1;
table[child_pivot_index] = field_num as u8; // 这里可以好好斟酌下
// 更新每个字段
self.field_0.serialize(table, child_pivot_index, 0, helper);
self.field_1.serialize(table, child_pivot_index, 1, helper);
self.field_2.serialize(table, child_pivot_index, 2, helper);
self.field_3.serialize(table, child_pivot_index, 3, helper);
self.field_4.serialize(table, child_pivot_index, 4, helper);
self.field_5.serialize(table, child_pivot_index, 5, helper);
self.field_6.serialize(table, child_pivot_index, 6, helper);
self.field_7.serialize(table, child_pivot_index, 7, helper);
self.field_8.serialize(table, child_pivot_index, 8, helper);
self.field_9.serialize(table, child_pivot_index, 9, helper);
self.field_10.serialize(table, child_pivot_index, 10, helper);
// 更新最终的长度
if pivot_index != 0 {
// 更新father的vtable
// 算出 child 和 pivot 的距离
let max = table[pivot_index] as usize;
let offset = child_pivot_index - pivot_index;
table[pivot_index - slot_size*(1+max - position)] = (offset & 0xff) as u8;
table[pivot_index - slot_size*(1+max - position)+1] = ((offset >> 8) & 0xff) as u8;
if position == max - 1 {
// 要更新father的len
let len = table.len() - 1 - pivot_index;
table[pivot_index - 2] = (len & 0xff) as u8;
table[pivot_index - 1] = ((len >> 8) & 0xff) as u8;
}
}
}
}
fn main() {
let helper = HyperHelper::new(2);
let mut bytes = Vec::with_capacity(1024);
let test = TestMessage::init();
let start = time::get_time();
for i in 0..1000000 {
let mut instance = TestMessage::init();
instance.serialize(&mut bytes, 0, 0, &helper);
HyperHelper::push_pivot(11 ,&mut bytes, &helper);
assert_eq!(bytes, vec![255, 0, 0, 2, 0, 12, 0, 14, 0, 17, 0, 19, 0, 0, 0, 24, 0, 29, 0, 39, 0, 54, 0, 54, 0, 11, 255, 109, 101, 115, 115, 97, 103, 101, 95, 48, 255, 0, 255, 105, 110, 255, 1, 255, 82, 117, 115, 116, 255, 96, 174, 10, 0, 255, 109, 101, 115, 115, 97, 103, 101, 95, 49, 255, 119, 105, 116, 104, 111, 117, 116, 32, 79, 112, 116, 105, 111, 110, 255, 1, 25]);
bytes.clear();
}
let end = time::get_time();
println!("序列化 {:?}", (end - start)/1000000);
let start = time::get_time();
for i in 0..1000000 {
let mut data = vec![255, 0, 0, 2, 0, 12, 0, 14, 0, 17, 0, 19, 0, 0, 0, 24, 0, 29, 0, 39, 0, 54, 0, 54, 0, 11, 255, 109, 101, 115, 115, 97, 103, 101, 95, 48, 255, 0, 255, 105, 110, 255, 1, 255, 82, 117, 115, 116, 255, 96, 174, 10, 0, 255, 109, 101, 115, 115, 97, 103, 101, 95, 49, 255, 119, 105, 116, 104, 111, 117, 116, 32, 79, 112, 116, 105, 111, 110, 255, 1, 25];
let pivot = data.pop().unwrap() as usize;
let de_instance = TestMessage::deserialize(&data, pivot, pivot, 0, &helper);
assert_eq!(de_instance.field_7.unwrap(), 700000u32);
}
let end = time::get_time();
println!("反序列化 10 {:?}", (end - start)/1000000);
}
|
fn basic_match(num: i32) {
print!("Tell me about {}\n -- ", num);
match num {
1 => println!("One!"),
2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
13..=19 => println!("A teen"),
_ => println!("Ain't special")
}
}
fn return_match() {
let boolean = true;
let binary = match boolean {
true => 1,
false => 0
};
println!("C equivalent of {} is {}", boolean, binary);
}
fn main() {
let vect = vec![3, 1, 4, 15, 92];
for n in vect.iter() {
basic_match(*n);
}
return_match();
} |
/* Copyright 2021 Al Liu (https://github.com/al8n). Licensed under Apache-2.0.
*
* Copyright 2017 The Hashicorp's Raft repository authors(https://github.com/hashicorp/raft) authors. Licensed under MPL-2.0.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use crate::config::{Configuration, ServerID, ServerSuffrage};
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::Arc;
cfg_default!(
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
);
cfg_not_default!(
use crossbeam::channel::{Receiver, Sender};
);
/// `Commitment` is used to advance the leader's commit index. The leader and
/// replication routines report in newly written entries with Match(), and
/// this notifies on commit_ch when the commit index has advanced.
pub struct Commitment {
/// notified when commitIndex increases
#[cfg(feature = "default")]
commit_rx_ch: UnboundedReceiver<()>,
#[cfg(feature = "default")]
commit_tx_ch: UnboundedSender<()>,
#[cfg(not(feature = "default"))]
commit_rx_ch: Receiver<()>,
#[cfg(not(feature = "default"))]
commit_tx_ch: Sender<()>,
/// voter ID to log index: the server stores up through this log entry
match_indexes: HashMap<ServerID, u64>,
/// a quorum stores up through this log entry. monotonically increases.
commit_index: u64,
/// the first index of this leader's term: this needs to be replicated to a
/// majority of the cluster before this leader may mark anything committed
/// (per Raft's commitment rule)
start_index: u64,
}
impl Commitment {
pub fn new(
#[cfg(feature = "default")] commit_tx_ch: UnboundedSender<()>,
#[cfg(feature = "default")] commit_rx_ch: UnboundedReceiver<()>,
#[cfg(not(feature = "default"))] commit_tx_ch: Sender<()>,
#[cfg(not(feature = "default"))] commit_rx_ch: Receiver<()>,
cfg: Configuration,
start_index: u64,
) -> Arc<Mutex<Self>> {
let match_indexes = {
let mut m = HashMap::<ServerID, u64>::new();
for s in cfg.servers {
if s.suffrage == ServerSuffrage::Voter {
m.insert(s.id, 0);
}
}
m
};
let val = Self {
commit_rx_ch,
commit_tx_ch,
match_indexes,
commit_index: 0,
start_index,
};
Arc::new(Mutex::new(val))
}
/// Called when a new cluster membership configuration is created: it will be
/// used to determine `Commitment` from now on. 'configuration' is the servers in
/// the cluster.
pub fn set_configuration(&mut self, cfg: Configuration) {
let mut new_match_indexes = HashMap::<ServerID, u64>::new();
for s in cfg.servers {
if s.suffrage == ServerSuffrage::Voter {
new_match_indexes.insert(s.id, *self.match_indexes.get(&s.id).unwrap_or(&0u64));
// defaults to 0
}
}
self.match_indexes = new_match_indexes;
self.recalculate();
}
/// Called by leader after `commit_rx_ch` is notified
pub fn get_commit_index(&self) -> u64 {
self.commit_index
}
/// `match_server` is called once a server completes writing entries to disk: either the
/// leader has written the new entry or a follower has replied to an
/// AppendEntries RPC. The given server's disk agrees with this server's log up
/// through the given index.
pub fn match_server(&mut self, server: ServerID, match_index: u64) {
match self.match_indexes.get_mut(&server) {
None => {}
Some(prev) => {
if match_index > *prev {
*prev = match_index;
self.recalculate();
}
}
}
}
/// Internal helper to calculate new `commit_index` from `match_indexes`.
/// Must be called with lock held.
fn recalculate(&mut self) {
let size = self.match_indexes.len();
if size == 0 {
return;
}
let mut matched = Vec::<u64>::with_capacity(size);
for (_, v) in &self.match_indexes {
matched.push(*v);
}
matched.sort();
let quorum_match_index = matched[(matched.len() - 1) / 2];
if quorum_match_index > self.commit_index && quorum_match_index >= self.start_index {
self.commit_index = quorum_match_index;
self.commit_tx_ch.send(());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{Server, ServerAddress};
use tokio::sync::mpsc::unbounded_channel;
fn make_configuration(voters: Vec<u64>) -> Configuration {
let mut servers = Vec::<Server>::new();
for v in voters {
servers.push(Server {
suffrage: ServerSuffrage::Voter,
id: v,
address: ServerAddress::from(format!("{}addr", v)),
});
}
Configuration::with_servers(servers)
}
fn voters(n: u64) -> Configuration {
let severs = vec![1u64, 2, 3, 4, 5, 6, 7];
if n > 7 {
panic!("only up to 7 servers implemented")
}
make_configuration(
severs
.into_iter()
.filter(|val| *val <= n)
.collect::<Vec<u64>>(),
)
}
#[tokio::test]
async fn test_commitment_set_voters() {
let (commit_tx, commit_rx) = unbounded_channel::<()>();
let c = Commitment::new(
commit_tx,
commit_rx,
make_configuration(vec![100, 101, 102]),
0,
);
c.lock().match_server(100, 10);
c.lock().match_server(101, 20);
c.lock().match_server(102, 30);
// commit_index: 20
let rx = c.lock().commit_rx_ch.recv().await;
if let Some(v) = rx {
assert_eq!(v, (), "expected commit notify");
}
c.lock()
.set_configuration(make_configuration(vec![102, 103, 104]));
// 102: 30, 103: 0, 104: 0
c.lock().match_server(104, 40);
let idx = c.lock().get_commit_index();
assert_eq!(idx, 30, "expected 30 entries committed, found {}", idx);
let rx = c.lock().commit_rx_ch.recv().await;
if let Some(v) = rx {
assert_eq!(v, (), "expected commit notify");
}
}
#[test]
fn test_commitment_match_max() {
let (commit_tx, commit_rx) = unbounded_channel::<()>();
let c = Commitment::new(commit_tx, commit_rx, voters(5), 4);
c.lock().match_server(1, 8);
c.lock().match_server(2, 8);
c.lock().match_server(2, 1);
c.lock().match_server(3, 8);
let idx = c.lock().get_commit_index();
assert_eq!(
idx, 8,
"calling match with an earlier index should be ignored"
)
}
#[tokio::test]
async fn test_commitment_match_nonvoting() {
let (commit_tx, commit_rx) = unbounded_channel::<()>();
let c = Commitment::new(commit_tx, commit_rx, voters(5), 4);
c.lock().match_server(1, 8);
c.lock().match_server(2, 8);
c.lock().match_server(3, 8);
let rx = c.lock().commit_rx_ch.recv().await;
if let Some(v) = rx {
assert_eq!(v, (), "expected commit notify");
}
c.lock().match_server(90, 10);
c.lock().match_server(91, 10);
c.lock().match_server(92, 10);
let idx = c.lock().get_commit_index();
assert_eq!(idx, 8, "non-voting servers shouldn't be able to commit");
}
#[tokio::test]
async fn test_commitment_recalculate() {
let (commit_tx, commit_rx) = unbounded_channel::<()>();
let c = Commitment::new(commit_tx, commit_rx, voters(5), 0);
c.lock().match_server(1, 30);
c.lock().match_server(2, 20);
let idx = c.lock().get_commit_index();
assert_eq!(idx, 0, "shouldn't commit after two of five servers");
c.lock().match_server(3, 10);
let idx = c.lock().get_commit_index();
assert_eq!(idx, 10, "expected 10 entries committed, found {}", idx);
let rx = c.lock().commit_rx_ch.recv().await;
if let Some(v) = rx {
assert_eq!(v, (), "expected commit notify");
}
c.lock().match_server(4, 15);
let idx = c.lock().get_commit_index();
assert_eq!(idx, 15, "expected 15 entries committed, found {}", idx);
let rx = c.lock().commit_rx_ch.recv().await;
if let Some(v) = rx {
assert_eq!(v, (), "expected commit notify");
}
c.lock().set_configuration(voters(3));
// 1:30, 2: 20, 3: 10
let idx = c.lock().get_commit_index();
assert_eq!(idx, 20, "expected 20 entries committed, found {}", idx);
let rx = c.lock().commit_rx_ch.recv().await;
if let Some(v) = rx {
assert_eq!(v, (), "expected commit notify");
}
c.lock().set_configuration(voters(4));
// 1:30, 2: 20, 3: 10, 4: 0
c.lock().match_server(2, 25);
let idx = c.lock().get_commit_index();
assert_eq!(idx, 20, "expected 20 entries committed, found {}", idx);
c.lock().match_server(4, 23);
let idx = c.lock().get_commit_index();
assert_eq!(idx, 23, "expected 23 entries committed, found {}", idx);
let rx = c.lock().commit_rx_ch.recv().await;
if let Some(v) = rx {
assert_eq!(v, (), "expected commit notify");
}
}
#[tokio::test]
async fn test_commitment_recalculate_start_index() {
let (commit_tx, commit_rx) = unbounded_channel::<()>();
let c = Commitment::new(commit_tx, commit_rx, voters(5), 4);
c.lock().match_server(1, 3);
c.lock().match_server(2, 3);
c.lock().match_server(3, 3);
let idx = c.lock().get_commit_index();
assert_eq!(
idx, 0,
"can't commit until startIndex is replicated to a quorum"
);
c.lock().match_server(1, 4);
c.lock().match_server(2, 4);
c.lock().match_server(3, 4);
let idx = c.lock().get_commit_index();
assert_eq!(
idx, 4,
"should be able to commit startIndex once replicated to a quorum"
);
let rx = c.lock().commit_rx_ch.recv().await;
if let Some(v) = rx {
assert_eq!(v, (), "expected commit notify");
}
}
#[tokio::test]
async fn test_commitment_no_voter_sanity() {
let (commit_tx, commit_rx) = unbounded_channel::<()>();
let c = Commitment::new(commit_tx, commit_rx, make_configuration(vec![]), 4);
c.lock().match_server(1, 10);
c.lock().set_configuration(make_configuration(vec![]));
c.lock().match_server(1, 10);
let idx = c.lock().get_commit_index();
assert_eq!(idx, 0, "no voting servers: shouldn't be able to commit");
// add a voter so we can commit something and then remove it
c.lock().set_configuration(voters(1));
c.lock().match_server(1, 10);
let idx = c.lock().get_commit_index();
assert_eq!(idx, 10, "expected 10 entries committed, found {}", idx);
let rx = c.lock().commit_rx_ch.recv().await;
if let Some(v) = rx {
assert_eq!(v, (), "expected commit notify");
}
c.lock().set_configuration(make_configuration(vec![]));
c.lock().match_server(1, 20);
let idx = c.lock().get_commit_index();
assert_eq!(idx, 10, "expected 10 entries committed, found {}", idx);
}
#[tokio::test]
async fn test_commitment_single_voter() {
let (commit_tx, commit_rx) = unbounded_channel::<()>();
let c = Commitment::new(commit_tx, commit_rx, voters(1), 4);
c.lock().match_server(1, 10);
let idx = c.lock().get_commit_index();
assert_eq!(idx, 10, "expected 10 entries committed, found {}", idx);
let rx = c.lock().commit_rx_ch.recv().await;
if let Some(v) = rx {
assert_eq!(v, (), "expected commit notify");
}
c.lock().set_configuration(voters(1));
c.lock().match_server(1, 12);
let idx = c.lock().get_commit_index();
assert_eq!(idx, 12, "expected 12 entries committed, found {}", idx);
let rx = c.lock().commit_rx_ch.recv().await;
if let Some(v) = rx {
assert_eq!(v, (), "expected commit notify");
}
}
}
|
use crate::shabal256::{shabal256_deadline_fast, shabal256_hash_fast};
use core::{u32, u64};
use sp_std::mem::transmute;
const SCOOP_SIZE: usize = 64;
pub fn calculate_scoop(height: u64, gensig: &[u8; 32]) -> u32 {
let mut data: [u8; 64] = [0; 64];
let height_bytes: [u8; 8] = unsafe { transmute(height.to_be()) };
data[..32].clone_from_slice(gensig);
data[32..40].clone_from_slice(&height_bytes);
data[40] = 0x80;
let data = unsafe { sp_std::mem::transmute::<&[u8; 64], &[u32; 16]>(&data) };
let new_gensig = &shabal256_hash_fast(&[], &data);
(u32::from(new_gensig[30] & 0x0F) << 8) | u32::from(new_gensig[31])
}
pub fn find_best_deadline_rust(
data: &[u8],
number_of_nonces: u64,
gensig: &[u8; 32],
) -> (u64, u64) {
let mut best_deadline = u64::MAX;
let mut best_offset = 0;
for i in 0..number_of_nonces as usize {
let result =
shabal256_deadline_fast(&data[i * SCOOP_SIZE..i * SCOOP_SIZE + SCOOP_SIZE], &gensig);
if result < best_deadline {
best_deadline = result;
best_offset = i;
}
}
(best_deadline, best_offset as u64)
}
|
use raylib::prelude::*;
use specs::prelude::*;
pub const CHUNK_SIZE : usize = 64;
type BlockData = bool;
pub struct ChunkData([BlockData; CHUNK_SIZE*CHUNK_SIZE*CHUNK_SIZE]);
impl ChunkData {
pub fn new() -> Self {
return ChunkData([false; CHUNK_SIZE*CHUNK_SIZE*CHUNK_SIZE]);
}
pub fn from_array(arr : [bool; CHUNK_SIZE*CHUNK_SIZE*CHUNK_SIZE]) -> ChunkData {
return ChunkData(arr);
}
pub fn set(&mut self,value: BlockData, x: usize, y:usize, z:usize) {
if x >= CHUNK_SIZE || y >= CHUNK_SIZE || z >= CHUNK_SIZE {
panic!("Invalid chunk position: Tried to access position ({}, {}, {}) on chunk of size {}",
x, y, z, CHUNK_SIZE);
}
self.0[Self::position_from_coordinates(x, y, z)] = value;
}
pub fn get(&mut self, x: usize, y:usize, z:usize) -> BlockData {
if x >= CHUNK_SIZE || y >= CHUNK_SIZE || z >= CHUNK_SIZE {
panic!("Invalid chunk position: Tried to access position ({}, {}, {}) on chunk of size {}",
x, y, z, CHUNK_SIZE);
}
return self.0[Self::position_from_coordinates(x, y, z)];
}
pub fn position_from_coordinates(x: usize, y:usize, z:usize) -> usize {
return CHUNK_SIZE*(CHUNK_SIZE*x + y) + z;
}
pub fn coordinates_from_position(pos: usize) ->(usize, usize, usize) {
let x = pos%(CHUNK_SIZE*CHUNK_SIZE);
let y = (pos - x*CHUNK_SIZE)%CHUNK_SIZE;
let z = (pos - y*CHUNK_SIZE - x*CHUNK_SIZE*CHUNK_SIZE)%CHUNK_SIZE;
return (x, y, z);
}
//TODO
//unsafe fn generate_mesh(&self) -> Mesh {
// return mesh;
//}
}
struct ChunkComponent {
chunk_data : ChunkData,
must_rebuild: bool,
}
impl Component for ChunkComponent {
type Storage = VecStorage<Self>;
}
struct VoxelSystem{
} |
#[doc = "Register `RCC_IDR` reader"]
pub type R = crate::R<RCC_IDR_SPEC>;
#[doc = "Field `ID` reader - ID"]
pub type ID_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - ID"]
#[inline(always)]
pub fn id(&self) -> ID_R {
ID_R::new(self.bits)
}
}
#[doc = "This register gives the unique identifier of the RCC\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rcc_idr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct RCC_IDR_SPEC;
impl crate::RegisterSpec for RCC_IDR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`rcc_idr::R`](R) reader structure"]
impl crate::Readable for RCC_IDR_SPEC {}
#[doc = "`reset()` method sets RCC_IDR to value 0x01"]
impl crate::Resettable for RCC_IDR_SPEC {
const RESET_VALUE: Self::Ux = 0x01;
}
|
use aoc::*;
fn main() -> Result<()> {
let mut world = World {
computer: Computer::load("15.txt")?,
map: vec![vec![255; 50]; 50],
position: Point::new(25, 25),
oxygen: None,
};
world.dfs();
world.bfs();
world.draw();
Ok(())
}
struct World {
computer: Computer,
map: Vec<Vec<u8>>,
position: Point,
oxygen: Option<Point>,
}
impl World {
fn dfs(&mut self) {
for direction in 1..=4 {
let destination = self.position.direction(direction);
if self.map[destination.y][destination.x] != 255 {
continue;
}
if let Some(response) = self.computer.run(&[direction]) {
self.map[destination.y][destination.x] = response as u8;
match response {
0 => continue,
2 => self.oxygen = Some(destination),
_ => (),
}
self.position = destination;
self.dfs();
let backtrack = match direction {
1 => 2,
2 => 1,
3 => 4,
4 => 3,
_ => unreachable!(),
};
self.computer.run(&[backtrack]);
self.position = self.position.direction(backtrack);
}
}
}
fn bfs(&mut self) {
let mut border = vec![self.oxygen.unwrap()];
for minute in 0.. {
if !self.map.iter().any(|row| row.contains(&1)) {
println!("Minute {}", minute);
break;
}
let mut next = vec![];
for position in &border {
for direction in 1..=4 {
let destination = position.direction(direction);
if self.map[destination.y][destination.x] == 1 {
self.map[destination.y][destination.x] = 3;
next.push(destination);
}
}
}
border = next;
}
}
fn draw(&self) {
for row in &self.map {
let line: String = row
.iter()
.map(|b| match b {
0 => '#',
1 => '.',
2 => '*',
3 => 'O',
_ => ' ',
})
.collect();
println!("{}", line);
}
}
}
#[derive(Clone, Copy, Debug)]
struct Point {
x: usize,
y: usize,
}
impl Point {
fn new(x: usize, y: usize) -> Point {
Self { x, y }
}
fn direction(&self, direction: i64) -> Point {
match direction {
1 => Self::new(self.x, self.y - 1),
2 => Self::new(self.x, self.y + 1),
3 => Self::new(self.x - 1, self.y),
4 => Self::new(self.x + 1, self.y),
_ => unreachable!(),
}
}
}
#[derive(Clone)]
struct Computer {
base: usize,
mem: Vec<i64>,
ip: usize,
}
impl Computer {
fn load(filename: &str) -> Result<Self> {
let mut mem: Vec<i64> = input(filename)?
.split(',')
.map(|s| s.parse().unwrap())
.collect();
mem.resize(10 * 1024, 0);
Ok(Computer {
base: 0,
mem,
ip: 0,
})
}
const OP_SIZE: &'static [usize] = &[0, 4, 4, 2, 2, 3, 3, 4, 4, 2];
fn run(&mut self, input: &[i64]) -> Option<i64> {
let mut input = input.iter();
loop {
let op = (self.mem[self.ip] % 100) as usize;
match op {
1 => *self.at(3) = *self.at(1) + *self.at(2),
2 => *self.at(3) = *self.at(1) * *self.at(2),
3 => *self.at(1) = *input.next().unwrap(),
4 => {
let output = *self.at(1);
self.ip += Self::OP_SIZE[op];
return Some(output);
}
5 => {
if *self.at(1) != 0 {
self.ip = *self.at(2) as usize;
continue;
}
}
6 => {
if *self.at(1) == 0 {
self.ip = *self.at(2) as usize;
continue;
}
}
7 => *self.at(3) = if *self.at(1) < *self.at(2) { 1 } else { 0 },
8 => *self.at(3) = if *self.at(1) == *self.at(2) { 1 } else { 0 },
9 => self.base = (self.base as i64 + *self.at(1)) as usize,
99 => return None,
_ => unreachable!(),
}
self.ip += Self::OP_SIZE[op];
}
}
fn at(&mut self, parameter: usize) -> &mut i64 {
let mode = self.mem[self.ip] / 10i64.pow(parameter as u32 + 1) % 10;
let parameter = self.ip + parameter;
let address = match mode {
0 => self.mem[parameter] as usize,
1 => parameter,
2 => (self.base as i64 + self.mem[parameter]) as usize,
_ => unreachable!(),
};
&mut self.mem[address]
}
}
|
extern crate libc;
extern crate libpulse_sys;
mod context;
mod error;
mod ffi;
mod mainloop;
mod mainloop_api;
mod operation;
mod stream;
mod threaded_mainloop;
mod time_event;
pub use context::Context;
pub use error::ErrorCode;
pub use mainloop::Mainloop;
pub use mainloop_api::MainloopApi;
pub use operation::Operation;
pub use stream::Stream;
pub use threaded_mainloop::ThreadedMainloop;
pub use time_event::TimeEvent;
// Data Structures
pub use libpulse_sys::pa_buffer_attr as BufferAttr;
pub use libpulse_sys::pa_channel_map as ChannelMap;
pub use libpulse_sys::pa_cvolume as CVolume;
pub use libpulse_sys::pa_sample_spec as SampleSpec;
pub use libpulse_sys::pa_seek_mode_t as SeekMode;
pub use libpulse_sys::pa_server_info as ServerInfo;
pub use libpulse_sys::pa_sink_flags_t as SinkFlags;
pub use libpulse_sys::pa_sink_info as SinkInfo;
pub use libpulse_sys::pa_sink_input_info as SinkInputInfo;
pub use libpulse_sys::pa_stream_flags_t as StreamFlags;
pub use libpulse_sys::pa_stream_state_t as StreamState;
pub use libpulse_sys::pa_usec_t as USec;
pub use context::ContextState;
pub type Result<T> = ::std::result::Result<T, error::ErrorCode>;
pub fn frame_size(ss: &SampleSpec) -> usize
{
unsafe { libpulse_sys::pa_frame_size(ss as *const _) }
}
pub fn rtclock_now() -> USec {
unsafe { libpulse_sys::pa_rtclock_now() }
}
|
#![warn(rust_2018_idioms)]
use std::cell::RefCell;
use std::rc::Rc;
use futures::channel::mpsc;
use js_sys::Uint8Array;
use rand::rngs::OsRng;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::{BinaryType, ErrorEvent, MessageEvent, WebSocket};
use netholdem_game::model;
use netholdem_game::protocol::{IntroductionRequest, Request, Response};
macro_rules! console_log {
($($t:tt)*) => (log(&format_args!($($t)*).to_string()))
}
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
fn connect() -> Result<WebSocket, JsValue> {
let window = web_sys::window().expect("window to exist");
let addr = format!(
"ws://{}:{}/server",
window.location().hostname().expect("hostname to exist"),
window.location().port().expect("port to exist")
);
let ws = WebSocket::new(&addr)?;
Ok(ws)
}
#[wasm_bindgen]
pub struct Client {
ws: WebSocket,
state: Rc<RefCell<State>>,
}
#[wasm_bindgen]
impl Client {
pub fn connect() -> Result<Client, JsValue> {
/*
use rand::rngs::OsRng;
use x25519_dalek::{EphemeralSecret, PublicKey};
let secret = EphemeralSecret::new(&mut OsRng);
let public = PublicKey::from(&secret);
console_log!("{:?}", public.as_bytes());
*/
let (request_tx, _request_rx) = mpsc::channel(8);
let (_response_tx, response_rx) = mpsc::channel(8);
let state = Rc::new(RefCell::new(State::new(request_tx, response_rx)));
let ws = connect()?;
ws.set_binary_type(BinaryType::Arraybuffer);
let onmessage_callback = Closure::wrap(Box::new(move |e: MessageEvent| {
console_log!("raw response: {:?}", e.data());
let msg = Uint8Array::new(&e.data()).to_vec();
console_log!("vec response: {:?}", msg);
let response: Result<Response, _> = bincode::deserialize(&msg);
match response {
Ok(response) => {
console_log!("got response: {:?}", response);
}
Err(e) => {
console_log!("error decoding response: {}", e);
}
}
}) as Box<dyn FnMut(MessageEvent)>);
ws.set_onmessage(Some(onmessage_callback.as_ref().unchecked_ref()));
onmessage_callback.forget();
let onerror_callback = Closure::wrap(Box::new(move |e: ErrorEvent| {
console_log!("error event: {:?}", e);
}) as Box<dyn FnMut(ErrorEvent)>);
ws.set_onerror(Some(onerror_callback.as_ref().unchecked_ref()));
onerror_callback.forget();
let cloned_ws = ws.clone();
let onopen_callback = Closure::wrap(Box::new(move |_| {
console_log!("socket opened");
let secret = x25519_dalek::EphemeralSecret::new(&mut OsRng);
let public_key = x25519_dalek::PublicKey::from(&secret);
let client_id = model::EndpointId(public_key.as_bytes().clone());
let request = Request::Introduction(IntroductionRequest::new(client_id));
let request_bytes: Vec<u8> =
bincode::serialize(&request).expect("serialization to work");
match cloned_ws.send_with_u8_array(&request_bytes) {
Ok(_) => console_log!("message successfully sent"),
Err(err) => console_log!("error sending message: {:?}", err),
}
}) as Box<dyn FnMut(JsValue)>);
ws.set_onopen(Some(onopen_callback.as_ref().unchecked_ref()));
onopen_callback.forget();
let client = Client { ws, state };
Ok(client)
}
}
struct State {
request_tx: mpsc::Sender<Request>,
response_rx: mpsc::Receiver<Response>,
}
impl State {
pub fn new(request_tx: mpsc::Sender<Request>, response_rx: mpsc::Receiver<Response>) -> Self {
State {
request_tx,
response_rx,
}
}
}
|
// Copyright (c) 2018, Maarten de Vries <maarten@de-vri.es>
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use std::cell::UnsafeCell;
use std::collections::btree_map;
use std::collections::BTreeMap;
use std::collections::Bound::{Excluded, Included, Unbounded};
use super::BorrowSlice;
use super::Slice;
use super::StableBorrow;
pub struct Entry<Data, Metadata> {
/// The data being tracked.
data: Data,
/// Metadata for the entry.
///
/// The metadata is kept in a box so references remain valid
/// when new entries are added to the map.
meta: Box<Metadata>,
}
/// Tracker for slices with metadata.
///
/// The tracker can take ownership or store references if their lifetime is long enough.
/// Each slice added to the tracker has some metadata attached to it.
/// This information can later be retrieved from the tracker with a subslice of the tracked slice.
///
/// The tracker can not track empty slices, and it can not look up information for empty slices.
pub struct SliceTracker<Data, Metadata>
where
Data: BorrowSlice + StableBorrow,
{
map: UnsafeCell<BTreeMap<*const <Data::Slice as Slice>::Element, Entry<Data, Metadata>>>,
}
impl<Data, Metadata> Default for SliceTracker<Data, Metadata>
where
Data: BorrowSlice + StableBorrow,
{
fn default() -> Self {
Self::new()
}
}
impl<Data, Metadata> SliceTracker<Data, Metadata>
where
Data: BorrowSlice + StableBorrow,
{
/// Create a new slice tracker.
pub fn new() -> Self {
Self {
map: UnsafeCell::new(BTreeMap::new()),
}
}
/// Insert a slice with metadata without checking if the data is already present.
pub unsafe fn insert_unsafe<'path>(&self, data: Data, meta: impl Into<Box<Metadata>>) -> &Data::Slice {
// Insert the data itself.
match self.map_mut().entry(data.start_ptr()) {
btree_map::Entry::Vacant(x) => &x
.insert(Entry {
data,
meta: meta.into(),
})
.data
.borrow_slice(),
btree_map::Entry::Occupied(_) => unreachable!(),
}
}
/// Safely insert a slice with metadata.
pub fn insert<'path>(&self, data: Data, meta: impl Into<Box<Metadata>>) -> Result<&Data::Slice, ()> {
// Reject empty data or data that is already (partially) tracked.
if data.is_empty() || self.has_overlap(data.borrow_slice()) {
return Err(());
}
Ok(unsafe { self.insert_unsafe(data, meta) })
}
/// Check if a slice is tracked.
pub fn is_tracked(&self, data: &Data::Slice) -> bool {
self.get_entry(data).is_some()
}
/// Get the whole tracked slice and metadata for a (partial) slice.
pub fn get(&self, data: &Data::Slice) -> Option<(&Data::Slice, &Metadata)> {
self.get_entry(data)
.map(|entry| (entry.data.borrow_slice(), entry.meta.as_ref()))
}
/// Get the metadata for a (partial) slice.
pub fn metadata(&self, data: &Data::Slice) -> Option<&Metadata> {
self.get_entry(data).map(|entry| entry.meta.as_ref())
}
/// Get the whole tracked slice for a (partial) slice.
pub fn whole_slice(&self, data: &Data::Slice) -> Option<&Data::Slice> {
self.get_entry(data).map(|entry| entry.data.borrow_slice())
}
/// Get the map from the UnsafeCell.
fn map(&self) -> &BTreeMap<*const <Data::Slice as Slice>::Element, Entry<Data, Metadata>> {
unsafe { &*self.map.get() }
}
/// Get the map from the UnsafeCell as mutable map.
fn map_mut(&self) -> &mut BTreeMap<*const <Data::Slice as Slice>::Element, Entry<Data, Metadata>> {
unsafe { &mut *self.map.get() }
}
/// Find the last entry with start_ptr <= the given bound.
fn last_at_or_before(&self, bound: *const <Data::Slice as Slice>::Element) -> Option<&Entry<Data, Metadata>> {
let (_key, value) = self.map().range((Unbounded, Included(bound))).next_back()?;
Some(&value)
}
/// Find the last entry with start_ptr < the given bound.
fn last_before(&self, bound: *const <Data::Slice as Slice>::Element) -> Option<&Entry<Data, Metadata>> {
let (_key, value) = self.map().range((Unbounded, Excluded(bound))).next_back()?;
Some(&value)
}
/// Get the tracking entry for a slice.
fn get_entry(&self, data: &Data::Slice) -> Option<&Entry<Data, Metadata>> {
// Empty slices can not be tracked.
// They can't be distuingished from str_a[end..end] or str_b[0..0],
// if str_a and str_b directly follow eachother in memory.
if data.is_empty() {
return None;
}
// Get the last element where start_ptr <= data.start_ptr
let entry = self.last_at_or_before(data.start_ptr())?;
if data.end_ptr() <= entry.data.borrow_slice().end_ptr() {
Some(entry)
} else {
None
}
}
/// Check if the given slice has overlap with anything in the slice tracker.
fn has_overlap(&self, data: &Data::Slice) -> bool {
// Empty slices can't overlap with anything, even if their start pointer is tracked.
if data.is_empty() {
return false;
}
// Last element with start < data.end_ptr()
let conflict = match self.last_before(data.end_ptr()) {
None => return false,
Some(entry) => entry,
};
// If conflict doesn't end before data starts, it's a conflict.
// Though end is one-past the end, so end == start is also okay.
conflict.data.borrow_slice().end_ptr() > data.start_ptr()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_insert() {
let pool = SliceTracker::<&str, ()>::default();
let data = "aap noot mies";
let len = data.len();
assert_eq!(pool.is_tracked(data), false);
// Cant insert empty string slices.
assert!(pool.insert("", ()).is_err());
assert!(pool.insert(&data[3..3], ()).is_err());
// Can insert non-empty str only once.
let tracked = pool.insert(data, ()).unwrap();
assert!(pool.insert(data, ()).is_err());
assert!(pool.is_tracked(data));
// is_tracked says no to empty sub-slices.
assert!(!pool.is_tracked(&data[0..0]));
assert!(!pool.is_tracked(&data[1..1]));
assert!(!pool.is_tracked(&data[len..len]));
// non-empty sub-slices give the whole slice back.
assert!(std::ptr::eq(data, tracked));
assert!(std::ptr::eq(data, pool.whole_slice(data).unwrap()));
assert!(std::ptr::eq(data, pool.whole_slice(&data[0..1]).unwrap()));
assert!(std::ptr::eq(data, pool.whole_slice(&data[4..8]).unwrap()));
assert!(std::ptr::eq(data, pool.whole_slice(&data[len - 1..len]).unwrap()));
assert!(std::ptr::eq(data, pool.whole_slice(&data[..]).unwrap()));
}
#[test]
fn test_insert_part() {
let pool = SliceTracker::<&str, ()>::default();
let data = "aap noot mies";
let noot = &data[4..8];
assert_eq!(noot, "noot");
// Adding the subslice to the pool doesn't make the whole str tracked.
let tracked = pool.insert(noot, ()).unwrap();
assert!(pool.is_tracked(noot));
assert!(pool.is_tracked(&data[4..8]));
assert!(!pool.is_tracked(data));
assert!(!pool.is_tracked(&data[..4]));
assert!(!pool.is_tracked(&data[8..]));
// But we can't track the whole slice anymore now.
assert!(pool.insert(data, ()).is_err());
// Subslices from the original str in the right range give the whole tracked subslice.
assert!(std::ptr::eq(noot, tracked));
assert!(std::ptr::eq(noot, pool.whole_slice(noot).unwrap()));
assert!(std::ptr::eq(noot, pool.whole_slice(&data[4..8]).unwrap()));
assert!(std::ptr::eq(noot, pool.whole_slice(&data[4..7]).unwrap()));
assert!(std::ptr::eq(noot, pool.whole_slice(&data[5..8]).unwrap()));
assert!(std::ptr::eq(noot, pool.whole_slice(&data[5..7]).unwrap()));
}
}
|
use super::Canvas;
use crate::{
terminal::SIZE,
util::{Color, Point, Size},
};
mod bucket;
impl Canvas {
/// Sets the terminal cursor accordingly and then draws a block.
pub fn block_at(&mut self, point: Point, color: Color) {
self.terminal.set_cursor(Point {
y: point.y / 2,
..point
});
self.half_block(point, color);
}
/// Draws a block.
pub fn block(&mut self, point: Point, color: Color) {
self.terminal.set_foreground_color(color);
self.block_at(point, color);
self.terminal.reset_colors();
}
/// Sets the terminal cursor accordingly and then efficiently draws multiple blocks in a row.
pub fn blocks_at(&mut self, point: Point, color: Color, count: SIZE) {
self.terminal.set_cursor(Point {
y: point.y / 2,
..point
});
for index in 0..count {
self.half_block(
Point {
x: point.x + index,
..point
},
color,
);
}
}
/// Efficiently draws multiple blocks in a row.
pub fn blocks(&mut self, point: Point, color: Color, count: SIZE) {
self.terminal.set_foreground_color(color);
self.blocks_at(point, color, count);
self.terminal.reset_colors();
}
pub fn line(
&self,
x1: SIZE,
y1: SIZE,
x2: SIZE,
y2: SIZE,
) -> bracket_geometry::prelude::Bresenham {
use bracket_geometry::prelude::{Bresenham, Point};
Bresenham::new(Point::new(x1, y1), Point::new(x2, y2))
}
pub fn brush(&mut self, point: Point, color: Color, size: SIZE) {
match size {
1 => {
self.terminal.set_foreground_color(color);
self.block_at(point, color); // Middle dot
}
2 => {
self.terminal.set_foreground_color(color);
self.block_at(
// Left dot
Point {
y: point.y - 1,
..point
},
color,
);
self.block_at(
// Upper dot
Point {
x: point.x - 1,
..point
},
color,
);
self.block_at(point, color); // Middle dot
self.block_at(
// Lower dot
Point {
x: point.x + 1,
..point
},
color,
);
self.block_at(
// Right dot
Point {
y: point.y + 1,
..point
},
color,
);
}
_ => {
self.circle(point, color, size - 1);
return; // `circle` has already reset the color
}
}
self.terminal.reset_colors();
}
pub fn quill(&mut self, point: Point, color: Color, size: SIZE) {
self.terminal.set_foreground_color(color);
for size in 0..=size {
if size % 2 == 0 {
self.block_at(
Point {
y: point.y + size / 2,
..point
},
color,
);
} else {
self.block_at(
Point {
y: point.y - size / 2,
..point
},
color,
);
}
}
self.terminal.reset_colors();
}
}
#[derive(Clone)]
pub enum Tool {
Brush,
Quill,
Rectangle,
Bucket,
}
impl Default for Tool {
fn default() -> Self {
Self::Brush
}
}
impl Tool {
pub fn draw(
&self,
canvas: &mut Canvas,
point: Point,
last_point: Option<Point>,
color: Color,
tool_size: SIZE,
) {
if let Some(last_point) = last_point {
if last_point == point {
self.r#use(canvas, point, color, tool_size);
} else {
for draw_point in canvas.line(last_point.x, last_point.y, point.x, point.y) {
let draw_point = Point {
x: draw_point.x as SIZE,
y: draw_point.y as SIZE,
};
self.r#use(canvas, draw_point, color, tool_size);
}
}
} else {
self.r#use(canvas, point, color, tool_size);
}
}
fn r#use(&self, canvas: &mut Canvas, point: Point, color: Color, size: SIZE) {
match self {
Tool::Brush => {
canvas.brush(point, color, size);
}
Tool::Quill => {
canvas.quill(point, color, size);
}
Tool::Rectangle => {
canvas.hollow_rectangle(
point,
Size {
width: size,
height: size,
},
color,
);
}
Tool::Bucket => {
canvas.bucket(point, color);
}
}
}
}
|
extern crate dotenv;
use crate::errors::ServiceError;
use crate::graphql::input::movie::MovieFilter;
use crate::graphql::Context;
use crate::models::movie::Movie;
use diesel::prelude::*;
pub fn movies(context: &Context, filter: Option<MovieFilter>) -> Result<Vec<Movie>, ServiceError> {
use crate::schema::movies::dsl::*;
let conn: &MysqlConnection = &context.db.lock().unwrap();
if context.user.is_none() {
return Err(ServiceError::Unauthorized);
}
let mut query = movies.into_boxed();
if let Some(filter) = filter {
if let Some(id_filter) = filter.id {
query = query.filter(id.eq(id_filter));
}
if let Some(name_filter) = filter.name {
query = query.filter(name.like(format!("%{}%", name_filter)));
}
}
let movies_data = query.load::<Movie>(conn).expect("");
Ok(movies_data)
}
|
//! Provides the selection sort feature
/// Triggers one step of the selection sort
pub fn iterate_over_selection_sort(
array: &mut [u8; 50],
index: &mut usize,
)
{
let mut min = *index;
let start = *index + 1;
for i in start..50 {
if array[i] < array[min] {
min = i;
}
}
if min != *index {
array.swap(
*index,
min,
);
}
*index += 1;
}
|
use crate::*;
use std::collections::BTreeMap;
use std::sync::Arc;
use tracing;
const COUNT_PER_ROW: u32 = 20;
const SCATTER_SYMBOL_NOT_TESTED_YET: char = '.';
const SCATTER_SYMBOL_PASSED: char = 'O';
const SCATTER_SYMBOL_FAILED: char = 'X';
const SCATTER_SYMBOL_PREPARE_FAILED: char = '-';
const SCATTER_SYMBOL_HANDSHAKE_FAILED: char = 'H';
const SCATTER_SYMBOL_DISCONNECT_FAILED: char = 'D';
pub struct PingResultProcessorResultScatterLogger {
common_config: Arc<PingResultProcessorCommonConfig>,
ping_history: Vec<BTreeMap<u32, Vec<char>>>,
}
impl PingResultProcessorResultScatterLogger {
#[tracing::instrument(name = "Creating ping result result scatter logger", level = "debug")]
pub fn new(common_config: Arc<PingResultProcessorCommonConfig>) -> PingResultProcessorResultScatterLogger {
return PingResultProcessorResultScatterLogger { common_config, ping_history: vec![BTreeMap::new()] };
}
fn get_ping_history_position(&self, port: u32) -> (u32, usize) {
let row: u32 = (port / COUNT_PER_ROW) * COUNT_PER_ROW;
let index = port % COUNT_PER_ROW;
return (row, index as usize);
}
fn convert_result_hits_to_string(hits: &Vec<char>) -> String {
let mut s: String = String::new();
for index in 0..COUNT_PER_ROW {
s.push(hits[index as usize]);
if (index != COUNT_PER_ROW - 1) && ((index + 1) % 5 == 0) {
s.push(' ');
}
}
return s;
}
}
impl PingResultProcessor for PingResultProcessorResultScatterLogger {
fn name(&self) -> &'static str {
"ResultScatterLogger"
}
fn config(&self) -> &PingResultProcessorCommonConfig {
self.common_config.as_ref()
}
fn process_ping_result(&mut self, ping_result: &PingResult) {
if self.has_quiet_level(RNP_QUIET_LEVEL_NO_PING_SUMMARY) {
return;
}
// Skip warmup pings in analysis.
if ping_result.is_warmup() {
return;
}
let (row, index) = self.get_ping_history_position(ping_result.source().port() as u32);
let result = if let Some(e) = ping_result.error() {
match e {
PingClientError::PreparationFailed(_) => SCATTER_SYMBOL_PREPARE_FAILED,
PingClientError::PingFailed(_) => SCATTER_SYMBOL_FAILED,
}
} else if let Some(e) = ping_result.warning() {
match e {
PingClientWarning::AppHandshakeFailed(_) => SCATTER_SYMBOL_HANDSHAKE_FAILED,
PingClientWarning::DisconnectFailed(_) => SCATTER_SYMBOL_DISCONNECT_FAILED,
}
} else {
SCATTER_SYMBOL_PASSED
};
// Find the last iteration and update the result.
loop {
let last_iteration = self.ping_history.last_mut().expect("Ping history should always be non-empty.");
let last_iteration_results = last_iteration.entry(row).or_insert(vec![SCATTER_SYMBOL_NOT_TESTED_YET; COUNT_PER_ROW as usize]);
// If the source port is already tested in the last iteration, it means a new iteration is started,
// hence create a new iteration and update there.
if last_iteration_results[index] != SCATTER_SYMBOL_NOT_TESTED_YET {
self.ping_history.push(BTreeMap::new());
continue;
}
last_iteration_results[index] = result;
break;
}
}
fn rundown(&mut self) {
if self.has_quiet_level(RNP_QUIET_LEVEL_NO_PING_SUMMARY) {
return;
}
println!("\n=== Ping result scatter map ===");
println!(
"(\"{}\" = Ok, \"{}\" = Fail, \"{}\" = Not tested yet, \"{}\" = Preparation failed, \"{}\" = App handshake failed, \"{}\" = Disconnect failed)",
SCATTER_SYMBOL_PASSED, SCATTER_SYMBOL_FAILED, SCATTER_SYMBOL_NOT_TESTED_YET, SCATTER_SYMBOL_PREPARE_FAILED, SCATTER_SYMBOL_HANDSHAKE_FAILED, SCATTER_SYMBOL_DISCONNECT_FAILED
);
println!("\n{:>5} | {:>5} | {}", "Iter", "Src", "Results");
println!("{:>5} | {:>5} | ", "#", "Port");
println!("{:->6}|{:->8}-0---4-5---9-0---4-5---9-", "", "+");
for (iteration_index, iteration) in self.ping_history.iter().enumerate() {
for (port_bucket, result_hits) in iteration {
print!("{:>5} | {:>5} | ", iteration_index, port_bucket);
let result = PingResultProcessorResultScatterLogger::convert_result_hits_to_string(result_hits);
println!("{}", result);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn convert_result_info_to_string_should_work() {
let mut results =
vec![vec![SCATTER_SYMBOL_NOT_TESTED_YET; 20], vec![SCATTER_SYMBOL_NOT_TESTED_YET; 20], vec![SCATTER_SYMBOL_NOT_TESTED_YET; 20]];
results[1][0] = SCATTER_SYMBOL_PASSED;
results[2][1] = SCATTER_SYMBOL_FAILED;
results[2][2] = SCATTER_SYMBOL_PREPARE_FAILED;
results[2][3] = SCATTER_SYMBOL_HANDSHAKE_FAILED;
results[2][4] = SCATTER_SYMBOL_DISCONNECT_FAILED;
let formatted_results: Vec<String> =
results.into_iter().map(|x| PingResultProcessorResultScatterLogger::convert_result_hits_to_string(&x)).collect();
assert_eq!(vec!["..... ..... ..... .....", "O.... ..... ..... .....", ".X-HD ..... ..... .....",], formatted_results);
}
}
|
use test::res::module;
#[test]
pub fn load() {
unsafe { module::all_module() }.unwrap();
}
#[test]
pub fn verify_names() {
let module = unsafe { module::all_module() }.unwrap();
let (module_list, module_map, _) = module.destructure();
assert_eq!(module_list.len(), 1);
for module in module_list {
let module_index = module_map.get_index(module.get_name()).unwrap();
assert_eq!(module.get_index(), module_index);
}
}
|
use utils;
use std::collections::HashSet;
fn consecutive_quadratic_primes(a: i64, b: i64, primes: &HashSet<u64>) -> u64{
let mut n = 0;
let mut prime_candidate: i64 = n * n + a * n + b;
while (prime_candidate > 1) &primes.contains(&(prime_candidate as u64)){
n += 1;
prime_candidate = n * n + a * n + b;
}
n as u64
}
pub fn problem_027() -> i64 {
let n = 100000;
let max_a: i64 = 1000;
let max_b = 1000;
let mut primes = HashSet::new();
for &n in utils::prime_sieve(n).iter(){
primes.insert(n as u64);
}
// b must be prime and positive
let possible_b = utils::prime_sieve(max_b);
let mut max_consecutive_primes = 0;
let mut pair = (0, 0);
for &b in possible_b.iter() {
for a in (-1*max_a + 1)..max_a {
let n = consecutive_quadratic_primes(a, b as i64, &primes);
if n > max_consecutive_primes {
max_consecutive_primes = n;
pair = (a as i64, b as i64);
}
}
}
pair.0 * pair.1
}
#[cfg(test)]
mod test {
use super::*;
use test::Bencher;
#[test]
fn test_problem_027() {
let ans: i64= problem_027();
println!("Answer to Problem 27: {}", ans);
assert!(ans == -59231)
}
#[bench]
fn bench_problem_027(b: &mut Bencher) {
b.iter(|| problem_027());
}
}
|
//! symrs - As symbolic mathematics libary for Rust.
#![feature(box_syntax)]
#![feature(core_intrinsics)]
// Included Modules
pub mod core;
pub mod errors;
pub mod expressions;
// Re-export common modules.
pub use crate::core::Expression;
pub use crate::errors::*;
pub use crate::expressions::irreducibles::*;
pub use crate::expressions::operations::elementary::*;
|
fn returns_five() -> u8 {
5
}
fn main() {
// These parantheses create a block with a new scope and exp_var
// is expecting a value to be returned from that block.
let exp_var = {
let x = 12;
// omitting a semi-colon turns this into an
// expression from a statment. Unlike a function
// you can't use a return keyword.
x + 12
};
// if is an expression and not a statement in rust.
let if_else_var = if exp_var == 20 {
println!("Inside an if condition");
1
} else if exp_var == 24 {
println!("inside if else");
-1
} else {
println!("Inside an else condition");
0
};
println!("The value of if_else_var: {}", if_else_var);
println!("The value of exp_var: {:?}", exp_var);
let return_val = another_rogue_function(70) + returns_five();
println!("The returned val from the function: {}", return_val);
let x = 2;
println!("The value of x is {}", x);
// We are shadowing the variable and changing
// the value depending on the value of x before
// this. According to me this can be a source
// of confusion but it is useful for using the
// same variable name and mutating the type.
let x = x + 5;
println!("The value of x is {}", x);
// if this variable is not annotated with a type
// then it will throw an error because it cannot
// infer it.
let y: u32 = "34".parse().expect("Not a number");
// Scalar types
// Types like signed and unsigned integers, floats,
// chars, bool etc.
let z: i32 = -33;
println!(
"The unsigned value is: {} while the signed value is: {}",
y, z
);
// Tuple is a type of compound type
// A tuple can have elements of different types
let a_tuple_type: (u32, f64, char) = (500, 65.2, 'a');
// tuple supports destructuring
let (first, second, third) = a_tuple_type;
println!(
"The destructured vars are: {}, {}, {}",
first, second, third
);
// A certain value in the tuple can be accessed
// using the (.) operator followed by the index
// of that value.
let five_hundred = a_tuple_type.0;
println!("The first value in a_tuple_type: {}", five_hundred);
// An array type is also a compound type but it
// only allows for homogenous types in the array.
// Arrays are allocated on stack. If you need a
// collection that grows/shrinks, you need a vector.
let first_array: [u8; 4] = [1, 2, 3, 4];
// Need to include :? inside the formatter parens to print an array.
// TODO: Need to find why we need to do that.
println!("The first element in the array is: {:?}", first_array);
}
fn another_rogue_function(number: u8) -> u8 {
println!("I am a rogue function that prints whatever it wants");
println!(
"and oh yeah! I print the number that's passed to me: {}",
number
);
42
}
|
//! urot13.rs
//!
//! Perform a Unicode-aware rot13 transformation.
//!
//! last update: 2016-09-25
//!
//! This program manages to perform rot13 on a large number of precomposed
//! Unicode characters by decomposing said character into a base character
//! and a series of combining characters, rot13ing the base character, and
//! writing out the new, rotated base character followed by the series of
//! combining characters.
use std::io;
use std::io::BufRead;
use std::collections::HashMap;
/// Contains the raw data about decomposable Unicode characters.
mod unidata;
/// Unicode code points are represented internally as u32s. These two
/// functions translate between u32s and char primitives.
///
fn ch2code(c: char) -> u32 { c as u32 }
fn code2ch(n: u32) -> char { std::char::from_u32(n).unwrap() }
/// Any given Unicode character can be either atomic or decomposable, and
/// the program needs to deal with those cases differently
///
enum Unichar<'a> {
Single(u32),
Multi(&'a unidata::Multichar<'a>)
}
/// The lower end of each range of code points that could possibly be rot13'd.
///
static RANGES : [u32; 12] = [
0x0041, // A
0x0061, // a
0x249c, // parenthesized latin small letter a
0x24b6, // circled latin capital letter a
0x24d0, // circled latin small letter a
0xff21, // fullwidth latin capital letter a
0xff41, // fullwidth latin small letter a
0x1f110, // parenthesized latin capital letter a
0x1f130, // squared latin capital letter a
0x1f150, // negative circled latin capital letter a
0x1f170, // negative squared latin capital letter a
0x1f1e6 // regional indicator symbol letter a
];
/// If a code point falls in a rotatable range, do so, otherwise just
/// pass it through unchanged.
///
fn range_rotate(n: u32) -> u32 {
for &b in &RANGES {
if n < b {
return n;
} else if n < b + 26 {
return ((n - b + 13) % 26) + b;
}
}
n
}
/// If the character at code point n decomposes, return an appropriate
/// unidata::Multichar, else just the single code point.
///
/// The dat argument is a reference to the hash containing Unicode
/// decomposition data (as returned by unidata::generate_hash()).
///
fn decompose<'a>(
n: u32,
dat: &'a HashMap<u32, unidata::Multichar<'a>>
) -> Unichar<'a>
{
match dat.get(&n) {
Some(x) => Unichar::Multi(x),
None => Unichar::Single(n)
}
}
/// Return a new String containing the urot13'd text from s.
///
/// The dat argument is a reference to the hash containing Unicode
/// decomposition data (as returned by unidata::generate_hash()).
///
fn urot13(
s: &str,
dat: &HashMap<u32, unidata::Multichar>
) -> String
{
let mut rval = String::new();
for c in s.chars() {
match decompose(ch2code(c), dat) {
Unichar::Single(n) => { rval.push(code2ch(range_rotate(n))) },
Unichar::Multi(mc) => {
rval.push(code2ch(range_rotate(mc.base)));
for &n in mc.rest { rval.push(code2ch(n)); }
},
}
}
rval
}
/// Do the thing.
///
fn main() {
let stdin = io::stdin();
let unidat = unidata::generate_hash();
for line in stdin.lock().lines() {
println!("{}", urot13(&line.unwrap(), &unidat));
}
}
|
use std::io::{BufRead, Read};
// Constant declarations
pub const TAB: char = '\t';
pub const NEW_LINE: char = '\n';
pub const SPACE: char = ' ';
#[derive(Debug, PartialEq, Eq)]
enum Ops {
ADD,
SUB,
MUL,
DIV,
INVALID,
}
impl From<char> for Ops {
fn from(c: char) -> Self {
match c {
'+' => Ops::ADD,
'-' => Ops::SUB,
'*' => Ops::MUL,
'/' => Ops::DIV,
_ => Ops::INVALID,
}
}
}
/// Cradle contains the lookahead character
/// and Input that implements Read trait
/// This way it helps testing with dependency injection
pub struct Cradle<R> {
/// Lookahead character
pub look: char,
/// Input reader
pub input: R,
}
impl<R: BufRead> Cradle<R> {
pub fn new(input: R) -> Self {
let mut cradle = Cradle { look: '2', input };
cradle.look = cradle.get_char();
cradle.skip_white();
cradle
}
/// Get character
pub fn get_char(&mut self) -> char {
// TODO: don't use unwrap
self.input
.by_ref()
.bytes()
.next()
.map(|b| b.ok().unwrap() as char)
.unwrap()
}
/// Skip over leading White Space
pub fn skip_white(&mut self) {
while self.is_white() {
self.look = self.get_char();
}
}
/// Returns true if Lookahead character is TAB or SPACE
pub fn is_white(&mut self) -> bool {
[TAB, SPACE].iter().any(|w| *w == self.look)
}
/// Match a specific input character with Lookahead character
///
/// If it does not match, it will panic
pub fn match_char(&mut self, x: char) {
if self.look != x {
expected(&x.to_string());
}
self.look = self.get_char();
self.skip_white();
}
/// Get an Identifier
pub fn get_name(&mut self) -> String {
if !self.look.is_alphabetic() {
expected("Name");
}
let mut token = String::new();
while self.look.is_ascii_alphanumeric() {
let look_upcase = self.look.to_ascii_uppercase();
token.push(look_upcase);
self.look = self.get_char();
}
self.skip_white();
token
}
/// Get a Number
pub fn get_num(&mut self) -> String {
if !self.look.is_ascii_digit() {
expected("Integer");
}
let mut value = String::new();
while self.look.is_ascii_digit() {
value.push(self.look);
self.look = self.get_char();
}
self.skip_white();
value
}
/// Output a string with Tab
pub fn emit(&mut self, s: &str) {
print!("{}", TAB.to_string() + s);
}
/// Output a string with Tab and CRLF
pub fn emitln(&mut self, s: &str) {
self.emit(s);
println!();
}
/// Check if lookahead character is Mulop: * or /
pub fn is_mulop(&mut self) -> bool {
let ops = vec![Ops::DIV, Ops::MUL];
ops.iter().any(|op| *op == Ops::from(self.look))
}
/// Check if lookahead character is Addop: + or -
pub fn is_addop(&mut self) -> bool {
let ops = vec![Ops::ADD, Ops::SUB];
ops.iter().any(|val| *val == Ops::from(self.look))
}
/// Parse and Translate a Math Expression
///
/// 1+2
/// or 4-3
/// or, in general, <term> +/- <term>
///
/// <expression> ::= <term> [<addop> <term>]*
///
pub fn expression(&mut self) {
if self.is_addop() {
self.emitln("CLR D0");
} else {
self.term();
}
while self.is_addop() {
self.emitln("MOVE D0,-(SP)");
match Ops::from(self.look) {
Ops::ADD => {
self.add();
}
Ops::SUB => {
self.subtract();
}
_ => {
expected("Addop");
}
}
}
}
/// Parse and Translate an Assignment statement
pub fn assignment(&mut self) {
let name = self.get_name();
self.match_char('=');
self.expression();
self.emitln(&format!("LEA {}(PC),A0", name));
self.emitln(&"MOVE D0,(A0)");
}
/// Represent <term>
///
/// <mulop> -> *, /
///
/// <term> ::= <factor> [<mulop> <factor>]*
pub fn term(&mut self) {
self.factor();
while self.is_mulop() {
self.emitln("MOVE D0,-(SP)");
match Ops::from(self.look) {
Ops::MUL => {
self.multiply();
}
Ops::DIV => {
self.divide();
}
_ => {
expected("Mulop");
}
}
}
}
/// Represent <factor>
///
/// <factor> ::= <number> | (<expression>)
///
/// This supports parenthesis, like (2+3)/(6*2)
///
/// We can support variables also, i.e b * b + 4 * a * c:
/// <factor> ::= <number> | (<expression>) | <variable>
pub fn factor(&mut self) {
if self.look == '(' {
self.match_char('(');
self.expression();
self.match_char(')');
} else if self.look.is_alphabetic() {
self.ident();
} else {
let num = self.get_num();
self.emitln(&format!("MOVE #{},D0", num));
}
}
/// Deal with variable and function calls
pub fn ident(&mut self) {
let name = self.get_name();
if self.look == '(' {
self.match_char('(');
self.match_char(')');
self.emitln(&format!("BSR {}", name));
} else {
self.emitln(&format!("MOVE {}(PC),D0", name));
}
}
/// Recognize and Translate Multiply
pub fn multiply(&mut self) {
self.match_char('*');
self.factor();
self.emitln("MULS (SP)+,D0");
}
/// Recognize and Translate Divide
pub fn divide(&mut self) {
self.match_char('/');
self.factor();
self.emitln("MOVE (SP)+,D1");
self.emitln("DIVS D1,D0");
}
/// Recognize and Translate Add
pub fn add(&mut self) {
self.match_char('+');
self.term();
self.emitln("ADD (SP)+,D0");
}
/// Recognize and Translate Subtract
pub fn subtract(&mut self) {
self.match_char('-');
self.term();
self.emitln("SUB (SP)+,D0");
self.emitln("NEG D0");
}
}
pub fn expected(x: &str) {
panic!("{} Expected", x);
}
#[cfg(test)]
mod tests {
use super::*;
// TODO: assert with generated machine code
#[test]
fn test_valid_expression() {
let input = b"2+3-4 ";
let mut c = Cradle::new(&input[..]);
c.expression();
}
#[test]
fn test_invalid_expression() {
let input = b"2aa ";
let mut c = Cradle::new(&input[..]);
c.expression();
}
#[test]
fn test_single_expression() {
let input = b"1 ";
let mut c = Cradle::new(&input[..]);
c.expression();
}
#[test]
fn test_with_mulops() {
let input = b"2+3*5-6/3 ";
let mut c = Cradle::new(&input[..]);
c.expression();
}
#[test]
fn test_with_paren() {
let input = b"(((2+3)*5)-6)/3 ";
let mut c = Cradle::new(&input[..]);
c.expression();
}
#[test]
fn test_unary_minus() {
let input = b"-1 ";
let mut c = Cradle::new(&input[..]);
c.expression();
}
#[test]
fn test_with_variables() {
let input = b"b-1+a*2+(b/c) ";
let mut c = Cradle::new(&input[..]);
c.expression();
}
#[test]
fn test_func_identifier() {
let input = b"a+2*x() ";
let mut c = Cradle::new(&input[..]);
c.expression();
}
#[test]
fn test_assignment() {
let input = b"b=2+a*3/2-b*(4/6) ";
let mut c = Cradle::new(&input[..]);
c.assignment();
}
#[test]
fn test_tokens_skip() {
let input = b"variable = 2 * 3 / (function() + func()) * (x()/2)\n";
let mut c = Cradle::new(&input[..]);
c.assignment();
if c.look != NEW_LINE {
expected("NEW_LINE");
}
}
}
|
use hyper::{Body, Response};
use nails::error::NailsError;
use nails::Preroute;
use serde::Serialize;
use crate::context::AppCtx;
#[derive(Debug, Preroute)]
#[nails(path = "/api/articles")]
pub(crate) struct ListArticlesRequest {
tag: Option<String>,
author: Option<String>,
favorited: Option<String>,
limit: Option<i32>,
offset: Option<i32>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ListArticlesResponseBody {
articles: Vec<Article>,
articles_count: u64,
}
pub(crate) async fn list_articles(
_ctx: AppCtx,
_req: ListArticlesRequest,
) -> Result<Response<Body>, NailsError> {
let articles = vec![Article {
slug: String::from("slug"),
title: String::from("title"),
description: String::from("description"),
body: String::from("body"),
tag_list: vec![String::from("tag2"), String::from("tag3")],
created_at: String::from("2019-07-14T19:07:00+0900"),
updated_at: String::from("2019-07-14T19:07:00+0900"),
favorited: false,
favorites_count: 0,
author: Profile {
username: String::from("username"),
bio: String::from("bio"),
image: String::from("image"),
following: false,
},
}];
let body = ListArticlesResponseBody {
articles_count: articles.len() as u64,
articles,
};
Ok(super::json_response(&body))
}
#[derive(Debug, Preroute)]
#[nails(path = "/api/articles/feed")]
pub(crate) struct ListFeedArticlesRequest {
limit: Option<u32>,
offset: Option<u32>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ListFeedArticlesResponseBody {
articles: Vec<Article>,
articles_count: u64,
}
pub(crate) async fn list_feed_articles(
_ctx: AppCtx,
_req: ListFeedArticlesRequest,
) -> Result<Response<Body>, NailsError> {
let articles = vec![Article {
slug: String::from("slug"),
title: String::from("title"),
description: String::from("description"),
body: String::from("body"),
tag_list: vec![String::from("tag2"), String::from("tag3")],
created_at: String::from("2019-07-14T19:07:00+0900"),
updated_at: String::from("2019-07-14T19:07:00+0900"),
favorited: false,
favorites_count: 0,
author: Profile {
username: String::from("username"),
bio: String::from("bio"),
image: String::from("image"),
following: false,
},
}];
let body = ListFeedArticlesResponseBody {
articles_count: articles.len() as u64,
articles,
};
Ok(super::json_response(&body))
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Article {
slug: String,
title: String,
description: String,
body: String,
tag_list: Vec<String>,
created_at: String, // TODO: DateTime
updated_at: String, // TODO: DateTime
favorited: bool,
favorites_count: u64,
author: Profile,
}
#[derive(Debug, Serialize)]
pub(crate) struct Profile {
username: String,
bio: String,
image: String,
following: bool,
}
|
#![macro_use]
//! Registers a function to be called before main (if an executable) or when loaded (if a dynamic
//! library).
//! **Using this is a bad idea.** You can do this in a way that isn't abysmally fragile.
//!
//! Example
//! =======
//!
//! ```
//! # #[macro_use] extern crate constructor;
//! pub static mut X: usize = 0;
//!
//! extern fn init() {
//! unsafe { X = 5; }
//! }
//! constructor! { init }
//!
//!
//! fn main() {
//! assert_eq!(unsafe { X }, 5);
//! }
//! ```
//!
//! Caveats
//! =======
//! This isn't exactly portable, though the implementation is quite simple.
//!
//! Doing anything particularly complicated, such IO or loading libraries, may cause problems
//! on Windows. (?)
//!
//! Every parent module must be `pub`lic. If it is not, then it will be
//! stripped out by `--release`. At least the compiler gives a helpful warning.
//!
//!
//!
//! Beware, for some say that these techniques can unleash a terrible evil.
//! [lazy_static](https://crates.io/crates/lazy_static) may be a more appropriate tool.
#[macro_export]
macro_rules! constructor {
($($FN:ident),*) => {
$(pub mod $FN {
#![allow(non_snake_case)]
#![allow(dead_code)]
#![allow(non_upper_case_globals)]
#![deny(private_no_mangle_statics /* >>> constructor must be used from a pub mod <<< */)]
// (The comment above is to make the error message more meaningful.)
// http://stackoverflow.com/questions/35428834/how-to-specify-which-elf-section-to-use-in-a-rust-dylib
// https://msdn.microsoft.com/en-us/library/bb918180.aspx
// Help given by WindowsBunny!
#[cfg(target_os = "linux")]
#[link_section = ".ctors"]
#[no_mangle]
pub static $FN: extern fn() = super::$FN;
// FIXME: macos untested
#[cfg(target_os = "macos")]
#[link_section = "__DATA,__mod_init_func"]
#[no_mangle]
pub static $FN: extern fn() = super::$FN;
// FIXME: windows untested; may require something more complicated for certain target
// triples?
#[cfg(target_os = "windows")]
#[link_section = ".CRT$XCU"]
#[no_mangle]
pub static $FN: extern fn() = super::$FN;
// We could also just ignore cfg(target_os) & have 1 item, but this way we'll have a compilation error if we don't know `target_os`.
})*
};
}
#[cfg(test)]
pub mod test {
static mut BUNNY: &'static str = "i'm just a cute li'l bunny!\nand i wont hurt nobody!!\n🐰";
#[test]
fn bunny_is_fluffy() {
println!("{}", unsafe { BUNNY });
}
pub static mut RAN: bool = false;
extern "C" fn set_ran() {
unsafe { RAN = true }
}
constructor! { set_ran }
#[test]
fn works() {
assert!(unsafe { RAN });
}
extern crate zalgo;
constructor! { corrupt_bunny }
pub extern "C" fn corrupt_bunny() {
unsafe {
use self::zalgo::*;
let mr_bun = gen(BUNNY, false, false, true, ZalgoSize::None);
let red = "\x1b[31m";
let reset = "\x1b[0m";
let mr_bun = format!("{}{}{}", red, mr_bun, reset);
use std::mem::{transmute, forget};
{
let mr_bun: &str = &mr_bun;
BUNNY = transmute(mr_bun);
}
forget(mr_bun); // u din't see nuffin'
}
// ... okay there's probably a terminal somewhere that does a decent job of this.
}
}
|
pub use super::blob::{Blob, BlobBlockType, BlockList, BlockListType};
pub use super::container::PublicAccess;
pub use crate::blob::clients::{
AsBlobClient, AsBlobLeaseClient, AsContainerClient, AsContainerLeaseClient, BlobClient,
BlobLeaseClient, ContainerClient, ContainerLeaseClient,
};
pub use crate::{
AccessTier, BlobContentMD5, BlobVersioning, BlockId, ConditionAppendPosition, ConditionMaxSize,
DeleteSnapshotsMethod, Hash, RehydratePriority, Snapshot, StoredAccessPolicy,
StoredAccessPolicyList, VersionId,
};
|
pub mod sqlite_database_cleaner;
pub mod util;
pub use util::*;
use apllodb_test_support::setup::setup_test_logger;
/// general test setup sequence
pub fn test_setup() {
setup_test_logger();
}
|
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_9_A
fn main() {
let mut target_word = String::new();
std::io::stdin().read_line(&mut target_word).unwrap();
let target_word = String::from(target_word.trim().to_lowercase());
let mut count = 0;
loop {
let mut buf = String::new();
std::io::stdin().read_line(&mut buf).unwrap();
let words: Vec<_> = buf.trim().split_whitespace().collect();
if words[0] == "END_OF_TEXT" {
break;
}
for word in words {
if word.to_lowercase() == target_word {
count += 1;
}
}
}
println!("{}", count);
}
|
// q0019_remove_nth_node_from_end_of_list
struct Solution;
use crate::util::ListNode;
impl Solution {
pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {
let mut buf = vec![];
let mut node = head;
while let Some(l) = node {
buf.push(l.val);
node = l.next;
}
let mut ret = None;
let len = buf.len();
let mut count = 0;
for i in 1..=len {
count += 1;
if count == n {
continue;
}
ret = Some(Box::new(ListNode {
val: buf[len - i],
next: ret,
}))
}
ret
}
}
#[cfg(test)]
mod tests {
use super::Solution;
use crate::util::ListNode;
#[test]
fn it_works() {
assert_eq!(
Solution::remove_nth_from_end(
Some(Box::new(ListNode {
val: 1,
next: Some(Box::new(ListNode {
val: 2,
next: Some(Box::new(ListNode {
val: 3,
next: Some(Box::new(ListNode {
val: 4,
next: Some(Box::new(ListNode { val: 5, next: None }))
}))
}))
}))
})),
2
),
Some(Box::new(ListNode {
val: 1,
next: Some(Box::new(ListNode {
val: 2,
next: Some(Box::new(ListNode {
val: 3,
next: Some(Box::new(ListNode { val: 5, next: None }))
}))
}))
}))
)
}
}
|
use crate::models::*;
use crate::test::*;
use crate::service::*;
use crate::dao::*;
use serde::{Serialize, Deserialize};
use actix_web::{get, post, put, delete, web, Responder, HttpResponse, Scope};
pub fn user_scope() -> Scope{
web::scope("/user")
.service(get_user_by_email)
.service(create_new_user)
.service(delete_user)
.service(update_user)
}
#[get("/{email}")]
async fn get_user_by_email(path : web::Path<(String)>) -> impl Responder {
let user = ServiceUser::new().await.get_user(path.into_inner()).await;
match user {
Ok(answer) => {
let json_answer = serde_json::to_string(&answer).unwrap();
HttpResponse::Ok().content_type("application/json").body(json_answer)
}
Err(()) => {
HttpResponse::NotFound().body("")
}
}
}
#[post("/")]
async fn create_new_user(req: String) -> impl Responder {
let user : ReqUser = serde_json::from_str(req.as_str()).unwrap();
let answer = ServiceUser::new().await.create_user(user).await;
match answer {
Ok(()) => {
HttpResponse::Ok().content_type("application/json").body("user create")
}
Err(()) => {
HttpResponse::BadRequest().content_type("application/json").body("error")
}
}
}
#[delete("/{email}")]
async fn delete_user(path: web::Path<String>)-> impl Responder{
let email = path.into_inner();
let result = ServiceUser::new().await.delete_user(&email).await;
match result {
Ok(()) => {
HttpResponse::Ok().content_type("application/json").body(format!("delete {:?}", email))
}
Err(()) => {
HttpResponse::NotFound().body("error")
}
}
}
#[put("/{email}")]
async fn update_user(path: web::Path<String>)-> impl Responder{
HttpResponse::BadRequest().content_type("application/json").body("error")
}
|
// use std::io;
// use std::fmt::Display;
use rand::Rng;
fn main() {
println!("Hello, world!");
let lucky_number = rand::thread_rng().gen_range(1, 101);
println!("Lucky Number : {}",lucky_number);
}
|
use crate::player::PlayerMarker;
use crate::walls::{WallDeathMarker, WallMarker};
use crate::world::{
BounceMarker, CharType, DefaultSize, Force, Location, MaterialResource, ObjectMarker, Velocity,
};
use bevy::prelude::*;
use bevy::sprite::collide_aabb::{collide, Collision};
use rand::distributions::Uniform;
use rand::{thread_rng, Rng};
const BOUNCING_ENEMY_SIZE: f32 = 20f32;
const BOUNCING_ENEMY_VELOCITY: f32 = 225f32;
const TEAM: u8 = 1;
const HOMING_MINE_SIZE: f32 = 20f32;
const HOMING_MINE_FORCE: f32 = 125f32;
const MINE_HOME_DISTANCE: f32 = 250f32;
const MINE_SPIN_SPEED: f32 = std::f32::consts::PI * 2f32;
#[derive(Bundle)]
pub struct BouncingEnemyBundle {
marker: BounceMarker,
object_marker: ObjectMarker,
type_marker: CharType,
size: DefaultSize,
location: Location,
#[bundle]
sprite: SpriteBundle,
velocity: Velocity,
}
pub fn new_bouncing_enemy(material: Handle<ColorMaterial>, location: Vec2) -> BouncingEnemyBundle {
let sprite_bundle = SpriteBundle {
sprite: Sprite::new(Vec2::new(BOUNCING_ENEMY_SIZE, BOUNCING_ENEMY_SIZE)),
material: material.clone(),
..Default::default()
};
let uniform = Uniform::new(0f32, std::f32::consts::PI * 2f32);
let angle = thread_rng().sample(uniform);
let sin_cos = angle.sin_cos();
let bouncing_enemy_bundle = BouncingEnemyBundle {
marker: BounceMarker,
object_marker: ObjectMarker(TEAM),
type_marker: CharType::Enemy,
size: DefaultSize {
width: BOUNCING_ENEMY_SIZE,
height: BOUNCING_ENEMY_SIZE,
},
sprite: sprite_bundle,
velocity: Velocity(Vec2::new(
sin_cos.0 * BOUNCING_ENEMY_VELOCITY,
sin_cos.1 * BOUNCING_ENEMY_VELOCITY,
)),
location: Location(location),
};
bouncing_enemy_bundle
}
pub fn move_bouncing_enemy(
time: Res<Time>,
mut bouncing_enemy: Query<(&BounceMarker, &mut Location, &Velocity)>,
) {
let delta_seconds = time.delta_seconds();
for (_, mut location, velocity) in bouncing_enemy.iter_mut() {
let move_amt = velocity.0 * delta_seconds;
location.0.x += move_amt.x;
location.0.y += move_amt.y;
}
}
pub struct HomingMineMarker;
#[derive(Bundle)]
pub struct HomingMineBundle {
marker: HomingMineMarker,
obj_marker: ObjectMarker,
wall_death_marker: WallDeathMarker,
type_marker: CharType,
size: DefaultSize,
location: Location,
force: Force,
velocity: Velocity,
#[bundle]
sprite: SpriteBundle,
}
pub fn new_homing_mine(material: Handle<ColorMaterial>, location: Vec2) -> HomingMineBundle {
let sprite_bundle = SpriteBundle {
sprite: Sprite::new(Vec2::new(HOMING_MINE_SIZE, HOMING_MINE_SIZE)),
material: material.clone(),
..Default::default()
};
let homing_mine_bundle = HomingMineBundle {
marker: HomingMineMarker,
obj_marker: ObjectMarker(TEAM),
wall_death_marker: WallDeathMarker,
type_marker: CharType::Enemy,
size: DefaultSize {
width: HOMING_MINE_SIZE,
height: HOMING_MINE_SIZE,
},
location: Location(location),
force: Force(Vec2::default()),
velocity: Velocity(Vec2::default()),
sprite: sprite_bundle,
};
homing_mine_bundle
}
pub fn update_mines(
mut homing_mines: Query<(&HomingMineMarker, &Location, &mut Force)>,
mut player: Query<(&PlayerMarker, &Location)>,
) {
if let Ok((_, player_loc)) = player.single_mut() {
for (_, mine_loc, mut force) in homing_mines.iter_mut() {
if mine_loc.0.distance_squared(player_loc.0) < MINE_HOME_DISTANCE * MINE_HOME_DISTANCE {
force.0 = (player_loc.0 - mine_loc.0).normalize() * HOMING_MINE_FORCE;
}
}
}
}
pub fn homing_mine_spin(
time: Res<Time>,
mut homing_mines: Query<(&HomingMineMarker, &mut Transform)>,
) {
let delta_seconds = time.delta_seconds();
for (_, mut transform) in homing_mines.iter_mut() {
transform.rotate(Quat::from_rotation_z(delta_seconds * MINE_SPIN_SPEED));
}
}
|
use termion::cursor::*;
use crate::editor::Editor;
use crate::editor::Mode;
// TODO: Scrolling when traveling up or down
// TODO: Scrolling command history when moving up/down in command mode
impl Editor {
// TODO: Use cursor_pos function once
// https://github.com/ticki/termion/issues/136 is fixed
/// Get the current (0, 0)-based position of the cursor.
pub fn pos(&mut self) -> (usize, usize) {
// self.output.cursor_pos().unwrap()
(self.x, self.y)
}
/// Saves the cursor's current location.
pub fn save_pos(&mut self) {
let pos = self.pos();
self.saved_positions.push(pos);
}
/// Moves the cursor to the last saved location.
pub fn restore_pos(&mut self) {
if let Some((x, y)) = self.saved_positions.pop() {
self.goto(x, y)
};
}
// TODO: Check if x and y lie within the boundaries of the buffer
/// Set the position of the cursor.
///
/// This is (0, 0)-based cursor movement, instead of (1, 1)-based as termion
/// provides.
pub fn goto(&mut self, x: usize, y: usize) {
self.x = x;
self.y = y;
self.print(Goto(x as u16 + 1, y as u16 + 1));
}
/// Move the cursor left 'n' positions.
///
/// # Normal/Insert mode
///
/// If moving past the left edge: the cursor will move to the end of the
/// previous line if it exists, otherwise it will move to the origin.
/// Will move up multiple lines if needed.
///
/// # Command mode
///
/// Leftmost limit is the character after the initial `:` of the command
/// line.
pub fn left(&mut self, n: usize) {
let (x, y) = self.pos();
match self.mode {
Mode::Insert | Mode::Normal => {
if n <= x {
self.goto(x - n, y);
} else if y > 0 {
// Previous line exists, calculate leftover movement
let leftover = n - x - 1;
// Skip to previous line and move leftover amount
let end_of_prev_line = self.get_end_of_line(y - 1);
self.goto(end_of_prev_line, y - 1);
self.left(leftover);
} else {
self.goto(0, 0);
}
}
Mode::Command => {
if n < x {
self.goto(x - n, y);
} else {
self.goto(1, y);
}
}
}
}
/// Move the cursor right 'n' positions.
///
/// # Normal/Insert mode
///
/// If moving past the end of a line: the cursor will move to the beginning
/// of the next line if it exists, otherwise it will move to the end of the
/// file.
/// Will move down multiple lines if needed.
///
/// # Command mode
///
/// Doesn't allow rightward movement after reaching the end of the command.
pub fn right(&mut self, n: usize) {
let (x, y) = self.pos();
let end_of_current_line = self.get_end_of_line(y);
match self.mode {
Mode::Insert | Mode::Normal => {
if x + n <= end_of_current_line {
self.goto(x + n, y);
} else if y + 1 < self.buffer.len() {
// Next line exists, calculate leftover movement
let leftover = n - (end_of_current_line - x) - 1;
// Skip to next line and move leftover amount
self.goto(0, y + 1);
self.right(leftover);
} else {
self.goto(end_of_current_line, y);
}
}
Mode::Command => {
if x + n <= end_of_current_line {
self.goto(x + n, y);
} else {
self.goto(end_of_current_line, y);
}
}
}
}
// TODO: Word-moving commands
pub fn move_forward_word(&mut self) {}
pub fn move_back_word(&mut self) {}
pub fn move_end_of_word(&mut self) {}
/// Move the cursor up 'n' positions.
///
/// If moving to a line shorter than the current line, the cursor will jump
/// to the end of the shorter line.
pub fn up(&mut self, n: usize) {
match self.mode {
Mode::Insert | Mode::Normal => {
let (x, y) = self.pos();
// Don't move past the top of the terminal
if n <= y {
let end_of_above_line = self.get_end_of_line(y - n);
if x > end_of_above_line {
self.goto(end_of_above_line, y - n);
} else {
self.goto(x, y - n);
}
} else {
// Scroll if possible
}
}
Mode::Command => {
// Scroll up command history
}
}
}
/// Move the cursor down 'n' positions.
///
/// If moving to a line shorter than the current line, the cursor will jump
/// to the end of the shorter line.
pub fn down(&mut self, n: usize) {
match self.mode {
Mode::Insert | Mode::Normal => {
let (x, y) = self.pos();
// Don't move past the end of the buffer
if y + n < self.buffer.len() {
let end_of_below_line = self.get_end_of_line(y + n);
if x > end_of_below_line {
self.goto(end_of_below_line, y + n);
} else {
self.goto(x, y + n);
}
} else {
// Scroll if possible
}
}
Mode::Command => {
// Scroll down command history
}
}
}
/// Determine the ending position of a given line, depending on the current
/// mode.
///
/// For normal mode: last character of the line, unless the line is blank.
/// For insert mode: one beyond the last character of the line.
/// For command mode: one beyond the last character of the command.
fn get_end_of_line(&self, n: usize) -> usize {
if let Mode::Command = self.mode {
// Add 1 to account for the starting colon
return self.command.len() + 1;
}
let len = self.buffer[n].len();
match self.mode {
Mode::Normal if len == 0 => len,
Mode::Normal => len - 1,
Mode::Insert => len,
_ => unreachable!(),
}
}
}
|
use std::env;
use std::error::Error;
use std::fs::File;
mod account;
mod amount;
mod engine;
mod transaction;
mod transaction_row;
/// Helper function to parse and validate the required args
/// We expect one argument and this should be an .csv file.
fn get_file_name_to_process() -> Result<String, Box<dyn Error>> {
if let Some(file_name) = env::args().nth(1) {
match file_name.ends_with(".csv") {
true => Ok(file_name),
false => Err(From::from(format!(
"Invalid filename {}, expected an .csv file",
file_name
))),
}
} else {
Err(From::from("Expected 1 argument, but got none"))
}
}
fn get_reader_from_file(file_name: &str) -> Result<csv::Reader<File>, Box<dyn Error>> {
let reader = csv::ReaderBuilder::new()
.trim(csv::Trim::All)
.from_path(file_name)?;
Ok(reader)
}
fn main() -> Result<(), Box<dyn Error>> {
let file_name = get_file_name_to_process()?;
let reader = get_reader_from_file(&file_name)?;
let mut engine = engine::PaymentEngine::new();
engine.process_from_reader(reader)?;
engine.output_report();
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn input_1() -> Result<(), Box<dyn Error>> {
let reader = get_reader_from_file("./tests/input_1.csv")?;
let mut engine = engine::PaymentEngine::new();
engine.process_from_reader(reader)?;
let client_id: u16 = 1;
if let Some(client) = engine.accounts_by_client.get(&client_id) {
assert_eq!(client.locked, false);
assert_eq!(client.available, amount::Amount::from_input(1.5).value());
}
Ok(())
}
#[test]
fn input_disput() -> Result<(), Box<dyn Error>> {
let reader = get_reader_from_file("./tests/input_d.csv")?;
let mut engine = engine::PaymentEngine::new();
engine.process_from_reader(reader)?;
let client_id: u16 = 1;
if let Some(client) = engine.accounts_by_client.get(&client_id) {
assert_eq!(client.locked, false);
assert_eq!(client.available, amount::Amount::from_input(0.0).value());
assert_eq!(client.held, amount::Amount::from_input(1.5).value());
}
Ok(())
}
#[test]
fn input_resolve() -> Result<(), Box<dyn Error>> {
let reader = get_reader_from_file("./tests/input_r.csv")?;
let mut engine = engine::PaymentEngine::new();
engine.process_from_reader(reader)?;
let client_id: u16 = 1;
if let Some(client) = engine.accounts_by_client.get(&client_id) {
assert_eq!(client.locked, false);
assert_eq!(client.available, amount::Amount::from_input(1.5).value());
assert_eq!(client.held, amount::Amount::from_input(0.0).value());
}
Ok(())
}
#[test]
fn input_widrawal() -> Result<(), Box<dyn Error>> {
let reader = get_reader_from_file("./tests/input_w.csv")?;
let mut engine = engine::PaymentEngine::new();
engine.process_from_reader(reader)?;
let client_id: u16 = 2;
if let Some(client) = engine.accounts_by_client.get(&client_id) {
assert_eq!(client.locked, false);
assert_eq!(client.available, amount::Amount::from_input(0.9988).value());
assert_eq!(client.held, amount::Amount::from_input(0.0).value());
}
Ok(())
}
#[test]
fn input_lock() -> Result<(), Box<dyn Error>> {
let reader = get_reader_from_file("./tests/input_lock.csv")?;
let mut engine = engine::PaymentEngine::new();
engine.process_from_reader(reader)?;
let client_id: u16 = 2;
if let Some(client) = engine.accounts_by_client.get(&client_id) {
assert_eq!(client.locked, true);
assert_eq!(client.available, amount::Amount::from_input(0.0).value());
assert_eq!(client.held, amount::Amount::from_input(0.0).value());
}
Ok(())
}
}
|
#[macro_use]
extern crate failure;
pub mod error;
pub mod secp256k1;
|
use core::mem;
#[cfg(not(feature = "std"))]
use alloc::boxed::Box;
// *************************************************************************************************
// Record
// *************************************************************************************************
/// A wrapper type that prepends an instance of `T` with an instance of the
/// [`Header`][Reclaim::Header] type associated to the specified
/// [`Reclaimer`][Reclaim].
///
/// This struct guarantees the layout of its fields to match the declaration
/// order, i.e., the `header` always precedes the `data`.
#[repr(C)]
pub(crate) struct Record<H, T: ?Sized> {
/// The record's header
pub header: H,
/// The wrapped record data itself.
pub data: T,
}
/********** impl inherent *************************************************************************/
impl<H, T: ?Sized> Record<H, T> {
/// [`Record`] is marked as `#[repr(c)]` and hence the offset of the header
/// field is always `0`.
const HEADER_OFFSET: usize = 0;
#[inline]
pub unsafe fn record_from_data(data: *mut T) -> *mut Self {
// pointer is cast to a pointer to an unsized `Record<H, dyn ..>`, but
// in fact still points at the record's `data` field
let ptr = data as *mut Self;
// header is the "correct" thin pointer, since the header field is at
// offset 0
let header = Self::header_from_data(data) as *mut u8;
ptr.set_ptr_value(header)
}
/// Returns the pointer to the [`header`][Record::header] field of the
/// [`Record`] containing the value pointed to by `data`.
///
/// # Safety
///
/// The `data` pointer must be a valid, un-aliased pointer to an instance of
/// `T` that was constructed as part of a [`Record`].
#[inline]
pub unsafe fn header_from_data(data: *const T) -> *mut H {
// TODO: use align_of_val_raw once it becomes stable
let data_align = mem::align_of_val(&*data);
(data as *mut u8).sub(Self::data_offset(data_align)).cast()
}
/// Returns the offset in bytes from the [`Record`] to its `data` field for
/// a given `data_align` of that field's type (of which the concrete type
/// may not be known).
#[inline]
const fn data_offset(data_align: usize) -> usize {
// this matches the layout algorithm used by `rustc` for C-like structs.
let offset = Self::HEADER_OFFSET + mem::size_of::<H>();
offset + offset.wrapping_neg() % data_align
}
}
#[cfg(test)]
mod tests {
use std::mem;
use std::sync::atomic::{AtomicUsize, Ordering};
type Record<T> = super::Record<usize, T>;
trait TypeName {
fn type_name(&self) -> &'static str;
}
struct DropCounting<'a>(&'a AtomicUsize);
impl Drop for DropCounting<'_> {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::Relaxed);
}
}
impl TypeName for DropCounting<'_> {
fn type_name(&self) -> &'static str {
"DropCounting"
}
}
impl TypeName for [u8; 128] {
fn type_name(&self) -> &'static str {
"[u8; 128]"
}
}
#[test]
fn dyn_trait_record() {
const MAGIC1: usize = 0xDEAD_BEEF;
const MAGIC2: usize = 0xCAFE_BABE;
static COUNT: AtomicUsize = AtomicUsize::new(0);
let counting = Box::leak(Box::new(Record { header: MAGIC1, data: DropCounting(&COUNT) }))
as &mut Record<dyn TypeName>;
let counting = &mut counting.data as *mut dyn TypeName;
let array = Box::leak(Box::new(Record { header: MAGIC2, data: [0u8; 128] }))
as &mut Record<dyn TypeName>;
let array = &mut array.data as *mut dyn TypeName;
unsafe {
let counting = Box::from_raw(Record::record_from_data(counting));
assert_eq!(counting.header, MAGIC1);
assert_eq!(counting.data.type_name(), "DropCounting");
assert_eq!(mem::size_of_val(&counting.data), mem::size_of::<DropCounting<'_>>());
let array = Box::from_raw(Record::record_from_data(array));
assert_eq!(array.header, MAGIC2);
assert_eq!(array.data.type_name(), "[u8; 128]");
assert_eq!(mem::size_of_val(&array.data), mem::size_of::<[u8; 128]>());
}
assert_eq!(COUNT.load(Ordering::Relaxed), 1);
}
}
|
pub fn is_pangram(string: &str) -> bool {
let mut alphabet = "abcdefghijklmnopqrstuvwxyz".chars();
let string = string.to_lowercase();
alphabet.all(|x| string.contains(x))
} |
/*
* Copyright (C) 2019-2021 TON Labs. All Rights Reserved.
*
* Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use
* this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific TON DEV software governing permissions and
* limitations under the License.
*/
use crate::{TokenValue, error::AbiError, event::Event, function::Function, param::Param, param_type::ParamType, token::Token};
use std::fmt::Display;
use std::io;
use std::collections::HashMap;
use serde::de::{Error as SerdeError};
use serde_json;
use ton_block::{Serializable, MsgAddressInt};
use ton_types::{BuilderData, error, fail, HashmapE, Result, SliceData};
pub const MIN_SUPPORTED_VERSION: AbiVersion = ABI_VERSION_1_0;
pub const MAX_SUPPORTED_VERSION: AbiVersion = ABI_VERSION_2_3;
pub const ABI_VERSION_1_0: AbiVersion = AbiVersion::from_parts(1, 0);
pub const ABI_VERSION_2_0: AbiVersion = AbiVersion::from_parts(2, 0);
pub const ABI_VERSION_2_1: AbiVersion = AbiVersion::from_parts(2, 1);
pub const ABI_VERSION_2_2: AbiVersion = AbiVersion::from_parts(2, 2);
pub const ABI_VERSION_2_3: AbiVersion = AbiVersion::from_parts(2, 3);
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
pub struct AbiVersion {
pub major: u8,
pub minor: u8,
}
impl AbiVersion {
pub fn parse(str_version: &str) -> Result<Self> {
let parts: Vec<&str> = str_version.split(".").collect();
if parts.len() < 2 {
fail!(AbiError::InvalidVersion(format!("version must consist of two parts divided by `.` ({})", str_version)));
}
let major = u8::from_str_radix(parts[0], 10)
.map_err(|err| error!(AbiError::InvalidVersion(format!("can not parse version string: {} ({})", err, str_version))))?;
let minor = u8::from_str_radix(parts[1], 10)
.map_err(|err| error!(AbiError::InvalidVersion(format!("can not parse version string: {} ({})", err, str_version))))?;
Ok(Self { major, minor })
}
pub const fn from_parts(major: u8, minor: u8) -> Self {
Self { major, minor }
}
pub fn is_supported(&self) -> bool {
self >= &MIN_SUPPORTED_VERSION && self <= &MAX_SUPPORTED_VERSION
}
}
impl Display for AbiVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}.{}", self.major, self.minor)
}
}
impl From<u8> for AbiVersion {
fn from(value: u8) -> Self {
Self { major: value, minor: 0 }
}
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct DataItem {
pub key: u64,
#[serde(flatten)]
pub value: Param,
}
struct StringVisitor;
impl<'de> serde::de::Visitor<'de> for StringVisitor {
type Value = String;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("String")
}
fn visit_string<E>(self, v: String) -> std::result::Result<Self::Value, E> where E: serde::de::Error {
Ok(v)
}
fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E> where E: serde::de::Error {
Ok(v.to_string())
}
}
pub fn deserialize_opt_u32_from_string<'de, D>(d: D) -> std::result::Result<Option<u32>, D::Error>
where D: serde::Deserializer<'de>
{
match d.deserialize_string(StringVisitor) {
Err(_) => Ok(None),
Ok(string) => {
if !string.starts_with("0x") {
return Err(D::Error::custom(format!("Number parsing error: number must be prefixed with 0x ({})", string)));
}
u32::from_str_radix(&string[2..], 16)
.map_err(|err| D::Error::custom(format!("Error parsing number: {}", err)))
.map(|value| Some(value))
}
}
}
/// Contract function specification.
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub(crate) struct SerdeFunction {
/// Function name.
pub name: String,
/// Function input.
#[serde(default)]
pub inputs: Vec<Param>,
/// Function output.
#[serde(default)]
pub outputs: Vec<Param>,
/// Calculated function ID
#[serde(default)]
#[serde(deserialize_with = "deserialize_opt_u32_from_string")]
pub id: Option<u32>
}
/// Contract event specification.
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub(crate) struct SerdeEvent {
/// Event name.
pub name: String,
/// Event input.
#[serde(default)]
pub inputs: Vec<Param>,
#[serde(default)]
#[serde(deserialize_with = "deserialize_opt_u32_from_string")]
pub id: Option<u32>
}
fn bool_true() -> bool {
true
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
struct SerdeContract {
/// ABI version up to 2.
#[serde(rename="ABI version")]
pub abi_version: Option<u8>,
/// ABI version.
pub version: Option<String>,
/// Set timestamp in message.
#[serde(rename="setTime")]
#[serde(default="bool_true")]
pub set_time: bool,
/// Header parameters.
#[serde(default)]
pub header: Vec<Param>,
/// Contract functions.
pub functions: Vec<SerdeFunction>,
/// Contract events.
#[serde(default)]
pub events: Vec<SerdeEvent>,
/// Contract initial data.
#[serde(default)]
pub data: Vec<DataItem>,
/// Contract storage fields.
#[serde(default)]
pub fields: Vec<Param>,
}
pub struct DecodedMessage {
pub function_name: String,
pub tokens: Vec<Token>,
}
/// API building calls to contracts ABI.
#[derive(Clone, Debug, PartialEq)]
pub struct Contract {
/// ABI version
abi_version: AbiVersion,
/// Contract functions header parameters
header: Vec<Param>,
/// Contract functions.
functions: HashMap<String, Function>,
/// Contract events.
events: HashMap<String, Event>,
/// Contract initial data.
data: HashMap<String, DataItem>,
/// Contract storage fields.
fields: Vec<Param>,
}
impl Contract {
/// Loads contract from json.
pub fn load<T: io::Read>(reader: T) -> Result<Self> {
// A little trick similar to `Param` deserialization: first deserialize JSON into temporary
// struct `SerdeContract` containing necessary fields and then repack fields into HashMap
let mut serde_contract: SerdeContract = serde_json::from_reader(reader)?;
let version = if let Some(str_version) = &serde_contract.version {
AbiVersion::parse(str_version)?
} else if let Some(version) = serde_contract.abi_version {
AbiVersion::from_parts(version, 0)
} else {
fail!(AbiError::InvalidVersion("No version in ABI JSON".to_owned()));
};
if !version.is_supported() {
fail!(AbiError::InvalidVersion(format!("Provided ABI version is not supported ({})", version)));
}
if version.major == 1 {
if serde_contract.header.len() != 0 {
return Err(AbiError::InvalidData {
msg: "Header parameters are not supported in ABI v1".into()
}.into());
}
if serde_contract.set_time {
serde_contract.header.push(Param { name: "time".into(), kind: ParamType::Time});
}
}
if !serde_contract.fields.is_empty() && version < ABI_VERSION_2_1 {
fail!(AbiError::InvalidData {msg: "Storage fields are supported since ABI v2.1".into()});
}
let mut result = Self {
abi_version: version.clone(),
header: serde_contract.header,
functions: HashMap::new(),
events: HashMap::new(),
data: HashMap::new(),
fields: serde_contract.fields,
};
for function in serde_contract.functions {
Self::check_params_support(&version, function.inputs.iter())?;
Self::check_params_support(&version, function.outputs.iter())?;
result.functions.insert(
function.name.clone(),
Function::from_serde(version.clone(), function, result.header.clone()));
}
for event in serde_contract.events {
Self::check_params_support(&version, event.inputs.iter())?;
result.events.insert(event.name.clone(), Event::from_serde(version.clone(), event));
}
Self::check_params_support(&version, serde_contract.data.iter().map(|val| &val.value))?;
for data in serde_contract.data {
result.data.insert(data.value.name.clone(), data);
}
Ok(result)
}
fn check_params_support<'a, T>(abi_version: &AbiVersion, params: T) -> Result<()>
where
T: std::iter::Iterator<Item = &'a Param>
{
for param in params {
if !param.kind.is_supported(abi_version) {
return Err(AbiError::InvalidData {
msg: format!("Parameters of type {} are not supported in ABI v{}", param.kind, abi_version)
}.into());
}
}
Ok(())
}
/// Returns `Function` struct with provided function name.
pub fn function(&self, name: &str) -> Result<&Function> {
self.functions.get(name).ok_or_else(|| AbiError::InvalidName { name: name.to_owned() }.into())
}
/// Returns `Function` struct with provided function id.
pub fn function_by_id(&self, id: u32, input: bool) -> Result<&Function> {
for (_, func) in &self.functions {
let func_id = if input { func.get_input_id() } else { func.get_output_id() };
if func_id == id {
return Ok(func);
}
}
Err(AbiError::InvalidFunctionId { id }.into())
}
/// Returns `Event` struct with provided function name.
pub fn event(&self, name: &str) -> Result<&Event> {
self.events.get(name).ok_or_else(|| AbiError::InvalidName { name: name.to_owned() }.into())
}
/// Returns `Event` struct with provided function id.
pub fn event_by_id(&self, id: u32) -> Result<&Event> {
for (_, event) in &self.events {
if event.get_id() == id {
return Ok(event);
}
}
Err(AbiError::InvalidFunctionId { id }.into())
}
/// Returns functions collection
pub fn functions(&self) -> &HashMap<String, Function> {
&self.functions
}
/// Returns header parameters set
pub fn header(&self) -> &Vec<Param> {
&self.header
}
/// Returns events collection
pub fn events(&self) -> &HashMap<String, Event> {
&self.events
}
/// Returns data collection
pub fn data(&self) -> &HashMap<String, DataItem> {
&self.data
}
/// Returns storage fields collection
pub fn fields(&self) -> &Vec<Param> {
&self.fields
}
/// Returns version
pub fn version(&self) -> &AbiVersion {
&self.abi_version
}
/// Decodes contract answer and returns name of the function called
pub fn decode_output(&self, data: SliceData, internal: bool, allow_partial: bool) -> Result<DecodedMessage> {
let original_data = data.clone();
let func_id = Function::decode_output_id(data)?;
if let Ok(func) = self.function_by_id(func_id, false){
let tokens = func.decode_output(original_data, internal, allow_partial)?;
Ok( DecodedMessage {
function_name: func.name.clone(),
tokens: tokens,
})
} else {
let event = self.event_by_id(func_id)?;
let tokens = event.decode_input(original_data, allow_partial)?;
Ok( DecodedMessage {
function_name: event.name.clone(),
tokens: tokens,
})
}
}
/// Decodes contract answer and returns name of the function called
pub fn decode_input(&self, data: SliceData, internal: bool, allow_partial: bool) -> Result<DecodedMessage> {
let original_data = data.clone();
let func_id = Function::decode_input_id(&self.abi_version, data, &self.header, internal)?;
let func = self.function_by_id(func_id, true)?;
let tokens = func.decode_input(original_data, internal, allow_partial)?;
Ok( DecodedMessage {
function_name: func.name.clone(),
tokens,
})
}
pub const DATA_MAP_KEYLEN: usize = 64;
/// Changes initial values for public contract variables
pub fn update_data(&self, data: SliceData, tokens: &[Token]) -> Result<SliceData> {
let mut map = HashmapE::with_hashmap(
Self::DATA_MAP_KEYLEN,
data.reference_opt(0),
);
for token in tokens {
let builder = token.value.pack_into_chain(&self.abi_version)?;
let key = self.data
.get(&token.name)
.ok_or_else(||
AbiError::InvalidData { msg: format!("data item {} not found in contract ABI", token.name) }
)?.key;
map.set_builder(
SliceData::load_builder(key.write_to_new_cell()?)?,
&builder,
)?;
}
SliceData::load_cell(map.serialize()?)
}
/// Decode initial values of public contract variables
pub fn decode_data(&self, data: SliceData, allow_partial: bool) -> Result<Vec<Token>> {
let map = HashmapE::with_hashmap(
Self::DATA_MAP_KEYLEN,
data.reference_opt(0),
);
let mut tokens = vec![];
for (_, item) in &self.data {
let key = SliceData::load_builder(item.key.write_to_new_cell()?)?;
if let Some(value) = map.get(key)? {
tokens.append(
&mut TokenValue::decode_params(&vec![item.value.clone()], value, &self.abi_version, allow_partial)?
);
}
}
Ok(tokens)
}
// Gets public key from contract data
pub fn get_pubkey(data: &SliceData) -> Result<Option<Vec<u8>>> {
let map = HashmapE::with_hashmap(
Self::DATA_MAP_KEYLEN,
data.reference_opt(0),
);
map.get(SliceData::load_builder(0u64.write_to_new_cell()?)?)
.map(|opt| opt.map(|slice| slice.get_bytestring(0)))
}
/// Sets public key into contract data
pub fn insert_pubkey(data: SliceData, pubkey: &[u8]) -> Result<SliceData> {
let pubkey_vec = pubkey.to_vec();
let pubkey_len = pubkey_vec.len() * 8;
let value = BuilderData::with_raw(pubkey_vec, pubkey_len)?;
let mut map = HashmapE::with_hashmap(
Self::DATA_MAP_KEYLEN,
data.reference_opt(0)
);
map.set_builder(
SliceData::load_builder(0u64.write_to_new_cell()?)?,
&value,
)?;
SliceData::load_cell(map.serialize()?)
}
/// Add sign to messsage body returned by `prepare_input_for_sign` function
pub fn add_sign_to_encoded_input(
&self,
signature: &[u8],
public_key: Option<&[u8]>,
function_call: SliceData
) -> Result<BuilderData> {
Function::add_sign_to_encoded_input(&self.abi_version, signature, public_key, function_call)
}
/// Decode account storage fields
pub fn decode_storage_fields(&self, data: SliceData, allow_partial: bool) -> Result<Vec<Token>> {
TokenValue::decode_params(&self.fields, data, &self.abi_version, allow_partial)
}
/// Get signature and signed hash from function call data
pub fn get_signature_data(
&self,
cursor: SliceData,
address: Option<MsgAddressInt>,
) -> Result<(Vec<u8>, Vec<u8>)> {
Function::get_signature_data(&self.abi_version, cursor, address)
}
}
#[cfg(test)]
#[path = "tests/test_contract.rs"]
mod tests_common;
#[cfg(test)]
#[path = "tests/v1/test_contract.rs"]
mod tests_v1;
#[cfg(test)]
#[path = "tests/v2/test_contract.rs"]
mod tests_v2; |
fn main() {
let b = Box::new(5);
let s = Box::new("string");
println!("b = {}", b);
println!("b = {}", &b);
println!("b = {}", &s); // type of data
println!("b = {}", s);
} |
use std::env;
use std::fs;
use tempfile;
use utils::fixture;
use wasm_pack::binaries;
use wasm_pack::command::{self, build, test, Command};
use wasm_pack::logger;
#[test]
fn it_can_run_node_tests() {
let fixture = fixture::wbg_test_node();
fixture.install_local_wasm_bindgen();
let cmd = Command::Test(test::TestOptions {
path: Some(fixture.path.clone()),
node: true,
mode: build::BuildMode::Noinstall,
..Default::default()
});
let logger = logger::new(&cmd, 3).unwrap();
command::run_wasm_pack(cmd, &logger).expect("should run test command OK");
}
#[test]
fn it_can_run_tests_with_different_wbg_test_and_wbg_versions() {
let fixture = fixture::wbg_test_diff_versions();
fixture.install_local_wasm_bindgen();
let cmd = Command::Test(test::TestOptions {
path: Some(fixture.path.clone()),
node: true,
mode: build::BuildMode::Noinstall,
..Default::default()
});
let logger = logger::new(&cmd, 3).unwrap();
command::run_wasm_pack(cmd, &logger).expect("should run test command OK");
}
#[test]
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "x86_64"),
all(target_os = "windows", target_arch = "x86"),
all(target_os = "windows", target_arch = "x86_64")
))]
fn it_can_run_browser_tests() {
let fixture = fixture::wbg_test_browser();
fixture.install_local_wasm_bindgen();
let firefox = cfg!(any(
all(target_os = "linux", target_arch = "x86"),
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "x86_64"),
all(target_os = "windows", target_arch = "x86"),
all(target_os = "windows", target_arch = "x86_64")
));
if firefox {
fixture.install_local_geckodriver();
}
let chrome = cfg!(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "x86_64"),
all(target_os = "windows", target_arch = "x86")
));
if chrome {
fixture.install_local_chromedriver();
}
let safari = cfg!(target_os = "macos");
if !firefox && !chrome && !safari {
return;
}
let cmd = Command::Test(test::TestOptions {
path: Some(fixture.path.clone()),
firefox,
chrome,
safari,
headless: true,
mode: build::BuildMode::Noinstall,
..Default::default()
});
let logger = logger::new(&cmd, 3).unwrap();
command::run_wasm_pack(cmd, &logger).expect("should run test command OK");
}
#[test]
fn it_can_run_failing_tests() {
let fixture = fixture::wbg_test_fail();
fixture.install_local_wasm_bindgen();
let cmd = Command::Test(test::TestOptions {
path: Some(fixture.path.clone()),
node: true,
mode: build::BuildMode::Noinstall,
..Default::default()
});
let logger = logger::new(&cmd, 3).unwrap();
assert!(
command::run_wasm_pack(cmd, &logger).is_err(),
"failing tests should return Err"
);
}
#[test]
#[cfg(any(
all(target_os = "linux", target_arch = "x86"),
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "x86_64"),
all(target_os = "windows", target_arch = "x86"),
all(target_os = "windows", target_arch = "x86_64")
))]
fn it_can_find_a_webdriver_on_path() {
let fixture = fixture::wbg_test_browser();
fixture.install_local_wasm_bindgen();
fixture.install_local_geckodriver();
let geckodriver_dir = tempfile::TempDir::new().unwrap();
let local_geckodriver = binaries::local_bin_path(&fixture.path, "geckodriver");
fs::copy(
&local_geckodriver,
geckodriver_dir
.path()
.join(local_geckodriver.file_name().unwrap()),
).unwrap();
fs::remove_file(&local_geckodriver).unwrap();
let mut paths: Vec<_> = env::split_paths(&env::var("PATH").unwrap()).collect();
paths.insert(0, geckodriver_dir.path().into());
env::set_var("PATH", env::join_paths(paths).unwrap());
let cmd = Command::Test(test::TestOptions {
path: Some(fixture.path.clone()),
firefox: true,
headless: true,
mode: build::BuildMode::Noinstall,
..Default::default()
});
let logger = logger::new(&cmd, 3).unwrap();
command::run_wasm_pack(cmd, &logger).expect("should run test command OK");
}
#[test]
fn it_requires_node_or_a_browser() {
let fixture = fixture::wbg_test_node();
fixture.install_local_wasm_bindgen();
let cmd = Command::Test(test::TestOptions {
path: Some(fixture.path.clone()),
mode: build::BuildMode::Noinstall,
// Note: not setting node or any browser to true here.
..Default::default()
});
let logger = logger::new(&cmd, 3).unwrap();
assert!(
command::run_wasm_pack(cmd, &logger).is_err(),
"need to enable node or browser testing"
);
}
#[test]
fn the_headless_flag_requires_a_browser() {
let fixture = fixture::wbg_test_node();
fixture.install_local_wasm_bindgen();
let cmd = Command::Test(test::TestOptions {
path: Some(fixture.path.clone()),
node: true,
mode: build::BuildMode::Noinstall,
headless: true,
..Default::default()
});
let logger = logger::new(&cmd, 3).unwrap();
assert!(
command::run_wasm_pack(cmd, &logger).is_err(),
"running headless tests in node doesn't make sense"
);
}
|
use actix_web::HttpResponse;
use std::fs::OpenOptions;
use std::io::{BufReader, Read};
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use regex::{Regex, RegexBuilder};
use tokio::process::Command;
use tokio::time::timeout;
use actix_web::{client, http};
use handlebars::Handlebars;
use super::super::app;
use super::{command, message, project};
// #[derive(Clone)]
pub struct WxWorkCommandRuntime {
pub proj: project::WxWorkProjectPtr,
pub cmd: command::WxWorkCommandPtr,
pub cmd_match: command::WxWorkCommandMatch,
pub envs: serde_json::Value,
pub msg: message::WxWorkMessageNtf,
}
lazy_static! {
static ref PICK_AT_RULE: Regex = RegexBuilder::new(r"@(?P<AT>\S+)")
.case_insensitive(false)
.build()
.unwrap();
}
pub fn get_project_name_from_runtime(runtime: &Arc<WxWorkCommandRuntime>) -> Arc<String> {
runtime.proj.name()
}
pub fn get_command_name_from_runtime(runtime: &Arc<WxWorkCommandRuntime>) -> Arc<String> {
runtime.cmd.name()
}
// #[allow(unused)]
pub async fn run(runtime: Arc<WxWorkCommandRuntime>) -> HttpResponse {
debug!(
"dispatch for command \"{}\"({})",
runtime.cmd.name(),
runtime.cmd.description()
);
match runtime.cmd.data {
command::WxWorkCommandData::Echo(_) => run_echo(runtime).await,
command::WxWorkCommandData::Http(_) => run_http(runtime).await,
command::WxWorkCommandData::Help(_) => run_help(runtime).await,
command::WxWorkCommandData::Spawn(_) => run_spawn(runtime).await,
command::WxWorkCommandData::Ignore => run_ignore(runtime).await,
// _ => run_test,
}
}
#[allow(unused)]
async fn run_test(_: Arc<WxWorkCommandRuntime>) -> HttpResponse {
HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body("test success")
}
async fn run_ignore(_: Arc<WxWorkCommandRuntime>) -> HttpResponse {
message::make_robot_empty_response()
}
async fn run_help(runtime: Arc<WxWorkCommandRuntime>) -> HttpResponse {
let (echo_prefix, echo_suffix) =
if let command::WxWorkCommandData::Help(ref x) = runtime.cmd.data {
(x.prefix.clone(), x.suffix.clone())
} else {
(String::default(), String::default())
};
let mut output = String::with_capacity(4096);
let reg = Handlebars::new();
if !echo_prefix.is_empty() {
output += (match reg.render_template(echo_prefix.as_str(), &runtime.envs) {
Ok(x) => x,
Err(e) => format!("{:?}", e),
})
.as_str();
output += "\r\n";
}
let mut cmd_index = 1;
for ref cmd in runtime.proj.cmds.as_ref() {
if let Some(desc) = command::get_command_description(&cmd) {
output += format!("> {}. {}\r\n", cmd_index, desc).as_str();
cmd_index += 1;
}
}
let app_env = app::app();
for ref cmd in app_env.get_global_command_list().as_ref() {
if let Some(desc) = command::get_command_description(&cmd) {
output += format!("> {}. {}\r\n", cmd_index, desc).as_str();
cmd_index += 1;
}
}
if !echo_suffix.is_empty() {
output += (match reg.render_template(echo_suffix.as_str(), &runtime.envs) {
Ok(x) => x,
Err(e) => format!("{:?}", e),
})
.as_str();
}
debug!("Help message: \n{}", output);
runtime.proj.make_markdown_response_with_text(output)
}
async fn run_echo(runtime: Arc<WxWorkCommandRuntime>) -> HttpResponse {
let echo_input = if let command::WxWorkCommandData::Echo(ref x) = runtime.cmd.data {
x.echo.clone()
} else {
String::from("Hello world!")
};
let reg = Handlebars::new();
let echo_output = match reg.render_template(echo_input.as_str(), &runtime.envs) {
Ok(x) => x,
Err(e) => format!("{:?}", e),
};
debug!("Echo message: \n{}", echo_output);
runtime.proj.make_markdown_response_with_text(echo_output)
}
async fn run_http(runtime: Arc<WxWorkCommandRuntime>) -> HttpResponse {
let http_req_f;
let http_url;
let reg;
let echo_output_tmpl_str;
{
let http_data = if let command::WxWorkCommandData::Http(ref x) = runtime.cmd.data {
x.clone()
} else {
return runtime
.proj
.make_error_response(String::from("Configure type error"));
};
if http_data.url.is_empty() {
let err_msg = "Missing Request URL".to_string();
error!(
"project \"{}\" command \"{}\" {}",
runtime.proj.name(),
runtime.cmd.name(),
err_msg
);
return runtime.proj.make_error_response(err_msg);
}
reg = Handlebars::new();
http_url = match reg.render_template(http_data.url.as_str(), &runtime.envs) {
Ok(x) => x,
Err(e) => format!("{:?}", e),
};
echo_output_tmpl_str = if http_data.echo.is_empty() {
String::from("Ok")
} else {
http_data.echo.clone()
};
let post_data = match reg.render_template(http_data.post.as_str(), &runtime.envs) {
Ok(x) => x,
Err(_) => String::default(),
};
{
let mut http_request = match http_data.method {
command::WxWorkCommandHttpMethod::Auto => {
if !post_data.is_empty() {
client::Client::default().post(http_url.as_str())
} else {
client::Client::default().get(http_url.as_str())
}
}
command::WxWorkCommandHttpMethod::Get => {
client::Client::default().get(http_url.as_str())
}
command::WxWorkCommandHttpMethod::Post => {
client::Client::default().post(http_url.as_str())
}
command::WxWorkCommandHttpMethod::Delete => {
client::Client::default().delete(http_url.as_str())
}
command::WxWorkCommandHttpMethod::Put => {
client::Client::default().put(http_url.as_str())
}
command::WxWorkCommandHttpMethod::Head => {
client::Client::default().head(http_url.as_str())
}
};
http_request = http_request
.timeout(Duration::from_millis(app::app_conf().task_timeout))
.header(
http::header::USER_AGENT,
format!("Mozilla/5.0 (WXWork-Robotd {})", crate_version!()),
);
if !http_data.content_type.is_empty() {
http_request = http_request
.header(http::header::CONTENT_TYPE, http_data.content_type.as_str());
}
for (k, v) in &http_data.headers {
http_request = http_request.header(k.as_str(), v.as_str());
}
http_req_f = http_request.send_body(post_data);
}
// if let Err(e) = http_req_f {
// let err_msg = format!("Make request to {} failed, {:?}", http_url, e);
// error!(
// "project \"{}\" command \"{}\" {}",
// runtime.proj.name(),
// runtime.cmd.name(),
// err_msg
// );
// return Box::new(future_ok(runtime.proj.make_error_response(err_msg)));
// }
}
let mut http_rsp = match http_req_f.await {
Ok(x) => x,
Err(e) => {
let err_msg = format!("Make request to {} failed, {:?}", http_url, e);
error!(
"project \"{}\" command \"{}\" {}",
runtime.proj.name(),
runtime.cmd.name(),
err_msg
);
return runtime.proj.make_error_response(err_msg);
}
};
let rsp_data = match http_rsp.body().await {
Ok(x) => x,
Err(e) => {
let err_msg = format!("{:?}", e);
error!(
"project \"{}\" command \"{}\" get response from {} failed: {:?}",
get_project_name_from_runtime(&runtime),
get_command_name_from_runtime(&runtime),
http_url,
err_msg
);
return runtime.proj.make_markdown_response_with_text(err_msg);
}
};
let data_str = if let Ok(x) = String::from_utf8((&rsp_data).to_vec()) {
x
} else {
hex::encode(&rsp_data)
};
info!(
"project \"{}\" command \"{}\" get response from {}: \n{:?}",
get_project_name_from_runtime(&runtime),
get_command_name_from_runtime(&runtime),
http_url,
data_str
);
let mut vars_for_rsp = runtime.envs.clone();
if vars_for_rsp.is_object() {
vars_for_rsp["WXWORK_ROBOT_HTTP_RESPONSE"] = serde_json::Value::String(data_str);
}
let echo_output = match reg.render_template(echo_output_tmpl_str.as_str(), &vars_for_rsp) {
Ok(x) => x,
Err(e) => format!("{:?}", e),
};
runtime.proj.make_markdown_response_with_text(echo_output)
}
async fn run_spawn(runtime: Arc<WxWorkCommandRuntime>) -> HttpResponse {
let spawn_data = if let command::WxWorkCommandData::Spawn(ref x) = runtime.cmd.data {
x.clone()
} else {
return runtime
.proj
.make_error_response(String::from("Configure type error"));
};
let reg = Handlebars::new();
let exec = match reg.render_template(spawn_data.exec.as_str(), &runtime.envs) {
Ok(x) => x,
Err(_) => spawn_data.exec.clone(),
};
let cwd = match reg.render_template(spawn_data.cwd.as_str(), &runtime.envs) {
Ok(x) => x,
Err(_) => spawn_data.cwd.clone(),
};
let mut args = Vec::with_capacity(spawn_data.args.capacity());
for v in &spawn_data.args {
args.push(match reg.render_template(v.as_str(), &runtime.envs) {
Ok(x) => x,
Err(_) => v.clone(),
});
}
let output_type = spawn_data.output_type;
info!("Spawn message: (CWD={}) {} {}", cwd, exec, &args.join(" "));
let mut child = Command::new(exec.as_str());
child.stdin(Stdio::null());
child.stdout(Stdio::piped());
child.stderr(Stdio::piped());
child.kill_on_drop(true);
for ref v in args {
child.arg(v.as_str());
}
if let Some(kvs) = runtime.envs.as_object() {
for (k, v) in kvs {
match v {
serde_json::Value::Null => {}
serde_json::Value::Bool(x) => {
child.env(k.as_str(), if *x { "1" } else { "0" });
}
serde_json::Value::Number(x) => {
child.env(k.as_str(), x.to_string());
}
serde_json::Value::String(x) => {
child.env(k.as_str(), x.as_str());
}
x => {
child.env(k.as_str(), x.to_string());
}
}
}
}
if !cwd.is_empty() {
child.current_dir(cwd);
}
let async_job = match child.spawn() {
Ok(x) => x,
Err(e) => {
let err_msg = format!("Run command failed, {:?}", e);
error!(
"project \"{}\" command \"{}\" {}",
runtime.proj.name(),
runtime.cmd.name(),
err_msg
);
return runtime.proj.make_error_response(err_msg);
}
};
let run_result = match timeout(
Duration::from_millis(app::app_conf().task_timeout),
async_job.wait_with_output(),
)
.await
{
Ok(x) => x,
Err(e) => {
let err_msg = format!("Run command timeout, {:?}", e);
error!(
"project \"{}\" command \"{}\" {}",
runtime.proj.name(),
runtime.cmd.name(),
err_msg
);
return runtime.proj.make_markdown_response_with_text(err_msg);
}
};
let output = match run_result {
Ok(x) => x,
Err(e) => {
let err_msg = format!("Run command with io error, {:?}", e);
error!(
"project \"{}\" command \"{}\" {}",
runtime.proj.name(),
runtime.cmd.name(),
err_msg
);
return runtime.proj.make_markdown_response_with_text(err_msg);
}
};
let mut ret_msg = String::with_capacity(output.stdout.len() + output.stderr.len() + 32);
if !output.stdout.is_empty() {
ret_msg += (match String::from_utf8(output.stdout) {
Ok(x) => x,
Err(e) => hex::encode(e.as_bytes()),
})
.as_str();
}
if !output.stderr.is_empty() {
let stderr_str = match String::from_utf8(output.stderr) {
Ok(x) => x,
Err(e) => hex::encode(e.as_bytes()),
};
info!(
"project \"{}\" command \"{}\" run command with stderr:\n{}",
runtime.proj.name(),
runtime.cmd.name(),
stderr_str
);
ret_msg += stderr_str.as_str();
}
if output.status.success() {
match output_type {
command::WxWorkCommandSpawnOutputType::Markdown => {
runtime.proj.make_markdown_response_with_text(ret_msg)
}
command::WxWorkCommandSpawnOutputType::Text => {
let mut mentioned_list: Vec<String> = Vec::new();
for caps in PICK_AT_RULE.captures_iter(ret_msg.as_str()) {
if let Some(m) = caps.name("AT") {
mentioned_list.push(String::from(m.as_str()));
}
}
let rsp = message::WxWorkMessageTextRsp {
content: ret_msg,
mentioned_list,
mentioned_mobile_list: Vec::new(),
};
runtime.proj.make_text_response(rsp)
}
command::WxWorkCommandSpawnOutputType::Image => {
let file_path = ret_msg.trim();
let mut options = OpenOptions::new();
options
.write(false)
.create(false)
.truncate(false)
.read(true);
let mut err_msg = String::default();
let mut image_data: Vec<u8> = Vec::new();
if !file_path.is_empty() {
match options.open(file_path) {
Ok(f) => {
let mut reader = BufReader::new(f);
match reader.read_to_end(&mut image_data) {
Ok(_) => {}
Err(e) => {
err_msg =
format!("Try read data from {} failed, {:?}", file_path, e);
}
}
}
Err(e) => {
err_msg = format!("Try to open {} failed, {:?}", file_path, e);
}
};
}
if !image_data.is_empty() {
runtime
.proj
.make_image_response(message::WxWorkMessageImageRsp {
content: image_data,
})
} else {
runtime
.proj
.make_text_response(message::WxWorkMessageTextRsp {
content: err_msg,
mentioned_list: vec![runtime.msg.from.alias.clone()],
mentioned_mobile_list: Vec::new(),
})
}
}
}
} else {
runtime
.proj
.make_text_response(message::WxWorkMessageTextRsp {
content: ret_msg,
mentioned_list: vec![runtime.msg.from.alias.clone()],
mentioned_mobile_list: Vec::new(),
})
}
//Box::new(future_ok(runtime.proj.make_markdown_response_with_text(echo_output)))
}
|
pub mod app;
use serde::Deserialize;
#[derive(Clone, Debug, Deserialize)]
pub struct ControllerConfig {
/// The namespace in which the topics get created
pub topic_namespace: String,
/// The resource name of the Kafka cluster.
///
/// This will be used as the `strimzi.io/cluster` label value.
pub cluster_name: String,
}
|
use envconfig::Envconfig;
use lazy_static::lazy_static;
mod agent;
mod experiments;
mod maze;
mod mcc;
mod neat;
mod neatns;
lazy_static! {
pub static ref EXPERIMENTS: experiments::Config = experiments::Config::init().unwrap();
pub static ref MCC: mcc::Config = mcc::Config::init().unwrap();
pub static ref MAZE: maze::Config = maze::Config::init().unwrap();
pub static ref AGENT: agent::Config = agent::Config::init().unwrap();
pub static ref NEAT: neat::Config = neat::Config::init().unwrap();
pub static ref NEATNS: neatns::Config = neatns::Config::init().unwrap();
}
|
use crate::profile::Profile;
use crate::types::{decode_date_time, tag_deserializer, tag_types, ICCDateTime};
use crate::{ColorSpace, ICCTag, ICCTagType, Intent, ProfileClass, S15Fixed16};
use byteorder::{ByteOrder, ReadBytesExt, BE};
use cgmath::num_traits::{FromPrimitive, ToPrimitive};
use std::collections::HashMap;
use std::{fmt, io, mem};
pub enum DeserError {
/// Magic number mismatch.
MagicNumber,
/// Something is invalid.
Invalid,
/// The file is too big.
TooBig,
/// The type is unsupported.
UnsupportedType(u32),
/// An error occurred while deserializing a tag.
TagError(ICCTag, ICCTagType, io::Error),
/// An IO error.
IO(io::Error),
}
impl fmt::Debug for DeserError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
DeserError::MagicNumber => write!(f, "MagicNumber"),
DeserError::Invalid => write!(f, "Invalid"),
DeserError::TooBig => write!(f, "TooBig"),
DeserError::UnsupportedType(x) => {
use std::ffi::CStr;
let a = (x >> 24) as u8;
let b = ((x >> 16) & 0xFF_u32) as u8;
let c = ((x >> 8) & 0xFF_u32) as u8;
let d = (x & 0xFF) as u8;
let bytes = [a, b, c, d, 0];
match CStr::from_bytes_with_nul(&bytes) {
Ok(cstr) => write!(f, "UnsupportedType({})", cstr.to_string_lossy()),
Err(_) => write!(
f,
"UnsupportedType({:02x} {:02x} {:02x} {:02x})",
a, b, c, d
),
}
}
DeserError::TagError(tag, ty, err) => {
write!(f, "TagError({:?}, {:?}, {:?})", tag, ty, err)
}
DeserError::IO(err) => write!(f, "IO({:?})", err),
}
}
}
impl From<io::Error> for DeserError {
fn from(err: io::Error) -> DeserError {
DeserError::IO(err)
}
}
type Signature = u32;
/// ICC Platforms
enum Platform {
/// `APPL`
MacOS = 0x4150504C,
/// `MSFT`
Microsoft = 0x4D534654,
/// `SUNW`
Solaris = 0x53554E57,
/// `SGI `
SGI = 0x53474920,
/// `TGNT`
Taligent = 0x54474E54,
/// `*nix` from argyll—not official
Unices = 0x2A6E6978,
}
/// `acsp`
const MAGIC_NUMBER: u32 = 0x61637370;
/// Profile header -- is 32-bit aligned, so no issues expected with alignment
#[repr(C)]
struct ICCHeader {
/// Profile size in bytes.
size: u32,
/// CMM for this profile.
cmm_id: Signature,
/// Format version number.
version: u32,
/// Type of profile.
device_class: Signature,
/// Color space of data.
color_space: Signature,
/// PCS; XYZ or Lab only.
pcs: Signature,
/// Date profile was created.
date: ICCDateTime,
/// Magic number to identify an ICC profile.
magic: Signature,
/// Primary platform.
platform: Signature,
/// Various bit settings.
flags: u32,
/// Device manufacturer.
manufacturer: Signature,
/// Device model number.
model: u32,
/// Device attributes.
attributes: u64,
/// Rendering intent.
intent: u32,
/// Profile illuminant.
illuminant: EncodedXYZ,
/// Profile creator.
creator: Signature,
/// Profile ID using MD5.
profile_id: [u32; 4],
/// Reserved for future use.
reserved: [u8; 28],
}
/// ICC XYZ
#[repr(C)]
struct EncodedXYZ {
x: S15Fixed16,
y: S15Fixed16,
z: S15Fixed16,
}
/// Profile ID as computed by MD5 algorithm
union ProfileID {
u128: u128,
u32: [u32; 4],
}
/// A tag entry
#[repr(C)]
struct TagEntry {
signature: ICCTag,
/// Start of tag
offset: u32,
/// Size in bytes
size: u32,
}
#[derive(Debug)]
enum TagData<'a> {
Data(&'a [u8]),
Linked(ICCTag),
}
impl Profile {
/// Deserializes an ICC profile from binary data.
pub fn deser<T: io::Read>(input: &mut T) -> Result<Profile, DeserError> {
// created with dummy values that’ll be filled in below
let mut profile = Profile::new(ProfileClass::Abstract, ColorSpace::XYZ);
let (header_size, tags) = read_header(input, &mut profile)?;
let mut max_offset = 0;
for tag in &tags {
let offset = tag.offset + tag.size;
if offset > max_offset {
max_offset = offset;
}
}
// hard limit at 16 MiB
if max_offset > 16_777_216 {
return Err(DeserError::TooBig);
}
let mut pool = Vec::with_capacity(max_offset as usize - header_size);
pool.resize(max_offset as usize - header_size, 0);
input.read_exact(&mut pool)?;
let mut pool_tags = HashMap::new();
let mut pool_tags_by_offset = HashMap::new();
for tag in tags {
let offset = tag.offset as usize - header_size;
let mut end = offset + tag.size as usize;
if pool_tags_by_offset.contains_key(&offset) {
let link = pool_tags_by_offset.get(&offset).unwrap();
pool_tags.insert(tag.signature, TagData::Linked(*link));
} else {
// fix for “untrustworthy” MLU size
if let Some(ICCTagType::MLU) = ICCTagType::from_u32(BE::read_u32(&pool[offset..])) {
// just pass the whole thing
end = pool.len();
}
pool_tags.insert(tag.signature, TagData::Data(&pool[offset..end]));
pool_tags_by_offset.insert(offset, tag.signature);
}
}
for (tag, data) in pool_tags {
match data {
TagData::Linked(target) => profile.link_tag(tag, target),
TagData::Data(buf) => {
if let Some(tag_types) = tag_types(tag) {
if buf.len() < 8 {
return Err(io::Error::from(io::ErrorKind::UnexpectedEof).into());
}
let data_type = BE::read_u32(buf);
let tag_type =
match tag_types.iter().find(|x| x.to_u32() == Some(data_type)) {
Some(tt) => *tt,
None => return Err(DeserError::UnsupportedType(data_type)),
};
if let Some(deser_tag) = tag_deserializer(tag_type) {
profile.insert_tag_raw(
tag,
match deser_tag(&buf[8..]) {
Ok(data) => data,
Err(err) => {
return Err(DeserError::TagError(tag, tag_type, err))
}
},
);
} else {
profile.insert_tag_raw_data(tag, buf.to_vec());
}
}
}
}
}
Ok(profile)
}
}
/// Enforces that the profile version is per spec.
/// Operates on the big endian bytes from the profile.
/// Called before converting to platform endianness.
/// Byte 0 is BCD major version, so max 9.
/// Byte 1 is 2 BCD digits, one per nibble.
/// Reserved bytes 2 & 3 must be 0.
fn validated_version(version: u32) -> u32 {
union VersionUnion {
bytes: [u8; 4],
version: u32,
}
let mut bytes = unsafe { VersionUnion { version }.bytes };
if bytes[0] > 0x09 {
bytes[0] = 0x09;
}
let mut tmp1 = bytes[1] & 0xf0;
let mut tmp2 = bytes[1] & 0x0f;
if tmp1 > 0x90 {
tmp1 = 0x90;
}
if tmp2 > 0x09 {
tmp2 = 0x09;
}
bytes[1] = tmp1 | tmp2;
bytes[2] = 0;
bytes[3] = 0;
unsafe { VersionUnion { bytes }.version }
}
fn read_header<T: io::Read>(
buf: &mut T,
profile: &mut Profile,
) -> Result<(usize, Vec<TagEntry>), DeserError> {
let mut header_buf = Vec::new();
let mut header_size = mem::size_of::<ICCHeader>();
header_buf.resize(mem::size_of::<ICCHeader>(), 0);
buf.read_exact(&mut header_buf)?;
let header = unsafe { &*(&*header_buf as *const [u8] as *const ICCHeader) };
if u32::from_be(header.magic) != MAGIC_NUMBER {
return Err(DeserError::MagicNumber);
}
macro_rules! from_be {
($enum:ty, $expr:expr, $err:expr) => {
match <$enum>::from_u32(u32::from_be($expr)) {
Some(x) => x,
None => return Err($err),
}
};
}
profile.device_class = from_be!(ProfileClass, header.device_class, DeserError::Invalid);
profile.color_space = from_be!(ColorSpace, header.color_space, DeserError::Invalid);
profile.pcs = from_be!(ColorSpace, header.pcs, DeserError::Invalid);
match profile.pcs {
ColorSpace::XYZ | ColorSpace::Lab => (),
_ => return Err(DeserError::Invalid),
}
profile.rendering_intent = from_be!(Intent, header.intent, DeserError::Invalid);
profile.flags = u32::from_be(header.flags);
profile.manufacturer = u32::from_be(header.manufacturer);
profile.model = u32::from_be(header.model);
profile.creator = u32::from_be(header.creator);
profile.attributes = u64::from_be(header.attributes);
profile.version = u32::from_be(validated_version(header.version));
profile.created = decode_date_time(&header.date);
profile.profile_id = unsafe {
ProfileID {
u32: header.profile_id,
}
.u128
};
// tag directory
header_size += mem::size_of::<u32>();
let tag_count = buf.read_u32::<BE>()?;
let mut tags = Vec::new();
for _ in 0..tag_count {
header_size += 3 * mem::size_of::<u32>();
let signature = buf.read_u32::<BE>()?;
let signature = match ICCTag::from_u32(signature) {
Some(tag) => tag,
None => {
// skip
// TODO: handle non-lossily
buf.read_u32::<BE>()?;
buf.read_u32::<BE>()?;
continue;
}
};
let offset = buf.read_u32::<BE>()?;
let size = buf.read_u32::<BE>()?;
tags.push(TagEntry {
signature,
offset,
size,
});
}
Ok((header_size, tags))
}
|
use crate::hittable::{aabb::Aabb, HitRecord, Hittable, Hittables};
use crate::ray::Ray;
use crate::vec::Vec3;
use rand::prelude::*;
use rand::rngs::SmallRng;
#[derive(Debug, Clone)]
pub struct HittableList {
pub hittables: Vec<Hittables>,
}
impl HittableList {
#[allow(dead_code)]
pub fn new() -> Hittables {
Hittables::from(HittableList {
hittables: Vec::new(),
})
}
#[allow(dead_code)]
pub fn clear(&mut self) {
self.hittables.clear()
}
#[allow(dead_code)]
pub fn add(&mut self, s: Hittables) {
self.hittables.push(s)
}
}
impl Hittable for HittableList {
fn hit(&self, ray: &Ray, t_min: f64, t_max: f64, rng: &mut SmallRng) -> Option<HitRecord> {
let mut ret: Option<HitRecord> = None;
let mut closest = t_max;
for hittable in self.hittables.iter() {
match hittable.hit(ray, t_min, closest, rng) {
Some(h) => {
closest = h.t;
ret = Some(h);
}
None => (),
}
}
return ret;
}
fn bounding_box(&self, time0: f64, time1: f64) -> Option<Aabb> {
if self.hittables.is_empty() {
return None;
}
let mut temp_box = Aabb::default();
for hittable in self.hittables.iter() {
match hittable.bounding_box(time0, time1) {
Some(b) => {
temp_box = Aabb::surrounding_box(temp_box, b);
}
None => {
return None;
}
}
}
Some(temp_box)
}
fn pdf_value(&self, origin: Vec3, v: Vec3, rng: &mut SmallRng) -> f64 {
let weight = 1.0 / (self.hittables.len() as f64);
let mut sum = 0.0;
for h in self.hittables.iter() {
sum += weight * h.pdf_value(origin, v, rng);
}
return sum;
}
fn random(&self, origin: Vec3, rng: &mut SmallRng) -> Vec3 {
let sz = self.hittables.len();
match sz {
0 => {
return Vec3::new(1.0, 0.0, 0.0);
}
_ => return self.hittables[rng.gen_range(0, sz)].random(origin, rng),
}
}
fn length(&self) -> usize {
self.hittables.len()
}
}
|
#[doc = "Register `PRIVCFGR2` reader"]
pub type R = crate::R<PRIVCFGR2_SPEC>;
#[doc = "Register `PRIVCFGR2` writer"]
pub type W = crate::W<PRIVCFGR2_SPEC>;
#[doc = "Field `PRIV32` reader - PRIV32"]
pub type PRIV32_R = crate::BitReader;
#[doc = "Field `PRIV32` writer - PRIV32"]
pub type PRIV32_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV33` reader - PRIV33"]
pub type PRIV33_R = crate::BitReader;
#[doc = "Field `PRIV33` writer - PRIV33"]
pub type PRIV33_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV34` reader - PRIV34"]
pub type PRIV34_R = crate::BitReader;
#[doc = "Field `PRIV34` writer - PRIV34"]
pub type PRIV34_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV35` reader - PRIV35"]
pub type PRIV35_R = crate::BitReader;
#[doc = "Field `PRIV35` writer - PRIV35"]
pub type PRIV35_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV36` reader - PRIV36"]
pub type PRIV36_R = crate::BitReader;
#[doc = "Field `PRIV36` writer - PRIV36"]
pub type PRIV36_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV37` reader - PRIV37"]
pub type PRIV37_R = crate::BitReader;
#[doc = "Field `PRIV37` writer - PRIV37"]
pub type PRIV37_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV38` reader - PRIV38"]
pub type PRIV38_R = crate::BitReader;
#[doc = "Field `PRIV38` writer - PRIV38"]
pub type PRIV38_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV39` reader - PRIV39"]
pub type PRIV39_R = crate::BitReader;
#[doc = "Field `PRIV39` writer - PRIV39"]
pub type PRIV39_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV40` reader - PRIV40"]
pub type PRIV40_R = crate::BitReader;
#[doc = "Field `PRIV40` writer - PRIV40"]
pub type PRIV40_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV41` reader - PRIV41"]
pub type PRIV41_R = crate::BitReader;
#[doc = "Field `PRIV41` writer - PRIV41"]
pub type PRIV41_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV42` reader - PRIV42"]
pub type PRIV42_R = crate::BitReader;
#[doc = "Field `PRIV42` writer - PRIV42"]
pub type PRIV42_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - PRIV32"]
#[inline(always)]
pub fn priv32(&self) -> PRIV32_R {
PRIV32_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - PRIV33"]
#[inline(always)]
pub fn priv33(&self) -> PRIV33_R {
PRIV33_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - PRIV34"]
#[inline(always)]
pub fn priv34(&self) -> PRIV34_R {
PRIV34_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - PRIV35"]
#[inline(always)]
pub fn priv35(&self) -> PRIV35_R {
PRIV35_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - PRIV36"]
#[inline(always)]
pub fn priv36(&self) -> PRIV36_R {
PRIV36_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - PRIV37"]
#[inline(always)]
pub fn priv37(&self) -> PRIV37_R {
PRIV37_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - PRIV38"]
#[inline(always)]
pub fn priv38(&self) -> PRIV38_R {
PRIV38_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - PRIV39"]
#[inline(always)]
pub fn priv39(&self) -> PRIV39_R {
PRIV39_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - PRIV40"]
#[inline(always)]
pub fn priv40(&self) -> PRIV40_R {
PRIV40_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - PRIV41"]
#[inline(always)]
pub fn priv41(&self) -> PRIV41_R {
PRIV41_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - PRIV42"]
#[inline(always)]
pub fn priv42(&self) -> PRIV42_R {
PRIV42_R::new(((self.bits >> 10) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - PRIV32"]
#[inline(always)]
#[must_use]
pub fn priv32(&mut self) -> PRIV32_W<PRIVCFGR2_SPEC, 0> {
PRIV32_W::new(self)
}
#[doc = "Bit 1 - PRIV33"]
#[inline(always)]
#[must_use]
pub fn priv33(&mut self) -> PRIV33_W<PRIVCFGR2_SPEC, 1> {
PRIV33_W::new(self)
}
#[doc = "Bit 2 - PRIV34"]
#[inline(always)]
#[must_use]
pub fn priv34(&mut self) -> PRIV34_W<PRIVCFGR2_SPEC, 2> {
PRIV34_W::new(self)
}
#[doc = "Bit 3 - PRIV35"]
#[inline(always)]
#[must_use]
pub fn priv35(&mut self) -> PRIV35_W<PRIVCFGR2_SPEC, 3> {
PRIV35_W::new(self)
}
#[doc = "Bit 4 - PRIV36"]
#[inline(always)]
#[must_use]
pub fn priv36(&mut self) -> PRIV36_W<PRIVCFGR2_SPEC, 4> {
PRIV36_W::new(self)
}
#[doc = "Bit 5 - PRIV37"]
#[inline(always)]
#[must_use]
pub fn priv37(&mut self) -> PRIV37_W<PRIVCFGR2_SPEC, 5> {
PRIV37_W::new(self)
}
#[doc = "Bit 6 - PRIV38"]
#[inline(always)]
#[must_use]
pub fn priv38(&mut self) -> PRIV38_W<PRIVCFGR2_SPEC, 6> {
PRIV38_W::new(self)
}
#[doc = "Bit 7 - PRIV39"]
#[inline(always)]
#[must_use]
pub fn priv39(&mut self) -> PRIV39_W<PRIVCFGR2_SPEC, 7> {
PRIV39_W::new(self)
}
#[doc = "Bit 8 - PRIV40"]
#[inline(always)]
#[must_use]
pub fn priv40(&mut self) -> PRIV40_W<PRIVCFGR2_SPEC, 8> {
PRIV40_W::new(self)
}
#[doc = "Bit 9 - PRIV41"]
#[inline(always)]
#[must_use]
pub fn priv41(&mut self) -> PRIV41_W<PRIVCFGR2_SPEC, 9> {
PRIV41_W::new(self)
}
#[doc = "Bit 10 - PRIV42"]
#[inline(always)]
#[must_use]
pub fn priv42(&mut self) -> PRIV42_W<PRIVCFGR2_SPEC, 10> {
PRIV42_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 = "EXTI security enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`privcfgr2::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 [`privcfgr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct PRIVCFGR2_SPEC;
impl crate::RegisterSpec for PRIVCFGR2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`privcfgr2::R`](R) reader structure"]
impl crate::Readable for PRIVCFGR2_SPEC {}
#[doc = "`write(|w| ..)` method takes [`privcfgr2::W`](W) writer structure"]
impl crate::Writable for PRIVCFGR2_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets PRIVCFGR2 to value 0"]
impl crate::Resettable for PRIVCFGR2_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::collections::HashMap;
use std::sync::Arc;
use lambda_http::http;
use tracing::info;
use tracing::instrument;
use htsget_http::{get as htsget_get, Endpoint};
use htsget_search::htsget::HtsGet;
use crate::handlers::handle_response;
use crate::{Body, Response};
/// Get request reads endpoint
#[instrument(skip(searcher))]
pub async fn get<H: HtsGet + Send + Sync + 'static>(
id_path: String,
searcher: Arc<H>,
mut query: HashMap<String, String>,
endpoint: Endpoint,
) -> http::Result<Response<Body>> {
info!(query = ?query, "GET request");
query.insert("id".to_string(), id_path);
handle_response(htsget_get(searcher, query, endpoint).await)
}
|
fn main() {
let mut x = 5;
println!("The value of X is {}", x);
x = 6;
println!("The new value of X is {}", x);
const MAX_POINTS: u32 = 100_000;
println!("The maximum ammount of points is {}", MAX_POINTS);
let spaces = " ";
let spaces = spaces.len();
}
|
mod error;
mod darwinia_tracker;
use service::{Service, Message};
use darwinia::Darwinia;
use darwinia_tracker::DarwiniaBlockTracker;
#[macro_use]
extern crate log;
pub type Error = error::Error;
pub type Result<T> = std::result::Result<T, Error>;
pub struct DarwiniaRelayerService {
url: &'static str,
scan_from: u32,
}
impl DarwiniaRelayerService {
pub fn new(url: &'static str, scan_from: u32) -> Self {
DarwiniaRelayerService {
url,
scan_from
}
}
}
#[async_trait::async_trait]
impl Service for DarwiniaRelayerService {
fn get_binding_keys(&self) -> Vec<&'static str> {
vec![
"*.darwinia.*"
]
}
async fn start(&mut self) -> std::result::Result<(), service::Error>{
match Darwinia::new(self.url).await {
Ok(darwinia) => {
let mut tracker = DarwiniaBlockTracker::new(darwinia, self.scan_from);
loop {
match tracker.next_block().await {
Ok(header) => {
println!("{:?}", header);
},
Err(_err) => {
return self.start().await;
}
}
}
},
Err(_err) => {
return Err(service::Error::Stopped("未能连接上 Darwinia 节点, 请检查网络"));
}
}
}
async fn send(&self, msg: Message) {
println!("Message log - [ route_key: {}, content: {} ]", msg.route_key, msg.content);
}
}
|
pub mod chain_spec;
pub mod service;
pub mod puzzle_rpc;
pub mod rpc;
|
#[path = "../linux/dir.rs"]
pub(crate) mod dir;
#[path = "../linux/fadvise.rs"]
pub(crate) mod fadvise;
#[path = "../linux/file.rs"]
pub(crate) mod file;
use crate::dir::SeekLoc;
use std::convert::TryInto;
use std::io::{Error, Result};
impl SeekLoc {
pub unsafe fn from_raw(loc: i64) -> Result<Self> {
// The cookie (or `loc`) is an opaque value, and applications aren't supposed to do
// arithmetic on them or pick their own values or have any awareness of the numeric
// range of the values. They're just supposed to pass back in the values that we
// give them. And any value we give them will be convertable back to `long`,
// because that's the type the OS gives them to us in. So return an `EINVAL`.
let loc = loc
.try_into()
.map_err(|_| Error::from_raw_os_error(libc::EINVAL))?;
Ok(Self(loc))
}
}
|
use crate::object::{Object, CompiledFunction, Builtin};
use crate::code::{Instructions, InstructionsFns, Op, make_instruction};
use crate::parser::parse;
use crate::ast;
use crate::token::Token;
use std::{error, fmt};
use std::fmt::Display;
use std::rc::Rc;
use std::cell::RefCell;
use std::borrow::Borrow;
use hashbrown::HashMap;
use enum_iterator::IntoEnumIterator;
pub struct Bytecode<'a> {
pub instructions: &'a Instructions,
pub constants: &'a Vec<Rc<Object>>,
}
#[derive(Clone)]
struct EmittedInstruction {
op_code: Op,
position: usize,
}
impl EmittedInstruction {
fn is_pop(&self) -> bool {
match self.op_code {
Op::Pop => true,
_ => false,
}
}
}
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum SymbolScope {
Global,
Local,
Builtin,
Free,
}
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct Symbol {
name: String,
scope: SymbolScope,
index: usize,
}
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct SymbolTable {
outer: Option<Box<SymbolTable>>,
store: HashMap<String, Rc<Symbol>>,
num_definitions: usize,
free_symbols: Vec<Rc<Symbol>>,
}
impl SymbolTable {
pub fn new() -> SymbolTable {
SymbolTable{
outer: None,
store: HashMap::new(),
num_definitions: 0,
free_symbols: vec![],
}
}
pub fn new_enclosed_symbol_table(outer: SymbolTable) -> SymbolTable {
SymbolTable{
outer: Some(Box::new(outer)),
store: HashMap::new(),
num_definitions: 0,
free_symbols: vec![],
}
}
fn define(&mut self, name: &str) -> Rc<Symbol> {
let scope = match &self.outer {
Some(_) => SymbolScope::Local,
_ => SymbolScope::Global,
};
let symbol = Rc::new(Symbol{name: name.to_string(), scope, index: self.num_definitions});
self.store.insert(name.to_string(), Rc::clone(&symbol));
self.num_definitions += 1;
symbol
}
fn define_builtin(&mut self, name: String, index: usize) -> Rc<Symbol> {
let symbol = Rc::new(Symbol{name: name.clone(), scope: SymbolScope::Builtin, index: index});
self.store.insert(name, Rc::clone(&symbol));
symbol
}
pub fn load_builtins(&mut self) {
for builtin in Builtin::into_enum_iter() {
self.define_builtin(builtin.string(), builtin as usize);
}
}
fn define_free(&mut self, original: &Rc<Symbol>) -> Rc<Symbol> {
self.free_symbols.push(Rc::clone(original));
let symbol = Rc::new(Symbol{
name: original.name.clone(),
scope: SymbolScope::Free,
index: self.free_symbols.len() - 1,
});
self.store.insert(symbol.name.clone(), Rc::clone(&symbol));
symbol
}
fn resolve(&mut self, name: &str) -> Option<Rc<Symbol>> {
// TODO: clean this mess up
match self.store.get(name) {
Some(sym) => Some(Rc::clone(&sym)),
None => match &mut self.outer {
Some(outer) => {
match outer.resolve(name) {
Some(sym) => {
match sym.scope {
SymbolScope::Global | SymbolScope::Builtin => Some(Rc::clone(&sym)),
SymbolScope::Local | SymbolScope::Free => {
let free = self.define_free(&sym);
Some(free)
}
}
},
None => None,
}
},
None => None,
},
}
}
}
struct CompilationScope {
instructions: Instructions,
last_instruction: Option<EmittedInstruction>,
previous_instruction: Option<EmittedInstruction>,
}
pub struct Compiler {
pub constants: Vec<Rc<Object>>,
pub symbol_table: SymbolTable,
scopes: Vec<CompilationScope>,
scope_index: usize,
}
impl Compiler {
pub fn new() -> Compiler {
let mut symbol_table = SymbolTable::new();
symbol_table.load_builtins();
Compiler{
constants: vec![],
symbol_table,
scopes: vec![CompilationScope{
instructions: vec![],
last_instruction: None,
previous_instruction: None}],
scope_index: 0,
}
}
pub fn new_with_state(symbol_table: SymbolTable, constants: Vec<Rc<Object>>) -> Compiler {
Compiler{
constants,
symbol_table,
scopes: vec![CompilationScope{
instructions: vec![],
last_instruction: None,
previous_instruction: None}],
scope_index: 0,
}
}
pub fn compile(&mut self, node: ast::Node) -> Result {
match node {
ast::Node::Program(prog) => self.compile_program(&prog)?,
ast::Node::Statement(stmt) => self.compile_statement(&stmt)?,
ast::Node::Expression(exp) => self.compile_expression(&exp)?,
}
Ok(self.bytecode())
}
pub fn current_instructions(&self) -> &Instructions {
&self.scopes[self.scope_index].instructions
}
pub fn bytecode(&self) -> Bytecode {
Bytecode{
instructions: &self.scopes[self.scope_index].instructions,
constants: &self.constants,
}
}
fn emit(&mut self, op: Op, operands: &Vec<usize>) -> usize {
let mut ins = make_instruction(op.clone(), &operands);
let pos= self.add_instruction(&mut ins);
self.set_last_instruction(op, pos);
return pos;
}
fn set_last_instruction(&mut self, op_code: Op, position: usize) {
match &self.scopes[self.scope_index].last_instruction {
Some(ins) => self.scopes[self.scope_index].previous_instruction = Some(ins.clone()),
_ => (),
}
self.scopes[self.scope_index].last_instruction = Some(EmittedInstruction{op_code, position});
}
fn add_instruction(&mut self, ins: &Vec<u8>) -> usize {
let pos = self.scopes[self.scope_index].instructions.len();
self.scopes[self.scope_index].instructions.extend_from_slice(ins);
return pos;
}
fn add_constant(&mut self, obj: Object) -> usize {
self.constants.push(Rc::new(obj));
return self.constants.len() - 1;
}
fn compile_program(&mut self, prog: &ast::Program) -> ::std::result::Result<(), CompileError> {
for stmt in &prog.statements {
self.compile_statement(stmt)?
}
Ok(())
}
fn compile_statement(&mut self, stmt: &ast::Statement) -> ::std::result::Result<(), CompileError> {
match stmt {
ast::Statement::Expression(exp) => {
self.compile_expression(&exp.expression)?;
// expressions put their value on the stack so this should be popped off since it doesn't get reused
self.emit(Op::Pop, &vec![]);
},
ast::Statement::Return(ret) => {
self.compile_expression(&ret.value);
self.emit(Op::ReturnValue, &vec![]);
},
ast::Statement::Let(stmt) => {
let symbol = self.symbol_table.define(&stmt.name);
self.compile_expression(&stmt.value)?;
match &symbol.scope {
SymbolScope::Global => self.emit(Op::SetGobal, &vec![symbol.index]),
SymbolScope::Local => self.emit(Op::SetLocal, &vec![symbol.index]),
SymbolScope::Builtin => return Err(CompileError{message: "can't assign to builtin function name".to_string()}),
SymbolScope::Free => panic!("free not here"),
};
},
}
Ok(())
}
fn compile_block_statement(&mut self, stmt: &ast::BlockStatement) -> ::std::result::Result<(), CompileError> {
for stmt in &stmt.statements {
self.compile_statement(stmt)?;
}
Ok(())
}
fn compile_expression(&mut self, exp: &ast::Expression) -> ::std::result::Result<(), CompileError> {
match exp {
ast::Expression::Integer(int) => {
let int = Object::Int(*int);
let operands = vec![self.add_constant(int)];
self.emit(Op::Constant, &operands);
},
ast::Expression::Boolean(b) => {
if *b {
self.emit(Op::True, &vec![]);
} else {
self.emit(Op::False, &vec![]);
}
},
ast::Expression::String(s) => {
let operands = vec![self.add_constant(Object::String(s.to_string()))];
self.emit(Op::Constant, &operands);
},
ast::Expression::Infix(exp) => {
if exp.operator == Token::Lt {
self.compile_expression(&exp.right);
self.compile_expression(&exp.left);
self.emit(Op::GreaterThan, &vec![]);
return Ok(());
}
self.compile_expression(&exp.left);
self.compile_expression(&exp.right);
match exp.operator {
Token::Plus => self.emit(Op::Add, &vec![]),
Token::Minus => self.emit(Op::Sub, &vec![]),
Token::Asterisk => self.emit(Op::Mul, &vec![]),
Token::Slash => self.emit(Op::Div, &vec![]),
Token::Gt => self.emit(Op::GreaterThan, &vec![]),
Token::Eq => self.emit(Op::Equal, &vec![]),
Token::Neq => self.emit(Op::NotEqual, &vec![]),
_ => return Err(CompileError{message: format!("unknown operator {:?}", exp.operator)}),
};
},
ast::Expression::Prefix(exp) => {
self.compile_expression(&exp.right);
match exp.operator {
Token::Minus => self.emit(Op::Minus, &vec![]),
Token::Bang => self.emit(Op::Bang, &vec![]),
_ => return Err(CompileError{message: format!("unknown operator {:?}", exp.operator)}),
};
},
ast::Expression::If(ifexp) => {
self.compile_expression(&ifexp.condition);
let jump_not_truthy_pos = self.emit(Op::JumpNotTruthy, &vec![9999]);
self.compile_block_statement(&ifexp.consequence);
if self.last_instruction_is(Op::Pop) {
self.remove_last_instruction();
}
let jump_pos = self.emit(Op::Jump, &vec![9999]);
let after_consequence_pos = self.scopes[self.scope_index].instructions.len();
self.change_operand(jump_not_truthy_pos, after_consequence_pos);
if let Some(alternative) = &ifexp.alternative {
self.compile_block_statement(alternative)?;
if self.last_instruction_is(Op::Pop) {
self.remove_last_instruction();
}
} else {
self.emit(Op::Null, &vec![]);
}
let after_alternative_pos = self.scopes[self.scope_index].instructions.len();
self.change_operand(jump_pos, after_alternative_pos);
},
ast::Expression::Identifier(name) => {
match self.symbol_table.resolve(name) {
Some(sym) => {
self.load_symbol(&sym);
},
_ => panic!("symbol not resolved {:?}", name)
}
},
ast::Expression::Array(array) => {
for el in &array.elements {
self.compile_expression(el)?;
}
self.emit(Op::Array, &vec![array.elements.len()]);
},
ast::Expression::Hash(hash) => {
let mut keys: Vec<&ast::Expression> = hash.pairs.keys().into_iter().collect();
keys.sort_by(|a, b| (*a).string().cmp(&(*b).string()));
for k in &keys {
self.compile_expression(*k)?;
self.compile_expression(hash.pairs.get(*k).unwrap())?;
};
self.emit(Op::Hash, &vec![keys.len() * 2]);
},
ast::Expression::Index(idx) => {
self.compile_expression(&idx.left)?;
self.compile_expression(&idx.index)?;
self.emit(Op::Index, &vec![]);
},
ast::Expression::Function(func) => {
self.enter_scope();
for arg in &func.parameters {
self.symbol_table.define(&arg.name);
}
self.compile_block_statement(&func.body);
if self.last_instruction_is(Op::Pop) {
self.replace_last_pop_with_return();
}
if !self.last_instruction_is(Op::ReturnValue) {
self.emit(Op::Return, &vec![]);
}
let free_symbols = self.symbol_table.free_symbols.clone();
let num_locals = self.symbol_table.num_definitions;
let instructions = self.leave_scope();
for sym in &free_symbols {
self.load_symbol(sym);
}
let compiled_func = Object::CompiledFunction(Rc::new(CompiledFunction{instructions, num_locals, num_parameters: func.parameters.len()}));
let func_index= self.add_constant(compiled_func);
self.emit(Op::Closure, &vec![func_index, free_symbols.len()]);
},
ast::Expression::Call(exp) => {
self.compile_expression(&exp.function);
for arg in &exp.arguments {
self.compile_expression(arg);
}
self.emit(Op::Call, &vec![exp.arguments.len()]);
},
_ => panic!("not implemented {:?}", exp)
}
Ok(())
}
fn load_symbol(&mut self, symbol: &Rc<Symbol>) {
match &symbol.scope {
SymbolScope::Global => self.emit(Op::GetGlobal, &vec![symbol.index]),
SymbolScope::Local => self.emit(Op::GetLocal, &vec![symbol.index]),
SymbolScope::Builtin => self.emit(Op::GetBuiltin, &vec![symbol.index]),
SymbolScope::Free => self.emit(Op::GetFree, &vec![symbol.index]),
};
}
fn replace_last_pop_with_return(&mut self) {
let mut last_pos = 0;
if let Some(ref ins) = self.scopes[self.scope_index].last_instruction {
last_pos = ins.position;
};
self.replace_instruction(last_pos, &make_instruction(Op::ReturnValue, &vec![]));
if let Some(ref mut ins) = self.scopes[self.scope_index].last_instruction {
ins.op_code = Op::ReturnValue;
}
}
fn last_instruction_is(&self, op: Op) -> bool {
if let Some(ins) = &self.scopes[self.scope_index].last_instruction {
ins.op_code == op
} else {
false
}
}
fn enter_scope(&mut self) {
let scope = CompilationScope{
instructions: vec![],
last_instruction: None,
previous_instruction: None,
};
self.scopes.push(scope);
self.scope_index += 1;
self.symbol_table = SymbolTable::new_enclosed_symbol_table(self.symbol_table.clone());
}
fn leave_scope(&mut self) -> Instructions {
self.scope_index -= 1;
match &self.symbol_table.outer {
Some(outer) => self.symbol_table = outer.as_ref().clone(),
None => panic!("can't leave top level scope"),
}
self.scopes.pop().unwrap().instructions
}
fn remove_last_instruction(&mut self) {
let ref mut scope = self.scopes[self.scope_index];
let pos = match &scope.last_instruction {
Some(ins) => ins.position,
_ => 0,
};
scope.instructions.truncate(pos);
scope.last_instruction = scope.previous_instruction.clone();
}
fn replace_instruction(&mut self, pos: usize, ins: &[u8]) {
let mut i = 0;
let ref mut scope = self.scopes[self.scope_index];
while i < ins.len() {
scope.instructions[pos + i] = ins[i];
i += 1;
}
}
fn change_operand(&mut self, pos: usize, operand: usize) {
let op = unsafe { ::std::mem::transmute(self.scopes[self.scope_index].instructions[pos]) };
let ins = make_instruction(op, &vec![operand]);
self.replace_instruction(pos, &ins);
}
}
type Result<'a> = ::std::result::Result<Bytecode<'a>, CompileError>;
#[derive(Debug)]
pub struct CompileError {
pub message: String,
}
impl error::Error for CompileError {
fn description(&self) -> &str { &self.message }
}
impl Display for CompileError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "CompileError: {}", &self.message)
}
}
#[cfg(test)]
mod test {
use super::*;
struct CompilerTestCase<'a> {
input: &'a str,
expected_constants: Vec<Object>,
expected_instructions: Vec<Instructions>,
}
#[test]
fn integer_arithmetic() {
let tests = vec![
CompilerTestCase{
input:"1 + 2",
expected_constants: vec![Object::Int(1), Object::Int(2)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::Add, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input:"1; 2",
expected_constants: vec![Object::Int(1), Object::Int(2)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Pop, &vec![]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "1 - 2",
expected_constants: vec![Object::Int(1), Object::Int(2)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::Sub, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "1 * 2",
expected_constants: vec![Object::Int(1), Object::Int(2)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::Mul, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "2 / 1",
expected_constants: vec![Object::Int(2), Object::Int(1)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::Div, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "-1",
expected_constants: vec![Object::Int(1)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Minus, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
];
run_compiler_tests(tests)
}
#[test]
fn boolean_expressions() {
let tests = vec![
CompilerTestCase{
input: "true",
expected_constants: vec![],
expected_instructions: vec![
make_instruction(Op::True, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "false",
expected_constants: vec![],
expected_instructions: vec![
make_instruction(Op::False, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "1 > 2",
expected_constants: vec![Object::Int(1), Object::Int(2)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::GreaterThan, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "1 < 2",
expected_constants: vec![Object::Int(2), Object::Int(1)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::GreaterThan, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "1 == 2",
expected_constants: vec![Object::Int(1), Object::Int(2)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::Equal, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "1 != 2",
expected_constants: vec![Object::Int(1), Object::Int(2)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::NotEqual, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "true == false",
expected_constants: vec![],
expected_instructions: vec![
make_instruction(Op::True, &vec![]),
make_instruction(Op::False, &vec![]),
make_instruction(Op::Equal, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "true != false",
expected_constants: vec![],
expected_instructions: vec![
make_instruction(Op::True, &vec![]),
make_instruction(Op::False, &vec![]),
make_instruction(Op::NotEqual, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "!true",
expected_constants: vec![],
expected_instructions: vec![
make_instruction(Op::True, &vec![]),
make_instruction(Op::Bang, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
];
run_compiler_tests(tests)
}
#[test]
fn conditionals() {
let tests = vec![
CompilerTestCase{
input: "if (true) { 10 }; 3333;",
expected_constants: vec![Object::Int(10), Object::Int(3333)],
expected_instructions: vec![
// 0000
make_instruction(Op::True, &vec![]),
// 0001
make_instruction(Op::JumpNotTruthy, &vec![10]),
// 0004
make_instruction(Op::Constant, &vec![0]),
// 0007
make_instruction(Op::Jump, &vec![11]),
// 0010
make_instruction(Op::Null, &vec![]),
// 0011
make_instruction(Op::Pop, &vec![]),
// 0012
make_instruction(Op::Constant, &vec![1]),
// 0015
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "if (true) { 10 } else { 20 }; 3333;",
expected_constants: vec![Object::Int(10), Object::Int(20), Object::Int(3333)],
expected_instructions: vec![
// 0000
make_instruction(Op::True, &vec![]),
// 0001
make_instruction(Op::JumpNotTruthy, &vec![10]),
// 0004
make_instruction(Op::Constant, &vec![0]),
// 0007
make_instruction(Op::Jump, &vec![13]),
// 0010
make_instruction(Op::Constant, &vec![1]),
// 0013
make_instruction(Op::Pop, &vec![]),
// 0014
make_instruction(Op::Constant, &vec![2]),
// 0017
make_instruction(Op::Pop, &vec![]),
],
},
];
run_compiler_tests(tests)
}
#[test]
fn test_global_let_statements() {
let tests = vec![
CompilerTestCase{
input: "let one = 1; let two = 2;",
expected_constants: vec![Object::Int(1), Object::Int(2)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::SetGobal, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::SetGobal, &vec![1]),
],
},
CompilerTestCase{
input: "let one = 1; one;",
expected_constants: vec![Object::Int(1)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::SetGobal, &vec![0]),
make_instruction(Op::GetGlobal, &vec![0]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "let one = 1; let two = one; two;",
expected_constants: vec![Object::Int(1)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::SetGobal, &vec![0]),
make_instruction(Op::GetGlobal, &vec![0]),
make_instruction(Op::SetGobal, &vec![1]),
make_instruction(Op::GetGlobal, &vec![1]),
make_instruction(Op::Pop, &vec![]),
],
},
];
run_compiler_tests(tests);
}
#[test]
fn define() {
let mut table = SymbolTable::new();
let a = table.define("a");
let exp_a = Rc::new(Symbol{name: "a".to_string(), scope: SymbolScope::Global, index: 0});
if a != exp_a {
panic!("exp: {:?}\ngot: {:?}", exp_a, a);
}
let b = table.define("b");
let exp_b = Rc::new(Symbol{name: "b".to_string(), scope: SymbolScope::Global, index: 1});
if b != exp_b {
panic!("exp: {:?}\ngot: {:?}", exp_b, b);
}
}
#[test]
fn resolve_global() {
let mut global = SymbolTable::new();
global.define("a");
global.define("b");
let exp_a = Rc::new(Symbol{name: "a".to_string(), scope: SymbolScope::Global, index: 0});
let exp_b = Rc::new(Symbol{name: "b".to_string(), scope: SymbolScope::Global, index: 1});
match global.resolve("a") {
Some(sym) => {
if sym != exp_a {
panic!("a not equal: exp: {:?} got: {:?}", exp_a, sym);
}
},
_ => panic!("a didn't resovle"),
}
match global.resolve("b") {
Some(sym) => {
if sym != exp_b {
panic!("b not equal: exp: {:?} got: {:?}", exp_b, sym);
}
},
_ => panic!("b didn't resolve"),
}
}
#[test]
fn string_expressions() {
let tests = vec![
CompilerTestCase{
input: "\"monkey\"",
expected_constants: vec![Object::String("monkey".to_string())],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "\"mon\" + \"key\"",
expected_constants: vec![Object::String("mon".to_string()), Object::String("key".to_string())],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::Add, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
];
run_compiler_tests(tests);
}
#[test]
fn array_literals() {
let tests = vec![
CompilerTestCase{
input: "[]",
expected_constants: vec![],
expected_instructions: vec![
make_instruction(Op::Array, &vec![0]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "[1, 2, 3]",
expected_constants: vec![Object::Int(1), Object::Int(2), Object::Int(3)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::Constant, &vec![2]),
make_instruction(Op::Array, &vec![3]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "[1 + 2, 3 - 4, 5 * 6]",
expected_constants: vec![Object::Int(1), Object::Int(2), Object::Int(3), Object::Int(4), Object::Int(5), Object::Int(6)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::Add, &vec![]),
make_instruction(Op::Constant, &vec![2]),
make_instruction(Op::Constant, &vec![3]),
make_instruction(Op::Sub, &vec![]),
make_instruction(Op::Constant, &vec![4]),
make_instruction(Op::Constant, &vec![5]),
make_instruction(Op::Mul, &vec![]),
make_instruction(Op::Array, &vec![3]),
make_instruction(Op::Pop, &vec![]),
],
},
];
run_compiler_tests(tests);
}
#[test]
fn hash_literals() {
let tests = vec![
CompilerTestCase{
input: "{}",
expected_constants: vec![],
expected_instructions: vec![
make_instruction(Op::Hash, &vec![0]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "{1: 2, 3: 4, 5: 6}",
expected_constants: vec![Object::Int(1), Object::Int(2), Object::Int(3), Object::Int(4), Object::Int(5), Object::Int(6)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::Constant, &vec![2]),
make_instruction(Op::Constant, &vec![3]),
make_instruction(Op::Constant, &vec![4]),
make_instruction(Op::Constant, &vec![5]),
make_instruction(Op::Hash, &vec![6]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "{1: 2 + 3, 4: 5 * 6}",
expected_constants: vec![Object::Int(1), Object::Int(2), Object::Int(3), Object::Int(4), Object::Int(5), Object::Int(6)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::Constant, &vec![2]),
make_instruction(Op::Add, &vec![]),
make_instruction(Op::Constant, &vec![3]),
make_instruction(Op::Constant, &vec![4]),
make_instruction(Op::Constant, &vec![5]),
make_instruction(Op::Mul, &vec![]),
make_instruction(Op::Hash, &vec![4]),
make_instruction(Op::Pop, &vec![]),
],
},
];
run_compiler_tests(tests);
}
#[test]
fn index_expressions() {
let tests = vec![
CompilerTestCase{
input: "[1, 2, 3][1 + 1]",
expected_constants: vec![Object::Int(1), Object::Int(2), Object::Int(3), Object::Int(1), Object::Int(1)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::Constant, &vec![2]),
make_instruction(Op::Array, &vec![3]),
make_instruction(Op::Constant, &vec![3]),
make_instruction(Op::Constant, &vec![4]),
make_instruction(Op::Add, &vec![]),
make_instruction(Op::Index, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "{1: 2}[2 - 1]",
expected_constants: vec![Object::Int(1), Object::Int(2), Object::Int(2), Object::Int(1)],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::Hash, &vec![2]),
make_instruction(Op::Constant, &vec![2]),
make_instruction(Op::Constant, &vec![3]),
make_instruction(Op::Sub, &vec![]),
make_instruction(Op::Index, &vec![]),
make_instruction(Op::Pop, &vec![]),
],
},
];
run_compiler_tests(tests);
}
#[test]
fn functions() {
let tests = vec![
CompilerTestCase{
input: "fn() { return 5 + 10 }",
expected_constants: vec![
Object::Int(5),
Object::Int(10),
Object::CompiledFunction(Rc::new(CompiledFunction{instructions: concat_instructions(&vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::Add, &vec![]),
make_instruction(Op::ReturnValue, &vec![])
]), num_locals: 0, num_parameters: 0})),
],
expected_instructions: vec![
make_instruction(Op::Closure, &vec![2, 0]),
make_instruction(Op::Pop, &vec![]),
],
},
];
run_compiler_tests(tests);
}
#[test]
fn function_calls() {
let tests = vec![
CompilerTestCase{
input: "fn() { 24 }();",
expected_constants: vec![
Object::Int(24),
Object::CompiledFunction(Rc::new(CompiledFunction{instructions: concat_instructions(&vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::ReturnValue, &vec![]),
]), num_locals: 0, num_parameters: 0})),
],
expected_instructions: vec![
make_instruction(Op::Closure, &vec![1, 0]),
make_instruction(Op::Call, &vec![0]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "let noArg = fn() { 24 }; noArg();",
expected_constants: vec![
Object::Int(24),
Object::CompiledFunction(Rc::new(CompiledFunction{instructions: concat_instructions(&vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::ReturnValue, &vec![]),
]), num_locals: 0, num_parameters: 0})),
],
expected_instructions: vec![
make_instruction(Op::Closure, &vec![1, 0]),
make_instruction(Op::SetGobal, &vec![0]),
make_instruction(Op::GetGlobal, &vec![0]),
make_instruction(Op::Call, &vec![0]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "let oneArg = fn(a) { a }; oneArg(24);",
expected_constants: vec![
Object::CompiledFunction(Rc::new(CompiledFunction{instructions: concat_instructions(&vec![
make_instruction(Op::GetLocal, &vec![0]),
make_instruction(Op::ReturnValue, &vec![]),
]), num_locals: 1, num_parameters: 1})),
Object::Int(24),
],
expected_instructions: vec![
make_instruction(Op::Closure, &vec![0, 0]),
make_instruction(Op::SetGobal, &vec![0]),
make_instruction(Op::GetGlobal, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::Call, &vec![1]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "let manyArg = fn(a, b, c) { a; b; c }; manyArg(24, 25, 26);",
expected_constants: vec![
Object::CompiledFunction(Rc::new(CompiledFunction{instructions: concat_instructions(&vec![
make_instruction(Op::GetLocal, &vec![0]),
make_instruction(Op::Pop, &vec![]),
make_instruction(Op::GetLocal, &vec![1]),
make_instruction(Op::Pop, &vec![]),
make_instruction(Op::GetLocal, &vec![2]),
make_instruction(Op::ReturnValue, &vec![]),
]), num_locals: 3, num_parameters: 3})),
Object::Int(24),
Object::Int(25),
Object::Int(26),
],
expected_instructions: vec![
make_instruction(Op::Closure, &vec![0, 0]),
make_instruction(Op::SetGobal, &vec![0]),
make_instruction(Op::GetGlobal, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::Constant, &vec![2]),
make_instruction(Op::Constant, &vec![3]),
make_instruction(Op::Call, &vec![3]),
make_instruction(Op::Pop, &vec![]),
],
},
];
run_compiler_tests(tests);
}
#[test]
fn compiler_scopes() {
let mut compiler = Compiler::new();
if compiler.scope_index != 0 {
panic!("scope_index wrong, exp: {}, got: {}", 0, compiler.scope_index);
}
compiler.emit(Op::Mul, &vec![]);
let global_symbol_table = compiler.symbol_table.clone();
compiler.enter_scope();
if compiler.scope_index != 1 {
panic!("scope_index wrong, exp: {}, got: {}", 0, compiler.scope_index);
}
compiler.emit(Op::Sub, &vec![]);
let len = compiler.scopes[compiler.scope_index].instructions.len();
if len != 1 {
panic!("instructions length wrong, got: {}", len);
}
match &compiler.scopes[compiler.scope_index].last_instruction {
Some(ins) => {
match ins.op_code {
Op::Sub => (),
_ => panic!("wrong op code {:?}", ins.op_code),
}
},
None => panic!("last instruction not in scope"),
}
match &compiler.symbol_table.outer {
Some(outer) => {
if outer.as_ref() != &global_symbol_table {
panic!("compiler did not enclose symbol table");
}
},
None => panic!("compiler did not enclose symbol table"),
}
compiler.leave_scope();
if compiler.scope_index != 0 {
panic!("wrong scope index, got: {}", compiler.scope_index);
}
if compiler.symbol_table != global_symbol_table {
panic!("compiler did not restore symbol table");
}
if let Some(_) = &compiler.symbol_table.outer {
panic!("compiler modified global symbol table incorrectly");
}
compiler.emit(Op::Add, &vec![]);
let len = compiler.scopes[compiler.scope_index].instructions.len();
if len != 2 {
panic!("instructions length wrong, got: {}", len);
}
match &compiler.scopes[compiler.scope_index].last_instruction {
Some(ins) => {
match ins.op_code {
Op::Add => (),
_ => panic!("wrong op code {:?}", ins.op_code),
}
},
None => panic!("last instruction not in scope"),
}
match &compiler.scopes[compiler.scope_index].previous_instruction {
Some(ins) => {
match ins.op_code {
Op::Mul => (),
_ => panic!("wrong op code {:?}", ins.op_code),
}
},
None => panic!("previous instruction not in scope"),
}
}
#[test]
fn let_statement_scopes() {
let tests = vec![
CompilerTestCase{
input: "let num = 55; fn() { num }",
expected_constants: vec![
Object::Int(55),
Object::CompiledFunction(Rc::new(CompiledFunction{instructions: concat_instructions(&vec![
make_instruction(Op::GetGlobal, &vec![0]),
make_instruction(Op::ReturnValue, &vec![]),
]), num_locals: 0, num_parameters: 0})),
],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::SetGobal, &vec![0]),
make_instruction(Op::Closure, &vec![1, 0]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "fn() { let num = 55; num }",
expected_constants: vec![
Object::Int(55),
Object::CompiledFunction(Rc::new(CompiledFunction{instructions: concat_instructions(&vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::SetLocal, &vec![0]),
make_instruction(Op::GetLocal, &vec![0]),
make_instruction(Op::ReturnValue, &vec![]),
]), num_locals: 1, num_parameters: 0})),
],
expected_instructions: vec![
make_instruction(Op::Closure, &vec![1, 0]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "fn() { let a = 55; let b = 77; a + b}",
expected_constants: vec![
Object::Int(55),
Object::Int(77),
Object::CompiledFunction(Rc::new(CompiledFunction{instructions: concat_instructions(&vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::SetLocal, &vec![0]),
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::SetLocal, &vec![1]),
make_instruction(Op::GetLocal, &vec![0]),
make_instruction(Op::GetLocal, &vec![1]),
make_instruction(Op::Add, &vec![]),
make_instruction(Op::ReturnValue, &vec![]),
]), num_locals: 2, num_parameters: 0})),
],
expected_instructions: vec![
make_instruction(Op::Closure, &vec![2, 0]),
make_instruction(Op::Pop, &vec![]),
],
},
];
run_compiler_tests(tests);
}
#[test]
fn resolve_local() {
let mut global = SymbolTable::new();
global.define("a");
global.define("b");
let mut local = SymbolTable::new_enclosed_symbol_table(global);
local.define("c");
local.define("d");
let tests = vec![
("a", SymbolScope::Global, 0),
("b", SymbolScope::Global, 1),
("c", SymbolScope::Local, 0),
("d", SymbolScope::Local, 1),
];
for (name, scope, index) in tests {
match local.resolve(name) {
Some(symbol) => {
if symbol.scope != scope {
panic!("expected scope {:?} on symbol {:?} but got {:?}", scope, name, symbol.scope);
}
if symbol.index != index {
panic!("expected index {} on symbol {:?} but got {}", index, symbol, symbol.index);
}
},
_ => panic!("couldn't resolve symbol: {}", name),
}
}
}
#[test]
fn resolve_nested_local() {
let mut global = SymbolTable::new();
global.define("a");
global.define("b");
let mut local = SymbolTable::new_enclosed_symbol_table(global);
local.define("c");
local.define("d");
let mut nested_local = SymbolTable::new_enclosed_symbol_table(local.clone());
nested_local.define("e");
nested_local.define("f");
let mut tests = vec![
(local, vec![
("a", SymbolScope::Global, 0),
("b", SymbolScope::Global, 1),
("c", SymbolScope::Local, 0),
("d", SymbolScope::Local, 1),
]),
(nested_local, vec![
("a", SymbolScope::Global, 0),
("b", SymbolScope::Global, 1),
("e", SymbolScope::Local, 0),
("f", SymbolScope::Local, 1),
]),
];
for (table, expected) in &mut tests {
for (name, scope, index) in expected {
match table.resolve(name) {
Some(symbol) => {
if symbol.scope != *scope {
panic!("expected scope {:?} on symbol {:?} but got {:?}", scope, name, symbol.scope);
}
if symbol.index != *index {
panic!("expected index {} on symbol {:?} but got {}", index, symbol, symbol.index);
}
},
_ => panic!("couldn't resolve symbol: {}", name),
}
}
}
}
#[test]
fn builtins() {
let tests = vec![
CompilerTestCase{
input: "len([]); push([], 1);",
expected_constants: vec![Object::Int(1)],
expected_instructions: vec![
make_instruction(Op::GetBuiltin, &vec![0]),
make_instruction(Op::Array, &vec![0]),
make_instruction(Op::Call, &vec![1]),
make_instruction(Op::Pop, &vec![]),
make_instruction(Op::GetBuiltin, &vec![5]),
make_instruction(Op::Array, &vec![0]),
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::Call, &vec![2]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "fn() { len([]) }",
expected_constants: vec![
Object::CompiledFunction(Rc::new(CompiledFunction{instructions: concat_instructions(&vec![
make_instruction(Op::GetBuiltin, &vec![0]),
make_instruction(Op::Array, &vec![0]),
make_instruction(Op::Call, &vec![1]),
make_instruction(Op::ReturnValue, &vec![]),
]), num_locals: 0, num_parameters: 0})),
],
expected_instructions: vec![
make_instruction(Op::Closure, &vec![0, 0]),
make_instruction(Op::Pop, &vec![]),
],
}
];
run_compiler_tests(tests);
}
#[test]
fn define_resolve_builtins() {
let mut global = SymbolTable::new();
let expected = vec![
Symbol{name: "a".to_string(), scope: SymbolScope::Builtin, index: 0},
Symbol{name: "c".to_string(), scope: SymbolScope::Builtin, index: 1},
Symbol{name: "e".to_string(), scope: SymbolScope::Builtin, index: 2},
Symbol{name: "f".to_string(), scope: SymbolScope::Builtin, index: 3},
];
for sym in &expected {
global.define_builtin(sym.name.clone(), sym.index);
}
let first_local = SymbolTable::new_enclosed_symbol_table(global.clone());
let second_local = SymbolTable::new_enclosed_symbol_table(first_local.clone());
for mut table in vec![global, first_local, second_local] {
for sym in &expected {
match table.resolve(&sym.name) {
Some(s) => if s != Rc::new(sym.clone()) {
panic!("exp: {:?}, got: {:?}", sym, s);
},
None => panic!("couldn't resolve symbol {}", sym.name),
}
}
}
}
#[test]
fn closures() {
let tests = vec![
CompilerTestCase{
input: "
fn(a) {
fn(b) {
a + b
}
}",
expected_constants: vec![
Object::CompiledFunction(Rc::new(CompiledFunction{instructions: concat_instructions(&vec![
make_instruction(Op::GetFree, &vec![0]),
make_instruction(Op::GetLocal, &vec![0]),
make_instruction(Op::Add, &vec![]),
make_instruction(Op::ReturnValue, &vec![]),
]), num_locals: 1, num_parameters: 1})),
],
expected_instructions: vec![
make_instruction(Op::Closure, &vec![1, 0]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "
fn(a) {
fn(b) {
fn(c) {
a + b + c
}
}
};",
expected_constants: vec![
Object::CompiledFunction(Rc::new(CompiledFunction{instructions: concat_instructions(&vec![
make_instruction(Op::GetFree, &vec![0]),
make_instruction(Op::GetFree, &vec![1]),
make_instruction(Op::Add, &vec![]),
make_instruction(Op::GetLocal, &vec![0]),
make_instruction(Op::Add, &vec![]),
make_instruction(Op::ReturnValue, &vec![]),
]), num_locals: 1, num_parameters: 1})),
Object::CompiledFunction(Rc::new(CompiledFunction{instructions: concat_instructions(&vec![
make_instruction(Op::GetFree, &vec![0]),
make_instruction(Op::GetLocal, &vec![0]),
make_instruction(Op::Closure, &vec![0, 2]),
make_instruction(Op::ReturnValue, &vec![]),
]), num_locals: 1, num_parameters: 1})),
Object::CompiledFunction(Rc::new(CompiledFunction{instructions: concat_instructions(&vec![
make_instruction(Op::GetLocal, &vec![0]),
make_instruction(Op::Closure, &vec![1, 1]),
make_instruction(Op::ReturnValue, &vec![]),
]), num_locals: 1, num_parameters: 1})),
],
expected_instructions: vec![
make_instruction(Op::Closure, &vec![2, 0]),
make_instruction(Op::Pop, &vec![]),
],
},
CompilerTestCase{
input: "
let global = 55;
fn() {
let a = 66;
fn() {
let b = 77;
fn() {
let c = 88;
global + a + b + c;
}
}
}",
expected_constants: vec![
Object::Int(55),
Object::Int(66),
Object::Int(77),
Object::Int(88),
Object::CompiledFunction(Rc::new(CompiledFunction{instructions: concat_instructions(&vec![
make_instruction(Op::Constant, &vec![3]),
make_instruction(Op::SetLocal, &vec![0]),
make_instruction(Op::GetGlobal, &vec![0]),
make_instruction(Op::GetFree, &vec![0]),
make_instruction(Op::Add, &vec![]),
make_instruction(Op::GetFree, &vec![1]),
make_instruction(Op::Add, &vec![]),
make_instruction(Op::GetLocal, &vec![0]),
make_instruction(Op::Add, &vec![]),
make_instruction(Op::ReturnValue, &vec![]),
]), num_locals: 1, num_parameters: 0})),
Object::CompiledFunction(Rc::new(CompiledFunction{instructions: concat_instructions(&vec![
make_instruction(Op::Constant, &vec![2]),
make_instruction(Op::SetLocal, &vec![0]),
make_instruction(Op::GetFree, &vec![0]),
make_instruction(Op::GetLocal, &vec![0]),
make_instruction(Op::Closure, &vec![4, 2]),
make_instruction(Op::ReturnValue, &vec![]),
]), num_locals: 1, num_parameters: 0})),
Object::CompiledFunction(Rc::new(CompiledFunction{instructions: concat_instructions(&vec![
make_instruction(Op::Constant, &vec![1]),
make_instruction(Op::SetLocal, &vec![0]),
make_instruction(Op::GetLocal, &vec![0]),
make_instruction(Op::Closure, &vec![5, 1]),
make_instruction(Op::ReturnValue, &vec![]),
]), num_locals: 1, num_parameters: 0})),
],
expected_instructions: vec![
make_instruction(Op::Constant, &vec![0]),
make_instruction(Op::SetGobal, &vec![0]),
make_instruction(Op::Closure, &vec![6, 0]),
make_instruction(Op::Pop, &vec![]),
],
},
];
run_compiler_tests(tests);
}
#[test]
fn resolve_free() {
let mut global = SymbolTable::new();
global.define("a");
global.define("b");
let mut first_local = SymbolTable::new_enclosed_symbol_table(global.clone());
first_local.define("c");
first_local.define("d");
let mut second_local = SymbolTable::new_enclosed_symbol_table(first_local.clone());
second_local.define("e");
second_local.define("f");
let mut tests = vec![
(first_local, vec![
Symbol{name: "a".to_string(), scope: SymbolScope::Global, index: 0},
Symbol{name: "b".to_string(), scope: SymbolScope::Global, index: 1},
Symbol{name: "c".to_string(), scope: SymbolScope::Local, index: 0},
Symbol{name: "d".to_string(), scope: SymbolScope::Local, index: 1},
], vec![]),
(second_local, vec![
Symbol{name: "a".to_string(), scope: SymbolScope::Global, index: 0},
Symbol{name: "b".to_string(), scope: SymbolScope::Global, index: 1},
Symbol{name: "c".to_string(), scope: SymbolScope::Free, index: 0},
Symbol{name: "d".to_string(), scope: SymbolScope::Free, index: 1},
Symbol{name: "e".to_string(), scope: SymbolScope::Local, index: 0},
Symbol{name: "f".to_string(), scope: SymbolScope::Local, index: 1},
], vec![
Symbol{name: "c".to_string(), scope: SymbolScope::Local, index: 0},
Symbol{name: "d".to_string(), scope: SymbolScope::Local, index: 1},
]),
];
for mut t in &mut tests {
let (table, expected_symbols, expected_free_symbols) = &mut t;
for exp in expected_symbols.clone() {
match table.resolve(&exp.name) {
Some(got) => assert_eq!(exp, *got),
None => panic!("name {} not resolvable", exp.name),
}
}
assert_eq!(table.free_symbols.len(), expected_free_symbols.len());
let mut i = 0;
for exp in expected_free_symbols {
let got = (*table.free_symbols[i]).borrow();
assert_eq!(*exp, *got);
i += 1;
}
}
}
#[test]
fn resolve_unresolvable_free() {
let mut global = SymbolTable::new();
global.define("a");
let mut first_local = SymbolTable::new_enclosed_symbol_table(global);
first_local.define("c");
let mut second_local = SymbolTable::new_enclosed_symbol_table(first_local);
second_local.define("e");
second_local.define("f");
let expected = vec![
Symbol{name: "a".to_string(), scope: SymbolScope::Global, index: 0},
Symbol{name: "c".to_string(), scope: SymbolScope::Free, index: 0},
Symbol{name: "e".to_string(), scope: SymbolScope::Local, index: 0},
Symbol{name: "f".to_string(), scope: SymbolScope::Local, index: 1},
];
for exp in &expected {
match second_local.resolve(&exp.name) {
Some(got) => assert_eq!(exp, got.borrow()),
None => panic!("name {} not resolvable", exp.name),
}
}
for name in vec!["b", "d"] {
if let Some(_) = second_local.resolve(name) {
panic!("name {} resolved but was not expected to", name);
}
}
}
fn run_compiler_tests(tests: Vec<CompilerTestCase>) {
for t in tests {
let program = parse(t.input).unwrap();
let mut compiler = Compiler::new();
let bytecode = compiler.compile(program).unwrap_or_else(
|err| panic!("{} error compiling on input: {}. want: {:?}", err.message, t.input, t.expected_instructions));
test_instructions(&t.expected_instructions, &bytecode.instructions).unwrap_or_else(
|err| panic!("{} error on instructions for: {}\nexp: {}\ngot: {}", &err.message, t.input, concat_instructions(&t.expected_instructions).string(), bytecode.instructions.string()));
test_constants(&t.expected_constants, bytecode.constants.borrow()).unwrap_or_else(
|err| panic!("{} error on constants for : {}", &err.message, t.input));
}
}
fn test_instructions(expected: &Vec<Instructions>, actual: &Instructions) -> ::std::result::Result<(), CompileError> {
let concatted = concat_instructions(expected);
if concatted.len() != actual.len() {
return Err(CompileError{message: format!("instruction lengths not equal\n\texp:\n{:?}\n\tgot:\n{:?}", concatted.string(), actual.string())})
}
let mut pos = 0;
for (exp, got) in concatted.into_iter().zip(actual) {
if exp != *got {
return Err(CompileError { message: format!("exp\n{:?} but got\n{} at position {:?}", exp, got, pos) });
}
pos = pos + 1;
}
Ok(())
}
fn test_constants(expected: &Vec<Object>, actual: &Vec<Rc<Object>>) -> ::std::result::Result<(), CompileError> {
let mut pos = 0;
for (exp, got) in expected.into_iter().zip(actual) {
let got = got.borrow();
match (exp, got) {
(Object::Int(exp), Object::Int(got)) => if *exp != *got {
return Err(CompileError{message: format!("constant {}, exp: {} got: {}", pos, exp, got)})
},
(Object::String(exp), Object::String(got)) => if exp != got {
return Err(CompileError{message: format!("constant {}, exp: {} got: {}", pos, exp, got)})
},
(Object::CompiledFunction(exp), Object::CompiledFunction(got)) => if exp != got {
return Err(CompileError{message: format!("constant {}, exp: {:?} got: {:?}, instructions exp:\n{}\ngot\n{}", pos, exp, got, exp.instructions.string(), got.instructions.string())})
},
_ => panic!("can't compare objects: exp: {:?} got: {:?}", exp, got)
}
pos = pos + 1;
}
Ok(())
}
fn concat_instructions(instructions: &Vec<Instructions>) -> Instructions {
let mut concatted = Instructions::new();
for i in instructions {
for u in i {
concatted.push(*u);
}
}
concatted
}
} |
use std::fs;
use std::path::PathBuf;
use structopt::StructOpt;
use sequence::{Options, transcribe_sequence};
fn main() {
let strand = Seq::from_args();
match strand {
Seq::Transcribe {file, is_dna, seq_len} => {
let contents = fs::read_to_string(&file).unwrap();
println!("count: {:?}", contents.chars().count());
let sequence = contents.replace("\n", "");
let result = transcribe_sequence(sequence, Options { seq_len, is_dna });
println!("{}", result);
},
Seq::Translate {} => {},
Seq::Identify {file } => {},
}
}
#[derive(StructOpt)]
enum Seq {
Transcribe {
#[structopt(parse(from_os_str))]
file: PathBuf,
#[structopt(long)]
is_dna: bool,
#[structopt(default_value = "100", long)]
seq_len: usize,
},
Translate {
},
Identify {
#[structopt(parse(from_os_str))]
file: PathBuf,
}
}
|
pub mod token_kind;
pub mod types;
use token_kind::*;
use types::*;
use logos::Logos;
pub struct Lexer<'input> {
input: &'input str,
generated: logos::SpannedIter<'input, LogosToken>,
eof: bool,
}
impl<'input> Lexer<'input> {
pub fn new(input: &'input str) -> Self {
Self {
input: input,
generated: LogosToken::lexer(input).spanned(),
eof: false,
}
}
}
impl<'input> Iterator for Lexer<'input> {
type Item = Token;
fn next(&mut self) -> Option<Self::Item> {
match self.generated.next() {
Some((token, span)) => Some(Token {
kind: TokenKind::from(token),
span: span.into(),
}),
None if self.eof => None,
None => {
self.eof = true;
Some(Token {
kind: TokenKind::Eof,
span: (self.input.len() - 1..self.input.len() - 1).into(),
})
}
}
}
}
|
use nu::{
serve_plugin, CallInfo, Plugin, Primitive, ReturnSuccess, ReturnValue, ShellError, Signature,
SyntaxShape, Tag, Tagged, TaggedDictBuilder, Value,
};
struct Embed {
field: Option<String>,
values: Vec<Tagged<Value>>,
}
impl Embed {
fn new() -> Embed {
Embed {
field: None,
values: Vec::new(),
}
}
fn embed(&mut self, value: Tagged<Value>) -> Result<(), ShellError> {
match value {
Tagged { item, tag } => match &self.field {
Some(_) => {
self.values.push(Tagged {
item: item,
tag: tag,
});
Ok(())
}
None => Err(ShellError::string(
"embed needs a field when embedding a value",
)),
},
}
}
}
impl Plugin for Embed {
fn config(&mut self) -> Result<Signature, ShellError> {
Ok(Signature::build("embed")
.desc("Embeds a new field to the table.")
.required("Field", SyntaxShape::String)
.rest(SyntaxShape::String)
.filter())
}
fn begin_filter(&mut self, call_info: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {
if let Some(args) = call_info.args.positional {
match &args[0] {
Tagged {
item: Value::Primitive(Primitive::String(s)),
..
} => {
self.field = Some(s.clone());
self.values = Vec::new();
}
_ => {
return Err(ShellError::string(format!(
"Unrecognized type in params: {:?}",
args[0]
)))
}
}
}
Ok(vec![])
}
fn filter(&mut self, input: Tagged<Value>) -> Result<Vec<ReturnValue>, ShellError> {
self.embed(input)?;
Ok(vec![])
}
fn end_filter(&mut self) -> Result<Vec<ReturnValue>, ShellError> {
let mut root = TaggedDictBuilder::new(Tag::unknown());
root.insert_tagged(
self.field.as_ref().unwrap(),
Tagged {
item: Value::Table(self.values.clone()),
tag: Tag::unknown(),
},
);
Ok(vec![ReturnSuccess::value(root.into_tagged_value())])
}
}
fn main() {
serve_plugin(&mut Embed::new());
}
|
#![allow(unsafe_code)]
#![allow(unused)]
//use super::smol_stack::{Blob};
use smoltcp::phy::{self, Device, DeviceCapabilities, Medium};
use smoltcp::time::Instant;
use smoltcp::{Error};
use std::cell::RefCell;
use std::collections::VecDeque;
use std::io;
use std::rc::Rc;
use std::sync::{Arc, Condvar, Mutex};
use std::vec::Vec;
use std::time::Duration;
use std::isize;
use std::ops::Deref;
use std::slice;
//static ERR_WOULD_BLOCK: u32 = 1;
pub enum VirtualTunReadError {
WouldBlock
}
#[derive(Debug)]
pub enum VirtualTunWriteError {
NoData
}
pub type OnVirtualTunRead = Arc<dyn Fn(&mut [u8]) -> Result<usize,VirtualTunReadError> + Send + Sync>;
//pub type OnVirtualTunWrite = Arc<dyn Fn(&dyn FnOnce(&mut [u8]) , usize) -> Result<(), VirtualTunWriteError> + Send + Sync>;
pub type OnVirtualTunWrite = Arc<
dyn Fn(&mut dyn FnMut(&mut [u8]), usize) -> Result<(), VirtualTunWriteError> + Send + Sync,
>;
#[derive(Clone)]
pub struct VirtualTunInterface {
mtu: usize,
//has_data: Arc<(Mutex<()>, Condvar)>,
on_virtual_tun_read: OnVirtualTunRead,
on_virtual_tun_write: OnVirtualTunWrite,
}
/*
fn copy_slice(dst: &mut [u8], src: &[u8]) -> usize {
let mut c = 0;
for (d, s) in dst.iter_mut().zip(src.iter()) {
*d = *s;
c += 1;
}
c
}
*/
impl<'a> VirtualTunInterface {
pub fn new(
_name: &str,
on_virtual_tun_read: OnVirtualTunRead,
on_virtual_tun_write: OnVirtualTunWrite,
//has_data: Arc<(Mutex<()>, Condvar)>,
mtu: usize
) -> smoltcp::Result<VirtualTunInterface> {
//let mtu = 1500; //??
Ok(VirtualTunInterface {
mtu: mtu,
//has_data: has_data,
on_virtual_tun_read: on_virtual_tun_read,
on_virtual_tun_write: on_virtual_tun_write,
})
}
}
impl<'d> Device<'d> for VirtualTunInterface {
type RxToken = RxToken;
type TxToken = TxToken;
fn capabilities(&self) -> DeviceCapabilities {
let mut d = DeviceCapabilities::default();
d.max_transmission_unit = self.mtu;
d
}
fn receive(&'d mut self) -> Option<(Self::RxToken, Self::TxToken)> {
let mut buffer = vec![0; self.mtu];
let r = (self.on_virtual_tun_read)(buffer.as_mut_slice());
match r {
Ok(size) => {
buffer.resize(size, 0);
let rx = RxToken {
lower: Rc::new(RefCell::new(self.clone())),
buffer,
size
};
let tx = TxToken {
lower: Rc::new(RefCell::new(self.clone())),
};
Some((rx, tx))
},
//Simulates a tun/tap device that returns EWOULDBLOCK
Err(VirtualTunReadError::WouldBlock) => None,
//TODO: do not panic
Err(_) => panic!("unknown error on virtual tun receive"),
}
}
fn transmit(&'d mut self) -> Option<Self::TxToken> {
Some(TxToken {
lower: Rc::new(RefCell::new(self.clone())),
})
}
fn medium(&self) -> Medium {
Medium::Ip
}
}
#[doc(hidden)]
pub struct RxToken {
lower: Rc<RefCell<VirtualTunInterface>>,
buffer: Vec<u8>,
size: usize
}
impl phy::RxToken for RxToken {
fn consume<R, F>(mut self, _timestamp: Instant, f: F) -> smoltcp::Result<R>
where
F: FnOnce(&mut [u8]) -> smoltcp::Result<R>,
{
//println!("rx consume");
let mut lower = self.lower.as_ref().borrow_mut();
let r = f(&mut self.buffer[..]);
/*
match &r {
Ok(_) => println!("ok"),
Err(_) => println!("err")
}
*/
//let (mutex, has_data_condition_variable) = &*lower.has_data.clone();
//has_data_condition_variable.notify_one();
r
}
}
//https://stackoverflow.com/a/66579120/5884503
//https://users.rust-lang.org/t/storing-the-return-value-from-an-fn-closure/57386/3?u=guerlando
trait CallOnceSafe<R> {
fn call_once_safe(&mut self, x: &mut [u8]) -> smoltcp::Result<R>;
}
impl<R, F: FnOnce(&mut [u8]) -> smoltcp::Result<R>> CallOnceSafe<R> for Option<F> {
fn call_once_safe(&mut self, x: &mut [u8]) -> smoltcp::Result<R> {
// panics if called more than once - but A::consume() calls it only once
let func = self.take().unwrap();
func(x)
}
}
#[doc(hidden)]
pub struct TxToken {
lower: Rc<RefCell<VirtualTunInterface>>,
}
impl<'a> phy::TxToken for TxToken {
fn consume<R, F>(self, _timestamp: Instant, len: usize, f: F) -> smoltcp::Result<R>
where
F: FnOnce(&mut [u8]) -> smoltcp::Result<R>,
{
let mut lower = self.lower.as_ref().borrow_mut();
//let mut buffer = vec![0; len];
//let result = f(&mut buffer);
let mut r: Option<smoltcp::Result<R>> = None;
/*
let _result = (lower.on_virtual_tun_write)(&|b: &mut [u8]| {
r = Some(f(b));
}, len);
*/
let mut f = Some(f);
match (lower.on_virtual_tun_write)(&mut |x| {
r = Some(f.call_once_safe(x))
}, len) {
Ok(()) => {
},
Err(_) => {
panic!("virtual tun receive unknown error");
}
}
//let result = lower.send(f, len);
/*
let packets_from_inside = &*lower.packets_from_inside.clone();
{
packets_from_inside.lock().unwrap().push_back(buffer);
}
*/
//TODO: I think this is not necessary?
//let (mutex, has_data_condition_variable) = &*lower.has_data.clone();
//has_data_condition_variable.notify_one();
//smoltcp::Result::Ok(_)
r.unwrap()
}
}
|
// Problem 32 - Pandigital products
//
// We shall say that an n-digit number is pandigital if it makes use of all the
// digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1
// through 5 pandigital.
//
// The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing
// multiplicand, multiplier, and product is 1 through 9 pandigital.
//
// Find the sum of all products whose multiplicand/multiplier/product identity
// can be written as a 1 through 9 pandigital.
//
// HINT: Some products can be obtained in more than one way so be sure to only
// include it once in your sum.
use std::collections::HashSet;
fn main() {
println!("{}", solution());
}
fn solution() -> usize {
let mut products = HashSet::new();
let mut sum = 0;
for start_pair in vec![(1, 1000), (10, 100)] {
let m = start_pair.0;
let n = start_pair.1;
for a in m..(m*10) {
for b in n..(n*10) {
if a*b >= 10000 {
break;
}
let p = a*b;
if products.contains(&p) {
continue;
}
let concatenated = a.to_string() + &b.to_string() + &p.to_string();
if is_pandigital(concatenated) {
products.insert(p);
sum += p;
}
}
}
}
sum
}
fn is_pandigital(s: String) -> bool {
let mut chars = s.chars().collect::<Vec<char>>();
chars.sort();
let sorted = chars.iter().cloned().collect::<String>();
sorted == "123456789"
}
|
use chrono::{DateTime, Utc};
use crate::event::{Event, ToEvent};
use crate::result::Result;
#[derive(Debug)]
pub struct AggregateRoot<ID, E> {
id: ID,
created_at: DateTime<Utc>,
updated_at: Option<DateTime<Utc>>,
deleted_at: Option<DateTime<Utc>>,
events: Vec<E>,
}
impl<ID, E> AggregateRoot<ID, E> {
pub fn new(id: ID) -> AggregateRoot<ID, E> {
AggregateRoot {
id,
created_at: Utc::now(),
updated_at: None,
deleted_at: None,
events: Vec::new(),
}
}
pub fn build(
id: ID,
created_at: DateTime<Utc>,
updated_at: Option<DateTime<Utc>>,
deleted_at: Option<DateTime<Utc>>,
) -> Self {
AggregateRoot {
id,
created_at,
updated_at,
deleted_at,
events: Vec::new(),
}
}
pub fn id(&self) -> &ID {
&self.id
}
pub fn created_at(&self) -> &DateTime<Utc> {
&self.created_at
}
pub fn updated_at(&self) -> Option<&DateTime<Utc>> {
self.updated_at.as_ref()
}
pub fn deleted_at(&self) -> Option<&DateTime<Utc>> {
self.deleted_at.as_ref()
}
pub fn update(&mut self) {
self.updated_at = Some(Utc::now());
}
pub fn delete(&mut self) {
self.deleted_at = Some(Utc::now());
}
}
impl<ID, E> AggregateRoot<ID, E>
where
E: ToEvent,
{
pub fn record_event(&mut self, event: E) {
self.events.push(event);
}
pub fn events(&self) -> Result<Vec<Event>> {
let mut events = Vec::new();
for event in self.events.iter() {
events.push(event.to_event()?);
}
Ok(events)
}
}
impl<ID: PartialEq, E> PartialEq for AggregateRoot<ID, E> {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl<ID: Clone, E> Clone for AggregateRoot<ID, E> {
fn clone(&self) -> Self {
AggregateRoot {
id: self.id.clone(),
created_at: self.created_at,
updated_at: self.updated_at,
deleted_at: self.deleted_at,
events: Vec::new(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug)]
enum AggRootEvent {
Created { text: String },
Updated { num: u32 },
Deleted(bool),
}
impl ToEvent for AggRootEvent {
fn to_event(&self) -> Result<Event> {
Ok(match self {
AggRootEvent::Created { text } => {
Event::new("agg_root.created", "", text.as_bytes().to_vec())
}
AggRootEvent::Updated { num } => Event::new(
"agg_root.updated",
"",
vec![if num < &255 { 255 } else { 0 }],
),
AggRootEvent::Deleted(_v) => Event::new("agg_root.deleted", "", vec![1]),
})
}
}
type AggRootID = String;
#[derive(Debug)]
struct AggRoot {
base: AggregateRoot<AggRootID, AggRootEvent>,
}
impl AggRoot {
fn new(id: AggRootID) -> AggRoot {
AggRoot {
base: AggregateRoot::new(id),
}
}
fn base(&self) -> &AggregateRoot<AggRootID, AggRootEvent> {
&self.base
}
fn base_mut(&mut self) -> &mut AggregateRoot<AggRootID, AggRootEvent> {
&mut self.base
}
}
#[test]
fn create() {
let e = AggRoot::new(AggRootID::from("AR_022"));
assert_eq!(e.base().id(), "AR_022");
}
#[test]
fn properties() {
let mut e = AggRoot::new(AggRootID::from("AR_022"));
assert_eq!(e.base().id(), "AR_022");
assert!(e.base().created_at() < &Utc::now());
assert!(e.base().updated_at().is_none());
assert!(e.base().deleted_at().is_none());
e.base_mut().update();
assert!(e.base().updated_at().is_some());
assert!(e.base().updated_at().unwrap() < &Utc::now());
e.base_mut().delete();
assert!(e.base().deleted_at().is_some());
assert!(e.base().deleted_at().unwrap() < &Utc::now());
}
#[test]
fn equals() {
let ag1 = AggRoot::new(AggRootID::from("AR_101"));
let ag2 = AggRoot::new(AggRootID::from("AR_101"));
assert_eq!(ag1.base(), ag2.base());
}
#[test]
fn events() {
let mut ag = AggRoot::new(AggRootID::from("AR_08"));
ag.base_mut().record_event(AggRootEvent::Created {
text: "agg_root.created".to_owned(),
});
ag.base_mut()
.record_event(AggRootEvent::Updated { num: 32 });
ag.base_mut().record_event(AggRootEvent::Deleted(true));
let events = ag.base().events().unwrap();
assert_eq!(events.len(), 3);
assert_eq!(events[0].topic(), "agg_root.created");
assert_eq!(events[0].payload(), "agg_root.created".as_bytes());
assert_eq!(events[1].topic(), "agg_root.updated");
assert_eq!(events[2].topic(), "agg_root.deleted");
}
}
|
use crate::input::keyboard::Key;
use crate::input::InputPreprocessor;
use crate::tool::{DocumentToolData, Fsm, ToolActionHandlerData};
use crate::{document::DocumentMessageHandler, message_prelude::*};
use glam::DAffine2;
use graphene::{layers::style, Operation};
use super::resize::*;
#[derive(Default)]
pub struct Ellipse {
fsm_state: EllipseToolFsmState,
data: EllipseToolData,
}
#[impl_message(Message, ToolMessage, Ellipse)]
#[derive(PartialEq, Clone, Debug, Hash)]
pub enum EllipseMessage {
DragStart,
DragStop,
Resize { center: Key, lock_ratio: Key },
Abort,
}
impl<'a> MessageHandler<ToolMessage, ToolActionHandlerData<'a>> for Ellipse {
fn process_action(&mut self, action: ToolMessage, data: ToolActionHandlerData<'a>, responses: &mut VecDeque<Message>) {
self.fsm_state = self.fsm_state.transition(action, data.0, data.1, &mut self.data, data.2, responses);
}
fn actions(&self) -> ActionList {
use EllipseToolFsmState::*;
match self.fsm_state {
Ready => actions!(EllipseMessageDiscriminant; DragStart),
Dragging => actions!(EllipseMessageDiscriminant; DragStop, Abort, Resize),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum EllipseToolFsmState {
Ready,
Dragging,
}
impl Default for EllipseToolFsmState {
fn default() -> Self {
EllipseToolFsmState::Ready
}
}
#[derive(Clone, Debug, Default)]
struct EllipseToolData {
sides: u8,
data: Resize,
}
impl Fsm for EllipseToolFsmState {
type ToolData = EllipseToolData;
fn transition(
self,
event: ToolMessage,
_document: &DocumentMessageHandler,
tool_data: &DocumentToolData,
data: &mut Self::ToolData,
input: &InputPreprocessor,
responses: &mut VecDeque<Message>,
) -> Self {
let mut shape_data = &mut data.data;
use EllipseMessage::*;
use EllipseToolFsmState::*;
if let ToolMessage::Ellipse(event) = event {
match (self, event) {
(Ready, DragStart) => {
shape_data.drag_start = input.mouse.position;
responses.push_back(DocumentMessage::StartTransaction.into());
shape_data.path = Some(vec![generate_uuid()]);
responses.push_back(DocumentMessage::DeselectAllLayers.into());
responses.push_back(
Operation::AddEllipse {
path: shape_data.path.clone().unwrap(),
insert_index: -1,
transform: DAffine2::ZERO.to_cols_array(),
style: style::PathStyle::new(None, Some(style::Fill::new(tool_data.primary_color))),
}
.into(),
);
Dragging
}
(state, Resize { center, lock_ratio }) => {
if let Some(message) = shape_data.calculate_transform(center, lock_ratio, input) {
responses.push_back(message);
}
state
}
(Dragging, DragStop) => {
// TODO: introduce comparison threshold when operating with canvas coordinates (https://github.com/GraphiteEditor/Graphite/issues/100)
match shape_data.drag_start == input.mouse.position {
true => responses.push_back(DocumentMessage::AbortTransaction.into()),
false => responses.push_back(DocumentMessage::CommitTransaction.into()),
}
shape_data.path = None;
Ready
}
(Dragging, Abort) => {
responses.push_back(DocumentMessage::AbortTransaction.into());
shape_data.path = None;
Ready
}
_ => self,
}
} else {
self
}
}
}
|
pub fn str_str(haystack: String, needle: String) -> i32 {
if needle.len() == 0 {
return 0
}
if haystack.len() == 0 {
return -1
}
let n = needle.len();
let h_vec: Vec<char> = haystack.chars().collect();
let n_vec: Vec<char> = needle.chars().collect();
let mut failure_table: Vec<i32> = vec![-1; n];
for i in 1..n {
if i == 1 {
failure_table[i] = 0;
continue
}
if i == 2 {
if n_vec[0] == n_vec[1] {
failure_table[i] = 1;
} else {
failure_table[i] = 0;
}
continue
}
let mut lsp = failure_table[i-1];
while lsp >= 0 {
if n_vec[lsp as usize] == n_vec[i-1] {
break;
} else {
lsp = failure_table[lsp as usize];
}
}
failure_table[i] = lsp + 1;
}
let mut m = 0;
let mut i = 0;
while i+m < haystack.len() {
if i == n {
return m as i32
}
if h_vec[i+m] == n_vec[i] {
i += 1;
if i == n {
return m as i32
}
continue
} else {
match failure_table[i] {
-1 => m += 1,
n => {
m += i - n as usize;
i = n as usize;
},
}
}
}
-1
}
#[test]
fn test_str_str() {
assert_eq!(str_str("aabaaabaaac".to_string(), "aabaaac".to_string()), 4);
assert_eq!(str_str("a".to_string(), "a".to_string()), 0);
assert_eq!(str_str("aaa".to_string(), "aaaa".to_string()), -1);
assert_eq!(str_str("hello".to_string(), "abcababcd".to_string()), -1);
assert_eq!(str_str("hello".to_string(), "ll".to_string()), 2);
assert_eq!(str_str("aaaaaa".to_string(), "bba".to_string()), -1);
assert_eq!(str_str("aaaaaa".to_string(), "".to_string()), 0);
} |
#![feature(plugin)]
#![plugin(ronat)]
/// This is a text misssspell.
pub fn main() {
}
|
use envconfig::Envconfig;
#[derive(Envconfig)]
pub struct Config {
#[envconfig(from = "mutate_weight", default = "0.6")]
pub mutate_weight: f64,
#[envconfig(from = "add_connection", default = "0.1")]
pub add_connection: f64,
#[envconfig(from = "add_neuron", default = "0.01")]
pub add_neuron: f64,
#[envconfig(from = "disable_connection", default = "0.005")]
pub disable_connection: f64,
#[envconfig(from = "start_offset", default = "315.0")] // pointing south east
pub start_offset: f64,
#[envconfig(from = "max_speed", default = "3.0")]
pub max_speed: f64,
#[envconfig(from = "agent_radius", default = "3.0")]
pub agent_radius: f64,
}
|
#[doc = "Master 0 protection context control\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 avaliable fields see [ms0_ctl](ms0_ctl) module"]
pub type MS0_CTL = crate::Reg<u32, _MS0_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MS0_CTL;
#[doc = "`read()` method returns [ms0_ctl::R](ms0_ctl::R) reader structure"]
impl crate::Readable for MS0_CTL {}
#[doc = "`write(|w| ..)` method takes [ms0_ctl::W](ms0_ctl::W) writer structure"]
impl crate::Writable for MS0_CTL {}
#[doc = "Master 0 protection context control"]
pub mod ms0_ctl;
#[doc = "Master 1 protection context control\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 avaliable fields see [ms1_ctl](ms1_ctl) module"]
pub type MS1_CTL = crate::Reg<u32, _MS1_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MS1_CTL;
#[doc = "`read()` method returns [ms1_ctl::R](ms1_ctl::R) reader structure"]
impl crate::Readable for MS1_CTL {}
#[doc = "`write(|w| ..)` method takes [ms1_ctl::W](ms1_ctl::W) writer structure"]
impl crate::Writable for MS1_CTL {}
#[doc = "Master 1 protection context control"]
pub mod ms1_ctl;
#[doc = "Master 2 protection context control\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 avaliable fields see [ms2_ctl](ms2_ctl) module"]
pub type MS2_CTL = crate::Reg<u32, _MS2_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MS2_CTL;
#[doc = "`read()` method returns [ms2_ctl::R](ms2_ctl::R) reader structure"]
impl crate::Readable for MS2_CTL {}
#[doc = "`write(|w| ..)` method takes [ms2_ctl::W](ms2_ctl::W) writer structure"]
impl crate::Writable for MS2_CTL {}
#[doc = "Master 2 protection context control"]
pub mod ms2_ctl;
#[doc = "Master 3 protection context control\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 avaliable fields see [ms3_ctl](ms3_ctl) module"]
pub type MS3_CTL = crate::Reg<u32, _MS3_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MS3_CTL;
#[doc = "`read()` method returns [ms3_ctl::R](ms3_ctl::R) reader structure"]
impl crate::Readable for MS3_CTL {}
#[doc = "`write(|w| ..)` method takes [ms3_ctl::W](ms3_ctl::W) writer structure"]
impl crate::Writable for MS3_CTL {}
#[doc = "Master 3 protection context control"]
pub mod ms3_ctl;
#[doc = "Master 4 protection context control\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 avaliable fields see [ms4_ctl](ms4_ctl) module"]
pub type MS4_CTL = crate::Reg<u32, _MS4_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MS4_CTL;
#[doc = "`read()` method returns [ms4_ctl::R](ms4_ctl::R) reader structure"]
impl crate::Readable for MS4_CTL {}
#[doc = "`write(|w| ..)` method takes [ms4_ctl::W](ms4_ctl::W) writer structure"]
impl crate::Writable for MS4_CTL {}
#[doc = "Master 4 protection context control"]
pub mod ms4_ctl;
#[doc = "Master 5 protection context control\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 avaliable fields see [ms5_ctl](ms5_ctl) module"]
pub type MS5_CTL = crate::Reg<u32, _MS5_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MS5_CTL;
#[doc = "`read()` method returns [ms5_ctl::R](ms5_ctl::R) reader structure"]
impl crate::Readable for MS5_CTL {}
#[doc = "`write(|w| ..)` method takes [ms5_ctl::W](ms5_ctl::W) writer structure"]
impl crate::Writable for MS5_CTL {}
#[doc = "Master 5 protection context control"]
pub mod ms5_ctl;
#[doc = "Master 6 protection context control\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 avaliable fields see [ms6_ctl](ms6_ctl) module"]
pub type MS6_CTL = crate::Reg<u32, _MS6_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MS6_CTL;
#[doc = "`read()` method returns [ms6_ctl::R](ms6_ctl::R) reader structure"]
impl crate::Readable for MS6_CTL {}
#[doc = "`write(|w| ..)` method takes [ms6_ctl::W](ms6_ctl::W) writer structure"]
impl crate::Writable for MS6_CTL {}
#[doc = "Master 6 protection context control"]
pub mod ms6_ctl;
#[doc = "Master 7 protection context control\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 avaliable fields see [ms7_ctl](ms7_ctl) module"]
pub type MS7_CTL = crate::Reg<u32, _MS7_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MS7_CTL;
#[doc = "`read()` method returns [ms7_ctl::R](ms7_ctl::R) reader structure"]
impl crate::Readable for MS7_CTL {}
#[doc = "`write(|w| ..)` method takes [ms7_ctl::W](ms7_ctl::W) writer structure"]
impl crate::Writable for MS7_CTL {}
#[doc = "Master 7 protection context control"]
pub mod ms7_ctl;
#[doc = "Master 8 protection context control\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 avaliable fields see [ms8_ctl](ms8_ctl) module"]
pub type MS8_CTL = crate::Reg<u32, _MS8_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MS8_CTL;
#[doc = "`read()` method returns [ms8_ctl::R](ms8_ctl::R) reader structure"]
impl crate::Readable for MS8_CTL {}
#[doc = "`write(|w| ..)` method takes [ms8_ctl::W](ms8_ctl::W) writer structure"]
impl crate::Writable for MS8_CTL {}
#[doc = "Master 8 protection context control"]
pub mod ms8_ctl;
#[doc = "Master 9 protection context control\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 avaliable fields see [ms9_ctl](ms9_ctl) module"]
pub type MS9_CTL = crate::Reg<u32, _MS9_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MS9_CTL;
#[doc = "`read()` method returns [ms9_ctl::R](ms9_ctl::R) reader structure"]
impl crate::Readable for MS9_CTL {}
#[doc = "`write(|w| ..)` method takes [ms9_ctl::W](ms9_ctl::W) writer structure"]
impl crate::Writable for MS9_CTL {}
#[doc = "Master 9 protection context control"]
pub mod ms9_ctl;
#[doc = "Master 10 protection context control\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 avaliable fields see [ms10_ctl](ms10_ctl) module"]
pub type MS10_CTL = crate::Reg<u32, _MS10_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MS10_CTL;
#[doc = "`read()` method returns [ms10_ctl::R](ms10_ctl::R) reader structure"]
impl crate::Readable for MS10_CTL {}
#[doc = "`write(|w| ..)` method takes [ms10_ctl::W](ms10_ctl::W) writer structure"]
impl crate::Writable for MS10_CTL {}
#[doc = "Master 10 protection context control"]
pub mod ms10_ctl;
#[doc = "Master 11 protection context control\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 avaliable fields see [ms11_ctl](ms11_ctl) module"]
pub type MS11_CTL = crate::Reg<u32, _MS11_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MS11_CTL;
#[doc = "`read()` method returns [ms11_ctl::R](ms11_ctl::R) reader structure"]
impl crate::Readable for MS11_CTL {}
#[doc = "`write(|w| ..)` method takes [ms11_ctl::W](ms11_ctl::W) writer structure"]
impl crate::Writable for MS11_CTL {}
#[doc = "Master 11 protection context control"]
pub mod ms11_ctl;
#[doc = "Master 12 protection context control\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 avaliable fields see [ms12_ctl](ms12_ctl) module"]
pub type MS12_CTL = crate::Reg<u32, _MS12_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MS12_CTL;
#[doc = "`read()` method returns [ms12_ctl::R](ms12_ctl::R) reader structure"]
impl crate::Readable for MS12_CTL {}
#[doc = "`write(|w| ..)` method takes [ms12_ctl::W](ms12_ctl::W) writer structure"]
impl crate::Writable for MS12_CTL {}
#[doc = "Master 12 protection context control"]
pub mod ms12_ctl;
#[doc = "Master 13 protection context control\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 avaliable fields see [ms13_ctl](ms13_ctl) module"]
pub type MS13_CTL = crate::Reg<u32, _MS13_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MS13_CTL;
#[doc = "`read()` method returns [ms13_ctl::R](ms13_ctl::R) reader structure"]
impl crate::Readable for MS13_CTL {}
#[doc = "`write(|w| ..)` method takes [ms13_ctl::W](ms13_ctl::W) writer structure"]
impl crate::Writable for MS13_CTL {}
#[doc = "Master 13 protection context control"]
pub mod ms13_ctl;
#[doc = "Master 14 protection context control\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 avaliable fields see [ms14_ctl](ms14_ctl) module"]
pub type MS14_CTL = crate::Reg<u32, _MS14_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MS14_CTL;
#[doc = "`read()` method returns [ms14_ctl::R](ms14_ctl::R) reader structure"]
impl crate::Readable for MS14_CTL {}
#[doc = "`write(|w| ..)` method takes [ms14_ctl::W](ms14_ctl::W) writer structure"]
impl crate::Writable for MS14_CTL {}
#[doc = "Master 14 protection context control"]
pub mod ms14_ctl;
#[doc = "Master 15 protection context control\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 avaliable fields see [ms15_ctl](ms15_ctl) module"]
pub type MS15_CTL = crate::Reg<u32, _MS15_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MS15_CTL;
#[doc = "`read()` method returns [ms15_ctl::R](ms15_ctl::R) reader structure"]
impl crate::Readable for MS15_CTL {}
#[doc = "`write(|w| ..)` method takes [ms15_ctl::W](ms15_ctl::W) writer structure"]
impl crate::Writable for MS15_CTL {}
#[doc = "Master 15 protection context control"]
pub mod ms15_ctl;
#[doc = r"Register block"]
#[repr(C)]
pub struct SMPU_STRUCT {
#[doc = "0x00 - SMPU region address 0 (slave structure)"]
pub addr0: self::smpu_struct::ADDR0,
#[doc = "0x04 - SMPU region attributes 0 (slave structure)"]
pub att0: self::smpu_struct::ATT0,
_reserved2: [u8; 24usize],
#[doc = "0x20 - SMPU region address 1 (master structure)"]
pub addr1: self::smpu_struct::ADDR1,
#[doc = "0x24 - SMPU region attributes 1 (master structure)"]
pub att1: self::smpu_struct::ATT1,
}
#[doc = r"Register block"]
#[doc = "SMPU structure"]
pub mod smpu_struct;
|
// --- paritytech ---
use pallet_utility::Config;
// --- darwinia-network ---
use crate::{weights::pallet_utility::WeightInfo, *};
impl Config for Runtime {
type Event = Event;
type Call = Call;
type WeightInfo = WeightInfo<Runtime>;
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::collections::BTreeMap;
use std::sync::Arc;
use bytes::Bytes;
use bytes::BytesMut;
use futures::future::Future;
use futures::stream::FuturesUnordered;
use futures::stream::StreamExt;
use nix::fcntl;
use nix::fcntl::OFlag;
use nix::sys::signal::Signal;
use nix::sys::stat;
use nix::sys::stat::Mode;
use nix::sys::uio;
use nix::unistd;
use reverie::Pid;
use safeptrace::ChildOp;
use tokio::io::AsyncWrite;
use tokio::io::AsyncWriteExt;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::sync::MappedMutexGuard;
use tokio::sync::Mutex;
use tokio::sync::MutexGuard;
use super::commands;
use super::commands::*;
use super::regs::CoreRegs;
use super::response::*;
use super::Breakpoint;
use super::BreakpointType;
use super::Error;
use super::GdbRequest;
use super::Inferior;
use super::InferiorThreadId;
use super::Packet;
use super::ResumeInferior;
use super::StoppedInferior;
type BoxWriter = Box<dyn AsyncWrite + Unpin + Send + Sync + 'static>;
/// Gdb session manager.
/// recv commands over tcp stream
/// recv request from Tracee (new task, reap orphans, etc..)
/// Session ends when client disconnect from tcp stream.
/// (gdb) detach semantics?
pub struct Session {
/// No-ACK mode, set by gdb client.
pub no_ack_mode: bool,
/// Stream to send reply to.
pub stream_tx: BoxWriter,
/// buffer use to send data over to tcp stream
pub tx_buf: BytesMut,
/// Gdb remote protocol command notifier.
pub pkt_rx: Option<mpsc::Receiver<Packet>>,
/// buffer used by hostio.
pub bufsiz: usize,
/// Current pid used by vFile (hostio).
pub hostio_pid: Option<Pid>,
/// Inferiors managed by this session.
pub inferiors: Arc<Mutex<BTreeMap<Pid, Inferior>>>,
/// Current thread
pub current: Option<InferiorThreadId>,
/// Channel to report stop event.
// NB: even though we could use a single `gdb_stop_rx` to receive all
// stop events (mpsc), we use a `stop_rx` channel for each `inferior`
// instead, this is because `vCont;p<pid>:-1` could resume multiple
// threads hence there are could be multiple threads reporting stop
// event at the same time, causing de-sync issue. This can be mitigated
// if each inferior has its own `stop_rx` channel. As a result,
// `gdb_stop_rx` is moved after initial gdb attach, once we can create
// the first inferior.
pub gdb_stop_rx: Option<mpsc::Receiver<StoppedInferior>>,
}
struct VcontResumeResult {
/// stop reason
reason: StopReason,
/// A new inferior was created.
new_inferior: Option<Inferior>,
/// ptids must be removed, due to some tasks are exited.
ptid_to_remove: Vec<ThreadId>,
/// Switch to a new task
//
// NB: This is possible when supporting multi-threaded programs. See
// Below examples.
//
// Sending packet: $vCont;c:p2.-1#10...Packet received: T05create:p02.12;06:70d9ffffff7f0000;07:28d9ffffff7f0000;10:1138eef7ff7f0000;thread:p02.02;
// Sending packet: $vCont;c:p2.-1#10...Packet received: T05swbreak:;06:201e5cf5ff7f0000;07:f01d5cf5ff7f0000;10:0e14400000000000;thread:p02.10;
// Sending packet: $qfThreadInfo#bb...Packet received: mp02.02,p02.06,p02.08,p02.0a,p02.0c,p02.0e,p02.10,p02.12,
// Sending packet: $qsThreadInfo#c8...Packet received: l
// [New Thread 2.18]
// [Switching to Thread 2.16]
// Sending packet: $z0,40140e,1#91...Packet received: OK
// Sending packet: $z0,7ffff7fe3340,1#ce...Packet received: OK
//
// Even though gdb (client) said `[Switching to Thread 2.16]`, No packets
// was sent to the server side (such as `Hgp2.16`) hence the server side
// was completely unaware of the switching. Presumably gdb (client)
// assumed *any* thread in the same process group and read/write memory,
// but it is not necessarily true for us because we use different
// channels to communicate between gdbstub <-> reverie. As a result
// we switch current to thread `switch_to`, to simulate gdb's (client)
// (mis)behavior.
switch_to: Option<InferiorThreadId>,
}
enum HandleVcontResume {
/// vCont resume not handled, this is possible because vCont can encode
/// multiple actions, only the left-most action is used if it matches
/// a given ptid.
NotHandled,
/// vCont matches a `ptid`.
Handled(VcontResumeResult),
}
impl Session {
/// Create a new session from root task.
pub fn new(
stream_tx: BoxWriter,
pkt_rx: mpsc::Receiver<Packet>,
gdb_stop_rx: mpsc::Receiver<StoppedInferior>,
) -> Self {
Session {
no_ack_mode: false,
stream_tx,
tx_buf: BytesMut::with_capacity(0x8000),
pkt_rx: Some(pkt_rx),
hostio_pid: None,
bufsiz: 0x8000,
inferiors: Arc::new(Mutex::new(BTreeMap::new())),
current: None,
gdb_stop_rx: Some(gdb_stop_rx),
}
}
/// Get current inferior. GDB can select current inferior by `Hg<thread-id>`.
async fn with_inferior<'a, F, Fut>(&'a self, threadid: ThreadId, f: F) -> Fut::Output
where
F: FnOnce(MappedMutexGuard<'a, Inferior>) -> Fut + 'a,
Fut: Future + 'a,
{
let tid = threadid
.gettid()
.unwrap_or_else(|| threadid.getpid().unwrap());
let inferiors = self.inferiors.lock().await;
let inferior = MutexGuard::map(inferiors, |inferiors| inferiors.get_mut(&tid).unwrap());
f(inferior).await
}
/// Get current inferior. GDB can select current inferior by `Hg<thread-id>`.
async fn with_current_inferior<'a, F, Fut>(&'a self, f: F) -> Fut::Output
where
F: FnOnce(MappedMutexGuard<'a, Inferior>) -> Fut + 'a,
Fut: Future + 'a,
{
let threadid: ThreadId = self.current.unwrap().into();
self.with_inferior(threadid, f).await
}
/// create a new response writer
fn response(&self, mut tx: BytesMut) -> ResponseWriter {
ResponseWriter::new(tx.split(), self.no_ack_mode)
}
/// Detach or Kill all threads matching `threadid`.
async fn detach_or_kill(&self, threadid: ThreadId, kill: bool) -> Result<(), Error> {
let mut inferiors = self.inferiors.lock().await;
let resume = ResumeInferior {
action: if kill {
ResumeAction::Continue(Some(Signal::SIGKILL))
} else {
ResumeAction::Continue(None)
},
detach: true,
};
for (_, inferior) in inferiors.iter_mut() {
if inferior.matches(&threadid) {
inferior.notify_resume(resume).await?;
}
}
inferiors.retain(|_, inferior| !inferior.matches(&threadid));
Ok(())
}
/// handle vCont resume
async fn vcont_resume(
&self,
threadid: ThreadId,
resume: ResumeInferior,
) -> Result<HandleVcontResume, Error> {
let mut inferiors_to_resume: Vec<&mut Inferior> = Vec::new();
let mut inferiors = self.inferiors.lock().await;
match threadid.tid {
// vCont a specific ptid, such as $vCont;c:p2.2#..
IdKind::Id(tid) => {
let inferior = inferiors.get_mut(&tid).ok_or(Error::UnknownThread(tid))?;
inferiors_to_resume.push(inferior);
}
// Invalid vCont
IdKind::Any => {
return Err(Error::ThreadIdNotSpecified);
}
// vCont all threads, such as $vCont;c:p2.-1#10
IdKind::All => match threadid.pid {
IdKind::Id(pid) => {
for (_, inferior) in inferiors.iter_mut() {
if inferior.getpid() == pid {
inferiors_to_resume.push(inferior);
}
}
}
_ => return Err(Error::ThreadIdNotSpecified),
},
}
if inferiors_to_resume.is_empty() {
return Ok(HandleVcontResume::NotHandled);
}
let mut new_inferior: Option<Inferior> = None;
let mut ptid_to_remove: Vec<ThreadId> = Vec::new();
let mut switch_to: Option<InferiorThreadId> = None;
let mut inferiors_to_wait = FuturesUnordered::new();
for inferior in inferiors_to_resume {
inferior.notify_resume(resume).await?;
inferiors_to_wait.push(inferior.wait_for_stop());
}
let mut reason: Option<StopReason> = None;
while let Some(stop_reason) = inferiors_to_wait.next().await {
let mut stop_reason = stop_reason?;
match &mut stop_reason {
StopReason::ThreadExited(pid, tgid, _exit_status) => {
ptid_to_remove.push(ThreadId::pid_tid(tgid.as_raw(), pid.as_raw()));
// The thread exit event `w XX; ptid is not reported
continue;
}
StopReason::Exited(pid, _exit_staus) => {
ptid_to_remove.push(ThreadId::pid(pid.as_raw()));
}
StopReason::NewTask(new_task) => {
new_inferior = Some(match new_task.op {
ChildOp::Fork => Inferior {
id: InferiorThreadId::new(new_task.child, new_task.child),
resume_tx: new_task.resume_tx.take(),
request_tx: new_task.request_tx.take(),
stop_rx: new_task.stop_rx.take(),
resume_pending: false,
},
ChildOp::Vfork => Inferior {
id: InferiorThreadId::new(new_task.child, new_task.child),
resume_tx: new_task.resume_tx.take(),
request_tx: new_task.request_tx.take(),
stop_rx: new_task.stop_rx.take(),
resume_pending: false,
},
ChildOp::Clone => Inferior {
id: InferiorThreadId::new(new_task.child, new_task.tgid),
resume_tx: new_task.resume_tx.take(),
request_tx: new_task.request_tx.take(),
stop_rx: new_task.stop_rx.take(),
resume_pending: false,
},
});
}
StopReason::Stopped(stopped) => {
switch_to = Some(InferiorThreadId::new(stopped.pid, stopped.tgid));
}
}
reason = Some(stop_reason);
break;
}
Ok(HandleVcontResume::Handled(VcontResumeResult {
reason: reason.unwrap(),
new_inferior,
ptid_to_remove,
switch_to,
}))
}
/// handle gdb remote base command
async fn handle_base(&mut self, cmd: Base, writer: &mut ResponseWriter) -> Result<(), Error> {
match cmd {
Base::QuestionMark(_) => {
writer.put_str("S05");
}
Base::QStartNoAckMode(_) => {
self.no_ack_mode = true;
writer.put_str("OK");
}
Base::qSupported(_) => {
writer.put_str("PacketSize=8000;vContSupported+;multiprocess+;exec-events+;fork-events+;vfork-events+;QThreadEvents+;QStartNoAckMode+;swbreak+;qXfer:features:read+;qXfer:auxv:read+;");
}
Base::qXfer(request) => match request {
qXfer::FeaturesRead { offset: _, len: _ } => {
// gdb/64bit-sse.xml
writer.put_str("l<target version=\"1.0\"><architecture>i386:x86-64</architecture><feature name=\"org.gnu.gdb.i386.sse\"></feature></target>");
}
qXfer::AuxvRead { offset, len } => {
if let Some(id) = self.current {
let buffer_size = std::cmp::min(self.bufsiz, len);
let mut auxv: Vec<u8> = vec![0; buffer_size];
if let Ok(nb) = fcntl::open(
format!("/proc/{}/auxv", id.pid).as_str(),
OFlag::O_RDONLY,
Mode::from_bits_truncate(0o644),
)
.and_then(|fd| {
let nb = uio::pread(fd, &mut auxv, offset as libc::off_t)?;
let _ = unistd::close(fd);
Ok(nb)
}) {
writer.put_str("l");
writer.put_binary_encoded(&auxv[..nb]);
}
}
}
},
Base::qfThreadInfo(_) => {
writer.put_str("m");
for task in self.inferiors.lock().await.values() {
let threadid: ThreadId = task.id.into();
threadid.write_response(writer);
writer.put_str(",");
}
}
Base::qsThreadInfo(_) => {
writer.put_str("l");
}
Base::qAttached(_pid) => {
writer.put_str("0");
}
Base::QThreadEvents(_thread_events) => {
// NB: This should toggle reporting thread event, such as
// `T05Create`, but I couldn't find any examples even with
// vanilla gdbserver debugging threaded programs. gdb client
// never send this command, even after I tried to run
// `set remote thread-events on`, as described in gdb remote
// protocol doc.
writer.put_str("OK");
}
Base::qC(_) => {
if let Some(id) = self.current {
let thread_id: ThreadId = id.into();
writer.put_str("QC");
thread_id.write_response(writer);
}
}
Base::H(h) => {
match h.op {
ThreadOp::g => {
// qeury or set current threadid.
if h.id.pid == IdKind::Any && h.id.tid == IdKind::Any {
ResponseOk.write_response(writer);
} else {
h.id.try_into()
.map(|id| {
self.current = Some(id);
ResponseOk
})
.write_response(writer)
}
}
_ => {
// Hc is deprecated, others not supported.
writer.put_str("E01");
}
}
}
Base::g(_) => self
.read_registers()
.await
.map(ResponseAsHex)
.write_response(writer),
Base::G(regs) => self
.write_registers(regs.vals)
.await
.map(|_| ResponseOk)
.write_response(writer),
Base::m(m) => self
.read_inferior_memory(m.addr, m.length)
.await
.map(ResponseAsHex)
.write_response(writer),
Base::M(mem) => self
.write_inferior_memory(mem.addr, mem.length, mem.vals)
.await
.map(|_| ResponseOk)
.write_response(writer),
Base::X(mem) => self
.write_inferior_memory(mem.addr, mem.length, mem.vals)
.await
.map(|_| ResponseOk)
.write_response(writer),
// NB: detach is a resume, but we don't care about receiving
// further (gdb) stop events.
Base::D(pid) => {
let pid = pid.pid;
let threadid = pid.map_or_else(ThreadId::all, |pid| ThreadId::pid(pid.as_raw()));
self.detach_or_kill(threadid, false)
.await
.map(|_| ResponseOk)
.write_response(writer);
}
Base::z(bkpt) => {
if bkpt.ty == BreakpointType::Software {
let bkpt = Breakpoint {
ty: BreakpointType::Software,
addr: bkpt.addr,
bytecode: None,
};
self.remove_breakpoint(bkpt)
.await
.map(|_| ResponseOk)
.write_response(writer);
}
}
Base::Z(bkpt) => {
if bkpt.ty == BreakpointType::Software {
let bkpt = Breakpoint {
ty: BreakpointType::Software,
addr: bkpt.addr,
bytecode: None,
};
self.set_breakpoint(bkpt)
.await
.map(|_| ResponseOk)
.write_response(writer);
}
}
// NB: kill is a resume(SIGKILL), but we don't care about
// receiving further (gdb) stop events.
Base::vKill(pid) => {
let threadid = ThreadId::pid(pid.pid.as_raw());
self.detach_or_kill(threadid, true)
.await
.map(|_| ResponseOk)
.write_response(writer);
}
Base::vCont(vcont) => match vcont {
vCont::Query => {
writer.put_str("vCont;c;C;s;S");
}
vCont::Actions(actions) => {
// `vCont` can encode multiple actions, but we should
// resume only one matching ptid only (left-most).
while let Some((action, threadid)) = actions.first() {
let resume = match action {
ResumeAction::Step(step) => ResumeInferior {
action: ResumeAction::Step(*step),
detach: false,
},
ResumeAction::Continue(cont) => ResumeInferior {
action: ResumeAction::Continue(*cont),
detach: false,
},
not_supported => {
// Shouldn't reach here because only `c;C;s:S` are advertised.
panic!("Unsupported vCont command: {:?}", not_supported);
}
};
match self.vcont_resume(*threadid, resume).await? {
HandleVcontResume::NotHandled => {}
HandleVcontResume::Handled(VcontResumeResult {
reason,
new_inferior,
ptid_to_remove,
switch_to,
}) => {
let mut inferiors = self.inferiors.lock().await;
for ptid in ptid_to_remove {
if let Some(tid) = ptid.gettid() {
let _ = inferiors.remove(&tid);
} else {
inferiors.retain(|_, inferior| !inferior.matches(&ptid));
}
}
if let Some(new_inferior) = new_inferior {
inferiors.insert(new_inferior.gettid(), new_inferior);
}
if let Some(switch_to) = switch_to {
self.current = Some(switch_to);
}
reason.write_response(writer);
break;
}
}
}
}
},
// TODO T92309086: implement ACL for hostio.
Base::vFile(hostio) => match hostio {
vFile::Setfs(pid) => {
match pid {
Some(pid) => {
self.hostio_pid = Some(Pid::from_raw(pid));
}
None => {
self.hostio_pid = self.current.as_ref().map(|x| x.pid);
}
}
writer.put_str("F0");
}
vFile::Open(fname, flags, mode) => {
let oflag = OFlag::from_bits_truncate(flags);
let mode = Mode::from_bits_truncate(mode);
writer.put_str("F");
match fcntl::open(&fname, oflag, mode) {
Ok(fd) => writer.put_num(fd),
Err(_) => writer.put_str("-1"),
}
}
vFile::Close(fd) => {
writer.put_str(unistd::close(fd).map_or("F-1", |_| "F0"));
}
vFile::Pread(fd, count, offset) => {
let count = std::cmp::min(count as usize, self.bufsiz);
let mut buf: Vec<u8> = vec![0; count];
match uio::pread(fd, &mut buf, offset as i64) {
Ok(nb) => {
writer.put_str("F");
writer.put_num(nb);
writer.put_str(";");
writer.put_binary_encoded(&buf[..nb]);
}
Err(_) => {
writer.put_str("F-1");
}
}
}
vFile::Pwrite(fd, offset, data) => match uio::pwrite(fd, &data, offset as i64) {
Ok(nb) => {
writer.put_str("F");
writer.put_num(nb);
}
Err(_) => {
writer.put_str("F-1");
}
},
vFile::Unlink(fname) => {
writer.put_str(unistd::unlink(&fname).map_or("F-1", |_| "F0"));
}
vFile::Readlink(fname) => {
match fcntl::readlink(&fname)
.ok()
.and_then(|s| s.to_str().map(|s| s.as_bytes().to_vec()))
{
Some(bytes) => {
writer.put_str("F");
writer.put_num(bytes.len());
writer.put_str(";");
writer.put_binary_encoded(&bytes)
}
None => {
writer.put_str("F-1");
}
}
}
vFile::Fstat(fd) => {
// NB: HostioStat is not the same as FileStat.
const STAT_SIZE: usize = std::mem::size_of::<HostioStat>();
match stat::fstat(fd).ok().map(|st| {
let st: HostioStat = st.into();
let bytes: [u8; STAT_SIZE] = unsafe { std::mem::transmute(st) };
bytes
}) {
Some(bytes) => {
writer.put_str("F");
writer.put_num(STAT_SIZE);
writer.put_str(";");
writer.put_binary_encoded(&bytes);
}
None => {
writer.put_str("F-1");
}
}
}
},
}
Ok(())
}
/// handle gdb remote extended mode command
async fn handle_extended_mode(
&mut self,
cmd: ExtendedMode,
writer: &mut ResponseWriter,
) -> Result<(), Error> {
match cmd {
ExtendedMode::ExclamationMark(_) => {
writer.put_str("OK");
}
ExtendedMode::QDisableRandomization(disable_aslr) => {
// ASLR is always disabled by reverie.
if disable_aslr.val {
writer.put_str("OK");
} else {
writer.put_str("E22");
}
}
}
Ok(())
}
/// handle gdb remote monitor command
async fn handle_monitor_cmd(
&mut self,
cmd: MonitorCmd,
_writer: &mut ResponseWriter,
) -> Result<(), Error> {
match cmd {
MonitorCmd::qRcmd(_) => {
unimplemented!()
}
}
}
/// handle gdb remote section offset command
async fn handle_section_offsets(
&mut self,
cmd: SectionOffsets,
writer: &mut ResponseWriter,
) -> Result<(), Error> {
match cmd {
// should use libraries-svr4:read instead
SectionOffsets::qOffsets(_) => {
writer.put_str("");
}
}
Ok(())
}
/// handle gdb remote command
async fn handle_command(
&mut self,
cmd: commands::Command,
resp: BytesMut,
) -> Result<Bytes, Error> {
let mut writer = self.response(resp);
match cmd {
Command::Unknown(cmd) => {
tracing::info!("Unknown command: {:?}", cmd);
}
Command::Base(cmd) => self.handle_base(cmd, &mut writer).await?,
Command::ExtendedMode(cmd) => self.handle_extended_mode(cmd, &mut writer).await?,
Command::MonitorCmd(cmd) => self.handle_monitor_cmd(cmd, &mut writer).await?,
Command::SectionOffsets(cmd) => self.handle_section_offsets(cmd, &mut writer).await?,
};
Ok(writer.finish())
}
/// Handle incoming request sent over tcp stream
pub async fn run(&mut self) -> Result<(), Error> {
let cmd_rx = self.pkt_rx.take().unwrap();
let mut gdb_stop_rx = self.gdb_stop_rx.take().ok_or(Error::Detached)?;
let stop_reason = gdb_stop_rx.recv().await.ok_or(Error::Detached)?;
// set initial task as current attached task.
match stop_reason.reason {
StopReason::Stopped(stopped) => {
let id = InferiorThreadId::new(stopped.pid, stopped.tgid);
self.current = Some(id);
let mut inferior = Inferior::new(id);
inferior.request_tx = Some(stop_reason.request_tx);
inferior.resume_tx = Some(stop_reason.resume_tx);
inferior.stop_rx = Some(gdb_stop_rx);
self.inferiors.lock().await.insert(id.tid, inferior);
}
_ => unreachable!(),
}
self.handle_gdb_commands(cmd_rx).await
}
async fn handle_gdb_commands(
&mut self,
mut cmd_rx: mpsc::Receiver<Packet>,
) -> Result<(), Error> {
let mut tx_buf = BytesMut::with_capacity(0x8000);
while let Some(pkt) = cmd_rx.recv().await {
match pkt {
Packet::Ack => {}
Packet::Nack => {
panic!("client send Nack")
}
// handle interrupt
Packet::Interrupt => {}
Packet::Command(cmd) => {
tx_buf.clear();
let resp = self.handle_command(cmd, tx_buf.clone()).await?;
self.stream_tx.write_all(&resp).await.unwrap();
}
}
}
Ok(())
}
/// Set a breakpoint. must have an active inferior.
async fn set_breakpoint(&self, bkpt: Breakpoint) -> Result<(), Error> {
self.with_current_inferior(move |inferior| async move {
let request_tx = inferior
.request_tx
.as_ref()
.ok_or(Error::SessionNotStarted)?;
let (reply_tx, reply_rx) = oneshot::channel();
let request = GdbRequest::SetBreakpoint(
Breakpoint {
ty: BreakpointType::Software,
addr: bkpt.addr,
bytecode: None,
},
reply_tx,
);
let _ = request_tx
.send(request)
.await
.map_err(|_| Error::GdbRequestSendError)?;
let reply = reply_rx.await.map_err(|_| Error::GdbRequestRecvError)??;
Ok(reply)
})
.await
}
async fn remove_breakpoint(&self, bkpt: Breakpoint) -> Result<(), Error> {
self.with_current_inferior(move |inferior| async move {
let request_tx = inferior
.request_tx
.as_ref()
.ok_or(Error::SessionNotStarted)?;
let (reply_tx, reply_rx) = oneshot::channel();
let request = GdbRequest::RemoveBreakpoint(
Breakpoint {
ty: BreakpointType::Software,
addr: bkpt.addr,
bytecode: None,
},
reply_tx,
);
request_tx
.send(request)
.await
.map_err(|_| Error::GdbRequestSendError)?;
let reply = reply_rx.await.map_err(|_| Error::GdbRequestRecvError)??;
Ok(reply)
})
.await
}
async fn read_inferior_memory(&self, addr: u64, size: usize) -> Result<Vec<u8>, Error> {
self.with_current_inferior(move |inferior| async move {
let request_tx = inferior
.request_tx
.as_ref()
.ok_or(Error::SessionNotStarted)?;
let (reply_tx, reply_rx) = oneshot::channel();
let request = GdbRequest::ReadInferiorMemory(addr, size, reply_tx);
let _ = request_tx
.send(request)
.await
.map_err(|_| Error::GdbRequestSendError)?;
let reply = reply_rx.await.map_err(|_| Error::GdbRequestRecvError)??;
Ok(reply)
})
.await
}
async fn write_inferior_memory(
&self,
addr: u64,
size: usize,
data: Vec<u8>,
) -> Result<(), Error> {
let data = data.clone();
self.with_current_inferior(move |inferior| async move {
let request_tx = inferior
.request_tx
.as_ref()
.ok_or(Error::SessionNotStarted)?;
let (reply_tx, reply_rx) = oneshot::channel();
let request = GdbRequest::WriteInferiorMemory(addr, size, data, reply_tx);
let _ = request_tx
.send(request)
.await
.map_err(|_| Error::GdbRequestSendError)?;
let reply = reply_rx.await.map_err(|_| Error::GdbRequestRecvError)??;
Ok(reply)
})
.await
}
async fn read_registers(&self) -> Result<CoreRegs, Error> {
self.with_current_inferior(move |inferior| async move {
let request_tx = inferior
.request_tx
.as_ref()
.ok_or(Error::SessionNotStarted)?;
let (reply_tx, reply_rx) = oneshot::channel();
let request = GdbRequest::ReadRegisters(reply_tx);
let _ = request_tx
.send(request)
.await
.map_err(|_| Error::GdbRequestSendError)?;
let reply = reply_rx.await.map_err(|_| Error::GdbRequestRecvError)??;
Ok(reply)
})
.await
}
async fn write_registers(&self, regs: Vec<u8>) -> Result<(), Error> {
self.with_current_inferior(move |inferior| async move {
let regs = regs.as_slice();
let request_tx = inferior
.request_tx
.as_ref()
.ok_or(Error::SessionNotStarted)?;
let (reply_tx, reply_rx) = oneshot::channel();
let core_regs: CoreRegs =
bincode::deserialize(regs).map_err(|_| CommandParseError::MalformedRegisters)?;
let request = GdbRequest::WriteRegisters(core_regs, reply_tx);
let _ = request_tx
.send(request)
.await
.map_err(|_| Error::GdbRequestSendError)?;
let reply = reply_rx.await.map_err(|_| Error::GdbRequestRecvError)??;
Ok(reply)
})
.await
}
}
|
use std::fs;
use std::fs::File;
use std::io::{Read, SeekFrom, Seek};
use crate::error::Error;
use crate::utils::*;
const ELF_MAGIC: [u8; 4] = [0x7F, 0x45, 0x4c, 0x46];
const ELF_HEADER_SIZE: u16 = 0x40;
const ELF_SHENT_SIZE: u16 = 0x40;
const ELF_PHENT_SIZE: u16 = 0x38;
pub(crate) const ELF_SYMBOL_SIZE: u64 = 0x18;
#[derive(Default)]
pub struct ElfHeader {
pub entry: u64,
pub shoff: u64,
pub phoff: u64,
pub phnum: u16,
pub shnum: u16,
pub shstrndx: u16,
}
#[derive(Default)]
pub struct SectionEntry {
pub name: u32,
pub offset: u64,
pub size: u64,
pub entsize: u64,
}
#[derive(Default)]
pub struct ProgramEntry {
pub off: u64,
pub vaddr: u64,
pub filesz: u64,
pub memsz: u64,
}
#[derive(Default)]
pub struct StringTable {
table: Vec<u8>,
}
#[derive(Default)]
pub struct SymbolEntry {
pub name: u32,
pub value: u64,
pub size: u64,
}
impl ElfHeader {
pub fn from_reader(reader: &mut impl Read) -> Result<ElfHeader, Error> {
let mut rv: ElfHeader = Default::default();
let mut b = [0; ELF_HEADER_SIZE as usize];
reader.read_exact(&mut b)?;
if &b[0..4] != ELF_MAGIC {
return Err(Error::InvalidMagic);
}
if b[4] != 2 {
return Err(Error::Not64Bit);
}
if b[5] != 1 {
return Err(Error::NotLittleEndianness);
}
if array_as_u16(&b[0x34..0x36]) != ELF_HEADER_SIZE ||
array_as_u16(&b[0x36..0x38]) != ELF_PHENT_SIZE ||
array_as_u16(&b[0x3a..0x3c]) != ELF_SHENT_SIZE {
return Err(Error::InvalidStructureSize);
}
rv.entry = array_as_u64(&b[0x18..]);
rv.phoff = array_as_u64(&b[0x20..]);
rv.shoff = array_as_u64(&b[0x28..]);
rv.phnum = array_as_u16(&b[0x38..]);
rv.shnum = array_as_u16(&b[0x3c..]);
rv.shstrndx = array_as_u16(&b[0x3e..]);
Ok(rv)
}
}
impl SectionEntry {
pub fn from_reader(reader: &mut impl Read)
-> Result<SectionEntry, Error> {
let mut rv: SectionEntry = Default::default();
let mut b = [0; ELF_SHENT_SIZE as usize];
reader.read_exact(&mut b)?;
rv.name = array_as_u32(&b[0x0..]);
rv.offset = array_as_u64(&b[0x18..]);
rv.size = array_as_u64(&b[0x20..]);
rv.entsize = array_as_u64(&b[0x38..]);
Ok(rv)
}
}
impl ProgramEntry {
pub fn from_reader(reader: &mut impl Read)
-> Result<ProgramEntry, Error> {
let mut rv: ProgramEntry = Default::default();
let mut b = [0; ELF_PHENT_SIZE as usize];
reader.read_exact(&mut b)?;
rv.vaddr = array_as_u64(&b[0x10..]);
rv.off = array_as_u64(&b[0x08..]);
rv.filesz = array_as_u64(&b[0x20..]);
rv.memsz = array_as_u64(&b[0x28..]);
Ok(rv)
}
}
impl StringTable {
fn lookup(&self, index: usize) -> &[u8] {
let mut rear = index;
while self.table[rear] != 0 {
rear += 1;
}
&self.table[index..rear]
}
pub fn lookup_symbol_name(&self, sym: &SymbolEntry) -> String {
let b = self.lookup(sym.name as usize);
match String::from_utf8(Vec::from(b)) {
Ok(rv) =>
if rv.is_empty() {String::from("<null>")} else {rv},
Err(e) => String::from("<unknown>"),
}
}
pub fn equal_to_string(&self, index: usize, s: &str) -> bool {
s.as_bytes() == self.lookup(index)
}
pub fn from_reader(mut reader: impl Read, size: usize) -> Self {
let mut rv = Self {
table: Vec::new(),
};
rv.table.resize(size, 0);
reader.read_exact(rv.table.as_mut_slice());
rv
}
pub fn from_file(f: &mut File, sec: &SectionEntry) -> Self {
f.seek(SeekFrom::Start(sec.offset));
StringTable::from_reader(f, sec.size as usize)
}
pub fn section_is(&self, sec: &SectionEntry, s: &str) -> bool {
self.equal_to_string(sec.name as usize, s)
}
}
impl SymbolEntry {
pub fn from_reader(reader: &mut impl Read)
-> Result<SymbolEntry, Error> {
let mut rv: SymbolEntry = Default::default();
let mut b = [0; ELF_SYMBOL_SIZE as usize];
reader.read_exact(&mut b)?;
rv.name = array_as_u32(&b[0x0..]);
rv.value = array_as_u64(&b[0x08..]);
rv.size = array_as_u64(&b[0x10..]);
Ok(rv)
}
}
#[test]
fn test_elf_header() {
let filename = "test_obj/a.out";
let mut f = fs::File::open(filename).unwrap();
let header: ElfHeader = ElfHeader::from_reader(&mut f).unwrap();
} |
/*!
```rudra-poc
[target]
crate = "quick-protobuf"
version = "0.8.0"
indexed_version = "0.7.0"
[report]
issue_url = "https://github.com/tafia/quick-protobuf/issues/186"
issue_date = 2021-01-30
[[bugs]]
analyzer = "UnsafeDataflow"
bug_class = "UninitExposure"
rudra_report_locations = ["src/reader.rs:552:5: 560:6"]
```
!*/
#![forbid(unsafe_code)]
fn main() {
panic!("This issue was reported without PoC");
}
|
#[cfg(test)]
#[path = "../../../../tests/unit/solver/mutation/local/exchange_inter_route_test.rs"]
mod exchange_inter_route_test;
use crate::construction::heuristics::*;
use crate::models::problem::Job;
use crate::solver::mutation::{select_seed_job, LocalOperator};
use crate::solver::RefinementContext;
use crate::utils::{map_reduce, Noise};
/// A local search operator which tries to exchange jobs in best way between different routes.
pub struct ExchangeInterRouteBest {
noise_probability: f64,
noise_range: (f64, f64),
}
/// A local search operator which tries to exchange random jobs between different routes.
pub struct ExchangeInterRouteRandom {
noise_probability: f64,
noise_range: (f64, f64),
}
impl ExchangeInterRouteBest {
/// Creates a new instance of `ExchangeInterRouteBest`.
pub fn new(noise_probability: f64, min: f64, max: f64) -> Self {
Self { noise_probability, noise_range: (min, max) }
}
}
impl Default for ExchangeInterRouteBest {
fn default() -> Self {
Self::new(0.05, 0.75, 1.25)
}
}
impl LocalOperator for ExchangeInterRouteBest {
fn explore(&self, _: &RefinementContext, insertion_ctx: &InsertionContext) -> Option<InsertionContext> {
find_best_insertion_pair(
insertion_ctx,
Noise::new(self.noise_probability, self.noise_range, insertion_ctx.environment.random.clone()),
Box::new(|_| true),
Box::new(|_| true),
)
}
}
impl ExchangeInterRouteRandom {
/// Creates a new instance of `ExchangeInterRouteRandom`.
pub fn new(noise_probability: f64, min: f64, max: f64) -> Self {
Self { noise_probability, noise_range: (min, max) }
}
}
impl Default for ExchangeInterRouteRandom {
fn default() -> Self {
Self::new(0.1, 0.75, 1.25)
}
}
impl LocalOperator for ExchangeInterRouteRandom {
fn explore(&self, _: &RefinementContext, insertion_ctx: &InsertionContext) -> Option<InsertionContext> {
let random = &insertion_ctx.environment.random;
find_best_insertion_pair(
insertion_ctx,
Noise::new(self.noise_probability, self.noise_range, random.clone()),
{
let random = random.clone();
Box::new(move |_idx| random.is_head_not_tails())
},
{
let random = random.clone();
Box::new(move |_idx| random.is_head_not_tails())
},
)
}
}
type InsertionSuccessPair = (InsertionSuccess, InsertionSuccess);
fn find_best_insertion_pair(
insertion_ctx: &InsertionContext,
noise: Noise,
filter_route_indices: Box<dyn Fn(usize) -> bool + Send + Sync>,
filter_jobs_indices: Box<dyn Fn(usize) -> bool + Send + Sync>,
) -> Option<InsertionContext> {
if let Some((seed_route_idx, seed_job)) =
select_seed_job(insertion_ctx.solution.routes.as_slice(), &insertion_ctx.environment.random)
{
let locked = &insertion_ctx.solution.locked;
// bad luck: cannot move locked job
if locked.contains(&seed_job) {
return None;
}
let new_insertion_ctx = get_new_insertion_ctx(insertion_ctx, &seed_job, seed_route_idx).unwrap();
let seed_route = new_insertion_ctx.solution.routes.get(seed_route_idx).unwrap();
let result_selector = NoiseResultSelector::new(noise.clone());
let insertion_pair = new_insertion_ctx
.solution
.routes
.iter()
.enumerate()
.filter(|(idx, _)| *idx != seed_route_idx && filter_route_indices(*idx))
.fold(Option::<InsertionSuccessPair>::None, |acc, (_, test_route)| {
let new_result = map_reduce(
test_route
.route
.tour
.jobs()
.enumerate()
.filter(|(idx, job)| !locked.contains(&job) && filter_jobs_indices(*idx))
.collect::<Vec<_>>()
.as_slice(),
|(_, test_job)| {
// try to insert test job into seed tour
let seed_success =
test_job_insertion(&new_insertion_ctx, &seed_route, &test_job, &result_selector)?;
// try to insert seed job into test route
let mut test_route = test_route.deep_copy();
test_route.route_mut().tour.remove(test_job);
new_insertion_ctx.problem.constraint.accept_route_state(&mut test_route);
let test_success =
test_job_insertion(&new_insertion_ctx, &test_route, &seed_job, &result_selector)?;
Some((seed_success, test_success))
},
|| None,
|left, right| reduce_pair_with_noise(left, right, &noise),
);
reduce_pair_with_noise(acc, new_result, &noise)
});
if let Some(insertion_pair) = insertion_pair {
let mut new_insertion_ctx = new_insertion_ctx;
apply_insertion_success(&mut new_insertion_ctx, insertion_pair.0);
apply_insertion_success(&mut new_insertion_ctx, insertion_pair.1);
finalize_insertion_ctx(&mut new_insertion_ctx);
return Some(new_insertion_ctx);
}
}
None
}
fn test_job_insertion(
insertion_ctx: &InsertionContext,
route: &RouteContext,
job: &Job,
result_selector: &(dyn ResultSelector + Send + Sync),
) -> Option<InsertionSuccess> {
let insertion = evaluate_job_insertion_in_route(
&insertion_ctx,
&route,
job,
InsertionPosition::Any,
InsertionResult::make_failure(),
result_selector,
);
match insertion {
InsertionResult::Failure(_) => None,
InsertionResult::Success(success) => Some(success),
}
}
fn apply_insertion_success(insertion_ctx: &mut InsertionContext, insertion_success: InsertionSuccess) {
let route_index = insertion_ctx
.solution
.routes
.iter()
.position(|ctx| ctx.route.actor == insertion_success.context.route.actor)
.unwrap();
// NOTE replace existing route context with the different
insertion_ctx.solution.routes[route_index] =
RouteContext::new_with_state(insertion_success.context.route.clone(), insertion_success.context.state.clone());
apply_insertion_result(insertion_ctx, InsertionResult::Success(insertion_success))
}
fn reduce_pair_with_noise(
left_result: Option<InsertionSuccessPair>,
right_result: Option<InsertionSuccessPair>,
noise: &Noise,
) -> Option<InsertionSuccessPair> {
match (&left_result, &right_result) {
(Some(left), Some(right)) => {
let left_cost = noise.add(left.0.cost + left.1.cost);
let right_cost = noise.add(right.0.cost + right.1.cost);
if left_cost < right_cost {
left_result
} else {
right_result
}
}
(Some(_), _) => left_result,
(None, Some(_)) => right_result,
_ => None,
}
}
fn get_new_insertion_ctx(
insertion_ctx: &InsertionContext,
seed_job: &Job,
seed_route_idx: usize,
) -> Result<InsertionContext, String> {
let mut new_insertion_ctx = insertion_ctx.deep_copy();
let mut route_ctx = &mut new_insertion_ctx.solution.routes[seed_route_idx];
let removal_result = route_ctx.route_mut().tour.remove(&seed_job);
if !removal_result {
return Err("cannot find job in insertion ctx".to_string());
}
// NOTE removed job is not added to the required list as it will be tried
// to be reinserted later. If insertion fails, the context is discarded
new_insertion_ctx.problem.constraint.accept_route_state(&mut route_ctx);
Ok(new_insertion_ctx)
}
|
use super::super::context::Context;
use super::super::error::*;
use super::super::traits::WorkType;
use super::super::utils::station_fn_ctx2;
use super::super::work::{WorkBox, WorkOutput};
use conveyor::{into_box, station_fn};
use conveyor_work::package::Package;
use std::fmt;
use std::sync::Arc;
#[derive(Serialize, Deserialize, Clone)]
pub struct ChildProcess {
pub command: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub args: Option<Vec<String>>,
}
impl fmt::Debug for ChildProcess {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ChildProcess")
}
}
#[typetag::serde]
impl WorkType for ChildProcess {
fn request_station(&self, ctx: &mut Context) -> CrawlResult<WorkBox<Package>> {
let log = ctx.log().new(o!("worktype" => "child-process"));
info!(log, "request child-process station");
let command = ctx.interpolate(self.command.as_str()).unwrap();
info!(log, "using script"; "script" => command);
Ok(into_box(station_fn(async move |mut package: Package| {
let body = await!(package.read_content())?;
Ok(vec![WorkOutput::Result(Ok(package))])
})))
}
fn box_clone(&self) -> Box<WorkType> {
Box::new(self.clone())
}
}
|
/// An enum to represent all characters in the PhoneticExtensions block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum PhoneticExtensions {
/// \u{1d00}: 'ᴀ'
LatinLetterSmallCapitalA,
/// \u{1d01}: 'ᴁ'
LatinLetterSmallCapitalAe,
/// \u{1d02}: 'ᴂ'
LatinSmallLetterTurnedAe,
/// \u{1d03}: 'ᴃ'
LatinLetterSmallCapitalBarredB,
/// \u{1d04}: 'ᴄ'
LatinLetterSmallCapitalC,
/// \u{1d05}: 'ᴅ'
LatinLetterSmallCapitalD,
/// \u{1d06}: 'ᴆ'
LatinLetterSmallCapitalEth,
/// \u{1d07}: 'ᴇ'
LatinLetterSmallCapitalE,
/// \u{1d08}: 'ᴈ'
LatinSmallLetterTurnedOpenE,
/// \u{1d09}: 'ᴉ'
LatinSmallLetterTurnedI,
/// \u{1d0a}: 'ᴊ'
LatinLetterSmallCapitalJ,
/// \u{1d0b}: 'ᴋ'
LatinLetterSmallCapitalK,
/// \u{1d0c}: 'ᴌ'
LatinLetterSmallCapitalLWithStroke,
/// \u{1d0d}: 'ᴍ'
LatinLetterSmallCapitalM,
/// \u{1d0e}: 'ᴎ'
LatinLetterSmallCapitalReversedN,
/// \u{1d0f}: 'ᴏ'
LatinLetterSmallCapitalO,
/// \u{1d10}: 'ᴐ'
LatinLetterSmallCapitalOpenO,
/// \u{1d11}: 'ᴑ'
LatinSmallLetterSidewaysO,
/// \u{1d12}: 'ᴒ'
LatinSmallLetterSidewaysOpenO,
/// \u{1d13}: 'ᴓ'
LatinSmallLetterSidewaysOWithStroke,
/// \u{1d14}: 'ᴔ'
LatinSmallLetterTurnedOe,
/// \u{1d15}: 'ᴕ'
LatinLetterSmallCapitalOu,
/// \u{1d16}: 'ᴖ'
LatinSmallLetterTopHalfO,
/// \u{1d17}: 'ᴗ'
LatinSmallLetterBottomHalfO,
/// \u{1d18}: 'ᴘ'
LatinLetterSmallCapitalP,
/// \u{1d19}: 'ᴙ'
LatinLetterSmallCapitalReversedR,
/// \u{1d1a}: 'ᴚ'
LatinLetterSmallCapitalTurnedR,
/// \u{1d1b}: 'ᴛ'
LatinLetterSmallCapitalT,
/// \u{1d1c}: 'ᴜ'
LatinLetterSmallCapitalU,
/// \u{1d1d}: 'ᴝ'
LatinSmallLetterSidewaysU,
/// \u{1d1e}: 'ᴞ'
LatinSmallLetterSidewaysDiaeresizedU,
/// \u{1d1f}: 'ᴟ'
LatinSmallLetterSidewaysTurnedM,
/// \u{1d20}: 'ᴠ'
LatinLetterSmallCapitalV,
/// \u{1d21}: 'ᴡ'
LatinLetterSmallCapitalW,
/// \u{1d22}: 'ᴢ'
LatinLetterSmallCapitalZ,
/// \u{1d23}: 'ᴣ'
LatinLetterSmallCapitalEzh,
/// \u{1d24}: 'ᴤ'
LatinLetterVoicedLaryngealSpirant,
/// \u{1d25}: 'ᴥ'
LatinLetterAin,
/// \u{1d26}: 'ᴦ'
GreekLetterSmallCapitalGamma,
/// \u{1d27}: 'ᴧ'
GreekLetterSmallCapitalLamda,
/// \u{1d28}: 'ᴨ'
GreekLetterSmallCapitalPi,
/// \u{1d29}: 'ᴩ'
GreekLetterSmallCapitalRho,
/// \u{1d2a}: 'ᴪ'
GreekLetterSmallCapitalPsi,
/// \u{1d2b}: 'ᴫ'
CyrillicLetterSmallCapitalEl,
/// \u{1d2c}: 'ᴬ'
ModifierLetterCapitalA,
/// \u{1d2d}: 'ᴭ'
ModifierLetterCapitalAe,
/// \u{1d2e}: 'ᴮ'
ModifierLetterCapitalB,
/// \u{1d2f}: 'ᴯ'
ModifierLetterCapitalBarredB,
/// \u{1d30}: 'ᴰ'
ModifierLetterCapitalD,
/// \u{1d31}: 'ᴱ'
ModifierLetterCapitalE,
/// \u{1d32}: 'ᴲ'
ModifierLetterCapitalReversedE,
/// \u{1d33}: 'ᴳ'
ModifierLetterCapitalG,
/// \u{1d34}: 'ᴴ'
ModifierLetterCapitalH,
/// \u{1d35}: 'ᴵ'
ModifierLetterCapitalI,
/// \u{1d36}: 'ᴶ'
ModifierLetterCapitalJ,
/// \u{1d37}: 'ᴷ'
ModifierLetterCapitalK,
/// \u{1d38}: 'ᴸ'
ModifierLetterCapitalL,
/// \u{1d39}: 'ᴹ'
ModifierLetterCapitalM,
/// \u{1d3a}: 'ᴺ'
ModifierLetterCapitalN,
/// \u{1d3b}: 'ᴻ'
ModifierLetterCapitalReversedN,
/// \u{1d3c}: 'ᴼ'
ModifierLetterCapitalO,
/// \u{1d3d}: 'ᴽ'
ModifierLetterCapitalOu,
/// \u{1d3e}: 'ᴾ'
ModifierLetterCapitalP,
/// \u{1d3f}: 'ᴿ'
ModifierLetterCapitalR,
/// \u{1d40}: 'ᵀ'
ModifierLetterCapitalT,
/// \u{1d41}: 'ᵁ'
ModifierLetterCapitalU,
/// \u{1d42}: 'ᵂ'
ModifierLetterCapitalW,
/// \u{1d43}: 'ᵃ'
ModifierLetterSmallA,
/// \u{1d44}: 'ᵄ'
ModifierLetterSmallTurnedA,
/// \u{1d45}: 'ᵅ'
ModifierLetterSmallAlpha,
/// \u{1d46}: 'ᵆ'
ModifierLetterSmallTurnedAe,
/// \u{1d47}: 'ᵇ'
ModifierLetterSmallB,
/// \u{1d48}: 'ᵈ'
ModifierLetterSmallD,
/// \u{1d49}: 'ᵉ'
ModifierLetterSmallE,
/// \u{1d4a}: 'ᵊ'
ModifierLetterSmallSchwa,
/// \u{1d4b}: 'ᵋ'
ModifierLetterSmallOpenE,
/// \u{1d4c}: 'ᵌ'
ModifierLetterSmallTurnedOpenE,
/// \u{1d4d}: 'ᵍ'
ModifierLetterSmallG,
/// \u{1d4e}: 'ᵎ'
ModifierLetterSmallTurnedI,
/// \u{1d4f}: 'ᵏ'
ModifierLetterSmallK,
/// \u{1d50}: 'ᵐ'
ModifierLetterSmallM,
/// \u{1d51}: 'ᵑ'
ModifierLetterSmallEng,
/// \u{1d52}: 'ᵒ'
ModifierLetterSmallO,
/// \u{1d53}: 'ᵓ'
ModifierLetterSmallOpenO,
/// \u{1d54}: 'ᵔ'
ModifierLetterSmallTopHalfO,
/// \u{1d55}: 'ᵕ'
ModifierLetterSmallBottomHalfO,
/// \u{1d56}: 'ᵖ'
ModifierLetterSmallP,
/// \u{1d57}: 'ᵗ'
ModifierLetterSmallT,
/// \u{1d58}: 'ᵘ'
ModifierLetterSmallU,
/// \u{1d59}: 'ᵙ'
ModifierLetterSmallSidewaysU,
/// \u{1d5a}: 'ᵚ'
ModifierLetterSmallTurnedM,
/// \u{1d5b}: 'ᵛ'
ModifierLetterSmallV,
/// \u{1d5c}: 'ᵜ'
ModifierLetterSmallAin,
/// \u{1d5d}: 'ᵝ'
ModifierLetterSmallBeta,
/// \u{1d5e}: 'ᵞ'
ModifierLetterSmallGreekGamma,
/// \u{1d5f}: 'ᵟ'
ModifierLetterSmallDelta,
/// \u{1d60}: 'ᵠ'
ModifierLetterSmallGreekPhi,
/// \u{1d61}: 'ᵡ'
ModifierLetterSmallChi,
/// \u{1d62}: 'ᵢ'
LatinSubscriptSmallLetterI,
/// \u{1d63}: 'ᵣ'
LatinSubscriptSmallLetterR,
/// \u{1d64}: 'ᵤ'
LatinSubscriptSmallLetterU,
/// \u{1d65}: 'ᵥ'
LatinSubscriptSmallLetterV,
/// \u{1d66}: 'ᵦ'
GreekSubscriptSmallLetterBeta,
/// \u{1d67}: 'ᵧ'
GreekSubscriptSmallLetterGamma,
/// \u{1d68}: 'ᵨ'
GreekSubscriptSmallLetterRho,
/// \u{1d69}: 'ᵩ'
GreekSubscriptSmallLetterPhi,
/// \u{1d6a}: 'ᵪ'
GreekSubscriptSmallLetterChi,
/// \u{1d6b}: 'ᵫ'
LatinSmallLetterUe,
/// \u{1d6c}: 'ᵬ'
LatinSmallLetterBWithMiddleTilde,
/// \u{1d6d}: 'ᵭ'
LatinSmallLetterDWithMiddleTilde,
/// \u{1d6e}: 'ᵮ'
LatinSmallLetterFWithMiddleTilde,
/// \u{1d6f}: 'ᵯ'
LatinSmallLetterMWithMiddleTilde,
/// \u{1d70}: 'ᵰ'
LatinSmallLetterNWithMiddleTilde,
/// \u{1d71}: 'ᵱ'
LatinSmallLetterPWithMiddleTilde,
/// \u{1d72}: 'ᵲ'
LatinSmallLetterRWithMiddleTilde,
/// \u{1d73}: 'ᵳ'
LatinSmallLetterRWithFishhookAndMiddleTilde,
/// \u{1d74}: 'ᵴ'
LatinSmallLetterSWithMiddleTilde,
/// \u{1d75}: 'ᵵ'
LatinSmallLetterTWithMiddleTilde,
/// \u{1d76}: 'ᵶ'
LatinSmallLetterZWithMiddleTilde,
/// \u{1d77}: 'ᵷ'
LatinSmallLetterTurnedG,
/// \u{1d78}: 'ᵸ'
ModifierLetterCyrillicEn,
/// \u{1d79}: 'ᵹ'
LatinSmallLetterInsularG,
/// \u{1d7a}: 'ᵺ'
LatinSmallLetterThWithStrikethrough,
/// \u{1d7b}: 'ᵻ'
LatinSmallCapitalLetterIWithStroke,
/// \u{1d7c}: 'ᵼ'
LatinSmallLetterIotaWithStroke,
/// \u{1d7d}: 'ᵽ'
LatinSmallLetterPWithStroke,
/// \u{1d7e}: 'ᵾ'
LatinSmallCapitalLetterUWithStroke,
}
impl Into<char> for PhoneticExtensions {
fn into(self) -> char {
match self {
PhoneticExtensions::LatinLetterSmallCapitalA => 'ᴀ',
PhoneticExtensions::LatinLetterSmallCapitalAe => 'ᴁ',
PhoneticExtensions::LatinSmallLetterTurnedAe => 'ᴂ',
PhoneticExtensions::LatinLetterSmallCapitalBarredB => 'ᴃ',
PhoneticExtensions::LatinLetterSmallCapitalC => 'ᴄ',
PhoneticExtensions::LatinLetterSmallCapitalD => 'ᴅ',
PhoneticExtensions::LatinLetterSmallCapitalEth => 'ᴆ',
PhoneticExtensions::LatinLetterSmallCapitalE => 'ᴇ',
PhoneticExtensions::LatinSmallLetterTurnedOpenE => 'ᴈ',
PhoneticExtensions::LatinSmallLetterTurnedI => 'ᴉ',
PhoneticExtensions::LatinLetterSmallCapitalJ => 'ᴊ',
PhoneticExtensions::LatinLetterSmallCapitalK => 'ᴋ',
PhoneticExtensions::LatinLetterSmallCapitalLWithStroke => 'ᴌ',
PhoneticExtensions::LatinLetterSmallCapitalM => 'ᴍ',
PhoneticExtensions::LatinLetterSmallCapitalReversedN => 'ᴎ',
PhoneticExtensions::LatinLetterSmallCapitalO => 'ᴏ',
PhoneticExtensions::LatinLetterSmallCapitalOpenO => 'ᴐ',
PhoneticExtensions::LatinSmallLetterSidewaysO => 'ᴑ',
PhoneticExtensions::LatinSmallLetterSidewaysOpenO => 'ᴒ',
PhoneticExtensions::LatinSmallLetterSidewaysOWithStroke => 'ᴓ',
PhoneticExtensions::LatinSmallLetterTurnedOe => 'ᴔ',
PhoneticExtensions::LatinLetterSmallCapitalOu => 'ᴕ',
PhoneticExtensions::LatinSmallLetterTopHalfO => 'ᴖ',
PhoneticExtensions::LatinSmallLetterBottomHalfO => 'ᴗ',
PhoneticExtensions::LatinLetterSmallCapitalP => 'ᴘ',
PhoneticExtensions::LatinLetterSmallCapitalReversedR => 'ᴙ',
PhoneticExtensions::LatinLetterSmallCapitalTurnedR => 'ᴚ',
PhoneticExtensions::LatinLetterSmallCapitalT => 'ᴛ',
PhoneticExtensions::LatinLetterSmallCapitalU => 'ᴜ',
PhoneticExtensions::LatinSmallLetterSidewaysU => 'ᴝ',
PhoneticExtensions::LatinSmallLetterSidewaysDiaeresizedU => 'ᴞ',
PhoneticExtensions::LatinSmallLetterSidewaysTurnedM => 'ᴟ',
PhoneticExtensions::LatinLetterSmallCapitalV => 'ᴠ',
PhoneticExtensions::LatinLetterSmallCapitalW => 'ᴡ',
PhoneticExtensions::LatinLetterSmallCapitalZ => 'ᴢ',
PhoneticExtensions::LatinLetterSmallCapitalEzh => 'ᴣ',
PhoneticExtensions::LatinLetterVoicedLaryngealSpirant => 'ᴤ',
PhoneticExtensions::LatinLetterAin => 'ᴥ',
PhoneticExtensions::GreekLetterSmallCapitalGamma => 'ᴦ',
PhoneticExtensions::GreekLetterSmallCapitalLamda => 'ᴧ',
PhoneticExtensions::GreekLetterSmallCapitalPi => 'ᴨ',
PhoneticExtensions::GreekLetterSmallCapitalRho => 'ᴩ',
PhoneticExtensions::GreekLetterSmallCapitalPsi => 'ᴪ',
PhoneticExtensions::CyrillicLetterSmallCapitalEl => 'ᴫ',
PhoneticExtensions::ModifierLetterCapitalA => 'ᴬ',
PhoneticExtensions::ModifierLetterCapitalAe => 'ᴭ',
PhoneticExtensions::ModifierLetterCapitalB => 'ᴮ',
PhoneticExtensions::ModifierLetterCapitalBarredB => 'ᴯ',
PhoneticExtensions::ModifierLetterCapitalD => 'ᴰ',
PhoneticExtensions::ModifierLetterCapitalE => 'ᴱ',
PhoneticExtensions::ModifierLetterCapitalReversedE => 'ᴲ',
PhoneticExtensions::ModifierLetterCapitalG => 'ᴳ',
PhoneticExtensions::ModifierLetterCapitalH => 'ᴴ',
PhoneticExtensions::ModifierLetterCapitalI => 'ᴵ',
PhoneticExtensions::ModifierLetterCapitalJ => 'ᴶ',
PhoneticExtensions::ModifierLetterCapitalK => 'ᴷ',
PhoneticExtensions::ModifierLetterCapitalL => 'ᴸ',
PhoneticExtensions::ModifierLetterCapitalM => 'ᴹ',
PhoneticExtensions::ModifierLetterCapitalN => 'ᴺ',
PhoneticExtensions::ModifierLetterCapitalReversedN => 'ᴻ',
PhoneticExtensions::ModifierLetterCapitalO => 'ᴼ',
PhoneticExtensions::ModifierLetterCapitalOu => 'ᴽ',
PhoneticExtensions::ModifierLetterCapitalP => 'ᴾ',
PhoneticExtensions::ModifierLetterCapitalR => 'ᴿ',
PhoneticExtensions::ModifierLetterCapitalT => 'ᵀ',
PhoneticExtensions::ModifierLetterCapitalU => 'ᵁ',
PhoneticExtensions::ModifierLetterCapitalW => 'ᵂ',
PhoneticExtensions::ModifierLetterSmallA => 'ᵃ',
PhoneticExtensions::ModifierLetterSmallTurnedA => 'ᵄ',
PhoneticExtensions::ModifierLetterSmallAlpha => 'ᵅ',
PhoneticExtensions::ModifierLetterSmallTurnedAe => 'ᵆ',
PhoneticExtensions::ModifierLetterSmallB => 'ᵇ',
PhoneticExtensions::ModifierLetterSmallD => 'ᵈ',
PhoneticExtensions::ModifierLetterSmallE => 'ᵉ',
PhoneticExtensions::ModifierLetterSmallSchwa => 'ᵊ',
PhoneticExtensions::ModifierLetterSmallOpenE => 'ᵋ',
PhoneticExtensions::ModifierLetterSmallTurnedOpenE => 'ᵌ',
PhoneticExtensions::ModifierLetterSmallG => 'ᵍ',
PhoneticExtensions::ModifierLetterSmallTurnedI => 'ᵎ',
PhoneticExtensions::ModifierLetterSmallK => 'ᵏ',
PhoneticExtensions::ModifierLetterSmallM => 'ᵐ',
PhoneticExtensions::ModifierLetterSmallEng => 'ᵑ',
PhoneticExtensions::ModifierLetterSmallO => 'ᵒ',
PhoneticExtensions::ModifierLetterSmallOpenO => 'ᵓ',
PhoneticExtensions::ModifierLetterSmallTopHalfO => 'ᵔ',
PhoneticExtensions::ModifierLetterSmallBottomHalfO => 'ᵕ',
PhoneticExtensions::ModifierLetterSmallP => 'ᵖ',
PhoneticExtensions::ModifierLetterSmallT => 'ᵗ',
PhoneticExtensions::ModifierLetterSmallU => 'ᵘ',
PhoneticExtensions::ModifierLetterSmallSidewaysU => 'ᵙ',
PhoneticExtensions::ModifierLetterSmallTurnedM => 'ᵚ',
PhoneticExtensions::ModifierLetterSmallV => 'ᵛ',
PhoneticExtensions::ModifierLetterSmallAin => 'ᵜ',
PhoneticExtensions::ModifierLetterSmallBeta => 'ᵝ',
PhoneticExtensions::ModifierLetterSmallGreekGamma => 'ᵞ',
PhoneticExtensions::ModifierLetterSmallDelta => 'ᵟ',
PhoneticExtensions::ModifierLetterSmallGreekPhi => 'ᵠ',
PhoneticExtensions::ModifierLetterSmallChi => 'ᵡ',
PhoneticExtensions::LatinSubscriptSmallLetterI => 'ᵢ',
PhoneticExtensions::LatinSubscriptSmallLetterR => 'ᵣ',
PhoneticExtensions::LatinSubscriptSmallLetterU => 'ᵤ',
PhoneticExtensions::LatinSubscriptSmallLetterV => 'ᵥ',
PhoneticExtensions::GreekSubscriptSmallLetterBeta => 'ᵦ',
PhoneticExtensions::GreekSubscriptSmallLetterGamma => 'ᵧ',
PhoneticExtensions::GreekSubscriptSmallLetterRho => 'ᵨ',
PhoneticExtensions::GreekSubscriptSmallLetterPhi => 'ᵩ',
PhoneticExtensions::GreekSubscriptSmallLetterChi => 'ᵪ',
PhoneticExtensions::LatinSmallLetterUe => 'ᵫ',
PhoneticExtensions::LatinSmallLetterBWithMiddleTilde => 'ᵬ',
PhoneticExtensions::LatinSmallLetterDWithMiddleTilde => 'ᵭ',
PhoneticExtensions::LatinSmallLetterFWithMiddleTilde => 'ᵮ',
PhoneticExtensions::LatinSmallLetterMWithMiddleTilde => 'ᵯ',
PhoneticExtensions::LatinSmallLetterNWithMiddleTilde => 'ᵰ',
PhoneticExtensions::LatinSmallLetterPWithMiddleTilde => 'ᵱ',
PhoneticExtensions::LatinSmallLetterRWithMiddleTilde => 'ᵲ',
PhoneticExtensions::LatinSmallLetterRWithFishhookAndMiddleTilde => 'ᵳ',
PhoneticExtensions::LatinSmallLetterSWithMiddleTilde => 'ᵴ',
PhoneticExtensions::LatinSmallLetterTWithMiddleTilde => 'ᵵ',
PhoneticExtensions::LatinSmallLetterZWithMiddleTilde => 'ᵶ',
PhoneticExtensions::LatinSmallLetterTurnedG => 'ᵷ',
PhoneticExtensions::ModifierLetterCyrillicEn => 'ᵸ',
PhoneticExtensions::LatinSmallLetterInsularG => 'ᵹ',
PhoneticExtensions::LatinSmallLetterThWithStrikethrough => 'ᵺ',
PhoneticExtensions::LatinSmallCapitalLetterIWithStroke => 'ᵻ',
PhoneticExtensions::LatinSmallLetterIotaWithStroke => 'ᵼ',
PhoneticExtensions::LatinSmallLetterPWithStroke => 'ᵽ',
PhoneticExtensions::LatinSmallCapitalLetterUWithStroke => 'ᵾ',
}
}
}
impl std::convert::TryFrom<char> for PhoneticExtensions {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'ᴀ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalA),
'ᴁ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalAe),
'ᴂ' => Ok(PhoneticExtensions::LatinSmallLetterTurnedAe),
'ᴃ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalBarredB),
'ᴄ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalC),
'ᴅ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalD),
'ᴆ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalEth),
'ᴇ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalE),
'ᴈ' => Ok(PhoneticExtensions::LatinSmallLetterTurnedOpenE),
'ᴉ' => Ok(PhoneticExtensions::LatinSmallLetterTurnedI),
'ᴊ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalJ),
'ᴋ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalK),
'ᴌ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalLWithStroke),
'ᴍ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalM),
'ᴎ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalReversedN),
'ᴏ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalO),
'ᴐ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalOpenO),
'ᴑ' => Ok(PhoneticExtensions::LatinSmallLetterSidewaysO),
'ᴒ' => Ok(PhoneticExtensions::LatinSmallLetterSidewaysOpenO),
'ᴓ' => Ok(PhoneticExtensions::LatinSmallLetterSidewaysOWithStroke),
'ᴔ' => Ok(PhoneticExtensions::LatinSmallLetterTurnedOe),
'ᴕ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalOu),
'ᴖ' => Ok(PhoneticExtensions::LatinSmallLetterTopHalfO),
'ᴗ' => Ok(PhoneticExtensions::LatinSmallLetterBottomHalfO),
'ᴘ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalP),
'ᴙ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalReversedR),
'ᴚ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalTurnedR),
'ᴛ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalT),
'ᴜ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalU),
'ᴝ' => Ok(PhoneticExtensions::LatinSmallLetterSidewaysU),
'ᴞ' => Ok(PhoneticExtensions::LatinSmallLetterSidewaysDiaeresizedU),
'ᴟ' => Ok(PhoneticExtensions::LatinSmallLetterSidewaysTurnedM),
'ᴠ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalV),
'ᴡ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalW),
'ᴢ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalZ),
'ᴣ' => Ok(PhoneticExtensions::LatinLetterSmallCapitalEzh),
'ᴤ' => Ok(PhoneticExtensions::LatinLetterVoicedLaryngealSpirant),
'ᴥ' => Ok(PhoneticExtensions::LatinLetterAin),
'ᴦ' => Ok(PhoneticExtensions::GreekLetterSmallCapitalGamma),
'ᴧ' => Ok(PhoneticExtensions::GreekLetterSmallCapitalLamda),
'ᴨ' => Ok(PhoneticExtensions::GreekLetterSmallCapitalPi),
'ᴩ' => Ok(PhoneticExtensions::GreekLetterSmallCapitalRho),
'ᴪ' => Ok(PhoneticExtensions::GreekLetterSmallCapitalPsi),
'ᴫ' => Ok(PhoneticExtensions::CyrillicLetterSmallCapitalEl),
'ᴬ' => Ok(PhoneticExtensions::ModifierLetterCapitalA),
'ᴭ' => Ok(PhoneticExtensions::ModifierLetterCapitalAe),
'ᴮ' => Ok(PhoneticExtensions::ModifierLetterCapitalB),
'ᴯ' => Ok(PhoneticExtensions::ModifierLetterCapitalBarredB),
'ᴰ' => Ok(PhoneticExtensions::ModifierLetterCapitalD),
'ᴱ' => Ok(PhoneticExtensions::ModifierLetterCapitalE),
'ᴲ' => Ok(PhoneticExtensions::ModifierLetterCapitalReversedE),
'ᴳ' => Ok(PhoneticExtensions::ModifierLetterCapitalG),
'ᴴ' => Ok(PhoneticExtensions::ModifierLetterCapitalH),
'ᴵ' => Ok(PhoneticExtensions::ModifierLetterCapitalI),
'ᴶ' => Ok(PhoneticExtensions::ModifierLetterCapitalJ),
'ᴷ' => Ok(PhoneticExtensions::ModifierLetterCapitalK),
'ᴸ' => Ok(PhoneticExtensions::ModifierLetterCapitalL),
'ᴹ' => Ok(PhoneticExtensions::ModifierLetterCapitalM),
'ᴺ' => Ok(PhoneticExtensions::ModifierLetterCapitalN),
'ᴻ' => Ok(PhoneticExtensions::ModifierLetterCapitalReversedN),
'ᴼ' => Ok(PhoneticExtensions::ModifierLetterCapitalO),
'ᴽ' => Ok(PhoneticExtensions::ModifierLetterCapitalOu),
'ᴾ' => Ok(PhoneticExtensions::ModifierLetterCapitalP),
'ᴿ' => Ok(PhoneticExtensions::ModifierLetterCapitalR),
'ᵀ' => Ok(PhoneticExtensions::ModifierLetterCapitalT),
'ᵁ' => Ok(PhoneticExtensions::ModifierLetterCapitalU),
'ᵂ' => Ok(PhoneticExtensions::ModifierLetterCapitalW),
'ᵃ' => Ok(PhoneticExtensions::ModifierLetterSmallA),
'ᵄ' => Ok(PhoneticExtensions::ModifierLetterSmallTurnedA),
'ᵅ' => Ok(PhoneticExtensions::ModifierLetterSmallAlpha),
'ᵆ' => Ok(PhoneticExtensions::ModifierLetterSmallTurnedAe),
'ᵇ' => Ok(PhoneticExtensions::ModifierLetterSmallB),
'ᵈ' => Ok(PhoneticExtensions::ModifierLetterSmallD),
'ᵉ' => Ok(PhoneticExtensions::ModifierLetterSmallE),
'ᵊ' => Ok(PhoneticExtensions::ModifierLetterSmallSchwa),
'ᵋ' => Ok(PhoneticExtensions::ModifierLetterSmallOpenE),
'ᵌ' => Ok(PhoneticExtensions::ModifierLetterSmallTurnedOpenE),
'ᵍ' => Ok(PhoneticExtensions::ModifierLetterSmallG),
'ᵎ' => Ok(PhoneticExtensions::ModifierLetterSmallTurnedI),
'ᵏ' => Ok(PhoneticExtensions::ModifierLetterSmallK),
'ᵐ' => Ok(PhoneticExtensions::ModifierLetterSmallM),
'ᵑ' => Ok(PhoneticExtensions::ModifierLetterSmallEng),
'ᵒ' => Ok(PhoneticExtensions::ModifierLetterSmallO),
'ᵓ' => Ok(PhoneticExtensions::ModifierLetterSmallOpenO),
'ᵔ' => Ok(PhoneticExtensions::ModifierLetterSmallTopHalfO),
'ᵕ' => Ok(PhoneticExtensions::ModifierLetterSmallBottomHalfO),
'ᵖ' => Ok(PhoneticExtensions::ModifierLetterSmallP),
'ᵗ' => Ok(PhoneticExtensions::ModifierLetterSmallT),
'ᵘ' => Ok(PhoneticExtensions::ModifierLetterSmallU),
'ᵙ' => Ok(PhoneticExtensions::ModifierLetterSmallSidewaysU),
'ᵚ' => Ok(PhoneticExtensions::ModifierLetterSmallTurnedM),
'ᵛ' => Ok(PhoneticExtensions::ModifierLetterSmallV),
'ᵜ' => Ok(PhoneticExtensions::ModifierLetterSmallAin),
'ᵝ' => Ok(PhoneticExtensions::ModifierLetterSmallBeta),
'ᵞ' => Ok(PhoneticExtensions::ModifierLetterSmallGreekGamma),
'ᵟ' => Ok(PhoneticExtensions::ModifierLetterSmallDelta),
'ᵠ' => Ok(PhoneticExtensions::ModifierLetterSmallGreekPhi),
'ᵡ' => Ok(PhoneticExtensions::ModifierLetterSmallChi),
'ᵢ' => Ok(PhoneticExtensions::LatinSubscriptSmallLetterI),
'ᵣ' => Ok(PhoneticExtensions::LatinSubscriptSmallLetterR),
'ᵤ' => Ok(PhoneticExtensions::LatinSubscriptSmallLetterU),
'ᵥ' => Ok(PhoneticExtensions::LatinSubscriptSmallLetterV),
'ᵦ' => Ok(PhoneticExtensions::GreekSubscriptSmallLetterBeta),
'ᵧ' => Ok(PhoneticExtensions::GreekSubscriptSmallLetterGamma),
'ᵨ' => Ok(PhoneticExtensions::GreekSubscriptSmallLetterRho),
'ᵩ' => Ok(PhoneticExtensions::GreekSubscriptSmallLetterPhi),
'ᵪ' => Ok(PhoneticExtensions::GreekSubscriptSmallLetterChi),
'ᵫ' => Ok(PhoneticExtensions::LatinSmallLetterUe),
'ᵬ' => Ok(PhoneticExtensions::LatinSmallLetterBWithMiddleTilde),
'ᵭ' => Ok(PhoneticExtensions::LatinSmallLetterDWithMiddleTilde),
'ᵮ' => Ok(PhoneticExtensions::LatinSmallLetterFWithMiddleTilde),
'ᵯ' => Ok(PhoneticExtensions::LatinSmallLetterMWithMiddleTilde),
'ᵰ' => Ok(PhoneticExtensions::LatinSmallLetterNWithMiddleTilde),
'ᵱ' => Ok(PhoneticExtensions::LatinSmallLetterPWithMiddleTilde),
'ᵲ' => Ok(PhoneticExtensions::LatinSmallLetterRWithMiddleTilde),
'ᵳ' => Ok(PhoneticExtensions::LatinSmallLetterRWithFishhookAndMiddleTilde),
'ᵴ' => Ok(PhoneticExtensions::LatinSmallLetterSWithMiddleTilde),
'ᵵ' => Ok(PhoneticExtensions::LatinSmallLetterTWithMiddleTilde),
'ᵶ' => Ok(PhoneticExtensions::LatinSmallLetterZWithMiddleTilde),
'ᵷ' => Ok(PhoneticExtensions::LatinSmallLetterTurnedG),
'ᵸ' => Ok(PhoneticExtensions::ModifierLetterCyrillicEn),
'ᵹ' => Ok(PhoneticExtensions::LatinSmallLetterInsularG),
'ᵺ' => Ok(PhoneticExtensions::LatinSmallLetterThWithStrikethrough),
'ᵻ' => Ok(PhoneticExtensions::LatinSmallCapitalLetterIWithStroke),
'ᵼ' => Ok(PhoneticExtensions::LatinSmallLetterIotaWithStroke),
'ᵽ' => Ok(PhoneticExtensions::LatinSmallLetterPWithStroke),
'ᵾ' => Ok(PhoneticExtensions::LatinSmallCapitalLetterUWithStroke),
_ => Err(()),
}
}
}
impl Into<u32> for PhoneticExtensions {
fn into(self) -> u32 {
let c: char = self.into();
let hex = c
.escape_unicode()
.to_string()
.replace("\\u{", "")
.replace("}", "");
u32::from_str_radix(&hex, 16).unwrap()
}
}
impl std::convert::TryFrom<u32> for PhoneticExtensions {
type Error = ();
fn try_from(u: u32) -> Result<Self, Self::Error> {
if let Ok(c) = char::try_from(u) {
Self::try_from(c)
} else {
Err(())
}
}
}
impl Iterator for PhoneticExtensions {
type Item = Self;
fn next(&mut self) -> Option<Self> {
let index: u32 = (*self).into();
use std::convert::TryFrom;
Self::try_from(index + 1).ok()
}
}
impl PhoneticExtensions {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
PhoneticExtensions::LatinLetterSmallCapitalA
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("PhoneticExtensions{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
pub mod vec3;
|
//! Evaluate expressions as integer, rational or floating point.
//!
//! At present, everything is converted to f64.
//! But `PI.sin()` should be zero.
//! But `(PI/2).sin()` should be one.
use crate::error::{Error, Result};
use crate::visitor::Visitor;
use crate::Expression;
use crate::Evaluateable;
use std::convert::{TryFrom, TryInto};
use syn::spanned::Spanned;
use syn::{BinOp, Expr, ExprBinary, ExprMethodCall, ExprUnary, UnOp, ExprParen};
#[derive(Debug, Clone)]
pub struct Eval<T: TryFrom<Expression> + TryInto<Expression>> {
pub(crate) datatype: std::marker::PhantomData<T>,
}
impl<T: Evaluateable> Visitor for Eval<T> {
/// eg. "(x)"
fn visit_paren(&self, exprparen: &ExprParen) -> Result<Expr> {
self.visit_expr(&exprparen.expr)
}
fn visit_method_call(&self, expr: &ExprMethodCall) -> Result<Expr> {
// println!("visit_method_call {:?}", expr);
let receiver: Expression = self.visit_expr(&expr.receiver)?.into();
let args: Vec<Expression> = expr
.args
.iter()
.map(|a| -> Result<Expression> { Ok(self.visit_expr(a)?.into()) })
.collect::<Result<Vec<_>>>()?;
match (
expr.method.to_string().as_str(),
T::try_from(receiver),
args.len(),
) {
// nan() -> Self;
// infinity() -> Self;
// neg_infinity() -> Self;
// neg_zero() -> Self;
// min_value() -> Self;
// min_positive_value() -> Self;
// epsilon() -> Self {
// max_value() -> Self;
// ("is_nan", Ok(receiver), 0) => Ok(receiver.is_nan().try_into()?.into()),
// ("is_infinite", Ok(receiver), 0) => Ok(receiver.is_infinite().try_into()?.into()),
// ("is_finite", Ok(receiver), 0) => Ok(receiver.is_finite().try_into()?.into()),
// ("is_normal", Ok(receiver), 0) => Ok(receiver.is_normal().try_into()?.into()),
// ("classify", Ok(receiver), 0) => Ok(receiver.classify().try_into()?.into()),
("floor", Ok(receiver), 0) => Ok(receiver.floor().try_into()?.into()),
("ceil", Ok(receiver), 0) => Ok(receiver.ceil().try_into()?.into()),
("round", Ok(receiver), 0) => Ok(receiver.round().try_into()?.into()),
("trunc", Ok(receiver), 0) => Ok(receiver.trunc().try_into()?.into()),
("fract", Ok(receiver), 0) => Ok(receiver.fract().try_into()?.into()),
("abs", Ok(receiver), 0) => Ok(receiver.abs().try_into()?.into()),
("signum", Ok(receiver), 0) => Ok(receiver.signum().try_into()?.into()),
// ("is_sign_positive", Ok(receiver), 0) => Ok(receiver.is_sign_positive().try_into()?.into()),
// ("is_sign_negative", Ok(receiver), 0) => Ok(receiver.is_sign_negative().try_into()?.into()),
("mul_add", Ok(receiver), 2) => Ok(receiver
.mul_add(args[0].clone().try_into()?, args[1].clone().try_into()?)
.try_into()?
.into()),
("recip", Ok(receiver), 0) => Ok(receiver.recip().try_into()?.into()),
("powi", Ok(receiver), 1) => Ok(receiver
.powf(args[0].clone().try_into()?)
.try_into()?
.into()),
("powf", Ok(receiver), 1) => Ok(receiver
.powf(args[0].clone().try_into()?)
.try_into()?
.into()),
("sqrt", Ok(receiver), 0) => Ok(receiver.sqrt().try_into()?.into()),
("exp", Ok(receiver), 0) => Ok(receiver.exp().try_into()?.into()),
("exp2", Ok(receiver), 0) => Ok(receiver.exp2().try_into()?.into()),
("ln", Ok(receiver), 0) => Ok(receiver.ln().try_into()?.into()),
("log", Ok(receiver), 1) => {
Ok(receiver.log(args[0].clone().try_into()?).try_into()?.into())
}
("log2", Ok(receiver), 0) => Ok(receiver.log2().try_into()?.into()),
("log10", Ok(receiver), 0) => Ok(receiver.log10().try_into()?.into()),
("to_degrees", Ok(receiver), 0) => Ok(receiver.to_degrees().try_into()?.into()),
("to_radians", Ok(receiver), 0) => Ok(receiver.to_radians().try_into()?.into()),
("max", Ok(receiver), 1) => {
Ok(receiver.max(args[0].clone().try_into()?).try_into()?.into())
}
("min", Ok(receiver), 1) => {
Ok(receiver.min(args[0].clone().try_into()?).try_into()?.into())
}
("abs_sub", Ok(receiver), 1) => Ok(receiver
.abs_sub(args[0].clone().try_into()?)
.try_into()?
.into()),
("cbrt", Ok(receiver), 0) => Ok(receiver.cbrt().try_into()?.into()),
("hypot", Ok(receiver), 1) => Ok(receiver
.hypot(args[0].clone().try_into()?)
.try_into()?
.into()),
("sin", Ok(receiver), 0) => Ok(receiver.sin().try_into()?.into()),
("cos", Ok(receiver), 0) => Ok(receiver.cos().try_into()?.into()),
("tan", Ok(receiver), 0) => Ok(receiver.tan().try_into()?.into()),
("asin", Ok(receiver), 0) => Ok(receiver.asin().try_into()?.into()),
("acos", Ok(receiver), 0) => Ok(receiver.acos().try_into()?.into()),
("atan", Ok(receiver), 0) => Ok(receiver.atan().try_into()?.into()),
("atan2", Ok(receiver), 1) => Ok(receiver
.atan2(args[0].clone().try_into()?)
.try_into()?
.into()),
//("sin_cos", Ok(receiver), 0) => Ok(receiver.sin_cos().try_into()?.into()),
("exp_m1", Ok(receiver), 0) => Ok(receiver.exp_m1().try_into()?.into()),
("ln_1p", Ok(receiver), 0) => Ok(receiver.ln_1p().try_into()?.into()),
("sinh", Ok(receiver), 0) => Ok(receiver.sinh().try_into()?.into()),
("cosh", Ok(receiver), 0) => Ok(receiver.cosh().try_into()?.into()),
("tanh", Ok(receiver), 0) => Ok(receiver.tanh().try_into()?.into()),
("asinh", Ok(receiver), 0) => Ok(receiver.asinh().try_into()?.into()),
("acosh", Ok(receiver), 0) => Ok(receiver.acosh().try_into()?.into()),
("atanh", Ok(receiver), 0) => Ok(receiver.atanh().try_into()?.into()),
// ("integer_decode", Ok(receiver), 0) => Ok(receiver.integer_decode().try_into()?.into()),
_ => Err(Error::CouldNotEvaulate(expr.span())),
}
}
fn visit_binary(&self, exprbinary: &ExprBinary) -> Result<Expr> {
let left = T::try_from(self.visit_expr(&exprbinary.left)?.into())?;
let right = T::try_from(self.visit_expr(&exprbinary.right)?.into())?;
match exprbinary.op {
BinOp::Add(_) => Ok((left + right).try_into()?.into()),
BinOp::Sub(_) => Ok((left - right).try_into()?.into()),
BinOp::Mul(_) => Ok((left * right).try_into()?.into()),
BinOp::Div(_) => Ok((left / right).try_into()?.into()),
_ => Err(Error::CouldNotEvaulate(exprbinary.span())),
}
}
fn visit_unary(&self, exprunary: &ExprUnary) -> Result<Expr> {
let expr = T::try_from(self.visit_expr(&exprunary.expr)?.into())?;
match exprunary.op {
// UnOp::Deref(_) => (),
// UnOp::Not(_) => (),
UnOp::Neg(_) => Ok((-expr).try_into()?.into()),
_ => Err(Error::CouldNotEvaulate(exprunary.span())),
}
}
}
|
use std::ptr;
use std::mem;
const max_values_per_leaf: usize = 4;
/* A pivot is a key and a node of the subtree of values >= that key. */
struct Pivot<K, V> {
min_key: K,
child: Box<Node<K, V>>
}
struct LeafNode<K, V> {
elements: [(K, V); max_values_per_leaf],
// must be <= max_values_per_leaf
len: usize,
}
impl<K, V> LeafNode<K, V> where K: Copy, V: Clone {
fn empty() -> Self {
unsafe {
Self { elements: mem::uninitialized(), len: 0 }
}
}
fn from(items: &[(K, V)]) -> Self {
debug_assert!(items.len() <= max_values_per_leaf);
let mut result = Self::empty();
result.elements.clone_from_slice(items);
result
}
fn valid_elements_mut(&mut self) -> &mut [(K, V)] {
&mut self.elements[0..self.len]
}
fn valid_elements(&self) -> &[(K, V)] {
&self.elements[0..self.len]
}
}
struct BranchNode<K, V> {
pivots: [Pivot<K, V>; max_values_per_leaf],
// must be <= max_values_per_leaf and > 1
len: usize,
}
impl<K, V> BranchNode<K, V> where K: Copy {
fn from(left: Pivot<K, V>, right: Pivot<K, V>) -> Self {
unsafe {
let mut result = Self { pivots: mem::uninitialized(), len: 2 };
result.pivots[0] = left;
result.pivots[1] = right;
result
}
}
fn valid_pivots_mut(&mut self) -> &mut [Pivot<K, V>] {
&mut self.pivots[0..self.len]
}
fn valid_pivots(&self) -> &[Pivot<K, V>] {
&self.pivots[0..self.len]
}
}
enum Node<K, V>
{
Branch(BranchNode<K, V>),
Leaf(LeafNode<K, V>)
}
impl<K, V> Node<K, V> where K: Copy + Ord, V: Clone {
fn min_key(&self) -> K {
match *self {
Node::Branch(ref branch) => {
debug_assert!(branch.len > 1);
branch.pivots[0].min_key
},
Node::Leaf(ref leaf) => {
debug_assert_ne!(leaf.len, 0);
leaf.elements[0].0
}
}
}
fn insert(&mut self, key: K, value: V) {
let replace_node: Option<Self> = match *self {
Node::Branch(ref mut branch) => {
// Find a child node whose keys are not before the target key
match branch.valid_pivots().iter().position(|ref p| key <= p.min_key) {
Some(i) => {
// If there is one, insert into it and update the pivot key
let pivot = &mut branch.pivots[i];
pivot.min_key = key;
pivot.child.insert(key, value)
},
// o/w, insert a new leaf at the end
None => {
branch.pivots[branch.len] = Pivot {min_key: key, child: Box::new(Node::Leaf(LeafNode::empty()))};
branch.len += 1
// XXX consider splitting branch
}
};
None
}
Node::Leaf(ref mut leaf) => {
let index = leaf.valid_elements_mut().binary_search_by_key(&key, |&(k, _)| k);
match index {
Err(i) => { // key is absent, true insert
if leaf.len < max_values_per_leaf {
// there's space left, just insert
unsafe {
slice_insert(leaf.valid_elements_mut(), i, (key, value))
}
leaf.len += 1;
None
} else {
// must split the node: create the new node here
let new_branch = {
let (left, right) = leaf.valid_elements_mut().split_at(max_values_per_leaf / 2);
let left_leaf = Box::new(Node::Leaf(LeafNode::from(left)));
let right_leaf = Box::new(Node::Leaf(LeafNode::from(right)));
Node::Branch(BranchNode::from(
Pivot { min_key: left_leaf.min_key(), child: left_leaf },
Pivot { min_key: right_leaf.min_key(), child: right_leaf }
))
};
Some(new_branch)
}
},
// key is present, replace
Ok(i) => {
leaf.elements[i] = (key, value);
None
}
}
}
};
if let Some(new_branch) = replace_node {
*self = new_branch
}
}
fn delete(&mut self, key: K) {
match *self {
Node::Branch(ref mut branch) => {
// Find a child node whose keys are not before the target key
match branch.valid_pivots_mut().iter_mut().find(|ref p| key <= p.min_key) {
Some(ref mut pivot) => {
// If there is one, delete from it and update the pivot key
pivot.child.delete(key);
pivot.min_key = pivot.child.min_key()
},
// o/w, nothing to do
None => ()
}
}
Node::Leaf(ref mut leaf) if leaf.len > 0 => {
let index = leaf.valid_elements_mut().binary_search_by_key(&key, |&(k, _)| k);
match index {
Err(_) => (),
Ok(i) => {
unsafe {
slice_remove(leaf.valid_elements_mut(), i);
leaf.len -= 1;
}
}
}
}
_ => ()
}
}
fn get(&self, key: K) -> Option<&V> {
match *self {
Node::Branch(ref branch) => {
// Find a child node whose keys are not before the target key
match branch.valid_pivots().iter().find(|ref p| key <= p.min_key) {
Some(ref pivot) => {
// If there is one, query it
pivot.child.get(key)
},
// o/w, the key doesn't exist
None => None
}
}
Node::Leaf(ref leaf) if leaf.len > 0 => {
let index = leaf.valid_elements().binary_search_by_key(&key, |&(k, _)| k);
match index {
Err(_) => None,
Ok(i) => Some(&leaf.elements[i].1)
}
}
_ => None
}
}
}
unsafe fn slice_insert<T>(slice: &mut [T], idx: usize, val: T) {
ptr::copy(
slice.as_ptr().offset(idx as isize),
slice.as_mut_ptr().offset(idx as isize + 1),
slice.len() - idx
);
ptr::write(slice.get_unchecked_mut(idx), val);
}
unsafe fn slice_remove<T>(slice: &mut [T], idx: usize) -> T {
let ret = ptr::read(slice.get_unchecked(idx));
ptr::copy(
slice.as_ptr().offset(idx as isize + 1),
slice.as_mut_ptr().offset(idx as isize),
slice.len() - idx - 1
);
ret
}
/// A map based on a B𝛆-tree
pub struct BeTree< K, V > {
root: Node< K, V >
}
impl<K, V> BeTree<K, V> where K: Copy + Ord, V: Clone {
/// Create an empty B𝛆-tree.
pub fn new() -> Self { BeTree { root: Node::Leaf(LeafNode::empty()) } }
/// Clear the tree, removing all entries.
pub fn clear(&mut self) {
match self.root {
Node::Leaf(ref mut leaf) => {
leaf.len = 0
},
_ => { self.root = Node::Leaf(LeafNode::empty()) }
}
}
/// Insert a key-value pair into the tree.
///
/// If the key is already present in the tree, the value is replaced. The key is not updated, though; this matters for
/// types that can be `==` without being identical.
pub fn insert(&mut self, key: K, value: V)
{
self.root.insert(key, value)
}
/// Remove a key (and its value) from the tree.
///
/// If the key is not present, silently does nothing.
pub fn delete(&mut self, key: K)
{
self.root.delete(key)
}
/// Retrieve a reference to the value corresponding to the key.
pub fn get(&self, key: K) -> Option<&V>
{
self.root.get(key)
}
}
#[cfg(test)]
mod tests {
use BeTree;
#[test]
fn can_construct() {
BeTree::<i32, char>::new();
}
#[test]
fn can_insert_single() {
let mut b = BeTree::new();
b.insert(0, 'x');
let result = b.get(0);
assert_eq!(Some(&'x'), result);
}
#[test]
fn can_insert_two() {
let mut b = BeTree::new();
b.insert(0, 'x');
b.insert(-1, 'y');
assert_eq!(Some(&'x'), b.get(0));
assert_eq!(Some(&'y'), b.get(-1));
}
#[test]
fn can_split() {
let mut b = BeTree::new();
// insert max_values_per_leaf + 1 items
for i in 0..::max_values_per_leaf {
b.insert(i, i);
}
// are they all there?
for i in 0..::max_values_per_leaf {
assert_eq!(Some(&i), b.get(i));
}
}
#[test]
fn can_clear() {
let mut b = BeTree::new();
b.insert(0, 'x');
b.insert(-1, 'y');
b.clear();
assert_eq!(None, b.get(0));
}
#[test]
fn insert_replaces_existing() {
let mut b = BeTree::new();
b.insert(0, 'x');
b.insert(0, 'y');
assert_eq!(Some(&'y'), b.get(0));
}
#[test]
fn can_delete_existing() {
let mut b = BeTree::new();
b.insert(0, 'x');
b.delete(0);
assert_eq!(b.get(0), None)
}
#[test]
fn can_delete_only_existing() {
let mut b = BeTree::new();
b.insert(0, 'x');
b.insert(2, 'y');
b.delete(0);
assert_eq!(b.get(0), None);
assert_eq!(Some(&'y'), b.get(2));
}
#[test]
fn can_delete_nothing() {
let mut b = BeTree::<i32, char>::new();
b.delete(0);
}
}
|
use super::blockchain::{BlockChain};
use super::contract::{Contract};
use std::thread;
use std::sync::mpsc::{self};
use std::sync::{Arc, Mutex};
pub enum ApiMessage {
StartSync,
StopSync,
ImmediateSync,
}
pub struct ContextHandle {
api_sender: channel::Sender<ApiMessage>,
}
impl ContextHandle {
pub fn send(&mut self, api: ApiMessage) {
self.api_sender.send(api).expect("ethsync handler sends api");
}
}
pub struct Context {
api_receiver: channel::Receiver<ApiMessage>,
contract: Arc<Mutex<Contract>>,
blockchain: Arc<Mutx<Blockchain>>,
}
impl Context {
pub fn new(
contract: Arc<Mutex<Contract>>,
blockchain: Arc<Mutex<BlockChain>>,
) -> (Context, ContextHandle) {
let (sender, receriver) = channel::channel();
let context = Context {
api_receiver: receiver,
contract: contract,
blockchain: blockchain
};
let context_handle = ContextHandle { api_sender: sender};
}
}
|
use std::fs;
mod report_repair;
fn get_inputs () -> Vec<i32> {
let inputs: Vec<i32> = (match fs::read_to_string("./src/data/day_one") {
Ok(s) => s,
Err(e) => panic!("Could not read file: {}", e)
})
.split("\n")
.collect::<Vec<&str>>()
.iter().map(|&s| match s.parse::<i32>() {
Ok(i) => i,
Err(_) => 0 // ignore a bad parse, was probably a new line
})
.filter(|&i| i != 0)
.collect();
return inputs;
}
fn main() {
let input = get_inputs();
let result: i32 = report_repair::find_error_part_one(input.clone());
let result_two: i32 = report_repair::find_error_part_two(input.clone());
println!(" result_one: {}", result);
println!(" result_two: {}", result_two);
} |
use std::collections::HashMap;
use std::collections::HashSet;
fn main() {
proconio::input! {
s1: String,
s2: String,
s3: String
}
let cs1_org: Vec<char> = s1.chars().rev().collect();
let cs2_org: Vec<char> = s2.chars().rev().collect();
let cs3_org: Vec<char> = s3.chars().rev().collect();
let cs1: Vec<char> = s1.chars().rev().collect();
let cs2: Vec<char> = s2.chars().rev().collect();
let cs3: Vec<char> = s3.chars().rev().collect();
let mut array: Vec<char> = cs1.clone();
array.extend(cs2.clone());
array.extend(cs3.clone());
let unique: HashSet<char> = array.clone().into_iter().collect();
let mut map = HashMap::new();
for x in unique {
map.entry(x).or_insert(-1 as i32);
}
let keta:usize = 0;
for i in 0..9 {
let Some(c1) = map.get_mut(&cs1[keta]);
if *c1 == -1 {
*c1 = i as i32;
}
for j in 0..9 {
let Some(c2) = map.get_mut(&cs2[keta]);
if *c2 == -1 {
*c2 = j as i32;
}
}
}
} |
use crate::{
gui::{BuildContext, Ui, UiMessage, UiNode},
send_sync_message,
sidebar::{make_section, make_text_mark, COLUMN_WIDTH, ROW_HEIGHT},
Message,
};
use rg3d::{
core::{pool::Handle, scope_profile},
gui::{
button::ButtonBuilder,
grid::{Column, GridBuilder, Row},
message::{ButtonMessage, MessageDirection, UiMessageData, WidgetMessage},
widget::WidgetBuilder,
},
scene::{graph::Graph, node::Node, terrain::Layer},
};
use std::sync::mpsc::Sender;
pub struct LayerSection {
pub section: Handle<UiNode>,
material: Handle<UiNode>,
}
impl LayerSection {
pub fn new(ctx: &mut BuildContext) -> Self {
let material;
let section = make_section(
"Layer Properties",
GridBuilder::new(
WidgetBuilder::new()
.with_child(make_text_mark(ctx, "Material", 0))
.with_child({
material = ButtonBuilder::new(WidgetBuilder::new().on_row(0).on_column(1))
.with_text("...")
.build(ctx);
material
}),
)
.add_column(Column::strict(COLUMN_WIDTH))
.add_column(Column::stretch())
.add_row(Row::strict(ROW_HEIGHT))
.build(ctx),
ctx,
);
Self { section, material }
}
pub fn sync_to_model(&mut self, layer: Option<&Layer>, ui: &mut Ui) {
send_sync_message(
ui,
WidgetMessage::visibility(self.section, MessageDirection::ToWidget, layer.is_some()),
);
}
pub fn handle_message(
&mut self,
message: &UiMessage,
graph: &Graph,
node_handle: Handle<Node>,
layer_index: usize,
sender: &Sender<Message>,
) {
scope_profile!();
if let UiMessageData::Button(ButtonMessage::Click) = message.data() {}
if message.destination() == self.material {
sender
.send(Message::OpenMaterialEditor(
graph[node_handle].as_terrain().layers()[layer_index]
.material
.clone(),
))
.unwrap();
}
}
}
|
extern crate bit_set;
use bit_set::BitSet;
#[derive(Clone)]
pub struct Chromosome {
pub alleles: BitSet,
pub inverted: bool,
}
pub type Individual = [Chromosome; 2];
pub type Population = Vec<Individual>;
|
//! Signals are like variables that update their dependencies.
use std::{
cell::{Ref, RefCell, RefMut},
collections::HashSet,
hash::Hash,
rc::{self, Rc},
};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use crate::clone;
type SharedState<T> = Rc<State<T>>;
type WeakSharedState<T> = rc::Weak<State<T>>;
/// A [`Signal`] is like a varible, but it can update it's dependencies when it
/// changes.
///
/// ```
/// # use silkenweb_reactive::signal::*;
/// let x = Signal::new(0);
/// let next_x = x.read().map(|x| x + 1);
/// assert_eq!(*next_x.current(), 1);
/// x.write().set(2);
/// assert_eq!(*next_x.current(), 3);
/// ```
pub struct Signal<T>(SharedState<T>);
impl<T> Clone for Signal<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T: 'static> Signal<T> {
pub fn new(initial: T) -> Self {
Self(Rc::new(State::new(initial)))
}
pub fn read(&self) -> ReadSignal<T> {
ReadSignal(self.0.clone())
}
pub fn write(&self) -> WriteSignal<T> {
WriteSignal(Rc::downgrade(&self.0))
}
}
#[cfg(feature = "serde")]
impl<T: 'static + Serialize> Serialize for Signal<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0.current.serialize(serializer)
}
}
#[cfg(feature = "serde")]
impl<'de, T: 'static + Deserialize<'de>> Deserialize<'de> for Signal<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(Signal::new(T::deserialize(deserializer)?))
}
}
/// Receive changes from a signal.
///
/// Changes will stop being received when this is destroyed:
///
/// ```
/// # use silkenweb_reactive::{clone, signal::*};
/// # use std::{mem, cell::Cell, rc::Rc};
/// let x = Signal::new(1);
/// let seen_by_y = Rc::new(Cell::new(0));
/// let y = x.read().map({
/// clone!(seen_by_y);
/// move|&x| seen_by_y.set(x)
/// });
/// assert_eq!(seen_by_y.get(), 1);
/// x.write().set(2);
/// assert_eq!(seen_by_y.get(), 2);
/// mem::drop(y);
/// // We won't see this update
/// x.write().set(3);
/// assert_eq!(seen_by_y.get(), 2);
/// ```
#[must_use]
pub struct ReadSignal<T>(SharedState<T>);
impl<T> Clone for ReadSignal<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T: 'static> ReadSignal<T> {
/// The current value of the signal
pub fn current(&self) -> Ref<T> {
self.0.current()
}
/// Only propagate actual changes to the signal value.
///
/// ```
/// # use silkenweb_reactive::{clone, signal::*};
/// # use std::{mem, cell::Cell, rc::Rc};
/// let all_updates_count = Rc::new(Cell::new(0));
/// let only_changes_count = Rc::new(Cell::new(0));
/// let x = Signal::new(0);
/// let all_updates = x.read().map({
/// clone!(all_updates_count);
/// move |_| all_updates_count.set(all_updates_count.get() + 1)
/// });
/// let only_changes = x.read().only_changes().map({
/// clone!(only_changes_count);
/// move |_| only_changes_count.set(only_changes_count.get() + 1)
/// });
///
/// x.write().set(1);
/// x.write().set(1);
/// assert_eq!(all_updates_count.get(), 3, "One for init + 2 updates");
/// assert_eq!(only_changes_count.get(), 2, "One for init + 1 actual change");
/// ```
pub fn only_changes(&self) -> ReadSignal<T>
where
T: Clone + PartialEq,
{
let child = Signal::new(self.current().clone());
self.add_dependent(
&child,
Rc::new({
clone!(child);
move |new_value| {
if *child.read().current() != *new_value {
child.write().set(new_value.clone())
}
}
}),
);
child.read()
}
/// Map a function onto the inner value to produce a new [`ReadSignal`].
///
/// This only exists to make type inference easier, and just forwards its
/// arguments to [`map_to`](Self::map_to).
pub fn map<Output, Generate>(&self, generate: Generate) -> ReadSignal<Output>
where
Output: 'static,
Generate: 'static + Fn(&T) -> Output,
{
self.map_to(generate)
}
/// Receive changes to a signal.
pub fn map_to<Output>(&self, receiver: impl SignalReceiver<T, Output>) -> ReadSignal<Output>
where
Output: 'static,
{
let child = Signal::new(receiver.receive(&self.current()));
self.add_dependent(
&child,
Rc::new({
let set_value = child.write();
move |new_value| set_value.set(receiver.receive(new_value))
}),
);
child.read()
}
fn add_dependent<U>(&self, child: &Signal<U>, dependent_callback: Rc<dyn Fn(&T)>) {
self.0
.dependents
.borrow_mut()
.insert(DependentCallback::new(&dependent_callback));
child
.0
.parents
.borrow_mut()
.push(Box::new(Parent::new(dependent_callback, &self)));
}
}
/// Receive changes to a signal.
///
/// Pass a `SignalReceiver` to [`ReadSignal::map_to`], as an alternative to
/// passing a closure to [`ReadSignal::map`].
pub trait SignalReceiver<Input, Output>: 'static
where
Input: 'static,
Output: 'static,
{
fn receive(&self, x: &Input) -> Output;
}
impl<Input, Output, F> SignalReceiver<Input, Output> for F
where
Input: 'static,
Output: 'static,
F: 'static + Fn(&Input) -> Output,
{
fn receive(&self, x: &Input) -> Output {
self(x)
}
}
/// Write changes to a signal.
pub struct WriteSignal<T>(WeakSharedState<T>);
impl<T> Clone for WriteSignal<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T: 'static> WriteSignal<T> {
/// Set the inner value of a signal, and update downstream signals.
pub fn set(&self, new_value: T) {
if let Some(state) = self.0.upgrade() {
*state.current_mut() = new_value;
state.update_dependents();
}
}
/// Replace inner value of a signal using `f`, and update downstream
/// signals.
pub fn replace(&self, f: impl 'static + FnOnce(&T) -> T) {
self.mutate(|x| *x = f(x));
}
/// Mutate the inner value of a signal using `f`, and update downstream
/// signals.
pub fn mutate(&self, f: impl 'static + FnOnce(&mut T)) {
if let Some(state) = self.0.upgrade() {
f(&mut state.current_mut());
state.update_dependents();
}
}
}
/// Zip signals together to create a new one. The tuple implementation allows
/// you to write `(signal0, signal1).zip().map(...)`.
pub trait ZipSignal {
/// The inner type of the target signal.
type Target;
/// Zip the elements of `self` together.
fn zip(self) -> ReadSignal<Self::Target>;
}
impl<Lhs, Rhs> ZipSignal for (ReadSignal<Lhs>, ReadSignal<Rhs>)
where
Lhs: 'static + Clone,
Rhs: 'static + Clone,
{
type Target = (Lhs, Rhs);
fn zip(self) -> ReadSignal<Self::Target> {
let (lhs, rhs) = self;
let current = (lhs.current().clone(), rhs.current().clone());
let product = Signal::new(current);
lhs.add_dependent(
&product,
Rc::new({
let set_value = product.write();
clone!(rhs);
move |new_value| set_value.set((new_value.clone(), rhs.current().clone()))
}),
);
rhs.add_dependent(
&product,
Rc::new({
let set_value = product.write();
clone!(lhs);
move |new_value| set_value.set((lhs.current().clone(), new_value.clone()))
}),
);
product.read()
}
}
macro_rules! zip_signal{
( $($x:ident : $typ:ident),* ) => {
impl<T0, $($typ),*> ZipSignal for (ReadSignal<T0>, $(ReadSignal<$typ>),*)
where
T0: 'static + Clone,
$($typ: 'static + Clone),*
{
type Target = (T0, $($typ),*);
fn zip(self) -> ReadSignal<Self::Target> {
let (x0, $($x),*) = self;
(x0, ( $($x),* ).zip())
.zip()
.map(|(x0, ( $($x),*) )| (x0.clone(), $($x.clone()),*))
}
}
}
}
macro_rules! zip_all_signals{
() => { zip_signal!(x1: T1, x2: T2); };
($head:ident : $head_typ: ident $(, $tail:ident : $tail_typ:ident)*) => {
zip_all_signals!( $($tail: $tail_typ),* );
zip_signal!(x1: T1, x2: T2, $head: $head_typ $(, $tail: $tail_typ)*);
}
}
zip_all_signals!(
x3: T3,
x4: T4,
x5: T5,
x6: T6,
x7: T7,
x8: T8,
x9: T9,
x10: T10
);
struct State<T> {
current: RefCell<T>,
parents: RefCell<Vec<Box<dyn AnyParent>>>,
dependents: RefCell<HashSet<DependentCallback<T>>>,
}
impl<T: 'static> State<T> {
fn new(init: T) -> Self {
Self {
current: RefCell::new(init),
parents: RefCell::new(Vec::new()),
dependents: RefCell::new(HashSet::new()),
}
}
fn update_dependents(&self) {
// Take a copy here, as updating dependencies could add or remove dependencies
// here, causing a multiple borrows.
let dependents = self.dependents.borrow().clone();
// If a dependency is added while updating, it won't need updating because it
// will be initialized with the current value.
//
// If a dependency is removed before we get to it in the loop, we'll have a null
// weak reference and ignore it.
//
// If a dependency is removed after we get to it in the loop, we'll still update
// it.
for dep in &dependents {
if let Some(f) = dep.0.upgrade() {
f(&self.current());
}
}
}
fn current(&self) -> Ref<T> {
self.current
.try_borrow()
.expect("Possible circular dependency")
}
fn current_mut(&self) -> RefMut<T> {
self.current
.try_borrow_mut()
.expect("Possible circular dependency")
}
}
trait AnyParent {}
struct Parent<T> {
dependent_callback: Rc<dyn Fn(&T)>,
parent: Rc<State<T>>,
}
impl<T> Parent<T> {
fn new(dependent_callback: Rc<dyn Fn(&T)>, parent: &ReadSignal<T>) -> Self {
Self {
dependent_callback,
parent: parent.0.clone(),
}
}
}
impl<T> AnyParent for Parent<T> {}
impl<T> Drop for Parent<T> {
fn drop(&mut self) {
let removed = self
.parent
.dependents
.borrow_mut()
.remove(&DependentCallback(Rc::downgrade(&self.dependent_callback)));
assert!(removed);
}
}
struct DependentCallback<T>(rc::Weak<dyn Fn(&T)>);
impl<T> Clone for DependentCallback<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T> DependentCallback<T> {
fn new(f: &Rc<dyn 'static + Fn(&T)>) -> Self {
Self(Rc::downgrade(f))
}
fn upgrade(&self) -> Rc<dyn 'static + Fn(&T)> {
self.0.upgrade().unwrap()
}
}
impl<T> PartialEq for DependentCallback<T> {
fn eq(&self, other: &Self) -> bool {
// We need to discard the vtable by casting as we only care if the data pointers
// are equal. See https://github.com/rust-lang/rust/issues/46139
Rc::as_ptr(&self.upgrade()).cast::<()>() == Rc::as_ptr(&other.upgrade()).cast::<()>()
}
}
impl<T> Eq for DependentCallback<T> {}
impl<T> Hash for DependentCallback<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
Rc::as_ptr(&self.upgrade()).hash(state);
}
}
|
use std::fmt;
use anyhow::Error;
use crate::error::ErrorKind;
const ENTROPY_OFFSET: usize = 8;
/// Determines the number of words that will be present in a [`Mnemonic`][Mnemonic] phrase
///
/// Also directly affects the amount of entropy that will be used to create a [`Mnemonic`][Mnemonic],
/// and therefore the cryptographic strength of the HD wallet keys/addresses that can be derived from
/// it using the [`Seed`][Seed].
///
/// For example, a 12 word mnemonic phrase is essentially a friendly representation of a 128-bit key,
/// while a 24 word mnemonic phrase is essentially a 256-bit key.
///
/// If you know you want a specific phrase length, you can use the enum variant directly, for example
/// `MnemonicType::Words12`.
///
/// You can also get a `MnemonicType` that corresponds to one of the standard BIP39 key sizes by
/// passing arbitrary `usize` values:
///
/// ```
/// use bip39::{MnemonicType};
///
/// let mnemonic_type = MnemonicType::for_key_size(128).unwrap();
/// ```
///
/// [MnemonicType]: ../mnemonic_type/struct.MnemonicType.html
/// [Mnemonic]: ../mnemonic/struct.Mnemonic.html
/// [Seed]: ../seed/struct.Seed.html
///
#[derive(Debug, Copy, Clone)]
pub enum MnemonicType {
// ... = (entropy_bits << ...) | checksum_bits
Words12 = (128 << ENTROPY_OFFSET) | 4,
Words15 = (160 << ENTROPY_OFFSET) | 5,
Words18 = (192 << ENTROPY_OFFSET) | 6,
Words21 = (224 << ENTROPY_OFFSET) | 7,
Words24 = (256 << ENTROPY_OFFSET) | 8,
}
impl MnemonicType {
/// Get a `MnemonicType` for a mnemonic phrase with a specific number of words
///
/// Specifying a word count not provided for by the BIP39 standard will return an `Error`
/// of kind `ErrorKind::InvalidWordLength`.
///
/// # Example
/// ```
/// use bip39::{MnemonicType};
///
/// let mnemonic_type = MnemonicType::for_word_count(12).unwrap();
/// ```
pub fn for_word_count(size: usize) -> Result<MnemonicType, Error> {
let mnemonic_type = match size {
12 => MnemonicType::Words12,
15 => MnemonicType::Words15,
18 => MnemonicType::Words18,
21 => MnemonicType::Words21,
24 => MnemonicType::Words24,
_ => Err(ErrorKind::InvalidWordLength(size))?,
};
Ok(mnemonic_type)
}
/// Get a `MnemonicType` for a mnemonic phrase representing the given key size as bits
///
/// Specifying a key size not provided for by the BIP39 standard will return an `Error`
/// of kind `ErrorKind::InvalidKeysize`.
///
/// # Example
/// ```
/// use bip39::{MnemonicType};
///
/// let mnemonic_type = MnemonicType::for_key_size(128).unwrap();
/// ```
pub fn for_key_size(size: usize) -> Result<MnemonicType, Error> {
let mnemonic_type = match size {
128 => MnemonicType::Words12,
160 => MnemonicType::Words15,
192 => MnemonicType::Words18,
224 => MnemonicType::Words21,
256 => MnemonicType::Words24,
_ => Err(ErrorKind::InvalidKeysize(size))?,
};
Ok(mnemonic_type)
}
/// Get a `MnemonicType` for an existing mnemonic phrase
///
/// This can be used when you need information about a mnemonic phrase based on the number of
/// words, for example you can get the entropy value using [`MnemonicType::entropy_bits`][MnemonicType::entropy_bits()].
///
/// Specifying a phrase that does not match one of the standard BIP39 phrase lengths will return
/// an `Error` of kind `ErrorKind::InvalidWordLength`. The phrase will not be validated in any
/// other way.
///
/// # Example
/// ```
/// use bip39::{MnemonicType};
///
/// let test_mnemonic = "park remain person kitchen mule spell knee armed position rail grid ankle";
///
/// let mnemonic_type = MnemonicType::for_phrase(test_mnemonic).unwrap();
///
/// let entropy_bits = mnemonic_type.entropy_bits();
/// ```
///
/// [MnemonicType::entropy_bits()]: ./enum.MnemonicType.html#method.entropy_bits
pub fn for_phrase(phrase: &str) -> Result<MnemonicType, Error> {
let word_count = phrase.split(" ").count();
Self::for_word_count(word_count)
}
/// Return the number of entropy+checksum bits
///
///
/// # Example
/// ```
/// use bip39::{MnemonicType};
///
/// let test_mnemonic = "park remain person kitchen mule spell knee armed position rail grid ankle";
///
/// let mnemonic_type = MnemonicType::for_phrase(test_mnemonic).unwrap();
///
/// let total_bits = mnemonic_type.total_bits();
/// ```
pub fn total_bits(&self) -> usize {
self.entropy_bits() + self.checksum_bits() as usize
}
/// Return the number of entropy bits
///
///
/// # Example
/// ```
/// use bip39::{MnemonicType};
///
/// let test_mnemonic = "park remain person kitchen mule spell knee armed position rail grid ankle";
///
/// let mnemonic_type = MnemonicType::for_phrase(test_mnemonic).unwrap();
///
/// let entropy_bits = mnemonic_type.entropy_bits();
/// ```
pub fn entropy_bits(&self) -> usize {
(*self as usize) >> ENTROPY_OFFSET
}
/// Return the number of checksum bits
///
///
/// # Example
/// ```
/// use bip39::{MnemonicType};
///
/// let test_mnemonic = "park remain person kitchen mule spell knee armed position rail grid ankle";
///
/// let mnemonic_type = MnemonicType::for_phrase(test_mnemonic).unwrap();
///
/// let checksum_bits = mnemonic_type.checksum_bits();
/// ```
pub fn checksum_bits(&self) -> u8 {
(*self as usize) as u8
}
/// Return the number of words
///
///
/// # Example
/// ```
/// use bip39::{MnemonicType};
///
/// let mnemonic_type = MnemonicType::Words12;
///
/// let word_count = mnemonic_type.word_count();
/// ```
pub fn word_count(&self) -> usize {
self.total_bits() / 11
}
}
impl Default for MnemonicType {
fn default() -> MnemonicType {
MnemonicType::Words12
}
}
impl fmt::Display for MnemonicType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{} words ({}bits)",
self.word_count(),
self.entropy_bits()
)
}
}
#[cfg(test)]
mod test {
use super::*;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::*;
#[cfg_attr(all(target_arch = "wasm32"), wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn word_count() {
assert_eq!(MnemonicType::Words12.word_count(), 12);
assert_eq!(MnemonicType::Words15.word_count(), 15);
assert_eq!(MnemonicType::Words18.word_count(), 18);
assert_eq!(MnemonicType::Words21.word_count(), 21);
assert_eq!(MnemonicType::Words24.word_count(), 24);
}
#[cfg_attr(all(target_arch = "wasm32"), wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn entropy_bits() {
assert_eq!(MnemonicType::Words12.entropy_bits(), 128);
assert_eq!(MnemonicType::Words15.entropy_bits(), 160);
assert_eq!(MnemonicType::Words18.entropy_bits(), 192);
assert_eq!(MnemonicType::Words21.entropy_bits(), 224);
assert_eq!(MnemonicType::Words24.entropy_bits(), 256);
}
#[cfg_attr(all(target_arch = "wasm32"), wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn checksum_bits() {
assert_eq!(MnemonicType::Words12.checksum_bits(), 4);
assert_eq!(MnemonicType::Words15.checksum_bits(), 5);
assert_eq!(MnemonicType::Words18.checksum_bits(), 6);
assert_eq!(MnemonicType::Words21.checksum_bits(), 7);
assert_eq!(MnemonicType::Words24.checksum_bits(), 8);
}
}
|
use std::io::{self, BufRead, Write};
#[macro_use] extern crate lrlex;
#[macro_use] extern crate lrpar;
// Using `lrlex_mod!` brings the lexer for `calc.l` into scope.
lrlex_mod!(calc_l);
// Using `lrpar_mod!` brings the lexer for `calc.l` into scope.
lrpar_mod!(calc_y);
fn main() {
// We need to get a `LexerDef` for the `calc` language in order that we can lex input.
let lexerdef = calc_l::lexerdef();
let stdin = io::stdin();
loop {
print!(">>> ");
io::stdout().flush().ok();
match stdin.lock().lines().next() {
Some(Ok(ref l)) => {
if l.trim().is_empty() {
continue;
}
// Now we create a lexer with the `lexer` method with which we can lex an input.
// Note that each lexer can only lex one input in its lifetime.
let lexer = lexerdef.lexer(l);
match lexer.lexemes() {
Ok(lexemes) => {
// Now parse the stream of lexemes into a tree
match calc_y::parse(&lexemes) {
Ok(pt) => println!("{:?}", pt),
Err((_, errs)) => {
// One or more errors were detected during parsing.
for e in errs {
let (line, col) = lexer.line_and_col(e.lexeme()).unwrap();
assert_eq!(line, 1);
println!("Error at column {}.", col);
}
}
}
},
Err(e) => println!("Lexing error {:?}", e)
}
},
_ => break
}
}
}
|
#[derive(Debug, Copy, Clone)]
pub enum Compression {
NONE = 0,
GZIP = 1,
SNAPPY = 2
}
impl Default for Compression {
fn default() -> Self {
Compression::NONE
}
}
|
use rand::Rng;
pub fn from(id: u8) -> crate::Text {
let url = format!(
"http://tazzon.free.fr/dactylotest/dactylotest/new_text.php?t=26&l=fr&force={}",
id
);
let text = reqwest::get(&url).unwrap().text().unwrap();
let mut text = text.split("###").skip(1);
let source = format!("Text number {} of tazzon (http://tazzon.free.fr/dactylotest/dactylotest).\nExtracted from: {}", id, text.next().expect("Tazzon has a bug"));
let text = text.next().expect("Tazzon has a bug");
crate::Text::new(text.to_string(), source.to_string())
}
pub fn random() -> crate::Text {
let mut rng = rand::thread_rng();
let id: u8 = rng.gen_range(0, 131);
from(id)
}
|
//! Organizational module for Hydroflow Send/RecvCtx structs and Input/OutputPort structs.
use std::cell::RefMut;
use std::marker::PhantomData;
use ref_cast::RefCast;
use sealed::sealed;
use super::HandoffId;
use crate::scheduled::handoff::{CanReceive, Handoff, TryCanReceive};
/// An empty trait used to denote [`Polarity`]: either **send** or **receive**.
///
/// [`SendPort`] and [`RecvPort`] have identical representations (via [`Port`]) but are not
/// interchangable, so [`SEND`] and [`RECV`] which implement this trait are used to differentiate
/// between the two polarities.
#[sealed]
pub trait Polarity: 'static {}
/// An uninstantiable type used to tag port [`Polarity`] as **send**.
///
/// See also: [`RECV`].
pub enum SEND {}
/// An uninstantiable type used to tag port [`Polarity`] as **receive**.
///
/// See also: [`SEND`].
pub enum RECV {}
#[sealed]
impl Polarity for SEND {}
#[sealed]
impl Polarity for RECV {}
/// Lightweight ID struct representing an input or output port for a [`Handoff`] added to a
/// [`Hydroflow`](super::graph::Hydroflow) instance..
#[must_use]
pub struct Port<S: Polarity, H>
where
H: Handoff,
{
pub(crate) handoff_id: HandoffId,
#[allow(clippy::type_complexity)]
pub(crate) _marker: PhantomData<(*const S, fn() -> H)>,
}
/// Send-specific variant of [`Port`]. An output port.
pub type SendPort<H> = Port<SEND, H>;
/// Recv-specific variant of [`Port`]. An input port.
pub type RecvPort<H> = Port<RECV, H>;
/// Wrapper around a handoff to differentiate between output and input.
#[derive(RefCast)]
#[repr(transparent)]
pub struct PortCtx<S: Polarity, H> {
pub(crate) handoff: H,
pub(crate) _marker: PhantomData<*const S>,
}
/// Send-specific [`PortCtx`]. Output to send into a handoff.
pub type SendCtx<H> = PortCtx<SEND, H>;
/// Recv-specific [`PortCtx`]. Input to receive from a handoff.
pub type RecvCtx<H> = PortCtx<RECV, H>;
/// Context provided to a subgraph for reading from a handoff. Corresponds to a [`SendPort`].
impl<H: Handoff> SendCtx<H> {
/// Alias for [`Handoff::give`] on the inner `H`.
pub fn give<T>(&self, item: T) -> T
where
H: CanReceive<T>,
{
<H as CanReceive<T>>::give(&self.handoff, item)
}
/// Alias for [`Handoff::try_give`] on the inner `H`.
pub fn try_give<T>(&self, item: T) -> Result<T, T>
where
H: TryCanReceive<T>,
{
<H as TryCanReceive<T>>::try_give(&self.handoff, item)
}
}
/// Context provided to a subgraph for reading from a handoff. Corresponds to a [`RecvPort`].
impl<H: Handoff> RecvCtx<H> {
/// See [`Handoff::take_inner`].
pub fn take_inner(&self) -> H::Inner {
self.handoff.take_inner()
}
/// See [`Handoff::borrow_mut_swap`].
pub fn borrow_mut_swap(&self) -> RefMut<H::Inner> {
self.handoff.borrow_mut_swap()
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.