text stringlengths 8 4.13M |
|---|
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* io/byte_reader.rs *
* *
* byte reader for Rust. *
* *
* LastModified: Sep 30, 2016 *
* Author: Chen Fei <cf@hprose.com> *
* *
\**********************************************************/
use super::tags::*;
use super::util::utf8_slice_to_str;
use self::ParserError::*;
use std::{io, num, f32, f64};
use time;
#[derive(Clone, PartialEq, Debug)]
pub enum ParserError {
BadUTF8Encode,
ParseBoolError,
ParseIntError(num::ParseIntError),
ParseFloatError(num::ParseFloatError),
ParseTimeError(time::ParseError),
IoError(io::ErrorKind),
}
pub type ParserResult<T> = Result<T, ParserError>;
pub struct ByteReader<'a> {
pub buf: &'a [u8],
pub off: usize
}
impl<'a> ByteReader<'a> {
/// Constructs a new `ByteReader<'a>`.
#[inline]
pub fn new(buf: &'a [u8]) -> ByteReader<'a> {
ByteReader {
buf: buf,
off: 0
}
}
pub fn next(&mut self, count: usize) -> ParserResult<&[u8]> {
let p = self.off + count;
if p <= self.buf.len() {
let b = &self.buf[self.off..p];
self.off = p;
Ok(b)
} else {
Err(IoError(io::ErrorKind::UnexpectedEof))
}
}
pub fn read_byte(&mut self) -> ParserResult<u8> {
if self.off < self.buf.len() {
let b = self.buf[self.off];
self.off += 1;
Ok(b)
} else {
Err(IoError(io::ErrorKind::UnexpectedEof))
}
}
#[inline]
pub fn unread_byte(&mut self) {
if self.off > 0 {
self.off -= 1;
}
}
pub fn read_i64_with_tag(&mut self, tag: u8) -> ParserResult<i64> {
let mut i: i64 = 0;
let mut b = try!(self.read_byte());
if b == tag {
return Ok(i)
}
let mut neg = false;
if b == TAG_NEG {
neg = true;
b = try!(self.read_byte());
} else if b == TAG_POS {
b = try!(self.read_byte());
}
if neg {
while b != tag {
i = i.wrapping_mul(10).wrapping_sub((b - b'0') as i64);
b = try!(self.read_byte());
}
Ok(i)
} else {
while b != tag {
i = i.wrapping_mul(10).wrapping_add((b - b'0') as i64);
b = try!(self.read_byte());
}
Ok(i)
}
}
#[inline]
pub fn read_u64_with_tag(&mut self, tag: u8) -> ParserResult<u64> {
self.read_i64_with_tag(tag).map(|i| i as u64)
}
pub fn read_long_as_f64(&mut self) -> ParserResult<f64> {
let mut f = 0f64;
let mut b = try!(self.read_byte());
if b == TAG_SEMICOLON {
return Ok(f)
}
let mut neg = false;
if b == TAG_NEG {
neg = true;
b = try!(self.read_byte());
} else if b == TAG_POS {
b = try!(self.read_byte());
}
if neg {
while b != TAG_SEMICOLON {
f = f * 10f64 - (b - b'0') as f64;
b = try!(self.read_byte());
}
Ok(f)
} else {
while b != TAG_SEMICOLON {
f = f * 10f64 + (b - b'0') as f64;
b = try!(self.read_byte());
}
Ok(f)
}
}
#[inline]
pub fn read_i64(&mut self) -> ParserResult<i64> {
self.read_i64_with_tag(TAG_SEMICOLON)
}
#[inline]
pub fn read_u64(&mut self) -> ParserResult<u64> {
self.read_u64_with_tag(TAG_SEMICOLON)
}
#[inline]
pub fn read_len(&mut self) -> ParserResult<usize> {
self.read_i64_with_tag(TAG_QUOTE).map(|i| i as usize)
}
pub fn read_until(&mut self, tag: u8) -> ParserResult<&[u8]> {
let result = &self.buf[self.off..];
match result.iter().position(|x| *x == tag) {
Some(idx) => {
self.off += idx + 1;
Ok(&result[..idx])
},
None => {
self.off = self.buf.len();
Ok(result)
}
}
}
pub fn read_f32(&mut self) -> ParserResult<f32> {
self.read_until(TAG_SEMICOLON)
.and_then(|v| utf8_slice_to_str(v).parse::<f32>().map_err(|e| ParseFloatError(e)))
}
pub fn read_f64(&mut self) -> ParserResult<f64> {
self.read_until(TAG_SEMICOLON)
.and_then(|v| utf8_slice_to_str(v).parse::<f64>().map_err(|e| ParseFloatError(e)))
}
pub fn read_utf8_slice(&mut self, length: usize) -> ParserResult<&[u8]> {
if length == 0 {
return Ok(&[])
}
let p = self.off;
let mut i: usize = 0;
while i < length {
let b = self.buf[self.off];
match b >> 4 {
0...7 => self.off += 1,
12 | 13 => self.off += 2,
14 => self.off += 3,
15 => {
if b & 8 == 8 {
return Err(BadUTF8Encode)
}
self.off += 4;
i += 1
},
_ => return Err(BadUTF8Encode)
}
i += 1;
}
Ok(&self.buf[p..self.off])
}
pub fn read_utf8_string(&mut self, length: usize) -> ParserResult<String> {
self.read_utf8_slice(length).map(|s| unsafe { String::from_utf8_unchecked(s.to_owned()) })
}
pub fn read_string(&mut self) -> ParserResult<String> {
let len = try!(self.read_len());
let s = self.read_utf8_string(len);
try!(self.read_byte());
s
}
pub fn read_inf_32(&mut self) -> ParserResult<f32> {
self.read_byte().map(|sign| if sign == TAG_POS { f32::INFINITY } else { f32::NEG_INFINITY })
}
pub fn read_inf_64(&mut self) -> ParserResult<f64> {
self.read_byte().map(|sign| if sign == TAG_POS { f64::INFINITY } else { f64::NEG_INFINITY })
}
}
|
use std::io;
fn main() {
let mut choice:usize = 0;
while choice!=5{
println!("=========================================================\nATIVIDADE AVALIATIVA - P1\nLINGUAGENS E TÉCNICAS DE PROGRAMAÇÃO\n[ 1 ] - VERIFICAR PARIDADE\n[ 2 ] - VERIFICAR POLARIDADE\n[ 3 ] - CRÉDITO ESPECIAL\n[ 4 ] - TRIANGULO\n[ 5 ] - SAIR DO PROGRAMA\n=========================================================\nDigite sua Opção: ");
let mut x = String::new();
io::stdin()
.read_line(&mut x)
.expect("Failed to read line");
let choice:usize = x
.trim()
.parse()
.expect("Opção incorreta");
if choice ==1{
println!("Digite um numero maior que 0: ");
let mut n1 = String::new();
io::stdin()
.read_line(&mut n1)
.expect("Failed to read line");
let mut n1u:usize = n1
.trim()
.parse()
.expect("Opção incorreta");
verifica_paridade(n1u);
}if choice ==2{
println!("Digite um numero : ");
let mut n1 = String::new();
io::stdin()
.read_line(&mut n1)
.expect("Failed to read line");
let mut n1u:isize = n1
.trim()
.parse()
.expect("Opção incorreta");
verifica_polaridade(n1u);
}if choice ==3{
println!("Digite o valor do saldo medio: ");
let mut sm = String::new();
io::stdin()
.read_line(&mut sm)
.expect("Failed to read line");
let mut smu:f32 = sm
.trim()
.parse()
.expect("Opção incorreta");
verifica_credito(smu);
}
if choice ==4{
println!("Digite o valor do primeiro triangulo: ");
let mut tx = String::new();
io::stdin()
.read_line(&mut tx)
.expect("Failed to read line");
let mut txu:usize = tx
.trim()
.parse()
.expect("Opção incorreta");
println!("Digite o valor do segundo triangulo: ");
let mut ty = String::new();
io::stdin()
.read_line(&mut ty)
.expect("Failed to read line");
let mut tyu:usize = ty
.trim()
.parse()
.expect("Opção incorreta");
println!("Digite o valor do terceiro triangulo: ");
let mut tz = String::new();
io::stdin()
.read_line(&mut tz)
.expect("Failed to read line");
let mut tzu:usize = tz
.trim()
.parse()
.expect("Opção incorreta");
verifica_triangulo(txu,tyu,tzu);
}if choice ==5{
break;
}
}
}
fn verifica_paridade(n1u:usize){
if n1u%2==0{
println!("numero par");
}else{
println!("numero impar");
}
}
fn verifica_polaridade (n1u:isize){
if n1u>=0{
println!("O número informado é POSITIVO");
}else if n1u<0{
println!("O número informado é NEGATIVO");
}
}
fn verifica_credito(smu:f32){
let mut ce = String::new();
io::stdin()
.read_line(&mut ce)
.expect("Failed to read line");
let mut ceu:f32 = ce
.trim()
.parse()
.expect("Opção incorreta");
if smu<201.0{
println!("Nenhum credito disponivel");
}else if smu>=201.0 && smu<=400.0{
let ceu=smu*0.2;
println!("Caro cliente, como o seu saldo médio foi de {}, o valor de seu crédito especial será de {}",smu,ceu);
}else if smu>=401.0 && smu<=600.0{
let ceu=smu*0.3;
println!("Caro cliente, como o seu saldo médio foi de {}, o valor de seu crédito especial será de {}",smu,ceu);
}else if smu>600.0{
let ceu=smu*0.4;
println!("Caro cliente, como o seu saldo médio foi de {}, o valor de seu crédito especial será de {}",smu,ceu);
}
}
fn verifica_triangulo(txu:usize,tyu:usize,tzu:usize){
if txu<=tyu+tzu && tyu<=tzu+txu && tzu<=txu+tyu &&txu>0&&tyu>0&&tzu>0{
if txu==tyu &&txu==tzu&&tyu==tzu{
println!("O triangulo é Equilatero")
}else if (txu==tyu &&txu!=tzu)|(tyu==tzu&&tyu!=txu)|(txu==tzu&&txu!=tyu){
println!("O triangulo é isosceles");
}else if txu!=tyu&&txu!=tzu&&tyu!=tzu{
println!("O triangulo é escaleno");
}
}else{
println!(" Triangulo inexistente")
}
} |
use std::{cell::Cell, fmt::Display, mem, u8};
pub struct Objects {
first: Cell<Option<Obj>>,
}
impl Objects {
pub fn new() -> Self {
Self {
first: Cell::new(None)
}
}
pub fn string(&self, s: &str) -> Obj {
let obj = Obj::string(s, self.first.get());
self.first.set(Some(obj));
obj
}
}
unsafe fn drop_obj(obj: Obj) {
match (*obj.0).kind {
ObjKind::String => {
let obj_pointer: *mut StringObj = mem::transmute(obj.0);
let obj_box = Box::from_raw(obj_pointer);
let slice_pointer: *mut [u8] = mem::transmute(obj_box.chars);
let slice_box = Box::from_raw(slice_pointer);
drop(slice_box);
drop(obj_box);
}
}
}
impl Drop for Objects {
fn drop(&mut self) {
unsafe {
let mut object = self.first.get();
loop {
if let Some(obj) = object {
let next = (*obj.0).next;
drop_obj(obj);
object = next;
} else {
break
}
}
}
}
}
#[derive(Debug, Clone, Copy)]
#[repr(transparent)]
pub struct Obj(*mut BaseObj);
impl Obj {
fn string(s: &str, next: Option<Obj>) -> Self {
unsafe {
assert!(s.len() < u32::MAX as usize);
let byte_pointer = s.as_bytes().to_owned().into_boxed_slice();
let byte_pointer = Box::into_raw(byte_pointer);
let obj = StringObj {
base: BaseObj {
kind: ObjKind::String,
next,
},
chars: byte_pointer,
};
let obj_pointer = Box::new(obj);
let obj_pointer = Box::into_raw(obj_pointer);
Obj(mem::transmute(obj_pointer))
}
}
pub fn as_string(&self) -> Option<&str> {
unsafe {
let base: &BaseObj = mem::transmute(self.0);
if base.kind == ObjKind::String {
let string: &StringObj = mem::transmute(self.0);
Some(string.as_str())
} else {
None
}
}
}
}
impl Display for Obj {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
unsafe {
let base: &BaseObj = mem::transmute(self.0);
match base.kind {
ObjKind::String => {
let string: &StringObj = mem::transmute(self.0);
write!(f, "{}", string.as_str())
}
}
}
}
}
impl PartialEq for Obj {
fn eq(&self, other: &Self) -> bool {
unsafe {
let base_self: &BaseObj = mem::transmute(self.0);
let other_self: &BaseObj = mem::transmute(other.0);
match (&base_self.kind, &other_self.kind) {
(ObjKind::String, ObjKind::String) => {
let a: &StringObj = mem::transmute(self.0);
let b: &StringObj = mem::transmute(other.0);
a.as_str() == b.as_str()
}
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
enum ObjKind {
String,
}
#[repr(C)]
struct BaseObj {
kind: ObjKind,
next: Option<Obj>,
}
#[repr(C)]
struct StringObj {
base: BaseObj,
chars: *const [u8],
}
impl StringObj {
unsafe fn as_str(&self) -> &str {
std::str::from_utf8_unchecked(mem::transmute(self.chars))
}
}
// TODO!
// Each string requires two separate dynamic allocations—one for the ObjString
// and a second for the character array. Accessing the characters from a value
// requires two pointer indirections, which can be bad for performance. A more
// efficient solution relies on a technique called flexible array members.
// Use that to store the ObjString and its character array in a single
// contiguous allocation.
// TODO!
// When we create the ObjString for each string literal, we copy the characters
// onto the heap. That way, when the string is later freed, we know it is safe
// to free the characters too.
//
// This is a simpler approach but wastes some memory, which might be a problem
// on very constrained devices. Instead, we could keep track of which ObjStrings
// own their character array and which are “constant strings” that just point
// back to the original source string or some other non-freeable location. Add
// support for this.
|
// Copyright 2019 Google LLC
//
// 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.
extern crate vimscript_core;
use std::env;
use std::fs;
use vimscript_core::format;
use vimscript_core::lexer::Lexer;
use vimscript_core::parser::Parser;
fn main() {
for filename in env::args().skip(1) {
println!("{}", filename);
let contents = fs::read_to_string(filename).expect("Something went wrong reading the file");
// TODO: read list of files from the command line
let mut parser = Parser::new(Lexer::new(&contents));
let program = parser.parse();
if parser.errors.len() > 0 {
for error in parser.errors {
println!("{:?}", error);
}
} else {
println!("{}", format::format(&program));
}
}
}
|
use std::collections::HashMap;
fn main() {
let filename = "input2.txt";
let input = std::fs::read_to_string(filename).unwrap();
let required_fields
= ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"];
// let optional_field = "cid";
let credentials: Vec<HashMap<&str, &str>> = input
.split("\n\n")
.map(|cred| {
let mut fields = HashMap::new();
let fields_strings = cred.split_whitespace();
for key_value in fields_strings {
let key_value_splitted:Vec<&str> = key_value.split(":").collect();
fields.insert(key_value_splitted[0], key_value_splitted[1]);
}
fields
})
.collect();
println!("{}", credentials.iter().count());
let mut bad = 0;
for (index, credential) in credentials.iter().enumerate() {
// let mut is_ok = true;
let required_available:Vec<bool> = required_fields
.clone()
.iter()
.map(|f| credential.contains_key(f))
.collect();
match required_available.iter().find(|x| **x == false) {
Some(_) => {
println!("Missing!");
println!("{}: {:?}", index, required_available);
bad = bad + 1
},
None => {}
}
}
println!("{}", bad);
}
// fn parse_file (str: String) -> {
// } |
#![allow(dead_code)]
#[derive(Debug)]
struct Person<'lifetime> {
name: &'lifetime str
}
#[derive(Debug)]
struct Company<'lifetime> {
employees: Vec<Person<'lifetime>>
}
pub fn lifetime_test() {
let p1 = Person {
name: "Vadhri"
};
let p2 = Person {
name: "Venkata"
};
let p3 = Person {
name: "Ratnam"
};
let c = Company {
employees: vec! [p1, p2, p3]
};
println!("Company => {:?}", c);
}
|
use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
use std::ops::Add;
pub trait Number {
fn value(&self) -> i32;
fn zero(&self) -> Self;
fn is_zero(&self) -> bool;
fn successor(&self) -> Self;
fn predecessor(&self) -> Self;
}
#[allow(dead_code)]
pub fn factorial<
T: Number
+ std::fmt::Debug
+ std::ops::Add<Output = T>
+ PartialOrd
+ Clone
+ std::ops::Mul<Output = T>,
>(
num: T,
) -> <T as Add>::Output {
let mut result = num.clone();
let mut counter = num.clone().predecessor();
while counter.is_zero() == false {
result = counter.clone() * result;
counter = counter.predecessor();
}
result
}
#[allow(dead_code)]
pub fn fib<T: Number + std::fmt::Debug + std::ops::Add<Output = T> + PartialOrd>(
num: T,
) -> <T as Add>::Output {
if num <= num.zero() {
num.zero()
} else if num == num.zero().successor() {
num.zero().successor()
} else if num == num.zero().successor().successor() {
fib(num.predecessor()) + num.zero()
} else {
let result = fib(num.predecessor()) + fib(num.predecessor().predecessor());
result
}
}
type Int = i32;
impl Number for Int {
fn value(&self) -> i32 {
self.clone()
}
fn zero(&self) -> Self {
0
}
fn is_zero(&self) -> bool {
*self == 0
}
fn successor(&self) -> Self {
*self + 1
}
fn predecessor(&self) -> Self {
*self - 1
}
}
#[derive(Debug, Clone)]
struct BigInt {
#[allow(dead_code)]
base: i32,
#[allow(dead_code)]
powers: Vec<i32>,
}
impl BigInt {
#[allow(dead_code)]
pub fn new(base: i32) -> Self {
BigInt {
base,
powers: vec![],
}
}
}
impl Eq for BigInt {}
impl Ord for BigInt {
fn cmp(&self, other: &Self) -> Ordering {
self.value().cmp(&other.value())
}
}
impl PartialOrd for BigInt {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for BigInt {
fn eq(&self, other: &Self) -> bool {
self.value() == other.value()
}
}
impl Add for BigInt {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
let mut result: BigInt;
let mut counter: BigInt;
match self.base == other.base {
false => panic!("Incompatible bases"),
true => {
if self.value() > other.value() {
result = self.clone();
counter = other.clone();
} else {
counter = self.clone();
result = other.clone();
}
while counter.is_zero() == false {
result = result.successor();
counter = counter.predecessor();
}
}
}
result
}
}
impl Number for BigInt {
fn value(&self) -> i32 {
self.powers
.iter()
.rev()
.enumerate()
.map(|(index, num)| {
if index == 0 {
num.clone()
} else if index == 1 {
num.clone() * self.base
} else {
let power = (1..=index as usize).fold(1, |sum, _| sum * self.base);
num.clone() * power
}
})
.fold(0, |sum, i| sum + i)
}
fn zero(&self) -> Self {
BigInt {
base: 10,
powers: vec![0],
}
}
fn is_zero(&self) -> bool {
self.powers.is_empty() || self.powers == vec![0]
}
fn successor(&self) -> Self {
match self.powers.is_empty() {
true => BigInt {
base: self.base.clone(),
powers: vec![0],
},
false => {
let mut new_powers = self.powers.clone();
for (index, num) in self.powers.iter().rev().enumerate() {
if num + 1 < self.base {
new_powers[self.powers.len() - index - 1] = num + 1;
break;
} else {
new_powers[self.powers.len() - index - 1] = 0;
if self.powers.len() > index + 1 {
new_powers[self.powers.len() - index - 2] = num + 1
} else {
new_powers.insert(0, 1);
}
}
}
// Get rid of extra powers
if new_powers.len() > 1 && new_powers[0] == 0 {
let _ = new_powers.remove(0);
}
BigInt {
base: self.base.clone(),
powers: new_powers,
}
}
}
}
fn predecessor(&self) -> Self {
match self.powers.is_empty() {
true => BigInt {
base: self.base.clone(),
powers: vec![0],
},
false => {
let mut new_powers = self.powers.clone();
for (index, num) in self.powers.iter().rev().enumerate() {
// Edge case:
if new_powers == vec![1] {
new_powers = vec![0]
}
if num - 1 >= 0 {
new_powers[self.powers.len() - index - 1] = num - 1;
break;
} else {
new_powers[self.powers.len() - index - 1] = self.base - 1;
if self.powers.len() - index - 2 > 0 {
let second_num = new_powers[self.powers.len() - index - 2];
if second_num > 0 {
new_powers[self.powers.len() - index - 2] = second_num - 1;
break;
} else {
continue;
}
}
}
}
// Get rid of extra powers
if new_powers.len() > 1 && new_powers[0] == 0 {
let _ = new_powers.remove(0);
}
BigInt {
base: self.base.clone(),
powers: new_powers,
}
}
}
}
}
#[cfg(test)]
mod tests {
use std::vec;
use super::*;
#[test]
fn test_add_for_int() {
let one: Int = 1;
let two: Int = 2;
let three: Int = 3;
assert_eq!(one + two, three);
}
#[test]
fn test_add_for_big_int() {
let ten = BigInt {
base: 10,
powers: vec![1, 0],
};
let hundred = BigInt {
base: 10,
powers: vec![1, 0, 0],
};
let result = ten.clone() + hundred.clone();
assert_eq!(result.value(), 110);
let result = hundred.clone() + ten.clone();
assert_eq!(result.value(), 110);
let result = hundred.clone() + hundred.clone();
assert_eq!(result.value(), 200);
}
#[test]
fn test_fib_for_int() {
let ten: Int = 10;
let result = fib(ten);
assert_eq!(result, 55);
}
#[test]
fn test_factorial_for_int() {
let ten: Int = 10;
let result = factorial(ten);
assert_eq!(result, 3628800);
}
#[test]
fn test_fib_for_big_int() {
let ten = BigInt {
base: 10,
powers: vec![1, 0],
};
let result = fib(ten);
assert_eq!(result.value(), 55);
}
#[test]
fn test_bigint_is_zero() {
let big_int = BigInt {
base: 10,
powers: vec![0],
};
assert_eq!(big_int.is_zero(), true);
}
#[test]
fn test_bigint_predecessor() {
let mut big_int = BigInt {
base: 10,
powers: vec![3, 0, 0],
};
for num in (0..300).rev() {
big_int = big_int.predecessor();
assert_eq!(big_int.value(), num);
}
}
#[test]
fn test_bigint_successor() {
let mut big_int = BigInt {
base: 10,
powers: vec![0],
};
for num in 1..300 {
big_int = big_int.successor();
assert_eq!(big_int.value(), num);
}
}
#[test]
fn test_bigint_value() {
let seven = BigInt {
base: 10,
powers: vec![7],
};
assert_eq!(seven.value(), 7);
let twenty_seven = BigInt {
base: 10,
powers: vec![2, 7],
};
assert_eq!(twenty_seven.value(), 27);
let three_hundred_seven = BigInt {
base: 10,
powers: vec![3, 0, 7],
};
assert_eq!(three_hundred_seven.value(), 307);
}
#[test]
fn test_int_zero() {
let num: Int = 5;
assert_eq!(num.zero(), 0);
}
#[test]
fn test_int_is_zero() {
let num: Int = 0;
assert_eq!(num.is_zero(), true);
let num: Int = 1;
assert_eq!(num.is_zero(), false);
}
#[test]
fn test_int_successor() {
let num: Int = 4;
assert_eq!(num.successor(), 5);
}
#[test]
fn test_int_predecessor() {
let num: Int = 4;
assert_eq!(num.predecessor(), 3);
}
}
|
#[repr(C)]
pub struct Point {
pub x: f32,
pub y: f32,
}
#[repr(u32)]
pub enum Foo {
A = 1,
B,
C,
}
#[no_mangle]
pub unsafe extern "C" fn get_origin() -> Point {
Point { x: 0.0, y: 0.0 }
}
#[no_mangle]
pub unsafe extern "C" fn add_points(p1: Point, p2: Point) -> Point {
Point {
x: p1.x + p2.x,
y: p1.y + p2.y,
}
}
#[no_mangle]
pub unsafe extern "C" fn is_in_range(point: Point, range: f32) -> bool {
(point.x.powi(2) + point.y.powi(2)).sqrt() <= range
}
#[no_mangle]
pub unsafe extern "C" fn print_foo(foo: *const Foo) {
println!(
"{}",
match *foo {
Foo::A => "a",
Foo::B => "b",
Foo::C => "c",
}
);
}
|
use binread::BinRead;
/// An unsigned axis, representing a centered value, such as a joystick axis.
#[derive(BinRead, Debug, Default)]
pub struct SignedAxis(u8);
impl SignedAxis {
pub fn from_raw(val: u8) -> Self {
Self(val)
}
pub fn raw(&self) -> u8 {
self.0
}
/// Return axis as an f32 in the range of [-1.0, 1.0]
///
/// **Note:** the gamecube doesn't have a true center point. To have the controller properly
/// centered, use [`SignedAxis::float_centered`] and provide a centerpoint (typically pulled
/// from when the controller is first registered or on recalibration).
pub fn float(&self) -> f32 {
((self.0 as f32) - 127.5) / 127.5
}
/// Return axis as an f64 in the range of [-1.0, 1.0]
///
/// **Note:** You likely do not want the additional precision.
pub fn double(&self) -> f64 {
((self.0 as f64) - 127.5) / 127.5
}
/// Return axis as an `f32` in the range of [-1.0, 1.0] centered around a given raw value.
/// It is recommended the provided center value is pulled on start and on recalibration on a
/// per-axis basis as most controllers have slight variation in their center.
pub fn float_centered(&self, center: u8) -> f32 {
let center_offset = ((self.0 as i16) - (center as i16)) as f32;
let scale = if self.0 > center { (u8::MAX - center).max(1) } else { center } as f32;
center_offset / scale
}
/// Return axis as an `f64` in the range of [-1.0, 1.0] centered around a given raw value.
/// It is recommended the provided center value is pulled on start and on recalibration on a
/// per-axis basis as most controllers have slight variation in their center.
pub fn double_centered(&self, center: u8) -> f64 {
let center_offset = ((self.0 as i16) - (center as i16)) as f64;
let scale = if self.0 > center { (u8::MAX - center).max(1) } else { center } as f64;
center_offset / scale
}
}
/// An unsigned axis, representing a positive or zero value.
#[derive(BinRead, Debug, Default)]
pub struct UnsignedAxis(u8);
impl UnsignedAxis {
pub fn from_raw(val: u8) -> Self {
Self(val)
}
pub fn raw(&self) -> u8 {
self.0
}
/// Return axis as an `f32` in the range of [-1.0, 1.0]
pub fn float(&self) -> f32 {
(self.0 as f32) / 255.0
}
/// Return axis as an `f64` in the range of [-1.0, 1.0]
///
/// **Note:** You likely do not want the additional precision.
pub fn double(&self) -> f64 {
(self.0 as f64) / 255.0
}
}
#[cfg(test)]
mod tests {
use super::*;
//#[test]
//fn test_signed() {
// assert_eq!(SignedAxis::from_raw(127).float(), 1.0);
// assert_eq!(SignedAxis::from_raw(-128).float(), -1.0);
// assert_eq!(SignedAxis::from_raw(0).float(), 0.0);
// assert_eq!(SignedAxis::from_raw(127).double(), 1.0);
// assert_eq!(SignedAxis::from_raw(-128).double(), -1.0);
// assert_eq!(SignedAxis::from_raw(0).double(), 0.0);
//}
//#[test]
//fn test_inverted() {
// assert_eq!(InvertedSignedAxis::from_raw(127).float(), -1.0);
// assert_eq!(InvertedSignedAxis::from_raw(-128).float(), 1.0);
// assert_eq!(InvertedSignedAxis::from_raw(0).float(), 0.0);
// assert_eq!(InvertedSignedAxis::from_raw(127).double(), -1.0);
// assert_eq!(InvertedSignedAxis::from_raw(-128).double(), 1.0);
// assert_eq!(InvertedSignedAxis::from_raw(0).double(), 0.0);
//}
//
//#[test]
//fn test_unsigned() {
// assert_eq!(UnsignedAxis::from_raw(255).float(), 1.0);
// assert_eq!(UnsignedAxis::from_raw(0).float(), 0.0);
// assert_eq!(UnsignedAxis::from_raw(255).double(), 1.0);
// assert_eq!(UnsignedAxis::from_raw(0).double(), 0.0);
//}
}
|
use crate::hittable::*;
use crate::ray::*;
use crate::vec3::*;
pub struct Sphere {
pub center: Point3,
pub radius: f64,
}
impl Sphere {
pub fn new() -> Self {
Self {
center: Point3::new(),
radius: 0.0,
}
}
pub fn from(cen: Point3, r: f64) -> Self {
Self {
center: cen,
radius: r,
}
}
}
impl Hittable for Sphere {
fn hit(&self, r: &Ray, t_min: f64, t_max: f64, rec: &mut HitRecord) -> bool {
let oc = r.origin() - self.center;
let a = r.direction().length_squared();
let half_b = dot(oc, r.direction());
let c = oc.length_squared() - self.radius * self.radius;
let discriminant = half_b * half_b - a * c;
if discriminant < 0.0 {
return false;
}
let sqrtd = discriminant.sqrt();
//Find the nearest root that lies in the acceptable range.
let mut root = (-half_b - sqrtd) / a;
if root < t_min || t_max < root {
root = (-half_b + sqrtd) / a;
if root < t_min || t_max < root {
return false;
}
}
rec.t = root;
rec.p = r.at(rec.t);
let outward_normal = (rec.p - self.center) / self.radius;
rec.set_face_normal(r, &outward_normal);
//rec.normal = (rec.p - self.center) / self.radius;
true
}
}
|
use common::rsip::{self, prelude::*};
use models::transport::{RequestMsg, ResponseMsg, TransportMsg};
use std::convert::TryInto;
use tokio::sync::Mutex;
#[derive(Debug)]
pub struct Messages(pub Mutex<Vec<TransportMsg>>);
impl Messages {
pub async fn len(&self) -> usize {
self.0.lock().await.len()
}
pub async fn first(&self) -> TransportMsg {
self.0
.lock()
.await
.first()
.expect("missing first message")
.clone()
}
pub async fn first_request_msg(&self) -> RequestMsg {
TryInto::<RequestMsg>::try_into(self.first().await).expect("convert to RequestMsg")
}
pub async fn first_request(&self) -> rsip::Request {
TryInto::<rsip::Request>::try_into(self.first().await.sip_message)
.expect("convert to rsip::Request")
}
pub async fn first_response_msg(&self) -> ResponseMsg {
TryInto::<ResponseMsg>::try_into(self.first().await).expect("convert to ResponseMsg")
}
pub async fn first_response(&self) -> rsip::Response {
TryInto::<rsip::Response>::try_into(self.first().await.sip_message)
.expect("convert to rsip::Response")
}
pub async fn last(&self) -> TransportMsg {
self.0
.lock()
.await
.last()
.expect("missing last message")
.clone()
}
pub async fn last_request_msg(&self) -> RequestMsg {
TryInto::<RequestMsg>::try_into(self.last().await).expect("convert to RequestMsg")
}
pub async fn last_request(&self) -> rsip::Request {
TryInto::<rsip::Request>::try_into(self.last().await.sip_message)
.expect("convert to rsip::Request")
}
pub async fn last_response_msg(&self) -> ResponseMsg {
TryInto::<ResponseMsg>::try_into(self.last().await).expect("convert to ResponseMsg")
}
pub async fn last_response(&self) -> rsip::Response {
TryInto::<rsip::Response>::try_into(self.last().await.sip_message)
.expect("convert to rsip::Response")
}
pub async fn push(&self, msg: TransportMsg) {
let mut messages = self.0.lock().await;
messages.push(msg);
}
}
impl Default for Messages {
fn default() -> Self {
Self(Mutex::new(vec![]))
}
}
|
#[doc = "Register `SCR` writer"]
pub type W = crate::W<SCR_SPEC>;
#[doc = "Field `CALRAF` writer - CALRAF"]
pub type CALRAF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CALRBF` writer - CALRBF"]
pub type CALRBF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CWUTF` writer - CWUTF"]
pub type CWUTF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CTSF` writer - CTSF"]
pub type CTSF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CTSOVF` writer - CTSOVF"]
pub type CTSOVF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CITSF` writer - CITSF"]
pub type CITSF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl W {
#[doc = "Bit 0 - CALRAF"]
#[inline(always)]
#[must_use]
pub fn calraf(&mut self) -> CALRAF_W<SCR_SPEC, 0> {
CALRAF_W::new(self)
}
#[doc = "Bit 1 - CALRBF"]
#[inline(always)]
#[must_use]
pub fn calrbf(&mut self) -> CALRBF_W<SCR_SPEC, 1> {
CALRBF_W::new(self)
}
#[doc = "Bit 2 - CWUTF"]
#[inline(always)]
#[must_use]
pub fn cwutf(&mut self) -> CWUTF_W<SCR_SPEC, 2> {
CWUTF_W::new(self)
}
#[doc = "Bit 3 - CTSF"]
#[inline(always)]
#[must_use]
pub fn ctsf(&mut self) -> CTSF_W<SCR_SPEC, 3> {
CTSF_W::new(self)
}
#[doc = "Bit 4 - CTSOVF"]
#[inline(always)]
#[must_use]
pub fn ctsovf(&mut self) -> CTSOVF_W<SCR_SPEC, 4> {
CTSOVF_W::new(self)
}
#[doc = "Bit 5 - CITSF"]
#[inline(always)]
#[must_use]
pub fn citsf(&mut self) -> CITSF_W<SCR_SPEC, 5> {
CITSF_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 = "This register can be protected against non-secure access. Refer to Section50.3.4: RTC secure protection modes.\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`scr::W`](W). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SCR_SPEC;
impl crate::RegisterSpec for SCR_SPEC {
type Ux = u32;
}
#[doc = "`write(|w| ..)` method takes [`scr::W`](W) writer structure"]
impl crate::Writable for SCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets SCR to value 0"]
impl crate::Resettable for SCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//! Library representing a Tetris game.
//! ```
//! use tetris::State;
//! use tetris::State::*;
//!
//! // Initialise a game at the title screen
//! let mut state = State::title();
//!
//! loop {
//! // Match on the state of the game and get a new state back.
//! state = match state {
//! Title(title) => {
//! title.start_game()
//! },
//! Play(ref mut game) => {
//! // Play some random moves
//! game.move_left();
//! game.rotate();
//! game.start_hard_drop();
//! state
//! }
//! Paused(paused) => {
//! paused.unpause()
//! }
//! GameOver(mut game_over) => {
//! // Submit my high-score!
//! game_over.push_name("BOB");
//! game_over.submit()
//! }
//! };
//!
//! // Update the state of the game by one tick
//! state = state.update();
//!
//! // Draw game state and sleep
//! // ...
//! # break;
//! }
//! ```
#![deny(missing_docs)]
pub use self::board::Board;
pub use self::game::Game;
pub use self::game_over::{GameOver, HighScores};
pub use self::piece::Piece;
pub use self::pos::Pos;
pub use self::score::{Score, ScoreMessage, ScoreValidationError, SCORE_ENDPOINT};
pub use self::shape::{Rotation, Shape, ShapeColor};
pub use self::state::{Paused, State, Title};
#[macro_use]
mod macros;
mod args;
mod board;
mod game;
mod game_over;
mod piece;
mod pos;
mod rest;
mod score;
mod shape;
mod state;
|
use super::{
shared::{mask_32, vector_256},
*,
};
use crate::{
bin_u32,
classification::{QuoteClassifiedBlock, ResumeClassifierBlockState, ResumeClassifierState},
debug,
input::{error::InputError, InputBlock, InputBlockIterator},
FallibleIterator,
};
super::shared::structural_classifier!(Avx2Classifier32, BlockAvx2Classifier32, mask_32, 32, u32);
struct BlockAvx2Classifier32 {
internal_classifier: vector_256::BlockClassifier256,
}
impl BlockAvx2Classifier32 {
fn new() -> Self {
Self {
// SAFETY: target feature invariant
internal_classifier: unsafe { vector_256::BlockClassifier256::new() },
}
}
#[target_feature(enable = "avx2")]
#[inline]
unsafe fn classify<'i, B: InputBlock<'i, 32>>(
&mut self,
quote_classified_block: QuoteClassifiedBlock<B, u32, 32>,
) -> mask_32::StructuralsBlock<B> {
let block = "e_classified_block.block;
let classification = self.internal_classifier.classify_block(block);
let structural = classification.structural;
let nonquoted_structural = structural & !quote_classified_block.within_quotes_mask;
bin_u32!("structural", structural);
bin_u32!("nonquoted_structural", nonquoted_structural);
mask_32::StructuralsBlock::new(quote_classified_block, nonquoted_structural)
}
}
|
/* Import macros and others */
use crate::schema::*;
/* For beeing able to serialize */
use serde::Serialize;
#[derive(Debug, Queryable, Serialize)]
pub struct User {
pub id: i32,
pub first_name: String,
pub last_name: Option<String>,
pub email: String,
pub created_at: String,
pub updated_at: String,
}
#[derive(Debug, Insertable, AsChangeset)]
#[table_name = "users"]
pub struct NewUser<'x> {
pub first_name: &'x str,
pub last_name: Option<&'x str>,
pub email: String,
}
|
use reqwest;
use reqwest::StatusCode;
use reqwest::header::HeaderMap;
use std::io;
use std::io::Write;
use super::error::{NodError, Result};
use url::Url;
pub fn download(url: &str) -> Result<Vec<u8>> {
let mut writer: Vec<u8> = vec![];
download_to(url, &mut writer)?;
Ok(writer)
}
pub fn download_to<T: Write>(url: &str, mut writer: T) -> Result<()> {
let mut res = reqwest::get(url)?;
if !res.status().is_success() {
return Err(NodError::Other("status not"));
}
io::copy(&mut res, &mut writer)?;
Ok(())
}
pub fn download_header(url: Url) -> Result<HeaderMap> {
let res = reqwest::get(url.as_str())?;
if !res.status().is_success() {
return Err(NodError::Other("status not"));
}
Ok(res.headers().clone())
} |
use ethereum_types::{Address, Bloom, H256, U256};
use bytes::Bytes;
use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp};
use keccak_hash::{keccak, KECCAK_NULL_RLP};
use byteorder::{BigEndian, ByteOrder};
#[derive(Debug, Clone, Eq)]
pub struct Header {
pub parent_hash: H256,
pub coinbase: Address,
pub state_root: H256,
pub receipts_root: H256,
pub transactions_root: H256,
pub log_bloom: Bloom,
pub difficulty: U256,
pub number: u64,
pub gas_used: U256,
pub gas_limit: U256,
pub timestamp: u64,
pub extra_data: Bytes,
pub mix_digest: H256,
pub nonce: Bytes,
}
impl PartialEq for Header {
fn eq(&self, c: &Header) -> bool {
self.parent_hash == c.parent_hash && self.coinbase == c.coinbase
&& self.state_root == c.state_root && self.receipts_root == c.receipts_root
&& self.transactions_root == c.transactions_root
&& self.log_bloom == c.log_bloom && self.difficulty == c.difficulty
&& self.number == c.number && self.gas_used == c.gas_used
&& self.gas_limit == c.gas_limit && self.timestamp == c.timestamp
&& self.extra_data == c.extra_data && self.mix_digest == c.mix_digest
&& self.nonce == c.nonce
}
}
impl Default for Header {
fn default() -> Self {
Header {
parent_hash: H256::default(),
coinbase: Address::default(),
state_root: KECCAK_NULL_RLP,
receipts_root: KECCAK_NULL_RLP,
transactions_root: KECCAK_NULL_RLP,
log_bloom: Bloom::default(),
difficulty: U256::default(),
number: 0,
gas_used: U256::default(),
gas_limit: U256::default(),
timestamp: 0,
extra_data: vec![],
mix_digest: H256::default(),
nonce: vec![],
}
}
}
impl Header {
pub fn new() -> Self {
Self::default()
}
pub fn parent_hash(&self) -> &H256 {
&self.parent_hash
}
pub fn timestamp(&self) -> u64 {
self.timestamp
}
pub fn number(&self) -> u64 {
self.number
}
pub fn coinbase(&self) -> &Address {
&self.coinbase
}
pub fn extra_data(&self) -> &Bytes {
&self.extra_data
}
pub fn state_root(&self) -> &H256 {
&self.state_root
}
pub fn receipts_root(&self) -> &H256 {
&self.receipts_root
}
pub fn transactions_root(&self) -> &H256 {
&self.transactions_root
}
pub fn log_bloom(&self) -> &Bloom {
&self.log_bloom
}
pub fn gas_used(&self) -> &U256 {
&self.gas_used
}
pub fn gas_limit(&self) -> &U256 {
&self.gas_limit
}
pub fn difficulty(&self) -> &U256 {
&self.difficulty
}
pub fn nonce(&self) -> u64 {
BigEndian::read_u64(&self.nonce.as_slice()[0..8])
}
pub fn stream_rlp(&self, s: &mut RlpStream, with_seal: bool) {
s.begin_list(13 + if with_seal { 2 } else { 0 });
s.append(&self.parent_hash);
s.append(&self.coinbase);
s.append(&self.state_root);
s.append(&self.transactions_root);
s.append(&self.receipts_root);
s.append(&self.log_bloom);
s.append(&self.difficulty);
s.append(&self.number);
s.append(&self.gas_limit);
s.append(&self.gas_used);
s.append(&self.timestamp);
s.append(&self.extra_data);
if with_seal {
s.append(&self.mix_digest);
s.append(&&self.nonce[0..8]);
}
}
pub fn rlp(&self, with_seal: bool) -> Bytes {
let mut s = RlpStream::new();
self.stream_rlp(&mut s, with_seal);
s.out()
}
pub fn rlp_keccak(&self, with_seal: bool) -> H256 {
keccak(self.rlp(with_seal))
}
}
impl Decodable for Header {
fn decode(r: &UntrustedRlp) -> Result<Self, DecoderError> {
let item_count = r.item_count()?;
if r.item_count()? != 14 {
Err(DecoderError::RlpIncorrectListLen)
} else {
Ok(Header {
parent_hash: r.val_at(0)?,
coinbase: r.val_at(1)?,
state_root: r.val_at(2)?,
transactions_root: r.val_at(3)?,
receipts_root: r.val_at(4)?,
log_bloom: r.val_at(5)?,
difficulty: r.val_at(6)?,
number: r.val_at(7)?,
gas_limit: r.val_at(8)?,
gas_used: r.val_at(9)?,
timestamp: r.val_at::<U256>(10)?.as_u64(),
extra_data: r.val_at(11)?,
mix_digest: r.val_at(12)?,
nonce: r.val_at(13)?,
})
}
}
}
impl Encodable for Header {
fn rlp_append(&self, s: &mut RlpStream) {
self.stream_rlp(s, true);
}
}
#[cfg(test)]
mod tests {
use rustc_hex::FromHex;
use rlp;
use super::Header;
use ethereum_types::{Address, Bloom, H256, U256};
use byteorder::{BigEndian, ByteOrder};
use bytes::Bytes;
#[test]
fn test_header_decode() {
let header_rlp = "f901d8a083cafc574e1f51ba9dc0568fc617a08ea2429fb384059c972f13b19fa1c8dd55948888f1f195afa192cfee860698584c030f4c9db1a0ef1552a40b7165c3cd773806b9e0c165b75356e0314bf0706f279c729f51e017a05fe50b260da6308036625b850b5d6ced6d0a9f814c0688bc91ffb7b7a3a54b67a0bc37d79753ad738a6dac4921e57392f145d8887476de3f783dfa7edae9283e52b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000001832fefd8825208845506eb0780a0bd4472abb6659ebe3ee06ee4d7b72a00a9f4d001caca51342001075469aff49888a13a5a8c8f2bb1c4".from_hex().unwrap();
let expected_header: Header = rlp::decode(&header_rlp);
let mut nonce: Bytes = vec![0; 8];
BigEndian::write_u64(&mut nonce, 0xa13a5a8c8f2bb1c4);
let header = Header {
parent_hash: H256::from(
"83cafc574e1f51ba9dc0568fc617a08ea2429fb384059c972f13b19fa1c8dd55"
.from_hex()
.unwrap()
.as_slice(),
),
coinbase: Address::from(
"8888f1f195afa192cfee860698584c030f4c9db1"
.from_hex()
.unwrap()
.as_slice(),
),
state_root: H256::from(
"ef1552a40b7165c3cd773806b9e0c165b75356e0314bf0706f279c729f51e017"
.from_hex()
.unwrap()
.as_slice(),
),
receipts_root: H256::from(
"bc37d79753ad738a6dac4921e57392f145d8887476de3f783dfa7edae9283e52"
.from_hex()
.unwrap()
.as_slice(),
),
transactions_root: H256::from(
"5fe50b260da6308036625b850b5d6ced6d0a9f814c0688bc91ffb7b7a3a54b67"
.from_hex()
.unwrap()
.as_slice(),
),
log_bloom: Bloom::default(),
difficulty: U256::from(131072),
number: 1,
gas_used: U256::from(21000),
gas_limit: U256::from(3141592),
timestamp: 1426516743,
extra_data: vec![],
mix_digest: H256::from(
"bd4472abb6659ebe3ee06ee4d7b72a00a9f4d001caca51342001075469aff498"
.from_hex()
.unwrap()
.as_slice(),
),
nonce: nonce,
};
assert_eq!(header, expected_header);
}
}
|
use {
crate::{
client::{self, RequestType},
entities::*,
Client,
},
image::DynamicImage,
serde_json::json,
std::error::Error,
};
pub struct EnableMFA(Client);
impl EnableMFA {
/// Finishes the 2FA activation. This will invalidate your token and you need to re-authenticate
pub async fn finish(self, token: String) -> Result<(), Box<dyn Error>> {
let body = json!({
"token": token,
});
let encoded_body = match serde_json::to_vec(&body) {
Ok(val) => val,
Err(e) => return Err(e.into()),
};
match client::perform_request::<GeneralMessage>(
RequestType::Post(encoded_body),
"/users/@me/mfa".into(),
Some(&self.0),
)
.await
{
Ok((status, msg)) if status != 200 => Err(failure::err_msg(msg.message).into()),
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
}
/// Enables 2FA on the authenticated account
/// This function consumes the client object since you need to re-authenticate afterwards anyway
pub async fn enable_mfa(client: Client) -> Result<(DynamicImage, EnableMFA), Box<dyn Error>> {
match client::perform_request::<GeneralMessage>(
RequestType::Get,
"/users/@me/mfa".into(),
Some(&client),
)
.await
{
Ok((status, msg)) if status != 200 => Err(failure::err_msg(msg.message).into()),
Ok((_, msg)) => {
let decoded_image = base64::decode(&msg.otp_auth_url)?;
let image = image::load_from_memory(&decoded_image)?;
Ok((image, EnableMFA(client)))
}
Err(e) => Err(e),
}
}
/// Disables 2FA on the authenticated account
/// This function consumes the client object since you need to re-authenticate afterwards anyway
pub async fn disable_mfa(client: Client, token: String) -> Result<(), Box<dyn Error>> {
match client::perform_request::<GeneralMessage>(
RequestType::Delete,
format!("/users/@me/mfa?token={}", token),
Some(&client),
)
.await
{
Ok((status, val)) if status != 200 => Err(failure::err_msg(val.message).into()),
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
/// Gets the user object of the currently authenticated user
pub async fn get_me(client: &Client) -> Result<User, Box<dyn Error>> {
get(client, "@me".into()).await
}
/// Gets the roles of a specific user
pub async fn get_roles(client: &Client, username: String) -> Result<Vec<Role>, Box<dyn Error>> {
match client::perform_request::<GeneralMessage>(
RequestType::Get,
format!("/users/{}/roles", username),
Some(client),
)
.await
{
Ok((status, msg)) if status != 200 => Err(failure::err_msg(msg.message).into()),
Ok((_, msg)) => Ok(msg.roles),
Err(e) => Err(e),
}
}
/// Gets information about a specific user
pub async fn get(client: &Client, username: String) -> Result<User, Box<dyn Error>> {
match client::perform_request::<GeneralMessage>(
RequestType::Get,
format!("/users/{}", username),
Some(client),
)
.await
{
Ok((status, msg)) if status != 200 => Err(failure::err_msg(msg.message).into()),
Ok((_, msg)) => Ok(msg.user),
Err(e) => Err(e),
}
}
/// Updates the biography of the authenticated user
pub async fn update_bio(client: &Client, bio: String) -> Result<(), Box<dyn Error>> {
let body = json!({
"bio": bio,
});
let encoded_body = match serde_json::to_vec(&body) {
Ok(val) => val,
Err(e) => return Err(e.into()),
};
match client::perform_request::<GeneralMessage>(
RequestType::Patch(encoded_body),
"/users/@me".into(),
Some(client),
)
.await
{
Ok((status, msg)) if status != 204 => Err(failure::err_msg(msg.message).into()),
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
|
pub mod file_msg;
pub mod file_thread;
pub mod text;
|
use common::{rsip, tokio::time::Instant};
#[derive(Debug)]
pub struct Terminated {
//final response, if none it means that it timedout
pub response: Option<rsip::Response>,
pub entered_at: Instant,
}
|
#[doc = "Reader of register RCC_BDCR"]
pub type R = crate::R<u32, super::RCC_BDCR>;
#[doc = "Writer for register RCC_BDCR"]
pub type W = crate::W<u32, super::RCC_BDCR>;
#[doc = "Register RCC_BDCR `reset()`'s with value 0"]
impl crate::ResetValue for super::RCC_BDCR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "LSEON\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LSEON_A {
#[doc = "0: LSE oscillator OFF (default after\r\n backup domain reset)"]
B_0X0 = 0,
#[doc = "1: LSE oscillator ON"]
B_0X1 = 1,
}
impl From<LSEON_A> for bool {
#[inline(always)]
fn from(variant: LSEON_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `LSEON`"]
pub type LSEON_R = crate::R<bool, LSEON_A>;
impl LSEON_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LSEON_A {
match self.bits {
false => LSEON_A::B_0X0,
true => LSEON_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == LSEON_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == LSEON_A::B_0X1
}
}
#[doc = "Write proxy for field `LSEON`"]
pub struct LSEON_W<'a> {
w: &'a mut W,
}
impl<'a> LSEON_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LSEON_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "LSE oscillator OFF (default after backup domain reset)"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(LSEON_A::B_0X0)
}
#[doc = "LSE oscillator ON"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(LSEON_A::B_0X1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "LSEBYP\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LSEBYP_A {
#[doc = "0: LSE oscillator not bypassed (default\r\n after backup domain reset)"]
B_0X0 = 0,
#[doc = "1: LSE oscillator\r\n bypassed"]
B_0X1 = 1,
}
impl From<LSEBYP_A> for bool {
#[inline(always)]
fn from(variant: LSEBYP_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `LSEBYP`"]
pub type LSEBYP_R = crate::R<bool, LSEBYP_A>;
impl LSEBYP_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LSEBYP_A {
match self.bits {
false => LSEBYP_A::B_0X0,
true => LSEBYP_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == LSEBYP_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == LSEBYP_A::B_0X1
}
}
#[doc = "Write proxy for field `LSEBYP`"]
pub struct LSEBYP_W<'a> {
w: &'a mut W,
}
impl<'a> LSEBYP_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LSEBYP_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "LSE oscillator not bypassed (default after backup domain reset)"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(LSEBYP_A::B_0X0)
}
#[doc = "LSE oscillator bypassed"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(LSEBYP_A::B_0X1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "LSERDY\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LSERDY_A {
#[doc = "0: LSE oscillator not ready (default\r\n after backup domain reset)"]
B_0X0 = 0,
#[doc = "1: LSE oscillator ready"]
B_0X1 = 1,
}
impl From<LSERDY_A> for bool {
#[inline(always)]
fn from(variant: LSERDY_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `LSERDY`"]
pub type LSERDY_R = crate::R<bool, LSERDY_A>;
impl LSERDY_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LSERDY_A {
match self.bits {
false => LSERDY_A::B_0X0,
true => LSERDY_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == LSERDY_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == LSERDY_A::B_0X1
}
}
#[doc = "LSEDRV\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum LSEDRV_A {
#[doc = "0: Lowest drive (default after backup\r\n domain reset)"]
B_0X0 = 0,
#[doc = "1: Medium low drive"]
B_0X1 = 1,
#[doc = "2: Medium high drive"]
B_0X2 = 2,
#[doc = "3: Highest drive"]
B_0X3 = 3,
}
impl From<LSEDRV_A> for u8 {
#[inline(always)]
fn from(variant: LSEDRV_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `LSEDRV`"]
pub type LSEDRV_R = crate::R<u8, LSEDRV_A>;
impl LSEDRV_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LSEDRV_A {
match self.bits {
0 => LSEDRV_A::B_0X0,
1 => LSEDRV_A::B_0X1,
2 => LSEDRV_A::B_0X2,
3 => LSEDRV_A::B_0X3,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == LSEDRV_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == LSEDRV_A::B_0X1
}
#[doc = "Checks if the value of the field is `B_0X2`"]
#[inline(always)]
pub fn is_b_0x2(&self) -> bool {
*self == LSEDRV_A::B_0X2
}
#[doc = "Checks if the value of the field is `B_0X3`"]
#[inline(always)]
pub fn is_b_0x3(&self) -> bool {
*self == LSEDRV_A::B_0X3
}
}
#[doc = "Write proxy for field `LSEDRV`"]
pub struct LSEDRV_W<'a> {
w: &'a mut W,
}
impl<'a> LSEDRV_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LSEDRV_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "Lowest drive (default after backup domain reset)"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(LSEDRV_A::B_0X0)
}
#[doc = "Medium low drive"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(LSEDRV_A::B_0X1)
}
#[doc = "Medium high drive"]
#[inline(always)]
pub fn b_0x2(self) -> &'a mut W {
self.variant(LSEDRV_A::B_0X2)
}
#[doc = "Highest drive"]
#[inline(always)]
pub fn b_0x3(self) -> &'a mut W {
self.variant(LSEDRV_A::B_0X3)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 4)) | (((value as u32) & 0x03) << 4);
self.w
}
}
#[doc = "LSECSSON\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LSECSSON_A {
#[doc = "0: Clock Security System on 32 kHz\r\n oscillator OFF (default after backup domain\r\n reset)"]
B_0X0 = 0,
#[doc = "1: Clock Security System on 32 kHz\r\n oscillator ON"]
B_0X1 = 1,
}
impl From<LSECSSON_A> for bool {
#[inline(always)]
fn from(variant: LSECSSON_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `LSECSSON`"]
pub type LSECSSON_R = crate::R<bool, LSECSSON_A>;
impl LSECSSON_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LSECSSON_A {
match self.bits {
false => LSECSSON_A::B_0X0,
true => LSECSSON_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == LSECSSON_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == LSECSSON_A::B_0X1
}
}
#[doc = "Write proxy for field `LSECSSON`"]
pub struct LSECSSON_W<'a> {
w: &'a mut W,
}
impl<'a> LSECSSON_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LSECSSON_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clock Security System on 32 kHz oscillator OFF (default after backup domain reset)"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(LSECSSON_A::B_0X0)
}
#[doc = "Clock Security System on 32 kHz oscillator ON"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(LSECSSON_A::B_0X1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "LSECSSD\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LSECSSD_A {
#[doc = "0: No failure detected on 32 kHz\r\n oscillator (default after backup domain\r\n reset)"]
B_0X0 = 0,
#[doc = "1: Failure detected on 32 kHz\r\n oscillator"]
B_0X1 = 1,
}
impl From<LSECSSD_A> for bool {
#[inline(always)]
fn from(variant: LSECSSD_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `LSECSSD`"]
pub type LSECSSD_R = crate::R<bool, LSECSSD_A>;
impl LSECSSD_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LSECSSD_A {
match self.bits {
false => LSECSSD_A::B_0X0,
true => LSECSSD_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == LSECSSD_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == LSECSSD_A::B_0X1
}
}
#[doc = "RTCSRC\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum RTCSRC_A {
#[doc = "0: No clock (default after backup\r\n domain reset)"]
B_0X0 = 0,
#[doc = "1: LSE clock used as RTC\r\n clock"]
B_0X1 = 1,
#[doc = "2: LSI clock used as RTC\r\n clock"]
B_0X2 = 2,
#[doc = "3: HSE clock divided by RTCDIV value is\r\n used as RTC clock"]
B_0X3 = 3,
}
impl From<RTCSRC_A> for u8 {
#[inline(always)]
fn from(variant: RTCSRC_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `RTCSRC`"]
pub type RTCSRC_R = crate::R<u8, RTCSRC_A>;
impl RTCSRC_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RTCSRC_A {
match self.bits {
0 => RTCSRC_A::B_0X0,
1 => RTCSRC_A::B_0X1,
2 => RTCSRC_A::B_0X2,
3 => RTCSRC_A::B_0X3,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == RTCSRC_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == RTCSRC_A::B_0X1
}
#[doc = "Checks if the value of the field is `B_0X2`"]
#[inline(always)]
pub fn is_b_0x2(&self) -> bool {
*self == RTCSRC_A::B_0X2
}
#[doc = "Checks if the value of the field is `B_0X3`"]
#[inline(always)]
pub fn is_b_0x3(&self) -> bool {
*self == RTCSRC_A::B_0X3
}
}
#[doc = "Write proxy for field `RTCSRC`"]
pub struct RTCSRC_W<'a> {
w: &'a mut W,
}
impl<'a> RTCSRC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RTCSRC_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "No clock (default after backup domain reset)"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(RTCSRC_A::B_0X0)
}
#[doc = "LSE clock used as RTC clock"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(RTCSRC_A::B_0X1)
}
#[doc = "LSI clock used as RTC clock"]
#[inline(always)]
pub fn b_0x2(self) -> &'a mut W {
self.variant(RTCSRC_A::B_0X2)
}
#[doc = "HSE clock divided by RTCDIV value is used as RTC clock"]
#[inline(always)]
pub fn b_0x3(self) -> &'a mut W {
self.variant(RTCSRC_A::B_0X3)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 16)) | (((value as u32) & 0x03) << 16);
self.w
}
}
#[doc = "RTCCKEN\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RTCCKEN_A {
#[doc = "0: rtc_ck clock is disabled (default\r\n after backup domain reset)"]
B_0X0 = 0,
#[doc = "1: rtc_ck clock enabled"]
B_0X1 = 1,
}
impl From<RTCCKEN_A> for bool {
#[inline(always)]
fn from(variant: RTCCKEN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `RTCCKEN`"]
pub type RTCCKEN_R = crate::R<bool, RTCCKEN_A>;
impl RTCCKEN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RTCCKEN_A {
match self.bits {
false => RTCCKEN_A::B_0X0,
true => RTCCKEN_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == RTCCKEN_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == RTCCKEN_A::B_0X1
}
}
#[doc = "Write proxy for field `RTCCKEN`"]
pub struct RTCCKEN_W<'a> {
w: &'a mut W,
}
impl<'a> RTCCKEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RTCCKEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "rtc_ck clock is disabled (default after backup domain reset)"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(RTCCKEN_A::B_0X0)
}
#[doc = "rtc_ck clock enabled"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(RTCCKEN_A::B_0X1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "VSWRST\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VSWRST_A {
#[doc = "0: Reset not activated (default after\r\n backup domain reset)"]
B_0X0 = 0,
#[doc = "1: Resets the entire VSW\r\n domain"]
B_0X1 = 1,
}
impl From<VSWRST_A> for bool {
#[inline(always)]
fn from(variant: VSWRST_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `VSWRST`"]
pub type VSWRST_R = crate::R<bool, VSWRST_A>;
impl VSWRST_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> VSWRST_A {
match self.bits {
false => VSWRST_A::B_0X0,
true => VSWRST_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == VSWRST_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == VSWRST_A::B_0X1
}
}
#[doc = "Write proxy for field `VSWRST`"]
pub struct VSWRST_W<'a> {
w: &'a mut W,
}
impl<'a> VSWRST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: VSWRST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Reset not activated (default after backup domain reset)"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(VSWRST_A::B_0X0)
}
#[doc = "Resets the entire VSW domain"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(VSWRST_A::B_0X1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bit 0 - LSEON"]
#[inline(always)]
pub fn lseon(&self) -> LSEON_R {
LSEON_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - LSEBYP"]
#[inline(always)]
pub fn lsebyp(&self) -> LSEBYP_R {
LSEBYP_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - LSERDY"]
#[inline(always)]
pub fn lserdy(&self) -> LSERDY_R {
LSERDY_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bits 4:5 - LSEDRV"]
#[inline(always)]
pub fn lsedrv(&self) -> LSEDRV_R {
LSEDRV_R::new(((self.bits >> 4) & 0x03) as u8)
}
#[doc = "Bit 8 - LSECSSON"]
#[inline(always)]
pub fn lsecsson(&self) -> LSECSSON_R {
LSECSSON_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - LSECSSD"]
#[inline(always)]
pub fn lsecssd(&self) -> LSECSSD_R {
LSECSSD_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bits 16:17 - RTCSRC"]
#[inline(always)]
pub fn rtcsrc(&self) -> RTCSRC_R {
RTCSRC_R::new(((self.bits >> 16) & 0x03) as u8)
}
#[doc = "Bit 20 - RTCCKEN"]
#[inline(always)]
pub fn rtccken(&self) -> RTCCKEN_R {
RTCCKEN_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 31 - VSWRST"]
#[inline(always)]
pub fn vswrst(&self) -> VSWRST_R {
VSWRST_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - LSEON"]
#[inline(always)]
pub fn lseon(&mut self) -> LSEON_W {
LSEON_W { w: self }
}
#[doc = "Bit 1 - LSEBYP"]
#[inline(always)]
pub fn lsebyp(&mut self) -> LSEBYP_W {
LSEBYP_W { w: self }
}
#[doc = "Bits 4:5 - LSEDRV"]
#[inline(always)]
pub fn lsedrv(&mut self) -> LSEDRV_W {
LSEDRV_W { w: self }
}
#[doc = "Bit 8 - LSECSSON"]
#[inline(always)]
pub fn lsecsson(&mut self) -> LSECSSON_W {
LSECSSON_W { w: self }
}
#[doc = "Bits 16:17 - RTCSRC"]
#[inline(always)]
pub fn rtcsrc(&mut self) -> RTCSRC_W {
RTCSRC_W { w: self }
}
#[doc = "Bit 20 - RTCCKEN"]
#[inline(always)]
pub fn rtccken(&mut self) -> RTCCKEN_W {
RTCCKEN_W { w: self }
}
#[doc = "Bit 31 - VSWRST"]
#[inline(always)]
pub fn vswrst(&mut self) -> VSWRST_W {
VSWRST_W { w: self }
}
}
|
use std::io;
use std::io::{Read, Write};
use std::string::String;
#[no_mangle]
pub fn add_emoji() {
let pattern = ":-)";
let mut input_vec: Vec<u8> = Vec::new();
// read vector and convert it to a string
io::stdin()
.read_to_end(&mut input_vec)
.expect("Unable to read input");
let mut input = String::from_utf8(input_vec).expect("Unable to convert input to a string");
// replace :-) by 😀
while let Some(idx) = input.find(pattern) {
input.replace_range(idx..idx + pattern.len(), "😀");
}
print!("{}", input);
io::stdout().flush().unwrap();
}
|
use {
http::{Method, Request},
juniper::{http::tests as http_tests, tests::model::Database, EmptyMutation, RootNode},
percent_encoding::{define_encode_set, utf8_percent_encode, QUERY_ENCODE_SET},
std::{cell::RefCell, sync::Arc},
tsukuyomi::{
endpoint,
test::{self, TestResponse, TestServer},
App,
},
tsukuyomi_juniper::GraphQLRequest,
};
#[test]
fn test_version_sync() {
version_sync::assert_html_root_url_updated!("src/lib.rs");
}
#[test]
fn integration_test() -> test::Result {
let database = Arc::new(Database::new());
let schema = Arc::new(RootNode::new(
Database::new(),
EmptyMutation::<Database>::new(),
));
let app = App::build(|mut s| {
let database = database.clone();
s.at("/")?
.route(&[Method::GET, Method::POST])
.with(tsukuyomi_juniper::capture_errors())
.extract(tsukuyomi_juniper::request())
.extract(tsukuyomi::extractor::value(schema))
.to(endpoint::call(
move |request: GraphQLRequest, schema: Arc<_>| {
let database = database.clone();
request.execute(schema, database)
},
))
})?;
let test_server = TestServer::new(app)?;
let integration = TestTsukuyomiIntegration {
local_server: RefCell::new(test_server),
};
http_tests::run_http_test_suite(&integration);
Ok(())
}
struct TestTsukuyomiIntegration {
local_server: RefCell<TestServer>,
}
impl http_tests::HTTPIntegration for TestTsukuyomiIntegration {
fn get(&self, url: &str) -> http_tests::TestResponse {
let mut server = self.local_server.borrow_mut();
let mut client = server.connect();
let response = client.request(Request::get(custom_url_encode(url)).body("").unwrap());
make_test_response(response)
}
fn post(&self, url: &str, body: &str) -> http_tests::TestResponse {
let mut server = self.local_server.borrow_mut();
let mut client = server.connect();
let response = client.request(
Request::post(custom_url_encode(url))
.header("content-type", "application/json")
.body(body.as_bytes())
.unwrap(),
);
make_test_response(response)
}
}
fn custom_url_encode(url: &str) -> String {
define_encode_set! {
pub CUSTOM_ENCODE_SET = [QUERY_ENCODE_SET] | {'{', '}'}
}
utf8_percent_encode(url, CUSTOM_ENCODE_SET).to_string()
}
#[allow(clippy::cast_lossless)]
fn make_test_response(response: TestResponse<'_>) -> http_tests::TestResponse {
let status_code = response.status().as_u16() as i32;
let content_type = response
.headers()
.get("content-type")
.expect("missing Content-type")
.to_str()
.expect("Content-type should be a valid UTF-8 string")
.to_owned();
let body = String::from_utf8(response.into_bytes().unwrap())
.expect("The response body should be a valid UTF-8 string");
http_tests::TestResponse {
status_code,
content_type,
body: Some(body),
}
}
|
extern crate gcc;
fn main() {
let mut config = gcc::Config::new();
config.include("breakpad");
config.include("breakpad/common");
config.include("breakpad/google_breakpad");
config.include("breakpad/common/linux");
if cfg!(target_os = "windows") {
config.define("OS_WINDOWS", Some("1"));
}
/*if cfg!(windows) {
config.file("breakpad/common/windows/dia_util.cc");
config.file("breakpad/common/windows/guid_string.cc");
config.file("breakpad/common/windows/omap.cc");
config.file("breakpad/common/windows/pdb_source_line_writer.cc");
config.file("breakpad/common/windows/string_utils.cc");
}*/
if !cfg!(target_env = "msvc") {
config.flag("-std=c++11");
} else {
config.flag("-EHsc");
config.define("_LIBCXXABI_DISABLE_DLL_IMPORT_EXPORT", Some("1"));
}
config.file("breakpad/api.cc");
config.file("breakpad/common/dwarf/bytereader.cc");
config.file("breakpad/common/dwarf/dwarf2diehandler.cc");
config.file("breakpad/common/dwarf/dwarf2reader.cc");
//config.file("breakpad/common/dwarf/dwarf_cfi_to_module.cc");
//config.file("breakpad/common/dwarf/dwarf_cu_to_module.cc");
//config.file("breakpad/common/dwarf/dwarf_line_to_module.cc");
config.file("breakpad/common/language.cc");
config.file("breakpad/common/linux/crc32.cc");
config.file("breakpad/common/linux/cxa_demangle.cc");
config.file("breakpad/common/linux/dump_symbols.cc");
config.file("breakpad/common/linux/elfutils.cc");
config.file("breakpad/common/linux/elf_symbols_to_module.cc");
config.file("breakpad/common/linux/file_id.cc");
config.file("breakpad/common/linux/linux_libc_support.cc");
config.file("breakpad/common/linux/memory_mapped_file.cc");
config.file("breakpad/common/module.cc");
config.file("breakpad/common/stabs_reader.cc");
config.file("breakpad/common/stabs_to_module.cc");
config.file("breakpad/common/windows/pdb_parser.cc");
config.file("breakpad/common/windows/utils.cc");
config.file("breakpad/processor/basic_code_modules.cc");
config.file("breakpad/processor/basic_source_line_resolver.cc");
config.file("breakpad/processor/cfi_frame_info.cc");
config.file("breakpad/processor/logging.cc");
config.file("breakpad/processor/module_serializer.cc");
config.file("breakpad/processor/pathname_stripper.cc");
config.file("breakpad/processor/source_line_resolver_base.cc");
config.file("breakpad/processor/tokenize.cc");
config.cpp(true);
config.compile("libbreakpad.a");
}
|
#[doc = "Register `AHBRSTR` reader"]
pub type R = crate::R<AHBRSTR_SPEC>;
#[doc = "Register `AHBRSTR` writer"]
pub type W = crate::W<AHBRSTR_SPEC>;
#[doc = "Field `DMARST` reader - DMA reset"]
pub type DMARST_R = crate::BitReader<DMARSTW_A>;
#[doc = "DMA reset\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DMARSTW_A {
#[doc = "1: Reset the module"]
Reset = 1,
}
impl From<DMARSTW_A> for bool {
#[inline(always)]
fn from(variant: DMARSTW_A) -> Self {
variant as u8 != 0
}
}
impl DMARST_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<DMARSTW_A> {
match self.bits {
true => Some(DMARSTW_A::Reset),
_ => None,
}
}
#[doc = "Reset the module"]
#[inline(always)]
pub fn is_reset(&self) -> bool {
*self == DMARSTW_A::Reset
}
}
#[doc = "Field `DMARST` writer - DMA reset"]
pub type DMARST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DMARSTW_A>;
impl<'a, REG, const O: u8> DMARST_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Reset the module"]
#[inline(always)]
pub fn reset(self) -> &'a mut crate::W<REG> {
self.variant(DMARSTW_A::Reset)
}
}
#[doc = "Field `MIFRST` reader - Memory interface reset"]
pub use DMARST_R as MIFRST_R;
#[doc = "Field `CRCRST` reader - Test integration module reset"]
pub use DMARST_R as CRCRST_R;
#[doc = "Field `TOUCHRST` reader - Touch Sensing reset"]
pub use DMARST_R as TOUCHRST_R;
#[doc = "Field `RNGRST` reader - Random Number Generator module reset"]
pub use DMARST_R as RNGRST_R;
#[doc = "Field `CRYPRST` reader - Crypto module reset"]
pub use DMARST_R as CRYPRST_R;
#[doc = "Field `MIFRST` writer - Memory interface reset"]
pub use DMARST_W as MIFRST_W;
#[doc = "Field `CRCRST` writer - Test integration module reset"]
pub use DMARST_W as CRCRST_W;
#[doc = "Field `TOUCHRST` writer - Touch Sensing reset"]
pub use DMARST_W as TOUCHRST_W;
#[doc = "Field `RNGRST` writer - Random Number Generator module reset"]
pub use DMARST_W as RNGRST_W;
#[doc = "Field `CRYPRST` writer - Crypto module reset"]
pub use DMARST_W as CRYPRST_W;
impl R {
#[doc = "Bit 0 - DMA reset"]
#[inline(always)]
pub fn dmarst(&self) -> DMARST_R {
DMARST_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 8 - Memory interface reset"]
#[inline(always)]
pub fn mifrst(&self) -> MIFRST_R {
MIFRST_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 12 - Test integration module reset"]
#[inline(always)]
pub fn crcrst(&self) -> CRCRST_R {
CRCRST_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 16 - Touch Sensing reset"]
#[inline(always)]
pub fn touchrst(&self) -> TOUCHRST_R {
TOUCHRST_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 20 - Random Number Generator module reset"]
#[inline(always)]
pub fn rngrst(&self) -> RNGRST_R {
RNGRST_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 24 - Crypto module reset"]
#[inline(always)]
pub fn cryprst(&self) -> CRYPRST_R {
CRYPRST_R::new(((self.bits >> 24) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - DMA reset"]
#[inline(always)]
#[must_use]
pub fn dmarst(&mut self) -> DMARST_W<AHBRSTR_SPEC, 0> {
DMARST_W::new(self)
}
#[doc = "Bit 8 - Memory interface reset"]
#[inline(always)]
#[must_use]
pub fn mifrst(&mut self) -> MIFRST_W<AHBRSTR_SPEC, 8> {
MIFRST_W::new(self)
}
#[doc = "Bit 12 - Test integration module reset"]
#[inline(always)]
#[must_use]
pub fn crcrst(&mut self) -> CRCRST_W<AHBRSTR_SPEC, 12> {
CRCRST_W::new(self)
}
#[doc = "Bit 16 - Touch Sensing reset"]
#[inline(always)]
#[must_use]
pub fn touchrst(&mut self) -> TOUCHRST_W<AHBRSTR_SPEC, 16> {
TOUCHRST_W::new(self)
}
#[doc = "Bit 20 - Random Number Generator module reset"]
#[inline(always)]
#[must_use]
pub fn rngrst(&mut self) -> RNGRST_W<AHBRSTR_SPEC, 20> {
RNGRST_W::new(self)
}
#[doc = "Bit 24 - Crypto module reset"]
#[inline(always)]
#[must_use]
pub fn cryprst(&mut self) -> CRYPRST_W<AHBRSTR_SPEC, 24> {
CRYPRST_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 = "AHB peripheral reset register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahbrstr::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 [`ahbrstr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct AHBRSTR_SPEC;
impl crate::RegisterSpec for AHBRSTR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ahbrstr::R`](R) reader structure"]
impl crate::Readable for AHBRSTR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ahbrstr::W`](W) writer structure"]
impl crate::Writable for AHBRSTR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets AHBRSTR to value 0"]
impl crate::Resettable for AHBRSTR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[doc = "Register `LCCCR` reader"]
pub type R = crate::R<LCCCR_SPEC>;
#[doc = "Field `COLC` reader - Color Coding"]
pub type COLC_R = crate::FieldReader;
#[doc = "Field `LPE` reader - Loosely Packed Enable"]
pub type LPE_R = crate::BitReader;
impl R {
#[doc = "Bits 0:3 - Color Coding"]
#[inline(always)]
pub fn colc(&self) -> COLC_R {
COLC_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bit 8 - Loosely Packed Enable"]
#[inline(always)]
pub fn lpe(&self) -> LPE_R {
LPE_R::new(((self.bits >> 8) & 1) != 0)
}
}
#[doc = "DSI Host LTDC Current Color Coding Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`lcccr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct LCCCR_SPEC;
impl crate::RegisterSpec for LCCCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`lcccr::R`](R) reader structure"]
impl crate::Readable for LCCCR_SPEC {}
#[doc = "`reset()` method sets LCCCR to value 0"]
impl crate::Resettable for LCCCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::model::{Post, User};
use crate::repository::PostsRepository;
use chrono::{DateTime, Utc};
pub struct PostsService {}
impl PostsService {
pub fn get_all() -> Vec<Post> {
PostsRepository::get_all().unwrap()
}
pub fn get_page(page_number: usize, posts_per_page: usize) -> Vec<Post> {
let all_posts = PostsRepository::get_all().unwrap();
let mut pages = all_posts.chunks(posts_per_page);
let page = pages.nth(page_number);
if let None = page {
return vec![];
}
page.unwrap().into()
}
pub fn add_post(title: String, content: String, author: User) -> Post {
let now: DateTime<Utc> = Utc::now();
let now = now.format("%F %R");
println!("UTC now is: {}", now);
let post = Post {
id: PostsService::get_all().len() as i32,
date: now.to_string(),
title,
author,
content,
};
PostsRepository::add_post(&post).unwrap();
post
}
}
|
#![cfg_attr(feature="serde-serialize", feature(proc_macro))]
extern crate chrono;
extern crate regex;
extern crate reqwest;
#[cfg(feature="serde-serialize")]
#[macro_use] extern crate serde_derive;
extern crate xml;
#[macro_use]
mod decoder;
pub mod api;
pub mod diff;
pub mod gradebook;
|
use anyhow::{anyhow, Result};
use proger_backend::{DynamoDbDriver, Server};
use proger_core::{
protocol::{
request::{DeleteStepPage, CreateStepPage, UpdateStepPage},
response::{PageAccess, StepPageProgress},
},
API_URL_V1_CREATE_STEP_PAGE, API_URL_V1_READ_STEP_PAGE, API_URL_V1_UPDATE_STEP_PAGE, API_URL_V1_DELETE_PAGE,
};
use reqwest::blocking::Client;
use rusoto_core::Region;
use rusoto_dynamodb::DynamoDbClient;
use std::thread;
use std::time::Duration;
use url::Url;
pub fn create_testserver(storage: DynamoDbDriver) -> Result<Url> {
// Set the test configuration
let host = "localhost:8080".to_string();
// url.set_port(Some(get_next_port()))
// .map_err(|_| format_err!("Unable to set server port"))?;
// Start the server
let host_clone = host.clone();
thread::spawn(move || Server::new(host_clone, storage).unwrap().start().unwrap());
// Wait until the server is up
let url = Url::parse(&format!("http://{}", &host))?;
for _ in 0..5 {
let check = Client::new().get(url.as_str()).send();
println!("check result {:?}", check);
if let Ok(res) = check {
if res.status().is_success() {
return Ok(url);
}
}
thread::sleep(Duration::from_millis(10));
}
// Return the server url
Err(anyhow!("failed to start server"))
}
#[test]
fn test_flow_with_dynamodb() {
let db_driver = DynamoDbDriver(DynamoDbClient::new(Region::EuCentral1));
let url = create_testserver(db_driver).unwrap();
// Create
let create_request = CreateStepPage {
steps: 20,
};
let mut create_url = url.clone();
create_url.set_path(API_URL_V1_CREATE_STEP_PAGE);
println!("new page URL: {:?}", create_url);
let result = create_new_page_with_dynamodb(create_url, create_request);
println!("RESULT: {:?}", result);
let page_acess: PageAccess = result.json().unwrap();
println!("PageAccess: {:?}", page_acess);
// Update
let update_request = UpdateStepPage {
step_completed: 7,
admin_secret: page_acess.admin_secret.clone(),
};
let mut update_url = url.clone();
update_url.set_path(&API_URL_V1_UPDATE_STEP_PAGE.replace("{id}", &page_acess.link));
println!("update page URL: {:?}", update_url);
let result = update_page_with_dynamodb(update_url, update_request);
println!("RESULT: {:?}", result);
// Read
let mut read_url = url.clone();
read_url.set_path(&API_URL_V1_READ_STEP_PAGE.replace("{id}", &page_acess.link));
println!("view page URL: {:?}", read_url);
let result = view_page_with_dynamodb(read_url);
println!("RESULT: {:?}", result);
let progress: StepPageProgress = result.json().unwrap();
println!("Progress: {:?}", progress);
assert_eq!(progress.steps, 20);
assert_eq!(progress.completed, 7);
// Delete
let delete_request = DeleteStepPage {
admin_secret: page_acess.admin_secret.clone(),
};
let mut delete_url = url.clone();
delete_url.set_path(&API_URL_V1_DELETE_PAGE.replace("{id}", &page_acess.link));
println!("delete page URL: {:?}", delete_request);
let result = delete_page_with_dynamodb(delete_url, delete_request);
println!("RESULT: {:?}", result);
}
fn create_new_page_with_dynamodb(url: Url, request: CreateStepPage) -> reqwest::blocking::Response {
let res = Client::new()
.post(url.as_str())
.json(&request)
.send()
.unwrap();
assert_eq!(res.status().as_u16(), 200);
res
}
fn update_page_with_dynamodb(url: Url, request: UpdateStepPage) -> reqwest::blocking::Response {
let res = Client::new()
.put(url.as_str())
.json(&request)
.send()
.unwrap();
assert_eq!(res.status().as_u16(), 200);
res
}
fn view_page_with_dynamodb(url: Url) -> reqwest::blocking::Response {
let res = Client::new().get(url.as_str()).send().unwrap();
assert_eq!(res.status().as_u16(), 200);
res
}
fn delete_page_with_dynamodb(url: Url, request: DeleteStepPage) -> reqwest::blocking::Response {
let res = Client::new()
.delete(url.as_str())
.json(&request)
.send()
.unwrap();
assert_eq!(res.status().as_u16(), 200);
res
}
|
use crate::Event;
use async_channel::{Receiver, Sender};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use std::{fs, io};
//events in the background that the thread will respond to
pub enum BgEvent {
//save task to a file
Save(PathBuf, String),
//Exit from the program loop
Quit,
}
pub async fn run(tx: Sender<Event>, rx: Receiver<BgEvent>) {
let xdg_dirs = xdg::BaseDirectories::with_prefix(crate::APP_ID).unwrap();
let data_home = xdg_dirs.get_data_home();
let _ = fs::create_dir_all(&data_home);
if let Some(path) = most_recent_file(&data_home).unwrap() {
if let Ok(data) = fs::read_to_string(&path) {
let _ = tx.send(Event::Load(data)).await;
}
}
while let Ok(event) = rx.recv().await {
match event {
BgEvent::Save(path, data) => {
let path = xdg_dirs.place_data_file(path).unwrap();
fs::write(&path, data.as_bytes()).unwrap();
}
BgEvent::Quit => break,
}
}
let _ = tx.send(Event::Quit).await;
}
fn most_recent_file(path: &Path) -> io::Result<Option<PathBuf>> {
let mut most_recent = SystemTime::UNIX_EPOCH;
let mut target = None;
for entry in fs::read_dir(path)? {
let entry = entry?;
if entry.file_type().map_or(false, |kind| kind.is_file()) {
if let Ok(modified) = entry.metadata().and_then(|m| m.modified()) {
if modified > most_recent {
target = Some(entry.path());
most_recent = modified;
}
}
}
}
Ok(target)
}
|
pub fn iterator_simple_test() {
println!(
"{}",
"------------iterator_demo_test start-------------------"
);
let v1 = vec![1, 2, 3];
//通过调用定义于 Vec 上的 iter 方法在一个 vector v1 上创建了一个迭代器
let v1_iter = v1.iter();
for val in v1_iter {
println!("Got: {}", val);
}
let mut v2 = vec![1, 2, 3];
{
let mut v2_iter = v2.iter_mut(); //into_iter seems like move
// let mut v2_iter = v2.into_iter(); //iter_mut seems like &mut
match v2_iter.next() {
Some(v) => {
println!("{}", v);
}
None => panic!(),
};
}
println!("{}", v2.get(0).unwrap());
println!("v2 length is {}", v2.len());
let v3 = vec![1, 2, 3];
{
let mut v3_iter = v3.into_iter(); //into_iter seems like move
// let mut v2_iter = v2.into_iter(); //iter_mut seems like &mut
match v3_iter.next() {
Some(v) => {
println!("{}", v);
}
None => panic!(),
};
}
//This will cause error because
/*
let mut v3_iter = v3.into_iter;
value used here after move
*/
//println!("{}",v3.get(0).unwrap());
//println!("v3 length is {}",v3.len());
}
|
//! High-level resolver operations
use std::cell::Cell;
use std::io;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs};
use std::time::{Duration, Instant};
use std::vec::IntoIter;
use log::info;
use crate::address::address_name;
use crate::config::DnsConfig;
use crate::message::{Message, Qr, Question, MESSAGE_LIMIT};
use crate::record::{Class, Ptr, Record, RecordType, A, AAAA};
use crate::socket::{DnsSocket, Error};
/// Performs resolution operations
pub struct DnsResolver {
sock: DnsSocket,
config: DnsConfig,
/// Index of `config.name_servers` to use in next DNS request;
/// ignored if `config.rotate` is `false`.
next_ns: Cell<usize>,
}
impl DnsResolver {
/// Constructs a `DnsResolver` using the given configuration.
pub fn new(config: DnsConfig) -> io::Result<DnsResolver> {
let bind = bind_addr(&config.name_servers);
let sock = DnsSocket::bind((bind, 0))?;
DnsResolver::with_sock(sock, config)
}
/// Constructs a `DnsResolver` using the given configuration and bound
/// to the given address.
pub fn bind<A: ToSocketAddrs>(addr: A, config: DnsConfig) -> io::Result<DnsResolver> {
let sock = DnsSocket::bind(addr)?;
DnsResolver::with_sock(sock, config)
}
fn with_sock(sock: DnsSocket, config: DnsConfig) -> io::Result<DnsResolver> {
Ok(DnsResolver {
sock,
config,
next_ns: Cell::new(0),
})
}
/// Resolves an IPv4 or IPv6 address to a hostname.
pub fn resolve_addr(&self, addr: &IpAddr) -> io::Result<String> {
convert_error("failed to resolve address", || {
let mut out_msg = self.basic_message();
out_msg.question.push(Question::new(
address_name(addr),
RecordType::Ptr,
Class::Internet,
));
let mut buf = [0; MESSAGE_LIMIT];
let msg = self.send_message(&out_msg, &mut buf)?;
for rr in msg.answer.into_iter() {
if rr.r_type == RecordType::Ptr {
let ptr = rr.read_rdata::<Ptr>()?;
let mut name = ptr.name;
if name.ends_with('.') {
name.pop();
}
return Ok(name);
}
}
Err(Error::IoError(io::Error::new(
io::ErrorKind::Other,
"failed to resolve address: name not found",
)))
})
}
/// Resolves a hostname to a series of IPv4 or IPv6 addresses.
pub fn resolve_host(&self, host: &str) -> io::Result<ResolveHost> {
convert_error("failed to resolve host", || {
query_names(host, &self.config, |name| {
let mut err;
let mut res = Vec::new();
info!("attempting lookup of name \"{}\"", name);
if self.config.use_inet6 {
err = self
.resolve_host_v6(&name, |ip| res.push(IpAddr::V6(ip)))
.err();
if res.is_empty() {
err = err.or_else(|| {
self.resolve_host_v4(&name, |ip| {
res.push(IpAddr::V6(ip.to_ipv6_mapped()))
})
.err()
});
}
} else {
err = self
.resolve_host_v4(&name, |ip| res.push(IpAddr::V4(ip)))
.err();
err = err.or_else(|| {
self.resolve_host_v6(&name, |ip| res.push(IpAddr::V6(ip)))
.err()
});
}
if !res.is_empty() {
return Ok(ResolveHost(res.into_iter()));
}
if let Some(e) = err {
Err(e)
} else {
Err(Error::IoError(io::Error::new(
io::ErrorKind::Other,
"failed to resolve host: name not found",
)))
}
})
})
}
/// Requests a type of record from the DNS server and returns the results.
pub fn resolve_record<Rec: Record>(&self, name: &str) -> io::Result<Vec<Rec>> {
convert_error("failed to resolve record", || {
let r_ty = Rec::record_type();
let mut msg = self.basic_message();
msg.question
.push(Question::new(name.to_owned(), r_ty, Class::Internet));
let mut buf = [0; MESSAGE_LIMIT];
let reply = self.send_message(&msg, &mut buf)?;
let mut rec = Vec::new();
for rr in reply.answer.into_iter() {
if rr.r_type == r_ty {
rec.push(rr.read_rdata::<Rec>()?);
}
}
Ok(rec)
})
}
fn resolve_host_v4<F>(&self, host: &str, mut f: F) -> Result<(), Error>
where
F: FnMut(Ipv4Addr),
{
let mut out_msg = self.basic_message();
out_msg.question.push(Question::new(
host.to_owned(),
RecordType::A,
Class::Internet,
));
let mut buf = [0; MESSAGE_LIMIT];
let msg = self.send_message(&out_msg, &mut buf)?;
for rr in msg.answer.into_iter() {
if rr.r_type == RecordType::A {
let a = rr.read_rdata::<A>()?;
f(a.address);
}
}
Ok(())
}
fn resolve_host_v6<F>(&self, host: &str, mut f: F) -> Result<(), Error>
where
F: FnMut(Ipv6Addr),
{
let mut out_msg = self.basic_message();
out_msg.question.push(Question::new(
host.to_owned(),
RecordType::AAAA,
Class::Internet,
));
let mut buf = [0; MESSAGE_LIMIT];
let msg = self.send_message(&out_msg, &mut buf)?;
for rr in msg.answer.into_iter() {
if rr.r_type == RecordType::AAAA {
let aaaa = rr.read_rdata::<AAAA>()?;
f(aaaa.address);
}
}
Ok(())
}
fn basic_message(&self) -> Message {
let mut msg = Message::new();
msg.header.recursion_desired = true;
msg
}
/// Sends a message to the DNS server and attempts to read a response.
pub fn send_message<'buf>(
&self,
out_msg: &Message,
buf: &'buf mut [u8],
) -> Result<Message<'buf>, Error> {
let mut last_err = None;
// FIXME(rust-lang/rust#21906):
// Workaround for mutable borrow interfering with itself.
// The drop probably isn't necessary, but it makes me feel better.
let buf_ptr = buf as *mut _;
drop(buf);
'retry: for retries in 0..self.config.attempts {
let ns_addr = if self.config.rotate {
self.next_nameserver()
} else {
let n = self.config.name_servers.len();
self.config.name_servers[retries as usize % n]
};
let mut timeout = self.config.timeout;
info!("resolver sending message to {}", ns_addr);
self.sock.send_message(out_msg, &ns_addr)?;
loop {
self.sock.get().set_read_timeout(Some(timeout))?;
// The other part of the aforementioned workaround.
let buf = unsafe { &mut *buf_ptr };
let start = Instant::now();
match self.sock.recv_message(&ns_addr, buf) {
Ok(None) => {
let passed = start.elapsed();
// Maintain the right total timeout if we're interrupted
// by irrelevant messages.
if timeout < passed {
timeout = Duration::from_secs(0);
} else {
timeout -= passed;
}
}
Ok(Some(msg)) => {
// Ignore irrelevant messages
if msg.header.id == out_msg.header.id && msg.header.qr == Qr::Response {
msg.get_error()?;
return Ok(msg);
}
}
Err(e) => {
// Retry on timeout
if e.is_timeout() {
last_err = Some(e);
continue 'retry;
}
// Immediately bail for other errors
return Err(e);
}
}
}
}
Err(last_err.unwrap())
}
fn next_nameserver(&self) -> SocketAddr {
let n = self.next_ns.get();
self.next_ns.set((n + 1) % self.config.name_servers.len());
self.config.name_servers[n]
}
}
fn bind_addr(name_servers: &[SocketAddr]) -> IpAddr {
match name_servers.first() {
Some(&SocketAddr::V6(_)) => IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)),
_ => IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)),
}
}
fn convert_error<T, F>(desc: &str, f: F) -> io::Result<T>
where
F: FnOnce() -> Result<T, Error>,
{
match f() {
Ok(t) => Ok(t),
Err(Error::IoError(e)) => Err(e),
Err(e) => Err(io::Error::new(
io::ErrorKind::Other,
format!("{}: {}", desc, e),
)),
}
}
fn query_names<F, T>(name: &str, config: &DnsConfig, mut f: F) -> Result<T, Error>
where
F: FnMut(String) -> Result<T, Error>,
{
let use_search =
!name.ends_with('.') && name.chars().filter(|&c| c == '.').count() as u32 >= config.n_dots;
if use_search {
let mut err = None;
for name in with_suffixes(name, &config.search) {
match f(name) {
Ok(t) => return Ok(t),
Err(e) => err = Some(e),
}
}
if let Some(e) = err {
Err(e)
} else {
Err(Error::IoError(io::Error::new(
io::ErrorKind::Other,
"failed to resolve host: name not found",
)))
}
} else {
f(name.to_owned())
}
}
fn with_suffixes(host: &str, suffixes: &[String]) -> Vec<String> {
let mut v = suffixes
.iter()
.map(|s| format!("{}.{}", host, s))
.collect::<Vec<_>>();
v.push(host.to_owned());
v
}
/// Resolves an IPv4 or IPv6 address to a hostname.
pub fn resolve_addr(addr: &IpAddr) -> io::Result<String> {
let r = DnsResolver::new(DnsConfig::load_default()?)?;
r.resolve_addr(addr)
}
/// Resolves a hostname to one or more IPv4 or IPv6 addresses.
///
/// # Example
///
/// ```no_run
/// use sync_resolve::resolve_host;
/// # use std::io;
///
/// # fn _foo() -> io::Result<()> {
/// for addr in resolve_host("rust-lang.org")? {
/// println!("found address: {}", addr);
/// }
/// # Ok(())
/// # }
/// ```
pub fn resolve_host(host: &str) -> io::Result<ResolveHost> {
let r = DnsResolver::new(DnsConfig::load_default()?)?;
r.resolve_host(host)
}
/// Yields a series of `IpAddr` values from `resolve_host`.
pub struct ResolveHost(IntoIter<IpAddr>);
impl Iterator for ResolveHost {
type Item = IpAddr;
fn next(&mut self) -> Option<IpAddr> {
self.0.next()
}
}
|
use ::window::WindowBuilder;
use ::widget::Widget;
#[cfg(target_os = "windows")]
mod win32;
#[cfg(any(target_os = "linux", feature = "gtk"))]
mod gtk;
#[cfg(all(target_os = "windows", not(feature = "gtk")))]
pub type BackendImpl = win32::Backend;
#[cfg(any(target_os = "linux", feature = "gtk"))]
pub type BackendImpl = gtk::Backend;
pub trait Backend {
type Window: Widget<Builder = WindowBuilder>;
fn start(window: WindowBuilder);
}
|
// error-pattern:unexpected token: '}'
// Issue #1200
type t = {};
fn main() {
} |
use crate::get_result_i64;
use std::collections::HashMap;
use std::ops::Neg;
// https://adventofcode.com/2020/day/14
// https://www.reddit.com/r/rust/comments/kcrbxw/advent_of_code_2020_day_14/
const INPUT_FILENAME: &str = "inputs/input14";
pub fn solve() {
get_result_i64(1, part01, INPUT_FILENAME);
get_result_i64(2, part02, INPUT_FILENAME);
}
fn part01(input: String) -> i64 {
let mut mask_1: i64 = 0;
let mut mask_0: i64 = 0;
let mut memory: HashMap<usize, i64> = HashMap::new();
for line in input.lines() {
if line.starts_with("mask") {
let bitmask = &line[line.find("= ").unwrap() + 2..];
mask_1 = i64::from_str_radix(&bitmask.replace('X', "0"), 2).unwrap();
mask_0 = i64::from_str_radix(&bitmask.replace('X', "1"), 2).unwrap();
} else {
let memory_address = &line[line.find('[').unwrap() + 1..line.find(']').unwrap()].parse::<usize>().unwrap();
let mut value = *&line[line.find("= ").unwrap() + 2..].parse::<i64>().unwrap();
value = (value | mask_1) & mask_0;
if value & (1 << 36) != 0 {
value = value.neg();
}
&memory.insert(*memory_address, value);
}
}
memory.values().sum()
}
fn part02(input: String) -> i64 {
let mut bitmask: i64 = 0;
let mut floating_bits: Vec<usize> = Vec::new();
let mut memory: HashMap<i64, i64> = HashMap::new();
for line in input.lines() {
if line.starts_with("mask") {
let bitmask_str = &line[line.find("= ").unwrap() + 2..];
bitmask = i64::from_str_radix(&bitmask_str.replace('X', "0"), 2).unwrap();
floating_bits = bitmask_str.char_indices().filter(|(_, char)| *char == 'X').map(|(idx, _)| 35 - idx).collect();
} else {
let mut memory_address = *&line[line.find('[').unwrap() + 1..line.find(']').unwrap()].parse::<i64>().unwrap();
let value = *&line[line.find("= ").unwrap() + 2..].parse::<i64>().unwrap();
memory_address = memory_address | bitmask;
recursive(&floating_bits, &mut memory, memory_address, value);
}
}
memory.values().sum()
}
fn recursive(floating_bits: &[usize], memory: &mut HashMap<i64, i64>, memory_address: i64, value: i64) {
if floating_bits.is_empty() {
return;
}
memory.insert(memory_address, value);
recursive(&floating_bits[1..], memory, memory_address, value);
let new_address = memory_address ^ (1 << floating_bits[0]);
memory.insert(new_address, value);
recursive(&floating_bits[1..], memory, new_address, value);
}
fn shift_bit(memory_address: i64, idx: usize) -> i64 {
memory_address ^ (1 << idx)
} |
extern crate extprim;
extern crate libc;
extern crate serde;
extern crate serde_json;
extern crate uuid;
extern crate byteorder;
extern crate bit_vec;
extern crate hex;
#[macro_use]
mod encoding;
#[macro_use]
mod messages;
#[macro_use]
mod macros;
mod assets;
mod capi;
mod decimal;
mod error;
mod transactions;
mod storage;
mod crypto;
pub use capi::*;
pub use error::*;
pub use encoding::*; |
use cgmath;
pub use cgmath::prelude::*;
pub type Vector2 = cgmath::Vector2<f32>;
pub type Vector3 = cgmath::Vector3<f32>;
pub type Vector4 = cgmath::Vector4<f32>;
pub type Matrix4 = cgmath::Matrix4<f32>;
pub type Quaternion = cgmath::Quaternion<f32>;
|
#[doc = "Reader of register RCC_MP_TZAHB6ENSETR"]
pub type R = crate::R<u32, super::RCC_MP_TZAHB6ENSETR>;
#[doc = "Writer for register RCC_MP_TZAHB6ENSETR"]
pub type W = crate::W<u32, super::RCC_MP_TZAHB6ENSETR>;
#[doc = "Register RCC_MP_TZAHB6ENSETR `reset()`'s with value 0"]
impl crate::ResetValue for super::RCC_MP_TZAHB6ENSETR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "MDMAEN\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MDMAEN_A {
#[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"]
B_0X0 = 0,
#[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"]
B_0X1 = 1,
}
impl From<MDMAEN_A> for bool {
#[inline(always)]
fn from(variant: MDMAEN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `MDMAEN`"]
pub type MDMAEN_R = crate::R<bool, MDMAEN_A>;
impl MDMAEN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MDMAEN_A {
match self.bits {
false => MDMAEN_A::B_0X0,
true => MDMAEN_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == MDMAEN_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == MDMAEN_A::B_0X1
}
}
#[doc = "Write proxy for field `MDMAEN`"]
pub struct MDMAEN_W<'a> {
w: &'a mut W,
}
impl<'a> MDMAEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MDMAEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(MDMAEN_A::B_0X0)
}
#[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(MDMAEN_A::B_0X1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 0 - MDMAEN"]
#[inline(always)]
pub fn mdmaen(&self) -> MDMAEN_R {
MDMAEN_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - MDMAEN"]
#[inline(always)]
pub fn mdmaen(&mut self) -> MDMAEN_W {
MDMAEN_W { w: self }
}
}
|
use crate::board::{Board, GameResult, PieceSpot, Player};
use crate::colors;
use iced::{
button, container, Align, Background, Button, Column, Container, Element, HorizontalAlignment,
Length, Row, Sandbox, Space, Text,
};
const HEADING: &str = "Connect – 4"; // en dash, not hyphen
const INSTRUCTIONS: &str = "\
In this game there are two players, A and B, A having the red pieces and B having the yellow pieces. \
The way you play this game is by dropping a piece in any of the columns. \
The goal of the game is to make any sequence of four pieces horizontally, vertically, or diagonally. \
";
const CIRCLE_SIZE: u16 = 50;
const INTERCOLUMN_SPACING: u16 = 5;
impl container::StyleSheet for PieceSpot {
fn style(&self) -> container::Style {
let background_color = match self {
PieceSpot::Player(Player::A) => colors::PLAYER_A,
PieceSpot::Player(Player::B) => colors::PLAYER_B,
PieceSpot::Empty => colors::EMPTY,
};
container::Style {
background: Some(Background::from(background_color)),
border_radius: CIRCLE_SIZE / 2,
..container::Style::default()
}
}
}
impl Board {
pub fn view(&self) -> Element<Message> {
let circle = || {
Container::new(Space::new(
Length::Units(CIRCLE_SIZE),
Length::Units(CIRCLE_SIZE),
))
};
let mut row = Row::new().spacing(INTERCOLUMN_SPACING);
for i in 0..7 {
let mut column = Column::new().spacing(INTERCOLUMN_SPACING);
for j in (0..6).rev() {
column = column.push(circle().style(self.board[i][j]));
}
row = row.push(column);
}
row.into()
}
}
#[derive(Clone, Copy, Debug, Default)]
struct ResetButton {
state: button::State,
}
#[derive(Clone, Copy, Debug)]
struct DropButton {
column: usize,
state: button::State,
}
impl DropButton {
fn new(column: usize) -> Self {
Self {
state: button::State::default(),
column,
}
}
fn new_array() -> [Self; 7] {
let mut array: [Self; 7] = [Self::new(0); 7];
for (index, btn) in (0..array.len()).map(|num| (num, Self::new(num))) {
array[index] = btn;
}
array
}
fn view(&mut self) -> Element<Message> {
Button::new(&mut self.state, Text::new("Drop"))
.width(Length::Units(CIRCLE_SIZE))
.on_press(Message::PieceDrop(self.column))
.into()
}
}
#[derive(Debug, Clone, Copy)]
pub enum Message {
PieceDrop(usize),
Reset,
}
#[derive(Debug, Clone)]
pub struct BoardGui {
board: Board,
reset_button: ResetButton,
drop_buttons: [DropButton; 7],
game_over: bool,
}
impl Sandbox for BoardGui {
type Message = Message;
fn new() -> Self {
Self {
board: Board::default(),
reset_button: ResetButton::default(),
drop_buttons: DropButton::new_array(),
game_over: false,
}
}
fn title(&self) -> String {
String::from(HEADING)
}
fn view(&mut self) -> Element<Self::Message> {
let (result_text, result_size) = match self.board.calculate_result() {
GameResult::Indefinite => (format!("Turn: {}", self.board.turn), 25),
GameResult::Draw => (String::from("It's a Draw!"), 80),
GameResult::Win(player) => (format!("{} Won!", player), 80),
};
let reset_button = Button::new(
&mut self.reset_button.state,
Text::new("Reset").horizontal_alignment(HorizontalAlignment::Center),
)
.width(Length::Units(CIRCLE_SIZE * 7))
.on_press(Message::Reset);
Column::<Message>::new()
.spacing(25)
.width(Length::Fill)
.align_items(Align::Center)
.push(Text::new(HEADING).size(80).color(colors::HEADING))
.push(Text::new(INSTRUCTIONS).width(Length::Units(600)))
.push(Text::new(result_text).size(result_size))
.push(
Row::with_children(self.drop_buttons.iter_mut().map(|btn| btn.view()).collect())
.spacing(INTERCOLUMN_SPACING),
)
.push(self.board.view())
.push(reset_button)
.into()
}
fn update(&mut self, message: Self::Message) {
match message {
Message::PieceDrop(column) => {
if !self.game_over {
let valid_drop = self.board.drop_piece(column);
if let GameResult::Indefinite = self.board.calculate_result() {
if valid_drop.is_ok() {
self.board.switch_turn();
}
} else {
self.game_over = true;
}
}
}
Message::Reset => {
self.board.reset();
self.game_over = false;
}
}
}
}
|
// pathfinder/examples/canvas_minimal/src/main.rs
//
// Copyright © 2019 The Pathfinder Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use euclid::default::Size2D;
use image::png::PNGEncoder;
use image::ColorType;
use pathfinder_canvas::{CanvasFontContext, CanvasRenderingContext2D, Path2D};
use pathfinder_color::ColorF;
use pathfinder_geometry::rect::RectF;
use pathfinder_geometry::rect::RectI;
use pathfinder_geometry::vector::{Vector2F, Vector2I};
use pathfinder_gl::{GLDevice, GLVersion as pathfinder_glversion};
use pathfinder_gpu::{Device, RenderTarget, TextureData};
use pathfinder_renderer::concurrent::rayon::RayonExecutor;
use pathfinder_renderer::concurrent::scene_proxy::SceneProxy;
use pathfinder_renderer::gpu::options::{DestFramebuffer, RendererOptions};
use pathfinder_renderer::gpu::renderer::Renderer;
use pathfinder_renderer::options::BuildOptions;
use pathfinder_resources::embedded::EmbeddedResourceLoader;
use std::fs::File;
use surfman::{
Connection, ContextAttributeFlags, ContextAttributes, GLVersion, SurfaceAccess, SurfaceType,
};
fn main() {
let window_size = Vector2I::new(640, 480);
let connection = Connection::new().unwrap();
let adapter = connection.create_hardware_adapter().unwrap();
let mut device = connection.create_device(&adapter).unwrap();
let context_attributes = ContextAttributes {
version: GLVersion::new(3, 3),
flags: ContextAttributeFlags::empty(),
};
let context_descriptor = device
.create_context_descriptor(&context_attributes)
.unwrap();
let mut context = device.create_context(&context_descriptor).unwrap();
let surface = device
.create_surface(
&context,
SurfaceAccess::GPUOnly,
SurfaceType::Generic {
size: Size2D::new(window_size.x(), window_size.y()),
},
)
.unwrap();
device
.bind_surface_to_context(&mut context, surface)
.unwrap();
gl::load_with(|symbol_name| device.get_proc_address(&context, symbol_name));
device.make_context_current(&context).unwrap();
// Create a Pathfinder renderer.
let mut renderer = Renderer::new(
GLDevice::new(pathfinder_glversion::GL3, 0),
&EmbeddedResourceLoader::new(),
DestFramebuffer::full_window(window_size),
RendererOptions {
background_color: Some(ColorF::white()),
},
);
// Make a canvas. We're going to draw a house.
let mut canvas = CanvasRenderingContext2D::new(
CanvasFontContext::from_system_source(),
window_size.to_f32(),
);
// Set line width.
canvas.set_line_width(10.0);
// Draw walls.
canvas.stroke_rect(RectF::new(
Vector2F::new(75.0, 140.0),
Vector2F::new(150.0, 110.0),
));
// Draw door.
canvas.fill_rect(RectF::new(
Vector2F::new(130.0, 190.0),
Vector2F::new(40.0, 60.0),
));
// Draw roof.
let mut path = Path2D::new();
path.move_to(Vector2F::new(50.0, 140.0));
path.line_to(Vector2F::new(150.0, 60.0));
path.line_to(Vector2F::new(250.0, 140.0));
path.close_path();
canvas.stroke_path(path);
// Render the canvas to screen.
let scene = SceneProxy::from_scene(canvas.into_scene(), RayonExecutor);
scene.build_and_render(&mut renderer, BuildOptions::default());
let viewport = RectI::new(Vector2I::default(), window_size);
let texture_data_receiver = renderer
.device
.read_pixels(&RenderTarget::Default, viewport);
let pixels = match renderer.device.recv_texture_data(&texture_data_receiver) {
TextureData::U8(pixels) => pixels,
_ => panic!("Unexpected pixel format for default framebuffer!"),
};
let mut output = File::create("./test.png").unwrap();
let encoder = PNGEncoder::new(&mut output);
encoder
.encode(
pixels.as_ref(),
window_size.x() as u32,
window_size.y() as u32,
ColorType::Rgba8,
)
.unwrap();
}
|
use crate::hittable::{aabb::Aabb, HitRecord, Hittable, Hittables};
use crate::material::{isotropic::Isotropic, MaterialType};
use crate::ray::Ray;
use crate::texture::Texture;
use crate::util::random_double;
use crate::vec::vec3;
use rand::rngs::SmallRng;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct ConstantMedium {
pub boundary: Arc<Hittables>,
pub phase_fn: Arc<MaterialType>,
pub neg_inv_density: f64,
}
impl ConstantMedium {
pub fn new(boundary: Arc<Hittables>, density: f64, texture: Texture) -> Hittables {
Hittables::from(ConstantMedium {
boundary: boundary,
neg_inv_density: -1.0 / density,
phase_fn: Isotropic::new(texture),
})
}
}
impl Hittable for ConstantMedium {
fn hit(&self, ray: &Ray, t_min: f64, t_max: f64, rng: &mut SmallRng) -> Option<HitRecord> {
let mut rec1 = match self
.boundary
.hit(ray, -std::f64::INFINITY, std::f64::INFINITY, rng)
{
Some(hit) => hit,
None => {
return None;
}
};
let mut rec2 = match self
.boundary
.hit(ray, rec1.t + 0.0001, std::f64::INFINITY, rng)
{
Some(hit) => hit,
None => {
return None;
}
};
if rec1.t < t_min {
rec1.t = t_min;
}
if rec2.t > t_max {
rec2.t = t_max;
}
if rec1.t >= rec2.t {
return None;
}
if rec1.t < 0.0 {
rec1.t = 0.0;
}
let ray_length = ray.direction.length();
let distance_inside_boundary = (rec2.t - rec1.t) * ray_length;
let hit_distance = self.neg_inv_density * random_double(rng).ln();
if hit_distance > distance_inside_boundary {
return None;
}
let t = rec1.t + hit_distance / ray_length;
Some(HitRecord {
t: t,
u: 0.0, // arbitrary
v: 0.0, // arbitrary
point: ray.at(t),
normal: vec3(1.0, 0.0, 0.0), // arbitrary
front_face: true, // arbitrary
mat: self.phase_fn.clone(),
})
}
fn bounding_box(&self, time0: f64, time1: f64) -> Option<Aabb> {
self.boundary.bounding_box(time0, time1)
}
}
|
use crate::interaction::navmesh::data_model::{Navmesh, NavmeshEdge};
use crate::interaction::navmesh::{NavmeshEntity, NavmeshVertex};
use rg3d::core::pool::Handle;
use std::collections::HashSet;
#[derive(PartialEq, Clone, Debug, Eq)]
pub struct NavmeshSelection {
dirty: bool,
navmesh: Handle<Navmesh>,
entities: Vec<NavmeshEntity>,
unique_vertices: HashSet<Handle<NavmeshVertex>>,
}
impl NavmeshSelection {
pub fn empty(navmesh: Handle<Navmesh>) -> Self {
Self {
dirty: false,
navmesh,
entities: vec![],
unique_vertices: Default::default(),
}
}
pub fn new(navmesh: Handle<Navmesh>, entities: Vec<NavmeshEntity>) -> Self {
Self {
dirty: true,
navmesh,
entities,
unique_vertices: Default::default(),
}
}
pub fn navmesh(&self) -> Handle<Navmesh> {
self.navmesh
}
pub fn add(&mut self, entity: NavmeshEntity) {
self.entities.push(entity);
self.dirty = true;
}
pub fn clear(&mut self) {
self.entities.clear();
self.unique_vertices.clear();
self.dirty = false;
}
pub fn first(&self) -> Option<&NavmeshEntity> {
self.entities.first()
}
pub fn is_empty(&self) -> bool {
self.entities.is_empty()
}
pub fn is_single_selection(&self) -> bool {
self.entities.len() == 1
}
pub fn unique_vertices(&mut self) -> &HashSet<Handle<NavmeshVertex>> {
if self.dirty {
self.unique_vertices.clear();
for entity in self.entities.iter() {
match entity {
NavmeshEntity::Vertex(v) => {
self.unique_vertices.insert(*v);
}
NavmeshEntity::Edge(edge) => {
self.unique_vertices.insert(edge.begin);
self.unique_vertices.insert(edge.end);
}
}
}
}
&self.unique_vertices
}
pub fn entities(&self) -> &[NavmeshEntity] {
&self.entities
}
pub fn contains_edge(&self, edge: NavmeshEdge) -> bool {
self.entities.contains(&NavmeshEntity::Edge(edge))
}
}
|
// overflow
fn main() {
} |
use embedded_hal::blocking::delay::DelayMs;
use hdc20xx::{Hdc20xx, SlaveAddr};
use linux_embedded_hal::{Delay, I2cdev};
fn main() {
let mut delay = Delay {};
let dev = I2cdev::new("/dev/i2c-1").unwrap();
let address = SlaveAddr::default();
let mut sensor = Hdc20xx::new(dev, address);
loop {
loop {
let result = sensor.read();
match result {
Err(nb::Error::WouldBlock) => delay.delay_ms(100_u8),
Err(e) => {
println!("Error! {:?}", e);
}
Ok(data) => {
println!(
"Temperature: {:2}°C, Humidity: {:2}%",
data.temperature,
data.humidity.unwrap()
);
}
}
}
}
}
|
fn main() {
let mut door_open = [false; 100];
for pass in 1..101 {
let mut door = pass;
while door <= 100 {
door_open[door - 1] = !door_open[door - 1];
door += pass;
}
}
//for (i, &is_open) in door_open.iter().enumerate() {
// println!("Door {} is {}.", i + 1, if is_open {"open"} else {"closed"});
//}
} |
//! Edit command
use super::Command;
use crate::Error;
use async_trait::async_trait;
use clap::{Arg, ArgMatches, Command as ClapCommand};
/// Abstract `edit` command
///
/// ```sh
/// leetcode-edit
/// Edit question by id
///
/// USAGE:
/// leetcode edit <id>
///
/// FLAGS:
/// -h, --help Prints help information
/// -V, --version Prints version information
///
/// ARGS:
/// <id> question id
/// ```
pub struct EditCommand;
#[async_trait]
impl Command for EditCommand {
/// `edit` usage
fn usage() -> ClapCommand {
ClapCommand::new("edit")
.about("Edit question by id")
.visible_alias("e")
.arg(
Arg::new("lang")
.short('l')
.long("lang")
.num_args(1)
.help("Edit with specific language"),
)
.arg(
Arg::new("id")
.num_args(1)
.required(true)
.value_parser(clap::value_parser!(i32))
.help("question id"),
)
}
/// `edit` handler
async fn handler(m: &ArgMatches) -> Result<(), crate::Error> {
use crate::{cache::models::Question, Cache};
use std::fs::File;
use std::io::Write;
use std::path::Path;
let id = *m.get_one::<i32>("id").ok_or(Error::NoneError)?;
let cache = Cache::new()?;
let problem = cache.get_problem(id)?;
let mut conf = cache.to_owned().0.conf;
let test_flag = conf.code.test;
let p_desc_comment = problem.desc_comment(&conf);
// condition language
if m.contains_id("lang") {
conf.code.lang = m
.get_one::<String>("lang")
.ok_or(Error::NoneError)?
.to_string();
conf.sync()?;
}
let lang = &conf.code.lang;
let path = crate::helper::code_path(&problem, Some(lang.to_owned()))?;
if !Path::new(&path).exists() {
let mut qr = serde_json::from_str(&problem.desc);
if qr.is_err() {
qr = Ok(cache.get_question(id).await?);
}
let question: Question = qr?;
let mut file_code = File::create(&path)?;
let question_desc = question.desc_comment(&conf) + "\n";
let test_path = crate::helper::test_cases_path(&problem)?;
let mut flag = false;
for d in question.defs.0 {
if d.value == *lang {
flag = true;
if conf.code.comment_problem_desc {
file_code.write_all(p_desc_comment.as_bytes())?;
file_code.write_all(question_desc.as_bytes())?;
}
if conf.code.edit_code_marker {
file_code.write_all(
(conf.code.comment_leading.clone()
+ " "
+ &conf.code.start_marker
+ "\n")
.as_bytes(),
)?;
}
file_code.write_all((d.code.to_string() + "\n").as_bytes())?;
if conf.code.edit_code_marker {
file_code.write_all(
(conf.code.comment_leading.clone()
+ " "
+ &conf.code.end_marker
+ "\n")
.as_bytes(),
)?;
}
if test_flag {
let mut file_tests = File::create(&test_path)?;
file_tests.write_all(question.all_cases.as_bytes())?;
}
}
}
// if language is not found in the list of supported languges clean up files
if !flag {
std::fs::remove_file(&path)?;
if test_flag {
std::fs::remove_file(&test_path)?;
}
return Err(crate::Error::FeatureError(format!(
"This question doesn't support {}, please try another",
&lang
)));
}
}
// Get arguments of the editor
//
// for example:
//
// ```toml
// [code]
// editor = "emacsclient"
// editor_args = [ "-n", "-s", "doom" ]
// ```
//
// ```rust
// Command::new("emacsclient").args(&[ "-n", "-s", "doom", "<problem>" ])
// ```
let mut args: Vec<String> = Default::default();
if let Some(editor_args) = conf.code.editor_args {
args.extend_from_slice(&editor_args);
}
args.push(path);
std::process::Command::new(conf.code.editor)
.args(args)
.status()?;
Ok(())
}
}
|
mod lib;
use lib::listen_and_serve;
use std::net::TcpStream;
fn main() {
println!("Hello, world!");
listen_and_serve(80, "hello_world")
}
fn hello_world(s: TcpStream) {
println!("eek");
}
|
#![allow(dead_code)]
pub mod cache;
pub mod multiset;
pub mod patch;
pub mod traits;
pub mod translate;
pub mod functions;
use crate::cache::*;
use crate::multiset::*;
use crate::patch::*;
use crate::traits::*;
use crate::translate::*;
use std::collections::HashMap;
use std::hash::Hash;
fn main() {
let b = Multiset::new(
[(Sum::new(1), Sum::new(2)), (Sum::new(11), Sum::new(-1))]
.iter()
.cloned(),
);
println!("{:?}", b.fold_group());
}
pub struct Plus;
pub struct PlusCache;
impl HasCache for Plus {
type Cache = PlusCache;
}
fn cplus(x: i32, y: i32) -> Caching<Plus, i32> {
Caching {
data: x + y,
cache: PlusCache,
}
}
fn dplus(
(_x, _y): (i32, i32),
(dx, dy): (i32, i32),
cache: PlusCache,
) -> Caching<Plus, Delta<i32>> {
Caching {
data: Delta(dx + dy),
cache,
}
}
pub struct Div;
pub struct DivCache;
impl HasCache for Div {
type Cache = DivCache;
}
fn cdiv(x: i32, y: i32) -> Caching<Div, i32> {
Caching {
data: x / y,
cache: DivCache,
}
}
fn ddiv(
(x, y): (i32, i32),
(dx, dy): (i32, i32),
cache: DivCache,
) -> Caching<Div, Delta<i32>> {
Caching {
data: Delta((x + dx) / (y + dy) - x / y),
cache,
}
}
fn multiset_sum(b: Multiset<Sum<i32>>) -> Sum<i32> {
b.fold_group()
}
// data Fun a b c where
// Primitive ::
// !(a -> (b, c)) -> !(a -> Dt a -> c -> (Dt b, c)) -> Fun a b c
// Closure :: (NilTestable e, NilChangeStruct e, NFData e) =>
// !(Fun (e, a) b c) -> !e -> Fun a b c
// data DFun a b c where
// DPrimitive ::
// !(a -> Dt a -> c -> (Dt b, c)) -> DFun a b c
// DClosure :: (NilTestable e, NilChangeStruct e, NFData e) =>
// !(Fun (e, a) b c) -> !(DFun (e, a) b c) -> !e -> !(Dt e) ->
// DFun a b c
|
//! The Styx IR builder.
//!
//! Styx IR is a structure very close to actual assembly.
//!
//! It consists of raw assembly with the following added features:
//! - **Macros**: Instructions that get expanded to one or more other instructions.
//! - **Variables**: Abstract variables that are automatically transformed into register
//! or stack variables during encoding.
//! - **Blocks**: Labels that allow simple jumping inside a function, by passing values.
//! - **Calls**: Easier function calls with automatic argument insertion.
//!
//! Additionally, the produced IR can be easily converted to machine code in multiple
//! architectures with little effort.
//!
//! The builder defined thereafter allows the emission of the described language
//! using a friendly API.
use prelude::*;
use arch::Architecture;
use assembler::AssemblyGraph;
use context::Context;
use diagnostics::{Diagnostic, DiagnosticBag};
use lexer::Span;
use typesystem::{Fun, Typed};
use std::fmt::{self, Display, Formatter, Write};
use std::marker::PhantomData;
use string_interner::StringInterner;
use yansi::Paint;
/// Panics if the given value is null or not a multiple of two.
macro_rules! check_size {
( $value: expr ) => (
assert!($value == 0 || $value.is_power_of_two(), "The specified value is null or odd.")
)
}
/// Writes all the given arguments, separated by a comma.
macro_rules! write_separated {
( $f: expr, $elements: expr, $elem: ident => $body: expr ) => {
#[allow(never_loop)]
'block: loop {
if $elements.len() == 0 {
break 'block Ok(())
}
for i in 0..$elements.len() - 1 {
let $elem = unsafe { $elements.get_unchecked(i) };
$body;
if let Err(err) = write!($f, ", ") {
break 'block Err(err)
}
}
let $elem = unsafe { $elements.get_unchecked($elements.len() - 1) };
$body;
break 'block Ok(())
}
}
}
// //==========================================================================//
// // INSTR & OPERAND //
// //==========================================================================//
/// An instruction, as seen by the `Builder`.
#[derive(Debug, Clone, PartialEq)]
pub struct Instr<'b, 'cx> {
name: usize,
operands: Vec<Value<'b, 'cx>>,
terminates: bool
}
impl<'b, 'cx> Instr<'b, 'cx> {
fn new(name: usize, operands: Vec<Value<'b, 'cx>>) -> Self {
Instr { name, operands, terminates: false }
}
fn that_terminates(mut self) -> Self {
self.terminates = true;
self
}
pub(crate) fn as_jmp<'a>(&'a self, builder: &'a Builder<'b, 'cx>) -> Option<(usize, &'a str)> {
let target = match &self.operands.get(0)?.kind {
&ValueKind::BlockReference(r) => r as usize,
_ => return None
};
let kind = builder.get_name(self.name as _).unwrap();
Some((target, kind))
}
pub(crate) fn as_call(&self) -> Option<&'cx Fun<'cx>> {
if self.name == Builder::CALL_INDEX {
match &self.operands.get(0)?.kind {
&ValueKind::FunctionReference(f) => Some(f),
_ => None
}
} else {
None
}
}
pub(crate) fn as_ret(&self) -> Option<Value<'b, 'cx>> {
if self.name == Builder::RET_INDEX {
Some(*self.operands.get(0).unwrap_or(&Value::null()))
} else {
None
}
}
/// Returns the name of the instruction, if it has one.
///
/// # Note
/// The `Builder` is required because the actual string is stored in it.
pub fn name<'a>(&'a self, builder: &'a Builder<'b, 'cx>) -> Option<&'a str> {
builder.get_name(self.name)
}
/// Returns a slice of all the operands passed to this instruction.
pub fn operands(&self) -> &[Value<'b, 'cx>] {
&self.operands
}
fn display(&self, f: &mut Write, builder: &Builder<'b, 'cx>) -> fmt::Result {
write!(f, "{} ", Paint::white(builder.get_name(self.name).unwrap()))?;
if self.name == Builder::CALL_INDEX {
self.operands[0].display(f, builder)?;
} else {
write_separated!(f, &self.operands, operand => operand.display(f, builder)?)?;
}
Ok(())
}
}
/// The kind of a `Value`.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum ValueKind<'cx> {
/// A local variable or function parameter.
Variable(bool, u32),
/// An immediate value.
Immediate(u64),
/// A pointer to a memory address.
Memory(u64),
/// A reference to a `Block`.
BlockReference(u16),
/// A reference to a function.
FunctionReference(&'cx Fun<'cx>),
/// A phi-value.
Phi(u64),
/// A block argument.
Argument(u16),
/// A null-operand.
Null
}
impl<'cx> Display for ValueKind<'cx> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
use self::ValueKind::*;
match *self {
Variable(..) => f.write_str("var"),
Immediate(_) => f.write_str("imm"),
BlockReference(_) => f.write_str("blockref"),
Memory(_) => f.write_str("mem"),
Phi(_) => f.write_str("phi"),
FunctionReference(_) => f.write_str("fn"),
Argument(_) => f.write_str("arg"),
Null => f.write_str("null")
}
}
}
/// An operand taken by an instruction emitted by a `Builder`.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Value<'b, 'cx> {
size: u16,
kind: ValueKind<'cx>,
symbol: u32,
_data: PhantomData<&'b ()>
}
impl<'a, 'b, 'cx> AsRef<Value<'b, 'cx>> for &'a Value<'b, 'cx> {
fn as_ref(&self) -> &Value<'b, 'cx> {
self
}
}
impl<'b, 'cx> Value<'b, 'cx> {
/// Creates a new `Value`, given its size, kind and name.
fn new(size: u16, kind: ValueKind<'cx>, symbol: usize) -> Self {
check_size!(size);
if size == 1 {
//panic!("Created value of size 1");
}
Value { size, symbol: symbol as _, kind, _data: PhantomData }
}
/// Creates a null `Value` with a null size, no name, and a `ValueKind::Null' kind.
fn null() -> Self {
Value { size: 0, symbol: Builder::EMPTY_INDEX as _, kind: ValueKind::Null, _data: PhantomData }
}
fn display(&self, f: &mut Write, builder: &Builder<'b, 'cx>) -> fmt::Result {
if self.symbol == 0 {
write!(f, "null")
} else {
write!(f, "{} '{}'", self.kind, builder.get_name(self.symbol as _).unwrap())
}
}
/// Returns a `bool` that indicates whether the value is null (it has a null size).
#[inline]
pub fn is_null(&self) -> bool {
self.kind == ValueKind::Null
}
/// Returns the size of the value in bytes.
pub fn size(&self) -> u16 {
self.size
}
/// Returns the kind of the value.
pub fn kind(&self) -> ValueKind<'cx> {
self.kind
}
/// Returns a `bool` that indicates whether the value must be processed by the `Analysis`.
#[inline]
pub(crate) fn must_be_processed(&self) -> bool {
use self::ValueKind::*;
match self.kind {
Variable(_, _) | Immediate(_) | Memory(_) | Argument(_) => false,
_ => true
}
}
}
// //==========================================================================//
// // BUILDER //
// //==========================================================================//
/// A structure that enables easy procedure creation during runtime.
pub struct Builder<'b, 'cx: 'b> {
pub(crate) blocks: Vec<Block<'b, 'cx>>,
pub(crate) diagnostics: &'b mut DiagnosticBag,
pub(crate) calls: Vec<&'cx Fun<'cx>>,
pub(crate) rets: Vec<Value<'b, 'cx>>,
pub(crate) paramsc: usize,
pub(crate) ctx: &'b Context<'cx>,
inlining: Vec<usize>,
variables: Vec<Value<'b, 'cx>>,
interner: StringInterner<usize>,
arch: Architecture,
block: usize,
span: Span
}
impl<'b, 'cx> Builder<'b, 'cx> {
const EMPTY_INDEX: usize = 0;
const NAME_INDEX: usize = 1;
const CALL_INDEX: usize = 2;
const RET_INDEX: usize = 3;
const ARG_INDEX: usize = 4;
/// Creates a new `Binder`.
pub fn new<N: Into<String>, S: ToString>(
ctx: &'b Context<'cx>,
arch: Architecture,
span: Span,
diagnostics: &'b mut DiagnosticBag,
name: N,
parameters: &[(S, u16)])
-> Self {
let mut interner = StringInterner::with_capacity(16);
let mut name = name.into();
if name.is_empty() {
name.push_str("<anonymous>");
}
interner.get_or_intern("");
interner.get_or_intern(name);
// Special instructions:
// THE ORDER IS IMPORTANT! special instructions
// can be easily resolved using their name,
// which depends on the order of declaration of their name.
interner.get_or_intern("call*");
interner.get_or_intern("ret*");
interner.get_or_intern("blockarg");
let name = interner.get_or_intern("entry");
let mut params = Vec::with_capacity(parameters.len());
let mut i = 0;
for &(ref name, size) in parameters.iter() {
let name = interner.get_or_intern(name.to_string());
params.push(Value::new(size, ValueKind::Variable(false, i), name));
i += 1;
}
Builder {
ctx,
blocks: vec!(Block::new(0, name, Some(0))),
calls: vec!(), rets: vec!(), inlining: vec!(),
variables: params,
block: 0,
interner,
arch,
span,
diagnostics,
paramsc: i as _
}
}
/// Returns the name of the function to which this builder corresponds.
#[inline]
pub fn name(&self) -> &str {
self.interner.resolve(Self::NAME_INDEX).unwrap()
}
/// Returns the target architecture of the builder.
#[inline]
pub fn arch(&self) -> Architecture {
self.arch
}
/// Returns the span in which the expressions making up this builder
/// were defined.
#[inline]
pub fn span(&self) -> Span {
self.span
}
/// Defines a variable with a specific size and an optional name,
/// and returns an `Value` that describes this variable.
///
/// # Panics
/// - `size` is null or not a multiple of two.
pub fn define<N: Into<String> + AsRef<str>>(&mut self, size: u16, name: N) -> Value<'b, 'cx> {
check_size!(size);
let length = self.vars().len();
let var = Value::new(size, ValueKind::Variable(false, length as u32), self.interner.get_or_intern(name));
self.variables.push(var);
var
}
/// Returns a name for a variable to be defined.
pub fn variable_name(&mut self) -> String {
// name defaults to 'i%' where % is the position of the variable in the variables array
format!("i{}", self.vars().len())
}
/// Updates the specified variable, giving it a new value and marking it as mutable.
pub fn update<N: Into<String> + AsRef<str>>(&mut self, _variable: Value<'b, 'cx>, _value: Value<'b, 'cx>) {
unimplemented!()
}
/// Returns the parameter defined at the given position.
///
/// # Errors
/// Returns `None` if no parameter matching this position exists.
pub fn parameter(&self, position: usize) -> Option<Value<'b, 'cx>> {
if self.paramsc <= position {
None
} else {
Some(self.variables[position])
}
}
/// Returns the variable defined at the given position.
pub fn variable(&self, position: usize) -> Option<Value<'b, 'cx>> {
self.variables.get(position + self.paramsc).cloned()
}
/// Defines a new instruction, and returns its value.
pub fn new_instruction<N: Into<String> + AsRef<str>>(&mut self, name: N, operands: Vec<Value<'b, 'cx>>) -> Instr<'b, 'cx> {
Instr::new(self.interner.get_or_intern(name), operands)
}
/// Defines a new operand, and returns its value.
pub fn new_value<N: Into<String> + AsRef<str>>(&mut self, size: u16, name: N, kind: ValueKind<'cx>) -> Value<'b, 'cx> {
Value::new(size, kind, self.interner.get_or_intern(name))
}
/// Defines a null operand with a null size and no name, and returns its value.
pub fn null_value(&mut self) -> Value<'b, 'cx> {
Value::null()
}
/// Emits a 'jump' instruction to the given block.
pub fn emit_jump(&mut self, block: usize, value: Option<Value<'b, 'cx>>) {
let jump = Instr::new(self.interner.get_or_intern("jmp"), vec!(Value {
symbol: self.blocks[block].name as _,
size: 0,
kind: ValueKind::BlockReference(block as u16),
_data: PhantomData
}, value.unwrap_or_else(Value::null)));
let currblock = self.block;
self.blck().is_terminated = true;
self.blocks[block].imm_dominators.push(currblock);
self.instrs().push(jump.that_terminates())
}
/// Emits a conditional 'jump' instruction to the given block.
pub fn emit_cond_jump<N: Into<String> + AsRef<str>>(&mut self, jmpkind: N, block: usize, value: Option<Value<'b, 'cx>>) {
let jump = Instr::new(self.interner.get_or_intern(jmpkind), vec!(Value {
symbol: self.blocks[block].name as _,
size: 0,
kind: ValueKind::BlockReference(block as u16),
_data: PhantomData
}, value.unwrap_or_else(Value::null)));
let currblock = self.block;
self.blocks[block].imm_dominators.push(currblock);
self.instrs().push(jump)
}
/// Emits a 'ret' instruction which returns the specified variable.
pub fn emit_ret(&mut self, value: Value<'b, 'cx>) {
let inliningc = self.inlining.len();
if inliningc == 0 {
self.rets.push(value);
self.blck().is_terminated = true;
self.instrs().push(Instr::new(Self::RET_INDEX, vec!(value)).that_terminates());
} else {
// currently inlining an expression, jump to its end block with the value instead
let target = unsafe { *self.inlining.get_unchecked(inliningc - 1) };
let value = if value.size() == 0 { None } else { Some(value) };
self.emit_jump(target, value);
}
}
/// Emits a 'call' instruction to the specified function.
pub fn emit_call(&mut self, fun: &'cx Fun<'cx>, args: &[Value<'b, 'cx>]) -> Value<'b, 'cx> {
let mut operands = Vec::with_capacity(args.len() + 1);
let ret_size = fun.ty().size().unwrap();
let varname = self.variable_name();
let name = {
let mut name = format!("{}(", fun.name());
write_separated!(name, args, v => v.display(&mut name, self).expect("Could not write argument."))
.expect("Could not write argument.");
if ret_size == 0 {
name.push(')');
} else {
write!(name, ") -> {}", varname).expect("Could not write name");
}
name
};
operands.push(Value {
symbol: self.interner.get_or_intern(name) as _,
size: 0,
kind: ValueKind::FunctionReference(fun),
_data: PhantomData
});
operands.extend_from_slice(args);
self.calls.push(fun);
self.instrs().push(Instr::new(Self::CALL_INDEX, operands));
if ret_size == 0 {
self.null_value()
} else {
self.define(ret_size, varname)
}
}
/// Inlines the given function in the current body.
///
/// The function cannot depend on the current block.
pub fn emit_inline<'g>(&mut self, graph: &AssemblyGraph<'g, 'cx>, args: &[Value<'b, 'cx>]) -> Value<'b, 'cx> {
let target = graph.target;
let builder: &Self = unsafe {
&*(&graph.builder as *const _ as *const () as *const Self)
};
let ret_size = target.ty().size().unwrap();
let mut varc = self.variables.len();
// copy variables
for (i, var) in builder.variables.iter().enumerate() {
let var = self.new_value(var.size, builder.get_name(var.symbol as _).unwrap(), ValueKind::Variable(false, (varc + i) as u32));
self.variables.push(var);
}
// create after-call block, which contains the result of the "call"
let curr = self.block_index();
let then = self.create_block("after-call", if ret_size == 0 { None } else { Some(ret_size) }).index();
let diff = self.blocks().len();
// copy body
for block in builder.blocks() {
block.clone_to(diff - 1, varc as _, builder, self);
}
// move arguments
self.position_at_nth(curr);
for arg in args {
let var = self.variables[varc];
self.emit_move(*arg, var);
varc += 1;
}
// jump to after-call, and return value
self.emit_jump(then + 1, None);
self.position_at_nth(then);
self.block_argument().unwrap_or_else(Value::null)
}
/// Emits a 'mov' instruction.
pub fn emit_move(&mut self, source: Value<'b, 'cx>, destination: Value<'b, 'cx>) {
if destination != source {
self.emit2("mov", destination, source)
}
}
/// Emits the given expression inline.
///
/// If the expression returns a value, the function will not exit,
/// and the parameter of the 'after-expr' block will be set to the return value.
pub fn emit_expr(&mut self, expr: &Expr<'cx>) -> Value<'b, 'cx> {
let ty = expr.ty();
let size = ty.size().unwrap();
let after = self.create_block("after-expr", if size == 0 { None } else { Some(size) }).index();
// notify builder that we're building
// this is important, and changes the behavior of "ret"
self.inlining.push(after);
// emit expression
let result = expr.build(self);
// pop last element from inlining vec
self.inlining.pop();
// return value corresponding to block param
self.emit_jump(after, Some(result));
self.block_argument().unwrap_or_else(Value::null)
}
/// Emits the instruction described by the specified opcode.
///
/// Returns `Err` if no instruction matching the given opcode could be found.
pub fn emit(&mut self, opcode: &str, operands: Vec<Value<'b, 'cx>>) {
let name = self.interner.get_or_intern(opcode);
self.instrs().push(Instr::new(name, operands));
}
/// Emits the instruction described by the specified opcode.
///
/// Returns `Err` if no instruction matching the given opcode could be found.
pub fn emit0(&mut self, opcode: &str) {
let name = self.interner.get_or_intern(opcode);
self.instrs().push(Instr::new(name, vec!()));
}
/// Emits the instruction described by the specified opcode and operand.
///
/// Returns `Err` if no instruction matching the given opcode could be found.
pub fn emit1(&mut self, opcode: &str, op: Value<'b, 'cx>) {
let name = self.interner.get_or_intern(opcode);
self.instrs().push(Instr::new(name, vec!(op)));
}
/// Emits the instruction described by the specified opcode and operands.
///
/// Returns `Err` if no instruction matching the given opcode could be found.
pub fn emit2(&mut self, opcode: &str, op1: Value<'b, 'cx>, op2: Value<'b, 'cx>) {
let name = self.interner.get_or_intern(opcode);
self.instrs().push(Instr::new(name, vec!(op1, op2)));
}
/// Emits the instruction described by the specified opcode and operands.
///
/// Returns `Err` if no instruction matching the given opcode could be found.
pub fn emit3(&mut self, opcode: &str, op1: Value<'b, 'cx>, op2: Value<'b, 'cx>, op3: Value<'b, 'cx>) {
let name = self.interner.get_or_intern(opcode);
self.instrs().push(Instr::new(name, vec!(op1, op2, op3)));
}
/// Creates a block with no parameter, given its name.
#[inline]
pub fn create_block<N: Into<String> + AsRef<str>>(&mut self, name: N, argsize: Option<u16>) -> &'b Block<'b, 'cx> {
let name = self.interner.get_or_intern(name);
let index = self.blocks.len();
self.blocks.push(Block::new(index, name, argsize));
unsafe {
&*(self.blocks.get_unchecked(index) as *const _)
}
}
/// Creates a block with no parameter, and moves the builder to its end.
#[inline]
pub fn position_at_new_block<N: Into<String> + AsRef<str>>(&mut self, name: N, argsize: Option<u16>) -> &mut Self {
let name = self.interner.get_or_intern(name);
self.block = self.blocks.len();
self.blocks.push(Block::new(self.block, name, argsize));
self
}
/// Positions the builder at the end of the specified block.
#[inline]
pub fn position(&mut self, block: &Block<'b, 'cx>) -> &mut Self {
self.position_at_nth(block.index)
}
/// Positions the builder at the end of the nth block.
#[inline]
pub fn position_at_nth(&mut self, index: usize) -> &mut Self {
if index >= self.blocks.len() {
panic!("Index ouf of bounds.")
} else {
self.block = index;
self
}
}
#[inline]
fn blck<'a>(&'a mut self) -> &'a mut Block<'b, 'cx> {
&mut self.blocks[self.block]
}
#[inline]
fn instrs<'a>(&'a mut self) -> &'a mut Vec<Instr<'b, 'cx>> {
&mut self.blck().instructions
}
#[inline]
fn vars<'a>(&'a mut self) -> &'a mut Vec<Value<'b, 'cx>> {
&mut self.blck().variables
}
/// Gets the argument passed to the current block.
#[inline]
pub fn block_argument(&self) -> Option<Value<'b, 'cx>> {
match self.block().argsize {
Some(size) => Some(Value::new(size, ValueKind::Argument(self.block as _), Self::ARG_INDEX)),
None => None
}
}
/// Returns a reference to the block in which the builder is currently emitting.
#[inline]
pub fn block(&self) -> &Block<'b, 'cx> {
unsafe {
self.blocks.get_unchecked(self.block)
}
}
/// Returns the index of the block in which the builder is currently emitting.
#[inline]
pub fn block_index(&self) -> usize {
self.block
}
/// Returns a slice containing all built blocks.
#[inline]
pub fn blocks(&self) -> &[Block<'b, 'cx>] {
&self.blocks
}
/// Returns the nth block.
#[inline]
pub fn nth_block(&self, nth: usize) -> Option<&Block<'b, 'cx>> {
self.blocks.get(nth)
}
/// Returns the name associated with the specified symbol,
/// or `None` if it couldn't be resolved.
#[inline]
pub(crate) fn get_name(&self, symbol: usize) -> Option<&str> {
self.interner.resolve(symbol)
}
}
impl<'b, 'cx> Builder<'b, 'cx> {
/// Finalizes the builder, expanding macros and inlining method calls.
/// Furthermore, errors may be reported.
pub fn finalize(&mut self) {
// TODO: Right now, this doesn't do anything.
let diagnostics = unsafe {
&mut *(self.diagnostics as *mut DiagnosticBag)
};
for block in self.blocks() {
if !block.is_terminated {
diagnostics.report(Diagnostic::non_terminated_block(self.span));
}
}
}
}
impl<'b, 'cx> Display for Builder<'b, 'cx> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
// write name
write!(f, "{} {{\n\n", Paint::white(self.name()).bold())?;
for block in &self.blocks {
block.display(f, self)?;
}
f.write_char('}')
}
}
// //==========================================================================//
// // BLOCK //
// //==========================================================================//
/// A group of `Instr`s prefixed with a block header, which can be jumped to.
/// A block may be identified by a name, and may have parameters.
#[derive(Clone, Debug, PartialEq)]
pub struct Block<'b, 'cx: 'b> {
name: usize,
index: usize,
variables: Vec<Value<'b, 'cx>>,
instructions: Vec<Instr<'b, 'cx>>,
is_terminated: bool,
imm_dominators: Vec<usize>,
argsize: Option<u16>
}
impl<'b, 'cx> Block<'b, 'cx> {
/// Creates a new parameter-less `Block`, given its name symbol.
#[inline]
fn new(index: usize, name: usize, argsize: Option<u16>) -> Self {
Block {
index, name,
variables: Vec::new(),
instructions: Vec::new(),
is_terminated: false,
imm_dominators: Vec::new(),
argsize
}
}
fn clone_to(&self, then: usize, vardiff: u32, origin: &Builder<'b, 'cx>, to: &mut Builder<'b, 'cx>) {
to.position_at_new_block(format!("inlined-{}", self.name(origin)), self.argsize);
// copy variables
for (i, var) in self.variables.iter().enumerate() {
let var = to.new_value(var.size, origin.get_name(var.symbol as _).unwrap(), ValueKind::Variable(false, i as _));
to.vars().push(var);
}
// copy instructions
for mut instr in self.instructions.clone() {
instr.name = to.interner.get_or_intern(origin.get_name(instr.name).unwrap());
for operand in &mut instr.operands {
operand.symbol = to.interner.get_or_intern(origin.get_name(operand.symbol as _).unwrap()) as _;
operand.kind = match operand.kind {
ValueKind::BlockReference(nth) => ValueKind::BlockReference(then as u16 + nth),
ValueKind::Variable(m, nth) => ValueKind::Variable(m, nth + vardiff),
ValueKind::Argument(nth) => ValueKind::Argument(then as u16 + nth),
other => other
};
}
if let Some(call) = instr.as_call() {
to.calls.push(call);
to.instrs().push(instr);
}
else if let Some(ret) = instr.as_ret() {
to.emit_jump(then, Some(ret));
}
else if let Some((jmp, kind)) = instr.as_jmp(origin) {
to.emit_cond_jump(kind, then + jmp, instr.operands().get(1).cloned());
}
else {
assert!(!instr.terminates, "A non-jump / ret instruction cannot terminate.");
to.instrs().push(instr.clone());
}
}
}
/// Returns the index of the block, relative to its parent body.
#[inline]
pub fn index(&self) -> usize {
self.index
}
/// Returns the name of the block.
#[inline]
pub fn name<'a>(&'a self, builder: &'a Builder<'b, 'cx>) -> &'a str {
builder.get_name(self.name).unwrap()
}
/// Returns a slice containing all variables declared in this block.
#[inline]
pub fn variables(&self) -> &[Value<'b, 'cx>] {
&self.variables
}
/// Returns a slice containing all instructions that make up this block.
#[inline]
pub fn instructions(&self) -> &[Instr<'b, 'cx>] {
&self.instructions
}
/// Returns whether the block contains a terminating instruction.
#[inline]
pub fn is_terminated(&self) -> bool {
self.is_terminated
}
/// Returns the dominators of this block.
#[inline]
pub fn dominators(&self) -> &[usize] {
&self.imm_dominators
}
fn display(&self, f: &mut Write, builder: &Builder<'b, 'cx>) -> fmt::Result {
// block header:
writeln!(f, " {}:", Paint::white(builder.get_name(self.name).unwrap()).underline())?;
// instructions:
for ins in &self.instructions {
f.write_str(" ")?;
ins.display(f, builder)?;
f.write_char('\n')?;
}
f.write_str("\n")
}
}
|
use core::cmp::{max, min};
/// Solves the Day 22 Part 1 puzzle with respect to the given input.
pub fn part_1(input: String) {
let steps = parse_input(input)
.into_iter()
.filter(|step| step.cuboid.min_x.abs() <= 50)
.filter(|step| step.cuboid.min_y.abs() <= 50)
.filter(|step| step.cuboid.min_z.abs() <= 50)
.filter(|step| step.cuboid.max_x.abs() <= 51)
.filter(|step| step.cuboid.max_y.abs() <= 51)
.filter(|step| step.cuboid.max_z.abs() <= 51)
.collect();
let cuboids = apply(steps);
let lit = cuboids.iter().map(volume).sum::<i64>();
println!("{}", lit);
}
/// Solves the Day 22 Part 2 puzzle with respect to the given input.
pub fn part_2(input: String) {
let steps = parse_input(input);
let cuboids = apply(steps);
let lit = cuboids.iter().map(volume).sum::<i64>();
println!("{}", lit);
}
struct Step {
action: String,
cuboid: Cuboid,
}
#[derive(Debug)]
struct Cuboid {
min_x: i64,
min_y: i64,
min_z: i64,
max_x: i64,
max_y: i64,
max_z: i64,
}
/// Parses the input to the Day 22 puzzle into a vector of steps.
fn parse_input(input: String) -> Vec<Step> {
let mut steps: Vec<Step> = Vec::new();
for line in input.lines() {
let mut halves = line.split(" ");
let action = halves.next().unwrap();
let bounds = halves.next().unwrap();
let parse_range = |range: &str| -> (i64, i64) {
let suffix: String = range.chars().skip(2).collect();
let mut halves = suffix.split("..");
let lo = halves.next().unwrap().parse::<i64>().unwrap();
let hi = halves.next().unwrap().parse::<i64>().unwrap();
return (lo, hi);
};
let mut coords = bounds.split(",");
let (min_x, max_x) = parse_range(coords.next().unwrap());
let (min_y, max_y) = parse_range(coords.next().unwrap());
let (min_z, max_z) = parse_range(coords.next().unwrap());
let cuboid = Cuboid {
min_x: min_x,
min_y: min_y,
min_z: min_z,
max_x: max_x + 1,
max_y: max_y + 1,
max_z: max_z + 1,
};
let step = Step {
action: action.to_string(),
cuboid: cuboid,
};
steps.push(step);
}
return steps;
}
/// Applies the given steps and returns the remaining (lit) cuboids.
fn apply(steps: Vec<Step>) -> Vec<Cuboid> {
let mut cuboids: Vec<Cuboid> = Vec::new();
for step in steps {
let mut next_cuboids: Vec<Cuboid> = Vec::new();
if step.action == "on" {
let mut parts = vec![step.cuboid];
for cuboid in &cuboids {
let mut next_parts = Vec::new();
for prev_part in parts.drain(..) {
for next_part in intersect(&cuboid, &prev_part) {
next_parts.push(next_part);
}
}
parts = next_parts;
}
for cuboid in cuboids {
next_cuboids.push(cuboid);
}
for part in parts {
next_cuboids.push(part);
}
} else {
for cuboid in cuboids.drain(..) {
for part in intersect(&step.cuboid, &cuboid) {
next_cuboids.push(part);
}
}
}
cuboids = next_cuboids;
}
return cuboids;
}
/// Partitions dst into a set of non-intersecting cuboids such that the returned
/// cuboids cover the same cubes as dst except for those which are also reside
/// in src.
fn intersect(src: &Cuboid, dst: &Cuboid) -> Vec<Cuboid> {
let center = Cuboid {
min_x: max(dst.min_x, min(dst.max_x, src.min_x)),
min_y: max(dst.min_y, min(dst.max_y, src.min_y)),
min_z: max(dst.min_z, min(dst.max_z, src.min_z)),
max_x: min(dst.max_x, max(dst.min_x, src.max_x)),
max_y: min(dst.max_y, max(dst.min_y, src.max_y)),
max_z: min(dst.max_z, max(dst.min_z, src.max_z)),
};
return [
// -Z
Cuboid {
min_x: dst.min_x,
max_x: dst.max_x,
min_y: dst.min_y,
max_y: dst.max_y,
min_z: dst.min_z,
max_z: center.min_z,
},
// +Z
Cuboid {
min_x: dst.min_x,
max_x: dst.max_x,
min_y: dst.min_y,
max_y: dst.max_y,
min_z: center.max_z,
max_z: dst.max_z,
},
// -Y
Cuboid {
min_x: dst.min_x,
max_x: dst.max_x,
min_y: dst.min_y,
max_y: center.min_y,
min_z: center.min_z,
max_z: center.max_z,
},
// +Y
Cuboid {
min_x: dst.min_x,
max_x: dst.max_x,
min_y: center.max_y,
max_y: dst.max_y,
min_z: center.min_z,
max_z: center.max_z,
},
// -X
Cuboid {
min_x: dst.min_x,
max_x: center.min_x,
min_y: center.min_y,
max_y: center.max_y,
min_z: center.min_z,
max_z: center.max_z,
},
// +X
Cuboid {
min_x: center.max_x,
max_x: dst.max_x,
min_y: center.min_y,
max_y: center.max_y,
min_z: center.min_z,
max_z: center.max_z,
},
]
.into_iter()
.filter(|cuboid| volume(cuboid) > 0)
.collect();
}
/// Returns the volume of the given cuboid.
fn volume(cuboid: &Cuboid) -> i64 {
let dx = cuboid.max_x - cuboid.min_x;
let dy = cuboid.max_y - cuboid.min_y;
let dz = cuboid.max_z - cuboid.min_z;
return dx * dy * dz;
}
|
use syscalls::*;
#[test]
fn test_syscall() {
let s = "Hello\0";
assert_eq!(
unsafe { syscall!(Sysno::write, 1, s.as_ptr() as *const _, 6) },
Ok(6)
);
}
#[test]
fn test_syscall_map() {
// Make sure the macro exports are ok
let mut map = SysnoMap::new();
assert!(map.is_empty());
assert_eq!(map.count(), 0);
assert_eq!(map.get(Sysno::write), None);
map.insert(Sysno::write, 42);
assert_eq!(map.get(Sysno::write), Some(&42));
assert_eq!(map.count(), 1);
assert!(!map.is_empty());
map.remove(Sysno::write);
assert_eq!(map.count(), 0);
assert!(map.is_empty());
}
|
#[doc = "Reader of register DDRCTRL_PWRTMG"]
pub type R = crate::R<u32, super::DDRCTRL_PWRTMG>;
#[doc = "Writer for register DDRCTRL_PWRTMG"]
pub type W = crate::W<u32, super::DDRCTRL_PWRTMG>;
#[doc = "Register DDRCTRL_PWRTMG `reset()`'s with value 0x0040_2010"]
impl crate::ResetValue for super::DDRCTRL_PWRTMG {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x0040_2010
}
}
#[doc = "Reader of field `POWERDOWN_TO_X32`"]
pub type POWERDOWN_TO_X32_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `POWERDOWN_TO_X32`"]
pub struct POWERDOWN_TO_X32_W<'a> {
w: &'a mut W,
}
impl<'a> POWERDOWN_TO_X32_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x1f) | ((value as u32) & 0x1f);
self.w
}
}
#[doc = "Reader of field `T_DPD_X4096`"]
pub type T_DPD_X4096_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `T_DPD_X4096`"]
pub struct T_DPD_X4096_W<'a> {
w: &'a mut W,
}
impl<'a> T_DPD_X4096_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xff << 8)) | (((value as u32) & 0xff) << 8);
self.w
}
}
#[doc = "Reader of field `SELFREF_TO_X32`"]
pub type SELFREF_TO_X32_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SELFREF_TO_X32`"]
pub struct SELFREF_TO_X32_W<'a> {
w: &'a mut W,
}
impl<'a> SELFREF_TO_X32_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xff << 16)) | (((value as u32) & 0xff) << 16);
self.w
}
}
impl R {
#[doc = "Bits 0:4 - POWERDOWN_TO_X32"]
#[inline(always)]
pub fn powerdown_to_x32(&self) -> POWERDOWN_TO_X32_R {
POWERDOWN_TO_X32_R::new((self.bits & 0x1f) as u8)
}
#[doc = "Bits 8:15 - T_DPD_X4096"]
#[inline(always)]
pub fn t_dpd_x4096(&self) -> T_DPD_X4096_R {
T_DPD_X4096_R::new(((self.bits >> 8) & 0xff) as u8)
}
#[doc = "Bits 16:23 - SELFREF_TO_X32"]
#[inline(always)]
pub fn selfref_to_x32(&self) -> SELFREF_TO_X32_R {
SELFREF_TO_X32_R::new(((self.bits >> 16) & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:4 - POWERDOWN_TO_X32"]
#[inline(always)]
pub fn powerdown_to_x32(&mut self) -> POWERDOWN_TO_X32_W {
POWERDOWN_TO_X32_W { w: self }
}
#[doc = "Bits 8:15 - T_DPD_X4096"]
#[inline(always)]
pub fn t_dpd_x4096(&mut self) -> T_DPD_X4096_W {
T_DPD_X4096_W { w: self }
}
#[doc = "Bits 16:23 - SELFREF_TO_X32"]
#[inline(always)]
pub fn selfref_to_x32(&mut self) -> SELFREF_TO_X32_W {
SELFREF_TO_X32_W { w: self }
}
}
|
use serde_derive::{
Deserialize,
Serialize,
};
#[derive(Debug, Serialize, Deserialize)]
pub struct Index {
pub name: String,
pub number: i32,
} |
//! <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
//!
//! The OSQP (Operator Splitting Quadratic Program) solver is a numerical optimization package for
//! solving convex quadratic programs in the form
//!
//! <div class="math">
//! \[\begin{split}\begin{array}{ll}
//! \mbox{minimize} & \frac{1}{2} x^T P x + q^T x \\
//! \mbox{subject to} & l \leq A x \leq u
//! \end{array}\end{split}\]
//! </div>
//!
//! <p>
//! where \(x\) is the optimization variable and \(P \in \mathbf{S}^{n}_{+}\) a positive
//! semidefinite matrix.
//! </p>
//!
//! Further information about the solver is available at
//! [osqp.org](https://osqp.org/).
//!
//! # Example
//!
//! Consider the following QP
//!
//! <div class="math">
//! \[\begin{split}\begin{array}{ll}
//! \mbox{minimize} & \frac{1}{2} x^T \begin{bmatrix}4 & 1\\ 1 & 2 \end{bmatrix} x + \begin{bmatrix}1 \\ 1\end{bmatrix}^T x \\
//! \mbox{subject to} & \begin{bmatrix}1 \\ 0 \\ 0\end{bmatrix} \leq \begin{bmatrix} 1 & 1\\ 1 & 0\\ 0 & 1\end{bmatrix} x \leq \begin{bmatrix}1 \\ 0.7 \\ 0.7\end{bmatrix}
//! \end{array}\end{split}\]
//! </div>
//!
//! ```rust
//! use osqp::{CscMatrix, Problem, Settings};
//!
//! // Define problem data
//! let P = &[[4.0, 1.0],
//! [1.0, 2.0]];
//! let q = &[1.0, 1.0];
//! let A = &[[1.0, 1.0],
//! [1.0, 0.0],
//! [0.0, 1.0]];
//! let l = &[1.0, 0.0, 0.0];
//! let u = &[1.0, 0.7, 0.7];
//!
//! // Extract the upper triangular elements of `P`
//! let P = CscMatrix::from(P).into_upper_tri();
//!
//! // Disable verbose output
//! let settings = Settings::default()
//! .verbose(false);
//! # let settings = settings.adaptive_rho(false);
//!
//! // Create an OSQP problem
//! let mut prob = Problem::new(P, q, A, l, u, &settings).expect("failed to setup problem");
//!
//! // Solve problem
//! let result = prob.solve();
//!
//! // Print the solution
//! println!("{:?}", result.x().expect("failed to solve problem"));
//! #
//! # // Check the solution
//! # let expected = &[0.30137570387082474, 0.6983956863817343];
//! # let x = result.solution().unwrap().x();
//! # assert_eq!(expected.len(), x.len());
//! # assert!(expected.iter().zip(x).all(|(&a, &b)| (a - b).abs() < 1e-9));
//! ```
extern crate osqp_sys;
use osqp_sys as ffi;
use std::error::Error;
use std::fmt;
use std::ptr;
mod csc;
pub use csc::CscMatrix;
mod settings;
pub use settings::{LinsysSolver, Settings};
mod status;
pub use status::{
DualInfeasibilityCertificate, Failure, PolishStatus, PrimalInfeasibilityCertificate, Solution,
Status,
};
#[allow(non_camel_case_types)]
type float = f64;
// Ensure osqp_int is the same size as usize/isize.
#[allow(dead_code)]
fn assert_osqp_int_size() {
let _osqp_int_must_be_usize = ::std::mem::transmute::<ffi::osqp_int, usize>;
}
macro_rules! check {
($fun:ident, $ret:expr) => {
assert!(
$ret == 0,
"osqp_{} failed with exit code {}",
stringify!($fun),
$ret
);
};
}
/// An instance of the OSQP solver.
pub struct Problem {
workspace: *mut ffi::OSQPWorkspace,
/// Number of variables
n: usize,
/// Number of constraints
m: usize,
}
impl Problem {
/// Initialises the solver and validates the problem.
///
/// Returns an error if the problem is non-convex or the solver cannot be initialised.
///
/// Panics if any of the matrix or vector dimensions are incompatible, if `P` or `A` are not
/// valid CSC matrices, or if `P` is not structurally upper triangular.
#[allow(non_snake_case)]
pub fn new<'a, 'b, T: Into<CscMatrix<'a>>, U: Into<CscMatrix<'b>>>(
P: T,
q: &[float],
A: U,
l: &[float],
u: &[float],
settings: &Settings,
) -> Result<Problem, SetupError> {
// Function split to avoid monomorphising the main body of Problem::new.
Problem::new_inner(P.into(), q, A.into(), l, u, settings)
}
#[allow(non_snake_case)]
fn new_inner(
P: CscMatrix,
q: &[float],
A: CscMatrix,
l: &[float],
u: &[float],
settings: &Settings,
) -> Result<Problem, SetupError> {
let invalid_data = |msg| Err(SetupError::DataInvalid(msg));
unsafe {
// Ensure the provided data is valid. While OSQP internally performs some validity
// checks it can be made to read outside the provided buffers so all the invariants
// are checked here.
// Dimensions must be consistent with the number of variables
let n = P.nrows;
if P.ncols != n {
return invalid_data("P must be a square matrix");
}
if q.len() != n {
return invalid_data("q must be the same number of rows as P");
}
if A.ncols != n {
return invalid_data("A must have the same number of columns as P");
}
// Dimensions must be consistent with the number of constraints
let m = A.nrows;
if l.len() != m {
return invalid_data("l must have the same number of rows as A");
}
if u.len() != m {
return invalid_data("u must have the same number of rows as A");
}
if l.iter().zip(u.iter()).any(|(&l, &u)| !(l <= u)) {
return invalid_data("all elements of l must be less than or equal to the corresponding element of u");
}
// `A` and `P` must be valid CSC matrices and `P` must be structurally upper triangular
if !P.is_valid() {
return invalid_data("P must be a valid CSC matrix");
}
if !A.is_valid() {
return invalid_data("A must be a valid CSC matrix");
}
if !P.is_structurally_upper_tri() {
return invalid_data("P must be structurally upper triangular");
}
// Calling `to_ffi` is safe as we have ensured that `P` and `A` are valid CSC matrices.
let mut P_ffi = P.to_ffi();
let mut A_ffi = A.to_ffi();
let data = ffi::OSQPData {
n: n as ffi::osqp_int,
m: m as ffi::osqp_int,
P: &mut P_ffi,
A: &mut A_ffi,
q: q.as_ptr() as *mut float,
l: l.as_ptr() as *mut float,
u: u.as_ptr() as *mut float,
};
let settings = &settings.inner as *const ffi::OSQPSettings as *mut ffi::OSQPSettings;
let mut workspace: *mut ffi::OSQPWorkspace = ptr::null_mut();
let status = ffi::osqp_setup(&mut workspace, &data, settings);
let err = match status as ffi::osqp_error_type {
0 => return Ok(Problem { workspace, n, m }),
ffi::OSQP_DATA_VALIDATION_ERROR => SetupError::DataInvalid(""),
ffi::OSQP_SETTINGS_VALIDATION_ERROR => SetupError::SettingsInvalid,
ffi::OSQP_LINSYS_SOLVER_LOAD_ERROR => SetupError::LinsysSolverLoadFailed,
ffi::OSQP_LINSYS_SOLVER_INIT_ERROR => SetupError::LinsysSolverInitFailed,
ffi::OSQP_NONCVX_ERROR => SetupError::NonConvex,
ffi::OSQP_MEM_ALLOC_ERROR => SetupError::MemoryAllocationFailed,
_ => unreachable!(),
};
// If the call to `osqp_setup` fails the `OSQPWorkspace` may be partially allocated
if !workspace.is_null() {
ffi::osqp_cleanup(workspace);
}
Err(err)
}
}
/// Sets the linear part of the cost function to `q`.
///
/// Panics if the length of `q` is not the same as the number of problem variables.
pub fn update_lin_cost(&mut self, q: &[float]) {
unsafe {
assert_eq!(self.n, q.len());
check!(
update_lin_cost,
ffi::osqp_update_lin_cost(self.workspace, q.as_ptr())
);
}
}
/// Sets the lower and upper bounds of the constraints to `l` and `u`.
///
/// Panics if the length of `l` or `u` is not the same as the number of problem constraints.
pub fn update_bounds(&mut self, l: &[float], u: &[float]) {
unsafe {
assert_eq!(self.m, l.len());
assert_eq!(self.m, u.len());
check!(
update_bounds,
ffi::osqp_update_bounds(self.workspace, l.as_ptr(), u.as_ptr())
);
}
}
/// Sets the lower bound of the constraints to `l`.
///
/// Panics if the length of `l` is not the same as the number of problem constraints.
pub fn update_lower_bound(&mut self, l: &[float]) {
unsafe {
assert_eq!(self.m, l.len());
check!(
update_lower_bound,
ffi::osqp_update_lower_bound(self.workspace, l.as_ptr())
);
}
}
/// Sets the upper bound of the constraints to `u`.
///
/// Panics if the length of `u` is not the same as the number of problem constraints.
pub fn update_upper_bound(&mut self, u: &[float]) {
unsafe {
assert_eq!(self.m, u.len());
check!(
update_upper_bound,
ffi::osqp_update_upper_bound(self.workspace, u.as_ptr())
);
}
}
/// Warm starts the primal variables at `x` and the dual variables at `y`.
///
/// Panics if the length of `x` is not the same as the number of problem variables or the
/// length of `y` is not the same as the number of problem constraints.
pub fn warm_start(&mut self, x: &[float], y: &[float]) {
unsafe {
assert_eq!(self.n, x.len());
assert_eq!(self.m, y.len());
check!(
warm_start,
ffi::osqp_warm_start(self.workspace, x.as_ptr(), y.as_ptr())
);
}
}
/// Warm starts the primal variables at `x`.
///
/// Panics if the length of `x` is not the same as the number of problem variables.
pub fn warm_start_x(&mut self, x: &[float]) {
unsafe {
assert_eq!(self.n, x.len());
check!(
warm_start_x,
ffi::osqp_warm_start_x(self.workspace, x.as_ptr())
);
}
}
/// Warms start the dual variables at `y`.
///
/// Panics if the length of `y` is not the same as the number of problem constraints.
pub fn warm_start_y(&mut self, y: &[float]) {
unsafe {
assert_eq!(self.m, y.len());
check!(
warm_start_y,
ffi::osqp_warm_start_y(self.workspace, y.as_ptr())
);
}
}
/// Updates the elements of matrix `P` without changing its sparsity structure.
///
/// Panics if the sparsity structure of `P` differs from the sparsity structure of the `P`
/// matrix provided to `Problem::new`.
#[allow(non_snake_case)]
pub fn update_P<'a, T: Into<CscMatrix<'a>>>(&mut self, P: T) {
self.update_P_inner(P.into());
}
#[allow(non_snake_case)]
fn update_P_inner(&mut self, P: CscMatrix) {
unsafe {
let P_ffi = CscMatrix::from_ffi((*(*self.workspace).data).P);
P.assert_same_sparsity_structure(&P_ffi);
check!(
update_P,
ffi::osqp_update_P(
self.workspace,
P.data.as_ptr(),
ptr::null(),
P.data.len() as ffi::osqp_int,
)
);
}
}
/// Updates the elements of matrix `A` without changing its sparsity structure.
///
/// Panics if the sparsity structure of `A` differs from the sparsity structure of the `A`
/// matrix provided to `Problem::new`.
#[allow(non_snake_case)]
pub fn update_A<'a, T: Into<CscMatrix<'a>>>(&mut self, A: T) {
self.update_A_inner(A.into());
}
#[allow(non_snake_case)]
fn update_A_inner(&mut self, A: CscMatrix) {
unsafe {
let A_ffi = CscMatrix::from_ffi((*(*self.workspace).data).A);
A.assert_same_sparsity_structure(&A_ffi);
check!(
update_A,
ffi::osqp_update_A(
self.workspace,
A.data.as_ptr(),
ptr::null(),
A.data.len() as ffi::osqp_int,
)
);
}
}
/// Updates the elements of matrices `P` and `A` without changing either's sparsity structure.
///
/// Panics if the sparsity structure of `P` or `A` differs from the sparsity structure of the
/// `P` or `A` matrices provided to `Problem::new`.
#[allow(non_snake_case)]
pub fn update_P_A<'a, 'b, T: Into<CscMatrix<'a>>, U: Into<CscMatrix<'b>>>(
&mut self,
P: T,
A: U,
) {
self.update_P_A_inner(P.into(), A.into());
}
#[allow(non_snake_case)]
fn update_P_A_inner(&mut self, P: CscMatrix, A: CscMatrix) {
unsafe {
let P_ffi = CscMatrix::from_ffi((*(*self.workspace).data).P);
P.assert_same_sparsity_structure(&P_ffi);
let A_ffi = CscMatrix::from_ffi((*(*self.workspace).data).A);
A.assert_same_sparsity_structure(&A_ffi);
check!(
update_P_A,
ffi::osqp_update_P_A(
self.workspace,
P.data.as_ptr(),
ptr::null(),
P.data.len() as ffi::osqp_int,
A.data.as_ptr(),
ptr::null(),
A.data.len() as ffi::osqp_int,
)
);
}
}
/// Attempts to solve the quadratic program.
pub fn solve<'a>(&'a mut self) -> Status<'a> {
unsafe {
check!(solve, ffi::osqp_solve(self.workspace));
Status::from_problem(self)
}
}
}
impl Drop for Problem {
fn drop(&mut self) {
unsafe {
ffi::osqp_cleanup(self.workspace);
}
}
}
unsafe impl Send for Problem {}
unsafe impl Sync for Problem {}
/// An error that can occur when setting up the solver.
#[derive(Debug)]
pub enum SetupError {
DataInvalid(&'static str),
SettingsInvalid,
LinsysSolverLoadFailed,
LinsysSolverInitFailed,
NonConvex,
MemoryAllocationFailed,
// Prevent exhaustive enum matching
#[doc(hidden)]
__Nonexhaustive,
}
impl fmt::Display for SetupError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SetupError::DataInvalid(msg) => {
"problem data invalid".fmt(f)?;
if !msg.is_empty() {
": ".fmt(f)?;
msg.fmt(f)?;
}
Ok(())
}
SetupError::SettingsInvalid => "problem settings invalid".fmt(f),
SetupError::LinsysSolverLoadFailed => "linear system solver failed to load".fmt(f),
SetupError::LinsysSolverInitFailed => {
"linear system solver failed to initialise".fmt(f)
}
SetupError::NonConvex => "problem non-convex".fmt(f),
SetupError::MemoryAllocationFailed => "memory allocation failed".fmt(f),
SetupError::__Nonexhaustive => unreachable!(),
}
}
}
impl Error for SetupError {}
#[cfg(test)]
mod tests {
use std::iter;
use super::*;
#[test]
#[allow(non_snake_case)]
fn update_matrices() {
// Define problem data
let P_wrong = CscMatrix::from(&[[2.0, 1.0], [1.0, 4.0]]).into_upper_tri();
let A_wrong = &[[2.0, 3.0], [1.0, 0.0], [0.0, 9.0]];
let P = CscMatrix::from(&[[4.0, 1.0], [1.0, 2.0]]).into_upper_tri();
let q = &[1.0, 1.0];
let A = &[[1.0, 1.0], [1.0, 0.0], [0.0, 1.0]];
let l = &[1.0, 0.0, 0.0];
let u = &[1.0, 0.7, 0.7];
// Change the default alpha and disable verbose output
let settings = Settings::default().alpha(1.0).verbose(false);
let settings = settings.adaptive_rho(false);
// Check updating P and A together
let mut prob = Problem::new(&P_wrong, q, A_wrong, l, u, &settings).unwrap();
prob.update_P_A(&P, A);
let result = prob.solve();
let x = result.solution().unwrap().x();
let expected = &[0.2987710845986426, 0.701227995544065];
assert_eq!(expected.len(), x.len());
assert!(expected.iter().zip(x).all(|(&a, &b)| (a - b).abs() < 1e-9));
// Check updating P and A separately
let mut prob = Problem::new(&P_wrong, q, A_wrong, l, u, &settings).unwrap();
prob.update_P(&P);
prob.update_A(A);
let result = prob.solve();
let x = result.solution().unwrap().x();
let expected = &[0.2987710845986426, 0.701227995544065];
assert_eq!(expected.len(), x.len());
assert!(expected.iter().zip(x).all(|(&a, &b)| (a - b).abs() < 1e-9));
}
#[test]
#[allow(non_snake_case)]
fn empty_A() {
let P = CscMatrix::from(&[[4.0, 1.0], [1.0, 2.0]]).into_upper_tri();
let q = &[1.0, 1.0];
let A = CscMatrix::from_column_iter_dense(0, 2, iter::empty());
let l = &[];
let u = &[];
let mut prob = Problem::new(&P, q, &A, l, u, &Settings::default()).unwrap();
prob.update_A(&A);
let A = CscMatrix::from(&[[0.0, 0.0], [0.0, 0.0]]);
assert_eq!(A.data.len(), 0);
let l = &[0.0, 0.0];
let u = &[1.0, 1.0];
let mut prob = Problem::new(&P, q, &A, l, u, &Settings::default()).unwrap();
prob.update_A(&A);
}
}
|
/// Search for an element in a sorted array using binary search
///
/// # Parameters
///
/// - `target`: The element to find
/// - `arr`: A vector to search the element in
///
/// # Type parameters
///
/// - `T`: A type that can be checked for equality and ordering e.g. a `i32`, a
/// `u8`, or a `f32`.
///
/// # Examples
///
/// ```rust
/// use algorithmplus::search::binary_search;
///
/// let ls = vec![1, 7, 9, 11, 12];
/// let idx = binary_search(&7, &ls).unwrap_or_default();
///
/// assert_eq!(idx, 1);
/// ```
///
/// ```rust
/// use algorithmplus::search::binary_search;
///
/// let ls = vec![1, 7, 9, 11, 12];
/// let idx = binary_search(&8, &ls);
///
/// assert_eq!(idx, None);
/// ```
pub fn binary_search<T: PartialEq + PartialOrd>(target: &T, arr: &[T]) -> Option<usize> {
let mut left = 0;
let arr_len = arr.len();
if arr_len == 0 {
return None;
}
let mut right = arr_len - 1;
if &arr[left] > target || &arr[right] < target {
return None;
}
while left <= right {
let mid = left + (right - left) / 2;
if &arr[mid] > target {
right = mid - 1;
} else if &arr[mid] < target {
left = mid + 1;
} else {
return Some(mid);
}
}
None
}
|
use fltk::{
app, dialog,
enums::{CallbackTrigger, Color, Event, Font, FrameType, Shortcut},
menu,
prelude::*,
printer, text, window,
};
use std::{
error,
ops::{Deref, DerefMut},
panic, path,
};
#[derive(Copy, Clone)]
pub enum Message {
Changed,
New,
Open,
Save,
SaveAs,
Print,
Quit,
Cut,
Copy,
Paste,
About,
}
pub fn center() -> (i32, i32) {
(
(app::screen_size().0 / 2.0) as i32,
(app::screen_size().1 / 2.0) as i32,
)
}
pub struct MyEditor {
editor: text::TextEditor,
}
impl MyEditor {
pub fn new(buf: text::TextBuffer) -> Self {
let mut editor = text::TextEditor::new(5, 35, 790, 560, "");
editor.set_buffer(Some(buf));
#[cfg(target_os = "macos")]
editor.resize(5, 5, 790, 590);
editor.set_scrollbar_size(15);
editor.set_text_font(Font::Courier);
editor.set_linenumber_width(32);
editor.set_linenumber_fgcolor(Color::from_u32(0x008b_8386));
editor.set_trigger(CallbackTrigger::Changed);
Self { editor }
}
}
impl Deref for MyEditor {
type Target = text::TextEditor;
fn deref(&self) -> &Self::Target {
&self.editor
}
}
impl DerefMut for MyEditor {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.editor
}
}
pub struct MyMenu {
_menu: menu::SysMenuBar,
}
impl MyMenu {
pub fn new(s: &app::Sender<Message>) -> Self {
let mut menu = menu::SysMenuBar::default().with_size(800, 35);
menu.set_frame(FrameType::FlatBox);
menu.add_emit(
"&File/New...\t",
Shortcut::Ctrl | 'n',
menu::MenuFlag::Normal,
*s,
Message::New,
);
menu.add_emit(
"&File/Open...\t",
Shortcut::Ctrl | 'o',
menu::MenuFlag::Normal,
*s,
Message::Open,
);
menu.add_emit(
"&File/Save\t",
Shortcut::Ctrl | 's',
menu::MenuFlag::Normal,
*s,
Message::Save,
);
menu.add_emit(
"&File/Save as...\t",
Shortcut::Ctrl | 'w',
menu::MenuFlag::Normal,
*s,
Message::SaveAs,
);
menu.add_emit(
"&File/Print...\t",
Shortcut::Ctrl | 'p',
menu::MenuFlag::MenuDivider,
*s,
Message::Print,
);
menu.add_emit(
"&File/Quit\t",
Shortcut::Ctrl | 'q',
menu::MenuFlag::Normal,
*s,
Message::Quit,
);
menu.add_emit(
"&Edit/Cut\t",
Shortcut::Ctrl | 'x',
menu::MenuFlag::Normal,
*s,
Message::Cut,
);
menu.add_emit(
"&Edit/Copy\t",
Shortcut::Ctrl | 'c',
menu::MenuFlag::Normal,
*s,
Message::Copy,
);
menu.add_emit(
"&Edit/Paste\t",
Shortcut::Ctrl | 'v',
menu::MenuFlag::Normal,
*s,
Message::Paste,
);
menu.add_emit(
"&Help/About\t",
Shortcut::None,
menu::MenuFlag::Normal,
*s,
Message::About,
);
if let Some(mut item) = menu.find_item("&File/Quit\t") {
item.set_label_color(Color::Red);
}
Self { _menu: menu }
}
}
pub struct MyApp {
app: app::App,
saved: bool,
filename: String,
r: app::Receiver<Message>,
buf: text::TextBuffer,
editor: MyEditor,
printable: text::TextDisplay,
}
impl MyApp {
pub fn new(args: Vec<String>) -> Self {
let app = app::App::default().with_scheme(app::Scheme::Gtk);
app::background(211, 211, 211);
let (s, r) = app::channel::<Message>();
let mut buf = text::TextBuffer::default();
buf.set_tab_distance(4);
let mut main_win = window::Window::default()
.with_size(800, 600)
.center_screen()
.with_label("RustyEd");
let _menu = MyMenu::new(&s);
let mut editor = MyEditor::new(buf.clone());
editor.emit(s, Message::Changed);
main_win.make_resizable(true);
// only resize editor, not the menu bar
main_win.resizable(&*editor);
main_win.end();
main_win.show();
main_win.set_callback(move |_| {
if app::event() == Event::Close {
s.send(Message::Quit);
}
});
let filename = if args.len() > 1 {
let file = path::Path::new(&args[1]);
assert!(
file.exists() && file.is_file(),
"An error occured while opening the file!"
);
buf.load_file(&args[1]).unwrap();
args[1].clone()
} else {
String::new()
};
// Handle drag and drop
editor.handle({
let mut dnd = false;
let mut released = false;
let mut buf = buf.clone();
move |_, ev| match ev {
Event::DndEnter => {
dnd = true;
true
}
Event::DndDrag => true,
Event::DndRelease => {
released = true;
true
}
Event::Paste => {
if dnd && released {
let path = app::event_text();
let path = std::path::Path::new(&path);
assert!(path.exists());
buf.load_file(&path).unwrap();
dnd = false;
released = false;
true
} else {
false
}
}
Event::DndLeave => {
dnd = false;
released = false;
true
}
_ => false,
}
});
// What shows when we attempt to print
let mut printable = text::TextDisplay::default();
printable.set_frame(FrameType::NoBox);
printable.set_scrollbar_size(0);
printable.set_buffer(Some(buf.clone()));
Self {
app,
saved: true,
filename,
r,
buf,
editor,
printable,
}
}
pub fn save_file(&mut self) -> Result<(), Box<dyn error::Error>> {
let mut filename = self.filename.clone();
if self.saved {
if filename.is_empty() {
let mut dlg = dialog::FileDialog::new(dialog::FileDialogType::BrowseSaveFile);
dlg.set_option(dialog::FileDialogOptions::SaveAsConfirm);
dlg.show();
filename = dlg.filename().to_string_lossy().to_string();
if !filename.is_empty() {
self.buf.save_file(&filename).unwrap_or_else(|_| {
dialog::alert(center().0 - 200, center().1 - 100, "Please specify a file!")
});
self.saved = true;
}
} else if path::Path::new(&filename).exists() {
self.buf.save_file(&filename)?;
self.saved = true;
} else {
dialog::alert(center().0 - 200, center().1 - 100, "Please specify a file!")
}
} else {
let mut dlg = dialog::FileDialog::new(dialog::FileDialogType::BrowseSaveFile);
dlg.set_option(dialog::FileDialogOptions::SaveAsConfirm);
dlg.show();
filename = dlg.filename().to_string_lossy().to_string();
if !filename.is_empty() {
self.buf.save_file(&filename).unwrap_or_else(|_| {
dialog::alert(center().0 - 200, center().1 - 100, "Please specify a file!")
});
self.saved = true;
}
}
Ok(())
}
pub fn launch(&mut self) {
while self.app.wait() {
use Message::*;
if let Some(msg) = self.r.recv() {
match msg {
Changed => self.saved = false,
New => {
if self.buf.text() != "" {
let x = dialog::choice(center().0 - 200, center().1 - 100, "File unsaved, Do you wish to continue?", "Yes", "No!", "");
if x == 0 {
self.buf.set_text("");
}
}
},
Open => {
let mut dlg = dialog::FileDialog::new(dialog::FileDialogType::BrowseFile);
dlg.set_option(dialog::FileDialogOptions::NoOptions);
dlg.set_filter("*.{txt,rs,toml}");
dlg.show();
let filename = dlg.filename().to_string_lossy().to_string();
if !filename.is_empty() {
if path::Path::new(&filename).exists() { self.buf.load_file(&filename).unwrap(); self.filename = filename; } else { dialog::alert(center().0 - 200, center().1 - 100, "File does not exist!") }
}
},
Save | SaveAs => self.save_file().unwrap(),
Print => {
let mut printer = printer::Printer::default();
if printer.begin_job(0).is_ok() {
let (w, h) = printer.printable_rect();
self.printable.set_size(w - 40, h - 40);
// Needs cleanup
let line_count = self.printable.count_lines(0, self.printable.buffer().unwrap().length(), true) / 45;
for i in 0..=line_count {
self.printable.scroll(45 * i, 0);
printer.begin_page().ok();
printer.print_widget(&self.printable, 20, 20);
printer.end_page().ok();
}
printer.end_job();
}
},
Quit => {
if self.saved {
self.app.quit();
} else {
let x = dialog::choice(center().0 - 200, center().1 - 100, "Would you like to save your work?", "Yes", "No", "");
if x == 0 {
self.save_file().unwrap();
self.app.quit();
} else {
self.app.quit();
}
}
},
Cut => self.editor.cut(),
Copy => self.editor.copy(),
Paste => self.editor.paste(),
About => dialog::message(center().0 - 300, center().1 - 100, "This is an example application written in Rust and using the FLTK Gui library."),
}
}
}
}
}
fn main() {
panic::set_hook(Box::new(|info| {
if let Some(s) = info.payload().downcast_ref::<&str>() {
dialog::message(center().0 - 200, center().1 - 100, s);
} else {
dialog::message(center().0 - 200, center().1 - 100, &info.to_string());
}
}));
let args: Vec<_> = std::env::args().collect();
let mut app = MyApp::new(args);
app.launch();
}
|
use anyhow::Result;
use tree_traversal::run;
fn main() -> Result<()> {
run()
}
|
//! # The Chain Library
//!
//! This Library contains the `ChainProvider` traits and `Chain` implement:
//!
//! - [ChainProvider](chain::chain::ChainProvider) provide index
//! and store interface.
//! - [Chain](chain::chain::Chain) represent a struct which
//! implement `ChainProvider`
pub mod cell_set;
pub mod chain_state;
pub mod error;
pub mod shared;
pub mod tx_pool;
mod tx_proposal_table;
// These tests are from testnet data dump, they are hard to maintenance.
// Although they pass curruent unit tests, we still comment out here,
// Keep the code for future unit test refactoring reference.
// #[cfg(test)]
// mod tests;
|
/*
chapter 4
primitive types
booleans
*/
fn main() {
let a = true;
println!("{}", a);
let b: bool = false;
println!("{}", b);
}
// output should be:
/*
true
false
*/
|
use universe::planet::Planet;
use rand::{Rng, SeedableRng, StdRng};
use nalgebra::geometry::Point3;
pub struct Star{
pub star_type: u32,
pub name: String,
pub coords: Point3<usize>,
pub surf_temperature: u32,
pub planets: Vec<Planet>
}
impl Star{
pub fn gen(coords: Point3<usize>, seed: &[usize]) -> Option<Star>{
let seed: &[usize] = &[seed[0] + coords[0], seed[1] + coords[1], seed[2] + coords[2]];
let mut rng: StdRng = SeedableRng::from_seed(seed);
let exist = rng.gen_range(0, 2);
if exist == 1{
let st_type = rng.gen_range(0, 3);
let surf_temperature = rng.gen_range(1000, 20000);
let name = gen_star_name(&[seed[0] + coords[0], seed[1] + coords[1], seed[2] + coords[2]]);
let mut planets = vec![];
for x in 1..rng.gen_range(0, 30){
planets.push(Planet::gen(x, seed, surf_temperature, name.clone()));
}
Some(Star{
star_type: st_type,
name: name,
coords: coords,
surf_temperature: surf_temperature,
planets: planets
})
}
else{
None
}
}
#[allow(dead_code)]
pub fn print_stats(&self){
println!("{}:", self.name);
println!(" Coords: {} {} {}", self.coords[0], self.coords[1], self.coords[2]);
println!(" Type: {}", self.star_type);
println!(" Temperature: {}°C", self.surf_temperature);
println!(" Planets:");
for x in &self.planets{
println!(" {}: {} {} AU {}°C", x.num, x.name, x.orbit, x.temperature);
}
}
}
pub fn gen_star_name(seed: &[usize]) -> String{
let mut rng: StdRng = SeedableRng::from_seed(seed);
let range = rng.gen_range(0, 5);
let range2 = rng.gen_range(0, 1000);
let name = match range{
0 => "Beta",
1 => "Alpha",
2 => "CX",
3 => "BG",
4 => "Zaxs",
5 => "SEV",
_ => "ERROR"
};
format!("{} {}", name, range2)
}
|
use std::{mem, ops::DerefMut, panic::panic_any, sync::Arc, time::Duration};
use tokio::{
select,
sync::{Mutex, Notify},
task::JoinHandle,
time::sleep,
};
use crate::{
connection::{Settings, SingleConnection},
error::RconError::{self, BusyReconnecting, IO},
reconnect::Status::{Connected, Disconnected, Stopped},
};
enum Status {
Connected(SingleConnection),
Disconnected(String),
Stopped,
}
struct Internal {
status: Mutex<Status>,
close_connection: Notify,
}
/// Drop-in replacement wrapper of [`Connection`](struct.Connection.html) which intercepts all [`IO errors`](enum.Error.html#variant.IO)
/// returned by [`Connection::exec`](struct.Connection.html#method.exec) to start the reconnection thread, and will opt to return [`BusyReconnecting`](enum.Error.html#variant.BusyReconnecting)
/// instead.
///
/// For further docs, refer to [`Connection`](struct.Connection.html), as it shares the same API.
pub struct ReconnectingConnection {
address: String,
pass: String,
settings: Settings,
internal: Arc<Internal>,
reconnect_loop: Option<JoinHandle<()>>,
}
impl ReconnectingConnection {
/// This function behaves identical to [`Connection::open`](struct.Connection.html#method.open).
pub async fn open(address: impl ToString, pass: impl ToString, settings: Settings) -> Result<Self, RconError> {
let address = address.to_string();
let pass = pass.to_string();
let status = Mutex::new(Connected(
SingleConnection::open(address.clone(), pass.clone(), settings.clone()).await?,
));
let internal = Arc::new(Internal {
status,
close_connection: Notify::new(),
});
Ok(ReconnectingConnection {
address,
pass,
settings,
internal,
reconnect_loop: None,
})
}
/// This function behaves identical to [`Connection::exec`](struct.Connection.html#method.exec) unless `Err([IO](enum.Error.html#variant.IO))` is returned,
/// in which case it will start reconnecting and return [`BusyReconnecting`](enum.Error.html#variant.BusyReconnecting) until the connection has been re-established.
pub async fn exec(&mut self, cmd: impl ToString) -> Result<String, RconError> {
// First, we check if we are actively reconnecting, this must be done within a Mutex
let result = {
let mut lock = self.internal.status.lock().await;
let connection = match lock.deref_mut() {
Connected(ref mut c) => c,
Disconnected(msg) => return Err(BusyReconnecting(msg.clone())),
Stopped => unreachable!("should only set Stopped state when closing connection"),
};
// If we are connected, send the request
connection.exec(cmd).await
};
// If the result is an IO error, trigger reconnection and return BusyReconnecting
if let Err(IO(_)) = result {
return Err(self.start_reconnect(result.unwrap_err()).await);
}
result
}
/// Closes the connection, joining any background tasks that were spawned to help manage it.
pub async fn close(mut self) {
{
let mut lock = self.internal.status.lock().await;
if let Connected(connection) = mem::replace(&mut *lock, Status::Stopped) {
connection.close().await;
}
}
self.internal.close_connection.notify_one();
if let Some(handle) = self.reconnect_loop.take() {
handle.await.unwrap_or_else(|e| match e.is_cancelled() {
true => (), // Cancellation is fine.
false => panic_any(e.into_panic()),
});
}
}
async fn start_reconnect(&mut self, e: RconError) -> RconError {
// First, we change the status, which automatically disconnects the old connection
{
let mut lock = self.internal.status.lock().await;
*lock = Disconnected(e.to_string());
}
self.reconnect_loop = Some(tokio::spawn(Self::reconnect_loop(
self.address.clone(),
self.pass.clone(),
self.settings.clone(),
self.internal.clone(),
)));
BusyReconnecting(e.to_string())
}
async fn reconnect_loop(address: String, pass: String, settings: Settings, internal: Arc<Internal>) {
loop {
let close_connection = internal.close_connection.notified();
let connection = SingleConnection::open(address.clone(), pass.clone(), settings.clone());
select! {
Ok(c) = connection => {
let mut lock = internal.status.lock().await;
match *lock {
Stopped => c.close().await,
_ => {
*lock = Connected(c);
}
}
return;
},
_ = close_connection => return,
else => (), // Connection error
};
let close_connection = internal.close_connection.notified();
select! {
_ = sleep(Duration::from_secs(1)) => (),
_ = close_connection => return,
};
}
}
}
|
#![feature(plugin)]
#![feature(duration_float)]
extern crate pest;
#[macro_use]
extern crate pest_derive;
extern crate inference;
extern crate libc;
extern crate llvm_sys;
mod array;
mod ast;
mod compiler;
mod error;
mod expressions;
mod function_loader;
mod llvm_builder;
mod llvm_codegen;
mod loader;
mod macros;
mod parser;
mod stdlib;
mod type_annotator;
mod types;
mod workflow;
use self::array::Array;
use self::ast::Token;
use self::compiler::CompilerData;
use self::error::{DispError, DispResult, GenericError, GenericResult};
use self::types::{Type, TypeSet};
// Exporting all functions publicy, so they will
// be discovered by llvm.
use self::expressions::{get_builtin_expressions, BuiltinExpressions};
use self::function_loader::{parse_functions_and_macros, FunctionMap, UnparsedFunction};
use self::llvm_builder::{Builder, LLVMInstruction};
pub use self::llvm_codegen::{
build_functions, to_ptr, CodegenError, Compiler, Context, Function, FunctionType, LLVMCompiler,
LLVMTypeCache, NativeFunction, Object, Scope,
};
use self::loader::load_file;
use self::macros::{apply_macros_to_function_map, parse_macro, MacroMap};
use self::parser::parse;
use self::stdlib::LIB_FILE;
use self::type_annotator::{
annotate_types, AnnotatedFunction, AnnotatedFunctionMap, TypecheckType, TypevarFunction,
AnnotatorScope
};
use self::workflow::load_string_into_compiler;
use std::{
env,
fs::File,
io::{self, Read, Write},
};
// use stdlib::load_stdlib;
fn main() {
let args: Vec<String> = env::args().collect();
let result = match args.len() {
2 => execute(&args[1]),
_ => {panic!("no repl atm.")}
// _ => repl(),
};
if let Err(ref message) = result {
panic!("{}", message);
}
}
fn execute(path: &str) -> Result<(), GenericError> {
let mut compiler = Compiler::new();
let mut input = String::new();
// load the standard lib
let mut stdlib = File::open(LIB_FILE)?;
stdlib.read_to_string(&mut input)?;
// load the main file
let mut file = File::open(path)?;
file.read_to_string(&mut input)?;
load_string_into_compiler(&mut compiler, &input)?;
Ok(())
}
fn read() -> Result<Token, GenericError> {
std::io::stdout().write(b">>> ")?;
std::io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
input = input.replace("\n", "");
Ok(parse_with_print(&input))
}
/// Parse the body in question, and wrap in a print statement
fn parse_with_print(body: &str) -> Token {
let input = parse(&body);
Token::Expression(vec![
Token::Symbol(Box::new(String::from("println"))),
input,
])
}
|
//! # Cargo And Crates
//!
//! `cargo_and_crates` is a collection of utilities to make performing certain
//! calculations more convenient.
pub mod kinds;
pub mod utils;
pub use kinds::PrimaryColor;
pub use kinds::SecondaryColor;
pub use utils::mix;
/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, cargo_and_crates::add_one(five));
/// ```
pub fn add_one(x: i32) -> i32 {
add(x, 1)
}
fn add(x: i32, y: i32) -> i32 {
x + y
}
|
#[derive(Queryable)]
pub struct User {
pub id: i32,
pub username: String,
pub password: Option<String>,
pub firstname: Option<String>,
pub lastname: Option<String>,
pub userlevel: i32,
pub email: Option<String>,
pub editable: i32,
pub salt: Option<String>,
}
|
use superslice::Ext;
pub trait LineIndex {
/// returns line number for given offset
fn line(&self, offset: usize) -> Option<usize>;
/// returns char offset of given line index
fn offset(&self, line: usize) -> Option<usize>;
}
pub struct LinearLineIndex {
line_offsets: Vec<usize>,
len: usize
}
impl LinearLineIndex {
pub fn new(text: &str) -> Self {
LinearLineIndex {
line_offsets: LinearLineIndex::calculate_offsets(text),
len: text.len()
}
}
pub fn line_offsets(&self) -> impl Iterator<Item = &usize> {
self.line_offsets.iter()
}
fn calculate_offsets(text: &str) -> Vec<usize> {
let mut new_line_offsets = Vec::new();
new_line_offsets.push(0);
for (offset, ch) in text.chars().enumerate() {
match ch {
'\n' => {
new_line_offsets.push(offset + 1)
}
_ => {}
}
}
new_line_offsets
}
}
impl LineIndex for LinearLineIndex {
fn line(&self, offset: usize) -> Option<usize> {
if offset >= self.len {
return None
}
let line = self.line_offsets.upper_bound(&offset);
Some(line)
}
fn offset(&self, line: usize) -> Option<usize> {
if line >= self.line_offsets.len() {
None
} else {
Some(self.line_offsets[line])
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn test_index_lines(text: &str, expected_line_offsets: Vec<usize>) {
let index = LinearLineIndex::new(text);
let actual_line_offsets: Vec<usize> = index.line_offsets()
.map(|it| it.clone())
.collect();
assert_eq!(actual_line_offsets, expected_line_offsets)
}
fn test_line_of_offset(text: &str, offset: usize, expected_line: Option<usize>) {
let index = LinearLineIndex::new(text);
let actual_line = index.line(offset);
assert_eq!(actual_line, expected_line)
}
fn test_offset_of_line(text: &str, line: usize, expected_offset: Option<usize>) {
let index = LinearLineIndex::new(text);
let actual_line = index.offset(line);
assert_eq!(actual_line, expected_offset)
}
#[test]
fn empty_text() {
test_index_lines("", vec![0])
}
#[test]
fn new_line() {
test_index_lines("\n", vec![0, 1])
}
#[test]
fn text_and_nl() {
test_index_lines("foo\nbar\nbaz", vec![0, 4, 8])
}
#[test]
fn text_line_1() {
test_line_of_offset("foo\nbar\nbaz", 1, Some(1))
}
#[test]
fn text_line_2() {
test_line_of_offset("foo\nbar\nbaz", 0, Some(1))
}
#[test]
fn text_line_3() {
test_line_of_offset("foo\nbar\nbaz", 100, None)
}
#[test]
fn text_offset() {
test_offset_of_line("foo\nbar\nbaz", 1, Some(4))
}
#[test]
fn text_offset_too_big() {
test_offset_of_line("foo\nbar\nbaz", 100, None)
}
} |
#![cfg(test)]
use super::FastBernoulliTrial;
use rand::{SeedableRng, XorShiftRng};
use std;
fn make(probability: f64) -> FastBernoulliTrial<XorShiftRng> {
let rng = XorShiftRng::from_seed([0x3b3f4150, 0x53704c15,
0x09b0136e, 0xf66c1396]);
FastBernoulliTrial::new_with_rng(probability, rng)
}
#[test]
fn proportions() {
let mut bernoulli = make(1.0);
assert!(bernoulli.by_ref().take(100).all(|b| b));
bernoulli.set_probability(0.001);
assert_eq!(bernoulli.by_ref().take(1000).filter(|b| *b).count(), 2);
bernoulli.set_probability(0.5);
assert_eq!(bernoulli.by_ref().take(1000).filter(|b| *b).count(), 499);
bernoulli.set_probability(0.85);
assert_eq!(bernoulli.by_ref().take(1000).filter(|b| *b).count(), 836);
bernoulli.set_probability(0.0);
assert_eq!(bernoulli.by_ref().take(1000).filter(|b| *b).count(), 0);
}
#[test]
fn harmonics() {
const N: usize = 100000;
const P: f64 = 0.1;
let trial = make(P);
let trials: Vec<bool> = trial.take(N).collect();
// For each harmonic and phase, check that the proportion sampled is
// within acceptable bounds.
for harmonic in 1..20 {
let expected = N as f64 / harmonic as f64 * P;
let low_expected = (expected * 0.85) as usize;
let high_expected = (expected * 1.15) as usize;
for phase in 0..harmonic {
let mut count = 0;
let mut i = phase;
while i < N {
if trials[i] {
count += 1;
}
i += harmonic;
}
assert!(low_expected <= count && count <= high_expected);
}
}
}
#[test]
fn any_of_next_n() {
const N: usize = 10000;
const P: f64 = 0.01;
let mut trial = make(P);
// Expected value: 0.01 * 10000 == 100
assert_eq!((0..N).filter(|_| trial.any_of_next_n(1)).count(), 103);
// Expected value: (1 - (1 - 0.01) ** 3) == 0.0297,
// 0.0297 * 10000 == 297
assert_eq!((0..N).filter(|_| trial.any_of_next_n(3)).count(), 296);
// Expected value: (1 - (1 - 0.01) ** 10) == 0.0956,
// 0.0956 * 10000 == 956
assert_eq!((0..N).filter(|_| trial.any_of_next_n(10)).count(), 946);
// Expected value: (1 - (1 - 0.01) ** 100) == 0.6339
// 0.6339 * 10000 == 6339
assert_eq!((0..N).filter(|_| trial.any_of_next_n(100)).count(), 6348);
// Expected value: (1 - (1 - 0.01) ** 1000) == 0.9999
// 0.9999 * 10000 == 9999
assert_eq!((0..N).filter(|_| trial.any_of_next_n(1000)).count(), 10000);
}
#[test]
fn set_probability() {
let mut bernoulli = make(1.0);
// Establish a very high skip count.
bernoulli.set_probability(0.0);
// This should re-establish a zero skip count.
bernoulli.set_probability(1.0);
// So this should return true.
assert_eq!(bernoulli.next(), Some(true));
}
#[test]
fn cusp_probabilities() {
// FastBernoulliTrial takes care to avoid screwing up on edge cases. The
// checks here all look pretty dumb, but they exercise paths in the code that
// could exhibit undefined behavior if coded naïvely.
// IEEE requires these results. They're just here to help persuade the
// skeptical that the call to `make` below really does pass the largest
// representable number less than 1.0.
assert!(1.0 - std::f64::EPSILON / 2.0 < 1.0);
assert!(1.0 - std::f64::EPSILON / 4.0 == 1.0);
// This should not be perceptibly different from 1; for 64-bit doubles, this
// is a one in ten trillion chance of the trial not succeeding. Overflows
// converting doubles to usize skip counts may change this, though.
let mut bernoulli = make(1.0 - std::f64::EPSILON / 2.0);
assert!(bernoulli.by_ref().take(1000).all(|b| b));
// This should not be perceptibly different from 0; for 64-bit doubles, the
// FastBernoulliTrial will actually treat this as exactly zero.
bernoulli.set_probability(std::f64::MIN_POSITIVE);
assert!(!bernoulli.by_ref().take(1000).any(|b| b));
// This should be a vanishingly low probability which FastBernoulliTrial does
// *not* treat as exactly zero.
bernoulli.set_probability(std::f64::EPSILON);
assert!(!bernoulli.by_ref().take(1000).any(|b| b));
}
|
// Copyright (C) 2022 Subspace Labs, Inc.
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! Subspace fraud proof verification in the consensus level.
use codec::{Decode, Encode};
use sc_consensus::block_import::{BlockCheckParams, BlockImport, BlockImportParams, ImportResult};
use sp_api::{ProvideRuntimeApi, TransactionFor};
use sp_consensus::Error as ConsensusError;
use sp_domains::DomainsApi;
use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
use std::marker::PhantomData;
use std::sync::Arc;
use subspace_fraud_proof::VerifyFraudProof;
/// A block-import handler for Subspace fraud proof.
///
/// This scans each imported block for a fraud proof. If the extrinsc `pallet_domains::Call::submit_fraud_proof`
/// is found, ensure the included fraud proof in it is valid.
///
/// This block import object should be used with the subspace consensus block import together until
/// the fraud proof verification can be done in the runtime properly.
pub struct FraudProofBlockImport<Block, Client, I, Verifier, DomainNumber, DomainHash> {
inner: I,
client: Arc<Client>,
fraud_proof_verifier: Verifier,
_phantom: PhantomData<(Block, DomainNumber, DomainHash)>,
}
impl<Block, Client, I, Verifier, DomainNumber, DomainHash> Clone
for FraudProofBlockImport<Block, Client, I, Verifier, DomainNumber, DomainHash>
where
I: Clone,
Verifier: Clone,
{
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
client: self.client.clone(),
fraud_proof_verifier: self.fraud_proof_verifier.clone(),
_phantom: self._phantom,
}
}
}
#[async_trait::async_trait]
impl<Block, Client, Inner, Verifier, DomainNumber, DomainHash> BlockImport<Block>
for FraudProofBlockImport<Block, Client, Inner, Verifier, DomainNumber, DomainHash>
where
Block: BlockT,
Client: ProvideRuntimeApi<Block> + Send + Sync + 'static,
Client::Api: DomainsApi<Block, DomainNumber, DomainHash>,
Inner: BlockImport<Block, Transaction = TransactionFor<Client, Block>, Error = ConsensusError>
+ Send,
Verifier: VerifyFraudProof<Block> + Send,
DomainNumber: Encode + Decode + Send,
DomainHash: Encode + Decode + Send,
{
type Error = ConsensusError;
type Transaction = TransactionFor<Client, Block>;
async fn check_block(
&mut self,
block: BlockCheckParams<Block>,
) -> Result<ImportResult, Self::Error> {
self.inner.check_block(block).await.map_err(Into::into)
}
async fn import_block(
&mut self,
block: BlockImportParams<Block, Self::Transaction>,
) -> Result<ImportResult, Self::Error> {
let _parent_hash = *block.header.parent_hash();
if !block.state_action.skip_execution_checks() {
if let Some(_extrinsics) = &block.body {
// TODO: Fetch the registered domains properly
// We may change `extract_fraud_proofs` API to return the fraud proofs for all
// domains instead of specifying the domain_id each time for the efficiency.
// let registered_domains = vec![];
// for domain_id in registered_domains {
// TODO: Implement `extract_fraud_proofs` when proceeding to fraud proof v2.
// let fraud_proofs = self
// .client
// .runtime_api()
// .extract_fraud_proofs(parent_hash, extrinsics.clone(), domain_id)
// .map_err(|e| ConsensusError::ClientImport(e.to_string()))?;
// for fraud_proof in fraud_proofs {
// self.fraud_proof_verifier
// .verify_fraud_proof(&fraud_proof)
// .map_err(|e| ConsensusError::Other(Box::new(e)))?;
// }
// }
}
}
self.inner.import_block(block).await
}
}
pub fn block_import<Block, Client, I, Verifier, DomainNumber, DomainHash>(
client: Arc<Client>,
wrapped_block_import: I,
fraud_proof_verifier: Verifier,
) -> FraudProofBlockImport<Block, Client, I, Verifier, DomainNumber, DomainHash> {
FraudProofBlockImport {
inner: wrapped_block_import,
client,
fraud_proof_verifier,
_phantom: PhantomData::<(Block, DomainNumber, DomainHash)>,
}
}
|
use rowan::TextSize;
use parser::syntax_kind::SyntaxKind;
use SyntaxKind::*;
use vimscript_core::peekable_chars_with_position::PeekableCharsWithPosition;
use std::convert::TryFrom;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Token {
pub kind: SyntaxKind,
pub len: TextSize,
}
pub fn lex(source: &str) -> Vec<Token> {
let mut lexer = Lexer {
source: source,
chars: PeekableCharsWithPosition::new(source),
tokens: Vec::new(),
start: 0,
};
lexer.lex()
}
struct Lexer<'a> {
source: &'a str,
chars: PeekableCharsWithPosition<'a>,
tokens: Vec<Token>,
start: usize,
}
impl<'a> Lexer<'a> {
fn lex(&mut self) -> Vec<Token> {
while let Some(kind) = self.read_token() {
let len = TextSize::try_from(self.chars.pos() - self.start).unwrap();
self.tokens.push(Token{kind: kind, len: len});
self.start = self.chars.pos();
}
return std::mem::replace(&mut self.tokens, Vec::new());
}
fn read_token(&mut self) -> Option<SyntaxKind> {
match self.chars.next() {
None => None,
Some('\n') => Some(NEW_LINE),
Some(' ') => Some(WHITESPACE),
Some('=') => Some(EQ),
Some(c) => {
if '0' <= c && c <= '9' {
Some(self.read_number())
} else {
Some(self.read_identifier())
}
}
}
}
fn read_identifier(&mut self) -> SyntaxKind {
loop {
match self.chars.peek() {
None => break,
Some(c) => {
if !(('a' <= c && c <= 'z')
|| ('A' <= c && c <= 'Z')
|| c == '#'
|| c == ':'
|| c == '_'
|| ('0' <= c && c <= '9'))
{
break;
}
}
}
self.chars.next();
}
let s = &self.source[self.start..self.chars.pos()];
match s {
"let" => LET_KW,
_ => IDENT,
}
}
fn read_number(&mut self) -> SyntaxKind {
// TODO: handle floating point numbers.
loop {
match self.chars.peek() {
None => break,
Some(c) => {
if !('0' <= c && c <= '9') {
break;
}
}
}
self.chars.next();
}
return NUMBER
}
}
|
use async_trait::async_trait;
use std::path::Path;
use std::{io, io::SeekFrom};
use tokio::{fs::File, io::AsyncReadExt};
use nbd_async::BlockDevice;
struct FileBackedDevice {
current_file_offs: u64,
file: tokio::fs::File,
block_size: u32,
block_count: u64,
}
impl FileBackedDevice {
fn new(block_size: u32, block_count: u64, file: File) -> Self {
Self {
current_file_offs: 0,
file,
block_size,
block_count,
}
}
}
#[async_trait(?Send)]
impl BlockDevice for FileBackedDevice {
async fn read(&mut self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
if offset != self.current_file_offs {
self.file.seek(SeekFrom::Start(offset)).await?;
self.current_file_offs = offset;
}
let mut total_read = 0;
while total_read < buf.len() {
let rc = self.file.read(&mut buf[total_read..]).await?;
if rc == 0 {
break;
}
total_read += rc;
self.current_file_offs += rc as u64;
}
if total_read < buf.len() {
buf[total_read..].iter_mut().for_each(|v| *v = 0);
}
Ok(())
}
async fn write(&mut self, _offset: u64, _buf: &[u8]) -> io::Result<()> {
unimplemented!()
}
}
pub async fn mount(backend_file: File, nbd_dev: &Path, block_size: u32) {
let block_count = {
let metadata = backend_file.metadata().await.expect("metadata");
(metadata.len() + block_size as u64 - 1) / block_size as u64
};
let device = FileBackedDevice::new(block_size, block_count, backend_file);
nbd_async::serve_local_nbd(nbd_dev, device.block_size, device.block_count, device)
.await
.expect("mount");
}
|
extern crate sdl2;
extern crate rand;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
#[allow(unused_imports, dead_code,unused_must_use,unused_variables,unused_mut,non_camel_case_types,patterns_in_fns_without_body)]
mod phi;
#[allow(unused_imports, dead_code,unused_must_use,unused_variables,unused_mut,non_camel_case_types,patterns_in_fns_without_body)]
mod views;
#[macro_use]
#[allow(unused_imports, dead_code,unused_must_use,unused_variables,unused_mut,non_camel_case_types,patterns_in_fns_without_body)]
mod game;
fn main() {
::phi::spawn("Greed", |phi| Box::new(::views::game::GameView::new(phi)));
}
|
extern crate stomp;
extern crate rustc_serialize;
use self::stomp::session::Session;
use self::stomp::session_builder::SessionBuilder;
use self::stomp::connection::{Credentials, HeartBeat};
use self::stomp::frame::Frame;
use self::stomp::header::{Header, SuppressedHeader};
use self::stomp::subscription::AckOrNack::{Ack, Nack};
use self::stomp::subscription::AckMode;
use self::rustc_serialize::json;
use std::mem::replace;
use worker::Request;
pub trait Consumer {
fn subscribe<T>(&mut self, handler: T) where T : Fn(Request) + 'static;
fn listen (&mut self);
}
#[derive(Debug, Clone, RustcDecodable, RustcEncodable)]
pub struct StompConfig {
address: String,
port: u16,
host: String,
username: String,
password: String,
topic: String,
prefetch_count: u16,
heartbeat: u32
}
pub struct StompConsumer<'a> {
session : Session<'a>,
topic: String,
prefetch_count: u16,
handlers: Vec<Box<Fn(Request)>>
}
impl<'a> StompConsumer<'a> {
pub fn new (config: &'a StompConfig) -> StompConsumer<'a> {
let session = match SessionBuilder::new(&config.address, config.port)
.with(Credentials(&config.username, &config.password))
.with(SuppressedHeader("host"))
.with(HeartBeat(config.heartbeat.clone(), config.heartbeat.clone()))
.with(Header::new("host", &config.host))
.start() {
Ok(session) => session,
Err(error) => panic!("Could not connect to the server: {}", error)
}
;
StompConsumer {
session: session,
topic: config.topic.clone(),
prefetch_count: config.prefetch_count,
handlers: vec![]
}
}
}
impl<'a> Consumer for StompConsumer<'a> {
fn subscribe<T>(&mut self, handler: T) where T : Fn(Request) + 'static {
self.handlers.push(Box::new(handler));
}
fn listen (&mut self) {
let handlers = replace(&mut self.handlers, Vec::new());
self.session.on_before_send(|frame: &mut Frame| {
match frame.command.as_ref() {
"NACK" => {
frame.headers.push(Header::new("requeue", "false"));
},
_ => {}
}
});
self.session.subscription(&self.topic, move |frame: &Frame| {
let frame_body = match String::from_utf8(frame.body.clone()) {
Ok(v) => v,
Err(_) => return Nack
};
let request: Request = match json::decode(&frame_body) {
Ok(v) => v,
Err(_) => return Nack
};
for handler in &handlers {
handler(request.clone());
}
Ack
})
.with(AckMode::ClientIndividual)
.with(Header::new("prefetch-count", &self.prefetch_count.to_string()))
.start().ok().expect("unable to start receiving messages")
;
self.session.listen().ok().expect("unable to listen");
}
} |
use crate::view::shader_utils;
use cgmath;
use web_sys::{WebGl2RenderingContext, WebGlProgram};
pub fn initialize_shader(context: &WebGl2RenderingContext) -> Result<WebGlProgram, String>
{
let vert_shader = shader_utils::compile_shader(
&context,
WebGl2RenderingContext::VERTEX_SHADER,
r#"#version 300 es
uniform vec2[10] sizes;
uniform vec2[10] positions;
uniform int[10] tileMapIndices;
out vec2 uv;
flat out int tileMapIndex;
void main()
{
int idx = gl_VertexID / 6;
vec2 centerPos = positions[idx];
tileMapIndex = tileMapIndices[idx];
int subIdx = gl_VertexID % 6;
if(subIdx == 0)
{
gl_Position = vec4(centerPos + (sizes[idx] / 2.0) * vec2(1, -1), 0, 1);
uv = vec2(1.0, 0.0);
}
else if(subIdx == 1)
{
gl_Position = vec4(centerPos + (sizes[idx] / 2.0) * vec2(1, 1), 0, 1);
uv = vec2(1.0, 1.0);
}
else if(subIdx == 2)
{
gl_Position = vec4(centerPos + (sizes[idx] / 2.0) * vec2(-1, 1), 0, 1);
uv = vec2(0.0, 1.0);
}
else if(subIdx == 3)
{
gl_Position = vec4(centerPos + (sizes[idx] / 2.0) * vec2(1, -1), 0, 1);
uv = vec2(1.0, 0.0);
}
else if(subIdx == 4)
{
gl_Position = vec4(centerPos + (sizes[idx] / 2.0) * vec2(-1, 1), 0, 1);
uv = vec2(0.0, 1.0);
}
else// if(subIdx == 5)
{
gl_Position = vec4(centerPos + (sizes[idx] / 2.0) * vec2(-1, -1), 0, 1);
uv = vec2(0.0, 0.0);
}
}
"#,
)?;
let frag_shader = shader_utils::compile_shader(
&context,
WebGl2RenderingContext::FRAGMENT_SHADER,
r#"#version 300 es
precision highp float;
uniform float tileMapWidth;
uniform float tileMapHeight;
uniform sampler2D tileMap;
in vec2 uv;
flat in int tileMapIndex;
out vec4 outColor;
void main()
{
//Flip, because bmp is not flipped in the file
vec2 uv = vec2(uv.x, 1.0 - uv.y);
float tileToUseCol = mod(float(tileMapIndex), tileMapWidth);
float tileToUseRow = floor(float(tileMapIndex) / tileMapHeight);
float startTileX = tileToUseCol / tileMapWidth;
float tileSizeX = 1.0 / tileMapWidth;
float tiledUvX = mix(startTileX, startTileX + tileSizeX, uv.x);
float startTileY = tileToUseRow / tileMapHeight;
float tileSizeY = 1.0 / tileMapHeight;
float tiledUvY = mix(startTileY, startTileY + tileSizeY, uv.y);
outColor = texture(tileMap, vec2(tiledUvX, tiledUvY));
// outColor = vec4(1.0, 0.0, 0.0, 1.0);
}
"#,
)?;
return shader_utils::link_program(
&context,
&vert_shader,
&frag_shader,
vec![(0, "position"), (1, "uv")],
);
}
pub fn update_sizes(context: &WebGl2RenderingContext, shader: &WebGlProgram, new_sizes: [cgmath::Vector2<f32>;10]) -> Result<(), String>
{
shader_utils::set_uniform2f_arr10(context, shader, new_sizes, "sizes")?;
Ok(())
}
pub fn update_positions(context: &WebGl2RenderingContext, shader: &WebGlProgram, new_positions: [cgmath::Vector2<f32>;10]) -> Result<(), String>
{
shader_utils::set_uniform2f_arr10(context, shader, new_positions, "positions")?;
Ok(())
}
pub fn update_tile_map_indices(context: &WebGl2RenderingContext, shader: &WebGlProgram, new_indices: [i32;10]) -> Result<(), String>
{
shader_utils::set_uniform1i_arr10(context, shader, new_indices, "tileMapIndices")?;
Ok(())
}
pub fn set_tile_map_uniforms(context: &WebGl2RenderingContext, program: &WebGlProgram, width: f32, height: f32) -> Result<(), String>
{
context.use_program(Some(&program));
shader_utils::set_uniform1f(context, program, width, "tileMapWidth")?;
shader_utils::set_uniform1f(context, program, height, "tileMapHeight")?;
Ok(())
} |
//! This file contains the main function
#![warn(
missing_docs,
absolute_paths_not_starting_with_crate,
anonymous_parameters,
box_pointers,
clashing_extern_declarations,
deprecated_in_future,
elided_lifetimes_in_paths,
explicit_outlives_requirements,
indirect_structural_match,
keyword_idents,
macro_use_extern_crate,
meta_variable_misuse,
missing_copy_implementations,
missing_crate_level_docs,
missing_debug_implementations,
missing_doc_code_examples,
non_ascii_idents,
private_doc_tests,
single_use_lifetimes,
trivial_casts,
trivial_numeric_casts,
unaligned_references,
unreachable_pub,
unsafe_code,
unstable_features,
unused_crate_dependencies,
unused_extern_crates,
unused_import_braces,
unused_lifetimes,
unused_qualifications,
unused_results,
variant_size_differences
)] // unsafe_op_in_unsafe_fn is unstable
#![warn(clippy::all)]
use vector_inheritance::Info;
use vector_inheritance::InfoList;
use vector_inheritance::InfoListMethod;
/// Entry point of the program
fn main() {
let info_0 = Info { i: 1, j: 2 };
let info_1 = Info { i: 3, j: 4 };
let info_2 = Info { i: 5, j: 6 };
let info_list: InfoList = vec![info_0, info_1, info_2];
let res = info_list.get_from_i(3);
print!("{:?}", res);
}
|
use quicksilver::{
geom::{ Rectangle, Shape, Tile, Tilemap, Vector},
graphics::{Background::Blended, Background::Img, Color, Font, FontStyle, Image},
input::Key,
lifecycle::{run, Asset, Settings, State, Window},
Future, Result
};
use std::collections::HashMap;
#[derive(Clone, Debug, PartialEq)]
struct Entity {
pos: Vector,
glyph: char,
color: Color,
hp: i32,
max_hp: i32,
}
fn generate_entities( ) -> Vec<Entity> {
vec![
Entity {
pos: Vector::new(9, 6),
glyph: 'g',
color: Color::RED,
hp: 1,
max_hp: 1,
},
Entity {
pos: Vector::new(2, 4),
glyph: 'g',
color: Color::RED,
hp: 1,
max_hp: 1,
},
Entity {
pos: Vector::new(7, 5),
glyph: '%',
color: Color::PURPLE,
hp: 0,
max_hp: 0,
},
Entity {
pos: Vector::new(4, 8),
glyph: '%',
color: Color::PURPLE,
hp: 0,
max_hp: 0,
},
]
}
#[derive(Clone, Debug, PartialEq)]
struct RougeTile {
pos: Vector,
glyph: char,
color: Color,
}
fn generate_map( size: Vector ) -> ( Vec<RougeTile>, Vec<Tile<char>> ) {
let width = size.x as usize;
let height = size.y as usize;
let mut map = Vec::with_capacity( width * height );
let mut blocks = Vec::with_capacity( width * height );
for x in 0..width {
for y in 0..height {
let mut tile = RougeTile {
pos: Vector::new( x as f32, y as f32 ),
glyph: '.',
color: Color::WHITE,
};
if x == 0 || x == width - 1 || y == 0 || y == height - 1 {
tile.glyph = '#';
blocks.push( Tile::solid( Some( tile.glyph ) ) );
} else {
blocks.push( Tile::empty( Some( tile.glyph ) ) );
}
map.push(tile);
}
}
( map, blocks )
}
struct Game {
title: Asset<Image>,
square_font_info: Asset<Image>,
map_size: Vector,
map: Vec<RougeTile>,
entities: Vec<Entity>,
player_id: usize,
tileset: Asset<HashMap<char, Image>>,
tile_size_px: Vector,
map_block: Tilemap<char>,
}
impl State for Game {
///Init game / load assests
fn new() -> Result<Self> {
let font_square = "square.ttf";
let title = Asset::new(Font::load(font_square).and_then(|font| {
font.render("QuickSilver Roguelike", &FontStyle::new(20.0, Color::RED))
}));
let square_font_info = Asset::new(Font::load(font_square).and_then(|font| {
font.render("Square font by Wouter Van Oortmerssen, terms: CC BY 3.0", &FontStyle::new(12.0, Color::GREEN))
}));
let game_glyphs = "#@g.%";
let tile_size_px = Vector::new(24, 24);
let tileset = Asset::new(Font::load(font_square).and_then(move |text| {
let tiles = text.render( game_glyphs, &FontStyle::new(tile_size_px.y, Color::WHITE) )
.expect("Could not render the font tileset.");
let mut tileset = HashMap::new();
for ( index, glyph ) in game_glyphs.chars().enumerate() {
let pos = ( index as i32 * tile_size_px.x as i32, 0 );
let tile = tiles.subimage( Rectangle::new(pos, tile_size_px) );
tileset.insert( glyph, tile );
}
Ok(tileset)
}));
let map_size = Vector::new( 20, 20 );
let ( map, blocks ) = generate_map( map_size );
let map_block = Tilemap::with_data( blocks, map_size, tile_size_px );
let mut entities = generate_entities();
let player_id = entities.len();
entities.push(Entity {
pos: Vector::new(5, 3),
glyph: '@',
color: Color::BLUE,
hp: 3,
max_hp: 5,
});
Ok(Self{
title,
square_font_info,
map_size,
map,
entities,
player_id,
tileset,
tile_size_px,
map_block,
})
}
/// Process input / update game state
fn update(&mut self, window: &mut Window) -> Result<()> {
use quicksilver::input::ButtonState::*;
let mut player_pos = self.entities[self.player_id].pos;
if window.keyboard()[Key::H] == Pressed {
player_pos.x -= 1.0;
}
if window.keyboard()[Key::L] == Pressed {
player_pos.x += 1.0;
}
if window.keyboard()[Key::K] == Pressed {
player_pos.y -= 1.0;
}
if window.keyboard()[Key::J] == Pressed {
player_pos.y += 1.0;
}
if window.keyboard()[Key::Q].is_down() {
window.close();
}
if self.map_block.valid( player_pos ) {
self.entities[self.player_id].pos = player_pos;
}
Ok(())
}
/// Draw stuff
fn draw(&mut self, window: &mut Window) -> Result<()> {
window.clear(Color::BLACK)?;
self.title.execute(|image| {
window.draw(
&image.area().with_center((window.screen_size().x as i32 / 2, 30)),
Img(&image),
);
Ok(())
})?;
self.square_font_info.execute(|image| {
window.draw(
&image.area().translate((4, window.screen_size().y as i32 - 60)),
Img(&image),
);
Ok(())
})?;
let tile_size_px = self.tile_size_px;
let ( tileset, map ) = (&mut self.tileset, &self.map );
tileset.execute(|tileset| {
let offset_px = Vector::new(20, 50);
for tile in map.iter() {
if let Some(image) = tileset.get(&tile.glyph) {
let pos_px = tile.pos.times(tile_size_px);
window.draw(
&Rectangle::new(offset_px + pos_px, image.area().size()),
Blended( &image, tile.color ),
);
}
}
Ok(())
})?;
let ( tileset, entities ) = (&mut self.tileset, &self.entities );
tileset.execute(|tileset| {
let offset_px = Vector::new(20, 50);
for entity in entities.iter() {
if let Some(image) = tileset.get(&entity.glyph) {
let pos_px = entity.pos.times(tile_size_px);
window.draw(
&Rectangle::new(offset_px + pos_px, image.area().size()),
Blended( &image, entity.color ),
);
}
}
Ok(())
})?;
Ok(())
}
}
fn main() {
std::env::set_var("WINIT_HIDPI_FACTOR", "1.0");
let settings = Settings {
resize: quicksilver::graphics::ResizeStrategy::Fill,
scale: quicksilver::graphics::ImageScaleStrategy::Blur,
..Default::default()
};
run::<Game>( "QuickSilver Rougelike", Vector::new(800,600), settings );
}
|
pub mod index;
pub mod register;
pub mod login; |
mod arithmetic;
mod karatsuba;
mod search;
mod sort;
mod strassen;
use std::{
fs::File,
io::{prelude::*, BufReader, Error, ErrorKind},
};
fn read_to_ints(filename: &str) -> Result<Vec<i64>, Error> {
let file = File::open(filename).expect("File not found!");
let buf = BufReader::new(file);
let result = buf
.lines()
.map(|l| l.and_then(|v| v.parse().map_err(|e| Error::new(ErrorKind::InvalidData, e))))
.collect();
return result;
}
fn main() {
println!("Hello world!");
let filename = "./data/integers.txt";
let mut vec = read_to_ints(filename).ok().unwrap();
let inversions = sort::count_inversions(&mut vec);
println!("INVERSIONS: {}", inversions);
}
|
use std::io;
// Use the std::io library which allows reading from stdin
fn main() {
let mut inpt = String::new();
// Create a mutable variable called inpt
// that is a new instance of a String.
println!("Input some text: ");
io::stdin()
.read_line(&mut inpt)
.expect("Failed to read line");
println!("Read: '{}' from stdin", inpt);
}
|
use proconio::{fastout, input};
#[fastout]
fn main() {
input! {
a: i64,
}
let a_2: i64 = a * a;
println!("{}", a + a_2 + a * a_2);
}
|
struct A;
struct S(A);
struct SGen<T>(T);
// not generic
fn reg_fn(_s: S) {}
// not generic
fn gen_spec_t(_s: SGen<A>) {}
// not generic
fn gen_spec_i32(_s: SGen<i32>) {}
// generic
fn generic<T>(_s: SGen<T>) {}
#[cfg(test)]
mod tests {
use crate::functions::{reg_fn, A, S, gen_spec_t, SGen, gen_spec_i32, generic};
#[test]
fn main() {
reg_fn(S(A));
gen_spec_t(SGen(A));
gen_spec_i32(SGen(6));
generic::<char>(SGen('a'));
generic(SGen('a'));
}
}
|
pub use systemd::SystemdNetworkConfig;
pub use systemd::NetworkConfigLoader;
pub mod systemd;
|
extern crate hyper;
use hyper::{Body, Request, Server, Method};
use hyper::rt::{Future};
use hyper::service::service_fn;
extern crate futures;
#[macro_use]
extern crate serde_derive;
mod handlers;
fn router(req: Request<Body>) -> handlers::BoxFutResponse {
match (req.method(), req.uri().path()) {
(&Method::GET, "/") => handlers::handle_root(),
(&Method::POST, "/echo") => handlers::handle_echo(req),
(&Method::POST, "/echo/uppercase") => handlers::handle_uppercase(req),
(&Method::POST, "/echo/reverse") => handlers::handle_reverse(req),
(&Method::POST, "/echo/json") => handlers::handle_json(req),
_ => handlers::handle_not_found()
}
}
fn main() {
let addr = ([127, 0, 0, 1], 3000).into();
let server = Server::bind(&addr)
.serve(|| service_fn(router))
.map_err(|e| eprintln!("server error: {}", e));
println!("Listening on http://{}", addr);
hyper::rt::run(server);
}
|
//use std::rc::Rc; // For pointer count mem management
use std::sync::mpsc; // multiple producer, single consumer
use std::sync::{Arc, Mutex}; // Arc is Atomic Rc
use std::thread;
use std::time::Duration;
pub fn basic_example() {
let handle = thread::spawn(|| {
for i in 1..10 {
println!("hi number {} from the spawned thread!", i);
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..5 {
println!("hi number {} from the main thread!", i);
thread::sleep(Duration::from_millis(1));
}
handle.join().unwrap();
}
pub fn using_data_from_parent_thread() {
let v = vec![1, 2, 3];
// v's ownership is passed to the thread
let handle = thread::spawn(move || {
println!("Here's a vector: {:?}", v);
});
handle.join().unwrap();
}
pub fn using_channels() {
// Create a transmitter and receiver
let (tx, rx) = mpsc::channel();
let tx1 = mpsc::Sender::clone(&tx); // multiple producers
thread::spawn(move || {
let vals = vec![
String::from("hi :tx"),
String::from("from :tx"),
String::from("the :tx"),
String::from("thread :tx"),
];
for val in vals {
tx.send(val).unwrap(); // moves ownership to receiver
thread::sleep(Duration::from_secs_f32(0.25));
}
});
thread::spawn(move || {
let vals = vec![
String::from("more :tx1"),
String::from("messages :tx1"),
String::from("for :tx1"),
String::from("you :tx1"),
];
for val in vals {
tx1.send(val).unwrap(); // moves ownership to receiver
thread::sleep(Duration::from_secs(1));
}
});
for received in rx {
println!("Got: {}.", received);
}
}
pub fn using_mutexes() {
// If used in multiple threads, Mutex has to be in a multiple counter
// so that it can be passed into many threads that all have mutable references.
// Arc is used for this purpose.
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
// Spawn threads
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
// Ensure all threads execute
for handle in handles {
handle.join().unwrap();
}
// Display result
println!("Result: {}", *counter.lock().unwrap());
}
|
// Copyright 2019. The Tari Project
// SPDX-License-Identifier: BSD-3-Clause
//! Bulletproofs+ implementation
use alloc::vec::Vec;
use std::convert::TryFrom;
pub use bulletproofs_plus::ristretto::RistrettoRangeProof;
use bulletproofs_plus::{
commitment_opening::CommitmentOpening,
extended_mask::ExtendedMask as BulletproofsExtendedMask,
generators::pedersen_gens::ExtensionDegree as BulletproofsExtensionDegree,
range_parameters::RangeParameters,
range_proof::{RangeProof, VerifyAction},
range_statement::RangeStatement,
range_witness::RangeWitness,
PedersenGens,
};
use curve25519_dalek::{ristretto::RistrettoPoint, scalar::Scalar};
use log::*;
use crate::{
alloc::string::ToString,
commitment::{ExtensionDegree as CommitmentExtensionDegree, HomomorphicCommitment},
errors::RangeProofError,
extended_range_proof,
extended_range_proof::{
AggregatedPrivateStatement,
AggregatedPublicStatement,
ExtendedRangeProofService,
ExtendedWitness,
Statement,
},
range_proof::RangeProofService,
ristretto::{
pedersen::extended_commitment_factory::ExtendedPedersenCommitmentFactory,
RistrettoPublicKey,
RistrettoSecretKey,
},
};
const LOG_TARGET: &str = "tari_crypto::ristretto::bulletproof_plus";
/// A wrapper around the Tari library implementation of Bulletproofs+ range proofs.
pub struct BulletproofsPlusService {
generators: RangeParameters<RistrettoPoint>,
transcript_label: &'static str,
}
/// An extended mask for the Ristretto curve
pub type RistrettoExtendedMask = extended_range_proof::ExtendedMask<RistrettoSecretKey>;
/// An extended witness for the Ristretto curve
pub type RistrettoExtendedWitness = ExtendedWitness<RistrettoSecretKey>;
/// A range proof statement for the Ristretto curve
pub type RistrettoStatement = Statement<RistrettoPublicKey>;
/// An aggregated statement for the Ristretto curve
pub type RistrettoAggregatedPublicStatement = AggregatedPublicStatement<RistrettoPublicKey>;
/// An aggregated private statement for the Ristretto curve
pub type RistrettoAggregatedPrivateStatement = AggregatedPrivateStatement<RistrettoPublicKey>;
/// A set of generators for the Ristretto curve
pub type BulletproofsPlusRistrettoPedersenGens = PedersenGens<RistrettoPoint>;
impl TryFrom<&RistrettoExtendedMask> for Vec<Scalar> {
type Error = RangeProofError;
fn try_from(extended_mask: &RistrettoExtendedMask) -> Result<Self, Self::Error> {
Ok(extended_mask.secrets().iter().map(|k| k.0).collect())
}
}
impl TryFrom<&BulletproofsExtendedMask> for RistrettoExtendedMask {
type Error = RangeProofError;
fn try_from(extended_mask: &BulletproofsExtendedMask) -> Result<Self, Self::Error> {
let secrets = extended_mask
.blindings()
.map_err(|e| RangeProofError::RPExtensionDegree { reason: e.to_string() })?;
RistrettoExtendedMask::assign(
CommitmentExtensionDegree::try_from_size(secrets.len())
.map_err(|e| RangeProofError::RPExtensionDegree { reason: e.to_string() })?,
secrets.iter().map(|k| RistrettoSecretKey(*k)).collect(),
)
}
}
impl TryFrom<&RistrettoExtendedMask> for BulletproofsExtendedMask {
type Error = RangeProofError;
fn try_from(extended_mask: &RistrettoExtendedMask) -> Result<Self, Self::Error> {
let extension_degree = BulletproofsExtensionDegree::try_from_size(extended_mask.secrets().len())
.map_err(|e| RangeProofError::RPExtensionDegree { reason: e.to_string() })?;
BulletproofsExtendedMask::assign(extension_degree, Vec::try_from(extended_mask)?)
.map_err(|e| RangeProofError::RPExtensionDegree { reason: e.to_string() })
}
}
impl BulletproofsPlusService {
/// Create a new BulletProofsPlusService containing the generators - this will err if each of 'bit_length' and
/// 'aggregation_factor' is not a power of two
pub fn init(
bit_length: usize,
aggregation_factor: usize,
factory: ExtendedPedersenCommitmentFactory,
) -> Result<Self, RangeProofError> {
Ok(Self {
generators: RangeParameters::init(bit_length, aggregation_factor, BulletproofsPlusRistrettoPedersenGens {
h_base: factory.h_base,
h_base_compressed: factory.h_base_compressed,
g_base_vec: factory.g_base_vec,
g_base_compressed_vec: factory.g_base_compressed_vec,
extension_degree: BulletproofsExtensionDegree::try_from_size(factory.extension_degree as usize)
.map_err(|e| RangeProofError::InitializationError { reason: e.to_string() })?,
})
.map_err(|e| RangeProofError::InitializationError { reason: e.to_string() })?,
transcript_label: "Tari Bulletproofs+",
})
}
/// Use a custom domain separated transcript label
pub fn custom_transcript_label(&mut self, transcript_label: &'static str) {
self.transcript_label = transcript_label;
}
/// Helper function to return the serialized proof's extension degree
pub fn extension_degree(serialized_proof: &[u8]) -> Result<CommitmentExtensionDegree, RangeProofError> {
let extension_degree = RistrettoRangeProof::extension_degree_from_proof_bytes(serialized_proof)
.map_err(|e| RangeProofError::InvalidRangeProof { reason: e.to_string() })?;
CommitmentExtensionDegree::try_from_size(extension_degree as usize)
.map_err(|e| RangeProofError::InvalidRangeProof { reason: e.to_string() })
}
/// Helper function to prepare a batch of public range statements
pub fn prepare_public_range_statements(
&self,
statements: Vec<&RistrettoAggregatedPublicStatement>,
) -> Vec<RangeStatement<RistrettoPoint>> {
let mut range_statements = Vec::with_capacity(statements.len());
for statement in statements {
range_statements.push(RangeStatement {
generators: self.generators.clone(),
commitments: statement.statements.iter().map(|v| v.commitment.0.point()).collect(),
commitments_compressed: statement
.statements
.iter()
.map(|v| *v.commitment.0.compressed())
.collect(),
minimum_value_promises: statement
.statements
.iter()
.map(|v| Some(v.minimum_value_promise))
.collect(),
seed_nonce: None,
});
}
range_statements
}
/// Helper function to prepare a batch of private range statements
pub fn prepare_private_range_statements(
&self,
statements: Vec<&RistrettoAggregatedPrivateStatement>,
) -> Vec<RangeStatement<RistrettoPoint>> {
let mut range_statements = Vec::with_capacity(statements.len());
for statement in statements {
range_statements.push(RangeStatement {
generators: self.generators.clone(),
commitments: statement.statements.iter().map(|v| v.commitment.0.point()).collect(),
commitments_compressed: statement
.statements
.iter()
.map(|v| *v.commitment.0.compressed())
.collect(),
minimum_value_promises: statement
.statements
.iter()
.map(|v| Some(v.minimum_value_promise))
.collect(),
seed_nonce: statement.recovery_seed_nonce.as_ref().map(|n| n.0),
});
}
range_statements
}
/// Helper function to deserialize a batch of range proofs
pub fn deserialize_range_proofs(
&self,
proofs: &[&<BulletproofsPlusService as RangeProofService>::Proof],
) -> Result<Vec<RangeProof<RistrettoPoint>>, RangeProofError> {
let mut range_proofs = Vec::with_capacity(proofs.len());
for (i, proof) in proofs.iter().enumerate() {
match RistrettoRangeProof::from_bytes(proof)
.map_err(|e| RangeProofError::InvalidRangeProof { reason: e.to_string() })
{
Ok(rp) => {
range_proofs.push(rp);
},
Err(e) => {
return Err(RangeProofError::InvalidRangeProof {
reason: format!("Range proof at index '{i}' could not be deserialized ({e})"),
});
},
}
}
Ok(range_proofs)
}
}
impl RangeProofService for BulletproofsPlusService {
type K = RistrettoSecretKey;
type PK = RistrettoPublicKey;
type Proof = Vec<u8>;
fn construct_proof(&self, key: &Self::K, value: u64) -> Result<Self::Proof, RangeProofError> {
let commitment = self
.generators
.pc_gens()
.commit(&Scalar::from(value), &[key.0])
.map_err(|e| RangeProofError::ProofConstructionError { reason: e.to_string() })?;
let opening = CommitmentOpening::new(value, vec![key.0]);
let witness = RangeWitness::init(vec![opening])
.map_err(|e| RangeProofError::ProofConstructionError { reason: e.to_string() })?;
let statement = RangeStatement::init(self.generators.clone(), vec![commitment], vec![None], None)
.map_err(|e| RangeProofError::ProofConstructionError { reason: e.to_string() })?;
let proof = RistrettoRangeProof::prove(self.transcript_label, &statement, &witness)
.map_err(|e| RangeProofError::ProofConstructionError { reason: e.to_string() })?;
Ok(proof.to_bytes())
}
fn verify(&self, proof: &Self::Proof, commitment: &HomomorphicCommitment<Self::PK>) -> bool {
match RistrettoRangeProof::from_bytes(proof)
.map_err(|e| RangeProofError::InvalidRangeProof { reason: e.to_string() })
{
Ok(rp) => {
let statement = RangeStatement {
generators: self.generators.clone(),
commitments: vec![commitment.0.clone().into()],
commitments_compressed: vec![*commitment.0.compressed()],
minimum_value_promises: vec![None],
seed_nonce: None,
};
match RistrettoRangeProof::verify_batch(
self.transcript_label,
&[statement],
&[rp.clone()],
VerifyAction::VerifyOnly,
) {
Ok(_) => true,
Err(e) => {
if self.generators.extension_degree() != rp.extension_degree() {
error!(
target: LOG_TARGET,
"Generators' extension degree ({:?}) and proof's extension degree ({:?}) do not \
match; consider using a BulletproofsPlusService with a matching extension degree",
self.generators.extension_degree(),
rp.extension_degree()
);
}
error!(target: LOG_TARGET, "Internal range proof error ({})", e.to_string());
false
},
}
},
Err(e) => {
error!(
target: LOG_TARGET,
"Range proof could not be deserialized ({})",
e.to_string()
);
false
},
}
}
fn range(&self) -> usize {
self.generators.bit_length()
}
}
impl ExtendedRangeProofService for BulletproofsPlusService {
type K = RistrettoSecretKey;
type PK = RistrettoPublicKey;
type Proof = Vec<u8>;
fn construct_proof_with_recovery_seed_nonce(
&self,
mask: &Self::K,
value: u64,
seed_nonce: &Self::K,
) -> Result<Self::Proof, RangeProofError> {
let commitment = self
.generators
.pc_gens()
.commit(&Scalar::from(value), &[mask.0])
.map_err(|e| RangeProofError::ProofConstructionError { reason: e.to_string() })?;
let opening = CommitmentOpening::new(value, vec![mask.0]);
let witness = RangeWitness::init(vec![opening])
.map_err(|e| RangeProofError::ProofConstructionError { reason: e.to_string() })?;
let statement = RangeStatement::init(
self.generators.clone(),
vec![commitment],
vec![None],
Some(seed_nonce.0),
)
.map_err(|e| RangeProofError::ProofConstructionError { reason: e.to_string() })?;
let proof = RistrettoRangeProof::prove(self.transcript_label, &statement, &witness)
.map_err(|e| RangeProofError::ProofConstructionError { reason: e.to_string() })?;
Ok(proof.to_bytes())
}
fn construct_extended_proof(
&self,
extended_witnesses: Vec<RistrettoExtendedWitness>,
seed_nonce: Option<Self::K>,
) -> Result<Self::Proof, RangeProofError> {
if extended_witnesses.is_empty() {
return Err(RangeProofError::ProofConstructionError {
reason: "Extended witness vector cannot be empty".to_string(),
});
}
let mut commitments = Vec::with_capacity(extended_witnesses.len());
let mut openings = Vec::with_capacity(extended_witnesses.len());
let mut min_value_promises = Vec::with_capacity(extended_witnesses.len());
for witness in &extended_witnesses {
commitments.push(
self.generators
.pc_gens()
.commit(&Scalar::from(witness.value), &Vec::try_from(&witness.mask)?)
.map_err(|e| RangeProofError::ProofConstructionError { reason: e.to_string() })?,
);
openings.push(CommitmentOpening::new(witness.value, Vec::try_from(&witness.mask)?));
min_value_promises.push(witness.minimum_value_promise);
}
let witness = RangeWitness::init(openings)
.map_err(|e| RangeProofError::ProofConstructionError { reason: e.to_string() })?;
let statement = RangeStatement::init(
self.generators.clone(),
commitments,
min_value_promises.iter().map(|v| Some(*v)).collect(),
seed_nonce.map(|s| s.0),
)
.map_err(|e| RangeProofError::ProofConstructionError { reason: e.to_string() })?;
let proof = RistrettoRangeProof::prove(self.transcript_label, &statement, &witness)
.map_err(|e| RangeProofError::ProofConstructionError { reason: e.to_string() })?;
Ok(proof.to_bytes())
}
fn verify_batch_and_recover_masks(
&self,
proofs: Vec<&Self::Proof>,
statements: Vec<&RistrettoAggregatedPrivateStatement>,
) -> Result<Vec<Option<RistrettoExtendedMask>>, RangeProofError> {
// Prepare the range statements
let range_statements = self.prepare_private_range_statements(statements);
// Deserialize the range proofs
let range_proofs = self.deserialize_range_proofs(&proofs)?;
// Verify and recover
let mut recovered_extended_masks = Vec::new();
match RistrettoRangeProof::verify_batch(
self.transcript_label,
&range_statements,
&range_proofs,
VerifyAction::RecoverAndVerify,
) {
Ok(recovered_masks) => {
if recovered_masks.is_empty() {
// A mask vector should always be returned so this is a valid error condition
return Err(RangeProofError::InvalidRewind {
reason: "Range proof(s) verified Ok, but no mask vector returned".to_string(),
});
} else {
for recovered_mask in recovered_masks {
if let Some(mask) = &recovered_mask {
recovered_extended_masks.push(Some(RistrettoExtendedMask::try_from(mask)?));
} else {
recovered_extended_masks.push(None);
}
}
}
},
Err(e) => {
return Err(RangeProofError::InvalidRangeProof {
reason: format!("Internal range proof(s) error ({e})"),
})
},
};
Ok(recovered_extended_masks)
}
fn verify_batch(
&self,
proofs: Vec<&Self::Proof>,
statements: Vec<&RistrettoAggregatedPublicStatement>,
) -> Result<(), RangeProofError> {
// Prepare the range statements
let range_statements = self.prepare_public_range_statements(statements);
// Deserialize the range proofs
let range_proofs = self.deserialize_range_proofs(&proofs)?;
// Verify
match RistrettoRangeProof::verify_batch(
self.transcript_label,
&range_statements,
&range_proofs,
VerifyAction::VerifyOnly,
) {
Ok(_) => Ok(()),
Err(e) => Err(RangeProofError::InvalidRangeProof {
reason: format!("Internal range proof(s) error ({e})"),
}),
}
}
fn recover_mask(
&self,
proof: &Self::Proof,
commitment: &HomomorphicCommitment<Self::PK>,
seed_nonce: &Self::K,
) -> Result<Self::K, RangeProofError> {
match RistrettoRangeProof::from_bytes(proof)
.map_err(|e| RangeProofError::InvalidRangeProof { reason: e.to_string() })
{
Ok(rp) => {
let statement = RangeStatement {
generators: self.generators.clone(),
commitments: vec![commitment.0.point()],
commitments_compressed: vec![*commitment.0.compressed()],
minimum_value_promises: vec![None],
seed_nonce: Some(seed_nonce.0),
};
// Prepare the range statement
match RistrettoRangeProof::verify_batch(
self.transcript_label,
&vec![statement],
&[rp],
VerifyAction::RecoverOnly,
) {
Ok(recovered_mask) => {
if recovered_mask.is_empty() {
Err(RangeProofError::InvalidRewind {
reason: "Mask could not be recovered".to_string(),
})
} else if let Some(mask) = &recovered_mask[0] {
Ok(RistrettoSecretKey(
mask.blindings()
.map_err(|e| RangeProofError::InvalidRewind { reason: e.to_string() })?[0],
))
} else {
Err(RangeProofError::InvalidRewind {
reason: "Mask could not be recovered".to_string(),
})
}
},
Err(e) => Err(RangeProofError::InvalidRangeProof {
reason: format!("Internal range proof error ({e})"),
}),
}
},
Err(e) => Err(RangeProofError::InvalidRangeProof {
reason: format!("Range proof could not be deserialized ({e})"),
}),
}
}
fn recover_extended_mask(
&self,
proof: &Self::Proof,
statement: &RistrettoAggregatedPrivateStatement,
) -> Result<Option<RistrettoExtendedMask>, RangeProofError> {
match RistrettoRangeProof::from_bytes(proof)
.map_err(|e| RangeProofError::InvalidRangeProof { reason: e.to_string() })
{
Ok(rp) => {
// Prepare the range statement
let range_statements = self.prepare_private_range_statements(vec![statement]);
match RistrettoRangeProof::verify_batch(
self.transcript_label,
&range_statements,
&[rp],
VerifyAction::RecoverOnly,
) {
Ok(recovered_mask) => {
if recovered_mask.is_empty() {
Ok(None)
} else if let Some(mask) = &recovered_mask[0] {
Ok(Some(RistrettoExtendedMask::try_from(mask)?))
} else {
Ok(None)
}
},
Err(e) => Err(RangeProofError::InvalidRangeProof {
reason: format!("Internal range proof error ({e})"),
}),
}
},
Err(e) => Err(RangeProofError::InvalidRangeProof {
reason: format!("Range proof could not be deserialized ({e})"),
}),
}
}
fn verify_mask(
&self,
commitment: &HomomorphicCommitment<Self::PK>,
mask: &Self::K,
value: u64,
) -> Result<bool, RangeProofError> {
match self
.generators
.pc_gens()
.commit(&Scalar::from(value), &[mask.0])
.map_err(|e| RangeProofError::RPExtensionDegree { reason: e.to_string() })
{
Ok(val) => Ok(val == commitment.0.point()),
Err(e) => Err(e),
}
}
fn verify_extended_mask(
&self,
commitment: &HomomorphicCommitment<Self::PK>,
extended_mask: &RistrettoExtendedMask,
value: u64,
) -> Result<bool, RangeProofError> {
match self
.generators
.pc_gens()
.commit(&Scalar::from(value), &Vec::try_from(extended_mask)?)
.map_err(|e| RangeProofError::RPExtensionDegree { reason: e.to_string() })
{
Ok(val) => Ok(val == commitment.0.point()),
Err(e) => Err(e),
}
}
}
#[cfg(test)]
mod test {
use std::{collections::HashMap, vec::Vec};
use bulletproofs_plus::protocols::scalar_protocol::ScalarProtocol;
use curve25519_dalek::scalar::Scalar;
use rand::Rng;
use crate::{
commitment::{
ExtendedHomomorphicCommitmentFactory,
ExtensionDegree as CommitmentExtensionDegree,
HomomorphicCommitmentFactory,
},
extended_range_proof::ExtendedRangeProofService,
range_proof::RangeProofService,
ristretto::{
bulletproofs_plus::{
BulletproofsPlusService,
RistrettoAggregatedPrivateStatement,
RistrettoAggregatedPublicStatement,
RistrettoExtendedMask,
RistrettoExtendedWitness,
RistrettoStatement,
},
pedersen::extended_commitment_factory::ExtendedPedersenCommitmentFactory,
RistrettoSecretKey,
},
};
static EXTENSION_DEGREE: [CommitmentExtensionDegree; 6] = [
CommitmentExtensionDegree::DefaultPedersen,
CommitmentExtensionDegree::AddOneBasePoint,
CommitmentExtensionDegree::AddTwoBasePoints,
CommitmentExtensionDegree::AddThreeBasePoints,
CommitmentExtensionDegree::AddFourBasePoints,
CommitmentExtensionDegree::AddFiveBasePoints,
];
/// 'BulletproofsPlusService' initialization should only succeed when both bit length and aggregation size are a
/// power of 2 and when bit_length <= 64
#[test]
fn test_service_init() {
for extension_degree in EXTENSION_DEGREE {
let factory = ExtendedPedersenCommitmentFactory::new_with_extension_degree(extension_degree).unwrap();
for bit_length in [1, 2, 4, 128] {
for aggregation_size in [1, 2, 64] {
let bullet_proofs_plus_service =
BulletproofsPlusService::init(bit_length, aggregation_size, factory.clone());
if bit_length.is_power_of_two() && aggregation_size.is_power_of_two() && bit_length <= 64 {
assert!(bullet_proofs_plus_service.is_ok());
} else {
assert!(bullet_proofs_plus_service.is_err());
}
}
}
}
}
/// The 'BulletproofsPlusService' interface 'construct_proof' should only accept Pedersen generators of
/// 'ExtensionDegree::Zero' with 'aggregation_size == 1' and values proportional to the bit length
#[test]
fn test_construct_verify_proof_no_recovery() {
let mut rng = rand::thread_rng();
for extension_degree in EXTENSION_DEGREE {
let factory = ExtendedPedersenCommitmentFactory::new_with_extension_degree(extension_degree).unwrap();
// bit length and aggregation size are chosen so that 'BulletProofsPlusService::init' will always succeed
for bit_length in [4, 64] {
for aggregation_size in [1, 16] {
let bulletproofs_plus_service =
BulletproofsPlusService::init(bit_length, aggregation_size, factory.clone()).unwrap();
for value in [0, 1, u64::MAX] {
let key = RistrettoSecretKey(Scalar::random_not_zero(&mut rng));
let proof = bulletproofs_plus_service.construct_proof(&key, value);
if extension_degree == CommitmentExtensionDegree::DefaultPedersen &&
aggregation_size == 1 &&
value >> (bit_length - 1) <= 1
{
assert!(proof.is_ok());
assert!(
bulletproofs_plus_service.verify(&proof.unwrap(), &factory.commit_value(&key, value))
);
} else {
assert!(proof.is_err());
}
}
}
}
}
}
#[test]
#[allow(clippy::too_many_lines)]
fn test_construct_verify_extended_proof_with_recovery() {
static BIT_LENGTH: [usize; 2] = [2, 64];
static AGGREGATION_SIZE: [usize; 2] = [2, 64];
let mut rng = rand::thread_rng();
for extension_degree in [
CommitmentExtensionDegree::DefaultPedersen,
CommitmentExtensionDegree::AddFiveBasePoints,
] {
let factory = ExtendedPedersenCommitmentFactory::new_with_extension_degree(extension_degree).unwrap();
// bit length and aggregation size are chosen so that 'BulletProofsPlusService::init' will always succeed
for bit_length in BIT_LENGTH {
// 0. Batch data
let mut private_masks: Vec<Option<RistrettoExtendedMask>> = vec![];
let mut public_masks: Vec<Option<RistrettoExtendedMask>> = vec![];
let mut proofs = vec![];
let mut statements_private = vec![];
let mut statements_public = vec![];
#[allow(clippy::mutable_key_type)]
let mut commitment_value_map_private = HashMap::new();
#[allow(clippy::cast_possible_truncation)]
let (value_min, value_max) = (0u64, ((1u128 << bit_length) - 1) as u64);
for aggregation_size in AGGREGATION_SIZE {
// 1. Prover's service
let bulletproofs_plus_service =
BulletproofsPlusService::init(bit_length, aggregation_size, factory.clone()).unwrap();
// 2. Create witness data
let mut statements = vec![];
let mut extended_witnesses = vec![];
for m in 0..aggregation_size {
let value = rng.gen_range(value_min..value_max);
let minimum_value_promise = if m == 0 { value / 3 } else { 0 };
let secrets =
vec![RistrettoSecretKey(Scalar::random_not_zero(&mut rng)); extension_degree as usize];
let extended_mask = RistrettoExtendedMask::assign(extension_degree, secrets.clone()).unwrap();
let commitment = factory.commit_value_extended(&secrets, value).unwrap();
statements.push(RistrettoStatement {
commitment: commitment.clone(),
minimum_value_promise,
});
extended_witnesses.push(RistrettoExtendedWitness {
mask: extended_mask.clone(),
value,
minimum_value_promise,
});
if m == 0 {
if aggregation_size == 1 {
private_masks.push(Some(extended_mask));
public_masks.push(None);
} else {
private_masks.push(None);
public_masks.push(None);
}
}
commitment_value_map_private.insert(commitment, value);
}
// 3. Generate the statement
let seed_nonce = if aggregation_size == 1 {
Some(RistrettoSecretKey(Scalar::random_not_zero(&mut rng)))
} else {
None
};
statements_private.push(
RistrettoAggregatedPrivateStatement::init(statements.clone(), seed_nonce.clone()).unwrap(),
);
statements_public.push(RistrettoAggregatedPublicStatement::init(statements).unwrap());
// 4. Create the proof
let proof = bulletproofs_plus_service.construct_extended_proof(extended_witnesses, seed_nonce);
proofs.push(proof.unwrap());
}
if proofs.is_empty() {
panic!("Proofs cannot be empty");
} else {
// 5. Verifier's service
let aggregation_factor = *AGGREGATION_SIZE.iter().max().unwrap();
let bulletproofs_plus_service =
BulletproofsPlusService::init(bit_length, aggregation_factor, factory.clone()).unwrap();
// 6. Verify the entire batch as the commitment owner, i.e. the prover self
// --- Only recover the masks
for (i, proof) in proofs.iter().enumerate() {
let recovered_private_mask = bulletproofs_plus_service
.recover_extended_mask(proof, &statements_private[i])
.unwrap();
assert_eq!(private_masks[i], recovered_private_mask);
for statement in &statements_private[i].statements {
if let Some(this_mask) = recovered_private_mask.clone() {
assert!(bulletproofs_plus_service
.verify_extended_mask(
&statement.commitment,
&this_mask,
*commitment_value_map_private.get(&statement.commitment).unwrap()
)
.unwrap());
}
}
}
// --- Recover the masks and verify the proofs
let statements_ref = statements_private.iter().collect::<Vec<_>>();
let proofs_ref = proofs.iter().collect::<Vec<_>>();
let recovered_private_masks = bulletproofs_plus_service
.verify_batch_and_recover_masks(proofs_ref.clone(), statements_ref.clone())
.unwrap();
assert_eq!(private_masks, recovered_private_masks);
for (index, aggregated_statement) in statements_private.iter().enumerate() {
for statement in &aggregated_statement.statements {
if let Some(this_mask) = recovered_private_masks[index].clone() {
// Verify the recovered mask
assert!(bulletproofs_plus_service
.verify_extended_mask(
&statement.commitment,
&this_mask,
*commitment_value_map_private.get(&statement.commitment).unwrap()
)
.unwrap());
// Also verify that the extended commitment factory can open the commitment
assert!(factory
.open_value_extended(
&this_mask.secrets(),
*commitment_value_map_private.get(&statement.commitment).unwrap(),
&statement.commitment,
)
.unwrap());
}
}
}
// // 7. Verify the entire batch as public entity
let statements_ref = statements_public.iter().collect::<Vec<_>>();
assert!(bulletproofs_plus_service
.verify_batch(proofs_ref, statements_ref)
.is_ok());
}
}
}
}
#[test]
fn test_simple_aggregated_extended_proof() {
let mut rng = rand::thread_rng();
let bit_length = 64;
for extension_degree in [
CommitmentExtensionDegree::DefaultPedersen,
CommitmentExtensionDegree::AddOneBasePoint,
] {
let factory = ExtendedPedersenCommitmentFactory::new_with_extension_degree(extension_degree).unwrap();
for aggregation_size in [2, 4] {
// 0. Batch data
let mut proofs = vec![];
let mut statements_public = vec![];
#[allow(clippy::cast_possible_truncation)]
let (value_min, value_max) = (0u64, ((1u128 << bit_length) - 1) as u64);
// 1. Prover's service
let bulletproofs_plus_service =
BulletproofsPlusService::init(bit_length, aggregation_size, factory.clone()).unwrap();
// 2. Create witness data
let mut statements = vec![];
let mut extended_witnesses = vec![];
for _m in 0..aggregation_size {
let value = rng.gen_range(value_min..value_max);
let minimum_value_promise = value / 3;
let secrets =
vec![RistrettoSecretKey(Scalar::random_not_zero(&mut rng)); extension_degree as usize];
let extended_mask = RistrettoExtendedMask::assign(extension_degree, secrets.clone()).unwrap();
let commitment = factory.commit_value_extended(&secrets, value).unwrap();
statements.push(RistrettoStatement {
commitment: commitment.clone(),
minimum_value_promise,
});
extended_witnesses.push(RistrettoExtendedWitness {
mask: extended_mask.clone(),
value,
minimum_value_promise,
});
}
// 3. Generate the statement
statements_public.push(RistrettoAggregatedPublicStatement::init(statements).unwrap());
// 4. Create the aggregated proof
let seed_nonce = None; // This only has meaning for non-aggregated proofs
let proof = bulletproofs_plus_service.construct_extended_proof(extended_witnesses, seed_nonce);
proofs.push(proof.unwrap());
// 5. Verifier's service
let bulletproofs_plus_service =
BulletproofsPlusService::init(bit_length, aggregation_size, factory.clone()).unwrap();
// 7. Verify the aggregated proof as public entity
let proofs_ref = proofs.iter().collect::<Vec<_>>();
let statements_ref = statements_public.iter().collect::<Vec<_>>();
assert!(bulletproofs_plus_service
.verify_batch(proofs_ref, statements_ref)
.is_ok());
}
}
}
#[test]
fn test_construct_verify_simple_extended_proof_with_recovery() {
let bit_length = 64usize;
let aggregation_size = 1usize;
let extension_degree = CommitmentExtensionDegree::DefaultPedersen;
let mut rng = rand::thread_rng();
let factory = ExtendedPedersenCommitmentFactory::new_with_extension_degree(extension_degree).unwrap();
#[allow(clippy::cast_possible_truncation)]
let (value_min, value_max) = (0u64, ((1u128 << bit_length) - 1) as u64);
// 1. Prover's service
let mut provers_bulletproofs_plus_service =
BulletproofsPlusService::init(bit_length, aggregation_size, factory.clone()).unwrap();
provers_bulletproofs_plus_service.custom_transcript_label("123 range proof");
// 2. Create witness data
let value = rng.gen_range(value_min..value_max);
let minimum_value_promise = value / 3;
let secrets = vec![RistrettoSecretKey(Scalar::random_not_zero(&mut rng)); extension_degree as usize];
let extended_mask = RistrettoExtendedMask::assign(extension_degree, secrets.clone()).unwrap();
let commitment = factory.commit_value_extended(&secrets, value).unwrap();
let extended_witness = RistrettoExtendedWitness {
mask: extended_mask.clone(),
value,
minimum_value_promise,
};
let private_mask = Some(extended_mask);
// 4. Create the proof
let seed_nonce = Some(RistrettoSecretKey(Scalar::random_not_zero(&mut rng)));
let proof = provers_bulletproofs_plus_service
.construct_extended_proof(vec![extended_witness.clone()], seed_nonce.clone())
.unwrap();
// 5. Verifier's service
let mut verifiers_bulletproofs_plus_service =
BulletproofsPlusService::init(bit_length, aggregation_size, factory.clone()).unwrap();
// 6. Verify as the commitment owner, i.e. the prover self
// --- Generate the private statement
let statement_private = RistrettoAggregatedPrivateStatement::init(
vec![RistrettoStatement {
commitment: commitment.clone(),
minimum_value_promise,
}],
seed_nonce,
)
.unwrap();
// --- Only recover the mask (use the wrong transcript label for the service - will fail)
let recovered_private_mask = verifiers_bulletproofs_plus_service
.recover_extended_mask(&proof, &statement_private)
.unwrap();
assert_ne!(private_mask, recovered_private_mask);
// --- Only recover the mask (use the correct transcript label for the service)
verifiers_bulletproofs_plus_service.custom_transcript_label("123 range proof");
let recovered_private_mask = verifiers_bulletproofs_plus_service
.recover_extended_mask(&proof, &statement_private)
.unwrap();
assert_eq!(private_mask, recovered_private_mask);
if let Some(this_mask) = recovered_private_mask {
assert!(verifiers_bulletproofs_plus_service
.verify_extended_mask(
&statement_private.statements[0].commitment,
&this_mask,
extended_witness.value,
)
.unwrap());
} else {
panic!("A mask should have been recovered!");
}
// --- Recover the masks and verify the proof
let recovered_private_masks = verifiers_bulletproofs_plus_service
.verify_batch_and_recover_masks(vec![&proof], vec![&statement_private])
.unwrap();
assert_eq!(vec![private_mask], recovered_private_masks);
if let Some(this_mask) = recovered_private_masks[0].clone() {
// Verify the recovered mask
assert!(verifiers_bulletproofs_plus_service
.verify_extended_mask(
&statement_private.statements[0].commitment,
&this_mask,
extended_witness.value,
)
.unwrap());
// Also verify that the extended commitment factory can open the commitment
assert!(factory
.open_value_extended(
&this_mask.secrets(),
extended_witness.value,
&statement_private.statements[0].commitment,
)
.unwrap());
} else {
panic!("A mask should have been recovered!");
}
// // 7. Verify the proof as public entity
let statement_public = RistrettoAggregatedPublicStatement::init(vec![RistrettoStatement {
commitment,
minimum_value_promise,
}])
.unwrap();
assert!(verifiers_bulletproofs_plus_service
.verify_batch(vec![&proof], vec![&statement_public])
.is_ok());
}
#[test]
fn test_construct_verify_simple_proof_with_recovery() {
let bit_length = 64usize;
let aggregation_size = 1usize;
let extension_degree = CommitmentExtensionDegree::DefaultPedersen;
let mut rng = rand::thread_rng();
let factory = ExtendedPedersenCommitmentFactory::new_with_extension_degree(extension_degree).unwrap();
#[allow(clippy::cast_possible_truncation)]
let (value_min, value_max) = (0u64, ((1u128 << bit_length) - 1) as u64);
// 1. Prover's service
let mut provers_bulletproofs_plus_service =
BulletproofsPlusService::init(bit_length, aggregation_size, factory.clone()).unwrap();
provers_bulletproofs_plus_service.custom_transcript_label("123 range proof");
// 2. Create witness data
let value = rng.gen_range(value_min..value_max);
let mask = RistrettoSecretKey(Scalar::random_not_zero(&mut rng));
let commitment = factory.commit_value(&mask, value);
// 4. Create the proof
let seed_nonce = RistrettoSecretKey(Scalar::random_not_zero(&mut rng));
let proof = provers_bulletproofs_plus_service
.construct_proof_with_recovery_seed_nonce(&mask, value, &seed_nonce)
.unwrap();
// 5. Verifier's service
let mut verifiers_bulletproofs_plus_service =
BulletproofsPlusService::init(bit_length, aggregation_size, factory.clone()).unwrap();
// 6. Mask recovery as the commitment owner, i.e. the prover self
// --- Recover the mask (use the wrong transcript label for the service - will fail)
let recovered_mask = verifiers_bulletproofs_plus_service
.recover_mask(&proof, &commitment, &seed_nonce)
.unwrap();
assert_ne!(mask, recovered_mask);
// --- Recover the mask (use the correct transcript label for the service)
verifiers_bulletproofs_plus_service.custom_transcript_label("123 range proof");
let recovered_mask = verifiers_bulletproofs_plus_service
.recover_mask(&proof, &commitment, &seed_nonce)
.unwrap();
assert_eq!(mask, recovered_mask);
// --- Verify that the mask opens the commitment
assert!(verifiers_bulletproofs_plus_service
.verify_mask(&commitment, &recovered_mask, value)
.unwrap());
// --- Also verify that the commitment factory can open the commitment
assert!(factory.open_value(&recovered_mask, value, &commitment));
// 7. Verify the proof as private or public entity
assert!(verifiers_bulletproofs_plus_service.verify(&proof, &commitment));
}
}
|
use std::fs;
use std::result::Result;
use rayon::prelude::*;
fn main() -> Result<(), String> {
let input = fs::read_to_string("input/data.txt").map_err(|e| e.to_string())?;
part1(&input);
part2(&input);
Ok(())
}
fn part1(input: &str) -> () {
let result = perform_reactions(input);
println!("Result = {}\nLength = {}", result, result.len());
}
fn part2(input: &str) -> () {
static ASCII_LOWER: [char; 26] = [
'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y',
'z',
];
let lengths: Vec<usize> = ASCII_LOWER.par_iter().map(|to_remove| {
let filtered = input.clone().chars().filter(|ch| !ch.eq_ignore_ascii_case(to_remove)).collect::<String>();
perform_reactions(&filtered).len()
}).collect();
let minimum = lengths.into_iter().fold(None, |min, curr| match min {
None => Some(curr),
Some(existing) => Some(if existing < curr { existing } else { curr })
});
println!("Min = {}", minimum.unwrap());
}
fn perform_reactions(input: &str) -> String {
let mut new_str = input.to_string();
loop {
let start_size = new_str.len();
new_str = perform_single_reaction_pass(&new_str);
if new_str.len() == start_size {
break;
}
}
new_str
}
fn perform_single_reaction_pass(input: &str) -> String {
let mut new_str = "".to_string();
let mut iter = input.chars().peekable();
while let Some(ch) = iter.next() {
match iter.peek() {
None => {
new_str.push(ch);
break;
},
Some(next_char) => {
if ch.eq_ignore_ascii_case(next_char) && casings_are_different(&ch, &next_char) {
iter.next();
} else {
new_str.push(ch);
}
}
}
}
new_str
}
fn casings_are_different(ch1: &char, ch2: &char) -> bool {
ch1.is_lowercase() && !ch2.is_lowercase() || !ch1.is_lowercase() && ch2.is_lowercase()
}
#[cfg(test)]
mod test_perform_reactions {
use super::{perform_single_reaction_pass, perform_reactions};
#[test]
fn no_reactions_single_letter() {
assert_eq!(perform_single_reaction_pass("a"), "a");
assert_eq!(perform_single_reaction_pass("A"), "A");
assert_eq!(perform_reactions("a"), "a");
assert_eq!(perform_reactions("A"), "A");
}
#[test]
fn no_reactions_different_letters() {
assert_eq!(perform_reactions("abcABC"), "abcABC");
assert_eq!(perform_reactions("aabbCCDD"), "aabbCCDD");
}
#[test]
fn single_reacting_pair() {
assert_eq!(perform_reactions("Aa"), "");
assert_eq!(perform_reactions("aA"), "");
}
#[test]
fn two_reacting_pairs() {
assert_eq!(perform_reactions("AabB"), "");
assert_eq!(perform_reactions("AaCbB"), "C");
}
#[test]
fn pair_after_removal() {
assert_eq!(perform_reactions("ACca"), "");
}
#[test]
fn pair_after_multi_removal() {
assert_eq!(perform_reactions("ZbACcaBz"), "");
}
}
|
// Copyright 2019, 2020 Wingchain
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::convert::TryInto;
use std::ffi::CStr;
use std::os::raw::{c_char, c_uchar, c_uint};
use std::path::Path;
#[cfg(unix)]
use libloading::os::unix as imp;
#[cfg(windows)]
use libloading::os::windows as imp;
use libloading::{Library, Symbol};
use primitives::errors::CommonResult;
use crate::hash::Hash;
use crate::{errors, HashLength};
type CallName = unsafe extern "C" fn() -> *mut c_char;
type CallNameFree = unsafe extern "C" fn(*mut c_char);
type CallHashLength = unsafe extern "C" fn() -> c_uint;
type CallHash = unsafe extern "C" fn(*mut c_uchar, c_uint, *const c_uchar, c_uint);
pub struct CustomLib {
#[allow(dead_code)]
/// lib is referred by symbols, should be kept
lib: Library,
name: String,
length: HashLength,
/// unsafe, should never out live lib
call_hash: imp::Symbol<CallHash>,
}
impl CustomLib {
pub fn new(path: &Path) -> CommonResult<Self> {
let err = |_| errors::ErrorKind::CustomLibLoadFailed(path.to_path_buf());
let lib = Library::new(path).map_err(err)?;
let (call_name, call_name_free, call_length, call_hash) = unsafe {
let call_name: Symbol<CallName> = lib.get(b"_crypto_hash_custom_name").map_err(err)?;
let call_name = call_name.into_raw();
let call_name_free: Symbol<CallNameFree> =
lib.get(b"_crypto_hash_custom_name_free").map_err(err)?;
let call_name_free = call_name_free.into_raw();
let call_length: Symbol<CallHashLength> =
lib.get(b"_crypto_hash_custom_length").map_err(err)?;
let call_length = call_length.into_raw();
let call_hash: Symbol<CallHash> = lib.get(b"_crypto_hash_custom_hash").map_err(err)?;
let call_hash = call_hash.into_raw();
(call_name, call_name_free, call_length, call_hash)
};
let name = Self::name(&call_name, &call_name_free, &path)?;
let length = Self::length(&call_length)?;
Ok(CustomLib {
lib,
name,
length,
call_hash,
})
}
fn name(
call_name: &imp::Symbol<CallName>,
call_name_free: &imp::Symbol<CallNameFree>,
path: &Path,
) -> CommonResult<String> {
let err = |_| errors::ErrorKind::InvalidName(format!("{:?}", path));
let name: String = unsafe {
let raw = call_name();
let name = CStr::from_ptr(raw).to_str().map_err(err)?;
let name = name.to_owned();
call_name_free(raw);
name
};
Ok(name)
}
fn length(call_length: &imp::Symbol<CallHashLength>) -> CommonResult<HashLength> {
let length: usize = unsafe {
let length = call_length();
length as usize
};
length.try_into()
}
}
impl Hash for CustomLib {
fn name(&self) -> String {
self.name.clone()
}
fn length(&self) -> HashLength {
self.length.clone()
}
fn hash(&self, out: &mut [u8], data: &[u8]) {
unsafe {
(self.call_hash)(
out.as_mut_ptr(),
out.len() as c_uint,
data.as_ptr(),
data.len() as c_uint,
);
};
}
}
#[macro_export]
macro_rules! declare_hash_custom_lib {
($impl:path) => {
use std::ffi::CString;
use std::os::raw::{c_char, c_uchar, c_uint};
#[no_mangle]
pub unsafe extern "C" fn _crypto_hash_custom_name() -> *mut c_char {
let name = $impl.name();
CString::new(name).expect("qed").into_raw()
}
#[no_mangle]
pub unsafe extern "C" fn _crypto_hash_custom_name_free(name: *mut c_char) {
unsafe {
assert!(!name.is_null());
CString::from_raw(name)
};
}
#[no_mangle]
pub extern "C" fn _crypto_hash_custom_length() -> c_uint {
let length: usize = $impl.length().into();
length as c_uint
}
#[no_mangle]
pub unsafe extern "C" fn _crypto_hash_custom_hash(
out: *mut c_uchar,
out_len: c_uint,
data: *const c_uchar,
data_len: c_uint,
) {
use std::slice;
let data = unsafe {
assert!(!data.is_null());
slice::from_raw_parts(data, data_len as usize)
};
let out = unsafe {
assert!(!out.is_null());
slice::from_raw_parts_mut(out, out_len as usize)
};
$impl.hash(out, data);
}
};
}
|
extern crate leap;
#[test]
fn test_vanilla_leap_year() {
assert_eq!(leap::is_leap_year(1996), true);
}
#[test]
#[ignore]
fn test_any_old_year() {
assert_eq!(leap::is_leap_year(1997), false);
}
#[test]
#[ignore]
fn test_century() {
assert_eq!(leap::is_leap_year(1900), false);
}
#[test]
#[ignore]
fn test_exceptional_century() {
assert_eq!(leap::is_leap_year(2000), true);
}
|
use super::DbIterator;
use super::tuple::Tuple;
#[derive(Debug, Clone)]
pub struct Projection<I> {
pub input: I,
pub columns: Vec<usize>,
}
impl <I: DbIterator> DbIterator for Projection<I>
where Self: Sized,
{
fn next(&mut self) -> Option<Tuple> {
// TODO assert that all cols exist
if let Some(tuple) = self.input.next() {
let new_data: Vec<Vec<_>> = self.columns.iter().map(|i| {
tuple[*i].to_vec() // try not to allocate?
}).collect();
Some(Tuple::new(new_data))
} else {
None
}
}
fn reset(&mut self) {
self.input.reset();
}
}
|
#[doc = "Register `IWDG_SIDR` reader"]
pub type R = crate::R<IWDG_SIDR_SPEC>;
#[doc = "Field `SID` reader - SID"]
pub type SID_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - SID"]
#[inline(always)]
pub fn sid(&self) -> SID_R {
SID_R::new(self.bits)
}
}
#[doc = "IWDG size identification register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`iwdg_sidr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct IWDG_SIDR_SPEC;
impl crate::RegisterSpec for IWDG_SIDR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`iwdg_sidr::R`](R) reader structure"]
impl crate::Readable for IWDG_SIDR_SPEC {}
#[doc = "`reset()` method sets IWDG_SIDR to value 0xa3c5_dd01"]
impl crate::Resettable for IWDG_SIDR_SPEC {
const RESET_VALUE: Self::Ux = 0xa3c5_dd01;
}
|
use std::{
collections::BTreeSet,
sync::{Arc, RwLock},
};
use crate::{SelectFilter, Selection};
#[derive(Debug)]
pub enum Filtered {
None,
Some(BTreeSet<usize>),
All,
}
/// Internal state is wrapped in an Arc, so cloning this is not very expensive
pub struct SelectState<T> {
pub(crate) options: Arc<[T]>,
pub(crate) selected_indices: Arc<RwLock<Selection>>,
pub(crate) filtered_indices: Arc<RwLock<Filtered>>,
filter_fn: SelectFilter<T>,
filter_input: Arc<RwLock<Option<String>>>,
}
impl<T> Clone for SelectState<T> {
fn clone(&self) -> Self {
Self {
options: self.options.clone(),
selected_indices: self.selected_indices.clone(),
filtered_indices: self.filtered_indices.clone(),
filter_fn: self.filter_fn.clone(),
filter_input: self.filter_input.clone(),
}
}
}
impl<T> PartialEq for SelectState<T> {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.options, &other.options)
&& Arc::ptr_eq(&self.selected_indices, &other.selected_indices)
&& Arc::ptr_eq(&self.filtered_indices, &other.filtered_indices)
&& self.filter_fn == other.filter_fn
&& Arc::ptr_eq(&self.filter_input, &other.filter_input)
}
}
impl<T> SelectState<T> {
// TODO: make filter optional?
pub fn new<I: Into<Arc<[T]>>, F: Into<SelectFilter<T>>>(
options: I,
selection: Selection,
filter_fn: F,
) -> Self {
Self {
options: options.into(),
selected_indices: Arc::new(RwLock::new(selection)),
filtered_indices: Arc::new(RwLock::new(Filtered::All)),
filter_fn: filter_fn.into(),
filter_input: Arc::new(RwLock::new(None)),
}
}
pub fn is_multiple(&self) -> bool {
if let Ok(inner) = self.selected_indices.read() {
inner.is_multiple()
} else {
// TODO: handle lock error?
false
}
}
pub fn is_nullable(&self) -> bool {
if let Ok(inner) = self.selected_indices.read() {
inner.is_nullable()
} else {
// TODO: handle lock error?
false
}
}
/// Replace the option set. You should probably use `replace_options_reselecting`
pub async fn replace_options<I: Into<Arc<[T]>>>(&mut self, options: I) {
if let Ok(mut inner) = self.selected_indices.write() {
match *inner {
Selection::MaybeOne(_) => *inner = Selection::none(),
Selection::AlwaysOne(_) => *inner = Selection::one(0),
Selection::Multiple(_) => *inner = Selection::empty(),
}
}
self.refilter().await;
self.options = options.into();
}
/// Replace the existing options and attempt to reeselect the existing selections
/// (if `Selection::AlwaysOne`, it will default to index 0 if not found)
pub async fn replace_options_reselecting<I: Into<Arc<[T]>>, F: Fn(&T, &T) -> bool>(
&mut self,
options: I,
selection_eq: F,
) {
let new_options: Arc<[T]> = options.into();
if let Ok(mut inner) = self.selected_indices.write() {
match *inner {
Selection::MaybeOne(None) => {} // Do nothing
Selection::MaybeOne(Some(index)) => {
*inner = Selection::MaybeOne(
self.options
.get(index)
.map(|item| new_options.iter().position(|t| (selection_eq)(item, t)))
.flatten(),
)
}
Selection::AlwaysOne(index) => {
*inner = Selection::one(
self.options
.get(index)
.map(|item| new_options.iter().position(|t| (selection_eq)(item, t)))
.flatten()
.unwrap_or_default(),
)
}
Selection::Multiple(ref indices) => {
*inner = Selection::Multiple(
indices
.iter()
.filter_map(|&i| {
self.options
.get(i)
.map(|item| {
new_options.iter().position(|t| (selection_eq)(item, t))
})
.flatten()
})
.collect(),
)
}
}
}
self.refilter().await;
self.options = new_options;
}
async fn filter_inner(&self, input: &str) {
if let Ok(mut filtered_indices) = self.filtered_indices.write() {
let indices = self
.options
.iter()
.enumerate()
.filter_map(|(i, item)| {
if self.filter_fn.call(item, input) {
Some(i)
} else {
None
}
})
.collect::<BTreeSet<usize>>();
*filtered_indices = if indices.is_empty() {
Filtered::None
} else {
Filtered::Some(indices)
}
}
}
async fn refilter(&self) {
if let Ok(input) = self.filter_input.read() {
if let Some(ref input) = *input {
self.filter_inner(input).await;
} else {
self.unfilter().await;
}
}
// TODO: handle errors
}
pub async fn filter(&self, input: &str) {
if input.is_empty() {
if let Ok(mut filter_input) = self.filter_input.write() {
*filter_input = Some(input.to_string());
} else {
// TODO: handle poison
}
self.filter_inner(input).await;
} else {
if let Ok(mut filter_input) = self.filter_input.write() {
*filter_input = None;
} else {
// TODO: handle poison
}
self.unfilter().await
}
}
pub async fn unfilter(&self) {
if let Ok(mut inner) = self.filtered_indices.write() {
*inner = Filtered::All;
}
}
// Expose the internal api of the options
pub fn get(&self, index: usize) -> Option<&T> {
self.options.get(index)
}
pub fn iter(&self) -> std::slice::Iter<T> {
self.options.iter()
}
pub fn first_selected(&self) -> Option<(usize, &T)> {
if let Ok(selected) = self.selected_indices.read() {
match *selected {
Selection::MaybeOne(None) => {}
Selection::AlwaysOne(index) | Selection::MaybeOne(Some(index)) => {
if let Some(item) = self.options.get(index) {
return Some((index, item));
}
}
Selection::Multiple(ref set) => {
if let Some(&index) = set.iter().next() {
if let Some(item) = self.options.get(index) {
return Some((index, item));
}
}
}
}
}
None
}
pub fn selected_items(&self) -> Vec<(usize, &T)> {
if let Ok(selected) = self.selected_indices.read() {
match *selected {
Selection::MaybeOne(None) => Vec::new(),
Selection::AlwaysOne(index) | Selection::MaybeOne(Some(index)) => {
if let Some(item) = self.options.get(index) {
vec![(index, item)]
} else {
Vec::new()
}
}
Selection::Multiple(ref set) => {
// let mut indices = set.iter().cloned().collect::<Vec<_>>();
// indices.sort_unstable();
let mut selected_items = Vec::with_capacity(set.len());
for &index in set {
if let Some(item) = self.options.get(index) {
selected_items.push((index, item))
}
}
selected_items
}
}
} else {
Vec::new()
}
}
pub fn first_filtered(&self) -> Option<(usize, &T)> {
if let Ok(filtered) = self.filtered_indices.read() {
match *filtered {
Filtered::All => {
if let Some(item) = self.options.first() {
return Some((0, item));
}
}
Filtered::Some(ref set) => {
if let Some(&index) = set.iter().next() {
if let Some(item) = self.options.get(index) {
return Some((index, item));
}
}
}
Filtered::None => {}
}
}
None
}
// Get an option item an it's global index using it's relative position in the filter list
pub fn get_filtered(&self, position: usize) -> Option<(usize, &T)> {
if let Ok(filtered) = self.filtered_indices.read() {
match *filtered {
Filtered::All => {
// If no filtering, position is equivalent to index
if let Some(item) = self.options.get(position) {
return Some((position, item));
}
}
Filtered::Some(ref set) => {
// If filtered, we need to find the global index of the item at this position
if let Some(&index) = set.iter().nth(position) {
if let Some(item) = self.options.get(index) {
return Some((index, item));
}
}
}
Filtered::None => {} // No elements means nothing at this position
}
}
None
}
pub fn filtered_items(&self) -> Vec<(usize, bool, &T)> {
if let (Ok(filtered), Ok(selected)) =
(self.filtered_indices.read(), self.selected_indices.read())
{
match *filtered {
Filtered::All => self
.options
.iter()
.enumerate()
.map(|(i, item)| (i, selected.includes(&i), item))
.collect::<Vec<_>>(),
Filtered::Some(ref set) => {
// let mut indices = set.iter().cloned().collect::<Vec<_>>();
// indices.sort_unstable();
let mut filtered_items = Vec::with_capacity(set.len());
for &index in set {
if let Some(item) = self.options.get(index) {
filtered_items.push((index, selected.includes(&index), item))
}
}
filtered_items
}
Filtered::None => Vec::new(),
}
} else {
Vec::new()
}
}
/// Select an index from the options.
/// Returns true if the selection has changed.
pub fn select(&self, index: usize) -> bool {
if index >= self.options.len() {
return false;
}
if let Ok(mut inner) = self.selected_indices.write() {
inner.select(index)
} else {
false
}
}
/// Deselect an index from the options.
/// Returns true if the selection has changed.
pub fn deselect(&self, index: usize) -> bool {
if index >= self.options.len() {
return false;
}
if let Ok(mut inner) = self.selected_indices.write() {
inner.deselect(index)
} else {
false
}
}
/// Clear the selected items.
/// Returns true if the selection has changed.
pub fn clear(&self) -> bool {
if let Ok(mut inner) = self.selected_indices.write() {
inner.clear()
} else {
false
}
}
}
|
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{parse_macro_input, DeriveInput};
struct FieldAttribute {
name: String,
value: String,
}
#[proc_macro_derive(Builder, attributes(builder))]
pub fn derive(input: TokenStream) -> TokenStream {
let parsed_input = parse_macro_input!(input as DeriveInput);
let struct_name = parsed_input.ident;
let struct_vis = parsed_input.vis;
let fields: Vec<syn::Field> = match parsed_input.data {
syn::Data::Struct(data) => match data.fields {
syn::Fields::Named(n) => n.named.iter().map(|f| f.clone()).collect(),
_ => unimplemented!(),
},
_ => unimplemented!(),
};
// make builder name
let builder_name = format_ident!("{}Builder", struct_name);
// grab the visibility, identifier name, and type of all struct fields
let field_name_types: Vec<(syn::Visibility, syn::Ident, syn::Type)> = fields
.iter()
.map(|field| {
(
field.vis.clone(),
field.ident.clone().unwrap(),
field.ty.clone(),
)
})
.collect();
// builder struct fields
let struct_fields =
field_name_types
.iter()
.map(|(vis, ident, ty)| match get_optional_type(ty) {
Some(_) => quote! {
#vis #ident: #ty
},
None => quote! {
#vis #ident: Option<#ty>
},
});
// declares builder struct
let builder_struct = quote! {
#struct_vis struct #builder_name {
#(#struct_fields),*
}
};
// defaults all fields in the builder to `None`
let init_builder_fields = field_name_types.iter().map(|(_, ident, _)| {
quote! {
#ident: None
}
});
// generates setter methods
let setters = field_name_types.iter().map(|(vis, ident, ty)| {
let optional = get_optional_type(ty);
match optional {
Some(inner_ty) => quote! {
#vis fn #ident(&mut self, arg: #inner_ty) -> &mut Self {
self.#ident = Some(arg);
self
}
},
None => quote! {
#vis fn #ident(&mut self, arg: #ty) -> &mut Self {
self.#ident = Some(arg);
self
}
},
}
});
let build_method_setters = field_name_types.iter().map(|(_, ident, ty)| {
let ident_str = ident.to_string();
match get_optional_type(ty) {
Some(_) => quote! {
#ident: self.#ident.clone(),
},
None => quote! {
#ident: match &self.#ident {
Some(v) => v.clone(),
None => return Err(format!("missing field {}", #ident_str).into()),
}
},
}
});
let expanded = quote! {
#builder_struct
impl #struct_name {
#struct_vis fn builder() -> #builder_name {
#builder_name {
#(#init_builder_fields),*
}
}
}
impl #builder_name {
pub fn build(&mut self) -> Result<#struct_name, Box<dyn std::error::Error + 'static>> {
Ok(#struct_name {
#(#build_method_setters),*
})
}
#(#setters)*
}
};
eprintln!("expanded: {}", expanded);
TokenStream::from(expanded)
}
fn get_generic_type(ty: &syn::Type) -> Option<(&syn::Ident, &syn::Type)> {
match ty {
syn::Type::Path(syn::TypePath {
qself: None,
path:
syn::Path {
leading_colon: None,
segments,
},
}) => match segments.iter().collect::<Vec<_>>().as_slice() {
[segment] => match &segment.arguments {
syn::PathArguments::AngleBracketed(args) => {
match args.args.iter().collect::<Vec<_>>().as_slice() {
[syn::GenericArgument::Type(ty)] => Some((&segment.ident, ty)),
_ => None,
}
}
_ => None,
},
_ => None,
},
_ => None,
}
}
fn get_optional_type(ty: &syn::Type) -> Option<&syn::Type> {
get_generic_type(ty).and_then(|(ident, ty)| match ident.to_string().as_str() {
"Option" => Some(ty),
_ => None,
})
}
|
#![allow(dead_code, clippy::unreadable_literal)]
use image;
use rayon::prelude::*;
const INTPUT_PATH: &str = "src/day8_input.txt";
const IMG_WIDTH: u32 = 25;
const IMG_HEIGHT: u32 = 6;
const IMG_SIZE: usize = IMG_HEIGHT as usize * IMG_WIDTH as usize;
pub fn solve_day_8_pt_1() -> u32 {
let input = std::fs::read_to_string(INTPUT_PATH).unwrap();
let mut idx = 0;
let mut final_idx = 0;
let mut min_zeros = std::u32::MAX;
while idx < input.len() {
let zeros = count_char(&input[idx..idx + IMG_SIZE], '0');
if zeros < min_zeros {
min_zeros = zeros;
final_idx = idx;
}
idx += IMG_SIZE;
}
let ones = count_char(&input[final_idx..final_idx + IMG_SIZE], '1');
let twos = count_char(&input[final_idx..final_idx + IMG_SIZE], '2');
ones * twos
}
pub fn alt_solve_day_8_pt_1() -> u32 {
let input = std::fs::read(INTPUT_PATH).unwrap();
let chunk = input
.par_chunks(IMG_SIZE)
.min_by_key(|chunk| chunk.iter().filter(|n| (**n) as char == '0').count())
.unwrap();
let ones = chunk.iter().filter(|n| (**n) as char == '1').count() as u32;
let twos = chunk.iter().filter(|n| (**n) as char == '2').count() as u32;
ones * twos
}
fn count_char(segment: &str, c: char) -> u32 {
let mut zero_count = 0;
for char in segment.chars() {
if char == c {
zero_count += 1;
}
}
zero_count
}
pub fn solve_day_8_pt_2() {
let input = std::fs::read_to_string(INTPUT_PATH).unwrap();
let mut img = [2; IMG_SIZE];
for (i, c) in input.chars().enumerate() {
if img[i % IMG_SIZE] == 2 {
let mut val = c.to_digit(10).unwrap() as u8;
if val == 1 {
val = 255;
}
img[i % IMG_SIZE] = val;
}
}
image::save_buffer(
"day8_pass.png",
&img,
IMG_WIDTH,
IMG_HEIGHT,
image::ColorType::L8,
)
.unwrap();
}
pub fn alt_solve_day_8_pt_2() {
let input = std::fs::read(INTPUT_PATH).unwrap();
let img: [u8; IMG_SIZE] = input
.chunks(IMG_SIZE)
.fold([2; IMG_SIZE], |mut acc, chunk| {
acc.iter_mut()
.zip(chunk.iter())
.for_each(|(pixel, rpixel)| {
if *pixel == 2 {
match *rpixel as char {
'0' => *pixel = 0,
'1' => *pixel = 255,
_ => {}
}
}
});
acc
});
image::save_buffer(
"alt_day8_pass.png",
&img,
IMG_WIDTH,
IMG_HEIGHT,
image::ColorType::L8,
)
.unwrap();
}
|
use std::iter;
use itertools::Itertools;
use crate::helpers;
pub fn solve_1() {
let input: Vec<u16> = helpers::input::nums!();
// our wall outlet is treated as having a value of 0, so we add that to our input for convenience
// also, the correct order of adapters is just sorted in ascending order.
let sequence = input.iter().chain(iter::once(&0)).sorted();
let jolt_differences = sequence.tuple_windows().map(|(a, b)| b - a);
let (ones, _twos, threes) =
// threes start at 1 because the difference between the last adapter's output and our device's input is always 3
jolt_differences.fold((0, 0, 1), |(ones, twos, threes), diff| match diff {
1 => (ones + 1, twos, threes),
2 => (ones, twos + 1, threes),
3 => (ones, twos, threes + 1),
_ => panic!("Invalid jolt difference of {}.", diff),
});
println!("The magic number is {}.", ones * threes);
}
pub fn solve_2() {
unimplemented!()
}
|
#![crate_name = "hy_syntax"]
#![comment = "Hydra Tokens, Scanner, Parser, and AST"]
#![license = "MIT"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![feature(macro_rules)]
#![feature(globs)]
#![allow(dead_code)]
#![allow(unused_variable)]
#![allow(unused_mut)]
#![allow(non_camel_case_types)]
#![allow(dead_assignment)]
extern crate debug;
pub mod token;
pub mod scanner;
pub mod ast;
pub mod parser; |
use num_cpus;
use std::sync::{Arc, Mutex};
use std::thread;
use std::collections::BTreeMap;
use op::*;
use collect_stream::collect_stream;
/* lazy_static allows us to define a global variable that needs initialization
* code (that code runs on the first time the variable is referenced).
* To use the NUM_WORKERS variable, you just need to dereference it, e.g.
* for _ in 0..*NUM_WORKERS { .. }
*/
lazy_static! {
static ref NUM_WORKERS: usize = num_cpus::get();
}
pub fn collect_par<T: Iterator<Item = f64>>(
source: T,
ops: Vec<Op>,
) -> Vec<f64> {
let mut v: Vec<f64> = source.collect(); // materialization to calculate size
let mut sector_size = v.len() / *NUM_WORKERS;
if v.len() % *NUM_WORKERS != 0 {
sector_size += 1;
}
for op in ops {
let mut reference: Arc<Vec<f64>> = Arc::new(v);
v = match op {
Op::Map(f) => {
let mut handlers: Vec<thread::JoinHandle<Vec<f64>>> = vec![];
let mut ret: Vec<f64> = vec![];
for sector in reference.chunks(sector_size) {
let f = f.clone(); // copy
let this_sector = sector.to_owned(); // need to be owned
let handler = thread::spawn(move || {this_sector.into_iter().map(|x| f(x)).collect()});
handlers.push(handler);
}
for h in handlers {
ret.extend(h.join().unwrap());
}
return ret;
}
Op::Filter(f) => {
let mut handlers: Vec<thread::JoinHandle<Vec<f64>>> = vec![];
let mut ret: Vec<f64> = vec![];
for sector in reference.chunks(sector_size) {
let f = f.clone(); // copy
let this_sector = sector.to_owned(); // need to be owned
let handler = thread::spawn(move || {this_sector.into_iter().filter(|x| f(x)).collect()});
handlers.push(handler);
}
for h in handlers {
ret.extend(h.join().unwrap());
}
return ret;
}
Op::GroupBy(key, group) => {
let mut handlers: Vec<thread::JoinHandle<_>> = vec![];
let map = Arc::new(Mutex::new(BTreeMap::new()));
let mut ret = vec![];
for sector in reference.chunks(sector_size) {
let key = key.clone();
let map_clone = map.clone();
let this_sector = sector.to_owned();
let handler = thread::spawn(move || {
for ele in this_sector {
let mut map = map_clone.lock().unwrap();
let k = key(ele);
if !map.contains_key(&k) {
let mut vec = Vec::new();
vec.push(ele.clone());
map.insert(k, vec);
} else {
let mut val = map.get_mut(&k).unwrap();
val.push(ele.clone());
}
}
});
handlers.push(handler);
}
for h in handlers {
h.join().unwrap();
}
for (key, val) in map.lock().unwrap().iter() {
ret.push(group(val));
}
ret
}
}
}
v
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AddressResponse {
#[serde(rename = "serviceIpAddress", default, skip_serializing_if = "Option::is_none")]
pub service_ip_address: Option<String>,
#[serde(rename = "internalIpAddress", default, skip_serializing_if = "Option::is_none")]
pub internal_ip_address: Option<String>,
#[serde(rename = "outboundIpAddresses", default, skip_serializing_if = "Vec::is_empty")]
pub outbound_ip_addresses: Vec<String>,
#[serde(rename = "vipMappings", default, skip_serializing_if = "Vec::is_empty")]
pub vip_mappings: Vec<VirtualIpMapping>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppServiceEnvironmentCollection {
pub value: Vec<AppServiceEnvironmentResource>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppServiceEnvironmentPatchResource {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<AppServiceEnvironment>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppServiceEnvironmentResource {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<AppServiceEnvironment>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HostingEnvironmentDiagnostics {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "diagnosicsOutput", default, skip_serializing_if = "Option::is_none")]
pub diagnosics_output: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetricAvailabilily {
#[serde(rename = "timeGrain", default, skip_serializing_if = "Option::is_none")]
pub time_grain: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub retention: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetricDefinition {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<metric_definition::Properties>,
}
pub mod metric_definition {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(rename = "primaryAggregationType", default, skip_serializing_if = "Option::is_none")]
pub primary_aggregation_type: Option<String>,
#[serde(rename = "metricAvailabilities", default, skip_serializing_if = "Vec::is_empty")]
pub metric_availabilities: Vec<MetricAvailabilily>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SkuInfo {
#[serde(rename = "resourceType", default, skip_serializing_if = "Option::is_none")]
pub resource_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<SkuDescription>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub capacity: Option<SkuCapacity>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SkuInfoCollection {
pub value: Vec<SkuInfo>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StampCapacityCollection {
pub value: Vec<StampCapacity>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Usage {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<usage::Properties>,
}
pub mod usage {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "resourceName", default, skip_serializing_if = "Option::is_none")]
pub resource_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(rename = "currentValue", default, skip_serializing_if = "Option::is_none")]
pub current_value: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<i64>,
#[serde(rename = "nextResetTime", default, skip_serializing_if = "Option::is_none")]
pub next_reset_time: Option<String>,
#[serde(rename = "computeMode", default, skip_serializing_if = "Option::is_none")]
pub compute_mode: Option<properties::ComputeMode>,
#[serde(rename = "siteMode", default, skip_serializing_if = "Option::is_none")]
pub site_mode: Option<String>,
}
pub mod properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ComputeMode {
Shared,
Dedicated,
Dynamic,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageCollection {
pub value: Vec<Usage>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WorkerPoolCollection {
pub value: Vec<WorkerPoolResource>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WorkerPoolResource {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<WorkerPool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<SkuDescription>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppServicePlanPatchResource {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<app_service_plan_patch_resource::Properties>,
}
pub mod app_service_plan_patch_resource {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
pub name: String,
#[serde(rename = "workerTierName", default, skip_serializing_if = "Option::is_none")]
pub worker_tier_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<properties::Status>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subscription: Option<String>,
#[serde(rename = "adminSiteName", default, skip_serializing_if = "Option::is_none")]
pub admin_site_name: Option<String>,
#[serde(rename = "hostingEnvironmentProfile", default, skip_serializing_if = "Option::is_none")]
pub hosting_environment_profile: Option<HostingEnvironmentProfile>,
#[serde(rename = "maximumNumberOfWorkers", default, skip_serializing_if = "Option::is_none")]
pub maximum_number_of_workers: Option<i32>,
#[serde(rename = "geoRegion", default, skip_serializing_if = "Option::is_none")]
pub geo_region: Option<String>,
#[serde(rename = "perSiteScaling", default, skip_serializing_if = "Option::is_none")]
pub per_site_scaling: Option<bool>,
#[serde(rename = "numberOfSites", default, skip_serializing_if = "Option::is_none")]
pub number_of_sites: Option<i32>,
#[serde(rename = "isSpot", default, skip_serializing_if = "Option::is_none")]
pub is_spot: Option<bool>,
#[serde(rename = "spotExpirationTime", default, skip_serializing_if = "Option::is_none")]
pub spot_expiration_time: Option<String>,
#[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")]
pub resource_group: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reserved: Option<bool>,
#[serde(rename = "targetWorkerCount", default, skip_serializing_if = "Option::is_none")]
pub target_worker_count: Option<i32>,
#[serde(rename = "targetWorkerSizeId", default, skip_serializing_if = "Option::is_none")]
pub target_worker_size_id: Option<i32>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<properties::ProvisioningState>,
}
pub mod properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
Ready,
Pending,
Creating,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Succeeded,
Failed,
Canceled,
InProgress,
Deleting,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HybridConnectionCollection {
pub value: Vec<HybridConnection>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HybridConnectionLimits {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<hybrid_connection_limits::Properties>,
}
pub mod hybrid_connection_limits {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub current: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub maximum: Option<i32>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceCollection {
pub value: Vec<String>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceMetricCollection {
pub value: Vec<ResourceMetric>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceMetric {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<ResourceMetricName>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(rename = "timeGrain", default, skip_serializing_if = "Option::is_none")]
pub time_grain: Option<String>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "metricValues", default, skip_serializing_if = "Vec::is_empty")]
pub metric_values: Vec<ResourceMetricValue>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub properties: Vec<ResourceMetricProperty>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceMetricName {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(rename = "localizedValue", default, skip_serializing_if = "Option::is_none")]
pub localized_value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceMetricValue {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timestamp: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub average: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub minimum: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub maximum: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub total: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<f32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub properties: Vec<ResourceMetricProperty>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceMetricProperty {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceMetricDefinitionCollection {
pub value: Vec<ResourceMetricDefinition>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceMetricDefinition {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<resource_metric_definition::Properties>,
}
pub mod resource_metric_definition {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<ResourceMetricName>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(rename = "primaryAggregationType", default, skip_serializing_if = "Option::is_none")]
pub primary_aggregation_type: Option<String>,
#[serde(rename = "metricAvailabilities", default, skip_serializing_if = "Vec::is_empty")]
pub metric_availabilities: Vec<ResourceMetricAvailability>,
#[serde(rename = "resourceUri", default, skip_serializing_if = "Option::is_none")]
pub resource_uri: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<serde_json::Value>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceMetricAvailability {
#[serde(rename = "timeGrain", default, skip_serializing_if = "Option::is_none")]
pub time_grain: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub retention: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProxyOnlyResource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<operation::Status>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub errors: Vec<ErrorEntity>,
#[serde(rename = "createdTime", default, skip_serializing_if = "Option::is_none")]
pub created_time: Option<String>,
#[serde(rename = "modifiedTime", default, skip_serializing_if = "Option::is_none")]
pub modified_time: Option<String>,
#[serde(rename = "expirationTime", default, skip_serializing_if = "Option::is_none")]
pub expiration_time: Option<String>,
#[serde(rename = "geoMasterOperationId", default, skip_serializing_if = "Option::is_none")]
pub geo_master_operation_id: Option<String>,
}
pub mod operation {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
InProgress,
Failed,
Succeeded,
TimedOut,
Created,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorEntity {
#[serde(rename = "extendedCode", default, skip_serializing_if = "Option::is_none")]
pub extended_code: Option<String>,
#[serde(rename = "messageTemplate", default, skip_serializing_if = "Option::is_none")]
pub message_template: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub parameters: Vec<String>,
#[serde(rename = "innerErrors", default, skip_serializing_if = "Vec::is_empty")]
pub inner_errors: Vec<ErrorEntity>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebAppCollection {
pub value: Vec<Site>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Site {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<site::Properties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<ManagedServiceIdentity>,
}
pub mod site {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<String>,
#[serde(rename = "hostNames", default, skip_serializing_if = "Vec::is_empty")]
pub host_names: Vec<String>,
#[serde(rename = "repositorySiteName", default, skip_serializing_if = "Option::is_none")]
pub repository_site_name: Option<String>,
#[serde(rename = "usageState", default, skip_serializing_if = "Option::is_none")]
pub usage_state: Option<properties::UsageState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
#[serde(rename = "enabledHostNames", default, skip_serializing_if = "Vec::is_empty")]
pub enabled_host_names: Vec<String>,
#[serde(rename = "availabilityState", default, skip_serializing_if = "Option::is_none")]
pub availability_state: Option<properties::AvailabilityState>,
#[serde(rename = "hostNameSslStates", default, skip_serializing_if = "Vec::is_empty")]
pub host_name_ssl_states: Vec<HostNameSslState>,
#[serde(rename = "serverFarmId", default, skip_serializing_if = "Option::is_none")]
pub server_farm_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reserved: Option<bool>,
#[serde(rename = "lastModifiedTimeUtc", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time_utc: Option<String>,
#[serde(rename = "siteConfig", default, skip_serializing_if = "Option::is_none")]
pub site_config: Option<SiteConfig>,
#[serde(rename = "trafficManagerHostNames", default, skip_serializing_if = "Vec::is_empty")]
pub traffic_manager_host_names: Vec<String>,
#[serde(rename = "scmSiteAlsoStopped", default, skip_serializing_if = "Option::is_none")]
pub scm_site_also_stopped: Option<bool>,
#[serde(rename = "targetSwapSlot", default, skip_serializing_if = "Option::is_none")]
pub target_swap_slot: Option<String>,
#[serde(rename = "hostingEnvironmentProfile", default, skip_serializing_if = "Option::is_none")]
pub hosting_environment_profile: Option<HostingEnvironmentProfile>,
#[serde(rename = "clientAffinityEnabled", default, skip_serializing_if = "Option::is_none")]
pub client_affinity_enabled: Option<bool>,
#[serde(rename = "clientCertEnabled", default, skip_serializing_if = "Option::is_none")]
pub client_cert_enabled: Option<bool>,
#[serde(rename = "hostNamesDisabled", default, skip_serializing_if = "Option::is_none")]
pub host_names_disabled: Option<bool>,
#[serde(rename = "outboundIpAddresses", default, skip_serializing_if = "Option::is_none")]
pub outbound_ip_addresses: Option<String>,
#[serde(rename = "possibleOutboundIpAddresses", default, skip_serializing_if = "Option::is_none")]
pub possible_outbound_ip_addresses: Option<String>,
#[serde(rename = "containerSize", default, skip_serializing_if = "Option::is_none")]
pub container_size: Option<i32>,
#[serde(rename = "dailyMemoryTimeQuota", default, skip_serializing_if = "Option::is_none")]
pub daily_memory_time_quota: Option<i32>,
#[serde(rename = "suspendedTill", default, skip_serializing_if = "Option::is_none")]
pub suspended_till: Option<String>,
#[serde(rename = "maxNumberOfWorkers", default, skip_serializing_if = "Option::is_none")]
pub max_number_of_workers: Option<i32>,
#[serde(rename = "cloningInfo", default, skip_serializing_if = "Option::is_none")]
pub cloning_info: Option<CloningInfo>,
#[serde(rename = "snapshotInfo", default, skip_serializing_if = "Option::is_none")]
pub snapshot_info: Option<SnapshotRecoveryRequest>,
#[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")]
pub resource_group: Option<String>,
#[serde(rename = "isDefaultContainer", default, skip_serializing_if = "Option::is_none")]
pub is_default_container: Option<bool>,
#[serde(rename = "defaultHostName", default, skip_serializing_if = "Option::is_none")]
pub default_host_name: Option<String>,
#[serde(rename = "slotSwapStatus", default, skip_serializing_if = "Option::is_none")]
pub slot_swap_status: Option<SlotSwapStatus>,
#[serde(rename = "httpsOnly", default, skip_serializing_if = "Option::is_none")]
pub https_only: Option<bool>,
}
pub mod properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum UsageState {
Normal,
Exceeded,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum AvailabilityState {
Normal,
Limited,
DisasterRecoveryMode,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HostNameSslState {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "sslState", default, skip_serializing_if = "Option::is_none")]
pub ssl_state: Option<host_name_ssl_state::SslState>,
#[serde(rename = "virtualIP", default, skip_serializing_if = "Option::is_none")]
pub virtual_ip: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thumbprint: Option<String>,
#[serde(rename = "toUpdate", default, skip_serializing_if = "Option::is_none")]
pub to_update: Option<bool>,
#[serde(rename = "hostType", default, skip_serializing_if = "Option::is_none")]
pub host_type: Option<host_name_ssl_state::HostType>,
}
pub mod host_name_ssl_state {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SslState {
Disabled,
SniEnabled,
IpBasedEnabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum HostType {
Standard,
Repository,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SiteConfig {
#[serde(rename = "numberOfWorkers", default, skip_serializing_if = "Option::is_none")]
pub number_of_workers: Option<i32>,
#[serde(rename = "defaultDocuments", default, skip_serializing_if = "Vec::is_empty")]
pub default_documents: Vec<String>,
#[serde(rename = "netFrameworkVersion", default, skip_serializing_if = "Option::is_none")]
pub net_framework_version: Option<String>,
#[serde(rename = "phpVersion", default, skip_serializing_if = "Option::is_none")]
pub php_version: Option<String>,
#[serde(rename = "pythonVersion", default, skip_serializing_if = "Option::is_none")]
pub python_version: Option<String>,
#[serde(rename = "nodeVersion", default, skip_serializing_if = "Option::is_none")]
pub node_version: Option<String>,
#[serde(rename = "linuxFxVersion", default, skip_serializing_if = "Option::is_none")]
pub linux_fx_version: Option<String>,
#[serde(rename = "requestTracingEnabled", default, skip_serializing_if = "Option::is_none")]
pub request_tracing_enabled: Option<bool>,
#[serde(rename = "requestTracingExpirationTime", default, skip_serializing_if = "Option::is_none")]
pub request_tracing_expiration_time: Option<String>,
#[serde(rename = "remoteDebuggingEnabled", default, skip_serializing_if = "Option::is_none")]
pub remote_debugging_enabled: Option<bool>,
#[serde(rename = "remoteDebuggingVersion", default, skip_serializing_if = "Option::is_none")]
pub remote_debugging_version: Option<String>,
#[serde(rename = "httpLoggingEnabled", default, skip_serializing_if = "Option::is_none")]
pub http_logging_enabled: Option<bool>,
#[serde(rename = "logsDirectorySizeLimit", default, skip_serializing_if = "Option::is_none")]
pub logs_directory_size_limit: Option<i32>,
#[serde(rename = "detailedErrorLoggingEnabled", default, skip_serializing_if = "Option::is_none")]
pub detailed_error_logging_enabled: Option<bool>,
#[serde(rename = "publishingUsername", default, skip_serializing_if = "Option::is_none")]
pub publishing_username: Option<String>,
#[serde(rename = "appSettings", default, skip_serializing_if = "Vec::is_empty")]
pub app_settings: Vec<NameValuePair>,
#[serde(rename = "connectionStrings", default, skip_serializing_if = "Vec::is_empty")]
pub connection_strings: Vec<ConnStringInfo>,
#[serde(rename = "machineKey", default, skip_serializing_if = "Option::is_none")]
pub machine_key: Option<SiteMachineKey>,
#[serde(rename = "handlerMappings", default, skip_serializing_if = "Vec::is_empty")]
pub handler_mappings: Vec<HandlerMapping>,
#[serde(rename = "documentRoot", default, skip_serializing_if = "Option::is_none")]
pub document_root: Option<String>,
#[serde(rename = "scmType", default, skip_serializing_if = "Option::is_none")]
pub scm_type: Option<site_config::ScmType>,
#[serde(rename = "use32BitWorkerProcess", default, skip_serializing_if = "Option::is_none")]
pub use32_bit_worker_process: Option<bool>,
#[serde(rename = "webSocketsEnabled", default, skip_serializing_if = "Option::is_none")]
pub web_sockets_enabled: Option<bool>,
#[serde(rename = "alwaysOn", default, skip_serializing_if = "Option::is_none")]
pub always_on: Option<bool>,
#[serde(rename = "javaVersion", default, skip_serializing_if = "Option::is_none")]
pub java_version: Option<String>,
#[serde(rename = "javaContainer", default, skip_serializing_if = "Option::is_none")]
pub java_container: Option<String>,
#[serde(rename = "javaContainerVersion", default, skip_serializing_if = "Option::is_none")]
pub java_container_version: Option<String>,
#[serde(rename = "appCommandLine", default, skip_serializing_if = "Option::is_none")]
pub app_command_line: Option<String>,
#[serde(rename = "managedPipelineMode", default, skip_serializing_if = "Option::is_none")]
pub managed_pipeline_mode: Option<site_config::ManagedPipelineMode>,
#[serde(rename = "virtualApplications", default, skip_serializing_if = "Vec::is_empty")]
pub virtual_applications: Vec<VirtualApplication>,
#[serde(rename = "loadBalancing", default, skip_serializing_if = "Option::is_none")]
pub load_balancing: Option<site_config::LoadBalancing>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub experiments: Option<Experiments>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limits: Option<SiteLimits>,
#[serde(rename = "autoHealEnabled", default, skip_serializing_if = "Option::is_none")]
pub auto_heal_enabled: Option<bool>,
#[serde(rename = "autoHealRules", default, skip_serializing_if = "Option::is_none")]
pub auto_heal_rules: Option<AutoHealRules>,
#[serde(rename = "tracingOptions", default, skip_serializing_if = "Option::is_none")]
pub tracing_options: Option<String>,
#[serde(rename = "vnetName", default, skip_serializing_if = "Option::is_none")]
pub vnet_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cors: Option<CorsSettings>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub push: Option<PushSettings>,
#[serde(rename = "apiDefinition", default, skip_serializing_if = "Option::is_none")]
pub api_definition: Option<ApiDefinitionInfo>,
#[serde(rename = "autoSwapSlotName", default, skip_serializing_if = "Option::is_none")]
pub auto_swap_slot_name: Option<String>,
#[serde(rename = "localMySqlEnabled", default, skip_serializing_if = "Option::is_none")]
pub local_my_sql_enabled: Option<bool>,
#[serde(rename = "ipSecurityRestrictions", default, skip_serializing_if = "Vec::is_empty")]
pub ip_security_restrictions: Vec<IpSecurityRestriction>,
#[serde(rename = "http20Enabled", default, skip_serializing_if = "Option::is_none")]
pub http20_enabled: Option<bool>,
#[serde(rename = "minTlsVersion", default, skip_serializing_if = "Option::is_none")]
pub min_tls_version: Option<site_config::MinTlsVersion>,
}
pub mod site_config {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ScmType {
None,
Dropbox,
Tfs,
LocalGit,
GitHub,
CodePlexGit,
CodePlexHg,
BitbucketGit,
BitbucketHg,
ExternalGit,
ExternalHg,
OneDrive,
#[serde(rename = "VSO")]
Vso,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ManagedPipelineMode {
Integrated,
Classic,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum LoadBalancing {
WeightedRoundRobin,
LeastRequests,
LeastResponseTime,
WeightedTotalTraffic,
RequestHash,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum MinTlsVersion {
#[serde(rename = "1.0")]
N1_0,
#[serde(rename = "1.1")]
N1_1,
#[serde(rename = "1.2")]
N1_2,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NameValuePair {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConnStringInfo {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "connectionString", default, skip_serializing_if = "Option::is_none")]
pub connection_string: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<conn_string_info::Type>,
}
pub mod conn_string_info {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
MySql,
#[serde(rename = "SQLServer")]
SqlServer,
#[serde(rename = "SQLAzure")]
SqlAzure,
Custom,
NotificationHub,
ServiceBus,
EventHub,
ApiHub,
DocDb,
RedisCache,
#[serde(rename = "PostgreSQL")]
PostgreSql,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SiteMachineKey {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub validation: Option<String>,
#[serde(rename = "validationKey", default, skip_serializing_if = "Option::is_none")]
pub validation_key: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub decryption: Option<String>,
#[serde(rename = "decryptionKey", default, skip_serializing_if = "Option::is_none")]
pub decryption_key: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HandlerMapping {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub extension: Option<String>,
#[serde(rename = "scriptProcessor", default, skip_serializing_if = "Option::is_none")]
pub script_processor: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub arguments: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualApplication {
#[serde(rename = "virtualPath", default, skip_serializing_if = "Option::is_none")]
pub virtual_path: Option<String>,
#[serde(rename = "physicalPath", default, skip_serializing_if = "Option::is_none")]
pub physical_path: Option<String>,
#[serde(rename = "preloadEnabled", default, skip_serializing_if = "Option::is_none")]
pub preload_enabled: Option<bool>,
#[serde(rename = "virtualDirectories", default, skip_serializing_if = "Vec::is_empty")]
pub virtual_directories: Vec<VirtualDirectory>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualDirectory {
#[serde(rename = "virtualPath", default, skip_serializing_if = "Option::is_none")]
pub virtual_path: Option<String>,
#[serde(rename = "physicalPath", default, skip_serializing_if = "Option::is_none")]
pub physical_path: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Experiments {
#[serde(rename = "rampUpRules", default, skip_serializing_if = "Vec::is_empty")]
pub ramp_up_rules: Vec<RampUpRule>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RampUpRule {
#[serde(rename = "actionHostName", default, skip_serializing_if = "Option::is_none")]
pub action_host_name: Option<String>,
#[serde(rename = "reroutePercentage", default, skip_serializing_if = "Option::is_none")]
pub reroute_percentage: Option<f64>,
#[serde(rename = "changeStep", default, skip_serializing_if = "Option::is_none")]
pub change_step: Option<f64>,
#[serde(rename = "changeIntervalInMinutes", default, skip_serializing_if = "Option::is_none")]
pub change_interval_in_minutes: Option<i32>,
#[serde(rename = "minReroutePercentage", default, skip_serializing_if = "Option::is_none")]
pub min_reroute_percentage: Option<f64>,
#[serde(rename = "maxReroutePercentage", default, skip_serializing_if = "Option::is_none")]
pub max_reroute_percentage: Option<f64>,
#[serde(rename = "changeDecisionCallbackUrl", default, skip_serializing_if = "Option::is_none")]
pub change_decision_callback_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SiteLimits {
#[serde(rename = "maxPercentageCpu", default, skip_serializing_if = "Option::is_none")]
pub max_percentage_cpu: Option<f64>,
#[serde(rename = "maxMemoryInMb", default, skip_serializing_if = "Option::is_none")]
pub max_memory_in_mb: Option<i64>,
#[serde(rename = "maxDiskSizeInMb", default, skip_serializing_if = "Option::is_none")]
pub max_disk_size_in_mb: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutoHealRules {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub triggers: Option<AutoHealTriggers>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub actions: Option<AutoHealActions>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutoHealTriggers {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub requests: Option<RequestsBasedTrigger>,
#[serde(rename = "privateBytesInKB", default, skip_serializing_if = "Option::is_none")]
pub private_bytes_in_kb: Option<i32>,
#[serde(rename = "statusCodes", default, skip_serializing_if = "Vec::is_empty")]
pub status_codes: Vec<StatusCodesBasedTrigger>,
#[serde(rename = "slowRequests", default, skip_serializing_if = "Option::is_none")]
pub slow_requests: Option<SlowRequestsBasedTrigger>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RequestsBasedTrigger {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<i32>,
#[serde(rename = "timeInterval", default, skip_serializing_if = "Option::is_none")]
pub time_interval: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StatusCodesBasedTrigger {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<i32>,
#[serde(rename = "subStatus", default, skip_serializing_if = "Option::is_none")]
pub sub_status: Option<i32>,
#[serde(rename = "win32Status", default, skip_serializing_if = "Option::is_none")]
pub win32_status: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<i32>,
#[serde(rename = "timeInterval", default, skip_serializing_if = "Option::is_none")]
pub time_interval: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SlowRequestsBasedTrigger {
#[serde(rename = "timeTaken", default, skip_serializing_if = "Option::is_none")]
pub time_taken: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<i32>,
#[serde(rename = "timeInterval", default, skip_serializing_if = "Option::is_none")]
pub time_interval: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutoHealActions {
#[serde(rename = "actionType", default, skip_serializing_if = "Option::is_none")]
pub action_type: Option<auto_heal_actions::ActionType>,
#[serde(rename = "customAction", default, skip_serializing_if = "Option::is_none")]
pub custom_action: Option<AutoHealCustomAction>,
#[serde(rename = "minProcessExecutionTime", default, skip_serializing_if = "Option::is_none")]
pub min_process_execution_time: Option<String>,
}
pub mod auto_heal_actions {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ActionType {
Recycle,
LogEvent,
CustomAction,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutoHealCustomAction {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exe: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CorsSettings {
#[serde(rename = "allowedOrigins", default, skip_serializing_if = "Vec::is_empty")]
pub allowed_origins: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PushSettings {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<push_settings::Properties>,
}
pub mod push_settings {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "isPushEnabled")]
pub is_push_enabled: bool,
#[serde(rename = "tagWhitelistJson", default, skip_serializing_if = "Option::is_none")]
pub tag_whitelist_json: Option<String>,
#[serde(rename = "tagsRequiringAuth", default, skip_serializing_if = "Option::is_none")]
pub tags_requiring_auth: Option<String>,
#[serde(rename = "dynamicTagsJson", default, skip_serializing_if = "Option::is_none")]
pub dynamic_tags_json: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ApiDefinitionInfo {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IpSecurityRestriction {
#[serde(rename = "ipAddress")]
pub ip_address: String,
#[serde(rename = "subnetMask", default, skip_serializing_if = "Option::is_none")]
pub subnet_mask: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HostingEnvironmentProfile {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CloningInfo {
#[serde(rename = "correlationId", default, skip_serializing_if = "Option::is_none")]
pub correlation_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub overwrite: Option<bool>,
#[serde(rename = "cloneCustomHostNames", default, skip_serializing_if = "Option::is_none")]
pub clone_custom_host_names: Option<bool>,
#[serde(rename = "cloneSourceControl", default, skip_serializing_if = "Option::is_none")]
pub clone_source_control: Option<bool>,
#[serde(rename = "sourceWebAppId")]
pub source_web_app_id: String,
#[serde(rename = "hostingEnvironment", default, skip_serializing_if = "Option::is_none")]
pub hosting_environment: Option<String>,
#[serde(rename = "appSettingsOverrides", default, skip_serializing_if = "Option::is_none")]
pub app_settings_overrides: Option<serde_json::Value>,
#[serde(rename = "configureLoadBalancing", default, skip_serializing_if = "Option::is_none")]
pub configure_load_balancing: Option<bool>,
#[serde(rename = "trafficManagerProfileId", default, skip_serializing_if = "Option::is_none")]
pub traffic_manager_profile_id: Option<String>,
#[serde(rename = "trafficManagerProfileName", default, skip_serializing_if = "Option::is_none")]
pub traffic_manager_profile_name: Option<String>,
#[serde(rename = "ignoreQuotas", default, skip_serializing_if = "Option::is_none")]
pub ignore_quotas: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SnapshotRecoveryRequest {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<snapshot_recovery_request::Properties>,
}
pub mod snapshot_recovery_request {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "snapshotTime", default, skip_serializing_if = "Option::is_none")]
pub snapshot_time: Option<String>,
#[serde(rename = "recoveryTarget", default, skip_serializing_if = "Option::is_none")]
pub recovery_target: Option<SnapshotRecoveryTarget>,
pub overwrite: bool,
#[serde(rename = "recoverConfiguration", default, skip_serializing_if = "Option::is_none")]
pub recover_configuration: Option<bool>,
#[serde(rename = "ignoreConflictingHostNames", default, skip_serializing_if = "Option::is_none")]
pub ignore_conflicting_host_names: Option<bool>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SnapshotRecoveryTarget {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SlotSwapStatus {
#[serde(rename = "timestampUtc", default, skip_serializing_if = "Option::is_none")]
pub timestamp_utc: Option<String>,
#[serde(rename = "sourceSlotName", default, skip_serializing_if = "Option::is_none")]
pub source_slot_name: Option<String>,
#[serde(rename = "destinationSlotName", default, skip_serializing_if = "Option::is_none")]
pub destination_slot_name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedServiceIdentity {
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<managed_service_identity::Type>,
#[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
#[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")]
pub principal_id: Option<String>,
}
pub mod managed_service_identity {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
SystemAssigned,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
pub location: String,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppServicePlanCollection {
pub value: Vec<AppServicePlan>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppServicePlan {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<app_service_plan::Properties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<SkuDescription>,
}
pub mod app_service_plan {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
pub name: String,
#[serde(rename = "workerTierName", default, skip_serializing_if = "Option::is_none")]
pub worker_tier_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<properties::Status>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subscription: Option<String>,
#[serde(rename = "adminSiteName", default, skip_serializing_if = "Option::is_none")]
pub admin_site_name: Option<String>,
#[serde(rename = "hostingEnvironmentProfile", default, skip_serializing_if = "Option::is_none")]
pub hosting_environment_profile: Option<HostingEnvironmentProfile>,
#[serde(rename = "maximumNumberOfWorkers", default, skip_serializing_if = "Option::is_none")]
pub maximum_number_of_workers: Option<i32>,
#[serde(rename = "geoRegion", default, skip_serializing_if = "Option::is_none")]
pub geo_region: Option<String>,
#[serde(rename = "perSiteScaling", default, skip_serializing_if = "Option::is_none")]
pub per_site_scaling: Option<bool>,
#[serde(rename = "numberOfSites", default, skip_serializing_if = "Option::is_none")]
pub number_of_sites: Option<i32>,
#[serde(rename = "isSpot", default, skip_serializing_if = "Option::is_none")]
pub is_spot: Option<bool>,
#[serde(rename = "spotExpirationTime", default, skip_serializing_if = "Option::is_none")]
pub spot_expiration_time: Option<String>,
#[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")]
pub resource_group: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reserved: Option<bool>,
#[serde(rename = "targetWorkerCount", default, skip_serializing_if = "Option::is_none")]
pub target_worker_count: Option<i32>,
#[serde(rename = "targetWorkerSizeId", default, skip_serializing_if = "Option::is_none")]
pub target_worker_size_id: Option<i32>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<properties::ProvisioningState>,
}
pub mod properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
Ready,
Pending,
Creating,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Succeeded,
Failed,
Canceled,
InProgress,
Deleting,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SkuDescription {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tier: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub family: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub capacity: Option<i32>,
#[serde(rename = "skuCapacity", default, skip_serializing_if = "Option::is_none")]
pub sku_capacity: Option<SkuCapacity>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub locations: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub capabilities: Vec<Capability>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SkuCapacity {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub minimum: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub maximum: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default: Option<i32>,
#[serde(rename = "scaleType", default, skip_serializing_if = "Option::is_none")]
pub scale_type: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Capability {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CsmUsageQuotaCollection {
pub value: Vec<CsmUsageQuota>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CsmUsageQuota {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(rename = "nextResetTime", default, skip_serializing_if = "Option::is_none")]
pub next_reset_time: Option<String>,
#[serde(rename = "currentValue", default, skip_serializing_if = "Option::is_none")]
pub current_value: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<LocalizableString>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LocalizableString {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(rename = "localizedValue", default, skip_serializing_if = "Option::is_none")]
pub localized_value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualIpMapping {
#[serde(rename = "virtualIP", default, skip_serializing_if = "Option::is_none")]
pub virtual_ip: Option<String>,
#[serde(rename = "internalHttpPort", default, skip_serializing_if = "Option::is_none")]
pub internal_http_port: Option<i32>,
#[serde(rename = "internalHttpsPort", default, skip_serializing_if = "Option::is_none")]
pub internal_https_port: Option<i32>,
#[serde(rename = "inUse", default, skip_serializing_if = "Option::is_none")]
pub in_use: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppServiceEnvironment {
pub name: String,
pub location: String,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<app_service_environment::ProvisioningState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<app_service_environment::Status>,
#[serde(rename = "vnetName", default, skip_serializing_if = "Option::is_none")]
pub vnet_name: Option<String>,
#[serde(rename = "vnetResourceGroupName", default, skip_serializing_if = "Option::is_none")]
pub vnet_resource_group_name: Option<String>,
#[serde(rename = "vnetSubnetName", default, skip_serializing_if = "Option::is_none")]
pub vnet_subnet_name: Option<String>,
#[serde(rename = "virtualNetwork")]
pub virtual_network: VirtualNetworkProfile,
#[serde(rename = "internalLoadBalancingMode", default, skip_serializing_if = "Option::is_none")]
pub internal_load_balancing_mode: Option<app_service_environment::InternalLoadBalancingMode>,
#[serde(rename = "multiSize", default, skip_serializing_if = "Option::is_none")]
pub multi_size: Option<String>,
#[serde(rename = "multiRoleCount", default, skip_serializing_if = "Option::is_none")]
pub multi_role_count: Option<i32>,
#[serde(rename = "workerPools")]
pub worker_pools: Vec<WorkerPool>,
#[serde(rename = "ipsslAddressCount", default, skip_serializing_if = "Option::is_none")]
pub ipssl_address_count: Option<i32>,
#[serde(rename = "databaseEdition", default, skip_serializing_if = "Option::is_none")]
pub database_edition: Option<String>,
#[serde(rename = "databaseServiceObjective", default, skip_serializing_if = "Option::is_none")]
pub database_service_objective: Option<String>,
#[serde(rename = "upgradeDomains", default, skip_serializing_if = "Option::is_none")]
pub upgrade_domains: Option<i32>,
#[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")]
pub subscription_id: Option<String>,
#[serde(rename = "dnsSuffix", default, skip_serializing_if = "Option::is_none")]
pub dns_suffix: Option<String>,
#[serde(rename = "lastAction", default, skip_serializing_if = "Option::is_none")]
pub last_action: Option<String>,
#[serde(rename = "lastActionResult", default, skip_serializing_if = "Option::is_none")]
pub last_action_result: Option<String>,
#[serde(rename = "allowedMultiSizes", default, skip_serializing_if = "Option::is_none")]
pub allowed_multi_sizes: Option<String>,
#[serde(rename = "allowedWorkerSizes", default, skip_serializing_if = "Option::is_none")]
pub allowed_worker_sizes: Option<String>,
#[serde(rename = "maximumNumberOfMachines", default, skip_serializing_if = "Option::is_none")]
pub maximum_number_of_machines: Option<i32>,
#[serde(rename = "vipMappings", default, skip_serializing_if = "Vec::is_empty")]
pub vip_mappings: Vec<VirtualIpMapping>,
#[serde(rename = "environmentCapacities", default, skip_serializing_if = "Vec::is_empty")]
pub environment_capacities: Vec<StampCapacity>,
#[serde(rename = "networkAccessControlList", default, skip_serializing_if = "Vec::is_empty")]
pub network_access_control_list: Vec<NetworkAccessControlEntry>,
#[serde(rename = "environmentIsHealthy", default, skip_serializing_if = "Option::is_none")]
pub environment_is_healthy: Option<bool>,
#[serde(rename = "environmentStatus", default, skip_serializing_if = "Option::is_none")]
pub environment_status: Option<String>,
#[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")]
pub resource_group: Option<String>,
#[serde(rename = "frontEndScaleFactor", default, skip_serializing_if = "Option::is_none")]
pub front_end_scale_factor: Option<i32>,
#[serde(rename = "defaultFrontEndScaleFactor", default, skip_serializing_if = "Option::is_none")]
pub default_front_end_scale_factor: Option<i32>,
#[serde(rename = "apiManagementAccountId", default, skip_serializing_if = "Option::is_none")]
pub api_management_account_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub suspended: Option<bool>,
#[serde(rename = "dynamicCacheEnabled", default, skip_serializing_if = "Option::is_none")]
pub dynamic_cache_enabled: Option<bool>,
#[serde(rename = "clusterSettings", default, skip_serializing_if = "Vec::is_empty")]
pub cluster_settings: Vec<NameValuePair>,
#[serde(rename = "userWhitelistedIpRanges", default, skip_serializing_if = "Vec::is_empty")]
pub user_whitelisted_ip_ranges: Vec<String>,
}
pub mod app_service_environment {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Succeeded,
Failed,
Canceled,
InProgress,
Deleting,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
Preparing,
Ready,
Scaling,
Deleting,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum InternalLoadBalancingMode {
None,
Web,
Publishing,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualNetworkProfile {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subnet: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WorkerPool {
#[serde(rename = "workerSizeId", default, skip_serializing_if = "Option::is_none")]
pub worker_size_id: Option<i32>,
#[serde(rename = "computeMode", default, skip_serializing_if = "Option::is_none")]
pub compute_mode: Option<worker_pool::ComputeMode>,
#[serde(rename = "workerSize", default, skip_serializing_if = "Option::is_none")]
pub worker_size: Option<String>,
#[serde(rename = "workerCount", default, skip_serializing_if = "Option::is_none")]
pub worker_count: Option<i32>,
#[serde(rename = "instanceNames", default, skip_serializing_if = "Vec::is_empty")]
pub instance_names: Vec<String>,
}
pub mod worker_pool {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ComputeMode {
Shared,
Dedicated,
Dynamic,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StampCapacity {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "availableCapacity", default, skip_serializing_if = "Option::is_none")]
pub available_capacity: Option<i64>,
#[serde(rename = "totalCapacity", default, skip_serializing_if = "Option::is_none")]
pub total_capacity: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(rename = "computeMode", default, skip_serializing_if = "Option::is_none")]
pub compute_mode: Option<stamp_capacity::ComputeMode>,
#[serde(rename = "workerSize", default, skip_serializing_if = "Option::is_none")]
pub worker_size: Option<stamp_capacity::WorkerSize>,
#[serde(rename = "workerSizeId", default, skip_serializing_if = "Option::is_none")]
pub worker_size_id: Option<i32>,
#[serde(rename = "excludeFromCapacityAllocation", default, skip_serializing_if = "Option::is_none")]
pub exclude_from_capacity_allocation: Option<bool>,
#[serde(rename = "isApplicableForAllComputeModes", default, skip_serializing_if = "Option::is_none")]
pub is_applicable_for_all_compute_modes: Option<bool>,
#[serde(rename = "siteMode", default, skip_serializing_if = "Option::is_none")]
pub site_mode: Option<String>,
}
pub mod stamp_capacity {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ComputeMode {
Shared,
Dedicated,
Dynamic,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum WorkerSize {
Default,
Small,
Medium,
Large,
D1,
D2,
D3,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NetworkAccessControlEntry {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub action: Option<network_access_control_entry::Action>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub order: Option<i32>,
#[serde(rename = "remoteSubnet", default, skip_serializing_if = "Option::is_none")]
pub remote_subnet: Option<String>,
}
pub mod network_access_control_entry {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Action {
Permit,
Deny,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HybridConnection {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<hybrid_connection::Properties>,
}
pub mod hybrid_connection {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "serviceBusNamespace", default, skip_serializing_if = "Option::is_none")]
pub service_bus_namespace: Option<String>,
#[serde(rename = "relayName", default, skip_serializing_if = "Option::is_none")]
pub relay_name: Option<String>,
#[serde(rename = "relayArmUri", default, skip_serializing_if = "Option::is_none")]
pub relay_arm_uri: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hostname: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub port: Option<i32>,
#[serde(rename = "sendKeyName", default, skip_serializing_if = "Option::is_none")]
pub send_key_name: Option<String>,
#[serde(rename = "sendKeyValue", default, skip_serializing_if = "Option::is_none")]
pub send_key_value: Option<String>,
#[serde(rename = "serviceBusSuffix", default, skip_serializing_if = "Option::is_none")]
pub service_bus_suffix: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HybridConnectionKey {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<hybrid_connection_key::Properties>,
}
pub mod hybrid_connection_key {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "sendKeyName", default, skip_serializing_if = "Option::is_none")]
pub send_key_name: Option<String>,
#[serde(rename = "sendKeyValue", default, skip_serializing_if = "Option::is_none")]
pub send_key_value: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VnetInfo {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<vnet_info::Properties>,
}
pub mod vnet_info {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "vnetResourceId", default, skip_serializing_if = "Option::is_none")]
pub vnet_resource_id: Option<String>,
#[serde(rename = "certThumbprint", default, skip_serializing_if = "Option::is_none")]
pub cert_thumbprint: Option<String>,
#[serde(rename = "certBlob", default, skip_serializing_if = "Option::is_none")]
pub cert_blob: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub routes: Vec<VnetRoute>,
#[serde(rename = "resyncRequired", default, skip_serializing_if = "Option::is_none")]
pub resync_required: Option<bool>,
#[serde(rename = "dnsServers", default, skip_serializing_if = "Option::is_none")]
pub dns_servers: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VnetRoute {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<vnet_route::Properties>,
}
pub mod vnet_route {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "startAddress", default, skip_serializing_if = "Option::is_none")]
pub start_address: Option<String>,
#[serde(rename = "endAddress", default, skip_serializing_if = "Option::is_none")]
pub end_address: Option<String>,
#[serde(rename = "routeType", default, skip_serializing_if = "Option::is_none")]
pub route_type: Option<properties::RouteType>,
}
pub mod properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RouteType {
#[serde(rename = "DEFAULT")]
Default,
#[serde(rename = "INHERITED")]
Inherited,
#[serde(rename = "STATIC")]
Static,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VnetGateway {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<vnet_gateway::Properties>,
}
pub mod vnet_gateway {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "vnetName", default, skip_serializing_if = "Option::is_none")]
pub vnet_name: Option<String>,
#[serde(rename = "vpnPackageUri")]
pub vpn_package_uri: String,
}
}
|
mod content;
mod feed;
mod gen;
mod item;
mod markdown;
mod paths;
mod site;
mod site_url;
mod upload;
mod util;
#[cfg(test)]
mod tests;
use crate::site_url::{HrefUrl, ImgUrl};
use axum::{http::StatusCode, response::IntoResponse, routing::get_service, Router};
use camino::Utf8PathBuf;
use clap::{Parser, Subcommand};
use colored::Colorize;
use eyre::Result;
use futures::future::join_all;
use hotwatch::Hotwatch;
use lazy_static::lazy_static;
use paths::AbsPath;
use reqwest::Client;
use s3::creds::Credentials;
use s3::Bucket;
use s3::Region;
use site::{Site, SiteOptions};
use std::{collections::HashSet, io, net::SocketAddr, thread, time::Duration};
use tower_http::{services::ServeDir, trace::TraceLayer};
use tracing::{error, info};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use upload::SyncOpts;
use url::Url;
use util::parse_html_files;
#[derive(Parser, Debug)]
#[clap(version)]
struct Cli {
#[clap(subcommand)]
command: Commands,
/// Verbose output
#[clap(short, long)]
verbose: bool,
}
// FIXME edit/promote/demote should match against title or slug
// case insensitively.
#[derive(Subcommand, Debug)]
enum Commands {
/// Start a preview server
Watch,
/// Generate the site
Build,
/// Create a new post and open it for edit
Post {
#[clap(required = true)]
title: Vec<String>,
},
/// Create a new draft and open it for edit
Draft {
#[clap(required = true)]
title: Vec<String>,
},
/// Promote a draft to a post
Promote {
#[clap(required = true)]
pattern: Vec<String>,
},
/// Demote a post to a draft
Demote {
#[clap(required = true)]
pattern: Vec<String>,
},
/// Sync all generated files found in `.output`
Sync,
/// Upload files from `files` which aren't handled by the site generator
UploadFiles,
/// Dump a syntax binary, used to speedup SyntaxSet initialization
DumpSyntaxBinary,
/// Dump the CSS of a theme
DumpTheme { file: Utf8PathBuf },
/// Check external links
CheckExternalLinks,
}
lazy_static! {
static ref CURRENT_DIR: AbsPath = AbsPath::current_dir().unwrap();
static ref OUTPUT_DIR: AbsPath = CURRENT_DIR.join(".output");
static ref FILE_DIR: AbsPath = CURRENT_DIR.join("files");
}
static SITE_BUCKET: &str = "www.jonashietala.se";
static FILE_BUCKET: &str = "jonashietala-files";
static REGION: Region = Region::EuWest1;
#[tokio::main]
async fn main() -> Result<()> {
let cli = Cli::parse();
let log_level = if cli.verbose { "debug" } else { "info" };
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(format!(
"jonashietala_se={log_level},tower_http={log_level}"
)))
.with(tracing_subscriber::fmt::layer())
.init();
match &cli.command {
Commands::Build => {
build()?;
}
Commands::Watch => {
watch().await?;
}
Commands::Post { title } => {
gen::new_post(title.join(" "))?;
}
Commands::Draft { title } => {
gen::new_draft(title.join(" "))?;
}
Commands::Promote { pattern } => {
gen::promote(pattern.join(" "))?;
}
Commands::Demote { pattern } => {
gen::demote(pattern.join(" "))?;
}
Commands::Sync => {
// So we don't forget...
build()?;
upload::sync(SyncOpts {
dir: &OUTPUT_DIR,
bucket: site_bucket()?,
delete: true,
print_urls: false,
})
.await?;
}
Commands::UploadFiles => {
upload::sync(SyncOpts {
dir: &FILE_DIR,
bucket: file_bucket()?,
delete: false,
print_urls: true,
})
.await?;
}
Commands::DumpSyntaxBinary => {
markdown::dump_syntax_binary()?;
}
Commands::DumpTheme { file } => {
markdown::dump_theme(file)?;
}
Commands::CheckExternalLinks => {
check_external_links().await?;
}
}
Ok(())
}
fn site_bucket() -> Result<Bucket> {
let credentials = Credentials::default()?;
let bucket = Bucket::new(SITE_BUCKET, REGION.clone(), credentials)?.with_path_style();
Ok(bucket)
}
fn file_bucket() -> Result<Bucket> {
let credentials = Credentials::default()?;
let bucket = Bucket::new(FILE_BUCKET, REGION.clone(), credentials)?;
Ok(bucket)
}
fn build() -> Result<()> {
let site = Site::load_content(SiteOptions {
output_dir: OUTPUT_DIR.clone(),
input_dir: CURRENT_DIR.clone(),
clear_output_dir: true,
include_drafts: false,
})?;
site.render_all()?;
Ok(())
}
async fn watch() -> Result<()> {
let mut site = Site::load_content(SiteOptions {
output_dir: OUTPUT_DIR.clone(),
input_dir: CURRENT_DIR.clone(),
clear_output_dir: true,
include_drafts: true,
})?;
site.render_all()?;
tokio::task::spawn_blocking(move || {
let mut hotwatch = Hotwatch::new_with_custom_delay(Duration::from_millis(100))
.expect("hotwatch failed to initialize!");
hotwatch
.watch(".", move |event| {
if let Err(err) = site.file_changed(event) {
error!("{err}");
}
})
.expect("failed to watch folder!");
loop {
thread::sleep(Duration::from_secs(1));
}
});
let app: _ = Router::new()
.fallback(get_service(ServeDir::new(&*OUTPUT_DIR)).handle_error(handle_error))
.layer(TraceLayer::new_for_http());
let addr = SocketAddr::from(([127, 0, 0, 1], 8080));
info!("serving site on {addr}");
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await?;
Ok(())
}
async fn handle_error(err: io::Error) -> impl IntoResponse {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong... {err}"),
)
}
async fn check_external_links() -> Result<()> {
build()?;
let files = parse_html_files(&*OUTPUT_DIR)?;
let mut links = HashSet::new();
for file in files.values() {
// FIXME getting tons of error trying to connect: dns error: failed to lookup address information: Temporary failure in name resolution
for link in file.links.iter() {
if let HrefUrl::External(ref url) = link {
if url.scheme() != "mailto" {
links.insert(url);
}
}
}
for link in file.imgs.iter() {
if let ImgUrl::External(ref url) = link {
links.insert(url);
}
}
}
let client = Client::new();
let mut requests = Vec::new();
for link in links {
requests.push(check_external_link(&client, link));
}
join_all(requests).await;
Ok(())
}
async fn check_external_link(client: &Client, url: &Url) {
match client.get(url.as_str()).send().await {
Ok(response) => {
let status = response.status();
if status.is_success() {
// FIXME or only show errors? Lots of links here...
print!("{}", status.as_str().green());
} else {
print!("{}", status.as_str().red());
}
println!(" {url}");
}
Err(err) => {
println!("{} parsing {url}: {err}", "Error".red());
}
}
}
|
fn main() {
let a=[1,2,3,4,5];
let mut x=a.iter();
let mut y=x.next()
assert_eq!(1,*x.next().unwrap());
assert_eq!(1,*a.iter().next().unwrap());
assert_eq!(2,*x.next().unwrap());
assert_eq!(2,*a.iter().next().unwrap());
}
|
pub struct Point(f64, f64);
|
use crate::ParsingError;
use std::fmt;
use std::str::FromStr;
const PREFIX: &str = "bytes ";
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ContentRange {
start: u64,
end: u64,
total_length: u64,
}
impl ContentRange {
pub fn new(start: u64, end: u64, total_length: u64) -> ContentRange {
ContentRange {
start,
end,
total_length,
}
}
pub fn start(&self) -> u64 {
self.start
}
pub fn end(&self) -> u64 {
self.end
}
pub fn total_length(&self) -> u64 {
self.total_length
}
pub fn is_empty(&self) -> bool {
self.end == self.start
}
}
impl FromStr for ContentRange {
type Err = ParsingError;
fn from_str(s: &str) -> Result<ContentRange, Self::Err> {
let remaining = s
.strip_prefix(PREFIX)
.ok_or_else(|| ParsingError::TokenNotFound {
item: "ContentRange",
token: PREFIX.to_owned(),
full: s.into(),
})?;
let mut split_at_dash = remaining.split('-');
let start = split_at_dash.next().unwrap().parse()?;
let mut split_at_slash = split_at_dash
.next()
.ok_or_else(|| ParsingError::TokenNotFound {
item: "ContentRange",
token: "-".to_owned(),
full: s.into(),
})?
.split('/');
let end = split_at_slash.next().unwrap().parse()?;
let total_length = split_at_slash
.next()
.ok_or_else(|| ParsingError::TokenNotFound {
item: "ContentRange",
token: "/".to_owned(),
full: s.into(),
})?
.parse()?;
Ok(ContentRange {
start,
end,
total_length,
})
}
}
impl fmt::Display for ContentRange {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}{}-{}/{}",
PREFIX,
self.start(),
self.end(),
self.total_length()
)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse() {
let range = "bytes 172032-172489/172490"
.parse::<ContentRange>()
.unwrap();
assert_eq!(range.start(), 172032);
assert_eq!(range.end(), 172489);
assert_eq!(range.total_length(), 172490);
}
#[test]
fn test_parse_no_starting_token() {
let err = "something else".parse::<ContentRange>().unwrap_err();
assert_eq!(
err,
ParsingError::TokenNotFound {
item: "ContentRange",
token: "bytes ".to_string(),
full: "something else".to_string()
}
);
}
#[test]
fn test_parse_no_dash() {
let err = "bytes 100".parse::<ContentRange>().unwrap_err();
assert_eq!(
err,
ParsingError::TokenNotFound {
item: "ContentRange",
token: "-".to_string(),
full: "bytes 100".to_string()
}
);
}
#[test]
fn test_parse_no_slash() {
let err = "bytes 100-500".parse::<ContentRange>().unwrap_err();
assert_eq!(
err,
ParsingError::TokenNotFound {
item: "ContentRange",
token: "/".to_string(),
full: "bytes 100-500".to_string()
}
);
}
#[test]
fn test_display() {
let range = ContentRange {
start: 100,
end: 501,
total_length: 5000,
};
let txt = format!("{}", range);
assert_eq!(txt, "bytes 100-501/5000");
}
}
|
use crate::built_in::BuiltInChannel;
use crate::comm_queue::CommQueue;
use crate::prettyprint::PrettyPrintable;
use crate::prettyprint::PrettyPrintable::*;
use std::fmt;
use std::fmt::Display;
use uuid::Uuid;
#[derive(Clone, Debug, PartialEq)]
pub enum ProcCons<Binders> {
Parallel(Vec<ProcCons<Binders>>),
Unfreeze(ValueCons<Binders>),
Receive {
channel: ValueCons<Binders>,
binders: Binders,
body: Box<ProcCons<Binders>>,
},
New {
binders: Binders,
body: Box<ProcCons<Binders>>,
},
Tell {
channel: ValueCons<Binders>,
messages: Vec<ValueCons<Binders>>,
},
// Dummy values used at various points
BuiltInService(BuiltInChannel),
MemReplacement,
}
use crate::process::ProcCons::*;
#[derive(PartialEq, Clone, Debug, Eq, Hash)]
pub struct Path(pub Vec<String>);
/// Process with variable occurrence counts saved in the binders, for efficient
/// substitution in environments without garbage collector.
pub type Proc = ProcCons<Vec<u32>>;
/// Implements methods for processes that store occurrence counts in the
/// binders. The occurrence counts are necessary so that no superfluous
/// clones have to be generated during substitution.
impl Proc {
fn substitute(
&mut self,
replacement: &mut Vec<Value>,
depth: u32,
remaining_copies: &mut Vec<u32>,
) {
match self {
Parallel(ps) => {
for p in ps {
p.substitute(replacement, depth, remaining_copies);
}
}
Unfreeze(v) => {
v.substitute(replacement, depth, remaining_copies);
}
Receive {
channel: c,
binders: ocs,
body: b,
} => {
c.substitute(replacement, depth, remaining_copies);
b.substitute(
replacement,
depth + ocs.len() as u32,
remaining_copies,
);
}
New {
binders: ocs,
body: b,
} => {
b.substitute(
replacement,
depth + ocs.len() as u32,
remaining_copies,
);
}
Tell {
channel: c,
messages: ms,
} => {
c.substitute(replacement, depth, remaining_copies);
for m in ms {
m.substitute(replacement, depth, remaining_copies);
}
}
BuiltInService(_) => {}
MemReplacement => {}
}
}
fn beta(&mut self, mut values: Vec<Value>) {
let owned = std::mem::replace(self, MemReplacement);
let (mut ocs, mut body) = match owned {
Receive {
binders: ocs,
body: b,
..
} => (ocs, *b),
New {
binders: ocs,
body: b,
} => (ocs, *b),
_ => {
panic!("Invoked `beta`-rule on a non-binder struct: {:?}", self)
}
};
assert_eq!(ocs.len(), values.len());
body.substitute(&mut values, ocs.len() as u32, &mut ocs);
*self = body;
}
/// Recursive helper method for `explode`.
fn explode_rec(
self,
rcv_snd_buffer: &mut Vec<Proc>,
new_buffer: &mut Vec<Proc>,
) {
match self {
Parallel(ps) => {
for p in ps.into_iter() {
p.explode_rec(rcv_snd_buffer, new_buffer);
}
}
Unfreeze(Freeze(p)) => p.explode_rec(rcv_snd_buffer, new_buffer),
Unfreeze(sth_else) => panic!(
"Corrupt bytecode: `Unfreeze` was expected to contain \
`Freeze`, but contained {:?}",
sth_else
),
r @ Receive { .. } => rcv_snd_buffer.push(r),
s @ Tell { .. } => rcv_snd_buffer.push(s),
n @ New { .. } => new_buffer.push(n),
BuiltInService(n) => panic!(
"BuiltInService-process with name {:?} somehow ended up in a \
place where `explode_rec` has been invoked on it. This should \
never happen.",
n
),
MemReplacement => {
panic!(
"Attempted to `explode` the dummy element `MemReplacement`."
);
}
}
}
/// Eliminates `unfreeze-freeze`, flattens out nested `Parallel` processes,
/// keeps reducing everything until only `Receive`s, `Tell`s and `New`s
/// remain. The sends and receives are returned in first buffer. News
/// are returned separately in the second buffer.
/// No `Parallel` or `Unfreeze` processes will appear in the result.
pub fn explode(self) -> (Vec<Proc>, Vec<Proc>) {
let mut rcv_snd_buffer = Vec::new();
let mut new_buffer = Vec::new();
self.explode_rec(&mut rcv_snd_buffer, &mut new_buffer);
(rcv_snd_buffer, new_buffer)
}
/// Returns number of bound variables in `New` if it is one, and `None` if
/// this proc is not `New`.
fn num_new_vars(&self) -> Option<usize> {
match self {
New { binders: ocs, .. } => Some(ocs.len()),
_ => None,
}
}
/// Performs substitution on this term, replacing all bound variables by
/// fresh unforgeable names. This operation makes sense only on `New`,
/// and will panic for any other process.
pub fn supply_unforgeables(&mut self) {
let num_vars = self.num_new_vars().expect("Should be a `New`");
let uuids = (0..num_vars)
.map(|_i| Value::new_unforgeable_name())
.collect();
self.beta(uuids);
}
/// Repeatedly applies `comm`-rule until no two pairs of processes can
/// be combined any more.
/// Expects a vector that consists only of `Receive`s and `Tell`s.
/// Returns the irreducible residuum.
pub fn reduce_until_local_convergence(rcv_snds: Vec<Proc>) -> Vec<Proc> {
let mut comm_queue = CommQueue::new();
let mut news_queue = Vec::new(); // stack, but call it "queue" anyway
// enqueue all processes in the `comm` queue
for p in rcv_snds.into_iter() {
comm_queue.push_back(p);
}
let mut progress = true;
// as long as anything changes, repeatedly keep clearing both queues
while progress {
progress = false;
// clear the queue with `(receive, send)`-pairs
while let Some((mut rcv, snd)) = comm_queue.pop_front() {
progress = true;
if let Tell { messages: ms, .. } = snd {
match rcv {
// "delta reduction"
BuiltInService(b) => {
let (rcv_snd, news) =
b.handle_request(ms).explode();
for r in rcv_snd.into_iter() {
comm_queue.push_back(r);
}
news_queue.extend(news);
}
// "beta reduction"
_ => {
rcv.beta(ms);
let (rcv_snd, news) = rcv.explode();
for p in rcv_snd.into_iter() {
comm_queue.push_back(p);
}
news_queue.extend(news);
}
}
} else {
panic!(
"Fatal error: second component of a pair dequed from a \
`CommQueue` was not a `Tell`: {:?}",
snd
)
}
}
// clear the queue with `new`-binders by feeding UUIDs to them
while let Some(mut n) = news_queue.pop() {
progress = true;
n.supply_unforgeables();
let (rcv_snd, news) = n.explode();
for p in rcv_snd.into_iter() {
comm_queue.push_back(p);
}
news_queue.extend(news);
}
}
comm_queue.harvest()
}
/// Attempts to get the channel on which a process is sending or listening.
///
/// Returns `Some` value only if the channel is a `Receive` or a `Tell`,
/// otherwise returns `None`.
///
/// Does not check whether the channel is an actual name, or some random
/// unevaluated expression - checking it is left to the caller.
pub fn peek_channel(&self) -> Option<&Value> {
// This method caused: 1 bugs (last updated 2019-02-17)
match self {
Receive { channel: c, .. } => Some(c),
Tell { channel: c, .. } => Some(c),
_ => None,
}
}
pub fn is_built_in(&self) -> bool {
match self {
BuiltInService(_) => true,
_ => false
}
}
}
impl From<&Proc> for PrettyPrintable {
fn from(p: &Proc) -> PrettyPrintable {
match p {
Parallel(ps) => Delimited {
start: "{".to_string(),
content: ps
.iter()
.enumerate()
.map(|(idx, p)| {
if idx == ps.len() - 1 {
p.into()
} else {
Juxtaposition(vec![
p.into(),
Atom(" | ".to_string()),
])
}
})
.collect(),
end: "}".to_string(),
},
Tell {
channel: c,
messages: ms,
} => Juxtaposition(vec![
c.into(),
Delimited {
start: "![".to_string(),
content: ms.iter().map(|m| m.into()).collect(),
end: "]".to_string(),
},
]),
Receive {
channel: c,
binders: ocs,
body: b,
} => {
let num_binders = ocs.len();
Juxtaposition(vec![
c.into(),
Atom("?".to_string()),
Delimited {
start: "[".to_string(),
content:
ocs
.iter()
.enumerate()
.map(move |(idx, count)| if idx < num_binders - 1 {
Juxtaposition(vec![Atom(format!("{}", *count)), Atom(",".to_string())])
} else {
Atom(format!("{}", *count))
}).collect(),
end: "]".to_string()
},
Atom(".".to_string()),
b.as_ref().into(),
])
}
New {
binders: ocs,
body: b,
} => {
Juxtaposition(vec![
Atom("new".to_string()),
Delimited {
start: "[".to_string(),
content:
ocs.iter().map(|i| Atom(format!("{}", i))).collect(),
end: "]".to_string()
},
b.as_ref().into(),
])
},
Unfreeze(v) => Delimited {
start: "~(".to_string(),
content: vec![v.into()],
end: ")".to_string(),
},
BuiltInService(n) => {
Juxtaposition(vec![Atom("builtin-rcv:".to_string()), n.into()])
}
MemReplacement => Atom("<MemReplacementDummy>".to_string()),
}
}
}
impl Display for Proc {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = PrettyPrintable::from(self).pretty_print(60);
write!(f, "{}", s)
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum ValueCons<Binders> {
DeBruijnIndex(u32),
Freeze(Box<ProcCons<Binders>>),
// built-in values
U,
B(bool),
I(i32),
S(String),
// Representable names (path names eliminated by linker)
PathName(Path),
BuiltInChannelName(BuiltInChannel),
// Unrepresentable names used internally by the virtual machine
PathSurrogate(u64),
UnforgeableName(Uuid),
// Placeholder used during substitutions / beta-rule applications,
// needed for mem::replace. Not representable, should never occur
// in real terms.
Depleted,
}
pub type Value = ValueCons<Vec<u32>>;
use crate::process::ValueCons::*;
impl Value {
fn new_unforgeable_name() -> Value {
UnforgeableName(Uuid::new_v4())
}
fn substitute(
&mut self,
replacement: &mut Vec<Value>,
depth: u32, // how many bound vars are above this point
remaining_copies: &mut Vec<u32>,
) {
let num_vars = replacement.len();
match self {
DeBruijnIndex(i) => {
// `j` is the depth on which the referenced var is, the
// de-Bruijn index `i` is 1-based, that is, 1 corresponds to
// the most recently pushed variable.
let j = (depth - *i) as usize;
if j < num_vars {
if remaining_copies[j] > 1 {
let v = replacement[j].clone();
if let Depleted = v {
panic!("Fatal error: `Depleted` in var binding.");
}
*self = v;
remaining_copies[j] -= 1;
} else if remaining_copies[j] == 1 {
*self =
std::mem::replace(&mut replacement[j], Depleted);
remaining_copies[j] = 0;
} else {
panic!(
"Bytecode corrupted: \
invalid number of variable occurrences, \
at depth = {}, dbi = {}, self = {:?}",
depth, j, self
);
}
}
}
Freeze(p) => p.substitute(replacement, depth, remaining_copies),
PathName(_) => {}
PathSurrogate(_) => {}
UnforgeableName(_) => {}
BuiltInChannelName(_) => {}
Depleted => { /* thoughtfully & carefully do nothing */ }
U => { /* do nothing */ }
B(_) => { /* do nothing */ }
I(_) => { /* do nothing */ }
S(_) => { /* do nothing */ }
}
}
pub fn is_channel(&self) -> bool {
match self {
PathName(_) => true,
BuiltInChannelName(_) => true,
PathSurrogate(_) => true,
UnforgeableName(_) => true,
_ => false
}
}
}
impl From<&Value> for PrettyPrintable {
fn from(v: &Value) -> PrettyPrintable {
match v {
Freeze(p) => p.as_ref().into(),
PathName(path) => Atom(
path.0
.iter()
.map(|x| format!("/{}", x))
.collect::<Vec<String>>()
.join(""),
),
DeBruijnIndex(i) => Atom(format!("\u{2768}{}\u{2769}", i)),
PathSurrogate(x) => Atom(format!("\u{27ec}{}\u{27ed}", x)),
UnforgeableName(u) => Atom(format!("{}", u)),
BuiltInChannelName(c) => c.into(),
Depleted => Atom("<depleted>".to_string()),
U => Atom("()".to_string()),
B(b) => Atom(format!("{}", b)),
I(i) => Atom(format!("{}", i)),
S(s) => Atom(format!("\"{}\"", s.to_string())),
}
}
}
//=============================================================================
#[cfg(test)]
mod tests {
use super::Path;
use super::Proc;
use super::ProcCons::*;
use super::ValueCons::*;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
#[test]
fn test_path_eq() {
let a = Path(vec!["foo".to_string(), "bar".to_string()]);
let b = Path(vec!["foo".to_string(), "bar".to_string()]);
let c = Path(vec!["bar".to_string(), "baz".to_string()]);
assert_eq!(a, a);
assert_eq!(a, b);
assert_ne!(a, c);
assert_ne!(b, c);
let ha = {
let mut hasher = DefaultHasher::new();
a.hash(&mut hasher);
hasher.finish()
};
let hb = {
let mut hasher = DefaultHasher::new();
b.hash(&mut hasher);
hasher.finish()
};
assert_eq!(ha, hb);
}
#[test]
fn test_de_bruijn_indexing() {
let p = proc! {
(receive (/c) [x, y, z]
// 0 1 2 (depth)
// 2 4 1 (occurrence counts)
(new [u, v]
// 3 4 (depth)
// 1 1 (occurrence counts)
(send (/e) [x, y, z, u, v, x, y, y, y])
// 5 4 3 2 1 5 4 4 4 (de-Bruijn indices)
)
)
};
assert_eq!(
p,
Receive {
channel: value! { (/c) },
binders: vec![2, 4, 1],
body: Box::new(New {
binders: vec![1, 1],
body: Box::new(Tell {
channel: value! { (/e) },
messages: [5, 4, 3, 2, 1, 5, 4, 4, 4]
.into_iter()
.map(|i| DeBruijnIndex(*i))
.collect()
})
})
}
)
}
#[test]
fn test_beta_run_id() {
// listens on channel `/c`, unfreezes and runs whatever it receives
// as single argument.
let mut p = proc! { (receive (/c) [x] (unfreeze x)) };
assert_eq!(
p,
Receive {
channel: PathName(Path(vec!["c".to_string()])),
binders: vec![1],
body: Box::new(Unfreeze(DeBruijnIndex(1))) // dbi-1-based
}
);
// frozen terminated process
let q = value! { (freeze {}) };
p.beta(vec![q]);
let expected = proc! { (unfreeze (freeze {})) };
assert_eq!(p, expected);
}
#[test]
fn test_whitebox_substitute_repeated_values() {
let p = proc! {
(receive (/c) [x, y, z]
(new [u, v]
(send (/e) [x, y, z, u, v, x, y, y, y])
)
)
};
if let Receive {
body: b,
binders: mut occ_counts,
..
} = p
{
let mut body = *b;
let mut values = vec![value! { 42 }, value! { 58 }, value! { 100 }];
body.substitute(&mut values, 3, &mut occ_counts);
assert_eq!(
body,
proc! {
(new [u, v]
(send (/e) [42, 58, 100, u, v, 42, 58, 58, 58])
)
}
);
for i in 0..values.len() {
assert_eq!(&values[i], &Depleted);
assert_eq!(occ_counts[i], 0);
}
} else {
assert!(false);
}
}
#[test]
fn test_beta_repeated_values() {
let mut p = proc! {
(receive (/c) [x, y, z]
(new [u, v] (send (/e) [x, y, z, u, v, x, y, y, y]))
)
};
let values = vec![value! { 42 }, value! { 58 }, value! { 100 }];
p.beta(values);
assert_eq!(
p,
proc! {
(new [u, v]
(send (/e) [42, 58, 100, u, v, 42, 58, 58, 58])
)
}
);
}
#[test]
fn test_explode() {
let p = proc! { {
(unfreeze (freeze (unfreeze (freeze (send (/c) [42])))))
{
(receive (/c) [x] (unfreeze x))
(unfreeze (freeze (send (/x) [58])))
}
(unfreeze (freeze (unfreeze (freeze (send (/x) [142])))))
(unfreeze (freeze (new [x, y] (send x [y]))))
}};
let (rcv_snd, news) = p.explode();
assert_eq!(
rcv_snd,
vec![
proc! { (send (/c) [42]) },
proc! { (receive (/c) [x] (unfreeze x)) },
proc! { (send (/x) [58]) },
proc! { (send (/x) [142]) },
]
);
assert_eq!(news, vec![proc! { (new [x, y] (send x [y])) },]);
}
#[test]
fn test_local_comm_rule_single_step_empty_unfreeze_freeze() {
let res = Proc::reduce_until_local_convergence(vec![
proc! { (send (surrogate 42) [(freeze {})]) },
proc! { (receive (surrogate 42) [x] (unfreeze x)) },
]);
assert_eq!(res, vec![]);
}
#[test]
fn test_local_comm_rule_new_nested_pars() {
// CS-XVIp72
let res = Proc::reduce_until_local_convergence(vec![
proc! {
(receive (surrogate 0) [p] {
(receive (surrogate 1) [c] {
(send c [(surrogate 42)])
{}
})
(unfreeze p)
})
},
proc! {
(send (surrogate 0) [ (freeze {
{}
(new [a] {
(send (surrogate 1) [a])
(receive a [x] {
(send x [(surrogate 58)])
})
})
})])
},
]);
let expected_single_process = proc! {
(send (surrogate 42) [(surrogate 58)])
};
assert_eq!(res, vec![expected_single_process]);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.