text stringlengths 8 4.13M |
|---|
use crate::animation::{BlobAnims, BlobCurrentAnim, FireAnims, FrogAnims, JeanAnims};
use crate::component::{Animation, CoordinateSystem, Follow, Position, Sprite, Velocity};
use crate::image::{load_image, Image};
use randomize::PCG32;
use std::collections::HashMap;
use tiled::PropertyValue;
use ultraviolet::{Vec2, Vec3};
type BlobStorage = (Position, Velocity, Sprite, Animation<BlobAnims>);
pub(crate) fn jean(pos: Vec3) -> (Position, Velocity, Sprite, Animation<JeanAnims>) {
let (width, height, image) = load_image(include_bytes!("../assets/jean.png"));
let image = Image::new(image, Vec2::new(width as f32, height as f32));
let pos = Position(pos, CoordinateSystem::World);
let vel = Velocity::default();
let sprite = Sprite {
image,
frame_height: 32,
frame_index: 0,
};
let anim = Animation(JeanAnims::new());
(pos, vel, sprite, anim)
}
pub(crate) fn frog(
pos: Vec3,
follow: Follow,
) -> (Position, Velocity, Sprite, Animation<FrogAnims>, Follow) {
let (width, height, image) = load_image(include_bytes!("../assets/frog.png"));
let image = Image::new(image, Vec2::new(width as f32, height as f32));
let pos = Position(pos, CoordinateSystem::World);
let vel = Velocity::default();
let sprite = Sprite {
image,
frame_height: 19,
frame_index: 0,
};
let anim = Animation(FrogAnims::new());
(pos, vel, sprite, anim, follow)
}
pub(crate) fn blob(
pos: Vec3,
properties: &HashMap<String, PropertyValue>,
random: &mut PCG32,
) -> BlobStorage {
let (width, height, image) = load_image(include_bytes!("../assets/blob.png"));
let image = Image::new(image, Vec2::new(width as f32, height as f32));
let pos = Position(pos, CoordinateSystem::World);
let vel = Velocity::default();
let sprite = Sprite {
image,
frame_height: 25,
frame_index: 0,
};
let anim = Animation(BlobAnims::new(BlobCurrentAnim::new(
random,
properties.get("direction"),
)));
(pos, vel, sprite, anim)
}
pub(crate) fn fire(pos: Vec3, random: &mut PCG32) -> (Position, Sprite, Animation<FireAnims>) {
let (width, height, image) = load_image(include_bytes!("../assets/fire.png"));
let image = Image::new(image, Vec2::new(width as f32, height as f32));
let pos = Position(pos, CoordinateSystem::World);
let sprite = Sprite {
image,
frame_height: 32,
frame_index: 0,
};
let anim = Animation(FireAnims::new(random));
(pos, sprite, anim)
}
|
use std::fs;
use itertools::Itertools;
pub fn valid_sums(numbers: &Vec<usize>) -> Vec<usize> {
numbers.iter()
.combinations(2)
.filter(|c| !c.iter().all_equal())
.map(|c| c.into_iter().sum())
.collect()
}
pub fn day9(args: &[String]) -> i32 {
println!("Day 9");
if args.len() != 1 {
println!("Missing input file");
return -1;
}
let filename = &args[0];
println!("In file {}", filename);
let contents = fs::read_to_string(filename)
.expect("Something went wrong reading the file");
let numbers: Vec<usize> = contents.lines().map(|l| l.parse::<usize>().unwrap()).collect();
let p1 = part1(&numbers, 25).unwrap();
println!("Part 1: {}", p1);
let p2 = part2(&numbers, p1).unwrap();
println!("Part 2: {}", p2.0 + p2.1);
0
}
pub fn part1(numbers: &Vec<usize>, count: usize) -> Option<usize> {
for i in count..numbers.len() {
let sums = valid_sums(&numbers[i-count..i].to_vec());
if numbers[i] == 127 {
println!("{:?}", &numbers[i-count..i].to_vec());
}
match sums.iter().find(|&&s| s == numbers[i]) {
None => return Some(numbers[i]),
_ => (),
}
}
return None;
}
pub fn part2(numbers: &Vec<usize>, target: usize) -> Option<(usize, usize)> {
for i in 0..numbers.len() {
let mut sum = 0;
for j in i..numbers.len() {
if sum > target {
break;
}
if sum < target {
sum += numbers[j];
} else {
// matching sum
let n = &numbers[i..j].to_vec();
return Some((*n.iter().min().unwrap(), *n.iter().max().unwrap()));
}
}
}
return None;
}
|
extern crate rust_hawktracer;
use rust_hawktracer::*;
use std::ffi::CString;
use std::fs::File;
use std::io::Read;
use std::os::raw::c_char;
use std::thread;
use pyo3::prelude::*;
use s3::bucket::Bucket;
use s3::credentials::Credentials;
extern "C" {
fn download_file(url: *const c_char, destination: *const c_char) -> i32;
}
#[hawktracer(download_file_rs)]
fn download_file_rs(url: &str, destination: &str) -> i32 {
unsafe {
download_file(
CString::new(url).unwrap().as_ptr(),
CString::new(destination).unwrap().as_ptr(),
)
}
}
#[hawktracer(rotate_in_python)]
fn rotate_in_python(image_path: &str, file_pattern: &str) {
let code = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/rotate.py"));
let gil = Python::acquire_gil();
let executor = PyModule::from_code(gil.python(), &code, "rotate.py", "rotate").unwrap();
executor.call1("main", (image_path, file_pattern)).unwrap();
}
#[hawktracer(upload_to_s3)]
fn read_a_file(path: &str) -> Vec<u8> {
let mut file = File::open(path).unwrap();
let mut data = Vec::new();
file.read_to_end(&mut data).unwrap();
return data;
}
#[hawktracer(upload_to_s3)]
fn upload_to_s3(path: &str, name: &str) {
let mut data = Vec::new();
let mut file = File::open(path).unwrap();
file.read_to_end(&mut data).unwrap();
{
scoped_tracepoint!(_upload);
let bucket = Bucket::new(
"mkolny-fosdem-2020",
"eu-west-1".parse().unwrap(),
Credentials::default(),
)
.unwrap();
bucket
.put_object(name, &data, "application/octet-stream")
.unwrap();
}
}
fn main() {
let instance = HawktracerInstance::new();
let _listener = instance.create_listener(HawktracerListenerType::ToFile {
file_path: "rotate.htdump".into(),
buffer_size: 999999,
});
let url = "https://www.hawktracer.org/hawk.jpg";
let out_file_pattern = "rotated_{}.jpg";
let tmp_image = "/tmp/fosdem_demo_output.jpg";
let code = download_file_rs(url, tmp_image);
println!("Download result: {}", code);
let h1 = thread::spawn(move || {
rotate_in_python(tmp_image, &out_file_pattern);
});
let h2 = thread::spawn(move || {
upload_to_s3(tmp_image, "backup.jpg");
});
h1.join().unwrap();
h2.join().unwrap();
}
|
use librhd;
include!(concat!(env!("OUT_DIR"), "/version.rs"));
pub fn version(verbose: bool, colorize: bool) -> String {
match (verbose, colorize) {
(true, true) => {
format!("\x1b[32;1mrh {}\x1b[0m ({} {}) (built {})\nbinary: rh\n\
commit-hash: {}\ncommit-date: {}\nbuild-date: {}\n\
host: {}\nrelease: {}\n\n{}",
semver(), short_sha(), commit_date(), short_now(),
sha(), commit_date(), short_now(), target(), semver(),
librhd::version(verbose, colorize))
},
(true, false) => {
format!("rh {} ({} {}) (built {})\nbinary: rh\ncommit-hash: {}\n\
commit-date: {}\nbuild-date: {}\nhost: {}\nrelease: {}\n\n\
{}",
semver(), short_sha(), commit_date(), short_now(),
sha(), commit_date(), short_now(), target(), semver(),
librhd::version(verbose, colorize))
},
(false, true) => {
format!("\x1b[32;1mrh {}\x1b[0m ({} {}) (built {})\n{}",
semver(), short_sha(), commit_date(), short_now(),
librhd::version(verbose, colorize))
},
(false, false) => {
format!("rh {} ({} {}) (built {})\n{}",
semver(), short_sha(), commit_date(), short_now(),
librhd::version(verbose, colorize))
},
}
}
|
#[doc = "Register `APB1SMENR1` reader"]
pub type R = crate::R<APB1SMENR1_SPEC>;
#[doc = "Register `APB1SMENR1` writer"]
pub type W = crate::W<APB1SMENR1_SPEC>;
#[doc = "Field `TIM2SMEN` reader - TIM2 timer clocks enable during Sleep and Stop modes"]
pub type TIM2SMEN_R = crate::BitReader;
#[doc = "Field `TIM2SMEN` writer - TIM2 timer clocks enable during Sleep and Stop modes"]
pub type TIM2SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM6SMEN` reader - TIM6 timer clocks enable during Sleep and Stop modes"]
pub type TIM6SMEN_R = crate::BitReader;
#[doc = "Field `TIM6SMEN` writer - TIM6 timer clocks enable during Sleep and Stop modes"]
pub type TIM6SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM7SMEN` reader - TIM7 timer clocks enable during Sleep and Stop modes"]
pub type TIM7SMEN_R = crate::BitReader;
#[doc = "Field `TIM7SMEN` writer - TIM7 timer clocks enable during Sleep and Stop modes"]
pub type TIM7SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `LCDSMEN` reader - LCD clocks enable during Sleep and Stop modes"]
pub type LCDSMEN_R = crate::BitReader;
#[doc = "Field `LCDSMEN` writer - LCD clocks enable during Sleep and Stop modes"]
pub type LCDSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RTCAPBSMEN` reader - RTC APB clock enable during Sleep and Stop modes"]
pub type RTCAPBSMEN_R = crate::BitReader;
#[doc = "Field `RTCAPBSMEN` writer - RTC APB clock enable during Sleep and Stop modes"]
pub type RTCAPBSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `WWDGSMEN` reader - Window watchdog clocks enable during Sleep and Stop modes"]
pub type WWDGSMEN_R = crate::BitReader;
#[doc = "Field `WWDGSMEN` writer - Window watchdog clocks enable during Sleep and Stop modes"]
pub type WWDGSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SPI2SMEN` reader - SPI2 clocks enable during Sleep and Stop modes"]
pub type SPI2SMEN_R = crate::BitReader;
#[doc = "Field `SPI2SMEN` writer - SPI2 clocks enable during Sleep and Stop modes"]
pub type SPI2SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SP3SMEN` reader - SPI3 clocks enable during Sleep and Stop modes"]
pub type SP3SMEN_R = crate::BitReader;
#[doc = "Field `SP3SMEN` writer - SPI3 clocks enable during Sleep and Stop modes"]
pub type SP3SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USART2SMEN` reader - USART2 clocks enable during Sleep and Stop modes"]
pub type USART2SMEN_R = crate::BitReader;
#[doc = "Field `USART2SMEN` writer - USART2 clocks enable during Sleep and Stop modes"]
pub type USART2SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USART3SMEN` reader - USART3 clocks enable during Sleep and Stop modes"]
pub type USART3SMEN_R = crate::BitReader;
#[doc = "Field `USART3SMEN` writer - USART3 clocks enable during Sleep and Stop modes"]
pub type USART3SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `UART4SMEN` reader - UART4 clocks enable during Sleep and Stop modes"]
pub type UART4SMEN_R = crate::BitReader;
#[doc = "Field `UART4SMEN` writer - UART4 clocks enable during Sleep and Stop modes"]
pub type UART4SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C1SMEN` reader - I2C1 clocks enable during Sleep and Stop modes"]
pub type I2C1SMEN_R = crate::BitReader;
#[doc = "Field `I2C1SMEN` writer - I2C1 clocks enable during Sleep and Stop modes"]
pub type I2C1SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C2SMEN` reader - I2C2 clocks enable during Sleep and Stop modes"]
pub type I2C2SMEN_R = crate::BitReader;
#[doc = "Field `I2C2SMEN` writer - I2C2 clocks enable during Sleep and Stop modes"]
pub type I2C2SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C3SMEN` reader - I2C3 clocks enable during Sleep and Stop modes"]
pub type I2C3SMEN_R = crate::BitReader;
#[doc = "Field `I2C3SMEN` writer - I2C3 clocks enable during Sleep and Stop modes"]
pub type I2C3SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CRSSMEN` reader - CRS clock enable during Sleep and Stop modes"]
pub type CRSSMEN_R = crate::BitReader;
#[doc = "Field `CRSSMEN` writer - CRS clock enable during Sleep and Stop modes"]
pub type CRSSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CAN1SMEN` reader - CAN1 clocks enable during Sleep and Stop modes"]
pub type CAN1SMEN_R = crate::BitReader;
#[doc = "Field `CAN1SMEN` writer - CAN1 clocks enable during Sleep and Stop modes"]
pub type CAN1SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USBFSSMEN` reader - USB FS clock enable during Sleep and Stop modes"]
pub type USBFSSMEN_R = crate::BitReader;
#[doc = "Field `USBFSSMEN` writer - USB FS clock enable during Sleep and Stop modes"]
pub type USBFSSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PWRSMEN` reader - Power interface clocks enable during Sleep and Stop modes"]
pub type PWRSMEN_R = crate::BitReader;
#[doc = "Field `PWRSMEN` writer - Power interface clocks enable during Sleep and Stop modes"]
pub type PWRSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DAC1SMEN` reader - DAC1 interface clocks enable during Sleep and Stop modes"]
pub type DAC1SMEN_R = crate::BitReader;
#[doc = "Field `DAC1SMEN` writer - DAC1 interface clocks enable during Sleep and Stop modes"]
pub type DAC1SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OPAMPSMEN` reader - OPAMP interface clocks enable during Sleep and Stop modes"]
pub type OPAMPSMEN_R = crate::BitReader;
#[doc = "Field `OPAMPSMEN` writer - OPAMP interface clocks enable during Sleep and Stop modes"]
pub type OPAMPSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `LPTIM1SMEN` reader - Low power timer 1 clocks enable during Sleep and Stop modes"]
pub type LPTIM1SMEN_R = crate::BitReader;
#[doc = "Field `LPTIM1SMEN` writer - Low power timer 1 clocks enable during Sleep and Stop modes"]
pub type LPTIM1SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - TIM2 timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn tim2smen(&self) -> TIM2SMEN_R {
TIM2SMEN_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 4 - TIM6 timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn tim6smen(&self) -> TIM6SMEN_R {
TIM6SMEN_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - TIM7 timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn tim7smen(&self) -> TIM7SMEN_R {
TIM7SMEN_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 9 - LCD clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn lcdsmen(&self) -> LCDSMEN_R {
LCDSMEN_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - RTC APB clock enable during Sleep and Stop modes"]
#[inline(always)]
pub fn rtcapbsmen(&self) -> RTCAPBSMEN_R {
RTCAPBSMEN_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - Window watchdog clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn wwdgsmen(&self) -> WWDGSMEN_R {
WWDGSMEN_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 14 - SPI2 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn spi2smen(&self) -> SPI2SMEN_R {
SPI2SMEN_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - SPI3 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn sp3smen(&self) -> SP3SMEN_R {
SP3SMEN_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 17 - USART2 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn usart2smen(&self) -> USART2SMEN_R {
USART2SMEN_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - USART3 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn usart3smen(&self) -> USART3SMEN_R {
USART3SMEN_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - UART4 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn uart4smen(&self) -> UART4SMEN_R {
UART4SMEN_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 21 - I2C1 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn i2c1smen(&self) -> I2C1SMEN_R {
I2C1SMEN_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - I2C2 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn i2c2smen(&self) -> I2C2SMEN_R {
I2C2SMEN_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - I2C3 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn i2c3smen(&self) -> I2C3SMEN_R {
I2C3SMEN_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - CRS clock enable during Sleep and Stop modes"]
#[inline(always)]
pub fn crssmen(&self) -> CRSSMEN_R {
CRSSMEN_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - CAN1 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn can1smen(&self) -> CAN1SMEN_R {
CAN1SMEN_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 26 - USB FS clock enable during Sleep and Stop modes"]
#[inline(always)]
pub fn usbfssmen(&self) -> USBFSSMEN_R {
USBFSSMEN_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 28 - Power interface clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn pwrsmen(&self) -> PWRSMEN_R {
PWRSMEN_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 29 - DAC1 interface clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn dac1smen(&self) -> DAC1SMEN_R {
DAC1SMEN_R::new(((self.bits >> 29) & 1) != 0)
}
#[doc = "Bit 30 - OPAMP interface clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn opampsmen(&self) -> OPAMPSMEN_R {
OPAMPSMEN_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - Low power timer 1 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn lptim1smen(&self) -> LPTIM1SMEN_R {
LPTIM1SMEN_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - TIM2 timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn tim2smen(&mut self) -> TIM2SMEN_W<APB1SMENR1_SPEC, 0> {
TIM2SMEN_W::new(self)
}
#[doc = "Bit 4 - TIM6 timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn tim6smen(&mut self) -> TIM6SMEN_W<APB1SMENR1_SPEC, 4> {
TIM6SMEN_W::new(self)
}
#[doc = "Bit 5 - TIM7 timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn tim7smen(&mut self) -> TIM7SMEN_W<APB1SMENR1_SPEC, 5> {
TIM7SMEN_W::new(self)
}
#[doc = "Bit 9 - LCD clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn lcdsmen(&mut self) -> LCDSMEN_W<APB1SMENR1_SPEC, 9> {
LCDSMEN_W::new(self)
}
#[doc = "Bit 10 - RTC APB clock enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn rtcapbsmen(&mut self) -> RTCAPBSMEN_W<APB1SMENR1_SPEC, 10> {
RTCAPBSMEN_W::new(self)
}
#[doc = "Bit 11 - Window watchdog clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn wwdgsmen(&mut self) -> WWDGSMEN_W<APB1SMENR1_SPEC, 11> {
WWDGSMEN_W::new(self)
}
#[doc = "Bit 14 - SPI2 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn spi2smen(&mut self) -> SPI2SMEN_W<APB1SMENR1_SPEC, 14> {
SPI2SMEN_W::new(self)
}
#[doc = "Bit 15 - SPI3 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn sp3smen(&mut self) -> SP3SMEN_W<APB1SMENR1_SPEC, 15> {
SP3SMEN_W::new(self)
}
#[doc = "Bit 17 - USART2 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn usart2smen(&mut self) -> USART2SMEN_W<APB1SMENR1_SPEC, 17> {
USART2SMEN_W::new(self)
}
#[doc = "Bit 18 - USART3 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn usart3smen(&mut self) -> USART3SMEN_W<APB1SMENR1_SPEC, 18> {
USART3SMEN_W::new(self)
}
#[doc = "Bit 19 - UART4 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn uart4smen(&mut self) -> UART4SMEN_W<APB1SMENR1_SPEC, 19> {
UART4SMEN_W::new(self)
}
#[doc = "Bit 21 - I2C1 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn i2c1smen(&mut self) -> I2C1SMEN_W<APB1SMENR1_SPEC, 21> {
I2C1SMEN_W::new(self)
}
#[doc = "Bit 22 - I2C2 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn i2c2smen(&mut self) -> I2C2SMEN_W<APB1SMENR1_SPEC, 22> {
I2C2SMEN_W::new(self)
}
#[doc = "Bit 23 - I2C3 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn i2c3smen(&mut self) -> I2C3SMEN_W<APB1SMENR1_SPEC, 23> {
I2C3SMEN_W::new(self)
}
#[doc = "Bit 24 - CRS clock enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn crssmen(&mut self) -> CRSSMEN_W<APB1SMENR1_SPEC, 24> {
CRSSMEN_W::new(self)
}
#[doc = "Bit 25 - CAN1 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn can1smen(&mut self) -> CAN1SMEN_W<APB1SMENR1_SPEC, 25> {
CAN1SMEN_W::new(self)
}
#[doc = "Bit 26 - USB FS clock enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn usbfssmen(&mut self) -> USBFSSMEN_W<APB1SMENR1_SPEC, 26> {
USBFSSMEN_W::new(self)
}
#[doc = "Bit 28 - Power interface clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn pwrsmen(&mut self) -> PWRSMEN_W<APB1SMENR1_SPEC, 28> {
PWRSMEN_W::new(self)
}
#[doc = "Bit 29 - DAC1 interface clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn dac1smen(&mut self) -> DAC1SMEN_W<APB1SMENR1_SPEC, 29> {
DAC1SMEN_W::new(self)
}
#[doc = "Bit 30 - OPAMP interface clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn opampsmen(&mut self) -> OPAMPSMEN_W<APB1SMENR1_SPEC, 30> {
OPAMPSMEN_W::new(self)
}
#[doc = "Bit 31 - Low power timer 1 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn lptim1smen(&mut self) -> LPTIM1SMEN_W<APB1SMENR1_SPEC, 31> {
LPTIM1SMEN_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 = "APB1SMENR1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1smenr1::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 [`apb1smenr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct APB1SMENR1_SPEC;
impl crate::RegisterSpec for APB1SMENR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`apb1smenr1::R`](R) reader structure"]
impl crate::Readable for APB1SMENR1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`apb1smenr1::W`](W) writer structure"]
impl crate::Writable for APB1SMENR1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets APB1SMENR1 to value 0xf2fe_ca3f"]
impl crate::Resettable for APB1SMENR1_SPEC {
const RESET_VALUE: Self::Ux = 0xf2fe_ca3f;
}
|
pub mod binary_xml_parser;
|
fn vectors() {
let vect : Vec<i32> = Vec::new();
// vector with macro
let mut v = vec![1, 2, 3];
// push elements to it
v.push(4);
// access to elements
let second : &i32 = &v[1];
match v.get(1) {
Some(s) => println!("{}", second),
None => println!("No item at {} index", 1),
}
// iterating over values
// immutable
for i in &v {
println!("{}" , i)
}
//mutable
for i in &mut v {
*i += 50;
}
}
fn strings() {
let mut s = String::new();
// convert literals to string
let lit = "hello i'm a literal";
let str = lit.to_string();
// adding element to a string
let mut res = str + " plus";
res = format!("{} and this", res);
res.push_str(" and also this");
// slice
let slice = &res[0..2];
// iterate in a string
for c in res.chars() {
println!("{}", c)
}
}
use std::collections::HashMap;
fn hash_map() {
let mut scores = HashMap::new();
// add elements to hash map
scores.insert("Yellow", 10);
scores.insert("Blue", 6);
// accessing elements
let team_name = "Blue";
let score = scores.get(&team_name);
// iterating over elements
for (key, value) in &scores {
println!("{}: {}", key, value);
}
// replace a value
scores.insert("Blue", 10);
// check if a value exist and if not, insert it
scores.entry("Blue").or_insert(10);
// creating an hash map from two separate vectors
let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];
let mut scores: HashMap<_, _> =
teams.into_iter().zip(initial_scores.into_iter()).collect();
// after creation of hash map these two fields will be invalid
let field_name = String::from("Favorite color");
let field_value = String::from("Blue");
let mut map = HashMap::new();
map.insert(field_name, field_value);
// check how many times a word occurs by using hash map
let text = "hello world wonderful world";
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}
} |
use itertools::Itertools;
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::*;
type PersonAnswers = HashMap<char, bool>;
struct GroupAnswers {
all: Vec<PersonAnswers>,
}
impl GroupAnswers {
fn total_at_least_one(&self) -> usize {
let alphabet = "abcdefghijklmnopqrstuvwxyz";
let mut total = 0;
for c in alphabet.chars() {
for person in &self.all {
if person.get(&c) == Some(&true) {
total += 1;
break;
}
}
}
total
}
fn total_all(&self) -> usize {
let alphabet = "abcdefghijklmnopqrstuvwxyz";
let mut total = 26;
for c in alphabet.chars() {
for person in &self.all {
if person.get(&c) != Some(&true) {
total -= 1;
break;
}
}
}
total
}
}
fn read_file() -> Vec<GroupAnswers> {
let mut file = File::open("./input/input6.txt").unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
contents
.lines()
.group_by(|s| s.is_empty())
.into_iter()
.filter(|(k, _g)| !k)
.map(|(_k, g)| parse_group(g.collect()))
.collect()
}
fn parse_group(group: Vec<&str>) -> GroupAnswers {
GroupAnswers {
all: group.into_iter().map(parse_answers).collect(),
}
}
fn parse_answers(s: &str) -> PersonAnswers {
let mut answers = HashMap::new();
for c in s.chars() {
answers.insert(c, true);
}
answers
}
fn solve_part_1(info: Vec<GroupAnswers>) -> usize {
info.iter()
.map(|answers| answers.total_at_least_one())
.sum()
}
pub fn part_1() -> usize {
let info = read_file();
solve_part_1(info)
}
fn solve_part_2(info: Vec<GroupAnswers>) -> usize {
info.iter().map(|answers| answers.total_all()).sum()
}
pub fn part_2() -> usize {
let info = read_file();
solve_part_2(info)
}
|
use std::char;
use rand;
use std::time::Instant;
fn main() {
const MAX_ITEMS: usize = 10000;
let mut arr: Vec<String> = vec!["".to_string(); MAX_ITEMS];
for _ in 0..MAX_ITEMS {
for i in 0..MAX_ITEMS {
// Initializing
arr[i] = random_string();
}
let index: usize = random_int(MAX_ITEMS);
let key = arr[index].clone();
let start = Instant::now();
linear_search(&key, &arr);
println!("{};{}", index, start.elapsed().as_nanos());
}
}
fn linear_search(key: &String, arr: &Vec<String>) -> bool {
for val in arr.iter() {
if val == key {
return true;
}
}
false
}
fn random_string() -> String {
let mut buf = String::new();
for _ in 0..10 {
buf.push(char::from_u32(random_u32(127-32)+32).unwrap());
}
buf
}
fn random_int(max: usize) -> usize {
rand::random::<usize>() % max
}
fn random_u32(max: u32) -> u32 {
rand::random::<u32>() % max
}
|
use actix::*;
use quix::{self};
use quix::node::{NodeConfig, NodeController, Connect};
use actix::clock::Duration;
use quix::global::{Global, Set};
#[test]
fn test_nodes() {
std::env::set_var("RUST_LOG", "info");
env_logger::init();
std::thread::spawn(|| {
actix::run(async move {
Global::<NodeConfig>::from_registry().send(Set(NodeConfig {
listen: "127.0.0.1:9001".parse().unwrap(),
..Default::default()
})).await.unwrap();
NodeController::from_registry();
let link = NodeController::from_registry().send(Connect {
addr: "127.0.0.1:9002".parse().unwrap()
}).await.unwrap();
tokio::time::delay_for(Duration::from_secs(10)).await;
}).unwrap();
});
actix::run(async move {
Global::<NodeConfig>::from_registry().send(Set(NodeConfig {
listen: "127.0.0.1:9002".parse().unwrap(),
..Default::default()
})).await.unwrap();
let link = NodeController::from_registry().send(Connect {
addr: "127.0.0.1:9001".parse().unwrap()
}).await.unwrap();
tokio::time::delay_for(Duration::from_secs(10)).await;
}).unwrap();
} |
#[doc = "Register `RCC_RDLSICR` reader"]
pub type R = crate::R<RCC_RDLSICR_SPEC>;
#[doc = "Register `RCC_RDLSICR` writer"]
pub type W = crate::W<RCC_RDLSICR_SPEC>;
#[doc = "Field `LSION` reader - LSION"]
pub type LSION_R = crate::BitReader;
#[doc = "Field `LSION` writer - LSION"]
pub type LSION_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `LSIRDY` reader - LSIRDY"]
pub type LSIRDY_R = crate::BitReader;
#[doc = "Field `MRD` reader - MRD"]
pub type MRD_R = crate::FieldReader;
#[doc = "Field `MRD` writer - MRD"]
pub type MRD_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O>;
#[doc = "Field `EADLY` reader - EADLY"]
pub type EADLY_R = crate::FieldReader;
#[doc = "Field `EADLY` writer - EADLY"]
pub type EADLY_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `SPARE` reader - SPARE"]
pub type SPARE_R = crate::FieldReader;
#[doc = "Field `SPARE` writer - SPARE"]
pub type SPARE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O>;
impl R {
#[doc = "Bit 0 - LSION"]
#[inline(always)]
pub fn lsion(&self) -> LSION_R {
LSION_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - LSIRDY"]
#[inline(always)]
pub fn lsirdy(&self) -> LSIRDY_R {
LSIRDY_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bits 16:20 - MRD"]
#[inline(always)]
pub fn mrd(&self) -> MRD_R {
MRD_R::new(((self.bits >> 16) & 0x1f) as u8)
}
#[doc = "Bits 24:26 - EADLY"]
#[inline(always)]
pub fn eadly(&self) -> EADLY_R {
EADLY_R::new(((self.bits >> 24) & 7) as u8)
}
#[doc = "Bits 27:31 - SPARE"]
#[inline(always)]
pub fn spare(&self) -> SPARE_R {
SPARE_R::new(((self.bits >> 27) & 0x1f) as u8)
}
}
impl W {
#[doc = "Bit 0 - LSION"]
#[inline(always)]
#[must_use]
pub fn lsion(&mut self) -> LSION_W<RCC_RDLSICR_SPEC, 0> {
LSION_W::new(self)
}
#[doc = "Bits 16:20 - MRD"]
#[inline(always)]
#[must_use]
pub fn mrd(&mut self) -> MRD_W<RCC_RDLSICR_SPEC, 16> {
MRD_W::new(self)
}
#[doc = "Bits 24:26 - EADLY"]
#[inline(always)]
#[must_use]
pub fn eadly(&mut self) -> EADLY_W<RCC_RDLSICR_SPEC, 24> {
EADLY_W::new(self)
}
#[doc = "Bits 27:31 - SPARE"]
#[inline(always)]
#[must_use]
pub fn spare(&mut self) -> SPARE_W<RCC_RDLSICR_SPEC, 27> {
SPARE_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 is used to control the minimum NRST active duration and LSI function.0 to 7 wait states are inserted for word, half-word and byte accesses. Wait states are inserted in case of successive accesses to this register.This register is reset by the por_rst reset, and it is located into the VDD domain. If TZEN = , this register can only be modified in secure mode.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rcc_rdlsicr::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 [`rcc_rdlsicr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct RCC_RDLSICR_SPEC;
impl crate::RegisterSpec for RCC_RDLSICR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`rcc_rdlsicr::R`](R) reader structure"]
impl crate::Readable for RCC_RDLSICR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`rcc_rdlsicr::W`](W) writer structure"]
impl crate::Writable for RCC_RDLSICR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets RCC_RDLSICR to value 0"]
impl crate::Resettable for RCC_RDLSICR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::rc::Rc;
use std::cell::RefCell;
use std::cell::Ref;
use std::cell::RefMut;
pub struct List<T> {
head: Link<T>,
tail: Link<T>,
}
type Link<T> = Option<Rc<RefCell<Node<T>>>>;
struct Node<T> {
elem: T,
next: Link<T>,
prev: Link<T>,
}
impl<T> Node<T> {
fn new(elem: T) -> Rc<RefCell<Self>> {
Rc::new(RefCell::new(Node {
elem: elem,
prev: None,
next: None,
}))
}
}
impl<T> List<T> {
pub fn new() -> Self {
List { head: None, tail: None }
}
pub fn push_front(&mut self, elem: T) {
let node = Node::new(elem);
match self.head.take() {
Some(head) => {
head.borrow_mut().prev = Some(node.clone());
node.borrow_mut().next = Some(head);
self.head = Some(node);
}
None => {
self.tail = Some(node.clone());
self.head = Some(node);
}
}
}
pub fn push_back(&mut self, elem: T) {
let node = Node::new(elem);
match self.tail.take() {
Some(tail) => {
tail.borrow_mut().next = Some(node.clone());
node.borrow_mut().prev = Some(tail);
self.tail = Some(node);
}
None => {
self.head = Some(node.clone());
self.tail = Some(node);
}
}
}
pub fn pop_front(&mut self) -> Option<T> {
self.head.take().map(|node| {
match node.borrow_mut().next.take() {
Some(next) => {
next.borrow_mut().prev.take();
self.head = Some(next);
}
None => {
self.tail.take();
}
}
Rc::try_unwrap(node).ok().unwrap().into_inner().elem //对照手册好好理解
})
}
pub fn pop_back(&mut self) -> Option<T> {
self.tail.take().map(|node| {
match node.borrow_mut().prev.take() {
Some(prev) => {
prev.borrow_mut().next.take();
self.tail = Some(prev);
}
None => {
self.head.take();
}
}
Rc::try_unwrap(node).ok().unwrap().into_inner().elem
})
}
//pub fn peek_front(&self) -> Option<&T> {
pub fn peek_front(&self) -> Option<Ref<T>> {
self.head.as_ref().map(|node| {
//&node.borrow().elem
//node.borrow()
Ref::map(node.borrow(), |node| &node.elem)
})
}
pub fn peek_back(&self) -> Option<Ref<T>> {
self.tail.as_ref().map(|node| {
Ref::map(node.borrow(), |node| &node.elem)
})
}
pub fn peek_front_mut(&mut self) -> Option<RefMut<T>> {
self.head.as_ref().map(|node| {
RefMut::map(node.borrow_mut(), |node| &mut node.elem)
})
}
pub fn peek_back_mut(&mut self) -> Option<RefMut<T>> {
self.tail.as_ref().map(|node| {
RefMut::map(node.borrow_mut(), |node| &mut node.elem)
})
}
}
//实现迭代器
//Iter 不实现
//IterMut 不实现
//IntoIter
pub struct IntoIter<T> (List<T>);
impl<T> List<T> {
pub fn into_iter(self) -> IntoIter<T> {
IntoIter(self)
}
}
impl<T> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.0.pop_front()
}
}
impl<T> DoubleEndedIterator for IntoIter<T> {
fn next_back(&mut self) -> Option<T> {
self.0.pop_back()
}
}
#[cfg(test)]
mod tests {
use super::List;
#[test]
fn basics() {
let mut list = List::new();
assert_eq!(list.pop_front(), None);
list.push_front(1);
list.push_front(2);
list.push_front(3);
assert_eq!(list.pop_front(), Some(3));
assert_eq!(list.pop_front(), Some(2));
list.push_front(4);
list.push_front(5);
assert_eq!(list.pop_front(), Some(5));
assert_eq!(list.pop_front(), Some(4));
assert_eq!(list.pop_front(), Some(1));
assert_eq!(list.pop_front(), None);
//----back-----
assert_eq!(list.pop_back(), None);
list.push_back(4);
list.push_back(5);
assert_eq!(list.pop_back(), Some(5));
assert_eq!(list.pop_back(), Some(4));
assert_eq!(list.pop_back(), None);
}
#[test]
fn peek() {
let mut list = List::new();
assert!(list.peek_front().is_none());
assert!(list.peek_back().is_none());
assert!(list.peek_front_mut().is_none());
assert!(list.peek_back_mut().is_none());
list.push_front(1);
list.push_front(2);
list.push_front(3);
assert_eq!(*list.peek_front().unwrap(), 3);
assert_eq!(*list.peek_front_mut().unwrap(), 3);
assert_eq!(*list.peek_back().unwrap(), 1);
assert_eq!(*list.peek_back_mut().unwrap(), 1);
}
#[test]
fn into_iter() {
let mut list = List::new();
list.push_front(1);
list.push_front(2);
list.push_front(3);
let mut iter = list.into_iter();
assert_eq!(iter.next(), Some(3));
assert_eq!(iter.next_back(), Some(1));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next_back(), None);
assert_eq!(iter.next(), None);
}
}
|
use libc::c_void;
use ffi::object::{self, LLVMObjectFileRef, LLVMSymbolIteratorRef};
use cbox::CBox;
use std::fmt;
use std::iter::Iterator;
use std::marker::PhantomData;
use std::mem;
use buffer::MemoryBuffer;
use util;
/// An external object file that has been parsed by LLVM.
pub struct ObjectFile {
obj: LLVMObjectFileRef,
}
native_ref!(ObjectFile, obj: LLVMObjectFileRef);
impl ObjectFile {
/// Parse the object file at the path given, or return an error string if an error occurs.
pub fn read(path: &str) -> Result<ObjectFile, CBox<str>> {
let buf = try!(MemoryBuffer::new_from_file(path));
unsafe {
let ptr = object::LLVMCreateObjectFile(buf.as_ptr());
if ptr.is_null() {
Err(CBox::from("unknown error"))
} else {
Ok(ptr.into())
}
}
}
/// Iterate through the symbols in this object file.
pub fn symbols(&self) -> Symbols {
Symbols {
iter: unsafe { object::LLVMGetSymbols(self.obj) },
marker: PhantomData,
}
}
}
pub struct Symbols<'a> {
iter: LLVMSymbolIteratorRef,
marker: PhantomData<&'a ()>,
}
impl<'a> Iterator for Symbols<'a> {
type Item = Symbol<'a>;
fn next(&mut self) -> Option<Symbol<'a>> {
unsafe {
let name = util::to_str(object::LLVMGetSymbolName(self.iter) as *mut i8);
let size = object::LLVMGetSymbolSize(self.iter) as usize;
let address = object::LLVMGetSymbolAddress(self.iter) as usize;
Some(Symbol {
name: name,
address: mem::transmute(address),
size: size,
})
}
}
}
impl<'a> Drop for Symbols<'a> {
fn drop(&mut self) {
unsafe { object::LLVMDisposeSymbolIterator(self.iter) }
}
}
pub struct Symbol<'a> {
/// The name of this symbol.
pub name: &'a str,
/// The address that this symbol is at.
pub address: *const c_void,
pub size: usize,
}
impl<'a> Copy for Symbol<'a> {}
impl<'a> Clone for Symbol<'a> {
fn clone(&self) -> Symbol<'a> {
*self
}
}
impl<'a> fmt::Debug for Symbol<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{} - {}", self.name, self.size)
}
}
impl<'a> Symbol<'a> {
/// Get the pointer for this symbol.
pub unsafe fn get<T>(self) -> &'a T {
mem::transmute(self.address)
}
}
|
pub mod death;
pub mod error;
|
use super::atom::btn::{self, Btn};
use super::atom::dropdown::{self, Dropdown};
use super::atom::fa;
use super::atom::tab_btn::TabBtn;
use super::atom::text::Text;
use crate::libs::color::color_system;
use crate::libs::random_id::U128Id;
use crate::libs::select_list::SelectList;
use crate::libs::type_id::type_id;
use isaribi::{
style,
styled::{Style, Styled},
};
use kagura::prelude::*;
use nusa::prelude::*;
use nusa::v_node::v_element::VEvent;
use std::cell::RefCell;
use std::rc::Rc;
pub struct Props<
Content: HtmlComponent + Unpin,
TabName: HtmlComponent<Props = Content::Props> + Unpin,
> where
Content::Props: Clone,
{
pub state: Rc<RefCell<State<Content, TabName>>>,
}
#[derive(PartialEq)]
pub struct ContainerRect {
pub left: f64,
pub top: f64,
pub width: f64,
pub height: f64,
}
pub enum Msg<Sub> {
NoOp,
Sub(On<Sub>),
DragStart {
page_x: i32,
page_y: i32,
drag_type: DragType,
},
DragEnd,
Drag {
page_x: i32,
page_y: i32,
},
DisconnectTab {
event_id: U128Id,
tab_idx: usize,
is_selected: bool,
},
SetSelectedTabIdx(usize),
CloseSelf,
SetMinimizedSelf(bool),
CloneTab(usize),
CloseTab(usize),
}
pub enum On<Sub> {
Focus(U128Id),
Close(U128Id),
ChangeDraggingState(U128Id, Option<(i32, i32)>),
SetMinimized(U128Id, bool),
Move(i32, i32),
Resize([f64; 2]),
DisconnectTab {
event_id: U128Id,
tab_idx: usize,
modeless_id: U128Id,
is_selected: bool,
},
ConnectTab {
event_id: U128Id,
header_tab_idx: Option<usize>,
modeless_id: U128Id,
},
Sub(Sub),
}
pub struct TabModeless<
Content: HtmlComponent + Unpin,
TabName: HtmlComponent<Props = Content::Props> + Unpin,
> where
Content::Props: Clone,
{
state: Rc<RefCell<State<Content, TabName>>>,
}
pub struct State<
Content: HtmlComponent + Unpin,
TabName: HtmlComponent<Props = Content::Props> + Unpin,
> where
Content::Props: Clone,
{
size: [f64; 2],
loc: [f64; 2],
dragging: Option<([i32; 2], DragType)>,
some_is_dragging: bool,
container_rect: Option<Rc<ContainerRect>>,
modeless_id: U128Id,
z_index: usize,
contents: SelectList<Content::Props>,
cmds: Vec<Cmd<TabModeless<Content, TabName>>>,
_phantom_content: std::marker::PhantomData<Content>,
_phantom_tab_name: std::marker::PhantomData<TabName>,
}
impl<Content: HtmlComponent + Unpin, TabName: HtmlComponent<Props = Content::Props> + Unpin>
State<Content, TabName>
where
Content::Props: Clone,
{
pub fn new(
size: [f64; 2],
page_x: i32,
page_y: i32,
contents: SelectList<Content::Props>,
) -> Rc<RefCell<Self>> {
Rc::new(RefCell::new(Self {
loc: [page_x as f64, page_y as f64],
size: size,
dragging: None,
some_is_dragging: false,
container_rect: None,
modeless_id: U128Id::none(),
contents: contents,
z_index: 0,
cmds: vec![],
_phantom_content: std::marker::PhantomData,
_phantom_tab_name: std::marker::PhantomData,
}))
}
pub fn set(
&mut self,
container_rect: Rc<ContainerRect>,
modeless_id: U128Id,
some_dragging: Option<(i32, i32)>,
z_index: usize,
) {
if let Some(self_container_rect) = self.container_rect.as_ref() {
if container_rect.width != self_container_rect.width {
let margin_ratio = self.loc[0] / (self_container_rect.width - self.size[0]);
let margin = container_rect.width - self.size[0];
self.loc[0] = margin_ratio * margin;
}
if container_rect.height != self_container_rect.height {
let margin_ratio = self.loc[1] / (self_container_rect.height - self.size[1]);
let margin = container_rect.height - self.size[1];
self.loc[1] = margin_ratio * margin;
}
} else {
let client_x = self.loc[0] as f64 - container_rect.left;
let client_y = self.loc[1] as f64 - container_rect.top;
let loc = [client_x.max(0.0), client_y.max(0.0)];
self.loc = loc;
}
self.container_rect = Some(container_rect);
self.modeless_id = modeless_id;
self.some_is_dragging = some_dragging.is_some();
self.z_index = z_index;
if self.dragging.is_some() {
if let Some((page_x, page_y)) = some_dragging {
self.cmds.push(Cmd::chain(Msg::Drag { page_x, page_y }));
} else {
self.cmds.push(Cmd::chain(Msg::DragEnd));
}
}
}
pub fn contents(&self) -> &SelectList<Content::Props> {
&self.contents
}
pub fn contents_mut(&mut self) -> &mut SelectList<Content::Props> {
&mut self.contents
}
}
#[derive(Clone, Copy)]
pub enum DragType {
Move,
Resize(DragDirection),
}
#[derive(Clone, Copy)]
pub enum DragDirection {
Top,
Left,
Bottom,
Right,
TopLeft,
TopRight,
BottomLeft,
BottomRight,
}
impl std::fmt::Display for DragDirection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Top => write!(f, "top"),
Self::Left => write!(f, "left"),
Self::Right => write!(f, "right"),
Self::Bottom => write!(f, "bottom"),
Self::TopLeft => write!(f, "top-left"),
Self::TopRight => write!(f, "top-right"),
Self::BottomLeft => write!(f, "bottom-left"),
Self::BottomRight => write!(f, "bottom-right"),
}
}
}
impl<Content: HtmlComponent + Unpin, TabName: HtmlComponent<Props = Content::Props> + Unpin>
Component for TabModeless<Content, TabName>
where
Content::Props: Clone,
{
type Props = Props<Content, TabName>;
type Msg = Msg<Content::Event>;
type Event = On<Content::Event>;
}
impl<Content: HtmlComponent + Unpin, TabName: HtmlComponent<Props = Content::Props> + Unpin>
HtmlComponent for TabModeless<Content, TabName>
where
Content::Props: Clone,
{
}
impl<Content: HtmlComponent + Unpin, TabName: HtmlComponent<Props = Content::Props> + Unpin>
Constructor for TabModeless<Content, TabName>
where
Content::Props: Clone,
{
fn constructor(props: Self::Props) -> Self {
Self { state: props.state }
}
}
impl<Content: HtmlComponent + Unpin, TabName: HtmlComponent<Props = Content::Props> + Unpin> Update
for TabModeless<Content, TabName>
where
Content::Props: Clone,
{
fn on_assemble(self: Pin<&mut Self>) -> Cmd<Self> {
Cmd::list(self.state.borrow_mut().cmds.drain(..).collect())
}
fn on_load(mut self: Pin<&mut Self>, props: Self::Props) -> Cmd<Self> {
self.state = props.state;
Cmd::list(self.state.borrow_mut().cmds.drain(..).collect())
}
fn update(self: Pin<&mut Self>, msg: Msg<Content::Event>) -> Cmd<Self> {
let mut this = self.state.borrow_mut();
match msg {
Msg::NoOp => Cmd::none(),
Msg::Sub(sub) => Cmd::submit(sub),
Msg::CloseSelf => Cmd::submit(On::Close(U128Id::clone(&this.modeless_id))),
Msg::SetMinimizedSelf(is_minimized) => Cmd::submit(On::SetMinimized(
U128Id::clone(&this.modeless_id),
is_minimized,
)),
Msg::CloneTab(tab_idx) => {
if let Some(tab) = this.contents.get(tab_idx) {
let tab = tab.clone();
this.contents.insert(tab_idx + 1, tab);
}
Cmd::none()
}
Msg::CloseTab(tab_idx) => {
this.contents.remove(tab_idx);
if this.contents.len() == 0 {
Cmd::submit(On::Close(U128Id::clone(&this.modeless_id)))
} else {
Cmd::none()
}
}
Msg::DragStart {
page_x,
page_y,
drag_type,
} => {
this.dragging = Some(([page_x, page_y], drag_type));
Cmd::list(vec![
Cmd::submit(On::Focus(U128Id::clone(&this.modeless_id))),
Cmd::submit(On::ChangeDraggingState(
U128Id::clone(&this.modeless_id),
Some((page_x, page_y)),
)),
])
}
Msg::DragEnd => {
this.dragging = None;
Cmd::list(vec![
Cmd::submit(On::Focus(U128Id::clone(&this.modeless_id))),
Cmd::submit(On::ChangeDraggingState(
U128Id::clone(&this.modeless_id),
None,
)),
])
}
Msg::DisconnectTab {
event_id,
tab_idx,
is_selected,
} => Cmd::submit(On::DisconnectTab {
event_id,
tab_idx,
modeless_id: U128Id::clone(&this.modeless_id),
is_selected,
}),
Msg::SetSelectedTabIdx(tab_idx) => {
this.contents.set_selected_idx(tab_idx);
Cmd::none()
}
Msg::Drag { page_x, page_y } => {
let mut cmds = vec![];
if let Some(mut dragging) = this.dragging {
let mov_x = (page_x - dragging.0[0]) as f64;
let mov_y = (page_y - dragging.0[1]) as f64;
match &dragging.1 {
DragType::Move => {
this.loc[0] += mov_x;
this.loc[1] += mov_y;
}
DragType::Resize(DragDirection::Top) => {
this.loc[1] += mov_y;
this.size[1] -= mov_y;
}
DragType::Resize(DragDirection::Left) => {
this.loc[0] += mov_x;
this.size[0] -= mov_x;
}
DragType::Resize(DragDirection::Bottom) => {
this.size[1] += mov_y;
}
DragType::Resize(DragDirection::Right) => {
this.size[0] += mov_x;
}
DragType::Resize(DragDirection::TopLeft) => {
this.loc[0] += mov_x;
this.loc[1] += mov_y;
this.size[0] -= mov_x;
this.size[1] -= mov_y;
}
DragType::Resize(DragDirection::TopRight) => {
this.loc[1] += mov_y;
this.size[0] += mov_x;
this.size[1] -= mov_y;
}
DragType::Resize(DragDirection::BottomLeft) => {
this.loc[0] += mov_x;
this.size[0] -= mov_x;
this.size[1] += mov_y;
}
DragType::Resize(DragDirection::BottomRight) => {
this.size[0] += mov_x;
this.size[1] += mov_y;
}
}
if this.loc[0] < 0.0 {
this.loc[0] = 0.0;
}
if this.loc[1] < 0.0 {
this.loc[1] = 0.0;
}
if let Some(this_container_rect) = this.container_rect.clone() {
if this.size[0] > this_container_rect.width {
this.size[0] = this_container_rect.width;
}
if this.size[1] > this_container_rect.height {
this.size[1] = this_container_rect.height;
}
if this.size[0] < this_container_rect.width * 0.1 {
this.size[0] = this_container_rect.width * 0.1;
}
if this.size[1] < this_container_rect.height * 0.1 {
this.size[1] = this_container_rect.height * 0.1;
}
if this.loc[0] + this.size[0] > this_container_rect.width {
this.loc[0] = this_container_rect.width - this.size[0];
}
if this.loc[1] + this.size[1] > this_container_rect.height {
this.loc[1] = this_container_rect.height - this.size[1];
}
}
dragging.0[0] = page_x;
dragging.0[1] = page_y;
this.dragging = Some(dragging);
cmds.push(match (&dragging.1, this.container_rect.as_ref()) {
(DragType::Move, Some(this_container_rect)) => {
let page_x = (this.loc[0] + this_container_rect.left).round() as i32;
let page_y = (this.loc[1] + this_container_rect.top).round() as i32;
Cmd::submit(On::Move(page_x, page_y))
}
_ => Cmd::submit(On::Resize(this.size.clone())),
})
}
if let Some(this_container_rect) = this.container_rect.as_ref() {
if page_x < this_container_rect.left as i32
|| page_x > (this_container_rect.left + this_container_rect.width) as i32
|| page_y < this_container_rect.top as i32
|| page_y > (this_container_rect.top + this_container_rect.height) as i32
{
this.dragging = None;
cmds.push(Cmd::submit(On::ChangeDraggingState(
U128Id::clone(&this.modeless_id),
None,
)));
}
}
Cmd::list(cmds)
}
}
}
}
impl<Content: HtmlComponent + Unpin, TabName: HtmlComponent<Props = Content::Props> + Unpin>
Render<Html> for TabModeless<Content, TabName>
where
Content::Props: Clone,
{
type Children = ();
fn render(&self, _: ()) -> Html {
Self::styled(Html::div(
Attributes::new()
.index_id(self.state.borrow().modeless_id.to_string())
.string("data-modeless-id", self.state.borrow().modeless_id.to_string())
.class(Self::class("base"))
.style("z-index", format!("{}", self.state.borrow().z_index))
.style("left", format!("{}px", self.state.borrow().loc[0].round() as i32))
.style("top", format!("{}px", self.state.borrow().loc[1].round() as i32))
.style("width", format!("{}px", self.state.borrow().size[0].round() as i32))
.style("height", format!("{}px", self.state.borrow().size[1].round() as i32)),
{
let mut events = Events::new();
if !self.state.borrow().some_is_dragging {
events = events.on_mousedown(self, |e| {
let e = unwrap!(e.dyn_into::<web_sys::MouseEvent>().ok(); Msg::NoOp);
e.stop_propagation();
Msg::DragStart {
page_x: e.page_x(),
page_y: e.page_y(),
drag_type: DragType::Move,
}
});
}
events = events.on("wheel",self, |e| {
e.stop_propagation();
Msg::NoOp
}).on_click(self, {
let modeless_id = U128Id::clone(&self.state.borrow().modeless_id);
|_| Msg::Sub(On::Focus(modeless_id))
});
events
},
vec![
Html::div(
Attributes::new().class(Self::class("header")),
Events::new()
.on_dragover(self, |e| {
e.prevent_default();
Msg::NoOp
})
.on_drop(self, {
let modeless_id = U128Id::clone(&self.state.borrow().modeless_id);
move |e| {
let e = unwrap!(e.dyn_into::<web_sys::DragEvent>().ok(); Msg::NoOp);
Self::on_drop_tab(None, e,modeless_id)
}
}),
vec![
Html::div(Attributes::new().class(Self::class("header-tabs")),Events::new(),
self.state.borrow()
.contents
.iter()
.enumerate()
.map(|(tab_idx, content)| {
let is_selected = tab_idx == self.state.borrow().contents.selected_idx();
TabBtn::new(
true,
is_selected,
Attributes::new(),
Events::new()
.on_mousedown(self, |e|{ e.stop_propagation(); Msg::NoOp})
.on_dragstart(self,
move |e| {
let e = unwrap!(e.dyn_into::<web_sys::DragEvent>().ok(); Msg::NoOp);
e.stop_propagation();
let data_transfer = unwrap!(e.data_transfer(); Msg::NoOp);
let event_id = U128Id::new();
unwrap!(
data_transfer
.set_data("text/plain", &(type_id::<Self>() + ";" + &event_id.to_string()))
.ok();
Msg::NoOp
);
Msg::DisconnectTab {
event_id,
tab_idx,
is_selected
}
}).on_drop(self, {
let modeless_id = U128Id::clone(&self.state.borrow().modeless_id);
move |e| {
let e = unwrap!(e.dyn_into::<web_sys::DragEvent>().ok(); Msg::NoOp);
Self::on_drop_tab(Some(tab_idx), e,modeless_id)
}
}).on_click(self, move |_| Msg::SetSelectedTabIdx(tab_idx)),
vec![TabName::empty(self, None, Clone::clone(content), Sub::none())],
)
})
.collect()
),
Dropdown::new(
self,
None,
dropdown::Props {
direction: dropdown::Direction::BottomLeft,
toggle_type: dropdown::ToggleType::Click,
variant: btn::Variant::TransparentDark,
},
Sub::none(),
(vec![fa::fas_i("fa-ellipsis-vertical")],vec![
Html::span(
Attributes::new()
.class(Dropdown::class("menu-heading"))
.class(Btn::class_name(&btn::Variant::SecondaryLikeMenu)),
Events::new(),
vec![Text::span("タブ")]
),
Btn::menu_as_secondary(
Attributes::new(),
Events::new().on_click(self,{
let selected_tab_idx = self.state.borrow().contents.selected_idx();
move |_| Msg::CloneTab(selected_tab_idx)
}),
vec![Html::text("現在のタブを複製")]
),
Btn::menu_as_secondary(
Attributes::new(),
Events::new().on_click(self,{
let selected_tab_idx = self.state.borrow().contents.selected_idx();
move |_| Msg::CloseTab(selected_tab_idx)
}),
vec![Html::text("現在のタブを閉じる")]
),
Html::span(
Attributes::new()
.class(Dropdown::class("menu-heading"))
.class(Btn::class_name(&btn::Variant::SecondaryLikeMenu)),
Events::new(),
vec![Text::span("ウィンドウ")]
),
Btn::menu_as_secondary(
Attributes::new(),
Events::new().on_click(self,|_| Msg::SetMinimizedSelf(true)),
vec![Html::text("ウィンドウを最小化")]
),
Btn::menu_as_secondary(
Attributes::new(),
Events::new().on_click(self,|_| Msg::CloseSelf),
vec![Html::text("ウィンドウを閉じる")]
),
])
)
]
),
Html::div(
Attributes::new().class(Self::class("content")),
Events::new().on_mousedown(self,|e| {
e.stop_propagation();
Msg::NoOp
}),
vec![self.state.borrow()
.contents
.selected()
.map(|content| Content::empty(self, None, Clone::clone(content), Sub::map(|sub| Msg::Sub(On::Sub(sub)))))
.unwrap_or(Html::none())],
),
self.render_rsz(DragDirection::Top),
self.render_rsz(DragDirection::TopLeft),
self.render_rsz(DragDirection::Left),
self.render_rsz(DragDirection::BottomLeft),
self.render_rsz(DragDirection::Bottom),
self.render_rsz(DragDirection::BottomRight),
self.render_rsz(DragDirection::Right),
self.render_rsz(DragDirection::TopRight),
],
))
}
}
impl<Content: HtmlComponent + Unpin, TabName: HtmlComponent<Props = Content::Props> + Unpin>
TabModeless<Content, TabName>
where
Content::Props: Clone,
{
fn render_rsz(&self, drag_direction: DragDirection) -> Html {
Html::div(
Attributes::new().class(Self::class(&format!("rsz-{}", &drag_direction))),
Events::new()
.on_mousedown(self, move |e| {
let e = unwrap!(e.dyn_into::<web_sys::MouseEvent>().ok(); Msg::NoOp);
e.stop_propagation();
Msg::DragStart {
page_x: e.page_x(),
page_y: e.page_y(),
drag_type: DragType::Resize(drag_direction),
}
})
.on_mouseup(self, |_| Msg::DragEnd),
vec![],
)
}
fn on_drop_tab(
tab_idx: Option<usize>,
e: VEvent<web_sys::DragEvent>,
modeless_id: U128Id,
) -> Msg<Content::Event> {
let e = unwrap!(e.dyn_into::<web_sys::DragEvent>().ok(); Msg::NoOp);
let data_transfer = unwrap!(e.data_transfer(); Msg::NoOp);
let data = unwrap!(data_transfer.get_data("text/plain").ok(); Msg::NoOp);
let payload = data.split(";").collect::<Vec<_>>();
if payload.len() < 2 {
return Msg::NoOp;
}
if type_id::<Self>() != payload[0] {
return Msg::NoOp;
}
if let Some(event_id) = U128Id::from_hex(&payload[1]) {
e.prevent_default();
e.stop_propagation();
return Msg::Sub(On::ConnectTab {
event_id,
header_tab_idx: tab_idx,
modeless_id,
});
}
Msg::NoOp
}
}
impl<Content: HtmlComponent + Unpin, TabName: HtmlComponent<Props = Content::Props> + Unpin> Styled
for TabModeless<Content, TabName>
where
Content::Props: Clone,
{
fn style() -> Style {
style! {
".base" {
"position": "absolute";
"overflow": "visible";
"display": "grid";
"grid-template-columns": "1fr";
"grid-template-rows": "max-content 1fr";
"border-radius": "2px";
"box-shadow": format!("0 0 0.1rem 0.1rem {}", color_system::gray(255, 9));
"background-color": format!("{}", crate::libs::color::Pallet::gray(0));
}
".header" {
"display": "grid";
"grid-template-columns": "1fr max-content";
"background-color": crate::libs::color::Pallet::gray(7);
}
".header-tabs" {
"display": "flex";
"felx-wrap": "wrap";
}
".content" {
"overflow": "hidden";
}
".rsz-top" {
"position": "absolute";
"top": "-0.9rem";
"left": "0.1rem";
"width": "calc(100% - 0.2rem)";
"height": "1rem";
}
".rsz-top:hover" {
"cursor": "ns-resize";
}
".rsz-top-left" {
"position": "absolute";
"top": "-0.9rem";
"left": "-0.9rem";
"width": "1rem";
"height": "1rem";
}
".rsz-top-left:hover" {
"cursor": "nwse-resize";
}
".rsz-left" {
"position": "absolute";
"top": "0.1rem";
"left": "-0.9rem";
"width": "1rem";
"height": "calc(100% - 0.2rem)";
}
".rsz-left:hover" {
"cursor": "ew-resize";
}
".rsz-bottom-left" {
"position": "absolute";
"top": "calc(100% - 0.2rem)";
"left": "-0.9rem";
"width": "1rem";
"height": "1rem";
}
".rsz-bottom-left:hover" {
"cursor": "nesw-resize";
}
".rsz-bottom" {
"position": "absolute";
"top": "calc(100% - 0.2rem)";
"left": "0.1rem";
"width": "calc(100% - 0.2rem)";
"height": "1rem";
}
".rsz-bottom:hover" {
"cursor": "ns-resize";
}
".rsz-bottom-right" {
"position": "absolute";
"top": "calc(100% - 0.2rem)";
"left": "calc(100% - 0.2rem)";
"width": "1rem";
"height": "1rem";
}
".rsz-bottom-right:hover" {
"cursor": "nwse-resize";
}
".rsz-right" {
"position": "absolute";
"top": "0.1rem";
"left": "calc(100% - 0.2rem)";
"width": "1rem";
"height": "calc(100% - 0.2rem)";
}
".rsz-right:hover" {
"cursor": "ew-resize";
}
".rsz-top-right" {
"position": "absolute";
"top": "-0.9rem";
"left": "calc(100% - 0.2rem)";
"width": "1rem";
"height": "1rem";
}
".rsz-top-right:hover" {
"cursor": "nesw-resize";
}
}
}
}
|
#[cfg(not(feature = "loom"))]
mod loom {
pub use std::sync;
}
#[cfg(feature = "loom")]
use loom;
pub mod queue;
use std::num::NonZeroUsize;
use std::marker::PhantomData;
use cache_padded::CachePadded;
use per_thread_object::ThreadLocal;
pub struct WfQueue<T: Queueable> {
queue: queue::WfQueue,
context: ThreadLocal<Context>,
_phantom: PhantomData<T>
}
pub trait Queueable {
fn into_nonzero(self) -> NonZeroUsize;
/// # Safety
///
/// Unsafe conversion from `NonZeroUsize`.
unsafe fn from_nonzero(n: NonZeroUsize) -> Self;
}
struct Context {
enq: CachePadded<queue::EnqueueCtx>,
deq: CachePadded<queue::DequeueCtx>
}
impl<T: Queueable> WfQueue<T> {
pub fn new(cap: usize) -> WfQueue<T> {
WfQueue {
queue: queue::WfQueue::new(cap),
context: ThreadLocal::new(),
_phantom: PhantomData
}
}
#[inline]
pub fn len(&self) -> usize {
self.queue.len()
}
#[inline]
pub fn capacity(&self) -> usize {
self.queue.capacity()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.queue.is_empty()
}
#[inline]
pub fn is_full(&self) -> bool {
self.queue.is_full()
}
pub fn push(&self, val: T) -> Result<(), T> {
let ctx = self.context.get_or(Context::new);
let val = val.into_nonzero();
if self.queue.try_enqueue(&ctx.enq, val) {
Ok(())
} else {
unsafe {
Err(T::from_nonzero(val))
}
}
}
pub fn pop(&self) -> Option<T> {
let ctx = self.context.get_or(Context::new);
let val = self.queue.try_dequeue(&ctx.deq)?;
unsafe {
Some(T::from_nonzero(val))
}
}
}
impl<T: Queueable> Drop for WfQueue<T> {
#[inline]
fn drop(&mut self) {
while self.pop().is_some() {}
}
}
impl Context {
pub const fn new() -> Context {
Context {
enq: CachePadded::new(queue::EnqueueCtx::new()),
deq: CachePadded::new(queue::DequeueCtx::new())
}
}
}
// impl Queueable
impl Queueable for NonZeroUsize {
#[inline]
fn into_nonzero(self) -> NonZeroUsize {
self
}
#[inline]
unsafe fn from_nonzero(n: NonZeroUsize) -> Self {
n
}
}
impl<T> Queueable for &'static T {
#[inline]
fn into_nonzero(self) -> NonZeroUsize {
unsafe {
NonZeroUsize::new_unchecked(self as *const T as usize)
}
}
#[inline]
unsafe fn from_nonzero(n: NonZeroUsize) -> Self {
&*(n.get() as *const T)
}
}
impl<T> Queueable for Box<T> {
#[inline]
fn into_nonzero(self) -> NonZeroUsize {
unsafe {
NonZeroUsize::new_unchecked(Box::into_raw(self) as usize)
}
}
#[inline]
unsafe fn from_nonzero(n: NonZeroUsize) -> Self {
Box::from_raw(n.get() as *mut _)
}
}
use loom::sync::Arc;
impl<T> Queueable for Arc<T> {
#[inline]
fn into_nonzero(self) -> NonZeroUsize {
unsafe {
NonZeroUsize::new_unchecked(Arc::into_raw(self) as usize)
}
}
#[inline]
unsafe fn from_nonzero(n: NonZeroUsize) -> Self {
Arc::from_raw(n.get() as *mut _)
}
}
use std::ptr::NonNull;
impl<T> Queueable for NonNull<T> {
#[inline]
fn into_nonzero(self) -> NonZeroUsize {
unsafe {
NonZeroUsize::new_unchecked(self.as_ptr() as usize)
}
}
#[inline]
unsafe fn from_nonzero(n: NonZeroUsize) -> Self {
NonNull::new_unchecked(n.get() as *mut _)
}
}
|
use std::net::SocketAddr;
use bytes::Bytes;
use futures::stream::SplitSink;
use hydroflow::hydroflow_syntax;
use hydroflow::lattices::Merge;
use hydroflow::scheduled::graph::Hydroflow;
use tokio_util::codec::LengthDelimitedCodec;
use tokio_util::udp::UdpFramed;
use crate::lattices::SealedSetOfIndexedValues;
use crate::structs::{ClientClass, Request};
use crate::test_data::client_class_iter;
pub(crate) async fn rep_server_flow(
shopping_ssiv: impl Iterator<Item = (usize, SealedSetOfIndexedValues<Request>)> + 'static,
out_addr: SocketAddr,
out: SplitSink<UdpFramed<LengthDelimitedCodec>, (Bytes, SocketAddr)>,
local_addr: SocketAddr,
remote_addr: SocketAddr,
gossip_addr: SocketAddr,
server_addrs: impl Iterator<Item = SocketAddr> + 'static,
) -> Hydroflow {
let (broadcast_out, broadcast_in, _) = hydroflow::util::bind_udp_bytes(gossip_addr).await;
let client_class = client_class_iter();
let ssiv_merge =
<SealedSetOfIndexedValues<Request> as Merge<SealedSetOfIndexedValues<Request>>>::merge;
const SSIV_BOT: fn() -> SealedSetOfIndexedValues<Request> = Default::default;
// Set up the Udp socket for proxy-server communication
let (reqs_out, reqs_in, _) = hydroflow::util::bind_udp_bytes(local_addr).await;
hydroflow_syntax! {
// Client Proxy
source_iter(shopping_ssiv)
-> map(|pair| (pair, remote_addr)) -> dest_sink_serde(reqs_out);
// Replicated Server
source_stream_serde(reqs_in)
-> map(Result::unwrap)
-> map(|((client, req), _a): ((usize, SealedSetOfIndexedValues<Request>), _)| (client, req))
-> fold_keyed::<'static>(SSIV_BOT, ssiv_merge)
-> [0]lookup_class;
source_iter(client_class) -> [1]lookup_class;
lookup_class = join::<'static>()
-> map(|(client, (li, class))| ((client, class), li) ) -> tee();
lookup_class[clients] -> all_in;
lookup_class[broadcast] -> [0]broadcast;
source_iter(server_addrs) -> [1]broadcast;
broadcast = cross_join::<'static>() -> dest_sink_serde(broadcast_out);
source_stream_serde(broadcast_in)
-> map(Result::unwrap)
-> map(|(m, _a): (((usize, ClientClass), SealedSetOfIndexedValues<Request>), _)| m)
-> all_in;
all_in = union()
-> fold_keyed::<'static>(SSIV_BOT, ssiv_merge)
-> unique()
-> map(|m| (m, out_addr)) -> dest_sink_serde(out);
}
}
|
#[cfg(feature = "extern")]
pub mod ex;
#[cfg(feature = "python")]
pub mod py;
mod test;
use super::super::super::
{
treloar_sums,
treloar_sum_0_with_prefactor
};
use std::f64::consts::PI;
use crate::physics::
{
PLANCK_CONSTANT,
BOLTZMANN_CONSTANT
};
use crate::physics::single_chain::ZERO;
/// The structure of the thermodynamics of the FJC model in the modified canonical ensemble approximated using an asymptotic approach valid for strong potentials.
pub struct FJC
{
/// The mass of each hinge in the chain in units of kg/mol.
pub hinge_mass: f64,
/// The length of each link in the chain in units of nm.
pub link_length: f64,
/// The number of links in the chain.
pub number_of_links: u8
}
/// The expected force as a function of the applied potential distance, potential stiffness, and temperature, parameterized by the number of links and link length.
pub fn force(number_of_links: &u8, link_length: &f64, potential_distance: &f64, potential_stiffness: &f64, temperature: &f64) -> f64
{
BOLTZMANN_CONSTANT*temperature/link_length*nondimensional_force(number_of_links, &(*potential_distance/((*number_of_links as f64)*link_length)), &(potential_stiffness*link_length.powi(2)/BOLTZMANN_CONSTANT/temperature))
}
/// The expected nondimensional force as a function of the applied nondimensional potential distance and nondimensional potential stiffness, parameterized by the number of links.
pub fn nondimensional_force(number_of_links: &u8, nondimensional_potential_distance: &f64, nondimensional_potential_stiffness: &f64) -> f64
{
let sums = treloar_sums(number_of_links, nondimensional_potential_distance, &[0, 1, 2, 3]);
let number_of_links_f64 = *number_of_links as f64;
(1.0/nondimensional_potential_distance + (0.5*number_of_links_f64 - 1.0)*sums[1]/sums[0])/number_of_links_f64 + 0.5/nondimensional_potential_stiffness/number_of_links_f64.powi(3)*((0.5*number_of_links_f64 - 1.0)*((0.5*number_of_links_f64 - 1.0)*sums[1]/sums[0]*((number_of_links_f64 - 2.0)*(sums[1]/sums[0]).powi(2) - (number_of_links_f64 - 3.0)*sums[2]/sums[0]) - (0.5*number_of_links_f64 - 1.5)*((0.5*number_of_links_f64 - 1.0)*sums[1]*sums[2]/sums[0].powi(2) - (0.5*number_of_links_f64 - 2.0)*sums[3]/sums[0])) + 2.0*nondimensional_potential_distance.powi(-3) - 2.0*((0.5*number_of_links_f64 - 1.0)*sums[1]/sums[0] + nondimensional_potential_distance.powi(-1))*((0.5*number_of_links_f64 - 1.0)*((0.5*number_of_links_f64 - 1.0)*(sums[1]/sums[0]).powi(2) - (0.5*number_of_links_f64 - 1.5)*sums[2]/sums[0]) - nondimensional_potential_distance.powi(-2)))
}
/// The Helmholtz free energy as a function of the applied potential distance, potential stiffness, and temperature, parameterized by the number of links, link length, and hinge mass.
pub fn helmholtz_free_energy(number_of_links: &u8, link_length: &f64, hinge_mass: &f64, potential_distance: &f64, potential_stiffness: &f64, temperature: &f64) -> f64
{
nondimensional_helmholtz_free_energy(number_of_links, link_length, hinge_mass, &(potential_distance/((*number_of_links as f64)*link_length)), &(potential_stiffness*link_length.powi(2)/BOLTZMANN_CONSTANT/temperature), temperature)*BOLTZMANN_CONSTANT*temperature
}
/// The Helmholtz free energy per link as a function of the applied potential distance, potential stiffness, and temperature, parameterized by the number of links, link length, and hinge mass.
pub fn helmholtz_free_energy_per_link(number_of_links: &u8, link_length: &f64, hinge_mass: &f64, potential_distance: &f64, potential_stiffness: &f64, temperature: &f64) -> f64
{
nondimensional_helmholtz_free_energy_per_link(number_of_links, link_length, hinge_mass, &(potential_distance/((*number_of_links as f64)*link_length)), &(potential_stiffness*link_length.powi(2)/BOLTZMANN_CONSTANT/temperature), temperature)*BOLTZMANN_CONSTANT*temperature
}
/// The relative Helmholtz free energy as a function of the applied potential distance, potential stiffness, and temperature, parameterized by the number of links and link length.
pub fn relative_helmholtz_free_energy(number_of_links: &u8, link_length: &f64, potential_distance: &f64, potential_stiffness: &f64, temperature: &f64) -> f64
{
helmholtz_free_energy(number_of_links, link_length, &1.0, potential_distance, potential_stiffness, temperature) - helmholtz_free_energy(number_of_links, link_length, &1.0, &(ZERO*(*number_of_links as f64)*link_length), potential_stiffness, temperature)
}
/// The relative Helmholtz free energy per link as a function of the applied potential distance, potential stiffness, and temperature, parameterized by the number of links and link length.
pub fn relative_helmholtz_free_energy_per_link(number_of_links: &u8, link_length: &f64, potential_distance: &f64, potential_stiffness: &f64, temperature: &f64) -> f64
{
helmholtz_free_energy_per_link(number_of_links, link_length, &1.0, potential_distance, potential_stiffness, temperature) - helmholtz_free_energy_per_link(number_of_links, link_length, &1.0, &(ZERO*(*number_of_links as f64)*link_length), potential_stiffness, temperature)
}
/// The nondimensional Helmholtz free energy as a function of the applied nondimensional potential distance, nondimensional potential stiffness, and temperature, parameterized by the number of links, link length, and hinge mass.
pub fn nondimensional_helmholtz_free_energy(number_of_links: &u8, link_length: &f64, hinge_mass: &f64, nondimensional_potential_distance: &f64, nondimensional_potential_stiffness: &f64, temperature: &f64) -> f64
{
let sums = treloar_sums(number_of_links, nondimensional_potential_distance, &[0, 1, 2]);
let number_of_links_f64 = *number_of_links as f64;
let number_of_links_squared = number_of_links_f64.powi(2);
let contour_length = number_of_links_f64*link_length;
-(treloar_sum_0_with_prefactor(number_of_links, nondimensional_potential_distance)/contour_length.powi(3)).ln() - (number_of_links_f64 - 1.0)*(8.0*PI.powi(2)*hinge_mass*link_length.powi(2)*BOLTZMANN_CONSTANT*temperature/PLANCK_CONSTANT.powi(2)).ln() - 1.5*(2.0*PI/nondimensional_potential_stiffness/number_of_links_squared).ln() - 3.0*(contour_length).ln() + 0.5/nondimensional_potential_stiffness/number_of_links_squared*((0.5*number_of_links_f64 - 1.0)*((0.5*number_of_links_f64 - 1.0)*(sums[1]/sums[0]).powi(2) - (0.5*number_of_links_f64 - 1.5)*sums[2]/sums[0]) - nondimensional_potential_distance.powi(-2) - ((0.5*number_of_links_f64 - 1.0)*sums[1]/sums[0] + nondimensional_potential_distance.powi(-1)).powi(2))
}
/// The nondimensional Helmholtz free energy per link as a function of the applied nondimensional potential distance, nondimensional potential stiffness, and temperature, parameterized by the number of links, link length, and hinge mass.
pub fn nondimensional_helmholtz_free_energy_per_link(number_of_links: &u8, link_length: &f64, hinge_mass: &f64, nondimensional_potential_distance: &f64, nondimensional_potential_stiffness: &f64, temperature: &f64) -> f64
{
nondimensional_helmholtz_free_energy(number_of_links, link_length, hinge_mass, nondimensional_potential_distance, nondimensional_potential_stiffness, temperature)/(*number_of_links as f64)
}
/// The nondimensional relative Helmholtz free energy as a function of the applied nondimensional potential distance and nondimensional potential stiffness, parameterized by the number of links.
pub fn nondimensional_relative_helmholtz_free_energy(number_of_links: &u8, nondimensional_potential_distance: &f64, nondimensional_potential_stiffness: &f64) -> f64
{
nondimensional_helmholtz_free_energy(number_of_links, &1.0, &1.0, nondimensional_potential_distance, nondimensional_potential_stiffness, &300.0) - nondimensional_helmholtz_free_energy(number_of_links, &1.0, &1.0, &ZERO, nondimensional_potential_stiffness, &300.0)
}
/// The nondimensional relative Helmholtz free energy per link as a function of the applied nondimensional potential distance and nondimensional potential stiffness, parameterized by the number of links.
pub fn nondimensional_relative_helmholtz_free_energy_per_link(number_of_links: &u8, nondimensional_potential_distance: &f64, nondimensional_potential_stiffness: &f64) -> f64
{
nondimensional_relative_helmholtz_free_energy(number_of_links, nondimensional_potential_distance, nondimensional_potential_stiffness)/(*number_of_links as f64)
}
/// The implemented functionality of the thermodynamics of the FJC model in the modified canonical ensemble approximated using an asymptotic approach valid for strong potentials.
impl FJC
{
/// Initializes and returns an instance of the thermodynamics of the FJC model in the modified canonical ensemble approximated using an asymptotic approach valid for strong potentials.
pub fn init(number_of_links: u8, link_length: f64, hinge_mass: f64) -> Self
{
FJC
{
hinge_mass,
link_length,
number_of_links
}
}
/// The expected force as a function of the applied potential distance, potential stiffness, and temperature.
pub fn force(&self, potential_distance: &f64, potential_stiffness: &f64, temperature: &f64) -> f64
{
force(&self.number_of_links, &self.link_length, potential_distance, potential_stiffness, temperature)
}
/// The expected nondimensional force as a function of the applied nondimensional potential distance and nondimensional potential stiffness.
pub fn nondimensional_force(&self, nondimensional_potential_distance: &f64, nondimensional_potential_stiffness: &f64) -> f64
{
nondimensional_force(&self.number_of_links, nondimensional_potential_distance, nondimensional_potential_stiffness)
}
/// The Helmholtz free energy as a function of the applied potential distance, potential stiffness, and temperature.
pub fn helmholtz_free_energy(&self, potential_distance: &f64, potential_stiffness: &f64, temperature: &f64) -> f64
{
helmholtz_free_energy(&self.number_of_links, &self.link_length, &self.hinge_mass, potential_distance, potential_stiffness, temperature)
}
/// The Helmholtz free energy per link as a function of the applied potential distance, potential stiffness, and temperature.
pub fn helmholtz_free_energy_per_link(&self, potential_distance: &f64, potential_stiffness: &f64, temperature: &f64) -> f64
{
helmholtz_free_energy_per_link(&self.number_of_links, &self.link_length, &self.hinge_mass, potential_distance, potential_stiffness, temperature)
}
/// The relative Helmholtz free energy as a function of the applied potential distance, potential stiffness, and temperature.
pub fn relative_helmholtz_free_energy(&self, potential_distance: &f64, potential_stiffness: &f64, temperature: &f64) -> f64
{
relative_helmholtz_free_energy(&self.number_of_links, &self.link_length, potential_distance, potential_stiffness, temperature)
}
/// The relative Helmholtz free energy per link as a function of the applied potential distance, potential stiffness, and temperature.
pub fn relative_helmholtz_free_energy_per_link(&self, potential_distance: &f64, potential_stiffness: &f64, temperature: &f64) -> f64
{
relative_helmholtz_free_energy_per_link(&self.number_of_links, &self.link_length, potential_distance, potential_stiffness, temperature)
}
/// The nondimensional Helmholtz free energy as a function of the applied nondimensional potential distance, nondimensional potential stiffness, and temperature.
pub fn nondimensional_helmholtz_free_energy(&self, nondimensional_potential_distance: &f64, nondimensional_potential_stiffness: &f64, temperature: &f64) -> f64
{
nondimensional_helmholtz_free_energy(&self.number_of_links, &self.link_length, &self.hinge_mass, nondimensional_potential_distance, nondimensional_potential_stiffness, temperature)
}
/// The nondimensional Helmholtz free energy per link as a function of the applied nondimensional potential distance, nondimensional potential stiffness, and temperature.
pub fn nondimensional_helmholtz_free_energy_per_link(&self, nondimensional_potential_distance: &f64, nondimensional_potential_stiffness: &f64, temperature: &f64) -> f64
{
nondimensional_helmholtz_free_energy_per_link(&self.number_of_links, &self.link_length, &self.hinge_mass, nondimensional_potential_distance, nondimensional_potential_stiffness, temperature)
}
/// The nondimensional relative Helmholtz free energy as a function of the applied nondimensional potential distance and nondimensional potential stiffness.
pub fn nondimensional_relative_helmholtz_free_energy(&self, nondimensional_potential_distance: &f64, nondimensional_potential_stiffness: &f64) -> f64
{
nondimensional_relative_helmholtz_free_energy(&self.number_of_links, nondimensional_potential_distance, nondimensional_potential_stiffness)
}
/// The nondimensional relative Helmholtz free energy per link as a function of the applied nondimensional potential distance and nondimensional potential stiffness.
pub fn nondimensional_relative_helmholtz_free_energy_per_link(&self, nondimensional_potential_distance: &f64, nondimensional_potential_stiffness: &f64) -> f64
{
nondimensional_relative_helmholtz_free_energy_per_link(&self.number_of_links, nondimensional_potential_distance, nondimensional_potential_stiffness)
}
}
|
pub const RESET: &str = "\x1B[0m";
pub const BOLD: &str = "\x1B[1m";
pub const ITALIC: &str = "\x1B[3m";
pub const UNDERLINE: &str = "\x1B[4m";
pub const INVERSE: &str = "\x1B[7m";
pub const BLACK: &str = "\x1B[30m";
pub const RED: &str = "\x1B[31m";
pub const GREEN: &str = "\x1B[32m";
pub const YELLOW: &str = "\x1B[33m";
pub const BLUE: &str = "\x1B[34m";
pub const MAGENTA: &str = "\x1B[35m";
pub const CYAN: &str = "\x1B[36m";
pub const WHITE: &str = "\x1B[37m";
pub const GREY: &str = "\x1B[38;5;237m";
pub const BG_BLACK: &str = "\x1B[40m";
pub const BG_RED: &str = "\x1B[41m";
pub const BG_GREEN: &str = "\x1B[42m";
pub const BG_YELLOW: &str = "\x1B[43m";
pub const BG_BLUE: &str = "\x1B[44m";
pub const BG_MAGENTA: &str = "\x1B[45m";
pub const BG_CYAN: &str = "\x1B[46m";
pub const BG_WHITE: &str = "\x1B[47m";
|
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![warn(clippy::module_name_repetitions)]
#![allow(dead_code)]
mod foo {
pub fn foo() {}
pub fn foo_bar() {}
pub fn bar_foo() {}
pub struct FooCake {}
pub enum CakeFoo {}
pub struct Foo7Bar;
// Should not warn
pub struct Foobar;
}
fn main() {}
|
use std::cmp::max;
use crate::prelude::*;
use super::Filter;
#[derive(Clone, Debug)]
pub struct BoxFilter {
radius: Vector2f,
radius_inv: Vector2f,
}
impl BoxFilter {
pub fn new(radius: Vector2f) -> Self {
Self {
radius,
radius_inv: Vector2f::new(
float(1.0) / radius.x,
float(1.0) / radius.y,
),
}
}
}
impl Filter for BoxFilter {
fn radius(&self) -> Vector2f {
self.radius
}
fn radius_inv(&self) -> Vector2f {
self.radius_inv
}
fn evaluate(&self, _: Point2f) -> Float {
float(1.0)
}
}
#[derive(Clone, Debug)]
pub struct TriangleFilter {
radius: Vector2f,
radius_inv: Vector2f,
}
impl TriangleFilter {
pub fn new(radius: Vector2f) -> Self {
Self {
radius,
radius_inv: Vector2f::new(
float(1.0) / radius.x,
float(1.0) / radius.y,
),
}
}
}
impl Filter for TriangleFilter {
fn radius(&self) -> Vector2f {
self.radius
}
fn radius_inv(&self) -> Vector2f {
self.radius_inv
}
fn evaluate(&self, p: Point2f) -> Float {
max(float(0.0), self.radius.x - p.x.abs()) *
max(float(0.0), self.radius.y - p.y.abs())
}
}
|
use proconio::input;
fn main() {
input! {
n:u32,
}
let mut ni = n;
let mut sn = 0;
while ni > 0 {
sn += ni % 10;
ni /= 10;
}
let ans = if n%sn == 0 {"Yes"} else {"No"};
println!("{}", ans);
}
|
use std::fs::read_dir;
use std::io::Write;
use std::path::{self, Path};
use anyhow::Result;
use structopt::StructOpt;
use utility::{clap_cache_dir, remove_dir_contents};
use crate::datastore::CACHE_INFO_IN_MEMORY;
/// List and remove all the cached contents.
#[derive(StructOpt, Debug, Clone)]
pub struct Cache {
/// List the current cached entries.
#[structopt(short, long)]
list: bool,
/// Purge all the cached contents.
#[structopt(short, long)]
purge: bool,
}
impl Cache {
pub fn run(&self) -> Result<()> {
let cache_dir = clap_cache_dir()?;
if self.purge {
if let Some(f) = crate::datastore::CACHE_JSON_PATH.as_deref() {
std::fs::remove_file(f)?;
println!("Cache metadata {} has been deleted", f.display());
}
remove_dir_contents(&cache_dir)?;
println!(
"Current cache directory {} has been purged",
cache_dir.display()
);
return Ok(());
}
if self.list {
self.list(&cache_dir)?;
}
Ok(())
}
fn list(&self, cache_dir: &Path) -> Result<()> {
let stdout = std::io::stdout();
let mut lock = stdout.lock();
let cache_dir_str = cache_dir.display();
writeln!(lock, "Current cache directory:")?;
writeln!(lock, "\t{}\n", cache_dir_str)?;
let cache_info = CACHE_INFO_IN_MEMORY.lock();
writeln!(lock, "{:#?}\n", cache_info)?;
if self.list {
writeln!(lock, "Cached entries:")?;
let mut entries = read_dir(cache_dir)?
.map(|res| {
res.map(|e| {
e.path()
.file_name()
.and_then(std::ffi::OsStr::to_str)
.map(Into::into)
.unwrap_or_else(|| panic!("Couldn't get file name from {:?}", e.path()))
})
})
.collect::<Result<Vec<String>, std::io::Error>>()?;
entries.sort();
for fname in entries {
writeln!(lock, "\t{}{}{}", cache_dir_str, path::MAIN_SEPARATOR, fname)?;
}
}
Ok(())
}
}
|
use bs58;
use byteorder::{ByteOrder, LittleEndian};
use ed25519_dalek::PublicKey;
use multihash::Blake2b256;
use rand_core::{OsRng, RngCore};
pub struct Wallet {
seed: Vec<u8>,
}
impl Wallet {
pub fn new() -> Wallet {
let mut seed = [0u8; 32];
OsRng.fill_bytes(&mut seed);
Wallet {
seed: seed.to_vec(),
}
}
pub fn from_base58(seed: &str) -> Wallet {
let decoded = bs58::decode(seed).into_vec().unwrap();
Wallet { seed: decoded }
}
pub fn sub_seed(&self, index: u64) -> Vec<u8> {
let mut index_bytes = [0; 8];
LittleEndian::write_u64(&mut index_bytes, index);
let res = Blake2b256::digest(&index_bytes);
// first 4 bytes aren't needed
let blakehash = &res[4..];
// XOR
let sub_seed: Vec<u8> = self
.seed
.iter()
.zip(blakehash.iter())
.map(|(&x1, &x2)| x1 ^ x2)
.collect();
sub_seed
}
pub fn address_bytes(&self, index: usize) -> Vec<u8> {
let subseed = self.sub_seed(index as u64);
let private_key = ed25519_dalek::SecretKey::from_bytes(&subseed).unwrap();
let public_key: PublicKey = PublicKey::from(&private_key);
let address_bytes = Blake2b256::digest(&public_key.to_bytes());
//add VersionED25519 byte
[&[1], &address_bytes[4..]].concat()
}
pub fn address(&self, index: usize) -> String {
bs58::encode(self.address_bytes(index)).into_string()
}
pub fn get_base58_seed(&self) -> String {
bs58::encode(&self.seed).into_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn correct_addresses() {
let wallet = Wallet::from_base58("Gnp4f3nn8RFgEMpjsr58DEWKQHTfpGP5wvic5e8aeSBp");
assert_eq!(
wallet.address(0),
"QbmLnx2zrQQJ1U5JyR54qrzWgQvqiD4wNjoRKYqCjo8q"
);
assert_eq!(
wallet.address(1),
"LbNeQyMtf2HF1D6oQWabsrd6wPX1CUhgacz8htoN6vJs"
);
}
}
|
#[doc = "Register `APB1LENR` reader"]
pub type R = crate::R<APB1LENR_SPEC>;
#[doc = "Register `APB1LENR` writer"]
pub type W = crate::W<APB1LENR_SPEC>;
#[doc = "Field `TIM2EN` reader - TIM2 clock enable Set and reset by software."]
pub type TIM2EN_R = crate::BitReader;
#[doc = "Field `TIM2EN` writer - TIM2 clock enable Set and reset by software."]
pub type TIM2EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM3EN` reader - TIM3 clock enable Set and reset by software."]
pub type TIM3EN_R = crate::BitReader;
#[doc = "Field `TIM3EN` writer - TIM3 clock enable Set and reset by software."]
pub type TIM3EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM4EN` reader - TIM4 clock enable Set and reset by software."]
pub type TIM4EN_R = crate::BitReader;
#[doc = "Field `TIM4EN` writer - TIM4 clock enable Set and reset by software."]
pub type TIM4EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM5EN` reader - TIM5 clock enable Set and reset by software."]
pub type TIM5EN_R = crate::BitReader;
#[doc = "Field `TIM5EN` writer - TIM5 clock enable Set and reset by software."]
pub type TIM5EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM6EN` reader - TIM6 clock enable Set and reset by software."]
pub type TIM6EN_R = crate::BitReader;
#[doc = "Field `TIM6EN` writer - TIM6 clock enable Set and reset by software."]
pub type TIM6EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM7EN` reader - TIM7 clock enable Set and reset by software."]
pub type TIM7EN_R = crate::BitReader;
#[doc = "Field `TIM7EN` writer - TIM7 clock enable Set and reset by software."]
pub type TIM7EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM12EN` reader - TIM12 clock enable Set and reset by software."]
pub type TIM12EN_R = crate::BitReader;
#[doc = "Field `TIM12EN` writer - TIM12 clock enable Set and reset by software."]
pub type TIM12EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM13EN` reader - TIM13 clock enable Set and reset by software."]
pub type TIM13EN_R = crate::BitReader;
#[doc = "Field `TIM13EN` writer - TIM13 clock enable Set and reset by software."]
pub type TIM13EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM14EN` reader - TIM14 clock enable Set and reset by software."]
pub type TIM14EN_R = crate::BitReader;
#[doc = "Field `TIM14EN` writer - TIM14 clock enable Set and reset by software."]
pub type TIM14EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `WWDGEN` reader - WWDG clock enable Set and reset by software."]
pub type WWDGEN_R = crate::BitReader;
#[doc = "Field `WWDGEN` writer - WWDG clock enable Set and reset by software."]
pub type WWDGEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SPI2EN` reader - SPI2 clock enable Set and reset by software."]
pub type SPI2EN_R = crate::BitReader;
#[doc = "Field `SPI2EN` writer - SPI2 clock enable Set and reset by software."]
pub type SPI2EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SPI3EN` reader - SPI3 clock enable Set and reset by software."]
pub type SPI3EN_R = crate::BitReader;
#[doc = "Field `SPI3EN` writer - SPI3 clock enable Set and reset by software."]
pub type SPI3EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USART2EN` reader - USART2 clock enable Set and reset by software."]
pub type USART2EN_R = crate::BitReader;
#[doc = "Field `USART2EN` writer - USART2 clock enable Set and reset by software."]
pub type USART2EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USART3EN` reader - USART3 clock enable Set and reset by software."]
pub type USART3EN_R = crate::BitReader;
#[doc = "Field `USART3EN` writer - USART3 clock enable Set and reset by software."]
pub type USART3EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `UART4EN` reader - UART4 clock enable Set and reset by software."]
pub type UART4EN_R = crate::BitReader;
#[doc = "Field `UART4EN` writer - UART4 clock enable Set and reset by software."]
pub type UART4EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `UART5EN` reader - UART5 clock enable Set and reset by software."]
pub type UART5EN_R = crate::BitReader;
#[doc = "Field `UART5EN` writer - UART5 clock enable Set and reset by software."]
pub type UART5EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C1EN` reader - I2C1 clock enable Set and reset by software."]
pub type I2C1EN_R = crate::BitReader;
#[doc = "Field `I2C1EN` writer - I2C1 clock enable Set and reset by software."]
pub type I2C1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C2EN` reader - I2C2 clock enable Set and reset by software."]
pub type I2C2EN_R = crate::BitReader;
#[doc = "Field `I2C2EN` writer - I2C2 clock enable Set and reset by software."]
pub type I2C2EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I3C1EN` reader - I3C1 clock enable Set and reset by software."]
pub type I3C1EN_R = crate::BitReader;
#[doc = "Field `I3C1EN` writer - I3C1 clock enable Set and reset by software."]
pub type I3C1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CRSEN` reader - CRS clock enable Set and reset by software."]
pub type CRSEN_R = crate::BitReader;
#[doc = "Field `CRSEN` writer - CRS clock enable Set and reset by software."]
pub type CRSEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USART6EN` reader - USART6 clock enable Set and reset by software."]
pub type USART6EN_R = crate::BitReader;
#[doc = "Field `USART6EN` writer - USART6 clock enable Set and reset by software."]
pub type USART6EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USART10EN` reader - USART10 clock enable Set and reset by software."]
pub type USART10EN_R = crate::BitReader;
#[doc = "Field `USART10EN` writer - USART10 clock enable Set and reset by software."]
pub type USART10EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USART11EN` reader - USART11 clock enable"]
pub type USART11EN_R = crate::BitReader;
#[doc = "Field `USART11EN` writer - USART11 clock enable"]
pub type USART11EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CECEN` reader - HDMI-CEC clock enable Set and reset by software."]
pub type CECEN_R = crate::BitReader;
#[doc = "Field `CECEN` writer - HDMI-CEC clock enable Set and reset by software."]
pub type CECEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `UART7EN` reader - UART7 clock enable Set and reset by software."]
pub type UART7EN_R = crate::BitReader;
#[doc = "Field `UART7EN` writer - UART7 clock enable Set and reset by software."]
pub type UART7EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `UART8EN` reader - UART8 clock enable Set and reset by software."]
pub type UART8EN_R = crate::BitReader;
#[doc = "Field `UART8EN` writer - UART8 clock enable Set and reset by software."]
pub type UART8EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - TIM2 clock enable Set and reset by software."]
#[inline(always)]
pub fn tim2en(&self) -> TIM2EN_R {
TIM2EN_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - TIM3 clock enable Set and reset by software."]
#[inline(always)]
pub fn tim3en(&self) -> TIM3EN_R {
TIM3EN_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - TIM4 clock enable Set and reset by software."]
#[inline(always)]
pub fn tim4en(&self) -> TIM4EN_R {
TIM4EN_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - TIM5 clock enable Set and reset by software."]
#[inline(always)]
pub fn tim5en(&self) -> TIM5EN_R {
TIM5EN_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - TIM6 clock enable Set and reset by software."]
#[inline(always)]
pub fn tim6en(&self) -> TIM6EN_R {
TIM6EN_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - TIM7 clock enable Set and reset by software."]
#[inline(always)]
pub fn tim7en(&self) -> TIM7EN_R {
TIM7EN_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - TIM12 clock enable Set and reset by software."]
#[inline(always)]
pub fn tim12en(&self) -> TIM12EN_R {
TIM12EN_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - TIM13 clock enable Set and reset by software."]
#[inline(always)]
pub fn tim13en(&self) -> TIM13EN_R {
TIM13EN_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - TIM14 clock enable Set and reset by software."]
#[inline(always)]
pub fn tim14en(&self) -> TIM14EN_R {
TIM14EN_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 11 - WWDG clock enable Set and reset by software."]
#[inline(always)]
pub fn wwdgen(&self) -> WWDGEN_R {
WWDGEN_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 14 - SPI2 clock enable Set and reset by software."]
#[inline(always)]
pub fn spi2en(&self) -> SPI2EN_R {
SPI2EN_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - SPI3 clock enable Set and reset by software."]
#[inline(always)]
pub fn spi3en(&self) -> SPI3EN_R {
SPI3EN_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 17 - USART2 clock enable Set and reset by software."]
#[inline(always)]
pub fn usart2en(&self) -> USART2EN_R {
USART2EN_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - USART3 clock enable Set and reset by software."]
#[inline(always)]
pub fn usart3en(&self) -> USART3EN_R {
USART3EN_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - UART4 clock enable Set and reset by software."]
#[inline(always)]
pub fn uart4en(&self) -> UART4EN_R {
UART4EN_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - UART5 clock enable Set and reset by software."]
#[inline(always)]
pub fn uart5en(&self) -> UART5EN_R {
UART5EN_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - I2C1 clock enable Set and reset by software."]
#[inline(always)]
pub fn i2c1en(&self) -> I2C1EN_R {
I2C1EN_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - I2C2 clock enable Set and reset by software."]
#[inline(always)]
pub fn i2c2en(&self) -> I2C2EN_R {
I2C2EN_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - I3C1 clock enable Set and reset by software."]
#[inline(always)]
pub fn i3c1en(&self) -> I3C1EN_R {
I3C1EN_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - CRS clock enable Set and reset by software."]
#[inline(always)]
pub fn crsen(&self) -> CRSEN_R {
CRSEN_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - USART6 clock enable Set and reset by software."]
#[inline(always)]
pub fn usart6en(&self) -> USART6EN_R {
USART6EN_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 26 - USART10 clock enable Set and reset by software."]
#[inline(always)]
pub fn usart10en(&self) -> USART10EN_R {
USART10EN_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - USART11 clock enable"]
#[inline(always)]
pub fn usart11en(&self) -> USART11EN_R {
USART11EN_R::new(((self.bits >> 27) & 1) != 0)
}
#[doc = "Bit 28 - HDMI-CEC clock enable Set and reset by software."]
#[inline(always)]
pub fn cecen(&self) -> CECEN_R {
CECEN_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 30 - UART7 clock enable Set and reset by software."]
#[inline(always)]
pub fn uart7en(&self) -> UART7EN_R {
UART7EN_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - UART8 clock enable Set and reset by software."]
#[inline(always)]
pub fn uart8en(&self) -> UART8EN_R {
UART8EN_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - TIM2 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim2en(&mut self) -> TIM2EN_W<APB1LENR_SPEC, 0> {
TIM2EN_W::new(self)
}
#[doc = "Bit 1 - TIM3 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim3en(&mut self) -> TIM3EN_W<APB1LENR_SPEC, 1> {
TIM3EN_W::new(self)
}
#[doc = "Bit 2 - TIM4 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim4en(&mut self) -> TIM4EN_W<APB1LENR_SPEC, 2> {
TIM4EN_W::new(self)
}
#[doc = "Bit 3 - TIM5 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim5en(&mut self) -> TIM5EN_W<APB1LENR_SPEC, 3> {
TIM5EN_W::new(self)
}
#[doc = "Bit 4 - TIM6 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim6en(&mut self) -> TIM6EN_W<APB1LENR_SPEC, 4> {
TIM6EN_W::new(self)
}
#[doc = "Bit 5 - TIM7 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim7en(&mut self) -> TIM7EN_W<APB1LENR_SPEC, 5> {
TIM7EN_W::new(self)
}
#[doc = "Bit 6 - TIM12 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim12en(&mut self) -> TIM12EN_W<APB1LENR_SPEC, 6> {
TIM12EN_W::new(self)
}
#[doc = "Bit 7 - TIM13 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim13en(&mut self) -> TIM13EN_W<APB1LENR_SPEC, 7> {
TIM13EN_W::new(self)
}
#[doc = "Bit 8 - TIM14 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim14en(&mut self) -> TIM14EN_W<APB1LENR_SPEC, 8> {
TIM14EN_W::new(self)
}
#[doc = "Bit 11 - WWDG clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn wwdgen(&mut self) -> WWDGEN_W<APB1LENR_SPEC, 11> {
WWDGEN_W::new(self)
}
#[doc = "Bit 14 - SPI2 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn spi2en(&mut self) -> SPI2EN_W<APB1LENR_SPEC, 14> {
SPI2EN_W::new(self)
}
#[doc = "Bit 15 - SPI3 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn spi3en(&mut self) -> SPI3EN_W<APB1LENR_SPEC, 15> {
SPI3EN_W::new(self)
}
#[doc = "Bit 17 - USART2 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn usart2en(&mut self) -> USART2EN_W<APB1LENR_SPEC, 17> {
USART2EN_W::new(self)
}
#[doc = "Bit 18 - USART3 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn usart3en(&mut self) -> USART3EN_W<APB1LENR_SPEC, 18> {
USART3EN_W::new(self)
}
#[doc = "Bit 19 - UART4 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn uart4en(&mut self) -> UART4EN_W<APB1LENR_SPEC, 19> {
UART4EN_W::new(self)
}
#[doc = "Bit 20 - UART5 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn uart5en(&mut self) -> UART5EN_W<APB1LENR_SPEC, 20> {
UART5EN_W::new(self)
}
#[doc = "Bit 21 - I2C1 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn i2c1en(&mut self) -> I2C1EN_W<APB1LENR_SPEC, 21> {
I2C1EN_W::new(self)
}
#[doc = "Bit 22 - I2C2 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn i2c2en(&mut self) -> I2C2EN_W<APB1LENR_SPEC, 22> {
I2C2EN_W::new(self)
}
#[doc = "Bit 23 - I3C1 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn i3c1en(&mut self) -> I3C1EN_W<APB1LENR_SPEC, 23> {
I3C1EN_W::new(self)
}
#[doc = "Bit 24 - CRS clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn crsen(&mut self) -> CRSEN_W<APB1LENR_SPEC, 24> {
CRSEN_W::new(self)
}
#[doc = "Bit 25 - USART6 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn usart6en(&mut self) -> USART6EN_W<APB1LENR_SPEC, 25> {
USART6EN_W::new(self)
}
#[doc = "Bit 26 - USART10 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn usart10en(&mut self) -> USART10EN_W<APB1LENR_SPEC, 26> {
USART10EN_W::new(self)
}
#[doc = "Bit 27 - USART11 clock enable"]
#[inline(always)]
#[must_use]
pub fn usart11en(&mut self) -> USART11EN_W<APB1LENR_SPEC, 27> {
USART11EN_W::new(self)
}
#[doc = "Bit 28 - HDMI-CEC clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn cecen(&mut self) -> CECEN_W<APB1LENR_SPEC, 28> {
CECEN_W::new(self)
}
#[doc = "Bit 30 - UART7 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn uart7en(&mut self) -> UART7EN_W<APB1LENR_SPEC, 30> {
UART7EN_W::new(self)
}
#[doc = "Bit 31 - UART8 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn uart8en(&mut self) -> UART8EN_W<APB1LENR_SPEC, 31> {
UART8EN_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "RCC APB1 peripheral clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1lenr::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 [`apb1lenr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct APB1LENR_SPEC;
impl crate::RegisterSpec for APB1LENR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`apb1lenr::R`](R) reader structure"]
impl crate::Readable for APB1LENR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`apb1lenr::W`](W) writer structure"]
impl crate::Writable for APB1LENR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets APB1LENR to value 0"]
impl crate::Resettable for APB1LENR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//! Target and related types.
use super::channel;
/// Standard target represents a channel names list and a channel group names
/// list that together are suitable for use in the API calls.
/// The value of this type is guaranteed to fulfill the standard invariants
/// required by the API calls - that at least one channel or channel group has
/// to be specified.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Standard {
/// The channel names you are subscribing to.
channels: Vec<channel::Name>,
/// The channel group names you are subscribing to.
channel_groups: Vec<channel::Name>,
}
impl Standard {
/// Create a standard target from a list of channels and a list of channel
/// groups.
///
/// # Errors
///
/// Retuns an error when both channels and channel groups lists are empty.
///
pub fn new(
channels: Vec<channel::Name>,
channel_groups: Vec<channel::Name>,
) -> Result<Self, (Vec<channel::Name>, Vec<channel::Name>)> {
if channels.is_empty() && channel_groups.is_empty() {
return Err((channels, channel_groups));
}
Ok(Self {
channels,
channel_groups,
})
}
/// Extract target value into channels and channel groups.
#[must_use]
pub fn into_inner(self) -> (Vec<channel::Name>, Vec<channel::Name>) {
(self.channels, self.channel_groups)
}
}
#[cfg(test)]
mod tests {
use super::Standard;
#[test]
fn standard_valid() {
assert!(Standard::new(vec!["channel".parse().unwrap()], vec![]).is_ok());
assert!(Standard::new(vec![], vec!["channel_group".parse().unwrap()]).is_ok());
assert!(Standard::new(
vec!["channel".parse().unwrap()],
vec!["channel_group".parse().unwrap()]
)
.is_ok());
assert!(Standard::new(
vec!["a".parse().unwrap(), "b".parse().unwrap()],
vec!["a".parse().unwrap(), "b".parse().unwrap()]
)
.is_ok());
}
#[test]
fn standard_invalid() {
assert!(Standard::new(vec![], vec![]).is_err());
}
}
|
pub mod decay;
pub mod collide;
|
#[doc = "Reader of register HSEM_C2MISR"]
pub type R = crate::R<u32, super::HSEM_C2MISR>;
#[doc = "Reader of field `MISF0`"]
pub type MISF0_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF1`"]
pub type MISF1_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF2`"]
pub type MISF2_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF3`"]
pub type MISF3_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF4`"]
pub type MISF4_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF5`"]
pub type MISF5_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF6`"]
pub type MISF6_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF7`"]
pub type MISF7_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF8`"]
pub type MISF8_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF9`"]
pub type MISF9_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF10`"]
pub type MISF10_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF11`"]
pub type MISF11_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF12`"]
pub type MISF12_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF13`"]
pub type MISF13_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF14`"]
pub type MISF14_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF15`"]
pub type MISF15_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF16`"]
pub type MISF16_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF17`"]
pub type MISF17_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF18`"]
pub type MISF18_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF19`"]
pub type MISF19_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF20`"]
pub type MISF20_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF21`"]
pub type MISF21_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF22`"]
pub type MISF22_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF23`"]
pub type MISF23_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF24`"]
pub type MISF24_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF25`"]
pub type MISF25_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF26`"]
pub type MISF26_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF27`"]
pub type MISF27_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF28`"]
pub type MISF28_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF29`"]
pub type MISF29_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF30`"]
pub type MISF30_R = crate::R<bool, bool>;
#[doc = "Reader of field `MISF31`"]
pub type MISF31_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf0(&self) -> MISF0_R {
MISF0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf1(&self) -> MISF1_R {
MISF1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf2(&self) -> MISF2_R {
MISF2_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf3(&self) -> MISF3_R {
MISF3_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf4(&self) -> MISF4_R {
MISF4_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf5(&self) -> MISF5_R {
MISF5_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf6(&self) -> MISF6_R {
MISF6_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf7(&self) -> MISF7_R {
MISF7_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf8(&self) -> MISF8_R {
MISF8_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf9(&self) -> MISF9_R {
MISF9_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf10(&self) -> MISF10_R {
MISF10_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf11(&self) -> MISF11_R {
MISF11_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf12(&self) -> MISF12_R {
MISF12_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf13(&self) -> MISF13_R {
MISF13_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf14(&self) -> MISF14_R {
MISF14_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf15(&self) -> MISF15_R {
MISF15_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf16(&self) -> MISF16_R {
MISF16_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf17(&self) -> MISF17_R {
MISF17_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf18(&self) -> MISF18_R {
MISF18_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 19 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf19(&self) -> MISF19_R {
MISF19_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 20 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf20(&self) -> MISF20_R {
MISF20_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 21 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf21(&self) -> MISF21_R {
MISF21_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 22 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf22(&self) -> MISF22_R {
MISF22_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 23 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf23(&self) -> MISF23_R {
MISF23_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 24 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf24(&self) -> MISF24_R {
MISF24_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 25 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf25(&self) -> MISF25_R {
MISF25_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 26 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf26(&self) -> MISF26_R {
MISF26_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bit 27 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf27(&self) -> MISF27_R {
MISF27_R::new(((self.bits >> 27) & 0x01) != 0)
}
#[doc = "Bit 28 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf28(&self) -> MISF28_R {
MISF28_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 29 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf29(&self) -> MISF29_R {
MISF29_R::new(((self.bits >> 29) & 0x01) != 0)
}
#[doc = "Bit 30 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf30(&self) -> MISF30_R {
MISF30_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - masked interrupt(N) semaphore n status bit after enable (mask)"]
#[inline(always)]
pub fn misf31(&self) -> MISF31_R {
MISF31_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
|
use glium::{Surface, VertexBuffer};
use lazy_static::lazy_static;
use send_wrapper::SendWrapper;
mod shaders;
mod textures;
use crate::game::{Camera, ChunkPos, Grid, Tile, TilePos, CHUNK_SIZE};
const TILE_BATCH_SIZE: usize = 4096;
#[derive(Debug, Copy, Clone)]
struct Vertex2D {
pos: [f32; 2],
}
glium::implement_vertex!(Vertex2D, pos);
#[derive(Debug, Copy, Clone)]
struct TileAttr {
tile_coords: [i32; 2],
sprite_coords: [u32; 2],
}
glium::implement_vertex!(TileAttr, tile_coords, sprite_coords);
impl TileAttr {
fn new(tile_coords: [i32; 2], sprite_coords: [u32; 2]) -> Self {
Self {
tile_coords,
sprite_coords,
}
}
}
lazy_static! {
static ref SQUARE_VBO: SendWrapper<VertexBuffer<Vertex2D>> = SendWrapper::new(
VertexBuffer::immutable(
&**crate::DISPLAY,
&[
Vertex2D { pos: [0.0, 0.0] },
Vertex2D { pos: [1.0, 0.0] },
Vertex2D { pos: [0.0, 1.0] },
Vertex2D { pos: [1.0, 1.0] },
]
)
.expect("Failed to create vertex buffer")
);
static ref TILE_INSTANCES_VBO: SendWrapper<VertexBuffer<TileAttr>> = SendWrapper::new(
VertexBuffer::empty_dynamic(&**crate::DISPLAY, TILE_BATCH_SIZE)
.expect("Failed to create vertex buffer")
);
static ref TILE_INSTANCES_OVERFLOW_VBO: SendWrapper<VertexBuffer<TileAttr>> = SendWrapper::new(
VertexBuffer::empty_dynamic(&**crate::DISPLAY, TILE_BATCH_SIZE)
.expect("Failed to create vertex buffer")
);
}
pub fn draw_grid(target: &mut glium::Frame, grid: &Grid, camera: &mut Camera) {
target.clear_color_srgb(0.2, 0.2, 0.2, 1.0);
// Update target dimensisons and get camera data.
camera.set_target_dimensions(target.get_dimensions());
let tile_transform_matrix: [[f32; 4]; 4] = camera.gl_matrix().into();
let draw_params = glium::DrawParameters {
blend: glium::Blend::alpha_blending(),
..glium::DrawParameters::default()
};
let (target_w, target_h) = target.get_dimensions();
let TilePos(mut x1, mut y1) = camera.pixel_to_tile_pos((0, target_h));
x1 -= 1;
y1 -= 1;
let TilePos(mut x2, mut y2) = camera.pixel_to_tile_pos((target_w, 0));
x2 += 1;
y2 += 1;
let ChunkPos(chunk_x1, chunk_y1) = TilePos(x1, y1).chunk();
let ChunkPos(chunk_x2, chunk_y2) = TilePos(x2, y2).chunk();
let mut tile_attrs = vec![];
for chunk_y in chunk_y1..=chunk_y2 {
for chunk_x in chunk_x1..=chunk_x2 {
let chunk = grid.get_chunk(ChunkPos(chunk_x, chunk_y));
for y in 0..CHUNK_SIZE as i32 {
for x in 0..CHUNK_SIZE as i32 {
let tile_coords = [
x + chunk_x * CHUNK_SIZE as i32,
y + chunk_y * CHUNK_SIZE as i32,
];
let tile = match chunk {
Some(c) => c.get_tile(TilePos(x, y)),
None => Tile::default(),
};
let bg_sprite_coords = textures::bg_sprite_coords(tile);
tile_attrs.push(TileAttr::new(tile_coords, bg_sprite_coords));
if let Some(fg_sprite_coords) = textures::fg_sprite_coords(tile) {
tile_attrs.push(TileAttr::new(tile_coords, fg_sprite_coords));
}
}
}
}
}
let uniform = glium::uniform! {
spritesheet: **textures::TILES_SPRITESHEET_SAMPLER,
camera_center: camera.int_center(),
transform: tile_transform_matrix,
};
for batch in tile_attrs.chunks(TILE_BATCH_SIZE) {
let instances_slice = if batch.len() == TILE_BATCH_SIZE {
&**TILE_INSTANCES_VBO
} else {
// For some bizarre reason, writing to only a portion of a VBO used
// for instanced rendering messes up *previous* draw calls using
// that same VBO. So we have to use the "overflow" VBO for the last
// batch.
&**TILE_INSTANCES_OVERFLOW_VBO
}
.slice(0..batch.len())
.unwrap();
instances_slice.write(batch);
target
.draw(
(&**SQUARE_VBO, instances_slice.per_instance().unwrap()),
&glium::index::NoIndices(glium::index::PrimitiveType::TriangleStrip),
&shaders::SPRITESHEET_PROGRAM,
&uniform,
&draw_params,
)
.expect("Failed to draw tiles");
}
}
|
use log::*;
use serde_json::Value;
use tantivy::tokenizer::{BoxTokenFilter, TextAnalyzer, TokenizerManager};
use crate::tokenizer::alpha_num_only_filter_factory::AlphaNumOnlyFilterFactory;
use crate::tokenizer::ascii_folding_filter_factory::AsciiFoldingFilterFactory;
use crate::tokenizer::cang_jie_tokenizer_factory::CangJieTokenizerFactory;
use crate::tokenizer::facet_tokenizer_factory::FacetTokenizerFactory;
use crate::tokenizer::lindera_tokenizer_factory::LinderaTokenizerFactory;
use crate::tokenizer::lower_case_filter_factory::LowerCaseFilterFactory;
use crate::tokenizer::ngram_tokenizer_factory::NgramTokenizerFactory;
use crate::tokenizer::raw_tokenizer_factory::RawTokenizerFactory;
use crate::tokenizer::remove_long_filter_factory::RemoveLongFilterFactory;
use crate::tokenizer::simple_tokenizer_factory::SimpleTokenizerFactory;
use crate::tokenizer::stemming_filter_factory::StemmingFilterFactory;
use crate::tokenizer::stop_word_filter_factory::StopWordFilterFactory;
pub struct TokenizerInitializer {
facet_tokenizer_factory: FacetTokenizerFactory,
ngram_tokenizer_factory: NgramTokenizerFactory,
raw_tokenizer_factory: RawTokenizerFactory,
simple_tokenizer_factory: SimpleTokenizerFactory,
cang_jie_tokenizer_factory: CangJieTokenizerFactory,
lindera_tokenizer_factory: LinderaTokenizerFactory,
alpha_num_only_filter_factory: AlphaNumOnlyFilterFactory,
ascii_folding_filter_factory: AsciiFoldingFilterFactory,
lower_case_filter_factory: LowerCaseFilterFactory,
remove_long_filter_factory: RemoveLongFilterFactory,
stemming_filter_factory: StemmingFilterFactory,
stop_word_filter_factory: StopWordFilterFactory,
}
impl TokenizerInitializer {
pub fn new() -> Self {
TokenizerInitializer {
facet_tokenizer_factory: FacetTokenizerFactory::new(),
ngram_tokenizer_factory: NgramTokenizerFactory::new(),
raw_tokenizer_factory: RawTokenizerFactory::new(),
simple_tokenizer_factory: SimpleTokenizerFactory::new(),
cang_jie_tokenizer_factory: CangJieTokenizerFactory::new(),
lindera_tokenizer_factory: LinderaTokenizerFactory::new(),
alpha_num_only_filter_factory: AlphaNumOnlyFilterFactory::new(),
ascii_folding_filter_factory: AsciiFoldingFilterFactory::new(),
lower_case_filter_factory: LowerCaseFilterFactory::new(),
remove_long_filter_factory: RemoveLongFilterFactory::new(),
stemming_filter_factory: StemmingFilterFactory::new(),
stop_word_filter_factory: StopWordFilterFactory::new(),
}
}
pub fn configure(&mut self, manager: &TokenizerManager, config: &str) {
let config_value: Value = serde_json::from_str(config).unwrap();
let config_map = config_value.as_object().unwrap();
for (name, tokenizer_config_value) in config_map {
debug!("name: {}", name);
let tokenizer_config_map = tokenizer_config_value.as_object().unwrap();
// tokenizer
let tokenizer_settings = tokenizer_config_map["tokenizer"].as_object().unwrap();
debug!("tokenizer_setting: {:?}", tokenizer_settings);
let tokenizer_name = tokenizer_settings["name"].as_str().unwrap();
debug!("tokenizer_name: {:?}", tokenizer_name);
let mut tokenizer_args = String::new();
if tokenizer_settings.contains_key("args") {
tokenizer_args = serde_json::to_string(&tokenizer_settings["args"]).unwrap();
}
debug!("tokenizer_args: {:?}", tokenizer_args);
// create tokenizer
let mut tokenizer;
match tokenizer_name {
"facet" => {
tokenizer = TextAnalyzer::from(self.facet_tokenizer_factory.clone().create());
}
"ngram" => {
tokenizer = TextAnalyzer::from(
self.ngram_tokenizer_factory
.clone()
.create(tokenizer_args.as_ref()),
);
}
"raw" => {
tokenizer = TextAnalyzer::from(self.raw_tokenizer_factory.clone().create());
}
"simple" => {
tokenizer = TextAnalyzer::from(self.simple_tokenizer_factory.clone().create());
}
"cang_jie" => {
tokenizer = TextAnalyzer::from(
self.cang_jie_tokenizer_factory
.clone()
.create(tokenizer_args.as_ref()),
);
}
"lindera" => {
tokenizer = TextAnalyzer::from(
self.lindera_tokenizer_factory
.clone()
.create(tokenizer_args.as_ref()),
);
}
_ => {
panic!("unknown tokenizer: {}", tokenizer_name);
}
}
// filters
if tokenizer_config_map.contains_key("filters") {
let filters_config_value = tokenizer_config_map["filters"].as_array().unwrap();
for filter_config_value in filters_config_value {
let filter_settings = filter_config_value.as_object().unwrap();
debug!("filter_settings: {:?}", filter_settings);
let filter_name = filter_settings["name"].as_str().unwrap();
debug!("filter_name: {:?}", filter_name);
let mut filter_args = String::new();
if filter_settings.contains_key("args") {
filter_args = serde_json::to_string(&filter_settings["args"]).unwrap();
}
debug!("filter_args: {:?}", filter_args);
// create filter
match filter_name {
"alpha_num_only" => {
tokenizer = tokenizer.filter(BoxTokenFilter::from(
self.alpha_num_only_filter_factory.clone().create(),
));
}
"ascii_folding" => {
tokenizer = tokenizer.filter(BoxTokenFilter::from(
self.ascii_folding_filter_factory.clone().create(),
));
}
"lower_case" => {
tokenizer = tokenizer.filter(BoxTokenFilter::from(
self.lower_case_filter_factory.clone().create(),
));
}
"remove_long" => {
tokenizer = tokenizer.filter(BoxTokenFilter::from(
self.remove_long_filter_factory
.clone()
.create(filter_args.as_ref()),
));
}
"stemming" => {
tokenizer = tokenizer.filter(BoxTokenFilter::from(
self.stemming_filter_factory
.clone()
.create(filter_args.as_ref()),
));
}
"stop_word" => {
tokenizer = tokenizer.filter(BoxTokenFilter::from(
self.stop_word_filter_factory
.clone()
.create(filter_args.as_ref()),
));
}
_ => {
panic!("unknown filter: {}", filter_name);
}
}
}
}
manager.register(name, tokenizer)
}
debug!("tokenizers are initialized");
}
}
#[cfg(test)]
mod tests {
use tantivy::tokenizer::TokenizerManager;
use crate::tokenizer::tokenizer_initializer::TokenizerInitializer;
#[test]
fn test_tokenizer() {
let config = r#"
{
"lang_en": {
"tokenizer": {
"name": "simple"
},
"filters": [
{
"name": "remove_long",
"args": {
"length_li mit": 50
}
},
{
"name": "lower_case"
},
{
"name": "stemming",
"args": {
"stemmer_algorithm": "english"
}
},
{
"name": "stop_word",
"args": {
"words": [
"a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into",
"is", "it", "no", "not", "of", "on", "or", "such", "that", "the", "their", "then",
"there", "these", "they", "this", "to", "was", "will", "with"
]
}
}
]
}
}
"#;
let manager = TokenizerManager::default();
let mut initializer = TokenizerInitializer::new();
initializer.configure(&manager, config);
let tokenizer = manager.get("lang_en").unwrap();
let mut stream = tokenizer.token_stream("I am saying HELLO WORLD!");
{
let token = stream.next().unwrap();
assert_eq!(token.text, "i");
assert_eq!(token.offset_from, 0);
assert_eq!(token.offset_to, 1);
}
{
let token = stream.next().unwrap();
assert_eq!(token.text, "am");
assert_eq!(token.offset_from, 2);
assert_eq!(token.offset_to, 4);
}
{
let token = stream.next().unwrap();
assert_eq!(token.text, "say");
assert_eq!(token.offset_from, 5);
assert_eq!(token.offset_to, 11);
}
{
let token = stream.next().unwrap();
assert_eq!(token.text, "hello");
assert_eq!(token.offset_from, 12);
assert_eq!(token.offset_to, 17);
}
{
let token = stream.next().unwrap();
assert_eq!(token.text, "world");
assert_eq!(token.offset_from, 18);
assert_eq!(token.offset_to, 23);
}
assert!(stream.next().is_none());
}
}
|
use super::{NodeID, NodeIDMask, TreeID};
use crate::dev::*;
use bitvec::{order::Msb0, slice::AsBits};
use derive_more::{AsRef, From};
use std::{
convert::{AsRef, TryFrom, TryInto},
io::{Cursor, Write},
net::Ipv6Addr,
str::FromStr,
};
///
pub const ADDRESS_NETMASK: u16 = 200;
///
pub const ADDRESS_PREFIX: u8 = 0x02;
///
pub const SUBNET_NETMASK: u16 = 300;
///
pub const SUBNET_PREFIX: u8 = 0x03;
///
#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq)]
pub enum NetworkID {
NodeID,
Curve25519,
// TODO Custom(String),
}
impl Default for NetworkID {
#[inline]
fn default() -> Self {
Self::NodeID
}
}
impl PartialEq<str> for NetworkID {
fn eq(&self, other: &str) -> bool {
match self {
Self::NodeID => other == "nodeid",
Self::Curve25519 => other == "curve25519",
// Self::Custom(s) => s == other,
}
}
}
// /// The current address prefix used by yggdrasil.
// pub const ADDRESS_PREFIX: [u8; 1] = [0x02];
///
#[derive(AsRef, Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[as_ref(forward)]
#[serde(try_from = "Ipv6Addr")]
pub struct Address(Ipv6Addr);
impl Address {
const BYTE_LENGTH: usize = 16;
pub fn to_bytes(&self) -> [u8; Self::BYTE_LENGTH] {
self.0.octets()
}
/// Returns two [`NodeID`]s.
/// The first [`NodeID`] with all the bits known from the `Address` set to
/// their correct values.
/// The second `NodeID` is a bitmask with 1 bit set for each bit that was
/// known from the `Address`.
/// This is used to look up `NodeID`s in the DHT and determine if they match
/// an `Address`.
///
/// [`NodeID`]: ../crypto/struct.NodeID.html
pub fn node_id_and_mask(&self) -> (NodeID, NodeIDMask) {
unimplemented!()
}
}
impl Default for Address {
fn default() -> Self {
unimplemented!()
}
}
/// Begins with `ADDRESS_PREFIX`, with the last bit set to 0, indicating an address.
/// The next 8 bits are set to the number of leading 1 bits in the [`NodeID`].
/// The remainder is the [`NodeID`], excluding the leading 1 bits and the first
/// leading 0 bit, truncated to the appropriate length.
///
/// [`NodeID`]: ../crypto/struct.NodeID.html
impl From<&NodeID> for Address {
fn from(node_id: &NodeID) -> Self {
let node_bytes: &[u8] = node_id.as_ref();
let prefix_len = node_id.prefix_len();
let mut addr = [0u8; Self::BYTE_LENGTH];
// write address prefix
*&mut addr[0] = ADDRESS_PREFIX;
// write number of leading ones as u8
*&mut addr[1] = prefix_len;
// write rest as NodeID with leading 1 bits and first leading 0 bit removed
// then truncated to maximum 128 bits
let node_id_rest = &node_bytes
.bits::<Msb0>()
.split_at(prefix_len as usize + 1)
.1
.as_slice()[0..(Self::BYTE_LENGTH - 2)];
(&mut addr[2..]).copy_from_slice(node_id_rest);
Self(addr.into())
}
}
impl TryFrom<Ipv6Addr> for Address {
type Error = Error;
fn try_from(raw: Ipv6Addr) -> Result<Self, Self::Error> {
if ADDRESS_NETMASK == raw.segments()[0] {
Ok(Self(raw))
} else {
Err(TypeError::OutOfBoundsAddress(raw))?
}
}
}
///
#[derive(AsRef, Copy, Clone, Debug, Eq, PartialEq)]
#[as_ref(forward)]
pub struct Subnet(Ipv6Addr);
impl Subnet {
const BYTE_LENGTH: usize = 8;
/// The first `NodeID` with all the bits known from the `Subnet` set to
/// their correct values.
/// The second `NodeID` is a bitmask with 1 bit set for each bit that was
/// known from the `Subnet`.
/// This is used to look up `NodeID`s in the DHT and determine if they match
/// an `Subnet`.
pub fn node_id_and_mask(&self) -> (NodeID, NodeIDMask) {
unimplemented!()
}
}
/// Begins with `SUBNET_PREFIX`, with the last bit set to 1, indicating a subnet.
/// The rest of the bits are set to the same as an [`Address`], truncated to
/// the appropriate length.
///
/// [`Address`]: ./struct.Address.html
impl From<&NodeID> for Subnet {
fn from(node_id: &NodeID) -> Self {
let addr_bytes = Address::from(node_id).to_bytes();
let mut subnet = [0u8; Address::BYTE_LENGTH];
// set subnet prefix byte
*&mut subnet[0] = SUBNET_PREFIX;
// copy rest of bytes from addr
let rest_addr = &addr_bytes[1..Self::BYTE_LENGTH];
(&mut subnet[1..Self::BYTE_LENGTH]).copy_from_slice(&rest_addr);
Self(subnet.into())
}
}
impl TryFrom<Ipv6Addr> for Subnet {
type Error = Error;
fn try_from(raw: Ipv6Addr) -> Result<Self, Self::Error> {
if SUBNET_NETMASK == raw.segments()[0] {
Ok(Self(raw))
} else {
Err(TypeError::OutOfBoundsAddress(raw))?
}
}
}
|
use argonautica::{Error, Hasher,Verifier};
use std::error;
use std::fmt;
#[derive(Debug, Clone)]
pub struct ExistingUserError;
impl fmt::Display for ExistingUserError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "User already exists")
}
}
impl error::Error for ExistingUserError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
None
}
fn description(&self) -> &str {
"User already exists"
}
}
#[derive(Debug)]
pub enum HandlerErrors {
UserNotExistError,
HashingError,
ValidationError(ExistingUserError),
DatabaseError(mongodb::Error),
DecoderError(mongodb::DecoderError)
}
pub fn encrypt_password(password: &str) -> Result<String, Error> {
let mut hasher = Hasher::default();
hasher
.with_password(password)
.with_secret_key("Super secret")
.hash()
}
pub fn verify_password(hash: &str,password: &str) -> Result<bool,Error> {
let mut verifier = Verifier::default();
verifier.with_hash(hash).with_password(password).with_secret_key("Super secret").verify()
}
|
use serde::{Deserialize, Serialize};
use lazy_static::lazy_static;
lazy_static! {
pub static ref DEFAULT_LOCATION: String = {
let mut home_dir =
std::path::PathBuf::from(std::env::var("HOME").unwrap_or(String::from("")));
home_dir.push(".mvg.conf");
String::from(home_dir.to_str().unwrap())
};
}
pub fn load_config(location: &str) -> Config {
match std::fs::File::open(location) {
Ok(file) => match serde_yaml::from_reader(file) {
Ok(conf) => return conf,
Err(e) => println!("Failed to parse config file!\n{}", e),
},
Err(e) => println!("Failed to open config file!\n{}", e),
}
if let Ok(file) = std::fs::File::open(location) {
if let Ok(conf) = serde_yaml::from_reader(file) {
return conf;
}
}
Config::default()
}
#[derive(Serialize, Deserialize, Default, Debug)]
pub struct Config {
#[serde(default)]
pub color_option: ColorOption,
#[serde(default)]
pub default_station: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub enum ColorOption {
TrueColor,
Ansi,
No,
}
impl Default for ColorOption {
fn default() -> Self {
let color_env_var = std::env::var("COLORTERM").unwrap_or(String::new());
if color_env_var.contains("truecolor") || color_env_var.contains("24bit") {
ColorOption::TrueColor
} else {
ColorOption::Ansi
}
}
}
|
use rocksdb::{DBOptions, Writable, DB};
use super::tempdir_with_prefix;
macro_rules! check_kv {
($db:expr, $key:expr, $val:expr) => {
assert_eq!($db.get($key).unwrap().unwrap(), $val);
};
($db:expr, $cf:expr, $key:expr, $val:expr) => {
assert_eq!($db.get_cf($cf, $key).unwrap().unwrap(), $val);
};
}
#[test]
fn test_open_for_read_only() {
let temp = tempdir_with_prefix("_rust_rocksdb_test_open_for_read_only");
let path = temp.path().to_str().unwrap();
let mut opts = DBOptions::new();
opts.create_if_missing(true);
let rw = DB::open_default(path).unwrap();
rw.put(b"k1", b"v1").unwrap();
rw.put(b"k2", b"v2").unwrap();
rw.put(b"k3", b"v3").unwrap();
check_kv!(rw, b"k1", b"v1");
check_kv!(rw, b"k2", b"v2");
check_kv!(rw, b"k3", b"v3");
let r1 = DB::open_for_read_only(opts.clone(), path, false).unwrap();
check_kv!(r1, b"k1", b"v1");
check_kv!(r1, b"k2", b"v2");
check_kv!(r1, b"k3", b"v3");
let r2 = DB::open_for_read_only(opts.clone(), path, false).unwrap();
check_kv!(r2, b"k1", b"v1");
check_kv!(r2, b"k2", b"v2");
check_kv!(r2, b"k3", b"v3");
let r3 = DB::open_for_read_only(opts.clone(), path, false).unwrap();
check_kv!(r3, b"k1", b"v1");
check_kv!(r3, b"k2", b"v2");
check_kv!(r3, b"k3", b"v3");
drop(rw);
drop(r1);
drop(r2);
drop(r3);
}
#[test]
fn test_open_cf_for_read_only() {
let temp = tempdir_with_prefix("_rust_rocksdb_test_open_cf_for_read_only");
let path = temp.path().to_str().unwrap();
{
let mut rw = DB::open_default(path).unwrap();
let _ = rw.create_cf("cf1").unwrap();
let _ = rw.create_cf("cf2").unwrap();
}
{
let rw = DB::open_cf(DBOptions::new(), path, vec!["cf1", "cf2"]).unwrap();
let cf1 = rw.cf_handle("cf1").unwrap();
rw.put_cf(cf1, b"cf1_k1", b"cf1_v1").unwrap();
rw.put_cf(cf1, b"cf1_k2", b"cf1_v2").unwrap();
rw.put_cf(cf1, b"cf1_k3", b"cf1_v3").unwrap();
check_kv!(rw, cf1, b"cf1_k1", b"cf1_v1");
check_kv!(rw, cf1, b"cf1_k2", b"cf1_v2");
check_kv!(rw, cf1, b"cf1_k3", b"cf1_v3");
let cf2 = rw.cf_handle("cf2").unwrap();
rw.put_cf(cf2, b"cf2_k1", b"cf2_v1").unwrap();
rw.put_cf(cf2, b"cf2_k2", b"cf2_v2").unwrap();
rw.put_cf(cf2, b"cf2_k3", b"cf2_v3").unwrap();
check_kv!(rw, cf2, b"cf2_k1", b"cf2_v1");
check_kv!(rw, cf2, b"cf2_k2", b"cf2_v2");
check_kv!(rw, cf2, b"cf2_k3", b"cf2_v3");
}
{
let r1 = DB::open_cf_for_read_only(DBOptions::new(), path, vec!["cf1"], false).unwrap();
let cf1 = r1.cf_handle("cf1").unwrap();
check_kv!(r1, cf1, b"cf1_k1", b"cf1_v1");
check_kv!(r1, cf1, b"cf1_k2", b"cf1_v2");
check_kv!(r1, cf1, b"cf1_k3", b"cf1_v3");
let r2 = DB::open_cf_for_read_only(DBOptions::new(), path, vec!["cf2"], false).unwrap();
let cf2 = r2.cf_handle("cf2").unwrap();
check_kv!(r2, cf2, b"cf2_k1", b"cf2_v1");
check_kv!(r2, cf2, b"cf2_k2", b"cf2_v2");
check_kv!(r2, cf2, b"cf2_k3", b"cf2_v3");
}
}
|
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct ListQueryOptions {
pub offset: Option<usize>,
pub limit: Option<usize>,
}
#[derive(Debug, Deserialize)]
pub struct DeleteQueryOptions {
pub soft: Option<bool>,
}
|
use anyhow::{anyhow, bail, Context, Result};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
#[derive(Eq, PartialEq, Clone, Debug)]
enum Component {
Constant(String),
Parameter(String),
}
#[derive(Eq, PartialEq, Clone, Debug)]
pub struct Template {
components: Vec<Component>,
}
impl Template {
pub fn compile(&self) -> TokenStream {
let mut fmt = String::new();
fmt.push_str("{}");
for c in self.components.iter() {
fmt.push('/');
match c {
Component::Constant(n) => fmt.push_str(n),
Component::Parameter(_) => fmt.push_str("{}"),
}
}
let components = self.components.iter().filter_map(|component| {
if let Component::Parameter(n) = &component {
let param = format_ident!("{}", n);
Some(quote! {
progenitor_support::encode_path(&#param.to_string())
})
} else {
None
}
});
quote! {
let url = format!(#fmt, self.baseurl, #(#components,)*);
}
}
pub fn names(&self) -> Vec<String> {
self.components
.iter()
.filter_map(|c| match c {
Component::Parameter(name) => Some(name.to_string()),
Component::Constant(_) => None,
})
.collect()
}
}
pub fn parse(t: &str) -> Result<Template> {
parse_inner(t)
.with_context(|| anyhow!("parse failure for template {:?}", t))
}
fn parse_inner(t: &str) -> Result<Template> {
enum State {
Start,
ConstantOrParameter,
Parameter,
ParameterSlash,
Constant,
}
let mut s = State::Start;
let mut a = String::new();
let mut components = Vec::new();
for c in t.chars() {
match s {
State::Start => {
if c == '/' {
s = State::ConstantOrParameter;
} else {
bail!("path must start with a slash");
}
}
State::ConstantOrParameter => {
if c == '/' || c == '}' {
bail!("expected a constant or parameter");
} else if c == '{' {
s = State::Parameter;
} else {
s = State::Constant;
a.push(c);
}
}
State::Constant => {
if c == '/' {
components.push(Component::Constant(a));
a = String::new();
s = State::ConstantOrParameter;
} else if c == '{' || c == '}' {
bail!("unexpected parameter");
} else {
a.push(c);
}
}
State::Parameter => {
if c == '}' {
components.push(Component::Parameter(a));
a = String::new();
s = State::ParameterSlash;
} else if c == '/' || c == '{' {
bail!("expected parameter");
} else {
a.push(c);
}
}
State::ParameterSlash => {
if c == '/' {
s = State::ConstantOrParameter;
} else {
bail!("expected a slash after parameter");
}
}
}
}
match s {
State::Start => bail!("empty path"),
State::ConstantOrParameter | State::ParameterSlash => (),
State::Constant => components.push(Component::Constant(a)),
State::Parameter => bail!("unterminated parameter"),
}
Ok(Template { components })
}
#[cfg(test)]
mod test {
use super::{parse, Component, Template};
use anyhow::{anyhow, Context, Result};
#[test]
fn basic() -> Result<()> {
let trials = vec![
(
"/info",
Template {
components: vec![Component::Constant("info".into())],
},
),
(
"/measure/{number}",
Template {
components: vec![
Component::Constant("measure".into()),
Component::Parameter("number".into()),
],
},
),
(
"/one/{two}/three",
Template {
components: vec![
Component::Constant("one".into()),
Component::Parameter("two".into()),
Component::Constant("three".into()),
],
},
),
];
for (path, want) in trials.iter() {
let t = parse(path).with_context(|| anyhow!("path {}", path))?;
assert_eq!(&t, want);
}
Ok(())
}
#[test]
fn names() -> Result<()> {
let trials = vec![
("/info", vec![]),
("/measure/{number}", vec!["number".to_string()]),
(
"/measure/{one}/{two}/and/{three}/yeah",
vec!["one".to_string(), "two".to_string(), "three".to_string()],
),
];
for (path, want) in trials.iter() {
let t = parse(path).with_context(|| anyhow!("path {}", path))?;
assert_eq!(&t.names(), want);
}
Ok(())
}
#[test]
fn compile() -> Result<()> {
let t = parse("/measure/{number}")?;
let out = t.compile();
let want = quote::quote! {
let url = format!("{}/measure/{}",
self.baseurl,
progenitor_support::encode_path(&number.to_string()),
);
};
assert_eq!(want.to_string(), out.to_string());
Ok(())
}
}
|
use crate::kernel::{
context::PackedPtr, stream::proof, Context, KResult, State, Stepper, Store_, Table, Table_,
Term, Theorem, Var_,
};
use crate::mmb_visitor::MmbVisitor;
use crate::statement_iter::StatementOwned;
use mmb_parser::Mmb;
use crate::kernel::stream::statement::Action;
use std::collections::HashMap;
#[derive(Default)]
struct Index {
data: HashMap<String, usize>,
names: Vec<String>,
}
impl mmb_parser::index::Visitor for Index {
fn visit<'a>(&mut self, idx: usize, _ptr: u64, name: &'a [u8]) {
let stripped = &name[..(name.len() - 1)];
let string = std::str::from_utf8(stripped).unwrap().to_string();
self.data.insert(string.clone(), idx);
self.names.push(string);
}
}
pub struct Verifier {
pub table: Table_,
pub context: Context<Store_>,
pub state: State,
theorem_index: Index,
stepper: Stepper<StatementOwned, Var_>,
}
impl Verifier {
pub fn new(data: &[u8]) -> Option<Verifier> {
let data = Mmb::from(data)?;
let mut visitor = MmbVisitor::new();
data.visit(&mut visitor).ok()?;
let mut index = Index::default();
data.visit_theorem_index(&mut index);
let (table, stream) = visitor.into_table_owned();
let stepper = Stepper::new(stream);
Some(Verifier {
table,
stepper,
context: Context::default(),
state: State::default(),
theorem_index: index,
})
}
pub fn get_theorem_index(&self, name: &str) -> Option<usize> {
self.theorem_index.data.get(name).cloned()
}
pub fn get_theorem_name(&self, idx: usize) -> Option<&str> {
self.theorem_index.names.get(idx).map(|x| x.as_str())
}
pub fn verify_unify(&self) -> KResult {
let mut i = 0;
let f = |x: u32| {
let term = self.table.get_term(x)?;
Some(term.get_binders().len() as u32)
};
while let Some(term) = self.table.get_term(i) {
let unify = term.get_command_stream();
let unify = self
.table
.get_unify_commands(unify)
.ok_or(crate::kernel::error::Kind::InvalidUnifyCommandIndex)?;
let proof =
trivial_compiler::unify_to_proof(term.get_binders().len() as u32, unify.iter(), f)
.map_err(|_| crate::kernel::error::Kind::InvalidTerm)?;
let binders = term.get_binders();
let binders = self
.table
.get_binders(binders)
.ok_or(crate::kernel::error::Kind::InvalidBinderIndices)?;
let mut dummy_context = Context::<Store_>::default();
dummy_context.allocate_binders(&self.table, self.state.get_current_sort(), binders)?;
let mut stepper = proof::Stepper::new(false, self.state, proof.iter().cloned());
stepper.run(&mut dummy_context, &self.table)?;
i += 1;
}
while let Some(thm) = self.table.get_theorem(i) {
let unify = thm.get_unify_commands();
let unify = self
.table
.get_unify_commands(unify)
.ok_or(crate::kernel::error::Kind::InvalidUnifyCommandIndex)?;
let proof =
trivial_compiler::unify_to_proof(thm.get_binders().len() as u32, unify.iter(), f)
.map_err(|_| crate::kernel::error::Kind::InvalidTerm)?;
let binders = thm.get_binders();
let binders = self
.table
.get_binders(binders)
.ok_or(crate::kernel::error::Kind::InvalidBinderIndices)?;
let mut dummy_context = Context::<Store_>::default();
dummy_context.allocate_binders(&self.table, self.state.get_current_sort(), binders)?;
let mut stepper = proof::Stepper::new(false, self.state, proof.iter().cloned());
stepper.run(&mut dummy_context, &self.table)?;
i += 1;
}
Ok(())
}
pub fn seek_term(&mut self, idx: usize) -> bool {
let stream = self.stepper.get_stream_mut();
if let Some(idx) = stream.term_indices.get(idx).copied() {
self.state = stream.seek_to(idx);
true
} else {
false
}
}
pub fn seek_theorem(&mut self, idx: usize) -> bool {
let stream = self.stepper.get_stream_mut();
if let Some(idx) = stream.theorem_indices.get(idx).copied() {
self.state = stream.seek_to(idx);
true
} else {
false
}
}
pub fn seek(&mut self, idx: usize) {
let stream = self.stepper.get_stream_mut();
self.state = stream.seek_to(idx);
}
pub fn create_theorem_application<'a>(
&self,
id: u32,
context: &'a mut Context<Store_>,
) -> KResult<(&'a [PackedPtr], &'a [PackedPtr], PackedPtr)> {
let f = |x: u32| {
let term = self.table.get_term(x)?;
Some(term.get_binders().len() as u32)
};
let thm = self
.table
.get_theorem(id)
.ok_or(crate::kernel::error::Kind::InvalidTheorem)?;
let unify = thm.get_unify_commands();
let unify = self
.table
.get_unify_commands(unify)
.ok_or(crate::kernel::error::Kind::InvalidUnifyCommandIndex)?;
let binders = thm.get_binders();
let nr_args = binders.len();
let binders = self
.table
.get_binders(binders)
.ok_or(crate::kernel::error::Kind::InvalidBinderIndices)?;
context.clear_except_store();
let state = State::from_table(&self.table);
context.allocate_binders(&self.table, state.get_current_sort(), binders)?;
let proof =
trivial_compiler::unify_to_proof(thm.get_binders().len() as u32, unify.iter(), f)
.map_err(|_| crate::kernel::error::Kind::InvalidTerm)?;
let mut stepper = proof::Stepper::new(false, state, proof.iter().cloned());
stepper.run(context, &self.table)?;
let args = context
.get_proof_heap()
.as_slice()
.get(..nr_args)
.ok_or(crate::kernel::error::Kind::InvalidHeapIndex)?;
let res = context
.get_proof_stack()
.peek()
.ok_or(crate::kernel::error::Kind::ProofStackUnderflow)?;
Ok((args, context.get_hyp_stack().as_slice(), *res))
}
pub fn step<F: FnMut(Action, &Self)>(&mut self, f: &mut F) -> KResult<Option<()>> {
let x = self
.stepper
.step(&mut self.context, &mut self.state, &self.table)?;
if let Some(x) = x {
f(x, self);
Ok(Some(()))
} else {
Ok(None)
}
}
pub fn run<F: FnMut(Action, &Self)>(&mut self, f: &mut F) -> KResult<()> {
while self.step(f)?.is_some() {}
Ok(())
}
pub fn step_statement<F: FnMut(Action, &Self)>(&mut self, f: &mut F) -> KResult<Option<()>> {
let x = self
.stepper
.step(&mut self.context, &mut self.state, &self.table)?;
if let Some(x) = x {
f(x, self);
if !self.stepper.is_state_normal() {
Ok(Some(()))
} else {
Ok(None)
}
} else {
Ok(None)
}
}
pub fn run_statement<F: FnMut(Action, &Self)>(&mut self, f: &mut F) -> KResult<()> {
while self.step_statement(f)?.is_some() {}
Ok(())
}
}
|
use crate::io::lcb::{AnalyticsCookie, QueryCookie};
use crate::io::request::*;
use crate::io::lcb::callbacks::{analytics_callback, query_callback};
use couchbase_sys::*;
use std::ffi::CString;
use std::os::raw::c_void;
use std::ptr;
/// Helper method to turn a string into a tuple of CString and its length.
#[inline]
fn into_cstring<T: Into<Vec<u8>>>(input: T) -> (usize, CString) {
let input = input.into();
(
input.len(),
CString::new(input).expect("Could not encode into CString"),
)
}
/// Encodes a `GetRequest` into its libcouchbase `lcb_CMDGET` representation.
///
/// Note that this method also handles get_and_lock and get_and_touch by looking
/// at the ty (type) enum of the get request. If one of them is used their inner
/// duration is passed down to libcouchbase either as a locktime or the expiry.
pub fn encode_get(instance: *mut lcb_INSTANCE, request: GetRequest) {
let (id_len, id) = into_cstring(request.id);
let cookie = Box::into_raw(Box::new(request.sender));
let mut command: *mut lcb_CMDGET = ptr::null_mut();
unsafe {
lcb_cmdget_create(&mut command);
lcb_cmdget_key(command, id.as_ptr(), id_len);
match request.ty {
GetRequestType::Get { options } => {
if let Some(timeout) = options.timeout {
lcb_cmdget_timeout(command, timeout.as_micros() as u32);
}
}
GetRequestType::GetAndLock { lock_time, options } => {
lcb_cmdget_locktime(command, lock_time.as_micros() as u32);
if let Some(timeout) = options.timeout {
lcb_cmdget_timeout(command, timeout.as_micros() as u32);
}
}
GetRequestType::GetAndTouch { expiry, options } => {
lcb_cmdget_expiry(command, expiry.as_micros() as u32);
if let Some(timeout) = options.timeout {
lcb_cmdget_timeout(command, timeout.as_micros() as u32);
}
}
};
lcb_get(instance, cookie as *mut c_void, command);
lcb_cmdget_destroy(command);
}
}
/// Encodes a `ExistsRequest` into its libcouchbase `lcb_CMDEXISTS` representation.
pub fn encode_exists(instance: *mut lcb_INSTANCE, request: ExistsRequest) {
let (id_len, id) = into_cstring(request.id);
let cookie = Box::into_raw(Box::new(request.sender));
let mut command: *mut lcb_CMDEXISTS = ptr::null_mut();
unsafe {
lcb_cmdexists_create(&mut command);
lcb_cmdexists_key(command, id.as_ptr(), id_len);
if let Some(timeout) = request.options.timeout {
lcb_cmdexists_timeout(command, timeout.as_micros() as u32);
}
lcb_exists(instance, cookie as *mut c_void, command);
lcb_cmdexists_destroy(command);
}
}
/// Encodes a `MutateRequest` into its libcouchbase `lcb_CMDSTORE` representation.
///
/// This method covers insert, upsert and replace since they are very similar and
/// only differ on certain properties.
pub fn encode_mutate(instance: *mut lcb_INSTANCE, request: MutateRequest) {
let (id_len, id) = into_cstring(request.id);
let (value_len, value) = into_cstring(request.content);
let cookie = Box::into_raw(Box::new(request.sender));
let mut command: *mut lcb_CMDSTORE = ptr::null_mut();
unsafe {
lcb_cmdstore_create(&mut command, lcb_STORE_OPERATION_LCB_STORE_UPSERT);
lcb_cmdstore_key(command, id.as_ptr(), id_len);
lcb_cmdstore_value(command, value.as_ptr(), value_len);
match request.ty {
MutateRequestType::Upsert { options } => {
if let Some(timeout) = options.timeout {
lcb_cmdstore_timeout(command, timeout.as_micros() as u32);
}
if let Some(expiry) = options.expiry {
lcb_cmdstore_expiry(command, expiry.as_secs() as u32);
}
}
MutateRequestType::Insert { options } => {
if let Some(timeout) = options.timeout {
lcb_cmdstore_timeout(command, timeout.as_micros() as u32);
}
if let Some(expiry) = options.expiry {
lcb_cmdstore_expiry(command, expiry.as_secs() as u32);
}
}
MutateRequestType::Replace { options } => {
if let Some(cas) = options.cas {
lcb_cmdstore_cas(command, cas);
}
if let Some(timeout) = options.timeout {
lcb_cmdstore_timeout(command, timeout.as_micros() as u32);
}
if let Some(expiry) = options.expiry {
lcb_cmdstore_expiry(command, expiry.as_secs() as u32);
}
}
}
lcb_store(instance, cookie as *mut c_void, command);
lcb_cmdstore_destroy(command);
}
}
/// Encodes a `RemoveRequest` into its libcouchbase `lcb_CMDREMOVE` representation.
pub fn encode_remove(instance: *mut lcb_INSTANCE, request: RemoveRequest) {
let (id_len, id) = into_cstring(request.id);
let cookie = Box::into_raw(Box::new(request.sender));
let mut command: *mut lcb_CMDREMOVE = ptr::null_mut();
unsafe {
lcb_cmdremove_create(&mut command);
lcb_cmdremove_key(command, id.as_ptr(), id_len);
if let Some(cas) = request.options.cas {
lcb_cmdremove_cas(command, cas);
}
if let Some(timeout) = request.options.timeout {
lcb_cmdremove_timeout(command, timeout.as_micros() as u32);
}
lcb_remove(instance, cookie as *mut c_void, command);
lcb_cmdremove_destroy(command);
}
}
/// Encodes a `QueryRequest` into its libcouchbase `lcb_CMDQUERY` representation.
pub fn encode_query(instance: *mut lcb_INSTANCE, mut request: QueryRequest) {
request.options.statement = Some(request.statement);
let (payload_len, payload) = into_cstring(serde_json::to_vec(&request.options).unwrap());
let (meta_sender, meta_receiver) = futures::channel::oneshot::channel();
let (rows_sender, rows_receiver) = futures::channel::mpsc::unbounded();
let cookie = Box::into_raw(Box::new(QueryCookie {
sender: Some(request.sender),
meta_sender,
meta_receiver: Some(meta_receiver),
rows_sender,
rows_receiver: Some(rows_receiver),
}));
let mut command: *mut lcb_CMDQUERY = ptr::null_mut();
unsafe {
lcb_cmdquery_create(&mut command);
lcb_cmdquery_payload(command, payload.as_ptr(), payload_len);
if let Some(a) = request.options.adhoc {
lcb_cmdquery_adhoc(command, a.into());
}
lcb_cmdquery_callback(command, Some(query_callback));
lcb_query(instance, cookie as *mut c_void, command);
lcb_cmdquery_destroy(command);
}
}
/// Encodes a `AnalyticsRequest` into its libcouchbase `lcb_CMDANALYTICS` representation.
pub fn encode_analytics(instance: *mut lcb_INSTANCE, mut request: AnalyticsRequest) {
request.options.statement = Some(request.statement);
let (payload_len, payload) = into_cstring(serde_json::to_vec(&request.options).unwrap());
let (meta_sender, meta_receiver) = futures::channel::oneshot::channel();
let (rows_sender, rows_receiver) = futures::channel::mpsc::unbounded();
let cookie = Box::into_raw(Box::new(AnalyticsCookie {
sender: Some(request.sender),
meta_sender,
meta_receiver: Some(meta_receiver),
rows_sender,
rows_receiver: Some(rows_receiver),
}));
let mut command: *mut lcb_CMDANALYTICS = ptr::null_mut();
unsafe {
lcb_cmdanalytics_create(&mut command);
lcb_cmdanalytics_payload(command, payload.as_ptr(), payload_len);
lcb_cmdanalytics_callback(command, Some(analytics_callback));
lcb_analytics(instance, cookie as *mut c_void, command);
lcb_cmdanalytics_destroy(command);
}
}
|
use super::util::SinkExt;
use crate::buffers::Acker;
use crate::event::{self, Event};
use futures::{future, Sink};
use serde::{Deserialize, Serialize};
use tokio::codec::{FramedWrite, LinesCodec};
use tokio::io;
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "lowercase")]
pub enum Target {
Stdout,
Stderr,
}
impl Default for Target {
fn default() -> Self {
Target::Stdout
}
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct ConsoleSinkConfig {
#[serde(default)]
pub target: Target,
pub encoding: Option<Encoding>,
}
#[derive(Deserialize, Serialize, Debug, Eq, PartialEq, Clone)]
#[serde(rename_all = "snake_case")]
pub enum Encoding {
Text,
Json,
}
#[typetag::serde(name = "console")]
impl crate::topology::config::SinkConfig for ConsoleSinkConfig {
fn build(&self, acker: Acker) -> Result<(super::RouterSink, super::Healthcheck), String> {
let encoding = self.encoding.clone();
let output: Box<dyn io::AsyncWrite + Send> = match self.target {
Target::Stdout => Box::new(io::stdout()),
Target::Stderr => Box::new(io::stderr()),
};
let sink = FramedWrite::new(output, LinesCodec::new())
.stream_ack(acker)
.sink_map_err(|_| ())
.with(move |event| encode_event(event, &encoding));
Ok((Box::new(sink), Box::new(future::ok(()))))
}
}
fn encode_event(event: Event, encoding: &Option<Encoding>) -> Result<String, ()> {
let log = event.into_log();
if (log.is_structured() && encoding != &Some(Encoding::Text))
|| encoding == &Some(Encoding::Json)
{
let bytes =
serde_json::to_vec(&log.all_fields()).map_err(|e| panic!("Error encoding: {}", e))?;
String::from_utf8(bytes).map_err(|e| panic!("Unable to convert json to utf8: {}", e))
} else {
let s = log
.get(&event::MESSAGE)
.map(|v| v.to_string_lossy())
.unwrap_or_else(|| "".into());
Ok(s)
}
}
|
pub mod days;
use days::*;
use std::time::Instant;
use criterion::black_box;
pub fn run(day: usize) {
match day {
1 => day1::run(),
2 => day2::run(),
3 => day3::run(),
4 => day4::run(),
5 => day5::run(),
6 => day6::run(),
7 => day7::run(),
8 => day8::run(),
9 => day9::run(),
10 => day10::run(),
11 => day11::run(),
12 => day12::run(),
13 => day13::run(),
14 => day14::run(),
15 => day15::run(),
16 => day16::run(),
17 => day17::run(),
18 => day18::run(),
19 => day19::run(),
20 => day20::run(),
21 => day21::run(),
22 => day22::run(),
23 => day23::run(),
24 => day24::run(),
25 => day25::run(),
_ => {
println!("Day not valid");
return
}
}
}
pub fn benchmark(day : usize, iter : usize) {
println!("Benchmarking day: {} with {} iterations", day, iter);
let mut tp : f64 = 0f64;
let t1 : f64;
let t2 : f64;
match day {
1 => {
let input = day1::default_input();
t1 = benchmark_function(input, &day1::part1::expense_rapport_str, iter);
t2 = benchmark_function(input, &day1::part2::expense_rapport_str, iter);
tp = benchmark_function(input, &day1::parse_input, iter)
}
2 => {
let input = day2::default_input();
t1 = benchmark_function(input, &day2::part1::password_validator_str, iter);
t2 = benchmark_function(input, &day2::part2::password_validator_str, iter);
tp = benchmark_function(input, &day2::parse_input, iter)
}
3 => {
let input = day3::default_input();
t1 = benchmark_function(input, &day3::part1::route_str, iter);
t2 = benchmark_function(input, &day3::part2::route_str, iter);
tp = benchmark_function(input, &day3::parse_input, iter)
}
4 => {
let input = day4::default_input();
t1 = benchmark_function(input, &day4::part1::password_system_str, iter);
t2 = benchmark_function(input, &day4::part2::password_system_str, iter);
tp = benchmark_function(input, &day4::parse_input, iter);
}
5 => {
let input = day5::default_input();
t1 = benchmark_function(input, &day5::part1::boarding_pass_str, iter);
t2 = benchmark_function(input, &day5::part2::boarding_pass_str, iter);
}
6 => {
let input = day6::default_input();
t1 = benchmark_function(input, &day6::part1::customs_groups_str, iter);
t2 = benchmark_function(input, &day6::part2::customs_groups_str, iter);
tp = benchmark_function(input, &day6::parse_input, iter);
}
7 => {
let input = day7::default_input();
t1 = benchmark_function(input, &day7::part1::color_bags_str, iter);
t2 = benchmark_function(input, &day7::part2::color_bags_str, iter);
tp = benchmark_function(input, &day7::parse_input, iter);
}
8 => {
let input = day8::default_input();
t1 = benchmark_function(input, &day8::part1::infinite_loop_str, iter);
t2 = benchmark_function(input, &day8::part2::infinite_loop_str, iter);
tp = benchmark_function(input, &day8::parse_input, iter);
}
9 => {
let input = day9::default_input();
t1 = benchmark_function(input, &day9::part1::xmas_str, iter);
t2 = benchmark_function(input, &day9::part2::xmas_str, iter);
tp = benchmark_function(input, &day9::parse_input, iter);
}
10 => {
let input = day10::default_input();
t1 = benchmark_function(input, &day10::part1::adapters_str, iter);
t2 = benchmark_function(input, &day10::part2::adapters_str, iter);
tp = benchmark_function(input, &day10::parse_input, iter);
}
11 => {
let input = day11::default_input();
t1 = benchmark_function(input, &day11::part1::seats_str, iter);
t2 = benchmark_function(input, &day11::part2::seats_str, iter);
tp = benchmark_function(input, &day11::parse_input, iter);
}
12 => {
let input = day12::default_input();
t1 = benchmark_function(input, &day12::part1::ship_str, iter);
t2 = benchmark_function(input, &day12::part2::ship_str, iter);
tp = benchmark_function(input, &day12::parse_input, iter);
}
13 => {
let input = day13::default_input();
t1 = benchmark_function(input, &day13::part1::busses_str, iter);
t2 = benchmark_function(input, &day13::part2::busses_str, iter);
}
14 => {
let input = day14::default_input();
t1 = benchmark_function(input, &day14::part1::mask_str, iter);
t2 = benchmark_function(input, &day14::part2::mask_str, iter);
tp = benchmark_function(input, &day14::parse_input, iter);
}
15 => {
let input = day15::default_input();
t1 = benchmark_function(input, |input | {day15::part1::memory_str(input, 2020)}, iter);
t2 = benchmark_function(input, |input | {day15::part1::memory_str(input, 30000000)}, iter);
tp = benchmark_function(input, &day15::parse_input, iter);
}
16 => {
let input = day16::default_input();
t1 = benchmark_function(input, &day16::part1::tickets_str, iter);
t2 = benchmark_function(input, &day16::part2::tickets_str, iter);
tp = benchmark_function(input, &day16::parse_input, iter);
}
17 => {
let input = day17::default_input();
t1 = benchmark_function(input, &day17::part1::pocket_str, iter);
t2 = benchmark_function(input, &day17::part2::pocket_str, iter);
tp = benchmark_function(input, &day17::parse_input3d, iter);
}
18 => {
let input = day18::default_input();
t1 = benchmark_function(input, &day18::part1::evaluate_str, iter);
t2 = benchmark_function(input, &day18::part2::evaluate_str, iter);
tp = benchmark_function(input, &day18::parse_input, iter);
}
19 => {
let input = day19::default_input();
t1 = benchmark_function(input, &day19::part1::message_str, iter);
t2 = benchmark_function(input, &day19::part2::message_str, iter);
tp = benchmark_function(input, &day19::parse_input, iter);
}
20 => {
let input = day20::default_input();
t1 = benchmark_function(input, &day20::part1::picture_str, iter);
t2 = benchmark_function(input, &day20::part2::picture_str, iter);
tp = benchmark_function(input, &day20::parse_input, iter);
}
21 => {
let input = day21::default_input();
t1 = benchmark_function(input, &day21::part1::food_str, iter);
t2 = benchmark_function(input, &day21::part2::food_str, iter);
tp = benchmark_function(input, &day21::parse_input, iter);
}
22 => {
let input = day22::default_input();
t1 = benchmark_function(input, &day22::part1::combat_str, iter);
t2 = benchmark_function(input, &day22::part2::combat_str, iter);
tp = benchmark_function(input, &day22::parse_input, iter);
}
23 => {
let input = day23::default_input();
t1 = benchmark_function(input, &day23::part1::circle_str, iter);
t2 = benchmark_function(input, &day23::part2::circle_str, iter);
tp = benchmark_function(input, &day23::parse_input, iter);
}
24 => {
let input = day24::default_input();
t1 = benchmark_function(input, &day24::part1::hex_str, iter);
t2 = benchmark_function(input, &day24::part2::hex_str, iter);
tp = benchmark_function(input, &day24::parse_input, iter);
}
25 => {
let input = day24::default_input();
t1 = benchmark_function(input, &day25::part1::room_str, iter);
t2 = 0f64;
tp = benchmark_function(input, &day25::parse_input, iter);
}
_ => {
println!("Day not valid");
return
}
}
println!("Parsing the input takes: {} ms", tp);
println!("Part 1 took: {} ms or without parsing: {} ms", t1, t1 - tp);
println!("Part 2 took: {} ms or without parsing: {} ms", t2, t2 - tp);
}
#[allow(unused_must_use)]
fn benchmark_function<'a, T, F: Fn(&'a str) -> T>(input : &'a str, f : F, iter : usize) -> f64 {
let mut scores = Vec::new();
for _ in 0..iter {
let start = Instant::now();
black_box(f(input));
scores.push(start.elapsed().as_micros() as f64 / i32::pow(10, 3) as f64);
}
scores.iter().sum::<f64>() / scores.len() as f64
}
pub fn criterion_bench_part1(day : usize, input : &str) {
match day {
1 => {
day1::part1::expense_rapport_str(input).unwrap();
}
2 => {
day2::part1::password_validator_str(input).unwrap();
}
3 => {
day3::part1::route_str(input).unwrap();
}
4 => {
day4::part1::password_system_str(input).unwrap();
}
5 => {
day5::part1::boarding_pass_str(input).unwrap();
}
6 => {
day6::part1::customs_groups_str(input).unwrap();
}
7 => {
day7::part1::color_bags_str(input).unwrap();
}
8 => {
day8::part1::infinite_loop_str(input).unwrap();
}
9 => {
day9::part1::xmas_str(input).unwrap();
}
10 => {
day10::part1::adapters_str(input).unwrap();
}
11 => {
day11::part1::seats_str(input).unwrap();
}
12 => {
day12::part1::ship_str(input).unwrap();
}
13 => {
day13::part1::busses_str(input).unwrap();
}
14 => {
day14::part1::mask_str(input).unwrap();
}
15 => {
day15::part1::memory_str(input, 2020).unwrap();
}
16 => {
day16::part1::tickets_str(input).unwrap();
}
17 => {
day17::part1::pocket_str(input).unwrap();
}
18 => {
day18::part1::evaluate_str(input).unwrap();
}
19 => {
day19::part1::message_str(input).unwrap();
}
20 => {
day20::part1::picture_str(input).unwrap();
}
21 => {
day21::part1::food_str(input).unwrap();
}
22 => {
day22::part1::combat_str(input).unwrap();
}
23 => {
day23::part1::circle_str(input).unwrap();
}
24 => {
day24::part1::hex_str(input).unwrap();
}
25 => {
day25::part1::room_str(input).unwrap();
}
_ => {
println!("Day not valid");
return
}
}
}
pub fn criterion_bench_part2(day : usize, input : &str) {
match day {
1 => {
day1::part2::expense_rapport_str(input).unwrap();
}
2 => {
day2::part2::password_validator_str(input).unwrap();
}
3 => {
day3::part2::route_str(input).unwrap();
}
4 => {
day4::part2::password_system_str(input).unwrap();
}
5 => {
day5::part2::boarding_pass_str(input).unwrap();
}
6 => {
day6::part2::customs_groups_str(input).unwrap();
}
7 => {
day7::part2::color_bags_str(input).unwrap();
}
8 => {
day8::part2::infinite_loop_str(input).unwrap();
}
9 => {
day9::part2::xmas_str(input).unwrap();
}
10 => {
day10::part2::adapters_str(input).unwrap();
}
11 => {
day11::part2::seats_str(input).unwrap();
}
12 => {
day12::part2::ship_str(input).unwrap();
}
13 => {
day13::part2::busses_str(input).unwrap();
}
14 => {
day14::part2::mask_str(input).unwrap();
}
15 => {
day15::part1::memory_str(input, 30000000).unwrap();
}
16 => {
day16::part2::tickets_str(input).unwrap();
}
17 => {
day17::part2::pocket_str(input).unwrap();
}
18 => {
day18::part2::evaluate_str(input).unwrap();
}
19 => {
day19::part2::message_str(input).unwrap();
}
20 => {
day20::part2::picture_str(input).unwrap();
}
21 => {
day21::part2::food_str(input).unwrap();
}
22 => {
day22::part2::combat_str(input).unwrap();
}
23 => {
day23::part2::circle_str(input).unwrap();
}
24 => {
day24::part2::hex_str(input).unwrap();
}
_ => {
println!("Day not valid");
return
}
}
} |
use crate::physics_system::PhysicsSystem;
use crate::types::EntityHandle;
use crate::force::Force;
use core::fmt::Debug;
use downcast_rs::{Downcast, impl_downcast};
/// A way to send forces into the system that are applied to each object separately (i.e. rather than applying them to pairs of colliding pairs or anything else).
/// This mainly intended to implement gravity, thought it could apply other things too (i.e. springs).
pub trait UnaryForceGenerator : Downcast + Debug {
/// The function to decide force based on the given Entity.
fn make_force(&mut self, dt : f32, physics : &PhysicsSystem, entity : EntityHandle) -> Force;
}
impl_downcast!(UnaryForceGenerator);
|
use slog::Logger;
use warp::Filter;
use crate::handlers::{
activate_protocol, bake_block_with_client, bake_block_with_client_arbitrary, get_wallets,
handle_rejection, init_client_data, start_node_with_config, stop_node,
};
use crate::node_runner::LightNodeRunnerRef;
use crate::tezos_client_runner::{
BakeRequest, SandboxWallets, TezosClientRunnerRef, TezosProtcolActivationParameters,
};
pub fn sandbox(
log: Logger,
runner: LightNodeRunnerRef,
client_runner: TezosClientRunnerRef,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
// Allow cors from any origin
let cors = warp::cors()
.allow_any_origin()
.allow_headers(vec!["content-type"])
.allow_methods(vec!["GET", "POST"]);
start(log.clone(), runner.clone())
.or(stop(log.clone(), runner, client_runner.clone()))
.or(init_client(log.clone(), client_runner.clone()))
.or(wallets(log.clone(), client_runner.clone()))
.or(activate(log.clone(), client_runner.clone()))
.or(bake(log.clone(), client_runner.clone()))
.or(bake_random(log, client_runner))
.recover(handle_rejection)
.with(cors)
}
pub fn start(
log: Logger,
runner: LightNodeRunnerRef,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
warp::path!("start")
.and(warp::post())
.and(json_body())
.and(with_log(log))
.and(with_runner(runner))
.and_then(start_node_with_config)
}
pub fn stop(
log: Logger,
runner: LightNodeRunnerRef,
client_runner: TezosClientRunnerRef,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
warp::path!("stop")
.and(warp::get())
.and(with_log(log))
.and(with_runner(runner))
.and(with_client_runner(client_runner))
.and_then(stop_node)
}
pub fn init_client(
log: Logger,
client_runner: TezosClientRunnerRef,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
warp::path!("init_client")
.and(warp::post())
.and(init_client_json_body())
.and(with_log(log))
.and(with_client_runner(client_runner))
.and_then(init_client_data)
}
pub fn wallets(
log: Logger,
client_runner: TezosClientRunnerRef,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
warp::path!("wallets")
.and(warp::get())
.and(with_log(log))
.and(with_client_runner(client_runner))
.and_then(get_wallets)
}
pub fn activate(
log: Logger,
client_runner: TezosClientRunnerRef,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
warp::path!("activate_protocol")
.and(warp::post())
.and(activation_json_body())
.and(with_log(log))
.and(with_client_runner(client_runner))
.and_then(activate_protocol)
}
pub fn bake(
log: Logger,
client_runner: TezosClientRunnerRef,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
warp::path!("bake")
.and(warp::post())
.and(bake_json_body())
.and(with_log(log))
.and(with_client_runner(client_runner))
.and_then(bake_block_with_client)
}
pub fn bake_random(
log: Logger,
client_runner: TezosClientRunnerRef,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
warp::path!("bake")
.and(warp::get())
.and(with_log(log))
.and(with_client_runner(client_runner))
.and_then(bake_block_with_client_arbitrary)
}
fn json_body() -> impl Filter<Extract = (serde_json::Value,), Error = warp::Rejection> + Clone {
// When accepting a body, we want a JSON body
// (and to reject huge payloads)...
warp::body::content_length_limit(1024 * 16).and(warp::body::json())
}
fn init_client_json_body(
) -> impl Filter<Extract = (SandboxWallets,), Error = warp::Rejection> + Clone {
// When accepting a body, we want a JSON body
// (and to reject huge payloads)...
warp::body::content_length_limit(1024 * 16).and(warp::body::json())
}
fn activation_json_body(
) -> impl Filter<Extract = (TezosProtcolActivationParameters,), Error = warp::Rejection> + Clone {
// When accepting a body, we want a JSON body and serialize it to TezosProtcolActivationParameters
// (and to reject huge payloads)...
warp::body::content_length_limit(1024 * 16).and(warp::body::json())
}
fn bake_json_body() -> impl Filter<Extract = (BakeRequest,), Error = warp::Rejection> + Clone {
// When accepting a body, we want a JSON body with the deserialized BakeRequest
// (and to reject huge payloads)...
warp::body::content_length_limit(1024 * 16).and(warp::body::json())
}
fn with_log(
log: Logger,
) -> impl Filter<Extract = (Logger,), Error = std::convert::Infallible> + Clone {
warp::any().map(move || log.clone())
}
fn with_runner(
runner: LightNodeRunnerRef,
) -> impl Filter<Extract = (LightNodeRunnerRef,), Error = std::convert::Infallible> + Clone {
warp::any().map(move || runner.clone())
}
fn with_client_runner(
client_runner: TezosClientRunnerRef,
) -> impl Filter<Extract = (TezosClientRunnerRef,), Error = std::convert::Infallible> + Clone {
warp::any().map(move || client_runner.clone())
}
|
extern crate websocket; // websocket = "~0.12.2"
use std::string::String;
use websocket::client::request::Url;
use websocket::{Client, Message, Sender, Receiver};
fn main() {
let url = Url::parse("wss://ws.binaryws.com/websockets/v3").unwrap();
let request = Client::connect(url).unwrap();
let response = request.send().unwrap();
let (mut sender, mut receiver) = response.begin().split();
let req = Message::Text(String::from("{\"ticks\": \"R_100\"}"));
sender.send_message(req).unwrap();
for message in receiver.incoming_messages::<Message>() {
match message {
Ok(Message::Text(m)) => { println!("tick update: {:?}", m) },
_ => { break },
};
}
}
|
use apllodb_sql_parser::ApllodbSqlParser;
use apllodb_test_support::setup::setup_test_logger;
use ctor::ctor;
#[ctor]
fn test_setup() {
setup_test_logger();
}
// https://rust-lang.github.io/api-guidelines/interoperability.html#data-structures-implement-serdes-serialize-deserialize-c-serde
#[cfg(feature = "serde")]
#[test]
fn test_api_guidelines_c_serde() {
use apllodb_sql_parser::ApllodbAst;
use serde::{Deserialize, Serialize};
fn assert_serialize<T: Serialize>() {}
assert_serialize::<ApllodbAst>();
fn assert_deserialize<'a, T: Deserialize<'a>>() {}
assert_deserialize::<ApllodbAst>();
}
// https://rust-lang.github.io/api-guidelines/interoperability.html#types-are-send-and-sync-where-possible-c-send-sync
#[test]
fn test_api_guidelines_c_send_sync() {
use apllodb_sql_parser::ApllodbAst;
fn assert_send<T: Send>() {}
assert_send::<ApllodbAst>();
fn assert_sync<T: Sync>() {}
assert_sync::<ApllodbAst>();
}
#[test]
fn test_case_insensitivity() {
let sqls = vec!["SELECT id FROM t", "select id from t"];
for sql in sqls {
let parser = ApllodbSqlParser::default();
parser.parse(sql).expect("should be parsed correctly");
}
}
|
/*!
```rudra-poc
[target]
crate = "crayon"
version = "0.7.1"
[report]
issue_url = "https://github.com/shawnscode/crayon/issues/87"
issue_date = 2020-08-31
rustsec_url = "https://github.com/RustSec/advisory-db/pull/371"
rustsec_id = "RUSTSEC-2020-0037"
[[bugs]]
analyzer = "Manual"
guide = "UnsafeDestructor"
bug_class = "HigherOrderInvariant"
rudra_report_locations = []
```
!*/
#![forbid(unsafe_code)]
use crayon::utils::handle::{HandleIndex, HandleLike};
use crayon::utils::object_pool::ObjectPool;
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Debug)]
struct DropDetector(u32);
impl Drop for DropDetector {
fn drop(&mut self) {
println!("Dropping {}", self.0);
}
}
static FLAG: AtomicBool = AtomicBool::new(false);
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
struct MyHandle {
indices: [HandleIndex; 2],
version: HandleIndex,
}
impl HandleLike for MyHandle {
fn new(index: HandleIndex, version: HandleIndex) -> Self {
MyHandle {
indices: [index, index],
version,
}
}
fn index(&self) -> HandleIndex {
if dbg!(FLAG.fetch_xor(true, Ordering::Relaxed)) {
self.indices[1]
} else {
self.indices[0]
}
}
fn version(&self) -> HandleIndex {
self.version
}
}
impl MyHandle {
fn with_indices(indices: [HandleIndex; 2], version: HandleIndex) -> Self {
MyHandle { indices, version }
}
}
fn main() {
let mut pool = ObjectPool::new();
let real_handle: MyHandle = pool.create(123);
let fake_handle =
MyHandle::with_indices([real_handle.index(), 12345678], real_handle.version());
// Segfault with OOB, accessing`pool.entries[12345678]` without boundary checking
dbg!(pool.get(fake_handle));
// The bug can be similarly triggered in all other methods of `ObjectPool`
// that call `handle.index()` in an unsafe block.
}
|
pub use self::{
below_zero::BelowZero, block_bounced_transform::BouncedBlock, bounce::Bounce,
paddle::PaddleSystem,
};
mod below_zero;
mod block_bounced_transform;
mod bounce;
mod paddle;
|
// 17.12 BiNode
// As doubly-linked lists are a nightmare in Rust, I often implement them with
// shared owned storage in a Vec<Node>, and use `usize` as pointers.
struct Node {
val: i32,
node1: Option<usize>,
node2: Option<usize>,
}
trait Tree {
fn instance(&self, storage: &mut Vec<Node>) -> usize;
}
impl Tree for i32 {
fn instance(&self, storage: &mut Vec<Node>) -> usize {
let index = storage.len();
storage.push(Node {
val: *self,
node1: None,
node2: None,
});
index
}
}
impl<L, R> Tree for (i32, L, R)
where
L: Tree,
R: Tree,
{
fn instance(&self, storage: &mut Vec<Node>) -> usize {
let index = storage.len();
storage.push(Node {
val: self.0,
node1: None,
node2: None,
});
let l_index = self.1.instance(storage);
let r_index = self.2.instance(storage);
storage[index].node1 = Some(l_index);
storage[index].node2 = Some(r_index);
index
}
}
struct LLIterator {
storage: Vec<Node>,
current: Option<usize>,
}
impl Iterator for LLIterator {
type Item = i32;
fn next(&mut self) -> Option<Self::Item> {
match self.current {
None => None,
Some(index) => {
let rv = &self.storage[index];
self.current = rv.node2;
Some(rv.val)
}
}
}
}
fn bin_tree_to_linked_list<T: Tree>(tree: T) -> LLIterator {
let mut storage = Vec::new();
let root = tree.instance(&mut storage);
fn is_leaf(node: &Node) -> bool {
node.node1.is_none() && node.node2.is_none()
}
// Transforms branch into linked list
// Takes node's index in storage container
// Returns indices of first and last node
fn recurse(root: usize, storage: &mut Vec<Node>) -> (usize, usize) {
let l = match storage[root].node1 {
None => (root, root),
Some(node1) => {
if is_leaf(&storage[node1]) {
(node1, node1)
} else {
recurse(node1, storage)
}
}
};
let r = match storage[root].node2 {
None => (root, root),
Some(node2) => {
if is_leaf(&storage[node2]) {
(node2, node2)
} else {
recurse(node2, storage)
}
}
};
if l.1 != root {
storage[l.1 as usize].node2 = Some(root);
storage[root as usize].node1 = Some(l.1);
}
if r.0 != root {
storage[r.0 as usize].node1 = Some(root);
storage[root as usize].node2 = Some(r.0);
}
(l.0, r.1)
}
let x = recurse(root, &mut storage);
LLIterator {
storage,
current: Some(x.0),
}
}
#[test]
fn test() {
/* 4
* ↙ ↘
* 2 6 => 1⇋2⇋3⇋4⇋5⇋6⇋7
* ↙↓ ↓↘
* 1 3 5 7
*
*/
assert!(
bin_tree_to_linked_list((4, (2, 1, 3), (6, 5, 7))).collect::<Vec<_>>()
== [1, 2, 3, 4, 5, 6, 7]
)
}
|
use self::rcb::RCBLL;
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Radio Control Bus (RCB) controller"]
pub rcb: RCB,
_reserved1: [u8; 3768usize],
#[doc = "0x1000 - Bluetooth Low Energy Link Layer"]
pub blell: BLELL,
_reserved2: [u8; 38140usize],
#[doc = "0x1f000 - Bluetooth Low Energy Subsystem Miscellaneous"]
pub bless: BLESS,
}
#[doc = r"Register block"]
#[repr(C)]
pub struct RCB {
#[doc = "0x00 - RCB control register."]
pub ctrl: self::rcb::CTRL,
#[doc = "0x04 - RCB status register."]
pub status: self::rcb::STATUS,
_reserved2: [u8; 8usize],
#[doc = "0x10 - Transmitter control register."]
pub tx_ctrl: self::rcb::TX_CTRL,
#[doc = "0x14 - Transmitter FIFO control register."]
pub tx_fifo_ctrl: self::rcb::TX_FIFO_CTRL,
#[doc = "0x18 - Transmitter FIFO status register."]
pub tx_fifo_status: self::rcb::TX_FIFO_STATUS,
#[doc = "0x1c - Transmitter FIFO write register."]
pub tx_fifo_wr: self::rcb::TX_FIFO_WR,
#[doc = "0x20 - Receiver control register."]
pub rx_ctrl: self::rcb::RX_CTRL,
#[doc = "0x24 - Receiver FIFO control register."]
pub rx_fifo_ctrl: self::rcb::RX_FIFO_CTRL,
#[doc = "0x28 - Receiver FIFO status register."]
pub rx_fifo_status: self::rcb::RX_FIFO_STATUS,
#[doc = "0x2c - Receiver FIFO read register."]
pub rx_fifo_rd: self::rcb::RX_FIFO_RD,
#[doc = "0x30 - Receiver FIFO read register."]
pub rx_fifo_rd_silent: self::rcb::RX_FIFO_RD_SILENT,
_reserved11: [u8; 12usize],
#[doc = "0x40 - Master interrupt request register."]
pub intr: self::rcb::INTR,
#[doc = "0x44 - Master interrupt set request register"]
pub intr_set: self::rcb::INTR_SET,
#[doc = "0x48 - Master interrupt mask register."]
pub intr_mask: self::rcb::INTR_MASK,
#[doc = "0x4c - Master interrupt masked request register"]
pub intr_masked: self::rcb::INTR_MASKED,
_reserved15: [u8; 176usize],
#[doc = "0x100 - Radio Control Bus (RCB) & Link Layer controller"]
pub rcbll: RCBLL,
}
#[doc = r"Register block"]
#[doc = "Radio Control Bus (RCB) controller"]
pub mod rcb;
#[doc = r"Register block"]
#[repr(C)]
pub struct BLELL {
#[doc = "0x00 - Instruction Register"]
pub command_register: self::blell::COMMAND_REGISTER,
_reserved1: [u8; 4usize],
#[doc = "0x08 - Event(Interrupt) status and Clear register"]
pub event_intr: self::blell::EVENT_INTR,
_reserved2: [u8; 4usize],
#[doc = "0x10 - Event indications enable."]
pub event_enable: self::blell::EVENT_ENABLE,
_reserved3: [u8; 4usize],
#[doc = "0x18 - Advertising parameters register."]
pub adv_params: self::blell::ADV_PARAMS,
#[doc = "0x1c - Advertising interval register."]
pub adv_interval_timeout: self::blell::ADV_INTERVAL_TIMEOUT,
#[doc = "0x20 - Advertising interrupt status and Clear register"]
pub adv_intr: self::blell::ADV_INTR,
#[doc = "0x24 - Advertising next instant."]
pub adv_next_instant: self::blell::ADV_NEXT_INSTANT,
#[doc = "0x28 - Scan Interval Register"]
pub scan_interval: self::blell::SCAN_INTERVAL,
#[doc = "0x2c - Scan window Register"]
pub scan_window: self::blell::SCAN_WINDOW,
#[doc = "0x30 - Scanning parameters register"]
pub scan_param: self::blell::SCAN_PARAM,
_reserved10: [u8; 4usize],
#[doc = "0x38 - Scan interrupt status and Clear register"]
pub scan_intr: self::blell::SCAN_INTR,
#[doc = "0x3c - Advertising next instant."]
pub scan_next_instant: self::blell::SCAN_NEXT_INSTANT,
#[doc = "0x40 - Initiator Interval Register"]
pub init_interval: self::blell::INIT_INTERVAL,
#[doc = "0x44 - Initiator window Register"]
pub init_window: self::blell::INIT_WINDOW,
#[doc = "0x48 - Initiator parameters register"]
pub init_param: self::blell::INIT_PARAM,
_reserved15: [u8; 4usize],
#[doc = "0x50 - Scan interrupt status and Clear register"]
pub init_intr: self::blell::INIT_INTR,
#[doc = "0x54 - Initiator next instant."]
pub init_next_instant: self::blell::INIT_NEXT_INSTANT,
#[doc = "0x58 - Lower 16 bit random address of the device."]
pub device_rand_addr_l: self::blell::DEVICE_RAND_ADDR_L,
#[doc = "0x5c - Middle 16 bit random address of the device."]
pub device_rand_addr_m: self::blell::DEVICE_RAND_ADDR_M,
#[doc = "0x60 - Higher 16 bit random address of the device."]
pub device_rand_addr_h: self::blell::DEVICE_RAND_ADDR_H,
_reserved20: [u8; 4usize],
#[doc = "0x68 - Lower 16 bit address of the peer device."]
pub peer_addr_l: self::blell::PEER_ADDR_L,
#[doc = "0x6c - Middle 16 bit address of the peer device."]
pub peer_addr_m: self::blell::PEER_ADDR_M,
#[doc = "0x70 - Higher 16 bit address of the peer device."]
pub peer_addr_h: self::blell::PEER_ADDR_H,
_reserved23: [u8; 4usize],
#[doc = "0x78 - whitelist address type"]
pub wl_addr_type: self::blell::WL_ADDR_TYPE,
#[doc = "0x7c - whitelist valid entry bit"]
pub wl_enable: self::blell::WL_ENABLE,
#[doc = "0x80 - Transmit window offset"]
pub transmit_window_offset: self::blell::TRANSMIT_WINDOW_OFFSET,
#[doc = "0x84 - Transmit window size"]
pub transmit_window_size: self::blell::TRANSMIT_WINDOW_SIZE,
#[doc = "0x88 - Data channel map 0 (lower word)"]
pub data_channels_l0: self::blell::DATA_CHANNELS_L0,
#[doc = "0x8c - Data channel map 0 (middle word)"]
pub data_channels_m0: self::blell::DATA_CHANNELS_M0,
#[doc = "0x90 - Data channel map 0 (upper word)"]
pub data_channels_h0: self::blell::DATA_CHANNELS_H0,
_reserved30: [u8; 4usize],
#[doc = "0x98 - Data channel map 1 (lower word)"]
pub data_channels_l1: self::blell::DATA_CHANNELS_L1,
#[doc = "0x9c - Data channel map 1 (middle word)"]
pub data_channels_m1: self::blell::DATA_CHANNELS_M1,
#[doc = "0xa0 - Data channel map 1 (upper word)"]
pub data_channels_h1: self::blell::DATA_CHANNELS_H1,
_reserved33: [u8; 4usize],
#[doc = "0xa8 - Connection interrupt status and Clear register"]
pub conn_intr: self::blell::CONN_INTR,
#[doc = "0xac - Connection channel status"]
pub conn_status: self::blell::CONN_STATUS,
#[doc = "0xb0 - Connection Index register"]
pub conn_index: self::blell::CONN_INDEX,
_reserved36: [u8; 4usize],
#[doc = "0xb8 - Wakeup configuration"]
pub wakeup_config: self::blell::WAKEUP_CONFIG,
_reserved37: [u8; 4usize],
#[doc = "0xc0 - Wakeup control"]
pub wakeup_control: self::blell::WAKEUP_CONTROL,
#[doc = "0xc4 - Clock control"]
pub clock_config: self::blell::CLOCK_CONFIG,
#[doc = "0xc8 - Reference Clock"]
pub tim_counter_l: self::blell::TIM_COUNTER_L,
#[doc = "0xcc - Wakeup configuration extended"]
pub wakeup_config_extd: self::blell::WAKEUP_CONFIG_EXTD,
_reserved41: [u8; 8usize],
#[doc = "0xd8 - BLE Time Control"]
pub poc_reg__tim_control: self::blell::POC_REG__TIM_CONTROL,
_reserved42: [u8; 4usize],
#[doc = "0xe0 - Advertising data transmit FIFO. Access ADVCH_TX_FIFO."]
pub adv_tx_data_fifo: self::blell::ADV_TX_DATA_FIFO,
_reserved43: [u8; 4usize],
#[doc = "0xe8 - Advertising scan response data transmit FIFO. Access ADVCH_TX_FIFO."]
pub adv_scn_rsp_tx_fifo: self::blell::ADV_SCN_RSP_TX_FIFO,
_reserved44: [u8; 12usize],
#[doc = "0xf8 - advertising scan response data receive data FIFO. Access ADVRX_FIFO."]
pub init_scn_adv_rx_fifo: self::blell::INIT_SCN_ADV_RX_FIFO,
_reserved45: [u8; 4usize],
#[doc = "0x100 - Connection Interval"]
pub conn_interval: self::blell::CONN_INTERVAL,
#[doc = "0x104 - Supervision timeout"]
pub sup_timeout: self::blell::SUP_TIMEOUT,
#[doc = "0x108 - Slave Latency"]
pub slave_latency: self::blell::SLAVE_LATENCY,
#[doc = "0x10c - Connection event length"]
pub ce_length: self::blell::CE_LENGTH,
#[doc = "0x110 - Access address (lower)"]
pub pdu_access_addr_l_register: self::blell::PDU_ACCESS_ADDR_L_REGISTER,
#[doc = "0x114 - Access address (upper)"]
pub pdu_access_addr_h_register: self::blell::PDU_ACCESS_ADDR_H_REGISTER,
#[doc = "0x118 - Connection event instant"]
pub conn_ce_instant: self::blell::CONN_CE_INSTANT,
#[doc = "0x11c - connection configuration & status register"]
pub ce_cnfg_sts_register: self::blell::CE_CNFG_STS_REGISTER,
#[doc = "0x120 - Next connection event instant"]
pub next_ce_instant: self::blell::NEXT_CE_INSTANT,
#[doc = "0x124 - connection event counter"]
pub conn_ce_counter: self::blell::CONN_CE_COUNTER,
#[doc = "0x128 - data list sent update and status"]
pub data_list_sent_update__status: self::blell::DATA_LIST_SENT_UPDATE__STATUS,
#[doc = "0x12c - data list ack update and status"]
pub data_list_ack_update__status: self::blell::DATA_LIST_ACK_UPDATE__STATUS,
#[doc = "0x130 - connection configuration & status register"]
pub ce_cnfg_sts_register_ext: self::blell::CE_CNFG_STS_REGISTER_EXT,
#[doc = "0x134 - Connection extended interrupt status and Clear register"]
pub conn_ext_intr: self::blell::CONN_EXT_INTR,
#[doc = "0x138 - Connection Extended Interrupt mask"]
pub conn_ext_intr_mask: self::blell::CONN_EXT_INTR_MASK,
_reserved60: [u8; 4usize],
#[doc = "0x140 - Data buffer descriptor 0 to 4"]
pub data_mem_descriptor: [self::blell::DATA_MEM_DESCRIPTOR; 5],
_reserved61: [u8; 12usize],
#[doc = "0x160 - Window widen for interval"]
pub window_widen_intvl: self::blell::WINDOW_WIDEN_INTVL,
#[doc = "0x164 - Window widen for offset"]
pub window_widen_winoff: self::blell::WINDOW_WIDEN_WINOFF,
_reserved63: [u8; 8usize],
#[doc = "0x170 - Direct Test Mode control"]
pub le_rf_test_mode: self::blell::LE_RF_TEST_MODE,
#[doc = "0x174 - Direct Test Mode receive packet count"]
pub dtm_rx_pkt_count: self::blell::DTM_RX_PKT_COUNT,
#[doc = "0x178 - Direct Test Mode control"]
pub le_rf_test_mode_ext: self::blell::LE_RF_TEST_MODE_EXT,
_reserved66: [u8; 12usize],
#[doc = "0x188 - Channel Address register"]
pub txrx_hop: self::blell::TXRX_HOP,
_reserved67: [u8; 4usize],
#[doc = "0x190 - Transmit/Receive data delay"]
pub tx_rx_on_delay: self::blell::TX_RX_ON_DELAY,
_reserved68: [u8; 20usize],
#[doc = "0x1a8 - ADV packet access code low word"]
pub adv_accaddr_l: self::blell::ADV_ACCADDR_L,
#[doc = "0x1ac - ADV packet access code high word"]
pub adv_accaddr_h: self::blell::ADV_ACCADDR_H,
#[doc = "0x1b0 - Advertising channel transmit power setting"]
pub adv_ch_tx_power_lvl_ls: self::blell::ADV_CH_TX_POWER_LVL_LS,
#[doc = "0x1b4 - Advertising channel transmit power setting extension"]
pub adv_ch_tx_power_lvl_ms: self::blell::ADV_CH_TX_POWER_LVL_MS,
#[doc = "0x1b8 - Connection channel transmit power setting"]
pub conn_ch_tx_power_lvl_ls: self::blell::CONN_CH_TX_POWER_LVL_LS,
#[doc = "0x1bc - Connection channel transmit power setting extension"]
pub conn_ch_tx_power_lvl_ms: self::blell::CONN_CH_TX_POWER_LVL_MS,
#[doc = "0x1c0 - Device public address lower register"]
pub dev_pub_addr_l: self::blell::DEV_PUB_ADDR_L,
#[doc = "0x1c4 - Device public address middle register"]
pub dev_pub_addr_m: self::blell::DEV_PUB_ADDR_M,
#[doc = "0x1c8 - Device public address higher register"]
pub dev_pub_addr_h: self::blell::DEV_PUB_ADDR_H,
_reserved77: [u8; 4usize],
#[doc = "0x1d0 - Offset to first instant"]
pub offset_to_first_instant: self::blell::OFFSET_TO_FIRST_INSTANT,
#[doc = "0x1d4 - Advertiser configuration register"]
pub adv_config: self::blell::ADV_CONFIG,
#[doc = "0x1d8 - Scan configuration register"]
pub scan_config: self::blell::SCAN_CONFIG,
#[doc = "0x1dc - Initiator configuration register"]
pub init_config: self::blell::INIT_CONFIG,
#[doc = "0x1e0 - Connection configuration register"]
pub conn_config: self::blell::CONN_CONFIG,
_reserved82: [u8; 4usize],
#[doc = "0x1e8 - Connection parameter 1"]
pub conn_param1: self::blell::CONN_PARAM1,
#[doc = "0x1ec - Connection parameter 2"]
pub conn_param2: self::blell::CONN_PARAM2,
#[doc = "0x1f0 - Connection Interrupt mask"]
pub conn_intr_mask: self::blell::CONN_INTR_MASK,
#[doc = "0x1f4 - slave timing control"]
pub slave_timing_control: self::blell::SLAVE_TIMING_CONTROL,
#[doc = "0x1f8 - Receive trigger control"]
pub receive_trig_ctrl: self::blell::RECEIVE_TRIG_CTRL,
_reserved87: [u8; 4usize],
#[doc = "0x200 - LL debug register 1"]
pub ll_dbg_1: self::blell::LL_DBG_1,
#[doc = "0x204 - LL debug register 2"]
pub ll_dbg_2: self::blell::LL_DBG_2,
#[doc = "0x208 - LL debug register 3"]
pub ll_dbg_3: self::blell::LL_DBG_3,
#[doc = "0x20c - LL debug register 4"]
pub ll_dbg_4: self::blell::LL_DBG_4,
#[doc = "0x210 - LL debug register 5"]
pub ll_dbg_5: self::blell::LL_DBG_5,
#[doc = "0x214 - LL debug register 6"]
pub ll_dbg_6: self::blell::LL_DBG_6,
#[doc = "0x218 - LL debug register 7"]
pub ll_dbg_7: self::blell::LL_DBG_7,
#[doc = "0x21c - LL debug register 8"]
pub ll_dbg_8: self::blell::LL_DBG_8,
#[doc = "0x220 - LL debug register 9"]
pub ll_dbg_9: self::blell::LL_DBG_9,
#[doc = "0x224 - LL debug register 10"]
pub ll_dbg_10: self::blell::LL_DBG_10,
_reserved97: [u8; 8usize],
#[doc = "0x230 - Lower 16 bit address of the peer device for INIT."]
pub peer_addr_init_l: self::blell::PEER_ADDR_INIT_L,
#[doc = "0x234 - Middle 16 bit address of the peer device for INIT."]
pub peer_addr_init_m: self::blell::PEER_ADDR_INIT_M,
#[doc = "0x238 - Higher 16 bit address of the peer device for INIT."]
pub peer_addr_init_h: self::blell::PEER_ADDR_INIT_H,
#[doc = "0x23c - Lower 16 bits of the secondary address of the peer device for ADV_DIR."]
pub peer_sec_addr_adv_l: self::blell::PEER_SEC_ADDR_ADV_L,
#[doc = "0x240 - Middle 16 bits of the secondary address of the peer device for ADV_DIR."]
pub peer_sec_addr_adv_m: self::blell::PEER_SEC_ADDR_ADV_M,
#[doc = "0x244 - Higher 16 bits of the secondary address of the peer device for ADV_DIR."]
pub peer_sec_addr_adv_h: self::blell::PEER_SEC_ADDR_ADV_H,
#[doc = "0x248 - Initiator Window NI timer control"]
pub init_window_timer_ctrl: self::blell::INIT_WINDOW_TIMER_CTRL,
#[doc = "0x24c - Connection extended configuration register"]
pub conn_config_ext: self::blell::CONN_CONFIG_EXT,
_reserved105: [u8; 8usize],
#[doc = "0x258 - DPLL & CY Correlator configuration register"]
pub dpll_config: self::blell::DPLL_CONFIG,
_reserved106: [u8; 4usize],
#[doc = "0x260 - Initiator Window NI instant"]
pub init_ni_val: self::blell::INIT_NI_VAL,
#[doc = "0x264 - Initiator Window offset captured at conn request"]
pub init_window_offset: self::blell::INIT_WINDOW_OFFSET,
#[doc = "0x268 - Initiator Window NI anchor point captured at conn request"]
pub init_window_ni_anchor_pt: self::blell::INIT_WINDOW_NI_ANCHOR_PT,
_reserved109: [u8; 312usize],
#[doc = "0x3a4 - Connection update new interval"]
pub conn_update_new_interval: self::blell::CONN_UPDATE_NEW_INTERVAL,
#[doc = "0x3a8 - Connection update new latency"]
pub conn_update_new_latency: self::blell::CONN_UPDATE_NEW_LATENCY,
#[doc = "0x3ac - Connection update new supervision timeout"]
pub conn_update_new_sup_to: self::blell::CONN_UPDATE_NEW_SUP_TO,
#[doc = "0x3b0 - Connection update new Slave Latency X Conn interval Value"]
pub conn_update_new_sl_interval: self::blell::CONN_UPDATE_NEW_SL_INTERVAL,
_reserved113: [u8; 12usize],
#[doc = "0x3c0 - Connection request address word 0"]
pub conn_req_word0: self::blell::CONN_REQ_WORD0,
#[doc = "0x3c4 - Connection request address word 1"]
pub conn_req_word1: self::blell::CONN_REQ_WORD1,
#[doc = "0x3c8 - Connection request address word 2"]
pub conn_req_word2: self::blell::CONN_REQ_WORD2,
#[doc = "0x3cc - Connection request address word 3"]
pub conn_req_word3: self::blell::CONN_REQ_WORD3,
#[doc = "0x3d0 - Connection request address word 4"]
pub conn_req_word4: self::blell::CONN_REQ_WORD4,
#[doc = "0x3d4 - Connection request address word 5"]
pub conn_req_word5: self::blell::CONN_REQ_WORD5,
#[doc = "0x3d8 - Connection request address word 6"]
pub conn_req_word6: self::blell::CONN_REQ_WORD6,
#[doc = "0x3dc - Connection request address word 7"]
pub conn_req_word7: self::blell::CONN_REQ_WORD7,
#[doc = "0x3e0 - Connection request address word 8"]
pub conn_req_word8: self::blell::CONN_REQ_WORD8,
#[doc = "0x3e4 - Connection request address word 9"]
pub conn_req_word9: self::blell::CONN_REQ_WORD9,
#[doc = "0x3e8 - Connection request address word 10"]
pub conn_req_word10: self::blell::CONN_REQ_WORD10,
#[doc = "0x3ec - Connection request address word 11"]
pub conn_req_word11: self::blell::CONN_REQ_WORD11,
_reserved125: [u8; 1556usize],
#[doc = "0xa04 - PDU response timer/Generic Timer (MMMS mode)"]
pub pdu_resp_timer: self::blell::PDU_RESP_TIMER,
#[doc = "0xa08 - Next response timeout instant"]
pub next_resp_timer_exp: self::blell::NEXT_RESP_TIMER_EXP,
#[doc = "0xa0c - Next supervision timeout instant"]
pub next_sup_to: self::blell::NEXT_SUP_TO,
#[doc = "0xa10 - Feature enable"]
pub llh_feature_config: self::blell::LLH_FEATURE_CONFIG,
#[doc = "0xa14 - Window minimum step size"]
pub win_min_step_size: self::blell::WIN_MIN_STEP_SIZE,
#[doc = "0xa18 - Slave window adjustment"]
pub slv_win_adj: self::blell::SLV_WIN_ADJ,
#[doc = "0xa1c - Slave Latency X Conn Interval Value"]
pub sl_conn_interval: self::blell::SL_CONN_INTERVAL,
#[doc = "0xa20 - LE Ping connection timer address"]
pub le_ping_timer_addr: self::blell::LE_PING_TIMER_ADDR,
#[doc = "0xa24 - LE Ping connection timer offset"]
pub le_ping_timer_offset: self::blell::LE_PING_TIMER_OFFSET,
#[doc = "0xa28 - LE Ping timer next expiry instant"]
pub le_ping_timer_next_exp: self::blell::LE_PING_TIMER_NEXT_EXP,
#[doc = "0xa2c - LE Ping Timer wrap count"]
pub le_ping_timer_wrap_count: self::blell::LE_PING_TIMER_WRAP_COUNT,
_reserved136: [u8; 976usize],
#[doc = "0xe00 - Transmit enable extension delay"]
pub tx_en_ext_delay: self::blell::TX_EN_EXT_DELAY,
#[doc = "0xe04 - Transmit/Receive enable delay"]
pub tx_rx_synth_delay: self::blell::TX_RX_SYNTH_DELAY,
#[doc = "0xe08 - External TX PA and RX LNA delay configuration"]
pub ext_pa_lna_dly_cnfg: self::blell::EXT_PA_LNA_DLY_CNFG,
_reserved139: [u8; 4usize],
#[doc = "0xe10 - Link Layer additional configuration"]
pub ll_config: self::blell::LL_CONFIG,
_reserved140: [u8; 236usize],
#[doc = "0xf00 - LL Backward compatibility"]
pub ll_control: self::blell::LL_CONTROL,
#[doc = "0xf04 - Device Resolvable/Non-Resolvable Private address lower register"]
pub dev_pa_addr_l: self::blell::DEV_PA_ADDR_L,
#[doc = "0xf08 - Device Resolvable/Non-Resolvable Private address middle register"]
pub dev_pa_addr_m: self::blell::DEV_PA_ADDR_M,
#[doc = "0xf0c - Device Resolvable/Non-Resolvable Private address higher register"]
pub dev_pa_addr_h: self::blell::DEV_PA_ADDR_H,
#[doc = "0xf10 - Resolving list entry control bit"]
pub rslv_list_enable: [self::blell::RSLV_LIST_ENABLE; 16],
_reserved145: [u8; 80usize],
#[doc = "0xfa0 - whitelist valid entry bit"]
pub wl_connection_status: self::blell::WL_CONNECTION_STATUS,
_reserved146: [u8; 2140usize],
#[doc = "0x1800 - DLE Connection RX memory base address"]
pub conn_rxmem_base_addr_dle: self::blell::CONN_RXMEM_BASE_ADDR_DLE,
_reserved147: [u8; 4092usize],
#[doc = "0x2800 - DLE Connection TX memory base address"]
pub conn_txmem_base_addr_dle: self::blell::CONN_TXMEM_BASE_ADDR_DLE,
_reserved148: [u8; 65532usize],
#[doc = "0x12800 - Connection Parameter memory base address for connection 1"]
pub conn_1_param_mem_base_addr: self::blell::CONN_1_PARAM_MEM_BASE_ADDR,
_reserved149: [u8; 124usize],
#[doc = "0x12880 - Connection Parameter memory base address for connection 2"]
pub conn_2_param_mem_base_addr: self::blell::CONN_2_PARAM_MEM_BASE_ADDR,
_reserved150: [u8; 124usize],
#[doc = "0x12900 - Connection Parameter memory base address for connection 3"]
pub conn_3_param_mem_base_addr: self::blell::CONN_3_PARAM_MEM_BASE_ADDR,
_reserved151: [u8; 124usize],
#[doc = "0x12980 - Connection Parameter memory base address for connection 4"]
pub conn_4_param_mem_base_addr: self::blell::CONN_4_PARAM_MEM_BASE_ADDR,
_reserved152: [u8; 5756usize],
#[doc = "0x14000 - Next Instant Timer"]
pub ni_timer: self::blell::NI_TIMER,
#[doc = "0x14004 - Micro-second Offset"]
pub us_offset: self::blell::US_OFFSET,
#[doc = "0x14008 - Next Connection"]
pub next_conn: self::blell::NEXT_CONN,
#[doc = "0x1400c - Abort next scheduled connection"]
pub ni_abort: self::blell::NI_ABORT,
_reserved156: [u8; 16usize],
#[doc = "0x14020 - Connection NI Status"]
pub conn_ni_status: self::blell::CONN_NI_STATUS,
#[doc = "0x14024 - Next Supervision timeout Status"]
pub next_sup_to_status: self::blell::NEXT_SUP_TO_STATUS,
#[doc = "0x14028 - Connection Status"]
pub mmms_conn_status: self::blell::MMMS_CONN_STATUS,
#[doc = "0x1402c - BT Slot Captured Status"]
pub bt_slot_capt_status: self::blell::BT_SLOT_CAPT_STATUS,
#[doc = "0x14030 - Micro-second Capture Status"]
pub us_capt_status: self::blell::US_CAPT_STATUS,
#[doc = "0x14034 - Micro-second Offset Status"]
pub us_offset_status: self::blell::US_OFFSET_STATUS,
#[doc = "0x14038 - Accumulated Window Widen Status"]
pub accu_window_widen_status: self::blell::ACCU_WINDOW_WIDEN_STATUS,
#[doc = "0x1403c - Status when early interrupt is raised"]
pub early_intr_status: self::blell::EARLY_INTR_STATUS,
#[doc = "0x14040 - Multi-Master Multi-Slave Config"]
pub mmms_config: self::blell::MMMS_CONFIG,
#[doc = "0x14044 - Running US of the current BT Slot"]
pub us_counter: self::blell::US_COUNTER,
#[doc = "0x14048 - Previous captured US of the BT Slot"]
pub us_capt_prev: self::blell::US_CAPT_PREV,
#[doc = "0x1404c - NI at early interrupt"]
pub early_intr_ni: self::blell::EARLY_INTR_NI,
_reserved168: [u8; 48usize],
#[doc = "0x14080 - BT slot capture for master connection creation"]
pub mmms_master_create_bt_capt: self::blell::MMMS_MASTER_CREATE_BT_CAPT,
#[doc = "0x14084 - BT slot capture for slave connection creation"]
pub mmms_slave_create_bt_capt: self::blell::MMMS_SLAVE_CREATE_BT_CAPT,
#[doc = "0x14088 - Micro second capture for slave connection creation"]
pub mmms_slave_create_us_capt: self::blell::MMMS_SLAVE_CREATE_US_CAPT,
_reserved171: [u8; 116usize],
#[doc = "0x14100 - Data buffer descriptor 0 to 15"]
pub mmms_data_mem_descriptor: [self::blell::MMMS_DATA_MEM_DESCRIPTOR; 16],
_reserved172: [u8; 192usize],
#[doc = "0x14200 - data list sent update and status for connection 1"]
pub conn_1_data_list_sent: self::blell::CONN_1_DATA_LIST_SENT,
#[doc = "0x14204 - data list ack update and status for connection 1"]
pub conn_1_data_list_ack: self::blell::CONN_1_DATA_LIST_ACK,
#[doc = "0x14208 - Connection specific pause resume for connection 1"]
pub conn_1_ce_data_list_cfg: self::blell::CONN_1_CE_DATA_LIST_CFG,
_reserved175: [u8; 4usize],
#[doc = "0x14210 - data list sent update and status for connection 2"]
pub conn_2_data_list_sent: self::blell::CONN_2_DATA_LIST_SENT,
#[doc = "0x14214 - data list ack update and status for connection 2"]
pub conn_2_data_list_ack: self::blell::CONN_2_DATA_LIST_ACK,
#[doc = "0x14218 - Connection specific pause resume for connection 2"]
pub conn_2_ce_data_list_cfg: self::blell::CONN_2_CE_DATA_LIST_CFG,
_reserved178: [u8; 4usize],
#[doc = "0x14220 - data list sent update and status for connection 3"]
pub conn_3_data_list_sent: self::blell::CONN_3_DATA_LIST_SENT,
#[doc = "0x14224 - data list ack update and status for connection 3"]
pub conn_3_data_list_ack: self::blell::CONN_3_DATA_LIST_ACK,
#[doc = "0x14228 - Connection specific pause resume for connection 3"]
pub conn_3_ce_data_list_cfg: self::blell::CONN_3_CE_DATA_LIST_CFG,
_reserved181: [u8; 4usize],
#[doc = "0x14230 - data list sent update and status for connection 4"]
pub conn_4_data_list_sent: self::blell::CONN_4_DATA_LIST_SENT,
#[doc = "0x14234 - data list ack update and status for connection 4"]
pub conn_4_data_list_ack: self::blell::CONN_4_DATA_LIST_ACK,
#[doc = "0x14238 - Connection specific pause resume for connection 4"]
pub conn_4_ce_data_list_cfg: self::blell::CONN_4_CE_DATA_LIST_CFG,
_reserved184: [u8; 452usize],
#[doc = "0x14400 - Enable bits for ADV_NI, SCAN_NI and INIT_NI"]
pub mmms_advch_ni_enable: self::blell::MMMS_ADVCH_NI_ENABLE,
#[doc = "0x14404 - Next instant valid for ADV, SCAN, INIT"]
pub mmms_advch_ni_valid: self::blell::MMMS_ADVCH_NI_VALID,
#[doc = "0x14408 - Abort the next instant of ADV, SCAN, INIT"]
pub mmms_advch_ni_abort: self::blell::MMMS_ADVCH_NI_ABORT,
_reserved187: [u8; 4usize],
#[doc = "0x14410 - Register to configure the supervision timeout for next scheduled connection"]
pub conn_param_next_sup_to: self::blell::CONN_PARAM_NEXT_SUP_TO,
#[doc = "0x14414 - Register to configure Accumulated window widening for next scheduled connection"]
pub conn_param_acc_win_widen: self::blell::CONN_PARAM_ACC_WIN_WIDEN,
_reserved189: [u8; 8usize],
#[doc = "0x14420 - Register to configure offset from connection anchor point at which connection parameter memory should be read"]
pub hw_load_offset: self::blell::HW_LOAD_OFFSET,
#[doc = "0x14424 - Random number generated by Hardware for ADV NI calculation"]
pub adv_rand: self::blell::ADV_RAND,
#[doc = "0x14428 - Packet Counter of packets in RX FIFO in MMMS mode"]
pub mmms_rx_pkt_cntr: self::blell::MMMS_RX_PKT_CNTR,
_reserved192: [u8; 4usize],
#[doc = "0x14430 - Packet Counter for Individual connection index"]
pub conn_rx_pkt_cntr: [self::blell::CONN_RX_PKT_CNTR; 8],
_reserved193: [u8; 944usize],
#[doc = "0x14800 - Whitelist base address"]
pub whitelist_base_addr: self::blell::WHITELIST_BASE_ADDR,
_reserved194: [u8; 188usize],
#[doc = "0x148c0 - Resolving list base address for storing Peer Identity address"]
pub rslv_list_peer_idntt_base_addr: self::blell::RSLV_LIST_PEER_IDNTT_BASE_ADDR,
_reserved195: [u8; 188usize],
#[doc = "0x14980 - Resolving list base address for storing resolved Peer RPA address"]
pub rslv_list_peer_rpa_base_addr: self::blell::RSLV_LIST_PEER_RPA_BASE_ADDR,
_reserved196: [u8; 188usize],
#[doc = "0x14a40 - Resolving list base address for storing Resolved received INITA RPA"]
pub rslv_list_rcvd_init_rpa_base_addr: self::blell::RSLV_LIST_RCVD_INIT_RPA_BASE_ADDR,
_reserved197: [u8; 188usize],
#[doc = "0x14b00 - Resolving list base address for storing generated TX INITA RPA"]
pub rslv_list_tx_init_rpa_base_addr: self::blell::RSLV_LIST_TX_INIT_RPA_BASE_ADDR,
}
#[doc = r"Register block"]
#[doc = "Bluetooth Low Energy Link Layer"]
pub mod blell;
#[doc = r"Register block"]
#[repr(C)]
pub struct BLESS {
_reserved0: [u8; 96usize],
#[doc = "0x60 - BLESS DDFT configuration register"]
pub ddft_config: self::bless::DDFT_CONFIG,
#[doc = "0x64 - Crystal clock divider configuration register"]
pub xtal_clk_div_config: self::bless::XTAL_CLK_DIV_CONFIG,
#[doc = "0x68 - Link Layer interrupt status register"]
pub intr_stat: self::bless::INTR_STAT,
#[doc = "0x6c - Link Layer interrupt mask register"]
pub intr_mask: self::bless::INTR_MASK,
#[doc = "0x70 - Link Layer primary clock enable"]
pub ll_clk_en: self::bless::LL_CLK_EN,
#[doc = "0x74 - BLESS LF clock control and BLESS revision ID indicator"]
pub lf_clk_ctrl: self::bless::LF_CLK_CTRL,
#[doc = "0x78 - External TX PA and RX LNA control"]
pub ext_pa_lna_ctrl: self::bless::EXT_PA_LNA_CTRL,
_reserved7: [u8; 4usize],
#[doc = "0x80 - Link Layer Last Received packet RSSI/Channel energy and channel number"]
pub ll_pkt_rssi_ch_energy: self::bless::LL_PKT_RSSI_CH_ENERGY,
#[doc = "0x84 - BT clock captured on an LL DSM exit"]
pub bt_clock_capt: self::bless::BT_CLOCK_CAPT,
_reserved9: [u8; 24usize],
#[doc = "0xa0 - MT Configuration Register"]
pub mt_cfg: self::bless::MT_CFG,
#[doc = "0xa4 - MT Delay configuration for state transitions"]
pub mt_delay_cfg: self::bless::MT_DELAY_CFG,
#[doc = "0xa8 - MT Delay configuration for state transitions"]
pub mt_delay_cfg2: self::bless::MT_DELAY_CFG2,
#[doc = "0xac - MT Delay configuration for state transitions"]
pub mt_delay_cfg3: self::bless::MT_DELAY_CFG3,
#[doc = "0xb0 - MT Configuration Register to control VIO switches"]
pub mt_vio_ctrl: self::bless::MT_VIO_CTRL,
#[doc = "0xb4 - MT Status Register"]
pub mt_status: self::bless::MT_STATUS,
#[doc = "0xb8 - Link Layer Power Control FSM Status Register"]
pub pwr_ctrl_sm_st: self::bless::PWR_CTRL_SM_ST,
_reserved16: [u8; 4usize],
#[doc = "0xc0 - HVLDO Configuration register"]
pub hvldo_ctrl: self::bless::HVLDO_CTRL,
#[doc = "0xc4 - Radio Buck and Active regulator enable control"]
pub misc_en_ctrl: self::bless::MISC_EN_CTRL,
_reserved18: [u8; 8usize],
#[doc = "0xd0 - EFUSE mode configuration register"]
pub efuse_config: self::bless::EFUSE_CONFIG,
#[doc = "0xd4 - EFUSE timing control register (common for Program and Read modes)"]
pub efuse_tim_ctrl1: self::bless::EFUSE_TIM_CTRL1,
#[doc = "0xd8 - EFUSE timing control Register (for Read)"]
pub efuse_tim_ctrl2: self::bless::EFUSE_TIM_CTRL2,
#[doc = "0xdc - EFUSE timing control Register (for Program)"]
pub efuse_tim_ctrl3: self::bless::EFUSE_TIM_CTRL3,
#[doc = "0xe0 - EFUSE Lower read data"]
pub efuse_rdata_l: self::bless::EFUSE_RDATA_L,
#[doc = "0xe4 - EFUSE higher read data"]
pub efuse_rdata_h: self::bless::EFUSE_RDATA_H,
#[doc = "0xe8 - EFUSE lower write word"]
pub efuse_wdata_l: self::bless::EFUSE_WDATA_L,
#[doc = "0xec - EFUSE higher write word"]
pub efuse_wdata_h: self::bless::EFUSE_WDATA_H,
#[doc = "0xf0 - Divide by 625 for FW Use"]
pub div_by_625_cfg: self::bless::DIV_BY_625_CFG,
#[doc = "0xf4 - Output of divide by 625 divider"]
pub div_by_625_sts: self::bless::DIV_BY_625_STS,
_reserved28: [u8; 8usize],
#[doc = "0x100 - Packet counter 0"]
pub packet_counter0: self::bless::PACKET_COUNTER0,
#[doc = "0x104 - Packet counter 2"]
pub packet_counter2: self::bless::PACKET_COUNTER2,
#[doc = "0x108 - Master Initialization Vector 0"]
pub iv_master0: self::bless::IV_MASTER0,
#[doc = "0x10c - Slave Initialization Vector 0"]
pub iv_slave0: self::bless::IV_SLAVE0,
#[doc = "0x110 - Encryption Key register 0-3"]
pub enc_key: [self::bless::ENC_KEY; 4],
#[doc = "0x120 - MIC input register"]
pub mic_in0: self::bless::MIC_IN0,
#[doc = "0x124 - MIC output register"]
pub mic_out0: self::bless::MIC_OUT0,
#[doc = "0x128 - Encryption Parameter register"]
pub enc_params: self::bless::ENC_PARAMS,
#[doc = "0x12c - Encryption Configuration"]
pub enc_config: self::bless::ENC_CONFIG,
#[doc = "0x130 - Encryption Interrupt enable"]
pub enc_intr_en: self::bless::ENC_INTR_EN,
#[doc = "0x134 - Encryption Interrupt status and clear register"]
pub enc_intr: self::bless::ENC_INTR,
_reserved39: [u8; 8usize],
#[doc = "0x140 - Programmable B1 Data register (0-3)"]
pub b1_data_reg: [self::bless::B1_DATA_REG; 4],
#[doc = "0x150 - Encryption memory base address"]
pub enc_mem_base_addr: self::bless::ENC_MEM_BASE_ADDR,
_reserved41: [u8; 3500usize],
#[doc = "0xf00 - LDO Trim register 0"]
pub trim_ldo_0: self::bless::TRIM_LDO_0,
#[doc = "0xf04 - LDO Trim register 1"]
pub trim_ldo_1: self::bless::TRIM_LDO_1,
#[doc = "0xf08 - LDO Trim register 2"]
pub trim_ldo_2: self::bless::TRIM_LDO_2,
#[doc = "0xf0c - LDO Trim register 3"]
pub trim_ldo_3: self::bless::TRIM_LDO_3,
#[doc = "0xf10 - MXD die Trim registers"]
pub trim_mxd: [self::bless::TRIM_MXD; 4],
_reserved46: [u8; 16usize],
#[doc = "0xf30 - LDO Trim register 4"]
pub trim_ldo_4: self::bless::TRIM_LDO_4,
#[doc = "0xf34 - LDO Trim register 5"]
pub trim_ldo_5: self::bless::TRIM_LDO_5,
}
#[doc = r"Register block"]
#[doc = "Bluetooth Low Energy Subsystem Miscellaneous"]
pub mod bless;
|
#[cfg(test)]
mod tests {
use bbqueue::{BBBuffer, Consumer, GrantR, GrantW, Producer};
enum Potato<'a, const N: usize> {
Tx((Producer<'a, N>, u8)),
Rx((Consumer<'a, N>, u8)),
TxG(GrantW<'a, N>),
RxG(GrantR<'a, N>),
Idle,
Done,
}
#[cfg(not(feature = "short-potato"))]
const TOTAL_RINGS: usize = 1_000_000;
#[cfg(feature = "short-potato")]
const TOTAL_RINGS: usize = 1_000;
const TX_GRANTS_PER_RING: u8 = 3;
const RX_GRANTS_PER_RING: u8 = 3;
const BYTES_PER_GRANT: usize = 129;
const BUFFER_SIZE: usize = 4096;
impl<'a, const N: usize> Potato<'a, N> {
fn work(self) -> (Self, Self) {
match self {
Self::Tx((mut prod, ct)) => {
// If we are holding a producer, try to send three things before passing it on.
if ct == 0 {
// If we have exhausted our counts, pass on the sender.
(Self::Idle, Self::Tx((prod, TX_GRANTS_PER_RING)))
} else {
// If we get a grant, pass it on, otherwise keep trying
if let Ok(wgr) = prod.grant_exact(BYTES_PER_GRANT) {
(Self::Tx((prod, ct - 1)), Self::TxG(wgr))
} else {
(Self::Tx((prod, ct)), Self::Idle)
}
}
}
Self::Rx((mut cons, ct)) => {
// If we are holding a consumer, try to send three things before passing it on.
if ct == 0 {
// If we have exhausted our counts, pass on the sender.
(Self::Idle, Self::Rx((cons, RX_GRANTS_PER_RING)))
} else {
// If we get a grant, pass it on, otherwise keep trying
if let Ok(rgr) = cons.read() {
(Self::Rx((cons, ct - 1)), Self::RxG(rgr))
} else {
(Self::Rx((cons, ct)), Self::Idle)
}
}
}
Self::TxG(mut gr_w) => {
gr_w.iter_mut()
.take(BYTES_PER_GRANT)
.enumerate()
.for_each(|(i, by)| *by = i as u8);
gr_w.commit(BYTES_PER_GRANT);
(Self::Idle, Self::Idle)
}
Self::RxG(gr_r) => {
gr_r.iter()
.take(BYTES_PER_GRANT)
.enumerate()
.for_each(|(i, by)| assert_eq!(*by, i as u8));
gr_r.release(BYTES_PER_GRANT);
(Self::Idle, Self::Idle)
}
Self::Idle => (Self::Idle, Self::Idle),
Self::Done => (Self::Idle, Self::Done),
}
}
}
static BB: BBBuffer<BUFFER_SIZE> = BBBuffer::new();
use std::sync::mpsc::{channel, Receiver, Sender};
use std::thread::spawn;
#[test]
fn hello() {
let (prod, cons) = BB.try_split().unwrap();
// create the channels
let (tx_1_2, rx_1_2): (
Sender<Potato<'static, BUFFER_SIZE>>,
Receiver<Potato<'static, BUFFER_SIZE>>,
) = channel();
let (tx_2_3, rx_2_3): (
Sender<Potato<'static, BUFFER_SIZE>>,
Receiver<Potato<'static, BUFFER_SIZE>>,
) = channel();
let (tx_3_4, rx_3_4): (
Sender<Potato<'static, BUFFER_SIZE>>,
Receiver<Potato<'static, BUFFER_SIZE>>,
) = channel();
let (tx_4_1, rx_4_1): (
Sender<Potato<'static, BUFFER_SIZE>>,
Receiver<Potato<'static, BUFFER_SIZE>>,
) = channel();
tx_1_2.send(Potato::Tx((prod, 3))).unwrap();
tx_1_2.send(Potato::Rx((cons, 3))).unwrap();
let thread_1 = spawn(move || {
let mut count = TOTAL_RINGS;
let mut me: Potato<'static, BUFFER_SIZE> = Potato::Idle;
loop {
if let Potato::Idle = me {
if let Ok(new) = rx_4_1.recv() {
if let Potato::Tx(tx) = new {
count -= 1;
if (count % 100) == 0 {
println!("count left: {}", count);
}
if count == 0 {
me = Potato::Done;
} else {
me = Potato::Tx(tx);
}
} else {
me = new;
}
} else {
continue;
}
}
let (new_me, send) = me.work();
let we_done = if let Potato::Done = &send {
true
} else {
false
};
let nop = if let Potato::Idle = &send {
true
} else {
false
};
if !nop {
tx_1_2.send(send).unwrap();
}
if we_done {
println!("We good?");
return;
}
me = new_me;
}
});
let closure_2_3_4 =
move |rx: Receiver<Potato<'static, BUFFER_SIZE>>,
tx: Sender<Potato<'static, BUFFER_SIZE>>| {
let mut me: Potato<'static, BUFFER_SIZE> = Potato::Idle;
let mut count = 0;
loop {
if let Potato::Idle = me {
if let Ok(new) = rx.try_recv() {
if let Potato::Tx(_) = &new {
count += 1;
}
me = new;
} else {
continue;
}
}
let (new_me, send) = me.work();
let we_done = if let Potato::Done = &send {
true
} else {
false
};
let nop = if let Potato::Idle = &send {
true
} else {
false
};
if !nop {
tx.send(send).ok();
}
if we_done {
assert_eq!(count, TOTAL_RINGS);
println!("We good.");
return;
}
me = new_me;
}
};
let thread_2 = spawn(move || closure_2_3_4(rx_1_2, tx_2_3));
let thread_3 = spawn(move || closure_2_3_4(rx_2_3, tx_3_4));
let thread_4 = spawn(move || closure_2_3_4(rx_3_4, tx_4_1));
thread_1.join().unwrap();
thread_2.join().unwrap();
thread_3.join().unwrap();
thread_4.join().unwrap();
}
}
|
use actix_service::{Service, Transform};
use actix_web::{dev::ServiceRequest, dev::ServiceResponse, Error, HttpMessage};
use futures::{
future::{ok, Ready},
Future,
};
use slog::info;
use std::{
pin::Pin,
task::{Context, Poll},
};
use time::OffsetDateTime;
pub struct Logger(slog::Logger);
impl Logger {
pub fn new(logger: slog::Logger) -> Self {
Self(logger)
}
}
impl<S, B> Transform<S> for Logger
where
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
type Request = ServiceRequest;
type Response = ServiceResponse<B>;
type Error = Error;
type InitError = ();
type Transform = LoggerMiddleware<S>;
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ok(LoggerMiddleware {
service,
logger: self.0.clone(),
})
}
}
#[doc(hidden)]
pub struct LoggerMiddleware<S> {
service: S,
logger: slog::Logger,
}
#[allow(clippy::type_complexity)]
impl<S, B> Service for LoggerMiddleware<S>
where
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
type Request = ServiceRequest;
type Response = ServiceResponse<B>;
type Error = Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx)
}
fn call(&mut self, req: ServiceRequest) -> Self::Future {
let path = req.path().to_string();
let start = OffsetDateTime::now_utc();
let method = req.method().to_string();
let log = self.logger.clone();
req.extensions_mut().insert(String::new());
let address = req
.connection_info()
.realip_remote_addr()
.map(|s| s.to_string());
let agent = req
.headers()
.get("user-agent")
.and_then(|h| h.to_str().ok().map(|s| s.to_string()));
let next = self.service.call(req);
Box::pin(async move {
let res = next.await?;
let time_ms =
(OffsetDateTime::now_utc() - start).whole_nanoseconds() as f32 / 1_000_000f32;
info!(log, "request";
"method" => method,
"path" => path,
"status" => res.status().as_u16(),
"time" => format!("{}ms", time_ms),
"userAgent" => agent,
"address" => address,
);
Ok(res)
})
}
}
|
use crate::config::ContainerOpts;
use crate::errors::Errcode;
use crate::hostname::set_container_hostname;
use crate::mounts::setmountpoint;
use nix::unistd::{Pid, close, execve};
use nix::sched::{CloneFlags, clone};
use nix::sys::signal::Signal;
use std::ffi::CString;
fn child(config: ContainerOpts) -> isize {
match setup_container_configurations(&config) {
Ok(_) => log::info!("Container set up successfully"),
Err(e) => {
log::error!("Error while configuring container: {:?}", e);
return -1;
}
}
if let Err(_) = close(config.fd) {
log::error!("Error while closing socket ...");
return -1;
}
log::info!("Starting container with command {} and args {:?}", config.path.to_str().unwrap(), config.argv);
let retcode = match execve::<CString, CString>(&config.path, &config.argv, &[]) {
Ok(_) => 0,
Err(e) => {
log::error!("Error while trying to perform execve: {:?}", e);
-1
}
};
retcode
}
const STACK_SIZE: usize = 1024 * 1024;
pub fn generate_child_process(config: ContainerOpts) -> Result<Pid, Errcode> {
let mut tmp_stack: [u8; STACK_SIZE] = [0; STACK_SIZE];
let mut flags = CloneFlags::empty();
flags.insert(CloneFlags::CLONE_NEWNS);
flags.insert(CloneFlags::CLONE_NEWCGROUP);
flags.insert(CloneFlags::CLONE_NEWPID);
flags.insert(CloneFlags::CLONE_NEWIPC);
flags.insert(CloneFlags::CLONE_NEWNET);
flags.insert(CloneFlags::CLONE_NEWUTS);
match clone(
Box::new(|| child(config.clone())),
&mut tmp_stack,
flags,
Some(Signal::SIGCHLD as i32)
) {
Ok(pid) => Ok(pid),
Err(e) => {
log::error!("error occurred while generating child process because of {:?}", e);
Err(Errcode::ChildProcessError(0))
},
}
}
use crate::namespaces::userns;
use crate::capabilities::setcapabilities;
use crate::syscalls::setsyscalls;
pub fn setup_container_configurations(config: &ContainerOpts) -> Result<(), Errcode> {
set_container_hostname(&config.hostname)?;
setmountpoint(&config.mount_dir, &config.addpaths)?;
userns(config.fd, config.uid)?;
setcapabilities()?;
setsyscalls()?;
Ok(())
} |
use std::fs::File;
use std::io::Read;
use crate::rover::{Orientation, Position, Rover};
use crate::simulation::{Grid, Instruction};
const RADIX: u32 = 10;
pub fn read_input() -> (Grid, Vec<Rover>, Vec<Vec<Instruction>>) {
let data = match open_file() {
Err(error) => panic!("Couldn't read file: {:?}", error),
Ok(contents) => contents,
};
let data: Vec<&str> = data.split('\n').filter(|line| !line.is_empty()).collect();
(
get_grid(data[0]),
get_rovers(&data),
get_instructions(&data),
)
}
fn open_file() -> std::io::Result<String> {
let mut f = File::open("data.txt")?;
let mut contents = String::new();
f.read_to_string(&mut contents)?;
Ok(contents)
}
fn char_to_int(c: char) -> i32 {
c.to_digit(RADIX).unwrap() as i32
}
fn parse_line(line: &str) -> Vec<char> {
line.chars().filter(|c| !c.is_whitespace()).collect()
}
fn parse_orientation(orientation: char) -> Result<Orientation, String> {
match orientation {
'E' => Ok(Orientation::East),
'N' => Ok(Orientation::North),
'S' => Ok(Orientation::South),
'W' => Ok(Orientation::West),
_ => Err(String::from("unknown rover orientation")),
}
}
fn parse_instruction(instruction: char) -> Result<Instruction, String> {
match instruction {
'L' => Ok(Instruction::Left),
'R' => Ok(Instruction::Right),
'F' => Ok(Instruction::Forward),
_ => Err(String::from("unknown instruction")),
}
}
fn get_grid(line: &str) -> Grid {
let grid: Vec<i32> = line
.chars()
.filter(|c| *c != ' ')
.map(char_to_int)
.collect();
Grid(grid[0], grid[1])
}
fn get_rovers(data: &[&str]) -> Vec<Rover> {
let mut rovers: Vec<Rover> = vec![];
for line in (1..data.len()).step_by(2) {
let parsed_line = parse_line(data[line]);
let x = char_to_int(parsed_line[0]);
let y = char_to_int(parsed_line[1]);
let orientation = parse_orientation(parsed_line[2]).expect("get_rovers");
rovers.push(Rover::new(Position(x, y, orientation)));
}
rovers
}
fn get_instructions(data: &[&str]) -> Vec<Vec<Instruction>> {
let mut instructions: Vec<Vec<Instruction>> = vec![];
for line in (2..data.len()).step_by(2) {
let parsed_line = parse_line(data[line]);
let mut parsed_instructions: Vec<Instruction> = vec![];
for c in parsed_line {
let instruction = parse_instruction(c).expect("get_rovers");
parsed_instructions.push(instruction);
}
instructions.push(parsed_instructions);
}
instructions
}
|
#![deny(warnings)]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde;
#[macro_use]
extern crate failure;
#[macro_use]
extern crate diesel;
#[cfg(feature = "python")]
extern crate cpython;
use actix::prelude::*;
pub mod api;
mod build_info;
mod config;
mod db;
pub mod engine;
pub mod opentracing;
lazy_static! {
static ref DB_EXECUTOR_POOL: actix::Addr<db::update::DbExecutor> = {
let config = crate::config::Config::load();
actix::SyncArbiter::start(1, move || {
if let Ok(connection) = db::update::establish_connection(&config.db_url) {
db::update::DbExecutor(Some(connection))
} else {
error!("error opening connection to DB");
db::update::DbExecutor(None)
}
})
};
}
lazy_static! {
static ref DB_READ_EXECUTOR_POOL: actix::Addr<db::read::DbReadExecutor> = {
let config = crate::config::Config::load();
actix::SyncArbiter::start(3, move || {
if let Ok(connection) = db::read::establish_connection(&config.db_url) {
db::read::DbReadExecutor(Some(connection))
} else {
error!("error opening read connection to DB");
db::read::DbReadExecutor(None)
}
})
};
}
lazy_static! {
#[derive(Debug)]
static ref CONFIG: config::Config = config::Config::load();
}
pub fn start_server() {
info!("Starting i'Krelln with config: {:?}", *CONFIG);
let system = actix::System::new("i'Krelln");
match std::env::var("LISTEN_FD") {
Ok(fd) => api::serve_from_fd(&fd),
_ => api::serve(&CONFIG.host, CONFIG.port),
}
//actix::System::current().registry()
actix::System::current()
.registry()
.get::<crate::engine::streams::Streamer>()
.do_send(crate::engine::streams::LoadScripts);
let _: Addr<_> = db::cleanup::CleanUpTimer.start();
system.run();
}
|
use std::cmp::Ordering;
use crate::{AnyBin, AnyStr};
impl<TBin> Eq for AnyStr<TBin> where TBin: AnyBin {}
impl<TBin> PartialEq for AnyStr<TBin>
where
TBin: AnyBin,
{
fn eq(&self, other: &Self) -> bool {
self.as_str() == other.as_str()
}
}
impl<TBin> PartialEq<str> for AnyStr<TBin>
where
TBin: AnyBin,
{
fn eq(&self, other: &str) -> bool {
self.as_str() == other
}
}
impl<TBin> Ord for AnyStr<TBin>
where
TBin: AnyBin,
{
fn cmp(&self, other: &Self) -> Ordering {
self.as_str().cmp(other.as_str())
}
}
impl<TBin> PartialOrd for AnyStr<TBin>
where
TBin: AnyBin,
{
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.as_str().partial_cmp(other.as_str())
}
}
impl<TBin> PartialOrd<str> for AnyStr<TBin>
where
TBin: AnyBin,
{
fn partial_cmp(&self, other: &str) -> Option<Ordering> {
self.as_str().partial_cmp(other)
}
}
|
extern crate docopt;
use std::io::{self, Write};
use std::process;
use docopt::Docopt;
use csv;
use std::fs;
use std::path::Path;
use std::error::Error;
static USAGE: &'static str = "
Usage: city-pop [options] <data-path> <city>
city-pop --help
Options:
-h, --help Show this usage message.
";
#[derive(Debug, RustcDecodable)]
struct Args {
arg_data_path: Option<String>,
arg_city: String,
}
#[derive(Debug)]
struct PopulationCount {
city: String,
country: String,
count: u64,
}
#[derive(Debug, RustcDecodable)]
struct Row {
country: String,
city: String,
accent_city: String,
region: String,
population: Option<u64>,
latitude: Option<f64>,
longitude: Option<f64>,
}
fn search<P: AsRef<Path>>(file_path: &Option<P>, city: &str) -> Result<Vec<PopulationCount>, Box<Error + Send + Sync>> {
let mut found = vec![];
let input: Box<io::Read> = match *file_path {
None => Box::new(io::stdin()),
Some(ref file_path) => Box::new(fs::File::open(file_path)?),
};
let mut rdr = csv::Reader::from_reader(input);
for row in rdr.decode::<Row>() {
let row = row?;
if row.city == city {
match row.population {
None => {}
Some(count) => {
found.push(PopulationCount {
city: row.city,
country: row.country,
count: count,
});
}
}
}
}
if found.is_empty() {
Err(From::from("No matching cities with a population were found"))
} else {
Ok(found)
}
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|err| err.exit());
for pop in search(&args.arg_data_path, &args.arg_city).unwrap() {
println!("{}, {}: {:?}", pop.city, pop.country, pop.count);
}
} |
use crate::bitfield::BitField;
/// A single bucket within a hopscotch hashed hashmap.
#[derive(Clone, Debug)]
pub struct Bucket<K, V, B> {
/// Key, value, ideal hash position triplet.
pub data: Option<(K, V, usize)>,
/// A bitfield representing the next <sizeof bitfield> buckets in the hashmap (including this
/// one). A one in this bitfield means that the bucket contains a value which should be in this
/// bucket, a zero in this bitfield means that the bucket is either empty, or contains a value
/// which should not be in this bucket.
pub neighbourhood: B,
}
impl<K, V, B: BitField + Copy> Bucket<K, V, B> {
/// Create a new heap allocated array, with a given size, of empty buckets.
pub fn empty_vec(size: usize) -> Box<[Self]> {
let mut output = Vec::with_capacity(size);
for _ in 0..size {
let element: Self = Bucket {
data: None,
neighbourhood: B::one_at(0) & B::zero_at(0),
};
output.push(element);
}
output.into()
}
}
#[cfg(test)]
mod tests {
use crate::{bitfield::DefaultBitField, bucket::Bucket};
#[test]
fn test_empty_vec() {
let vec: Box<[Bucket<(), (), DefaultBitField>]> = Bucket::empty_vec(0);
assert!(vec.len() == 0)
}
#[test]
fn test_full_vec() {
let length = 1024;
let vec: Box<[Bucket<(), (), DefaultBitField>]> = Bucket::empty_vec(length);
assert!(vec.len() == length);
assert!(vec
.iter()
.all(|element| element.data == None && element.neighbourhood == 0));
}
}
|
pub const SCREEN_WIDTH: u32 = 1920 / 4;
pub const SCREEN_HEIGHT: u32 = 1080 / 4;
pub const FPS: f64 = 1000.0 / 60.0;
|
//! Association requester module
//!
//! The module provides an abstraction for a DICOM association
//! in which this application entity is the one requesting the association.
//! See [`ClientAssociationOptions`](self::ClientAssociationOptions)
//! for details and examples on how to create an association.
use std::{
borrow::Cow,
io::Write,
net::{TcpStream, ToSocketAddrs},
};
use crate::{
pdu::{
reader::{read_pdu, DEFAULT_MAX_PDU, MAXIMUM_PDU_SIZE},
writer::write_pdu,
AbortRQSource, AssociationRJResult, AssociationRJSource, Pdu, PresentationContextProposed,
PresentationContextResult, PresentationContextResultReason, UserVariableItem,
},
IMPLEMENTATION_CLASS_UID, IMPLEMENTATION_VERSION_NAME,
};
use snafu::{ensure, ResultExt, Snafu};
use super::pdata::PDataWriter;
#[derive(Debug, Snafu)]
#[non_exhaustive]
pub enum Error {
/// missing abstract syntax to begin negotiation
MissingAbstractSyntax,
/// could not connect to server
Connect { source: std::io::Error },
/// failed to send association request
SendRequest { source: crate::pdu::writer::Error },
/// failed to receive association response
ReceiveResponse { source: crate::pdu::reader::Error },
#[snafu(display("unexpected response from server `{:?}`", pdu))]
#[non_exhaustive]
UnexpectedResponse {
/// the PDU obtained from the server
pdu: Pdu,
},
#[snafu(display("unknown response from server `{:?}`", pdu))]
#[non_exhaustive]
UnknownResponse {
/// the PDU obtained from the server, of variant Unknown
pdu: Pdu,
},
#[snafu(display("protocol version mismatch: expected {}, got {}", expected, got))]
ProtocolVersionMismatch { expected: u16, got: u16 },
/// the association was rejected by the server
Rejected {
association_result: AssociationRJResult,
association_source: AssociationRJSource,
},
/// no presentation contexts accepted by the server
NoAcceptedPresentationContexts,
/// failed to send PDU message
#[non_exhaustive]
Send { source: crate::pdu::writer::Error },
/// failed to send PDU message on wire
#[non_exhaustive]
WireSend { source: std::io::Error },
#[snafu(display(
"PDU is too large ({} bytes) to be sent to the remote application entity",
length
))]
#[non_exhaustive]
SendTooLongPdu { length: usize },
/// failed to receive PDU message
#[non_exhaustive]
Receive { source: crate::pdu::reader::Error },
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// A DICOM association builder for a client node.
/// The final outcome is a [`ClientAssociation`].
///
/// This is the standard way of requesting and establishing
/// an association with another DICOM node,
/// that one usually taking the role of a service class provider (SCP).
///
/// # Example
///
/// ```no_run
/// # use dicom_ul::association::client::ClientAssociationOptions;
/// # fn run() -> Result<(), Box<dyn std::error::Error>> {
/// let association = ClientAssociationOptions::new()
/// .with_abstract_syntax("1.2.840.10008.1.1")
/// .with_transfer_syntax("1.2.840.10008.1.2.1")
/// .establish("129.168.0.5:104")?;
/// # Ok(())
/// # }
/// ```
///
/// At least one abstract syntax must be specified,
/// using the method [`with_abstract_syntax`](Self::with_abstract_syntax).
/// The requester will admit by default the transfer syntaxes
/// _Implicit VR Little Endian_
/// and _Explicit VR Little Endian_.
/// Other transfer syntaxes can be requested in the association
/// via the method [`with_transfer_syntax`](Self::with_transfer_syntax).
#[derive(Debug, Clone)]
pub struct ClientAssociationOptions<'a> {
/// the calling AE title
calling_ae_title: Cow<'a, str>,
/// the called AE title
called_ae_title: Cow<'a, str>,
/// the requested application context name
application_context_name: Cow<'a, str>,
/// the list of requested abstract syntaxes
abstract_syntax_uids: Vec<Cow<'a, str>>,
/// the list of requested transfer syntaxes
transfer_syntax_uids: Vec<Cow<'a, str>>,
/// the expected protocol version
protocol_version: u16,
/// the maximum PDU length requested for receiving PDUs
max_pdu_length: u32,
}
impl<'a> Default for ClientAssociationOptions<'a> {
fn default() -> Self {
ClientAssociationOptions {
/// the calling AE title
calling_ae_title: "THIS-SCU".into(),
/// the called AE title
called_ae_title: "ANY-SCP".into(),
/// the requested application context name
application_context_name: "1.2.840.10008.3.1.1.1".into(),
/// the list of requested abstract syntaxes
abstract_syntax_uids: Vec::new(),
/// the application context name
transfer_syntax_uids: Vec::new(),
protocol_version: 1,
max_pdu_length: crate::pdu::reader::DEFAULT_MAX_PDU,
}
}
}
impl<'a> ClientAssociationOptions<'a> {
/// Create a new set of options for establishing an association.
pub fn new() -> Self {
Self::default()
}
/// Define the calling application entity title for the association,
/// which refers to this DICOM node.
///
/// The default is `THIS-SCU`.
pub fn calling_ae_title<T>(mut self, calling_ae_title: T) -> Self
where
T: Into<Cow<'a, str>>,
{
self.calling_ae_title = calling_ae_title.into();
self
}
/// Define the called application entity title for the association,
/// which refers to the target DICOM node.
///
/// The default is `ANY-SCP`.
pub fn called_ae_title<T>(mut self, called_ae_title: T) -> Self
where
T: Into<Cow<'a, str>>,
{
self.called_ae_title = called_ae_title.into();
self
}
/// Include this abstract syntax
/// in the list of proposed presentation contexts.
pub fn with_abstract_syntax<T>(mut self, abstract_syntax_uid: T) -> Self
where
T: Into<Cow<'a, str>>,
{
self.abstract_syntax_uids.push(abstract_syntax_uid.into());
self
}
/// Include this transfer syntax in each proposed presentation context.
pub fn with_transfer_syntax<T>(mut self, transfer_syntax_uid: T) -> Self
where
T: Into<Cow<'a, str>>,
{
self.transfer_syntax_uids.push(transfer_syntax_uid.into());
self
}
/// Override the maximum PDU length
/// that this application entity will admit.
pub fn max_pdu_length(mut self, value: u32) -> Self {
self.max_pdu_length = value;
self
}
/// Initiate the TCP connection to the given address
/// and request a new DICOM association,
/// negotiating the presentation contexts in the process.
pub fn establish<A: ToSocketAddrs>(self, address: A) -> Result<ClientAssociation> {
let ClientAssociationOptions {
calling_ae_title,
called_ae_title,
application_context_name,
abstract_syntax_uids,
mut transfer_syntax_uids,
protocol_version,
max_pdu_length,
} = self;
// fail if no abstract syntaxes were provided: they represent intent,
// should not be omitted by the user
ensure!(!abstract_syntax_uids.is_empty(), MissingAbstractSyntax);
// provide default transfer syntaxes
if transfer_syntax_uids.is_empty() {
// Explicit VR Little Endian
transfer_syntax_uids.push("1.2.840.10008.1.2.1".into());
// Implicit VR Little Endian
transfer_syntax_uids.push("1.2.840.10008.1.2".into());
}
let presentation_contexts: Vec<_> = abstract_syntax_uids
.into_iter()
.enumerate()
.map(|(i, abstract_syntax)| PresentationContextProposed {
id: (i + 1) as u8,
abstract_syntax: abstract_syntax.to_string(),
transfer_syntaxes: transfer_syntax_uids
.iter()
.map(|uid| uid.to_string())
.collect(),
})
.collect();
let msg = Pdu::AssociationRQ {
protocol_version,
calling_ae_title: calling_ae_title.to_string(),
called_ae_title: called_ae_title.to_string(),
application_context_name: application_context_name.to_string(),
presentation_contexts,
user_variables: vec![
UserVariableItem::MaxLength(max_pdu_length),
UserVariableItem::ImplementationClassUID(IMPLEMENTATION_CLASS_UID.to_string()),
UserVariableItem::ImplementationVersionName(
IMPLEMENTATION_VERSION_NAME.to_string(),
),
],
};
let mut socket = std::net::TcpStream::connect(address).context(Connect)?;
let mut buffer: Vec<u8> = Vec::with_capacity(max_pdu_length as usize);
// send request
write_pdu(&mut buffer, &msg).context(SendRequest)?;
socket.write_all(&buffer).context(WireSend)?;
buffer.clear();
// receive response
let msg = read_pdu(&mut socket, MAXIMUM_PDU_SIZE, true).context(ReceiveResponse)?;
match msg {
Pdu::AssociationAC {
protocol_version: protocol_version_scp,
application_context_name: _,
presentation_contexts: presentation_contexts_scp,
calling_ae_title: _,
called_ae_title: _,
user_variables,
} => {
ensure!(
protocol_version == protocol_version_scp,
ProtocolVersionMismatch {
expected: protocol_version,
got: protocol_version_scp,
}
);
let acceptor_max_pdu_length = user_variables
.iter()
.find_map(|item| match item {
UserVariableItem::MaxLength(len) => Some(*len),
_ => None,
})
.unwrap_or(DEFAULT_MAX_PDU);
// treat 0 as the maximum size admitted by the standard
let acceptor_max_pdu_length = if acceptor_max_pdu_length == 0 {
MAXIMUM_PDU_SIZE
} else {
acceptor_max_pdu_length
};
let presentation_contexts: Vec<_> = presentation_contexts_scp
.into_iter()
.filter(|c| c.reason == PresentationContextResultReason::Acceptance)
.collect();
if presentation_contexts.is_empty() {
// abort connection
let _ = write_pdu(
&mut buffer,
&Pdu::AbortRQ {
source: AbortRQSource::ServiceUser,
},
);
let _ = socket.write_all(&buffer);
buffer.clear();
return NoAcceptedPresentationContexts.fail();
}
Ok(ClientAssociation {
presentation_contexts,
requestor_max_pdu_length: max_pdu_length,
acceptor_max_pdu_length,
socket,
buffer,
})
}
Pdu::AssociationRJ { result, source } => Rejected {
association_result: result,
association_source: source,
}
.fail(),
pdu @ Pdu::AbortRQ { .. }
| pdu @ Pdu::ReleaseRQ { .. }
| pdu @ Pdu::AssociationRQ { .. }
| pdu @ Pdu::PData { .. }
| pdu @ Pdu::ReleaseRP { .. } => {
// abort connection
let _ = write_pdu(
&mut buffer,
&Pdu::AbortRQ {
source: AbortRQSource::ServiceUser,
},
);
let _ = socket.write_all(&buffer);
UnexpectedResponse { pdu }.fail()
}
pdu @ Pdu::Unknown { .. } => {
// abort connection
let _ = write_pdu(
&mut buffer,
&Pdu::AbortRQ {
source: AbortRQSource::ServiceUser,
},
);
let _ = socket.write_all(&buffer);
UnknownResponse { pdu }.fail()
}
}
}
}
/// A DICOM upper level association from the perspective
/// of a requesting application entity.
///
/// The most common operations of an established association are
/// [`send`](Self::send)
/// and [`receive`](Self::receive).
/// Sending large P-Data fragments may be easier through the P-Data sender
/// abstraction (see [`send_pdata`](Self::send_pdata)).
///
/// When the value falls out of scope,
/// the program will automatically try to gracefully release the association
/// through a standard C-RELEASE message exchange,
/// then shut down the underlying TCP connection.
#[derive(Debug)]
pub struct ClientAssociation {
/// The presentation contexts accorded with the acceptor application entity,
/// without the rejected ones.
presentation_contexts: Vec<PresentationContextResult>,
/// The maximum PDU length that this application entity is expecting to receive
requestor_max_pdu_length: u32,
/// The maximum PDU length that the remote application entity accepts
acceptor_max_pdu_length: u32,
/// The TCP stream to the other DICOM node
socket: TcpStream,
/// Buffer to assemble PDU before sending it on wire
buffer: Vec<u8>,
}
impl ClientAssociation {
/// Retrieve the list of negotiated presentation contexts.
pub fn presentation_contexts(&self) -> &[PresentationContextResult] {
&self.presentation_contexts
}
/// Retrieve the maximum PDU length
/// admitted by the association acceptor.
pub fn acceptor_max_pdu_length(&self) -> u32 {
self.acceptor_max_pdu_length
}
/// Retrieve the maximum PDU length
/// that this application entity is expecting to receive.
///
/// The current implementation is not required to fail
/// and/or abort the association
/// if a larger PDU is received.
pub fn requestor_max_pdu_length(&self) -> u32 {
self.requestor_max_pdu_length
}
/// Send a PDU message to the other intervenient.
pub fn send(&mut self, msg: &Pdu) -> Result<()> {
self.buffer.clear();
write_pdu(&mut self.buffer, msg).context(Send)?;
if self.buffer.len() > self.acceptor_max_pdu_length as usize {
return SendTooLongPdu {
length: self.buffer.len(),
}
.fail();
}
self.socket.write_all(&self.buffer).context(WireSend)
}
/// Read a PDU message from the other intervenient.
pub fn receive(&mut self) -> Result<Pdu> {
read_pdu(&mut self.socket, self.requestor_max_pdu_length, true).context(Receive)
}
/// Gracefully terminate the association by exchanging release messages
/// and then shutting down the TCP connection.
pub fn release(mut self) -> Result<()> {
let out = self.release_impl();
let _ = self.socket.shutdown(std::net::Shutdown::Both);
out
}
/// Release implementation function,
/// which tries to send a release request and receive a release response.
/// This is in a separate private function because
/// terminating a connection should still close the connection
/// if the exchange fails.
/// Send an abort message and shut down the TCP connection,
/// terminating the association.
pub fn abort(mut self) -> Result<()> {
let pdu = Pdu::AbortRQ {
source: AbortRQSource::ServiceUser,
};
let out = self.send(&pdu);
let _ = self.socket.shutdown(std::net::Shutdown::Both);
out
}
/// Obtain access to the inner TCP stream
/// connected to the association acceptor.
///
/// This can be used to send the PDU in semantic fragments of the message,
/// thus using less memory.
///
/// **Note:** reading and writing should be done with care
/// to avoid inconsistencies in the association state.
/// Do not call `send` and `receive` while not in a PDU boundary.
pub fn inner_stream(&mut self) -> &mut TcpStream {
&mut self.socket
}
/// Prepare a P-Data writer for sending
/// one or more data items.
///
/// Returns a writer which automatically
/// splits the inner data into separate PDUs if necessary.
pub fn send_pdata(&mut self, presentation_context_id: u8) -> PDataWriter<&mut TcpStream> {
PDataWriter::new(
&mut self.socket,
presentation_context_id,
self.acceptor_max_pdu_length,
)
}
fn release_impl(&mut self) -> Result<()> {
let pdu = Pdu::ReleaseRQ;
self.send(&pdu)?;
let pdu =
read_pdu(&mut self.socket, self.requestor_max_pdu_length, true).context(Receive)?;
match pdu {
Pdu::ReleaseRP => {}
pdu @ Pdu::AbortRQ { .. }
| pdu @ Pdu::AssociationAC { .. }
| pdu @ Pdu::AssociationRJ { .. }
| pdu @ Pdu::AssociationRQ { .. }
| pdu @ Pdu::PData { .. }
| pdu @ Pdu::ReleaseRQ { .. } => return UnexpectedResponse { pdu }.fail(),
pdu @ Pdu::Unknown { .. } => return UnknownResponse { pdu }.fail(),
}
Ok(())
}
}
/// Automatically release the association and shut down the connection.
impl Drop for ClientAssociation {
fn drop(&mut self) {
let _ = self.release_impl();
let _ = self.socket.shutdown(std::net::Shutdown::Both);
}
}
|
use std::{
alloc::{self, AllocError},
ptr::NonNull,
};
pub struct LinearAllocator {
begin: *mut u8,
current: *mut u8,
end: *mut u8,
}
impl LinearAllocator {
const ALIGNMENT: usize = 16;
pub fn new(cap: usize) -> Self {
unsafe {
let cap = aligned_size(cap, 16);
let begin = alloc::alloc(alloc::Layout::from_size_align(cap, Self::ALIGNMENT).unwrap());
let end = begin.add(cap);
Self {
begin,
end,
current: begin,
}
}
}
/// # Safety
///
/// For each `allocate` a corresponding [rewind](LinearAllocator::rewind) must be called!
/// Rewind calls must be performed in the opposite order as the `allocate` calls!
pub unsafe fn allocate(&mut self, size: usize) -> Result<NonNull<[u8]>, AllocError> {
let size = aligned_size(size, 16);
let result = self.current;
let offset = self.end.offset_from(result);
if offset < size as isize {
return Err(AllocError);
}
self.current = self.current.add(size);
Ok(NonNull::new(std::slice::from_raw_parts_mut(result, size) as *mut _).unwrap())
}
pub fn rewind(&mut self, ptr: NonNull<u8>) {
unsafe {
assert!(self.current.offset_from(ptr.as_ptr()) >= 0
, "Trying to rewind to a point in front of `current`! This indicates that memory was freed in the wrong order!");
self.current = ptr.as_ptr();
}
}
pub fn current(&self) -> NonNull<u8> {
NonNull::new(self.current).unwrap()
}
}
impl Drop for LinearAllocator {
fn drop(&mut self) {
debug_assert!(
self.begin == self.current,
"Some memory has not been returned to the allocator"
);
unsafe {
let size = self.end.offset_from(self.begin);
alloc::dealloc(
self.begin,
alloc::Layout::from_size_align(size as usize, Self::ALIGNMENT).unwrap(),
);
}
}
}
#[inline]
pub fn aligned_size(size: usize, alignment: usize) -> usize {
debug_assert!(
(alignment & (alignment - 1)) == 0,
"Expected powers of two alignment"
);
(size + (alignment - 1)) & !(alignment - 1)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_can_alloc_linear() {
let mut alloc = LinearAllocator::new(1024);
unsafe {
let a = alloc.allocate(1024).unwrap();
alloc.rewind(NonNull::new_unchecked((*a.as_ptr()).as_mut_ptr()));
}
}
#[test]
fn test_can_alloc_linear_twice() {
let mut alloc = LinearAllocator::new(2048);
unsafe {
let a = alloc.allocate(512).unwrap();
let b = alloc.allocate(512).unwrap();
alloc.rewind(NonNull::new_unchecked((*b.as_ptr()).as_mut_ptr()));
alloc.rewind(NonNull::new_unchecked((*a.as_ptr()).as_mut_ptr()));
}
}
#[test]
#[should_panic]
fn linear_bad_rewind_is_panic() {
let mut alloc = LinearAllocator::new(2048);
unsafe {
let a = alloc.allocate(512).unwrap();
let b = alloc.allocate(512).unwrap();
// bad order, b should come first
alloc.rewind(NonNull::new_unchecked((*a.as_ptr()).as_mut_ptr()));
alloc.rewind(NonNull::new_unchecked((*b.as_ptr()).as_mut_ptr()));
}
}
}
|
fn main() {
let mut x = 100 ;
println!("x is {}", x );
x = 200 ;
println!("x is {}", x );
let name = get_person_name();
let mut age = get_person_age();
//
// 個々に色々な処理が入る
// 年齢が50以上だったら、50に入れ直す
if age > 50 {
age = 50 ;
}
//
println!("name is {}, age {}", name, age );
}
fn get_person_name() -> &'static str { "masuda" }
fn get_person_age() -> i32 { 50 }
fn test() {
let x = 100 ;
println!("x is {}", x );
let x = 200 ;
println!("x is {}", x );
}
|
// 2019-04-10
// Le smart pointer le plus habituel est la Box<T>, qui garde de la donnée sur
// le tas plutôt que sur la pile. C'est tout. On s'en sert :
// quand on ne connaît pas la taille d'un type à la compilation
// quand on a beaucoup de donnée dont on veut transférer l'ownership mais
// sans que ce soit copié.
// quand on veut posséder une valeur, mais le type a moins d'importance que
// le trait implémenté par le type
use List::{Cons, Nil};
fn main() {
// La syntaxe
// voici une box qui garde une valeur i32 sur le tas (heap)
// Le type est inféré par rustc, ici c'est le struct std::boxed::Box<i32>
let b = Box::new(5);
println!("b = {}", b);
// le tas sera nettoyé, et le pointeur supprimé, quand on sortira du scope
// Évidemment, on ne va pas se contenter d'une seule valeur
// De la récursivité, en veux-tu en voilà. Ce sont les CONS LISTS !
let liste = Cons(1,
Box::new(Cons(2,
Box::new(Cons(3,
Box::new(Nil)
))
))
);
println!("{:#?}", liste);
}
// Les élements d'une cons list sont :
// soit une cons list
// soit une valeur nulle, le Nil
// Normalement, une telle liste récursive a une taille infinie, c'est ingérable
// On utilise Box<List> pour limiter la taille de List
// Box<List> ne contient que des pointeurs, de taille connue
#[derive(Debug)]
enum List {
Cons(i32, Box<List>),
Nil,
}
|
/*
* A sample API conforming to the draft standard OGC API - Features - Part 1: Core
*
* This is a sample OpenAPI definition that conforms to the conformance classes \"Core\", \"GeoJSON\", \"HTML\" and \"OpenAPI 3.0\" of the draft standard \"OGC API - Features - Part 1: Core\". This example is a generic OGC API Features definition that uses path parameters to describe all feature collections and all features. The generic OpenAPI definition does not provide any details on the collections or the feature content. This information is only available from accessing the feature collection resources. There is [another example](ogcapi-features-1-example2.yaml) that specifies each collection explicitly.
*
* The version of the OpenAPI document: 1.0.0
* Contact: info@example.org
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FeatureGeoJson {
#[serde(rename = "type")]
pub _type: Type,
#[serde(rename = "geometry")]
pub geometry: crate::models::GeometryGeoJson,
#[serde(rename = "properties")]
pub properties: Option<serde_json::Value>,
#[serde(rename = "id", skip_serializing_if = "Option::is_none")]
pub id: Option<crate::models::OneOfstringinteger>,
#[serde(rename = "links", skip_serializing_if = "Option::is_none")]
pub links: Option<Vec<crate::models::Link>>,
}
impl FeatureGeoJson {
pub fn new(_type: Type, geometry: crate::models::GeometryGeoJson, properties: Option<serde_json::Value>) -> FeatureGeoJson {
FeatureGeoJson {
_type,
geometry,
properties,
id: None,
links: None,
}
}
}
///
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub enum Type {
#[serde(rename = "Feature")]
Feature,
}
|
#[doc = "Register `IER` reader"]
pub type R = crate::R<IER_SPEC>;
#[doc = "Register `IER` writer"]
pub type W = crate::W<IER_SPEC>;
#[doc = "Field `ADRDYIE` reader - ADRDYIE"]
pub type ADRDYIE_R = crate::BitReader;
#[doc = "Field `ADRDYIE` writer - ADRDYIE"]
pub type ADRDYIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EOSMPIE` reader - EOSMPIE"]
pub type EOSMPIE_R = crate::BitReader;
#[doc = "Field `EOSMPIE` writer - EOSMPIE"]
pub type EOSMPIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EOCIE` reader - EOCIE"]
pub type EOCIE_R = crate::BitReader;
#[doc = "Field `EOCIE` writer - EOCIE"]
pub type EOCIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EOSIE` reader - EOSIE"]
pub type EOSIE_R = crate::BitReader;
#[doc = "Field `EOSIE` writer - EOSIE"]
pub type EOSIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OVRIE` reader - OVRIE"]
pub type OVRIE_R = crate::BitReader;
#[doc = "Field `OVRIE` writer - OVRIE"]
pub type OVRIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AWD1IE` reader - AWD1IE"]
pub type AWD1IE_R = crate::BitReader;
#[doc = "Field `AWD1IE` writer - AWD1IE"]
pub type AWD1IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AWD2IE` reader - AWD2IE"]
pub type AWD2IE_R = crate::BitReader;
#[doc = "Field `AWD2IE` writer - AWD2IE"]
pub type AWD2IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AWD3IE` reader - AWD3IE"]
pub type AWD3IE_R = crate::BitReader;
#[doc = "Field `AWD3IE` writer - AWD3IE"]
pub type AWD3IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EOCALIE` reader - EOCALIE"]
pub type EOCALIE_R = crate::BitReader;
#[doc = "Field `EOCALIE` writer - EOCALIE"]
pub type EOCALIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CCRDYIE` reader - CCRDYIE"]
pub type CCRDYIE_R = crate::BitReader;
#[doc = "Field `CCRDYIE` writer - CCRDYIE"]
pub type CCRDYIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - ADRDYIE"]
#[inline(always)]
pub fn adrdyie(&self) -> ADRDYIE_R {
ADRDYIE_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - EOSMPIE"]
#[inline(always)]
pub fn eosmpie(&self) -> EOSMPIE_R {
EOSMPIE_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - EOCIE"]
#[inline(always)]
pub fn eocie(&self) -> EOCIE_R {
EOCIE_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - EOSIE"]
#[inline(always)]
pub fn eosie(&self) -> EOSIE_R {
EOSIE_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - OVRIE"]
#[inline(always)]
pub fn ovrie(&self) -> OVRIE_R {
OVRIE_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 7 - AWD1IE"]
#[inline(always)]
pub fn awd1ie(&self) -> AWD1IE_R {
AWD1IE_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - AWD2IE"]
#[inline(always)]
pub fn awd2ie(&self) -> AWD2IE_R {
AWD2IE_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - AWD3IE"]
#[inline(always)]
pub fn awd3ie(&self) -> AWD3IE_R {
AWD3IE_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 11 - EOCALIE"]
#[inline(always)]
pub fn eocalie(&self) -> EOCALIE_R {
EOCALIE_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 13 - CCRDYIE"]
#[inline(always)]
pub fn ccrdyie(&self) -> CCRDYIE_R {
CCRDYIE_R::new(((self.bits >> 13) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - ADRDYIE"]
#[inline(always)]
#[must_use]
pub fn adrdyie(&mut self) -> ADRDYIE_W<IER_SPEC, 0> {
ADRDYIE_W::new(self)
}
#[doc = "Bit 1 - EOSMPIE"]
#[inline(always)]
#[must_use]
pub fn eosmpie(&mut self) -> EOSMPIE_W<IER_SPEC, 1> {
EOSMPIE_W::new(self)
}
#[doc = "Bit 2 - EOCIE"]
#[inline(always)]
#[must_use]
pub fn eocie(&mut self) -> EOCIE_W<IER_SPEC, 2> {
EOCIE_W::new(self)
}
#[doc = "Bit 3 - EOSIE"]
#[inline(always)]
#[must_use]
pub fn eosie(&mut self) -> EOSIE_W<IER_SPEC, 3> {
EOSIE_W::new(self)
}
#[doc = "Bit 4 - OVRIE"]
#[inline(always)]
#[must_use]
pub fn ovrie(&mut self) -> OVRIE_W<IER_SPEC, 4> {
OVRIE_W::new(self)
}
#[doc = "Bit 7 - AWD1IE"]
#[inline(always)]
#[must_use]
pub fn awd1ie(&mut self) -> AWD1IE_W<IER_SPEC, 7> {
AWD1IE_W::new(self)
}
#[doc = "Bit 8 - AWD2IE"]
#[inline(always)]
#[must_use]
pub fn awd2ie(&mut self) -> AWD2IE_W<IER_SPEC, 8> {
AWD2IE_W::new(self)
}
#[doc = "Bit 9 - AWD3IE"]
#[inline(always)]
#[must_use]
pub fn awd3ie(&mut self) -> AWD3IE_W<IER_SPEC, 9> {
AWD3IE_W::new(self)
}
#[doc = "Bit 11 - EOCALIE"]
#[inline(always)]
#[must_use]
pub fn eocalie(&mut self) -> EOCALIE_W<IER_SPEC, 11> {
EOCALIE_W::new(self)
}
#[doc = "Bit 13 - CCRDYIE"]
#[inline(always)]
#[must_use]
pub fn ccrdyie(&mut self) -> CCRDYIE_W<IER_SPEC, 13> {
CCRDYIE_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 = "ADC interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ier::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ier::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct IER_SPEC;
impl crate::RegisterSpec for IER_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ier::R`](R) reader structure"]
impl crate::Readable for IER_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ier::W`](W) writer structure"]
impl crate::Writable for IER_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets IER to value 0"]
impl crate::Resettable for IER_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
pub trait Float {
fn sqrt(self) -> Self;
fn recip(self) -> Self;
}
macro_rules! impl_float {
($($t:ident),*) => {
$(impl Float for $t {
#[inline]
fn sqrt(self) -> $t {
self.sqrt()
}
#[inline]
fn recip(self) -> $t {
self.recip()
}
})*
}
}
impl_float!(f32, f64);
pub trait Zero {
fn zero() -> Self;
}
macro_rules! impl_zero {
($($t:ident),* => $z:expr) => {
$(impl Zero for $t {
fn zero() -> Self { $z }
})*
}
}
impl_zero!(u8, u16, u32, u64, i8, i16, i32, i64 => 0);
impl_zero!(f32, f64 => 0.0);
pub trait One {
fn one() -> Self;
}
macro_rules! impl_one {
($($t:ident),* => $o:expr) => {
$(impl One for $t {
fn one() -> Self { $o }
})*
}
}
impl_one!(u8, u16, u32, u64, i8, i16, i32, i64 => 1);
impl_one!(f32, f64 => 1.0);
pub trait ZeroByteEquivalent: Zero {}
macro_rules! impl_zbe {
($($t:ident),*) => {
$(impl ZeroByteEquivalent for $t {})*
}
}
impl_zbe!(u8, u16, u32, u64, i8, i16, i32, i64, f32, f64);
|
use riddle_image::*;
use std::env;
use std::fs::File;
const OUT_FILE: &str = "image-distance-field.out.png";
const FIELD_SCALE: f64 = 20.0;
fn main() -> Result<(), ImageError> {
let png_bytes = include_bytes!("sample.png");
let png_img = Image::load(&png_bytes[..], ImageFormat::Png)?;
println!("+ Image Loaded...");
let processed_img = filters::distance_field(png_img, FIELD_SCALE);
println!("+ Distance Field Calculated...");
let mut out_path = env::temp_dir();
out_path.push(OUT_FILE);
let out_file = File::create(out_path.clone())?;
processed_img.save(out_file, ImageFormat::Png)?;
println!("+ Image Saved ({:?})...", out_path);
println!("+ Done.");
Ok(())
}
|
#[doc = "Register `BSRR` writer"]
pub type W = crate::W<BSRR_SPEC>;
#[doc = "Port x set bit y (y= 0..15)\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BS0W_AW {
#[doc = "1: Sets the corresponding ODx bit"]
Set = 1,
}
impl From<BS0W_AW> for bool {
#[inline(always)]
fn from(variant: BS0W_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `BS0` writer - Port x set bit y (y= 0..15)"]
pub type BS0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, BS0W_AW>;
impl<'a, REG, const O: u8> BS0_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Sets the corresponding ODx bit"]
#[inline(always)]
pub fn set(self) -> &'a mut crate::W<REG> {
self.variant(BS0W_AW::Set)
}
}
#[doc = "Field `BS1` writer - Port x set bit y (y= 0..15)"]
pub use BS0_W as BS1_W;
#[doc = "Field `BS2` writer - Port x set bit y (y= 0..15)"]
pub use BS0_W as BS2_W;
#[doc = "Field `BS3` writer - Port x set bit y (y= 0..15)"]
pub use BS0_W as BS3_W;
#[doc = "Field `BS4` writer - Port x set bit y (y= 0..15)"]
pub use BS0_W as BS4_W;
#[doc = "Field `BS5` writer - Port x set bit y (y= 0..15)"]
pub use BS0_W as BS5_W;
#[doc = "Field `BS6` writer - Port x set bit y (y= 0..15)"]
pub use BS0_W as BS6_W;
#[doc = "Field `BS7` writer - Port x set bit y (y= 0..15)"]
pub use BS0_W as BS7_W;
#[doc = "Field `BS8` writer - Port x set bit y (y= 0..15)"]
pub use BS0_W as BS8_W;
#[doc = "Field `BS9` writer - Port x set bit y (y= 0..15)"]
pub use BS0_W as BS9_W;
#[doc = "Field `BS10` writer - Port x set bit y (y= 0..15)"]
pub use BS0_W as BS10_W;
#[doc = "Field `BS11` writer - Port x set bit y (y= 0..15)"]
pub use BS0_W as BS11_W;
#[doc = "Field `BS12` writer - Port x set bit y (y= 0..15)"]
pub use BS0_W as BS12_W;
#[doc = "Field `BS13` writer - Port x set bit y (y= 0..15)"]
pub use BS0_W as BS13_W;
#[doc = "Field `BS14` writer - Port x set bit y (y= 0..15)"]
pub use BS0_W as BS14_W;
#[doc = "Field `BS15` writer - Port x set bit y (y= 0..15)"]
pub use BS0_W as BS15_W;
#[doc = "Port x set bit y (y= 0..15)\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BR0W_AW {
#[doc = "1: Resets the corresponding ODx bit"]
Reset = 1,
}
impl From<BR0W_AW> for bool {
#[inline(always)]
fn from(variant: BR0W_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `BR0` writer - Port x set bit y (y= 0..15)"]
pub type BR0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, BR0W_AW>;
impl<'a, REG, const O: u8> BR0_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Resets the corresponding ODx bit"]
#[inline(always)]
pub fn reset(self) -> &'a mut crate::W<REG> {
self.variant(BR0W_AW::Reset)
}
}
#[doc = "Field `BR1` writer - Port x reset bit y (y = 0..15)"]
pub use BR0_W as BR1_W;
#[doc = "Field `BR2` writer - Port x reset bit y (y = 0..15)"]
pub use BR0_W as BR2_W;
#[doc = "Field `BR3` writer - Port x reset bit y (y = 0..15)"]
pub use BR0_W as BR3_W;
#[doc = "Field `BR4` writer - Port x reset bit y (y = 0..15)"]
pub use BR0_W as BR4_W;
#[doc = "Field `BR5` writer - Port x reset bit y (y = 0..15)"]
pub use BR0_W as BR5_W;
#[doc = "Field `BR6` writer - Port x reset bit y (y = 0..15)"]
pub use BR0_W as BR6_W;
#[doc = "Field `BR7` writer - Port x reset bit y (y = 0..15)"]
pub use BR0_W as BR7_W;
#[doc = "Field `BR8` writer - Port x reset bit y (y = 0..15)"]
pub use BR0_W as BR8_W;
#[doc = "Field `BR9` writer - Port x reset bit y (y = 0..15)"]
pub use BR0_W as BR9_W;
#[doc = "Field `BR10` writer - Port x reset bit y (y = 0..15)"]
pub use BR0_W as BR10_W;
#[doc = "Field `BR11` writer - Port x reset bit y (y = 0..15)"]
pub use BR0_W as BR11_W;
#[doc = "Field `BR12` writer - Port x reset bit y (y = 0..15)"]
pub use BR0_W as BR12_W;
#[doc = "Field `BR13` writer - Port x reset bit y (y = 0..15)"]
pub use BR0_W as BR13_W;
#[doc = "Field `BR14` writer - Port x reset bit y (y = 0..15)"]
pub use BR0_W as BR14_W;
#[doc = "Field `BR15` writer - Port x reset bit y (y = 0..15)"]
pub use BR0_W as BR15_W;
impl W {
#[doc = "Bit 0 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn bs0(&mut self) -> BS0_W<BSRR_SPEC, 0> {
BS0_W::new(self)
}
#[doc = "Bit 1 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn bs1(&mut self) -> BS1_W<BSRR_SPEC, 1> {
BS1_W::new(self)
}
#[doc = "Bit 2 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn bs2(&mut self) -> BS2_W<BSRR_SPEC, 2> {
BS2_W::new(self)
}
#[doc = "Bit 3 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn bs3(&mut self) -> BS3_W<BSRR_SPEC, 3> {
BS3_W::new(self)
}
#[doc = "Bit 4 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn bs4(&mut self) -> BS4_W<BSRR_SPEC, 4> {
BS4_W::new(self)
}
#[doc = "Bit 5 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn bs5(&mut self) -> BS5_W<BSRR_SPEC, 5> {
BS5_W::new(self)
}
#[doc = "Bit 6 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn bs6(&mut self) -> BS6_W<BSRR_SPEC, 6> {
BS6_W::new(self)
}
#[doc = "Bit 7 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn bs7(&mut self) -> BS7_W<BSRR_SPEC, 7> {
BS7_W::new(self)
}
#[doc = "Bit 8 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn bs8(&mut self) -> BS8_W<BSRR_SPEC, 8> {
BS8_W::new(self)
}
#[doc = "Bit 9 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn bs9(&mut self) -> BS9_W<BSRR_SPEC, 9> {
BS9_W::new(self)
}
#[doc = "Bit 10 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn bs10(&mut self) -> BS10_W<BSRR_SPEC, 10> {
BS10_W::new(self)
}
#[doc = "Bit 11 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn bs11(&mut self) -> BS11_W<BSRR_SPEC, 11> {
BS11_W::new(self)
}
#[doc = "Bit 12 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn bs12(&mut self) -> BS12_W<BSRR_SPEC, 12> {
BS12_W::new(self)
}
#[doc = "Bit 13 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn bs13(&mut self) -> BS13_W<BSRR_SPEC, 13> {
BS13_W::new(self)
}
#[doc = "Bit 14 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn bs14(&mut self) -> BS14_W<BSRR_SPEC, 14> {
BS14_W::new(self)
}
#[doc = "Bit 15 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn bs15(&mut self) -> BS15_W<BSRR_SPEC, 15> {
BS15_W::new(self)
}
#[doc = "Bit 16 - Port x set bit y (y= 0..15)"]
#[inline(always)]
#[must_use]
pub fn br0(&mut self) -> BR0_W<BSRR_SPEC, 16> {
BR0_W::new(self)
}
#[doc = "Bit 17 - Port x reset bit y (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn br1(&mut self) -> BR1_W<BSRR_SPEC, 17> {
BR1_W::new(self)
}
#[doc = "Bit 18 - Port x reset bit y (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn br2(&mut self) -> BR2_W<BSRR_SPEC, 18> {
BR2_W::new(self)
}
#[doc = "Bit 19 - Port x reset bit y (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn br3(&mut self) -> BR3_W<BSRR_SPEC, 19> {
BR3_W::new(self)
}
#[doc = "Bit 20 - Port x reset bit y (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn br4(&mut self) -> BR4_W<BSRR_SPEC, 20> {
BR4_W::new(self)
}
#[doc = "Bit 21 - Port x reset bit y (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn br5(&mut self) -> BR5_W<BSRR_SPEC, 21> {
BR5_W::new(self)
}
#[doc = "Bit 22 - Port x reset bit y (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn br6(&mut self) -> BR6_W<BSRR_SPEC, 22> {
BR6_W::new(self)
}
#[doc = "Bit 23 - Port x reset bit y (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn br7(&mut self) -> BR7_W<BSRR_SPEC, 23> {
BR7_W::new(self)
}
#[doc = "Bit 24 - Port x reset bit y (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn br8(&mut self) -> BR8_W<BSRR_SPEC, 24> {
BR8_W::new(self)
}
#[doc = "Bit 25 - Port x reset bit y (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn br9(&mut self) -> BR9_W<BSRR_SPEC, 25> {
BR9_W::new(self)
}
#[doc = "Bit 26 - Port x reset bit y (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn br10(&mut self) -> BR10_W<BSRR_SPEC, 26> {
BR10_W::new(self)
}
#[doc = "Bit 27 - Port x reset bit y (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn br11(&mut self) -> BR11_W<BSRR_SPEC, 27> {
BR11_W::new(self)
}
#[doc = "Bit 28 - Port x reset bit y (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn br12(&mut self) -> BR12_W<BSRR_SPEC, 28> {
BR12_W::new(self)
}
#[doc = "Bit 29 - Port x reset bit y (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn br13(&mut self) -> BR13_W<BSRR_SPEC, 29> {
BR13_W::new(self)
}
#[doc = "Bit 30 - Port x reset bit y (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn br14(&mut self) -> BR14_W<BSRR_SPEC, 30> {
BR14_W::new(self)
}
#[doc = "Bit 31 - Port x reset bit y (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn br15(&mut self) -> BR15_W<BSRR_SPEC, 31> {
BR15_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 = "GPIO port bit set/reset register\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 [`bsrr::W`](W). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct BSRR_SPEC;
impl crate::RegisterSpec for BSRR_SPEC {
type Ux = u32;
}
#[doc = "`write(|w| ..)` method takes [`bsrr::W`](W) writer structure"]
impl crate::Writable for BSRR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets BSRR to value 0"]
impl crate::Resettable for BSRR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[doc = "Register `CFGR` reader"]
pub type R = crate::R<CFGR_SPEC>;
#[doc = "Register `CFGR` writer"]
pub type W = crate::W<CFGR_SPEC>;
#[doc = "Field `CKSEL` reader - Clock selector"]
pub type CKSEL_R = crate::BitReader;
#[doc = "Field `CKSEL` writer - Clock selector"]
pub type CKSEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CKPOL` reader - Clock Polarity"]
pub type CKPOL_R = crate::FieldReader;
#[doc = "Field `CKPOL` writer - Clock Polarity"]
pub type CKPOL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `CKFLT` reader - Configurable digital filter for external clock"]
pub type CKFLT_R = crate::FieldReader;
#[doc = "Field `CKFLT` writer - Configurable digital filter for external clock"]
pub type CKFLT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `TRGFLT` reader - Configurable digital filter for trigger"]
pub type TRGFLT_R = crate::FieldReader;
#[doc = "Field `TRGFLT` writer - Configurable digital filter for trigger"]
pub type TRGFLT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `PRESC` reader - Clock prescaler"]
pub type PRESC_R = crate::FieldReader;
#[doc = "Field `PRESC` writer - Clock prescaler"]
pub type PRESC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `TRIGSEL` reader - Trigger selector"]
pub type TRIGSEL_R = crate::FieldReader;
#[doc = "Field `TRIGSEL` writer - Trigger selector"]
pub type TRIGSEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `TRIGEN` reader - Trigger enable and polarity"]
pub type TRIGEN_R = crate::FieldReader;
#[doc = "Field `TRIGEN` writer - Trigger enable and polarity"]
pub type TRIGEN_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `TIMOUT` reader - Timeout enable"]
pub type TIMOUT_R = crate::BitReader;
#[doc = "Field `TIMOUT` writer - Timeout enable"]
pub type TIMOUT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `WAVE` reader - Waveform shape"]
pub type WAVE_R = crate::BitReader;
#[doc = "Field `WAVE` writer - Waveform shape"]
pub type WAVE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `WAVPOL` reader - Waveform shape polarity"]
pub type WAVPOL_R = crate::BitReader;
#[doc = "Field `WAVPOL` writer - Waveform shape polarity"]
pub type WAVPOL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRELOAD` reader - Registers update mode"]
pub type PRELOAD_R = crate::BitReader;
#[doc = "Field `PRELOAD` writer - Registers update mode"]
pub type PRELOAD_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `COUNTMODE` reader - counter mode enabled"]
pub type COUNTMODE_R = crate::BitReader;
#[doc = "Field `COUNTMODE` writer - counter mode enabled"]
pub type COUNTMODE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ENC` reader - Encoder mode enable"]
pub type ENC_R = crate::BitReader;
#[doc = "Field `ENC` writer - Encoder mode enable"]
pub type ENC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - Clock selector"]
#[inline(always)]
pub fn cksel(&self) -> CKSEL_R {
CKSEL_R::new((self.bits & 1) != 0)
}
#[doc = "Bits 1:2 - Clock Polarity"]
#[inline(always)]
pub fn ckpol(&self) -> CKPOL_R {
CKPOL_R::new(((self.bits >> 1) & 3) as u8)
}
#[doc = "Bits 3:4 - Configurable digital filter for external clock"]
#[inline(always)]
pub fn ckflt(&self) -> CKFLT_R {
CKFLT_R::new(((self.bits >> 3) & 3) as u8)
}
#[doc = "Bits 6:7 - Configurable digital filter for trigger"]
#[inline(always)]
pub fn trgflt(&self) -> TRGFLT_R {
TRGFLT_R::new(((self.bits >> 6) & 3) as u8)
}
#[doc = "Bits 9:11 - Clock prescaler"]
#[inline(always)]
pub fn presc(&self) -> PRESC_R {
PRESC_R::new(((self.bits >> 9) & 7) as u8)
}
#[doc = "Bits 13:15 - Trigger selector"]
#[inline(always)]
pub fn trigsel(&self) -> TRIGSEL_R {
TRIGSEL_R::new(((self.bits >> 13) & 7) as u8)
}
#[doc = "Bits 17:18 - Trigger enable and polarity"]
#[inline(always)]
pub fn trigen(&self) -> TRIGEN_R {
TRIGEN_R::new(((self.bits >> 17) & 3) as u8)
}
#[doc = "Bit 19 - Timeout enable"]
#[inline(always)]
pub fn timout(&self) -> TIMOUT_R {
TIMOUT_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - Waveform shape"]
#[inline(always)]
pub fn wave(&self) -> WAVE_R {
WAVE_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - Waveform shape polarity"]
#[inline(always)]
pub fn wavpol(&self) -> WAVPOL_R {
WAVPOL_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - Registers update mode"]
#[inline(always)]
pub fn preload(&self) -> PRELOAD_R {
PRELOAD_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - counter mode enabled"]
#[inline(always)]
pub fn countmode(&self) -> COUNTMODE_R {
COUNTMODE_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - Encoder mode enable"]
#[inline(always)]
pub fn enc(&self) -> ENC_R {
ENC_R::new(((self.bits >> 24) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Clock selector"]
#[inline(always)]
#[must_use]
pub fn cksel(&mut self) -> CKSEL_W<CFGR_SPEC, 0> {
CKSEL_W::new(self)
}
#[doc = "Bits 1:2 - Clock Polarity"]
#[inline(always)]
#[must_use]
pub fn ckpol(&mut self) -> CKPOL_W<CFGR_SPEC, 1> {
CKPOL_W::new(self)
}
#[doc = "Bits 3:4 - Configurable digital filter for external clock"]
#[inline(always)]
#[must_use]
pub fn ckflt(&mut self) -> CKFLT_W<CFGR_SPEC, 3> {
CKFLT_W::new(self)
}
#[doc = "Bits 6:7 - Configurable digital filter for trigger"]
#[inline(always)]
#[must_use]
pub fn trgflt(&mut self) -> TRGFLT_W<CFGR_SPEC, 6> {
TRGFLT_W::new(self)
}
#[doc = "Bits 9:11 - Clock prescaler"]
#[inline(always)]
#[must_use]
pub fn presc(&mut self) -> PRESC_W<CFGR_SPEC, 9> {
PRESC_W::new(self)
}
#[doc = "Bits 13:15 - Trigger selector"]
#[inline(always)]
#[must_use]
pub fn trigsel(&mut self) -> TRIGSEL_W<CFGR_SPEC, 13> {
TRIGSEL_W::new(self)
}
#[doc = "Bits 17:18 - Trigger enable and polarity"]
#[inline(always)]
#[must_use]
pub fn trigen(&mut self) -> TRIGEN_W<CFGR_SPEC, 17> {
TRIGEN_W::new(self)
}
#[doc = "Bit 19 - Timeout enable"]
#[inline(always)]
#[must_use]
pub fn timout(&mut self) -> TIMOUT_W<CFGR_SPEC, 19> {
TIMOUT_W::new(self)
}
#[doc = "Bit 20 - Waveform shape"]
#[inline(always)]
#[must_use]
pub fn wave(&mut self) -> WAVE_W<CFGR_SPEC, 20> {
WAVE_W::new(self)
}
#[doc = "Bit 21 - Waveform shape polarity"]
#[inline(always)]
#[must_use]
pub fn wavpol(&mut self) -> WAVPOL_W<CFGR_SPEC, 21> {
WAVPOL_W::new(self)
}
#[doc = "Bit 22 - Registers update mode"]
#[inline(always)]
#[must_use]
pub fn preload(&mut self) -> PRELOAD_W<CFGR_SPEC, 22> {
PRELOAD_W::new(self)
}
#[doc = "Bit 23 - counter mode enabled"]
#[inline(always)]
#[must_use]
pub fn countmode(&mut self) -> COUNTMODE_W<CFGR_SPEC, 23> {
COUNTMODE_W::new(self)
}
#[doc = "Bit 24 - Encoder mode enable"]
#[inline(always)]
#[must_use]
pub fn enc(&mut self) -> ENC_W<CFGR_SPEC, 24> {
ENC_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 = "Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cfgr::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 [`cfgr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CFGR_SPEC;
impl crate::RegisterSpec for CFGR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`cfgr::R`](R) reader structure"]
impl crate::Readable for CFGR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`cfgr::W`](W) writer structure"]
impl crate::Writable for CFGR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CFGR to value 0"]
impl crate::Resettable for CFGR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not};
/// A bit-board for Score Four
///
/// ```
/// use score_four::BitBoard;
///
/// let b = BitBoard::new(0b1000_1000_1000_1000); // 4 beads in the most lower level
///
/// assert_eq!(b.popcnt(), 4);
/// ```
///
#[derive(PartialEq, PartialOrd, Clone, Copy, Debug, Default)]
pub struct BitBoard(pub u64);
/// An empty bitboard.
///
///
/// ```
/// use score_four::EMPTY;
///
/// assert_eq!(EMPTY.popcnt(), 0);
/// assert_eq!((!EMPTY).popcnt(), 64);
/// ```
///
pub const EMPTY: BitBoard = BitBoard(0);
macro_rules! from_each_level {
($arr: expr) => {
$arr[0] | ($arr[1] << 16) | ($arr[2] << 32) | ($arr[3] << 48)
};
}
impl BitBoard {
/// Construct a new bitboard instance from u64
pub fn new(b: u64) -> BitBoard {
BitBoard(b)
}
/// Construct a new bitboard representing a line at the given position
///
/// ```
/// use score_four::BitBoard;
///
/// let bb = BitBoard::line_at_pos(0);
///
/// assert_eq!(bb, BitBoard(281_4792_7174_3489));
/// ```
///
pub fn line_at_pos(_pos: u8) -> BitBoard {
let pos = 0b1 << _pos;
BitBoard(pos | (pos << 16) | (pos << 32) | (pos << 48))
}
/// Get the level at the given position
///
/// ```
/// use score_four::BitBoard;
///
/// let bb = BitBoard::line_at_pos(1);
///
/// assert_eq!(bb.get_level_at(1), 4);
/// ```
///
pub fn get_level_at(self, pos: u8) -> u8 {
(self & BitBoard::line_at_pos(pos)).0.count_ones() as u8
}
/// Count the numbers of beads in this bitboard
///
/// ```
/// use score_four::BitBoard;
///
/// let bb = BitBoard::new(u64::max_value());
///
/// assert_eq!(bb.popcnt(), 64);
/// ```
///
pub fn popcnt(self) -> u32 {
self.0.count_ones()
}
/// Check if a line has constructed
///
/// ```
/// use score_four::BitBoard;
///
/// let bb = BitBoard::new(0b1111);
///
/// assert!(bb.lined());
/// ```
///
pub fn lined(self) -> bool {
self.row_lined() || self.column_lined() || self.level_lined() || self.diagonal_lined()
}
/// Check there exists a lined row or not
///
/// ```
/// use score_four::BitBoard;
///
/// let bb = BitBoard::new(0b1111);
///
/// assert_eq!(bb.row_lined(), true);
///
/// let bb = BitBoard::new(0b0001_0001_0001_0001);
///
/// assert_eq!(bb.row_lined(), false);
/// ```
///
pub fn row_lined(self) -> bool {
for level in 0..4 {
for column in 0..4 {
let mask = BitBoard(0b1111 << (4 * column + 16 * level));
if mask == (self & mask) {
return true;
}
}
}
false
}
/// Check there exists a lined column or not
///
/// ```
/// use score_four::BitBoard;
///
/// let bb = BitBoard::new(0b0001_0001_0001_0001);
///
/// assert_eq!(bb.column_lined(), true);
///
/// let bb = BitBoard::new(0b1111);
///
/// assert_eq!(bb.column_lined(), false);
/// ```
///
pub fn column_lined(self) -> bool {
for level in 0..4 {
for row in 0..4 {
let mask = BitBoard(0b0001_0001_0001_0001 << (row + 16 * level));
if mask == (self & mask) {
return true;
}
}
}
false
}
/// Check there exists a lined column or not
///
/// ```
/// use score_four::BitBoard;
///
/// let bb = BitBoard::line_at_pos(1);
///
/// assert_eq!(bb.level_lined(), true);
///
/// let bb = BitBoard::new(0b1111);
///
/// assert_eq!(bb.level_lined(), false);
/// ```
///
pub fn level_lined(self) -> bool {
let line_tmpl = 0b0001 + (0b0001 << 16) + (0b0001 << 32) + (0b0001 << 48);
for row in 0..4 {
for column in 0..4 {
let mask = BitBoard(line_tmpl << (row + 4 * column));
if mask == (self & mask) {
return true;
}
}
}
false
}
/// Check there exists a lined diagonal or not
fn diagonal_2d_lined(self) -> bool {
let line_tmpl: [u64; 2] = [0b1000_0100_0010_0001, 0b0001_0010_0100_1000];
for level in 0..4 {
for _mask in line_tmpl.iter() {
let mask = BitBoard(_mask << (16 * level));
if mask == (self & mask) {
return true;
}
}
}
let line_tmpl: [u64; 2] = [
from_each_level!([
0b0000_0000_0000_0001,
0b0000_0000_0000_0010,
0b0000_0000_0000_0100,
0b0000_0000_0000_1000
]),
from_each_level!([
0b0000_0000_0000_1000,
0b0000_0000_0000_0100,
0b0000_0000_0000_0010,
0b0000_0000_0000_0001
]),
];
for row in 0..4 {
for _mask in line_tmpl.iter() {
let mask = BitBoard(_mask << (4 * row));
if mask == (self & mask) {
return true;
}
}
}
let line_tmpl: [u64; 2] = [
from_each_level!([
0b0000_0000_0000_0001,
0b0000_0000_0001_0000,
0b0000_0001_0000_0000,
0b0001_0000_0000_0000
]),
from_each_level!([
0b0001_0000_0000_0000,
0b0000_0001_0000_0000,
0b0000_0000_0001_0000,
0b0000_0000_0000_0001
]),
];
for column in 0..4 {
for _mask in line_tmpl.iter() {
let mask = BitBoard(_mask << column);
if mask == (self & mask) {
return true;
}
}
}
false
}
/// Check there exists a lined diagonal or not
fn diagonal_3d_lined(self) -> bool {
let line_tmpl = [
from_each_level!([
0b0000_0000_0000_0001,
0b0000_0000_0010_0000,
0b0000_0100_0000_0000,
0b1000_0000_0000_0000
]),
from_each_level!([
0b1000_0000_0000_0000,
0b0000_0100_0000_0000,
0b0000_0000_0010_0000,
0b0000_0000_0000_0001
]),
from_each_level!([
0b0000_0000_0000_1000,
0b0000_0000_0100_0000,
0b0000_0010_0000_0000,
0b0001_0000_0000_0000
]),
from_each_level!([
0b0001_0000_0000_0000,
0b0000_0010_0000_0000,
0b0000_0000_0100_0000,
0b0000_0000_0000_1000
]),
];
for _mask in line_tmpl.iter() {
let mask = BitBoard(*_mask);
if mask == (self & mask) {
return true;
}
}
false
}
/// Check there exists a lined diagonal or not
fn diagonal_lined(self) -> bool {
self.diagonal_2d_lined() || self.diagonal_3d_lined()
}
}
impl BitAnd for BitBoard {
type Output = BitBoard;
fn bitand(self, other: BitBoard) -> BitBoard {
BitBoard(self.0 & other.0)
}
}
impl BitOr for BitBoard {
type Output = BitBoard;
fn bitor(self, other: BitBoard) -> BitBoard {
BitBoard(self.0 | other.0)
}
}
impl BitAndAssign for BitBoard {
fn bitand_assign(&mut self, other: BitBoard) {
self.0 &= other.0
}
}
impl BitOrAssign for BitBoard {
fn bitor_assign(&mut self, other: BitBoard) {
self.0 |= other.0
}
}
impl Not for BitBoard {
type Output = BitBoard;
fn not(self) -> BitBoard {
BitBoard(!self.0)
}
}
|
use crate::{
gui::{make_dropdown_list_option, BuildContext, EditorUiNode, Ui, UiMessage, UiNode},
make_relative_path,
scene::commands::{
camera::{
SetCameraPreviewCommand, SetColorGradingEnabledCommand, SetColorGradingLutCommand,
SetExposureCommand, SetFovCommand, SetZFarCommand, SetZNearCommand,
},
SceneCommand,
},
send_sync_message,
sidebar::{
make_bool_input_field, make_f32_input_field, make_section, make_text_mark, COLUMN_WIDTH,
ROW_HEIGHT,
},
Message,
};
use rg3d::{
core::{futures::executor::block_on, pool::Handle, scope_profile},
engine::resource_manager::{ResourceManager, TextureImportOptions},
gui::{
dropdown_list::DropdownListBuilder,
grid::{Column, GridBuilder, Row},
image::ImageBuilder,
message::{
CheckBoxMessage, DropdownListMessage, ImageMessage, MessageDirection,
NumericUpDownMessage, UiMessageData, WidgetMessage,
},
stack_panel::StackPanelBuilder,
widget::WidgetBuilder,
},
resource::texture::CompressionOptions,
scene::{
camera::{ColorGradingLut, Exposure},
node::Node,
},
utils::into_gui_texture,
};
use std::sync::mpsc::Sender;
pub struct CameraSection {
pub section: Handle<UiNode>,
fov: Handle<UiNode>,
z_near: Handle<UiNode>,
z_far: Handle<UiNode>,
sender: Sender<Message>,
preview: Handle<UiNode>,
exposure_kind: Handle<UiNode>,
exposure_value: Handle<UiNode>,
key_value: Handle<UiNode>,
min_luminance: Handle<UiNode>,
max_luminance: Handle<UiNode>,
color_grading_lut: Handle<UiNode>,
use_color_grading: Handle<UiNode>,
manual_exposure_section: Handle<UiNode>,
auto_exposure_section: Handle<UiNode>,
}
impl CameraSection {
pub fn new(ctx: &mut BuildContext, sender: Sender<Message>) -> Self {
let fov;
let z_near;
let z_far;
let preview;
let exposure_kind;
let exposure_value;
let key_value;
let min_luminance;
let max_luminance;
let manual_exposure_section;
let auto_exposure_section;
let color_grading_lut;
let use_color_grading;
let section = make_section(
"Camera Properties",
StackPanelBuilder::new(
WidgetBuilder::new()
.with_child(
GridBuilder::new(
WidgetBuilder::new()
.with_child(make_text_mark(ctx, "FOV", 0))
.with_child({
fov = make_f32_input_field(
ctx,
0,
0.0,
std::f32::consts::PI,
0.01,
);
fov
})
.with_child(make_text_mark(ctx, "Z Near", 1))
.with_child({
z_near = make_f32_input_field(ctx, 1, 0.0, f32::MAX, 0.01);
z_near
})
.with_child(make_text_mark(ctx, "Z Far", 2))
.with_child({
z_far = make_f32_input_field(ctx, 2, 0.0, f32::MAX, 1.0);
z_far
})
.with_child(make_text_mark(ctx, "Preview", 3))
.with_child({
preview = make_bool_input_field(ctx, 3);
preview
})
.with_child(make_text_mark(ctx, "Use Color Grading", 4))
.with_child({
use_color_grading = make_bool_input_field(ctx, 4);
use_color_grading
})
.with_child(make_text_mark(ctx, "Color Grading LUT", 5))
.with_child({
color_grading_lut = ImageBuilder::new(
WidgetBuilder::new()
.on_row(5)
.on_column(1)
.with_allow_drop(true),
)
.build(ctx);
color_grading_lut
})
.with_child(make_text_mark(ctx, "Exposure Kind", 6))
.with_child({
exposure_kind = DropdownListBuilder::new(
WidgetBuilder::new().on_row(6).on_column(1),
)
.with_close_on_selection(true)
.with_items(vec![
make_dropdown_list_option(ctx, "Auto"),
make_dropdown_list_option(ctx, "Manual"),
])
.build(ctx);
exposure_kind
}),
)
.add_column(Column::strict(COLUMN_WIDTH))
.add_column(Column::stretch())
.add_row(Row::strict(ROW_HEIGHT))
.add_row(Row::strict(ROW_HEIGHT))
.add_row(Row::strict(ROW_HEIGHT))
.add_row(Row::strict(ROW_HEIGHT))
.add_row(Row::strict(ROW_HEIGHT))
.add_row(Row::strict(ROW_HEIGHT))
.add_row(Row::strict(ROW_HEIGHT))
.build(ctx),
)
.with_child(
StackPanelBuilder::new(
WidgetBuilder::new()
.with_child({
manual_exposure_section = make_section(
"Manual Exposure",
GridBuilder::new(
WidgetBuilder::new()
.with_child(make_text_mark(
ctx,
"Exposure Value",
0,
))
.with_child({
exposure_value = make_f32_input_field(
ctx,
0,
0.0,
f32::MAX,
1.0,
);
exposure_value
}),
)
.add_column(Column::strict(COLUMN_WIDTH))
.add_column(Column::stretch())
.add_row(Row::strict(ROW_HEIGHT))
.build(ctx),
ctx,
);
manual_exposure_section
})
.with_child({
auto_exposure_section = make_section(
"Auto Exposure",
GridBuilder::new(
WidgetBuilder::new()
.with_child(make_text_mark(ctx, "Key Value", 0))
.with_child({
key_value = make_f32_input_field(
ctx,
0,
0.001,
f32::MAX,
1.0,
);
key_value
})
.with_child(make_text_mark(ctx, "Min Luminance", 1))
.with_child({
min_luminance = make_f32_input_field(
ctx,
1,
0.001,
f32::MAX,
1.0,
);
min_luminance
})
.with_child(make_text_mark(ctx, "Max Luminance", 2))
.with_child({
max_luminance = make_f32_input_field(
ctx,
2,
0.0,
f32::MAX,
1.0,
);
max_luminance
}),
)
.add_column(Column::strict(COLUMN_WIDTH))
.add_column(Column::stretch())
.add_row(Row::strict(ROW_HEIGHT))
.add_row(Row::strict(ROW_HEIGHT))
.add_row(Row::strict(ROW_HEIGHT))
.build(ctx),
ctx,
);
auto_exposure_section
}),
)
.build(ctx),
),
)
.build(ctx),
ctx,
);
Self {
section,
fov,
z_near,
z_far,
sender,
preview,
exposure_kind,
exposure_value,
key_value,
min_luminance,
max_luminance,
auto_exposure_section,
manual_exposure_section,
color_grading_lut,
use_color_grading,
}
}
pub fn sync_to_model(&mut self, node: &Node, ui: &mut Ui) {
send_sync_message(
ui,
WidgetMessage::visibility(self.section, MessageDirection::ToWidget, node.is_camera()),
);
if let Node::Camera(camera) = node {
send_sync_message(
ui,
NumericUpDownMessage::value(self.fov, MessageDirection::ToWidget, camera.fov()),
);
send_sync_message(
ui,
NumericUpDownMessage::value(
self.z_near,
MessageDirection::ToWidget,
camera.z_near(),
),
);
send_sync_message(
ui,
NumericUpDownMessage::value(self.z_far, MessageDirection::ToWidget, camera.z_far()),
);
send_sync_message(
ui,
CheckBoxMessage::checked(
self.preview,
MessageDirection::ToWidget,
Some(camera.is_enabled()),
),
);
send_sync_message(
ui,
CheckBoxMessage::checked(
self.use_color_grading,
MessageDirection::ToWidget,
Some(camera.color_grading_enabled()),
),
);
send_sync_message(
ui,
ImageMessage::texture(
self.color_grading_lut,
MessageDirection::ToWidget,
camera
.color_grading_lut_ref()
.map(|lut| into_gui_texture(lut.unwrapped_lut().clone())),
),
);
match camera.exposure() {
Exposure::Auto {
key_value,
min_luminance,
max_luminance,
} => {
send_sync_message(
ui,
NumericUpDownMessage::value(
self.key_value,
MessageDirection::ToWidget,
key_value,
),
);
send_sync_message(
ui,
NumericUpDownMessage::value(
self.min_luminance,
MessageDirection::ToWidget,
min_luminance,
),
);
send_sync_message(
ui,
NumericUpDownMessage::value(
self.max_luminance,
MessageDirection::ToWidget,
max_luminance,
),
);
send_sync_message(
ui,
DropdownListMessage::selection(
self.exposure_kind,
MessageDirection::ToWidget,
Some(0),
),
);
send_sync_message(
ui,
WidgetMessage::visibility(
self.auto_exposure_section,
MessageDirection::ToWidget,
true,
),
);
send_sync_message(
ui,
WidgetMessage::visibility(
self.manual_exposure_section,
MessageDirection::ToWidget,
false,
),
);
}
Exposure::Manual(value) => {
send_sync_message(
ui,
NumericUpDownMessage::value(
self.exposure_value,
MessageDirection::ToWidget,
value,
),
);
send_sync_message(
ui,
DropdownListMessage::selection(
self.exposure_kind,
MessageDirection::ToWidget,
Some(1),
),
);
send_sync_message(
ui,
WidgetMessage::visibility(
self.auto_exposure_section,
MessageDirection::ToWidget,
false,
),
);
send_sync_message(
ui,
WidgetMessage::visibility(
self.manual_exposure_section,
MessageDirection::ToWidget,
true,
),
);
}
}
}
}
pub fn handle_ui_message(
&mut self,
message: &UiMessage,
node: &Node,
handle: Handle<Node>,
ui: &Ui,
resource_manager: ResourceManager,
) {
scope_profile!();
if let Node::Camera(camera) = node {
match *message.data() {
UiMessageData::NumericUpDown(NumericUpDownMessage::Value(value)) => {
if message.destination() == self.fov && camera.fov().ne(&value) {
self.sender
.send(Message::DoSceneCommand(SceneCommand::SetFov(
SetFovCommand::new(handle, value),
)))
.unwrap();
} else if message.destination() == self.z_far && camera.z_far().ne(&value) {
self.sender
.send(Message::DoSceneCommand(SceneCommand::SetZFar(
SetZFarCommand::new(handle, value),
)))
.unwrap();
} else if message.destination() == self.z_near && camera.z_near().ne(&value) {
self.sender
.send(Message::DoSceneCommand(SceneCommand::SetZNear(
SetZNearCommand::new(handle, value),
)))
.unwrap();
} else if message.destination() == self.exposure_value {
self.sender
.send(Message::DoSceneCommand(SceneCommand::SetExposure(
SetExposureCommand::new(handle, Exposure::Manual(value)),
)))
.unwrap();
} else if message.destination() == self.key_value {
let mut current_auto_exposure = camera.exposure().clone();
if let Exposure::Auto {
ref mut key_value, ..
} = current_auto_exposure
{
*key_value = value;
}
self.sender
.send(Message::DoSceneCommand(SceneCommand::SetExposure(
SetExposureCommand::new(handle, current_auto_exposure),
)))
.unwrap();
} else if message.destination() == self.min_luminance {
let mut current_auto_exposure = camera.exposure().clone();
if let Exposure::Auto {
ref mut min_luminance,
..
} = current_auto_exposure
{
*min_luminance = value;
}
self.sender
.send(Message::DoSceneCommand(SceneCommand::SetExposure(
SetExposureCommand::new(handle, current_auto_exposure),
)))
.unwrap();
} else if message.destination() == self.min_luminance {
let mut current_auto_exposure = camera.exposure().clone();
if let Exposure::Auto {
ref mut max_luminance,
..
} = current_auto_exposure
{
*max_luminance = value;
}
self.sender
.send(Message::DoSceneCommand(SceneCommand::SetExposure(
SetExposureCommand::new(handle, current_auto_exposure),
)))
.unwrap();
}
}
UiMessageData::CheckBox(CheckBoxMessage::Check(value)) => {
if message.destination() == self.preview
&& camera.is_enabled().ne(&value.unwrap())
{
self.sender
.send(Message::DoSceneCommand(SceneCommand::SetCameraActive(
SetCameraPreviewCommand::new(handle, value.unwrap_or(false)),
)))
.unwrap();
} else if message.destination() == self.use_color_grading {
self.sender
.send(Message::DoSceneCommand(
SceneCommand::SetColorGradingEnabled(
SetColorGradingEnabledCommand::new(
handle,
value.unwrap_or_default(),
),
),
))
.unwrap();
}
}
UiMessageData::DropdownList(DropdownListMessage::SelectionChanged(Some(index))) => {
if message.destination() == self.exposure_kind {
let exposure = match index {
0 => Exposure::default(),
1 => Exposure::Manual(1.0),
_ => unreachable!(),
};
self.sender
.send(Message::DoSceneCommand(SceneCommand::SetExposure(
SetExposureCommand::new(handle, exposure),
)))
.unwrap();
}
}
UiMessageData::Widget(WidgetMessage::Drop(dropped)) => {
if message.destination() == self.color_grading_lut {
if let UiNode::User(EditorUiNode::AssetItem(item)) = ui.node(dropped) {
let relative_path = make_relative_path(&item.path);
match block_on(ColorGradingLut::new(
resource_manager.request_texture(
relative_path,
Some(
TextureImportOptions::default()
.with_compression(CompressionOptions::NoCompression),
),
),
)) {
Ok(lut) => {
self.sender
.send(Message::DoSceneCommand(
SceneCommand::SetColorGradingLut(
SetColorGradingLutCommand::new(handle, Some(lut)),
),
))
.unwrap();
}
Err(e) => self
.sender
.send(Message::Log(format!(
"Failed to load color grading look-up texture. Reason: {}",
e
)))
.unwrap(),
}
}
}
}
_ => {}
}
}
}
}
|
#[doc = "Register `SR` reader"]
pub type R = crate::R<SR_SPEC>;
#[doc = "Register `SR` writer"]
pub type W = crate::W<SR_SPEC>;
#[doc = "Field `DAC1RDY` reader - DAC channel1 ready status bit This bit is set and cleared by hardware."]
pub type DAC1RDY_R = crate::BitReader;
#[doc = "Field `DORSTAT1` reader - DAC channel1 output register status bit This bit is set and cleared by hardware. It is applicable only when the DAC operates in Double data mode."]
pub type DORSTAT1_R = crate::BitReader;
#[doc = "Field `DMAUDR1` reader - DAC channel1 DMA underrun flag This bit is set by hardware and cleared by software (by writing it to 1)."]
pub type DMAUDR1_R = crate::BitReader;
#[doc = "Field `DMAUDR1` writer - DAC channel1 DMA underrun flag This bit is set by hardware and cleared by software (by writing it to 1)."]
pub type DMAUDR1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CAL_FLAG1` reader - DAC channel1 calibration offset status This bit is set and cleared by hardware"]
pub type CAL_FLAG1_R = crate::BitReader;
#[doc = "Field `BWST1` reader - DAC channel1 busy writing sample time flag This bit is systematically set just after Sample and hold mode enable and is set each time the software writes the register DAC_SHSR1, It is cleared by hardware when the write operation of DAC_SHSR1 is complete. (It takes about 3 LSI/LSE periods of synchronization)."]
pub type BWST1_R = crate::BitReader;
#[doc = "Field `DAC2RDY` reader - DAC channel2 ready status bit This bit is set and cleared by hardware. Note: This bit is available only on dual-channel DACs. Refer to implementation."]
pub type DAC2RDY_R = crate::BitReader;
#[doc = "Field `DORSTAT2` reader - DAC channel2 output register status bit This bit is set and cleared by hardware. It is applicable only when the DAC operates in Double data mode. Note: This bit is available only on dual-channel DACs. Refer to implementation."]
pub type DORSTAT2_R = crate::BitReader;
#[doc = "Field `DMAUDR2` reader - DAC channel2 DMA underrun flag This bit is set by hardware and cleared by software (by writing it to 1). Note: This bit is available only on dual-channel DACs. Refer to implementation."]
pub type DMAUDR2_R = crate::BitReader;
#[doc = "Field `DMAUDR2` writer - DAC channel2 DMA underrun flag This bit is set by hardware and cleared by software (by writing it to 1). Note: This bit is available only on dual-channel DACs. Refer to implementation."]
pub type DMAUDR2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CAL_FLAG2` reader - DAC channel2 calibration offset status This bit is set and cleared by hardware Note: This bit is available only on dual-channel DACs. Refer to implementation."]
pub type CAL_FLAG2_R = crate::BitReader;
#[doc = "Field `BWST2` reader - DAC channel2 busy writing sample time flag This bit is systematically set just after Sample and hold mode enable. It is set each time the software writes the register DAC_SHSR2, It is cleared by hardware when the write operation of DAC_SHSR2 is complete. (It takes about 3 LSI/LSE periods of synchronization). Note: This bit is available only on dual-channel DACs. Refer to implementation."]
pub type BWST2_R = crate::BitReader;
impl R {
#[doc = "Bit 11 - DAC channel1 ready status bit This bit is set and cleared by hardware."]
#[inline(always)]
pub fn dac1rdy(&self) -> DAC1RDY_R {
DAC1RDY_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - DAC channel1 output register status bit This bit is set and cleared by hardware. It is applicable only when the DAC operates in Double data mode."]
#[inline(always)]
pub fn dorstat1(&self) -> DORSTAT1_R {
DORSTAT1_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - DAC channel1 DMA underrun flag This bit is set by hardware and cleared by software (by writing it to 1)."]
#[inline(always)]
pub fn dmaudr1(&self) -> DMAUDR1_R {
DMAUDR1_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - DAC channel1 calibration offset status This bit is set and cleared by hardware"]
#[inline(always)]
pub fn cal_flag1(&self) -> CAL_FLAG1_R {
CAL_FLAG1_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - DAC channel1 busy writing sample time flag This bit is systematically set just after Sample and hold mode enable and is set each time the software writes the register DAC_SHSR1, It is cleared by hardware when the write operation of DAC_SHSR1 is complete. (It takes about 3 LSI/LSE periods of synchronization)."]
#[inline(always)]
pub fn bwst1(&self) -> BWST1_R {
BWST1_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 27 - DAC channel2 ready status bit This bit is set and cleared by hardware. Note: This bit is available only on dual-channel DACs. Refer to implementation."]
#[inline(always)]
pub fn dac2rdy(&self) -> DAC2RDY_R {
DAC2RDY_R::new(((self.bits >> 27) & 1) != 0)
}
#[doc = "Bit 28 - DAC channel2 output register status bit This bit is set and cleared by hardware. It is applicable only when the DAC operates in Double data mode. Note: This bit is available only on dual-channel DACs. Refer to implementation."]
#[inline(always)]
pub fn dorstat2(&self) -> DORSTAT2_R {
DORSTAT2_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 29 - DAC channel2 DMA underrun flag This bit is set by hardware and cleared by software (by writing it to 1). Note: This bit is available only on dual-channel DACs. Refer to implementation."]
#[inline(always)]
pub fn dmaudr2(&self) -> DMAUDR2_R {
DMAUDR2_R::new(((self.bits >> 29) & 1) != 0)
}
#[doc = "Bit 30 - DAC channel2 calibration offset status This bit is set and cleared by hardware Note: This bit is available only on dual-channel DACs. Refer to implementation."]
#[inline(always)]
pub fn cal_flag2(&self) -> CAL_FLAG2_R {
CAL_FLAG2_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - DAC channel2 busy writing sample time flag This bit is systematically set just after Sample and hold mode enable. It is set each time the software writes the register DAC_SHSR2, It is cleared by hardware when the write operation of DAC_SHSR2 is complete. (It takes about 3 LSI/LSE periods of synchronization). Note: This bit is available only on dual-channel DACs. Refer to implementation."]
#[inline(always)]
pub fn bwst2(&self) -> BWST2_R {
BWST2_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 13 - DAC channel1 DMA underrun flag This bit is set by hardware and cleared by software (by writing it to 1)."]
#[inline(always)]
#[must_use]
pub fn dmaudr1(&mut self) -> DMAUDR1_W<SR_SPEC, 13> {
DMAUDR1_W::new(self)
}
#[doc = "Bit 29 - DAC channel2 DMA underrun flag This bit is set by hardware and cleared by software (by writing it to 1). Note: This bit is available only on dual-channel DACs. Refer to implementation."]
#[inline(always)]
#[must_use]
pub fn dmaudr2(&mut self) -> DMAUDR2_W<SR_SPEC, 29> {
DMAUDR2_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 = "DAC status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr::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 [`sr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SR_SPEC;
impl crate::RegisterSpec for SR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`sr::R`](R) reader structure"]
impl crate::Readable for SR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`sr::W`](W) writer structure"]
impl crate::Writable for SR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets SR to value 0"]
impl crate::Resettable for SR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//
// imports
//
use hw::max31855::Thermocouple;
use hw::gpio::{Pin, Direction, State};
use std::time::{Instant, Duration};
use std::thread::sleep;
//
// constants
//
const HEAT_THRESHOLD: f32 = 0.5; // start heating when we fall this far below the temperature
const COOL_THRESHOLD: f32 = 0.0; // start cooling when we reach this far above the temperature
const STEP_PERIOD: u32 = 1000000000; // desired step period in nanoseconds
const THERMOCOUPLE_CORRECTION: f32 = -3.0; // correction constant for the thermocouple
//
// SousVide structure
//
// Holds the state of the sousvide.
//
pub struct SousVide {
thermocouple: Thermocouple, // the thermocouple in use
pump: Pin, // the pin that controls the pump
heater: Pin, // the pin that contorls the heater
set_temp: Option<f32>, // the desired temperature
cur_temp: Option<f32>, // the current temperature
pump_state: bool, // the current state of the pump
heater_state: bool, // the current state of the heater
}
impl SousVide {
//
// constructor for new sousvides
//
pub fn new(tc_dev: &str, pump_pin: u8, heater_pin: u8) -> SousVide {
let mut sv = SousVide {
thermocouple: Thermocouple::open(tc_dev).unwrap(),
pump: Pin::open(pump_pin, Direction::Out).unwrap(),
heater: Pin::open(heater_pin, Direction::Out).unwrap(),
set_temp: None,
cur_temp: None,
pump_state: false,
heater_state: false,
};
// default the pump and heater to off
sv.set_pump_state(false);
sv.set_heater_state(false);
sv
}
//
// clear_set_temp() - clears the set_temp, therby disabling the sousvide
//
pub fn clear_set_temp(&mut self) {
println!("set_temp: Cleared");
self.set_temp = None;
}
//
// change_set_temp(f32) - changes the set_temp
//
pub fn change_set_temp(&mut self, set_temp: f32) {
println!("set_temp: {}", set_temp);
self.set_temp = Some(set_temp)
}
//
// getters for current state
//
pub fn get_set_temp(&self) -> Option<f32> { self.set_temp }
pub fn get_cur_temp(&self) -> Option<f32> { self.cur_temp }
pub fn get_pump_state(&self) -> bool { self.pump_state }
pub fn get_heater_state(&self) -> bool { self.heater_state }
//
// setup() - performs one-time setup
//
pub fn setup(&mut self) {
// wait for thermocoupler chip to stabilize
sleep(Duration::from_millis(500));
}
//
// step() - updates the state of the sousvide and returns time until next step should occur
//
pub fn step(&mut self) -> Option<Duration> {
let step_start = Instant::now();
// get the current temperature
self.cur_temp = self.thermocouple.read_sample().ok().map(|t| { t.get_temp_fahrenheit().unwrap() + THERMOCOUPLE_CORRECTION });
if self.cur_temp.is_some() {
println!("cur_temp: {}", self.cur_temp.unwrap());
} else {
println!("cur_temp: Unknown");
}
// if the temp can't be read, or the set_temp isn't set
if self.set_temp.is_none() || self.cur_temp.is_none() {
// make sure the pump and heater are off
self.set_pump_state(false);
self.set_heater_state(false);
// otherwise
} else {
// make sure the pump is on
self.set_pump_state(true);
// if we are too cold, start heating
if self.set_temp.unwrap() - self.cur_temp.unwrap() > HEAT_THRESHOLD {
self.set_heater_state(true);
}
// if we are too hot, stop heating
if self.cur_temp.unwrap() - self.set_temp.unwrap() > COOL_THRESHOLD {
self.set_heater_state(false);
}
}
// calculate and return delay before next step
let step_end = Instant::now();
let step_duration = step_end.duration_from_earlier(step_start);
if step_duration.as_secs() == 0 && step_duration.subsec_nanos() < STEP_PERIOD {
Some(Duration::new(0, STEP_PERIOD - step_duration.subsec_nanos()))
} else {
None
}
}
//
// set_heater_state(bool) - change the heater state, if necessary
//
fn set_heater_state(&mut self, state: bool) {
if self.heater_state != state {
println!("heater: {}", state);
self.heater.set_state(if state { State::High } else { State::Low }).unwrap();
self.heater_state = state;
}
}
//
// set_pump_state(bool) - change the pump state, if necessary
//
fn set_pump_state(&mut self, state: bool) {
if self.pump_state != state {
println!("pump: {}", state);
self.pump.set_state(if state { State::High } else { State::Low }).unwrap();
self.pump_state = state;
}
}
}
|
use anyhow::{bail, Context, Result};
use fs_err as fs;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
/// The `[lib]` section of a Cargo.toml
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "kebab-case")]
pub(crate) struct CargoTomlLib {
pub(crate) crate_type: Option<Vec<String>>,
pub(crate) name: Option<String>,
}
/// The `[package]` section of a Cargo.toml
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "kebab-case")]
pub(crate) struct CargoTomlPackage {
pub(crate) name: String,
metadata: Option<CargoTomlMetadata>,
}
/// Extract of the Cargo.toml that can be reused for the python metadata
///
/// See https://doc.rust-lang.org/cargo/reference/manifest.html for a specification
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CargoToml {
pub(crate) lib: Option<CargoTomlLib>,
pub(crate) package: CargoTomlPackage,
}
impl CargoToml {
/// Reads and parses the Cargo.toml at the given location
pub fn from_path(manifest_file: impl AsRef<Path>) -> Result<Self> {
let contents = fs::read_to_string(&manifest_file).context(format!(
"Can't read Cargo.toml at {}",
manifest_file.as_ref().display(),
))?;
let cargo_toml = toml::from_str(&contents).context(format!(
"Failed to parse Cargo.toml at {}",
manifest_file.as_ref().display()
))?;
Ok(cargo_toml)
}
/// Returns the value of `[project.metadata.maturin]` or an empty stub
pub fn remaining_core_metadata(&self) -> RemainingCoreMetadata {
match &self.package.metadata {
Some(CargoTomlMetadata {
maturin: Some(extra_metadata),
}) => extra_metadata.clone(),
_ => Default::default(),
}
}
/// Check removed python metadata support in `Cargo.toml`
pub fn check_removed_python_metadata(&self) -> Result<()> {
let mut removed = Vec::new();
if let Some(CargoTomlMetadata {
maturin: Some(extra_metadata),
}) = &self.package.metadata
{
let removed_keys = [
"scripts",
"classifiers",
"classifier",
"data",
"maintainer",
"maintainer-email",
"requires-dist",
"requires-python",
"requires-external",
"project-url",
"provides-extra",
"description-content-type",
];
for key in removed_keys {
if extra_metadata.other.contains_key(key) {
removed.push(key);
}
}
}
if !removed.is_empty() {
bail!(
"The following metadata fields in `package.metadata.maturin` section \
of Cargo.toml are removed since maturin 0.14.0: {}, \
please set them in pyproject.toml as PEP 621 specifies.",
removed.join(", ")
);
}
Ok(())
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "kebab-case")]
struct CargoTomlMetadata {
maturin: Option<RemainingCoreMetadata>,
}
/// The `[project.metadata.maturin]` with the maturin specific metadata
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
#[serde(rename_all = "kebab-case")]
pub struct RemainingCoreMetadata {
#[serde(flatten)]
pub other: HashMap<String, toml::Value>,
}
#[cfg(test)]
mod test {
use super::*;
use indoc::indoc;
#[test]
fn test_metadata_from_cargo_toml() {
let cargo_toml = indoc!(
r#"
[package]
authors = ["konstin <konstin@mailbox.org>"]
name = "info-project"
version = "0.1.0"
description = "A test project"
homepage = "https://example.org"
keywords = ["ffi", "test"]
[lib]
crate-type = ["cdylib"]
name = "pyo3_pure"
[package.metadata.maturin.scripts]
ph = "maturin:print_hello"
[package.metadata.maturin]
classifiers = ["Programming Language :: Python"]
requires-dist = ["flask~=1.1.0", "toml==0.10.0"]
[[package.metadata.maturin.targets]]
name = "pyo3_pure"
kind = "lib"
bindings = "pyo3"
"#
);
let cargo_toml: Result<CargoToml, _> = toml::from_str(cargo_toml);
assert!(cargo_toml.is_ok());
}
#[test]
fn test_metadata_from_cargo_toml_without_authors() {
let cargo_toml = indoc!(
r#"
[package]
name = "info-project"
version = "0.1.0"
description = "A test project"
homepage = "https://example.org"
keywords = ["ffi", "test"]
[lib]
crate-type = ["cdylib"]
name = "pyo3_pure"
[package.metadata.maturin.scripts]
ph = "maturin:print_hello"
[package.metadata.maturin]
classifiers = ["Programming Language :: Python"]
requires-dist = ["flask~=1.1.0", "toml==0.10.0"]
"#
);
let cargo_toml: Result<CargoToml, _> = toml::from_str(cargo_toml);
assert!(cargo_toml.is_ok());
}
}
|
use std::{
fmt,
};
use amethyst::{
core::transform::components::Transform,
};
use crate::resources::RenderConfig;
use super::{
ChunkIndex, Planet, GameWorldError, TileError,
};
/// The Index of a tile in a [Chunk](struct.Chunk.html).
/// Used to calculate the render-position of a tile,
/// and to figure out which tile the player currently stands on.
///
/// Uses (rows, columns).
#[derive(PartialEq, Eq, Copy, Clone, PartialOrd, Ord, Hash, Debug, Serialize, Deserialize)]
pub struct TileIndex(pub u64, pub u64);
impl TileIndex {
/// Convenience function returning only the TileIndex. Best used when Chunk Index is known
#[allow(dead_code)]
pub fn from_transform(
transform: &Transform,
chunk_index: ChunkIndex,
render_config: &RenderConfig,
planet: &Planet,
) -> Result<Self, GameWorldError> {
let x_transl = transform.translation().x;
let y_transl = transform.translation().y;
let tile_width_f32 = render_config.tile_size.1;
let tile_height_f32 = render_config.tile_size.0;
let chunk_width_f32 = planet.chunk_dim.1 as f32 * tile_width_f32;
let chunk_height_f32 = planet.chunk_dim.0 as f32 * tile_height_f32;
let chunk_offset_x = chunk_index.1 as f32 * chunk_width_f32;
let chunk_offset_y = chunk_index.0 as f32 * chunk_height_f32;
let x_chunk_transl = x_transl - (chunk_offset_x);
let y_chunk_transl = y_transl - (chunk_offset_y);
// Supposedly more accurate, but is it necessary?
/*let x_chunk_transl = chunk_x.mul_add(-chunk_width_f32, x_transl);
let y_chunk_transl = chunk_y.mul_add(-chunk_height_f32, y_transl);*/
let tile_id_x_f32 = (x_chunk_transl / tile_width_f32).trunc();
let tile_id_y_f32 = (y_chunk_transl / tile_height_f32).trunc();
let tile_id_x = tile_id_x_f32.trunc() as u64;
let tile_id_y = tile_id_y_f32.trunc() as u64;
if tile_id_x_f32.is_sign_negative()
|| tile_id_y_f32.is_sign_negative()
|| tile_id_x >= planet.chunk_dim.1
|| tile_id_y >= planet.chunk_dim.0
{
return Err(GameWorldError::TileProblem(TileError::IndexOutOfBounds));
}
Ok(TileIndex(tile_id_y, tile_id_x))
}
}
impl fmt::Display for TileIndex {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("TileIndex(")?;
fmt.write_str(&self.0.to_string())?;
fmt.write_str(", ")?;
fmt.write_str(&self.1.to_string())?;
fmt.write_str(")")?;
Ok(())
}
} |
fn main() {
let (mut ans, mut max_cnt) = (0, 0);
for i in 1..1_000_001 {
let mut cnt = 0;
let mut tmp: i64 = i;
while tmp != 1 {
if tmp % 2 == 1 {
tmp += tmp * 2 + 1;
} else {
tmp /= 2;
}
cnt += 1;
}
if max_cnt < cnt {
max_cnt = cnt;
ans = i;
}
}
println!("{}", ans);
}
|
#[doc = "Reader of register STGENR_CNTCVL"]
pub type R = crate::R<u32, super::STGENR_CNTCVL>;
#[doc = "Reader of field `CNTCVL_L_32`"]
pub type CNTCVL_L_32_R = crate::R<u32, u32>;
impl R {
#[doc = "Bits 0:31 - CNTCVL_L_32"]
#[inline(always)]
pub fn cntcvl_l_32(&self) -> CNTCVL_L_32_R {
CNTCVL_L_32_R::new((self.bits & 0xffff_ffff) as u32)
}
}
|
extern crate makeiter;
use makeiter::{make_iter,FuncIter};
pub fn main() {
println!("{}", FuncIter::new(|| Some(3u)).next());
println!("{}", make_iter(|| Some(3u)).next());
}
|
pub mod index;
pub mod images; |
#[doc = "Register `GRXSTSP_Device` reader"]
pub type R = crate::R<GRXSTSP_DEVICE_SPEC>;
#[doc = "Field `EPNUM` reader - Endpoint number"]
pub type EPNUM_R = crate::FieldReader;
#[doc = "Field `BCNT` reader - Byte count"]
pub type BCNT_R = crate::FieldReader<u16>;
#[doc = "Field `DPID` reader - Data PID"]
pub type DPID_R = crate::FieldReader;
#[doc = "Field `PKTSTS` reader - Packet status"]
pub type PKTSTS_R = crate::FieldReader;
#[doc = "Field `FRMNUM` reader - Frame number"]
pub type FRMNUM_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:3 - Endpoint number"]
#[inline(always)]
pub fn epnum(&self) -> EPNUM_R {
EPNUM_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 4:14 - Byte count"]
#[inline(always)]
pub fn bcnt(&self) -> BCNT_R {
BCNT_R::new(((self.bits >> 4) & 0x07ff) as u16)
}
#[doc = "Bits 15:16 - Data PID"]
#[inline(always)]
pub fn dpid(&self) -> DPID_R {
DPID_R::new(((self.bits >> 15) & 3) as u8)
}
#[doc = "Bits 17:20 - Packet status"]
#[inline(always)]
pub fn pktsts(&self) -> PKTSTS_R {
PKTSTS_R::new(((self.bits >> 17) & 0x0f) as u8)
}
#[doc = "Bits 21:24 - Frame number"]
#[inline(always)]
pub fn frmnum(&self) -> FRMNUM_R {
FRMNUM_R::new(((self.bits >> 21) & 0x0f) as u8)
}
}
#[doc = "OTG status read and pop (device mode)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`grxstsp_device::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct GRXSTSP_DEVICE_SPEC;
impl crate::RegisterSpec for GRXSTSP_DEVICE_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`grxstsp_device::R`](R) reader structure"]
impl crate::Readable for GRXSTSP_DEVICE_SPEC {}
#[doc = "`reset()` method sets GRXSTSP_Device to value 0"]
impl crate::Resettable for GRXSTSP_DEVICE_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use typehack::peano::*;
pub type Idx = usize;
pub struct CCons<N> {
idx: Idx,
next: N,
}
pub struct CNil;
pub trait At<I: Nat> {
fn at(&self) -> Idx;
}
impl<N> At<Z> for CCons<N> {
fn at(&self) -> Idx {
self.idx
}
}
impl<I: Nat, N: At<I>> At<S<I>> for CCons<N> {
fn at(&self) -> Idx {
self.next.at()
}
}
pub type Idx1 = CNil;
pub type Idx2 = CCons<Idx1>;
pub type Idx3 = CCons<Idx2>;
pub type Idx4 = CCons<Idx3>;
pub type Idx5 = CCons<Idx4>;
pub type Idx6 = CCons<Idx5>;
pub type Idx7 = CCons<Idx6>;
pub type Idx8 = CCons<Idx7>;
pub type Idx9 = CCons<Idx8>;
macro_rules! i {
($idx:expr $(, $rest:expr)*) => (CCons { idx: $idx, next: i![$($rest),*] });
() => (());
}
|
use crate::hash::HashFunction;
use std::convert::TryInto;
/// The internal SHA256 digest. On output this internal digest will be converted to an
/// array of u8s.
type InternalDigest = [u32; 8];
/// Initial digest value.
const H: InternalDigest = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
];
/// Round constants.
const K: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];
/// Size of each message chunk in bytes.
const CHUNK_SIZE: usize = 512 / 8;
/// Type of each message chunk to be processed.
type MessageChunk = [u8; CHUNK_SIZE];
/// Produce a new digest by compressing the message chunk, and adding it to the source digest.
fn process_chunk(chunk: &MessageChunk, source_digest: &InternalDigest) -> InternalDigest {
// Prepare the message schedule.
let mut w = [0u32; 64];
// Word 0..15 comes from the chunk.
for i in 0..16 {
w[i] = u32::from_be_bytes([
chunk[i * 4],
chunk[i * 4 + 1],
chunk[i * 4 + 2],
chunk[i * 4 + 3],
])
}
// Extend the first 16 bytes to the remaining words.
for i in 16..64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16]
.wrapping_add(w[i - 7])
.wrapping_add(s1)
.wrapping_add(s0);
}
let mut a = source_digest[0];
let mut b = source_digest[1];
let mut c = source_digest[2];
let mut d = source_digest[3];
let mut e = source_digest[4];
let mut f = source_digest[5];
let mut g = source_digest[6];
let mut h = source_digest[7];
// Compression function.
for i in 0..64 {
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch = (e & f) ^ ((!e) & g);
let temp1 = h
.wrapping_add(w[i])
.wrapping_add(K[i])
.wrapping_add(s1)
.wrapping_add(ch);
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj = (a & b) ^ (a & c) ^ (b & c);
let temp2 = s0.wrapping_add(maj);
h = g;
g = f;
f = e;
e = d.wrapping_add(temp1);
d = c;
c = b;
b = a;
a = temp1.wrapping_add(temp2);
}
[
source_digest[0].wrapping_add(a),
source_digest[1].wrapping_add(b),
source_digest[2].wrapping_add(c),
source_digest[3].wrapping_add(d),
source_digest[4].wrapping_add(e),
source_digest[5].wrapping_add(f),
source_digest[6].wrapping_add(g),
source_digest[7].wrapping_add(h),
]
}
/// Secure Hashing Algorithm-2 with 256 bits of output.
///
/// # Example using the new-update-digest flow
/// ```
/// use hex_literal::hex;
/// use peko_crypto::hash::{HashFunction, SHA256};
///
/// let data = b"The quick brown fox jumps over the lazy dog";
/// let correct_digest = hex!("d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592");
///
/// let mut hasher = SHA256::new();
/// hasher.update(data);
/// assert_eq!(hasher.digest(), correct_digest)
/// ```
///
/// # Example using the one-shot function
/// ```
/// use hex_literal::hex;
/// use peko_crypto::hash::{HashFunction, SHA256};
///
/// let data = b"The quick brown fox jumps over the lazy dog";
/// let correct_digest = hex!("d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592");
///
/// assert_eq!(SHA256::hash(data), correct_digest);
/// ```
pub struct SHA256 {
digest: InternalDigest,
processed_data_length: usize,
remaining_data: Vec<u8>,
}
impl SHA256 {
/// Finalize the hash by hashing the remaining messages and any required paddings.
fn finalize(&self) -> InternalDigest {
let mut remaining_with_padding: Vec<u8> = self.remaining_data.clone();
// First byte in the padding is 0b10000000
remaining_with_padding.push(0b10000000);
// Pad the remaining with 0x00 so that the message can be divided into chunks of
// CHUNKS_SIZE bytes, after the total message length is added (below).
while ((remaining_with_padding.len() + 8) % CHUNK_SIZE) != 0 {
remaining_with_padding.push(0x00);
}
// The last 8 bytes is the total message length, in big-endian.
let final_length_bytes =
((self.processed_data_length + self.remaining_data.len()) * 8).to_be_bytes();
remaining_with_padding.extend_from_slice(&final_length_bytes);
assert_eq!(
remaining_with_padding.len() % CHUNK_SIZE,
0,
"Length after padding must be divisible by 64 bytes"
);
remaining_with_padding
.chunks_exact(CHUNK_SIZE)
.fold(self.digest, |prev_digest, chunk| {
process_chunk(
chunk.try_into().expect("Chunk must be 64 bytes long"),
&prev_digest,
)
})
}
}
impl HashFunction<{ 256 / 8 }> for SHA256 {
type Output = [u8; 256 / 8];
fn new() -> SHA256 {
SHA256 {
digest: H,
processed_data_length: 0,
remaining_data: Vec::new(),
}
}
fn update(&mut self, data: &[u8]) {
self.remaining_data.extend_from_slice(data);
let iter = self.remaining_data.chunks_exact(CHUNK_SIZE);
self.digest = iter.clone().fold(self.digest, |prev_digest, chunk| {
process_chunk(
chunk.try_into().expect("Chunk must be 64 bytes long"),
&prev_digest,
)
});
self.processed_data_length += iter.clone().count() * CHUNK_SIZE;
assert!(
iter.remainder().len() < CHUNK_SIZE,
"Remainder chunk must be smaller than 64 bytes"
);
self.remaining_data = Vec::from(iter.remainder());
}
fn digest(&self) -> Self::Output {
let mut result = [0u8; 32];
for (i, value) in self.finalize().iter().enumerate() {
let be = value.to_be_bytes();
result[i * 4] = be[0];
result[i * 4 + 1] = be[1];
result[i * 4 + 2] = be[2];
result[i * 4 + 3] = be[3];
}
result
}
}
|
mod client;
mod data_type;
mod export;
mod mitm;
mod report;
mod style;
use std::{env::current_dir, path::PathBuf};
use anyhow::{anyhow, Context};
use chrono::Local;
use console::style;
use dialoguer::{Confirm, Input, Select};
use reqwest::Url;
use crate::{
client::Client,
export::export_csv,
mitm::tap_for_url,
report::{summary::Summary, Report},
style::{init as init_style, THEME},
};
async fn run() -> anyhow::Result<()> {
init_style();
let url: Url = if Select::with_theme(&*THEME)
.with_prompt("请选择模式")
.item("代理模式: 启动HTTP代理自动获取网址")
.item("手动模式: 输入从Fiddler获取的网址")
.default(0)
.interact()?
== 0
{
tap_for_url().await?
} else {
Input::with_theme(&*THEME)
.with_prompt("请输入网址")
.validate_with(|input: &String| -> anyhow::Result<()> {
// input must be a url and something from in-game client
let url = Url::parse(input).map_err(|err| anyhow!("输入不是网址: {}", err))?;
if Client::verify_url(&url) {
Ok(())
} else {
Err(anyhow!("输入网址不是有效的抽卡记录网址"))
}
})
.interact()?
.parse()
.unwrap()
};
let client = Client::new(url).await.context("初始化客户端失败")?;
let pools = client.get_pools();
loop {
let selection: usize = Select::with_theme(&*THEME)
.with_prompt("请选择需要查询的卡池")
.items(pools)
.item("退出")
.default(0)
.interact()?;
// if the last one is selected, exit
if selection == pools.len() {
break;
}
let pool = &pools[selection];
let log = client
.request_gacha_log(pool)
.await
.context("获取抽卡记录失败")?;
let summary = Summary::new(&log);
summary.print();
if Confirm::with_theme(&*THEME)
.with_prompt("是否导出抽卡记录")
.wait_for_newline(true)
.default(true)
.interact()?
{
// default being under cwd
let mut save_path = current_dir().unwrap_or_default();
save_path.push(format!(
"{}-{}.csv",
Local::now().format("%Y-%m-%d %H-%M-%S"),
pool.name,
));
let save_path = Input::with_theme(&*THEME)
.with_prompt("保存位置")
.validate_with(|path: &String| -> anyhow::Result<()> {
path.parse::<PathBuf>()?;
Ok(())
})
.with_initial_text(save_path.display().to_string())
.interact()?;
// make sure the extension is csv
let save_path = PathBuf::from(save_path).with_extension("csv");
export_csv(&log, &save_path).context("保存文件失败")?;
}
}
Ok(())
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// catch any error and display it
if let Err(err) = run().await {
eprintln!("{}{:?}", style("错误: ").red(), err);
Input::<String>::new()
.with_prompt("按回车键退出")
.allow_empty(true)
.interact()?;
Err(err)
} else {
Ok(())
}
}
|
#[macro_export]
macro_rules! try_or(
($e:expr) => (
match $e {
Ok(e) => e,
Err(e) => return Err(e)
}
);
($e:expr, $c:expr) => (
match $e {
Ok(e) => e,
Err(e) => {
return Err(($c)(e))
}
}
);
($e:expr, $c:ident) => (
match $e {
Ok(e) => e,
Err(e) => {
return Err($c(e))
}
}
);
);
#[cfg(test)]
mod test {
enum SillyError {
Numb(BadThing),
Other(BadThing)
}
struct BadThing;
fn always_bad() -> Result<(), BadThing> {
Err(BadThing)
}
fn translates() -> Result<(), SillyError> {
try_or!(always_bad(), SillyError::Numb);
try_or!(always_bad(), SillyError::Other);
Ok(())
}
#[test]
fn test_something() {
match translates() {
Ok(_) => panic!("no!"),
Err(SillyError::Numb(_)) => {}
Err(SillyError::Other(_)) => {panic!("other no!")}
}
}
fn fails_with_int() -> Result<(), u32> {
Err(5)
}
fn modify_int() -> Result<(), u32> {
try_or!(fails_with_int(), |x: u32| x + 1);
Ok(())
}
#[test]
fn test_modint() {
match modify_int() {
Ok(_) => panic!("not ok man. not ok"),
Err(6) => {},
Err(x) => panic!("bad number, {}", x)
}
}
}
|
extern crate ncurses;
extern crate eventual;
use ncurses::*;
use eventual::Timer;
use std::env;
use std::str::FromStr;
fn main() {
let args : Vec<String> = env::args().collect();
if args.len() < 2 {
print_usage();
return;
}
run(&args)
}
fn run(args: &Vec<String>) {
let mut cols = 0;
let mut rows = 0;
initscr();
curs_set(CURSOR_VISIBILITY::CURSOR_INVISIBLE);
getmaxyx(stdscr(), &mut rows, &mut cols);
let timer = Timer::new();
let ticks = timer.interval_ms(1000).iter();
centering_print(&rows, &cols, &"--- Start! ---");
let seconds = i32::from_str(&args[1]).unwrap();
let mut i = seconds;
for _ in ticks {
if i < 0 {
break;
}
centering_print(&rows, &cols, &format!("{}s left", i));
i -= 1;
}
centering_print(&rows, &cols, &format!("Finish!!!"));
getch();
endwin();
}
fn centering_print(rows: &i32, cols: &i32, message: &str) {
clear();
let pos_x :i32 = cols/2 - ((message.len() / 2) as i32);
mvprintw(rows/2, pos_x, &message);
refresh();
}
fn print_usage() {
println!("Usage: timer [time in second]")
} |
use super::callable::{push_callable, Callable};
use super::class::{push_class_builder, Builder};
use super::error::{ErrorKind, Result};
use super::privates;
use super::types::{FromDuktape, ToDuktape, Type};
use duktape_sys::{self as duk, duk_context};
use std::ffi::CStr;
use std::fmt;
use std::ptr;
use typemap::TypeMap;
pub type Idx = i32;
pub trait Constructable<'ctor>: Sized {
fn construct(duk: &'ctor Context) -> Result<Self>;
}
bitflags! {
pub struct Compile: u32 {
const EVAL = 8;
const FUNCTION = 16;
const STRICT = 32;
const SHEBANG = 64;
const SAFE = 128;
const NORESULT = 256;
const NOSOURCE = 512;
const STRLEN = 1024;
const NOFILENAME = 2048;
const FUNCEXPR = 4096;
}
}
bitflags! {
pub struct Enumerate: u32 {
/* Enumeration flags for duk_enum() */
const INCLUDE_NONENUMERABLE = (1 << 0); /* enumerate non-numerable properties in addition to enumerable */
const INCLUDE_HIDDEN = (1 << 1); /* enumerate hidden symbols too (in Duktape 1.x called internal properties) */
const INCLUDE_SYMBOLS = (1 << 2); /* enumerate symbols */
const EXCLUDE_STRINGS = (1 << 3); /* exclude strings */
const OWN_PROPERTIES_ONLY = (1 << 4); /* don't walk prototype chain, only check own properties */
const ARRAY_INDICES_ONLY = (1 << 5); /* only enumerate array indices */
/* XXX: misleading name */
const SORT_ARRAY_INDICES = (1 << 6); /* sort array indices (applied to full enumeration result, including inherited array indices); XXX: misleading name */
const NO_PROXY_BEHAVIOR = (1 << 7); /* enumerate a proxy object itself without invoking proxy behavior */
}
}
pub struct Context {
pub(crate) inner: *mut duk_context,
managed: bool,
data: *mut TypeMap,
}
macro_rules! handle_error {
($ret: expr, $ctx: expr) => {
if ($ret) != duk::DUK_EXEC_SUCCESS as i32 {
if $ctx.has_prop_string(-1, "stack") {
$ctx.get_prop_string(-1, "stack");
} else {
$ctx.get_prop_string(-1, "message");
}
let msg: String;
if $ctx.is_string(-1) {
msg = $ctx.get_string(-1)?.to_owned();
} else {
msg = "Uknown".to_string();
}
$ctx.pop(2);
return Err(ErrorKind::TypeError(msg).into());
}
};
}
macro_rules! check_impl {
($ret:ident, $func:ident) => {
pub fn $ret (&self, index:Idx) -> bool {
match unsafe {
duk::$func(self.inner, index)
} {
1 => true,
_ => false,
}
}
};
}
macro_rules! push_impl {
($ret:ident, $func:ident) => {
pub fn $ret (&self) -> &Self {
unsafe {
duk::$func(self.inner)
};
self
}
};
}
impl Context {
/// Create a new context
/// Will return an error, if a duk heap couldn't be created
/// The context manage the lifetime of the wrapped duktape context
pub fn new() -> Result<Context> {
let d = unsafe { duk::duk_create_heap_default() };
if d.is_null() {
return Err(ErrorKind::InsufficientMemory.into());
}
unsafe { privates::init_refs(d) };
unsafe { privates::init_data(d) };
Ok(Context {
inner: d,
managed: true,
data: unsafe { privates::get_data(d) },
})
}
/// Create a new context, from a given duktape context
/// The duktape context will **not** be managed.
pub(crate) fn with(duk: *mut duk_context) -> Context {
unsafe { privates::init_refs(duk) };
unsafe { privates::init_data(duk) };
Context {
inner: duk,
managed: false,
data: unsafe { privates::get_data(duk) },
}
}
pub fn data<'a>(&'a self) -> Result<&'a TypeMap> {
unsafe {
if self.data.is_null() {
return Err(ErrorKind::InsufficientMemory.into());
}
Ok(&*self.data)
}
}
pub fn data_mut<'a>(&'a self) -> Result<&'a mut TypeMap> {
unsafe {
if self.data.is_null() {
return Err(ErrorKind::InsufficientMemory.into());
}
Ok(&mut *self.data)
}
}
/// Evaluate a script
pub fn eval<T: AsRef<[u8]>>(&self, script: T) -> Result<&Self> {
let script = script.as_ref();
let ret = unsafe {
duk::duk_peval_lstring(self.inner, script.as_ptr() as *const i8, script.len())
};
handle_error!(ret, self);
Ok(self)
}
pub fn compile(&self, flags: Compile) -> Result<&Self> {
let ret = unsafe { duk::duk_pcompile(self.inner, flags.bits()) };
handle_error!(ret, self);
Ok(self)
}
pub fn compile_string<T: AsRef<[u8]>>(&self, content: T, flags: Compile) -> Result<()> {
let content = content.as_ref();
let len = content.len();
let ret = unsafe {
duk::duk_pcompile_lstring(self.inner, flags.bits(), content.as_ptr() as *const i8, len)
};
handle_error!(ret, self);
Ok(())
}
pub fn compile_string_filename<T: AsRef<[u8]>>(
&self,
content: T,
file_name: &str,
flags: Compile,
) -> Result<()> {
let content = content.as_ref();
let len = content.len();
let ret = unsafe {
duk::duk_push_lstring(self.inner, file_name.as_ptr() as *const i8, file_name.len());
duk::duk_pcompile_lstring_filename(
self.inner,
flags.bits(),
content.as_ptr() as *const i8,
len,
)
};
handle_error!(ret, self);
Ok(())
}
pub fn dump(&self) -> String {
unsafe {
duk::duk_push_context_dump(self.inner);
let ostr = duk::duk_get_string(self.inner, -1);
let s = CStr::from_ptr(ostr).to_str().unwrap().to_string();
duk::duk_pop(self.inner);
s
}
}
pub fn push_null(&self) -> &Self {
unsafe { duk::duk_push_null(self.inner) };
self
}
pub fn push_undefined(&self) -> &Self {
unsafe { duk::duk_push_undefined(self.inner) };
self
}
pub fn push_boolean(&self, value: bool) -> &Self {
let out = if value { 1 } else { 0 };
unsafe { duk::duk_push_boolean(self.inner, out) };
self
}
pub fn push_int(&self, value: i32) -> &Self {
unsafe { duk::duk_push_int(self.inner, value) };
self
}
pub fn push_uint(&self, value: u32) -> &Self {
unsafe { duk::duk_push_uint(self.inner, value) };
self
}
pub fn push_number<T: Into<f64>>(&self, value: T) -> &Self {
unsafe { duk::duk_push_number(self.inner, value.into()) };
self
}
pub fn push_string<T: AsRef<[u8]>>(&self, value: T) -> &Self {
let len = value.as_ref().len();
unsafe { duk::duk_push_lstring(self.inner, value.as_ref().as_ptr() as *const i8, len) };
self
}
pub fn push_bytes<T: AsRef<[u8]>>(&self, value: T) -> &Self {
let value = value.as_ref();
let buffer =
unsafe { duktape_sys::duk_push_fixed_buffer(self.inner, value.len()) } as *mut u8;
unsafe { ptr::copy(value.as_ptr(), buffer, value.len()) };
self
}
pub fn push_function<T: 'static + Callable>(&self, call: T) -> &Self {
let c = Box::new(call);
unsafe { push_callable(self, c) };
self
}
push_impl!(push_object, duk_push_object);
push_impl!(push_bare_object, duk_push_bare_object);
push_impl!(push_array, duk_push_array);
push_impl!(push_global_object, duk_push_global_object);
push_impl!(push_global_stash, duk_push_global_stash);
push_impl!(push_this, duk_push_this);
push_impl!(push_current_function, duk_push_current_function);
pub fn is_buffer(&self, idx: Idx) -> bool {
unsafe {
if duk::duk_is_buffer(self.inner, idx) == 1 {
true
} else if duk::duk_is_buffer_data(self.inner, idx) == 1 {
true
} else {
false
}
}
}
pub fn get_number(&self, idx: Idx) -> Result<f64> {
if !self.is_number(idx) {
bail!(ErrorKind::TypeError(format!("number")));
}
let ret = unsafe { duk::duk_get_number(self.inner, idx) };
Ok(ret)
}
pub fn get_int(&self, idx: Idx) -> Result<i32> {
if !self.is_number(idx) {
bail!(ErrorKind::TypeError(format!("number")));
}
let ret = unsafe { duk::duk_get_int(self.inner, idx) };
Ok(ret)
}
pub fn get_uint(&self, idx: Idx) -> Result<u32> {
if !self.is_number(idx) {
bail!(ErrorKind::TypeError(format!("number")));
}
let ret = unsafe { duk::duk_get_uint(self.inner, idx) };
Ok(ret)
}
pub fn get_boolean(&self, idx: Idx) -> Result<bool> {
if !self.is_boolean(idx) {
bail!(ErrorKind::TypeError(format!("boolean")));
}
let ok = unsafe { duk::duk_get_boolean(self.inner, idx) };
Ok(if ok == 1 { true } else { false })
}
pub fn get_string(&self, idx: Idx) -> Result<&str> {
if !self.is_string(idx) {
bail!(ErrorKind::TypeError(format!("string")));
}
let ostr = unsafe { duk::duk_get_string(self.inner, idx) };
let s = unsafe { CStr::from_ptr(ostr).to_str()? }; //.to_string();
Ok(s)
}
pub fn get_bytes(&self, idx: Idx) -> Result<&[u8]> {
if !self.is_buffer(idx) {
bail!(ErrorKind::TypeError(format!("buffer")));
}
let r = unsafe {
let mut len: usize = 0;
let ptr = if duk::duk_is_buffer(self.inner, idx) == 1 {
duk::duk_get_buffer(self.inner, idx, &mut len)
} else {
duk::duk_get_buffer_data(self.inner, idx, &mut len)
};
let r = std::slice::from_raw_parts_mut(ptr as *mut u8, len) as *mut [u8];
//Vec::from_raw_parts(ptr: *mut T, length: usize, capacity: usize)
&*r
};
Ok(r)
}
pub fn get_global_string<T: AsRef<[u8]>>(&self, name: T) -> &Self {
unsafe {
duk::duk_get_global_lstring(
self.inner,
name.as_ref().as_ptr() as *const i8,
name.as_ref().len(),
)
};
self
}
pub fn dup(&self, idx: Idx) -> &Self {
unsafe { duk::duk_dup(self.inner, idx) };
self
}
pub fn pop(&self, mut index: Idx) -> &Self {
let top = self.top();
if index > top {
index = top;
}
if index == 0 {
return self;
}
unsafe {
duk::duk_pop_n(self.inner, index);
};
self
}
pub fn remove(&self, idx: Idx) -> &Self {
unsafe { duk::duk_remove(self.inner, idx) };
self
}
pub fn top(&self) -> i32 {
unsafe { duk::duk_get_top(self.inner) }
}
pub fn is_valid_index(&self, index: i32) -> bool {
match unsafe { duk::duk_is_valid_index(self.inner, index) } {
1 => true,
_ => false,
}
}
pub fn normalize_index(&self, idx: Idx) -> Idx {
unsafe { duk::duk_normalize_index(self.inner, idx) }
}
pub fn get_length(&self, idx: Idx) -> usize {
unsafe { duk::duk_get_length(self.inner, idx) }
}
/// Properties
///
pub fn put_prop_string<T: AsRef<[u8]>>(&self, index: i32, name: T) -> &Self {
unsafe {
duk::duk_put_prop_lstring(
self.inner,
index,
name.as_ref().as_ptr() as *const i8,
name.as_ref().len(),
);
}
self
}
pub fn get_prop_string<T: AsRef<[u8]>>(&self, index: i32, name: T) -> &Self {
unsafe {
duk::duk_get_prop_lstring(
self.inner,
index,
name.as_ref().as_ptr() as *const i8,
name.as_ref().len(),
);
}
self
}
pub fn del_prop_string<T: AsRef<[u8]>>(&self, index: i32, name: T) -> &Self {
unsafe {
duk::duk_del_prop_lstring(
self.inner,
index,
name.as_ref().as_ptr() as *const i8,
name.as_ref().len(),
);
}
self
}
pub fn has_prop_string<T: AsRef<[u8]>>(&self, index: i32, name: T) -> bool {
match unsafe {
duk::duk_has_prop_lstring(
self.inner,
index,
name.as_ref().as_ptr() as *const i8,
name.as_ref().len(),
)
} {
1 => true,
_ => false,
}
}
pub fn put_prop_index(&self, aidx: Idx, index: u32) -> &Self {
unsafe {
duk::duk_put_prop_index(self.inner, aidx, index);
}
self
}
pub fn get_prop_index(&self, aidx: Idx, index: u32) -> &Self {
unsafe {
duk::duk_get_prop_index(self.inner, aidx, index);
}
self
}
pub fn del_prop_index(&self, aidx: Idx, index: u32) -> &Self {
unsafe {
duk::duk_del_prop_index(self.inner, aidx, index);
}
self
}
pub fn has_prop_index(&self, aidx: Idx, index: u32) -> bool {
unsafe {
if duk::duk_has_prop_index(self.inner, aidx, index) == 1 {
true
} else {
false
}
}
}
/// Checks
/// Check if value at index is a string
check_impl!(is_string, duk_is_string);
check_impl!(is_number, duk_is_number);
check_impl!(is_boolean, duk_is_boolean);
check_impl!(is_object, duk_is_object);
check_impl!(is_function, duk_is_function);
check_impl!(is_undefined, duk_is_undefined);
check_impl!(is_null, duk_is_null);
check_impl!(is_array, duk_is_array);
pub fn is(&self, t: Type, idx: Idx) -> bool {
self.get_type(idx) == t
}
pub fn get_type(&self, index: Idx) -> Type {
let duk_type = unsafe { duk::duk_get_type(self.inner, index) as u32 };
match duk_type {
duk::DUK_TYPE_UNDEFINED => Type::Undefined,
duk::DUK_TYPE_NULL => Type::Null,
duk::DUK_TYPE_BOOLEAN => Type::Boolean,
duk::DUK_TYPE_NUMBER => Type::Number,
duk::DUK_TYPE_STRING => Type::String,
duk::DUK_TYPE_OBJECT => {
if self.is_function(index) {
return Type::Function;
} else if self.is_array(index) {
return Type::Array;
}
return Type::Object;
}
_ => Type::Undefined,
}
}
// Strings
pub fn concat(&self, argc: i32) -> Result<()> {
if argc > self.top() {
return Err(ErrorKind::ReferenceError(format!("invalid index: {}", argc)).into());
}
unsafe { duk::duk_concat(self.inner, argc) };
Ok(())
}
pub fn call(&self, args: i32) -> Result<&Self> {
let ret = unsafe { duk::duk_pcall(self.inner, args) };
handle_error!(ret, self);
Ok(self)
}
pub fn call_method(&self, args: i32) -> Result<&Self> {
let ret = unsafe { duk::duk_pcall_method(self.inner, args) };
handle_error!(ret, self);
Ok(self)
}
pub fn call_prop(&self, idx: Idx, args: i32) -> Result<&Self> {
let ret = unsafe { duk::duk_pcall_prop(self.inner, idx, args) };
handle_error!(ret, self);
Ok(self)
}
pub fn construct(&self, args: i32) -> Result<&Self> {
let ret = unsafe { duk::duk_pnew(self.inner, args) };
handle_error!(ret, self);
Ok(self)
}
pub fn set_finalizer(&self, idx: Idx) -> &Self {
unsafe { duk::duk_set_finalizer(self.inner, idx) };
self
}
pub fn instance_of(&self, this: Idx, that: Idx) -> bool {
match unsafe { duk::duk_instanceof(self.inner, this, that) } {
1 => true,
_ => false,
}
}
// Class
pub fn push_class(&self, builder: Builder) -> Result<&Self> {
let ret = unsafe { push_class_builder(self, builder) };
match ret {
Ok(_) => Ok(self),
Err(e) => Err(e),
}
}
pub fn create<'a, T: Constructable<'a>>(&'a self) -> Result<T> {
T::construct(self)
}
pub fn push<T: ToDuktape>(&self, value: T) -> Result<&Self> {
value.to_context(self)?;
Ok(self)
}
pub fn get<'de, T: FromDuktape<'de>>(&'de self, index: Idx) -> Result<T> {
T::from_context(self, index)
}
pub fn getp<'de, T: FromDuktape<'de>>(&'de self) -> Result<T> {
let ret = T::from_context(self, -1);
self.pop(1);
ret
}
pub fn enumerator(&self, index: Idx, flags: Enumerate) -> Result<()> {
unsafe { duk::duk_enum(self.inner, index, flags.bits()) };
Ok(())
}
pub fn next(&self, enum_idx: Idx, value: bool) -> Result<bool> {
let out = unsafe {
match duk::duk_next(self.inner, enum_idx, if value { 1 } else { 0 }) {
1 => true,
_ => false,
}
};
Ok(out)
}
}
impl Drop for Context {
fn drop(&mut self) {
if !self.inner.is_null() && self.managed {
unsafe {
duk::duk_destroy_heap(self.inner);
};
}
self.data = ptr::null_mut();
self.inner = ptr::null_mut();
}
}
impl fmt::Debug for Context {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.dump())?;
// unsafe { privates::get_refs(self.inner) };
// write!(f, "refs: {}", self.dump())?;
// self.pop(1);
Ok(())
}
}
impl std::cmp::PartialEq for Context {
fn eq(&self, other: &Context) -> bool {
self.inner == other.inner
}
}
#[cfg(test)]
pub mod tests {
use super::Context;
#[test]
fn context_new() {
let duk = Context::new();
assert!(duk.is_ok());
}
#[test]
fn context_push_function() {
let duk = Context::new().unwrap();
duk.push_function(|ctx: &Context| {
ctx.push_int(42);
Ok(1)
});
duk.call(0).unwrap();
assert_eq!(duk.get_int(-1).unwrap(), 42);
}
#[test]
fn context_push_function_args() {
let duk = Context::new().unwrap();
duk.push_function((1, |ctx: &Context| {
ctx.push_int(42);
Ok(1)
}));
duk.call(0).unwrap();
assert_eq!(duk.get_int(-1).unwrap(), 42);
}
#[test]
fn context_push_bytes() {
let duk = Context::new().unwrap();
let bs = b"Hello, World";
duk.push_bytes(bs);
assert_eq!(duk.is_buffer(-1), true);
let bs2 = duk.get_bytes(-1).unwrap();
assert_eq!(bs, bs2);
}
}
|
use anyhow::Context;
use stark_hash::StarkHash;
fn main() -> Result<(), anyhow::Error> {
tracing_subscriber::fmt::init();
if std::env::args().count() != 2 {
let me = std::env::args()
.next()
.map(std::borrow::Cow::Owned)
.unwrap_or(std::borrow::Cow::Borrowed("me"));
eprintln!("USAGE: {me} DATABASE_FILE");
eprintln!("this utility will go block by block, starting from the latest block");
eprintln!("estimating each transaction on the previous block and reporting any discrepancies with fees");
std::process::exit(1);
}
let storage = pathfinder_lib::storage::Storage::migrate(
std::env::args()
.nth(1)
.context("missing DATABASE_FILE argument")?
.into(),
pathfinder_lib::storage::JournalMode::WAL,
)?;
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_io()
.enable_time()
.build()?;
let (stopflag, stop_rx) = tokio::sync::oneshot::channel::<()>();
let processes = std::num::NonZeroUsize::new(24).unwrap();
// FIXME: with this high process count it's boring to wait for them to ramp up
let (handle, jh) = rt.block_on(async move {
pathfinder_lib::cairo::ext_py::start(
std::env::args().nth(1).unwrap().into(),
processes,
async move {
let _ = stop_rx.await;
},
pathfinder_lib::core::Chain::Mainnet,
)
.await
})?;
let (work_tx, work_rx) = tokio::sync::mpsc::channel(8);
let (ready_tx, ready_rx) = tokio::sync::mpsc::channel(1);
let reporter = std::thread::spawn(move || report_ready(ready_rx));
let processor = rt.spawn(estimate(work_rx, handle, processes, ready_tx));
feed_work(storage, work_tx)?;
rt.block_on(async move {
processor.await.unwrap();
let _ = stopflag.send(());
jh.await.unwrap();
});
reporter.join().unwrap();
Ok(())
}
#[derive(Debug)]
struct Work {
call: pathfinder_lib::rpc::types::request::Call,
at_block: pathfinder_lib::core::StarknetBlockHash,
gas_price: pathfinder_lib::cairo::ext_py::GasPriceSource,
actual_fee: web3::types::H256,
span: tracing::Span,
}
#[derive(Debug)]
struct ReadyResult {
actual_fee: web3::types::H256,
result: Result<
pathfinder_lib::rpc::types::reply::FeeEstimate,
pathfinder_lib::cairo::ext_py::CallFailure,
>,
span: tracing::Span,
}
fn feed_work(
storage: pathfinder_lib::storage::Storage,
sender: tokio::sync::mpsc::Sender<Work>,
) -> Result<(), anyhow::Error> {
let mut connection = storage.connection()?;
let mode = connection.query_row("PRAGMA journal_mode", [], |row| {
Ok(row.get_ref_unwrap(0).as_str().map(|s| s.to_owned())?)
})?;
if mode != "wal" {
tracing::warn!("This will lock up the database file for a long time");
std::thread::sleep(std::time::Duration::from_secs(5));
}
let tx = connection.transaction()?;
let mut prep = tx.prepare(
"select b2.hash as target_block_hash, tx.hash, tx.tx, tx.receipt, b.gas_price, b2.number, b.number
from starknet_blocks b
join starknet_transactions tx on (b.hash = tx.block_hash)
join starknet_blocks b2 on (b2.number = b.number - 1)
order by b.number desc, tx.idx asc",
)?;
let mut work = prep.query([])?;
let mut last_block = None;
let mut previously_declared_deployed_in_the_same_block = std::collections::HashSet::new();
let mut rows = 0usize;
let mut invokes = 0usize;
let mut declares = 0usize;
let mut deploys = 0usize;
let mut same_tx_deploy_call = 0usize;
while let Some(next) = work.next()? {
rows += 1;
let target_hash = StarkHash::from_be_slice(next.get_ref_unwrap(0).as_blob()?).unwrap();
let tx_hash = StarkHash::from_be_slice(next.get_ref_unwrap(1).as_blob()?).unwrap();
let tx = zstd::decode_all(next.get_ref_unwrap(2).as_blob()?)?;
let receipt = zstd::decode_all(next.get_ref_unwrap(3).as_blob()?).unwrap();
let gas_price_at_block = {
let mut raw = [0u8; 32];
let slice = next.get_ref_unwrap(4).as_blob()?;
raw[32 - slice.len()..].copy_from_slice(slice);
web3::types::H256::from(raw)
};
let prev_block_number = next.get_ref_unwrap(5).as_i64().unwrap() as u64;
let block_number = next.get_ref_unwrap(6).as_i64().unwrap() as u64;
match last_block {
Some(x) if x != block_number => previously_declared_deployed_in_the_same_block.clear(),
Some(_) => {}
None => {
last_block = Some(block_number);
}
}
assert_eq!(block_number, prev_block_number + 1);
let actual_fee = serde_json::from_slice::<SimpleReceipt>(&receipt)
.unwrap()
.actual_fee
.unwrap_or(StarkHash::ZERO);
let tx = serde_json::from_slice::<SimpleTransaction>(&tx).with_context(|| {
let tx = String::from_utf8_lossy(&tx);
format!("deserialize tx out of {tx_hash} {tx}")
})?;
let call = match tx {
SimpleTransaction::Invoke(tx)
if !previously_declared_deployed_in_the_same_block
.contains(&tx.contract_address.0) =>
{
tx.into()
}
SimpleTransaction::Invoke(SimpleInvoke {
contract_address, ..
}) => {
tracing::debug!(contract_address=%contract_address.0, "same block deployed contract found");
same_tx_deploy_call += 1;
continue;
}
SimpleTransaction::Declare(_) => {
declares += 1;
continue;
}
SimpleTransaction::Deploy(SimpleDeploy { contract_address }) => {
deploys += 1;
previously_declared_deployed_in_the_same_block.insert(contract_address.0);
continue;
}
};
/*
if actual_fee == StarkHash::ZERO {
// rest will not be useful to go through
tracing::info!("stopping scrolling since found actual_fee = 0");
break;
}
*/
let actual_fee = web3::types::H256::from(actual_fee.to_be_bytes());
invokes += 1;
let span = tracing::info_span!("tx", %tx_hash, block_number);
sender
.blocking_send(Work {
call,
at_block: pathfinder_lib::core::StarknetBlockHash(target_hash),
// use the b.gas_price to get as close as possible
gas_price: pathfinder_lib::cairo::ext_py::GasPriceSource::Current(
gas_price_at_block,
),
actual_fee,
span,
})
.map_err(|_| anyhow::anyhow!("sending to processor failed"))?;
}
// drop work_sender to signal no more work is incoming
drop(sender);
tracing::info!(
rows,
invokes,
declares,
deploys,
same_tx_deploy_call,
"completed query"
);
Ok(())
}
async fn estimate(
mut rx: tokio::sync::mpsc::Receiver<Work>,
handle: pathfinder_lib::cairo::ext_py::Handle,
processes: std::num::NonZeroUsize,
ready_tx: tokio::sync::mpsc::Sender<ReadyResult>,
) {
use futures::stream::StreamExt;
use tracing::Instrument;
let mut waiting = futures::stream::FuturesUnordered::new();
let mut rx_open = true;
loop {
tokio::select! {
next_work = rx.recv(), if rx_open => {
match next_work {
Some(Work {call, at_block, gas_price, actual_fee, span}) => {
let outer = span.clone();
let fut = handle.estimate_fee(call, at_block.into(), gas_price, None);
waiting.push(async move {
ReadyResult {
actual_fee,
result: fut.await,
span,
}
}.instrument(outer));
},
None => {
rx_open = false;
},
}
},
ready = waiting.next(), if !waiting.is_empty() => {
ready_tx.send(ready.expect("we never poll empty")).await.unwrap();
}
else => { break; }
}
// switch to polling only the waiting processes not to grow anything unboundedly
while waiting.len() >= processes.get() {
let ready = waiting.next().await;
ready_tx
.send(ready.expect("we never poll empty"))
.await
.unwrap();
}
}
}
fn report_ready(mut rx: tokio::sync::mpsc::Receiver<ReadyResult>) {
let mut eq = 0usize;
let mut ne = 0usize;
let mut fail = 0usize;
while let Some(ReadyResult {
actual_fee,
result,
span,
}) = rx.blocking_recv()
{
let _g = span.enter();
match result {
Ok(fees) if fees.fee == actual_fee => {
eq += 1;
tracing::info!(eq, ne, fail, "ok");
}
Ok(fees) => {
ne += 1;
let fee = web3::types::U256::from_big_endian(fees.fee.as_bytes());
let actual_fee = web3::types::U256::from_big_endian(actual_fee.as_bytes());
let gas_price = web3::types::U256::from_big_endian(fees.gas_price.as_bytes());
// this hasn't yet happened that any of the numbers would be
// even more than u64...
let diff = if fee > actual_fee {
fee - actual_fee
} else {
actual_fee - fee
};
let gas = diff
.checked_div(gas_price)
.expect("gas_price != 0 is not actually checked anywhere");
tracing::info!(eq, ne, fail, "bad fee {diff} or {gas} gas");
}
Err(e) => {
fail += 1;
tracing::info!(eq, ne, fail, err=?e, "fail");
}
}
}
}
#[derive(serde::Deserialize, Debug)]
struct SimpleReceipt {
actual_fee: Option<StarkHash>,
}
#[derive(serde::Deserialize, Debug)]
#[serde(tag = "type")]
enum SimpleTransaction {
#[serde(rename = "DEPLOY")]
Deploy(SimpleDeploy),
#[serde(rename = "DECLARE")]
Declare(SimpleDeclare),
#[serde(rename = "INVOKE_FUNCTION")]
Invoke(SimpleInvoke),
}
#[derive(serde::Deserialize, Debug)]
struct SimpleDeploy {
contract_address: pathfinder_lib::core::ContractAddress,
}
#[derive(serde::Deserialize, Debug)]
struct SimpleDeclare {}
#[serde_with::serde_as]
#[derive(serde::Deserialize, Debug)]
struct SimpleInvoke {
contract_address: pathfinder_lib::core::ContractAddress,
#[serde_as(as = "Vec<pathfinder_lib::rpc::serde::CallParamAsDecimalStr>")]
pub calldata: Vec<pathfinder_lib::core::CallParam>,
pub entry_point_selector: pathfinder_lib::core::EntryPoint,
#[serde_as(as = "Vec<pathfinder_lib::rpc::serde::TransactionSignatureElemAsDecimalStr>")]
#[serde(default)]
pub signature: Vec<pathfinder_lib::core::TransactionSignatureElem>,
#[serde_as(as = "pathfinder_lib::rpc::serde::FeeAsHexStr")]
pub max_fee: pathfinder_lib::core::Fee,
#[serde(default)]
#[serde_as(as = "Option<pathfinder_lib::rpc::serde::TransactionVersionAsHexStr>")]
pub version: Option<pathfinder_lib::core::TransactionVersion>,
}
impl From<SimpleInvoke> for pathfinder_lib::rpc::types::request::Call {
fn from(tx: SimpleInvoke) -> Self {
pathfinder_lib::rpc::types::request::Call {
contract_address: tx.contract_address,
calldata: tx.calldata,
entry_point_selector: tx.entry_point_selector,
signature: tx
.signature
.into_iter()
.map(|x| pathfinder_lib::core::CallSignatureElem(x.0))
.collect(),
max_fee: tx.max_fee,
version: tx
.version
.unwrap_or(pathfinder_lib::rpc::types::request::Call::DEFAULT_VERSION),
}
}
}
|
#[allow(dead_code)]
mod robust_arduino;
mod json_models;
mod arduino_helper;
mod crane;
mod grabber;
mod motor;
mod logger;
mod ultrasonic;
extern crate websocket;
extern crate serial;
extern crate serde_json;
use serde_json::{Value};
use std::thread;
use arduino_helper::*;
use robust_arduino::*;
use crane::*;
use grabber::*;
use motor::*;
use ultrasonic::*;
use logger::*;
use websocket::sync::Server;
use websocket::{OwnedMessage};
use websocket::result::WebSocketError;
use websocket::ws::dataframe::DataFrame;
use std::env;
use serde_json::json;
fn main() {
let debug = env::var("DEBUG").unwrap();
let debug: bool = debug.parse().unwrap();
let ip_string = env::var("IP").unwrap();
let server = Server::bind(ip_string).unwrap();
for request in server.filter_map(Result::ok) {
// Spawn a new thread for each connection.
thread::spawn(move || {
log(format!("New Connection Request."));
if !request.protocols().contains(&"rust-websocket".to_string()) {
request.reject().unwrap();
return;
}
let port_string = env::var("PORT").unwrap();
let mut port = connect_to_arduino(&port_string, debug);
let client = request.use_protocol("rust-websocket").accept().unwrap();
let ip = client.peer_addr().unwrap();
log(format!("Connection from {}", ip));
let (mut receiver, mut sender) = client.split().unwrap();
for message in receiver.incoming_messages() {
let message: OwnedMessage = match message {
Ok(m) => m,
Err(WebSocketError::NoDataAvailable) => return, // connection close by server
Err(e) => {
log(format!("Receive Loop First: {}", e));
break;
}
};
match message {
OwnedMessage::Close(_) => {
let message = OwnedMessage::Close(None);
sender.send_message(&message).unwrap();
log(format!("Client {} disconnected", ip));
write_order(&mut port, Order::CLOSE).unwrap();
log(format!("Order received: {:?}", read_order(&mut port).unwrap()));
if debug {
log(format!("Order received: {:?}", read_order(&mut port).unwrap()));
}
return;
},
OwnedMessage::Ping(ping) => {
log(format!("Received Ping!"));
let message = OwnedMessage::Pong(ping);
sender.send_message(&message).unwrap();
},
_ => {
let payload_bytes = message.take_payload();
let payload_string = match String::from_utf8(payload_bytes) {
Ok(p) => p,
Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
};
let message_type: Value = match serde_json::from_str(&payload_string) {
Ok(m) => m,
Err(e) => panic!("Something went wrong with parsing json: {}", e),
};
let message_type = message_type["event"].as_str().unwrap();
log(format!("Got {:?} event type.", message_type));
if message_type == "CRANE_DIRECTION" {
handle_crane(&mut port, &payload_string, debug);
} else if message_type == "GRABBER" {
handle_grabber(&mut port, &payload_string, debug);
} else if message_type == "MOTOR" {
handle_motor(&mut port, &payload_string, debug);
} else if message_type == "ULTRASONIC" {
let value = get_ultrasonic(&mut port, debug);
let event = json!({
"event": "ULTRASONIC",
"config": {
"value": value
}
});
let message = OwnedMessage::Text(event.to_string());
sender.send_message(&message).unwrap();
}
}
}
}
});
}
} |
#![feature(arbitrary_self_types)]
#![feature(type_alias_impl_trait)]
#![feature(stmt_expr_attributes)]
#![feature(proc_macro_hygiene)]
pub use ak::*;
use std::time::SystemTime;
struct Payload(usize);
impl Message for Payload {
type Result = ();
}
struct Node {
id: usize,
limit: usize,
next: Option<Addr<Node>>,
}
impl Actor for Node {}
impl Handler<Payload> for Node {
type Future = impl Future<Output=()> + 'static;
#[ak::suspend]
fn handle(mut self: ContextRef<Self>, msg: Payload) -> Self::Future {
async move {
if msg.0 >= self.limit {
println!("Reached limit of {} (payload was {}) on node {}", self.limit, msg.0, self.id);
self.stop();
return;
}
if let Some(next) = &self.next {
next.send(Payload(msg.0 + 1)).await;
} else {
panic!("Nodes werent properly chained");
}
}
}
}
struct FirstAddr(Addr<Node>);
impl Message for FirstAddr { type Result = (); }
impl Handler<FirstAddr> for Node {
type Future = impl Future<Output=()> + 'static;
#[ak::suspend]
fn handle(mut self: ContextRef<Self>, msg: FirstAddr) -> Self::Future {
async {
if let Some(next) = &self.next {
next.send(msg).await;
} else {
self.next = Some(msg.0);
}
}
}
}
const NUM_NODES: usize = 1000;
const NUM_MSGS: usize = 1000;
fn main() {
ak::rt::System::run(|| {
fn create(limit: usize, count: usize) -> Option<Addr<Node>> {
if count > 0 {
Some(Node::start(move |_| Node {
id: NUM_NODES - count,
limit,
next: create(limit, count - 1),
}))
} else {
None
}
};
ak::rt::spawn(async {
let first_node = create(NUM_NODES * NUM_MSGS, NUM_NODES).unwrap();
first_node.send(FirstAddr(first_node.clone())).await;
let t = SystemTime::now();
first_node.send(Payload(0)).await;
let elapsed = t.elapsed().unwrap();
println!("Elapsed : {}.{:06} seconds", elapsed.as_secs(), elapsed.subsec_micros());
});
});
} |
pub trait FromPrimitive {
fn from_bool(t: bool) -> Self;
fn from_usize(t: usize) -> Self;
fn from_u8(t: u8) -> Self;
fn from_u16(t: u16) -> Self;
fn from_u32(t: u32) -> Self;
fn from_u64(t: u64) -> Self;
fn from_isize(t: isize) -> Self;
fn from_i8(t: i8) -> Self;
fn from_i16(t: i16) -> Self;
fn from_i32(t: i32) -> Self;
fn from_i64(t: i64) -> Self;
fn from_f32(t: f32) -> Self;
fn from_f64(t: f64) -> Self;
}
macro_rules! from_primitive {
($n:ident, $t:ident, $f:ident) => (
#[inline(always)]
fn $n(f: $f) -> Self { f as $t }
);
($n:ident, $t:ident, $f:ident, $a:ident) => (
#[inline(always)]
fn $n(f: $f) -> Self { f as $a as $t }
);
}
macro_rules! trait_from_primitive {
($t:ident) => (
impl FromPrimitive for $t {
from_primitive!(from_bool, $t, bool);
from_primitive!(from_usize, $t, usize);
from_primitive!(from_u8, $t, u8);
from_primitive!(from_u16, $t, u16);
from_primitive!(from_u32, $t, u32);
from_primitive!(from_u64, $t, u64);
from_primitive!(from_isize, $t, isize);
from_primitive!(from_i8, $t, i8);
from_primitive!(from_i16, $t, i16);
from_primitive!(from_i32, $t, i32);
from_primitive!(from_i64, $t, i64);
from_primitive!(from_f32, $t, f32);
from_primitive!(from_f64, $t, f64);
}
);
}
trait_from_primitive!(usize);
trait_from_primitive!(u8);
trait_from_primitive!(u16);
trait_from_primitive!(u32);
trait_from_primitive!(u64);
trait_from_primitive!(isize);
trait_from_primitive!(i8);
trait_from_primitive!(i16);
trait_from_primitive!(i32);
trait_from_primitive!(i64);
macro_rules! from_primitive_bool {
($n:ident, $f:ident, $zero:expr) => (
#[inline(always)]
fn $n(f: $f) -> Self { if f != $zero {true} else {false} }
);
}
macro_rules! trait_bool_from_primitive {
($t:ident) => (
impl FromPrimitive for $t {
from_primitive_bool!(from_bool, bool, false);
from_primitive_bool!(from_usize, usize, 0);
from_primitive_bool!(from_u8, u8, 0);
from_primitive_bool!(from_u16, u16, 0);
from_primitive_bool!(from_u32, u32, 0);
from_primitive_bool!(from_u64, u64, 0);
from_primitive_bool!(from_isize, isize, 0);
from_primitive_bool!(from_i8, i8, 0);
from_primitive_bool!(from_i16, i16, 0);
from_primitive_bool!(from_i32, i32, 0);
from_primitive_bool!(from_i64, i64, 0);
from_primitive_bool!(from_f32, f32, 0f32);
from_primitive_bool!(from_f64, f64, 0f64);
}
);
}
trait_bool_from_primitive!(bool);
macro_rules! trait_float_from_primitive {
($t:ident, $a:ident) => (
impl FromPrimitive for $t {
from_primitive!(from_bool, $t, bool, $a);
from_primitive!(from_usize, $t, usize);
from_primitive!(from_u8, $t, u8);
from_primitive!(from_u16, $t, u16);
from_primitive!(from_u32, $t, u32);
from_primitive!(from_u64, $t, u64);
from_primitive!(from_isize, $t, isize);
from_primitive!(from_i8, $t, i8);
from_primitive!(from_i16, $t, i16);
from_primitive!(from_i32, $t, i32);
from_primitive!(from_i64, $t, i64);
from_primitive!(from_f32, $t, f32);
from_primitive!(from_f64, $t, f64);
}
);
}
trait_float_from_primitive!(f32, i32);
trait_float_from_primitive!(f64, i64);
#[cfg(test)]
mod test {
use super::FromPrimitive;
fn create_one<T: FromPrimitive>() -> T {
T::from_f32(1_f32)
}
#[test]
fn test() {
assert_eq!(create_one::<bool>(), true);
assert_eq!(create_one::<usize>(), 1_usize);
assert_eq!(create_one::<f32>(), 1_f32);
}
}
|
use ::*;
macro_rules! selector_as_ptr {
($x:expr) => {
match $x.as_c_str() {
None => std::ptr::null(),
Some(s) => s.as_ptr(),
}
};
}
mod keys;
mod mouse;
mod wheel;
mod touch;
pub mod webgl;
mod css;
pub use self::keys::*;
pub use self::mouse::*;
pub use self::wheel::*;
pub use self::touch::*;
pub use self::css::*;
#[derive(Debug)]
pub enum HtmlError {
Deferred,
NotSupported,
FailedNotDeferred,
InvalidTarget,
UnknownTarget,
InvalidParam,
Failed,
NoData,
TimedOut,
Unknown { code: c_int },
}
pub type HtmlResult<T> = Result<T, HtmlError>;
pub(crate) fn parse_html_result(code: EMSCRIPTEN_RESULT) -> Option<HtmlError> {
match code {
EMSCRIPTEN_RESULT_SUCCESS => None,
EMSCRIPTEN_RESULT_DEFERRED => Some(HtmlError::Deferred),
EMSCRIPTEN_RESULT_NOT_SUPPORTED => Some(HtmlError::NotSupported),
EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED => Some(HtmlError::FailedNotDeferred),
EMSCRIPTEN_RESULT_INVALID_TARGET => Some(HtmlError::InvalidTarget),
EMSCRIPTEN_RESULT_UNKNOWN_TARGET => Some(HtmlError::UnknownTarget),
EMSCRIPTEN_RESULT_INVALID_PARAM => Some(HtmlError::InvalidParam),
EMSCRIPTEN_RESULT_FAILED => Some(HtmlError::Failed),
EMSCRIPTEN_RESULT_NO_DATA => Some(HtmlError::NoData),
EMSCRIPTEN_RESULT_TIMED_OUT => Some(HtmlError::TimedOut),
_ => Some(HtmlError::Unknown { code }),
}
}
#[derive(Debug)]
pub enum Selector<'a> {
Default,
Window,
Document,
Screen,
Canvas,
Element { id: &'a str },
}
impl<'a> Selector<'a> {
pub(crate) fn as_c_str(&self) -> Option<Cow<CStr>> {
fn static_selector(selector: &'static [u8]) -> Option<Cow<CStr>> {
unsafe { Some(Cow::Borrowed(CStr::from_bytes_with_nul_unchecked(selector))) }
}
match *self {
Selector::Default => None,
Selector::Window => static_selector(b"#window\0"),
Selector::Document => static_selector(b"#document\0"),
Selector::Screen => static_selector(b"#screen\0"),
Selector::Canvas => static_selector(b"#canvas\0"),
Selector::Element { id } => Some(Cow::Owned(CString::new(id).unwrap())),
}
}
}
|
use ken2ken::{client::Client, listener::Listener};
use std::io::{self, Write};
use std::net::TcpStream;
use std::thread::spawn;
fn main() -> std::io::Result<()> {
let listener = Listener::new();
println!("Hosting ken2ken on port {}", listener.port);
spawn(move || listener.listen());
let stdin = io::stdin();
let mut stdout = io::stdout();
loop {
let mut address = String::new();
print!("Send to: ");
stdout.flush()?;
stdin.read_line(&mut address)?;
let stream = match TcpStream::connect(address.trim()) {
Ok(stream) => stream,
Err(error) => {
println!("Error connecting to ken: {}", error);
continue;
}
};
let mut client = match Client::connect(stream) {
Ok(client) => client,
Err(err) => {
println!("Error in making handshake: {}", err);
continue;
}
};
let mut message = String::new();
print!("Message: ");
stdout.flush()?;
stdin.read_line(&mut message)?;
let message = message.trim();
match message.strip_prefix("file:") {
Some(path) => client.write_file(path)?,
None => client.write_message(message)?,
}
}
}
|
pub mod misc_parameters;
pub use misc_parameters::MiscParameters;
|
fn main() {
let a = {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.trim_end().parse().unwrap()
};
let stdout = solve(a);
stdout.iter().for_each(|s| {
println!("{}", s);
})
}
fn solve(a: u32) -> Vec<String> {
let mut buf = Vec::new();
buf.push(format!("{} {}", a + 1, 2));
buf
}
#[test]
fn test_solve_1() {
assert_eq!(solve(1), vec!("2 2"));
}
#[test]
fn test_solve_2() {
assert_eq!(solve(100), vec!("101 2"));
}
#[test]
fn test_solve_3() {
assert_eq!(solve(1000000000), vec!("1000000001 2"));
}
|
use crate::float::Float;
use crate::matrix::M3;
use crate::numeric::Numeric;
use crate::vector::{Cross, FloatVector, Vector, V3};
use std::ops::{Add, Deref, Div, Mul, Sub};
impl<T> Deref for V3<T>
where
T: Numeric,
{
type Target = [T; 3];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> Vector<T> for V3<T>
where
T: Numeric,
{
fn dot(&self, rhs: Self) -> T {
self[0] * rhs[0] + self[1] * rhs[1] + self[2] * rhs[2]
}
}
impl<F> FloatVector<F> for V3<F> where F: Float {}
impl<T> Cross<T> for V3<T>
where
T: Numeric,
{
fn cross(&self, rhs: Self) -> V3<T> {
V3([
self[1] * rhs[2] - self[2] - rhs[1],
self[2] * rhs[0] - self[0] - rhs[2],
self[0] * rhs[1] - self[1] - rhs[0],
])
}
}
impl<T> Add for V3<T>
where
T: Numeric,
{
type Output = V3<T>;
fn add(self, rhs: Self) -> Self::Output {
V3([self[0] + rhs[0], self[1] + rhs[1], self[2] + rhs[2]])
}
}
impl<T> Sub for V3<T>
where
T: Numeric,
{
type Output = V3<T>;
fn sub(self, rhs: Self) -> Self::Output {
V3([self[0] - rhs[0], self[1] - rhs[1], self[2] - rhs[2]])
}
}
impl<T> Mul for V3<T>
where
T: Numeric,
{
type Output = V3<T>;
fn mul(self, rhs: Self) -> Self::Output {
V3([self[0] * rhs[0], self[1] * rhs[1], self[2] * rhs[2]])
}
}
impl<T> Mul<T> for V3<T>
where
T: Numeric,
{
type Output = V3<T>;
fn mul(self, rhs: T) -> Self::Output {
V3([self[0] * rhs, self[1] * rhs, self[2] * rhs])
}
}
impl<T> Mul<M3<T>> for V3<T>
where
T: Numeric,
{
type Output = V3<T>;
fn mul(self, rhs: M3<T>) -> Self::Output {
V3([
self[0] * rhs[0][0] + self[1] * rhs[1][0] + self[2] * rhs[2][0],
self[0] * rhs[0][1] + self[1] * rhs[1][1] + self[2] * rhs[2][1],
self[0] * rhs[0][2] + self[1] * rhs[1][2] + self[2] * rhs[2][2],
])
}
}
impl<T> Div for V3<T>
where
T: Numeric,
{
type Output = V3<T>;
fn div(self, rhs: Self) -> Self::Output {
V3([self[0] / rhs[0], self[1] / rhs[1], self[2] / rhs[2]])
}
}
impl<T> Div<T> for V3<T>
where
T: Numeric,
{
type Output = V3<T>;
fn div(self, rhs: T) -> Self::Output {
V3([self[0] / rhs, self[1] / rhs, self[2] / rhs])
}
}
|
pub fn count_and_say(n: i32) -> String {
let mut result = "1".to_string();
for _ in 1..n {
let mut vec = Vec::<(usize, char)>::new();
let c: Vec<char> = result.chars().collect();
let mut ref_pos = 0;
let mut curr_pos = 0;
loop {
if curr_pos >= c.len() {
vec.push((curr_pos-ref_pos, c[ref_pos]));
break
}
if c[curr_pos] != c[ref_pos] {
vec.push((curr_pos-ref_pos, c[ref_pos]));
ref_pos = curr_pos;
}
curr_pos += 1;
}
result = vec.iter().map(|(n, x)| format!("{}{}", n, x)).fold("".to_string(), |acc, x| acc + x.as_str())
}
result
}
#[test]
fn test_count_and_say() {
assert_eq!(count_and_say(1), "1".to_string());
assert_eq!(count_and_say(4), "1211".to_string());
assert_eq!(count_and_say(5), "111221".to_string());
} |
use crate::components::Codeblock;
use crate::with_raw_code;
use material_yew::list::GraphicType;
use material_yew::{MatButton, MatListItem, MatSelect, WeakComponentLink};
use yew::prelude::*;
pub struct Select {
link: ComponentLink<Self>,
natural_menu_width: bool,
select_link: WeakComponentLink<MatSelect>,
}
pub enum Msg {
ToggleNaturalMenuWidth,
SelectIndex2,
}
impl Component for Select {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
let select_link = WeakComponentLink::default();
Self {
link,
natural_menu_width: true,
select_link,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::ToggleNaturalMenuWidth => {
self.natural_menu_width = !self.natural_menu_width;
true
}
Msg::SelectIndex2 => {
self.select_link.select(2);
false
}
}
}
fn change(&mut self, _props: Self::Properties) -> bool {
false
}
fn view(&self) -> Html {
let filled = with_raw_code!(filled { html! {
<section>
<MatSelect label="Filled" select_link=self.select_link.clone()>
<MatListItem>{""}</MatListItem>
<MatListItem value="0">{"Option 0"}</MatListItem>
<MatListItem value="1">{"Option 1"}</MatListItem>
<MatListItem value="2">{"Option 2"}</MatListItem>
<MatListItem value="3">{"Option 3"}</MatListItem>
</MatSelect>
<span onclick=self.link.callback(|_| Msg::SelectIndex2)>
<MatButton label="Select 'Option 1'"/>
</span>
</section>
}});
let outlined = with_raw_code!(outlined { html! {
<section>
<MatSelect label="Outlined" outlined=true>
<MatListItem>{""}</MatListItem>
<MatListItem value="0">{"Option 0"}</MatListItem>
<MatListItem value="1">{"Option 1"}</MatListItem>
<MatListItem value="2">{"Option 2"}</MatListItem>
<MatListItem value="3">{"Option 3"}</MatListItem>
</MatSelect>
</section>
}});
let preselected = with_raw_code!(preselected { html! {
<section>
<MatSelect label="Preselected">
<MatListItem>{""}</MatListItem>
<MatListItem value="0">{"Option 0"}</MatListItem>
<MatListItem value="1">{"Option 1"}</MatListItem>
<MatListItem value="2" selected=true>{"Option 2"}</MatListItem>
<MatListItem value="3">{"Option 3"}</MatListItem>
</MatSelect>
</section>
}});
let has_icon = with_raw_code!(has_icon { html! {
<section>
<MatSelect label="Has Icon" outlined=true icon="event">
<MatListItem>{""}</MatListItem>
<MatListItem value="0" graphic=GraphicType::Icon>{"Option 0"}</MatListItem>
<MatListItem value="1" graphic=GraphicType::Icon>{"Option 1"}</MatListItem>
<MatListItem value="2" graphic=GraphicType::Icon>{"Option 2"}</MatListItem>
<MatListItem value="3" graphic=GraphicType::Icon>{"Option 3"}</MatListItem>
</MatSelect>
</section>
}});
let required = with_raw_code!(required { html! {
<section>
<MatSelect label="Required filled" required=true>
<MatListItem>{""}</MatListItem>
<MatListItem value="0">{"Option 0"}</MatListItem>
<MatListItem value="1">{"Option 1"}</MatListItem>
<MatListItem value="2">{"Option 2"}</MatListItem>
<MatListItem value="3">{"Option 3"}</MatListItem>
</MatSelect>
</section>
}});
let required_outlined = with_raw_code!(required_outlined { html! {
<section>
<MatSelect label="Required outlined" required=true outlined=true>
<MatListItem>{""}</MatListItem>
<MatListItem value="0">{"Option 0"}</MatListItem>
<MatListItem value="1">{"Option 1"}</MatListItem>
<MatListItem value="2">{"Option 2"}</MatListItem>
<MatListItem value="3">{"Option 3"}</MatListItem>
</MatSelect>
</section>
}});
let disabled = with_raw_code!(disabled { html! {
<section>
<MatSelect label="Disabled" disabled=true>
<MatListItem>{""}</MatListItem>
<MatListItem value="0">{"Option 0"}</MatListItem>
<MatListItem value="1" disabled=true>{"Option 1"}</MatListItem>
<MatListItem value="2">{"Option 2"}</MatListItem>
<MatListItem value="3">{"Option 3"}</MatListItem>
</MatSelect>
</section>
}});
let natural_width = with_raw_code!(natural_width { html! {
<section>
<MatSelect label="Natural width" natural_menu_width=self.natural_menu_width>
<MatListItem>{""}</MatListItem>
<MatListItem value="0">{"Option 0"}</MatListItem>
<MatListItem value="1">{"Option 1"}</MatListItem>
<MatListItem value="2">{"Option 2"}</MatListItem>
<MatListItem value="3">{"Option 3"}</MatListItem>
</MatSelect>
<div onclick=self.link.callback(|_| Msg::ToggleNaturalMenuWidth)>
<MatButton label="Toggle natural menu width" raised=true />
</div>
</section>
}});
html! {
<main class="list-demo">
<Codeblock title="Filled" code_and_html=filled />
<Codeblock title="Outlined" code_and_html=outlined />
<Codeblock title="Preselected" code_and_html=preselected />
<Codeblock title="Has Icon" code_and_html=has_icon />
<Codeblock title="Required" code_and_html=required />
<Codeblock title="Required outlined" code_and_html=required_outlined />
<Codeblock title="Disabled" code_and_html=disabled />
<Codeblock title="Natural width" code_and_html=natural_width />
</main>}
}
}
|
pub mod game_map;
#[derive(Default)]
pub struct DeltaTime(pub std::time::Duration);
#[derive(Default)]
pub struct CameraCenter {
pub x: i32,
pub y: i32,
}
pub struct Player {
pub ent: specs::Entity,
}
#[derive(Default)]
pub struct PendingAction(pub Option<super::input::Action>);
|
#[doc = "Register `DDRPHYC_DTDR1` reader"]
pub type R = crate::R<DDRPHYC_DTDR1_SPEC>;
#[doc = "Register `DDRPHYC_DTDR1` writer"]
pub type W = crate::W<DDRPHYC_DTDR1_SPEC>;
#[doc = "Field `DTBYTE4` reader - DTBYTE4"]
pub type DTBYTE4_R = crate::FieldReader;
#[doc = "Field `DTBYTE4` writer - DTBYTE4"]
pub type DTBYTE4_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `DTBYTE5` reader - DTBYTE5"]
pub type DTBYTE5_R = crate::FieldReader;
#[doc = "Field `DTBYTE5` writer - DTBYTE5"]
pub type DTBYTE5_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `DTBYTE6` reader - DTBYTE6"]
pub type DTBYTE6_R = crate::FieldReader;
#[doc = "Field `DTBYTE6` writer - DTBYTE6"]
pub type DTBYTE6_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `DTBYTE7` reader - DTBYTE7"]
pub type DTBYTE7_R = crate::FieldReader;
#[doc = "Field `DTBYTE7` writer - DTBYTE7"]
pub type DTBYTE7_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
impl R {
#[doc = "Bits 0:7 - DTBYTE4"]
#[inline(always)]
pub fn dtbyte4(&self) -> DTBYTE4_R {
DTBYTE4_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 8:15 - DTBYTE5"]
#[inline(always)]
pub fn dtbyte5(&self) -> DTBYTE5_R {
DTBYTE5_R::new(((self.bits >> 8) & 0xff) as u8)
}
#[doc = "Bits 16:23 - DTBYTE6"]
#[inline(always)]
pub fn dtbyte6(&self) -> DTBYTE6_R {
DTBYTE6_R::new(((self.bits >> 16) & 0xff) as u8)
}
#[doc = "Bits 24:31 - DTBYTE7"]
#[inline(always)]
pub fn dtbyte7(&self) -> DTBYTE7_R {
DTBYTE7_R::new(((self.bits >> 24) & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - DTBYTE4"]
#[inline(always)]
#[must_use]
pub fn dtbyte4(&mut self) -> DTBYTE4_W<DDRPHYC_DTDR1_SPEC, 0> {
DTBYTE4_W::new(self)
}
#[doc = "Bits 8:15 - DTBYTE5"]
#[inline(always)]
#[must_use]
pub fn dtbyte5(&mut self) -> DTBYTE5_W<DDRPHYC_DTDR1_SPEC, 8> {
DTBYTE5_W::new(self)
}
#[doc = "Bits 16:23 - DTBYTE6"]
#[inline(always)]
#[must_use]
pub fn dtbyte6(&mut self) -> DTBYTE6_W<DDRPHYC_DTDR1_SPEC, 16> {
DTBYTE6_W::new(self)
}
#[doc = "Bits 24:31 - DTBYTE7"]
#[inline(always)]
#[must_use]
pub fn dtbyte7(&mut self) -> DTBYTE7_W<DDRPHYC_DTDR1_SPEC, 24> {
DTBYTE7_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 = "DDRPHYC DTD register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ddrphyc_dtdr1::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 [`ddrphyc_dtdr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DDRPHYC_DTDR1_SPEC;
impl crate::RegisterSpec for DDRPHYC_DTDR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ddrphyc_dtdr1::R`](R) reader structure"]
impl crate::Readable for DDRPHYC_DTDR1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ddrphyc_dtdr1::W`](W) writer structure"]
impl crate::Writable for DDRPHYC_DTDR1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DDRPHYC_DTDR1 to value 0x7788_bb44"]
impl crate::Resettable for DDRPHYC_DTDR1_SPEC {
const RESET_VALUE: Self::Ux = 0x7788_bb44;
}
|
//! This is documentation for the `examplez` crate.
/// uno contains example #1
pub mod numberz;
/// pig_latin translates strings to [Pig Latin](https://en.wikipedia.org/wiki/Pig_Latin).
pub mod pig_latin;
pub mod company;
|
/*
* Copyright 2020 Damian Peckett <damian@pecke.tt>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use crate::error::*;
use crate::kubernetes::deployment::KubernetesDeploymentResource;
use crate::kubernetes::replicaset::KubernetesReplicaSetResource;
use crate::kubernetes::statefulset::KubernetesStatefulSetResource;
use crate::kubernetes::KubernetesResource;
use crate::kubernetes::KubernetesResourceTrait;
use crate::kubernetes::{KubernetesObject, KubernetesObjectTrait};
use crate::metrics::retrieve_aggregate_metric;
use crate::resource::{AutoScaler, AutoScalerKubernetesResourceKind, AutoScalerStrategyKind};
use crate::strategy::bang_bang::BangBangAutoScalerStrategy;
use crate::strategy::AutoScalerStrategy;
use crate::strategy::AutoScalerStrategyTrait;
use chrono::{DateTime, Utc};
use clap::{
arg_enum, crate_authors, crate_description, crate_name, crate_version, value_t, App, Arg,
};
use futures::channel::mpsc::unbounded;
use futures::channel::mpsc::UnboundedSender;
use futures::{SinkExt, StreamExt};
use kube::api::{Api, Informer, ListParams, WatchEvent};
use kube::client::APIClient;
use kube::config;
use slog::{crit, debug, error, info, o, warn, Drain, Level, LevelFilter, Logger};
use snafu::ResultExt;
use std::collections::HashMap;
use std::panic;
use std::process::exit;
use std::sync::{Arc, Mutex as StdMutex};
use std::time::Duration;
use stream_cancel::TakeUntil;
use stream_cancel::{StreamExt as StreamCancelExt, Tripwire};
use tokio::sync::Mutex;
use tokio::sync::RwLock;
use tokio::time::interval;
use tokio::time::Interval;
/// Pangolin error types.
mod error;
/// Kubernetes api abstraction.
#[allow(clippy::type_complexity)]
mod kubernetes;
/// Prometheus metrics related functions.
mod metrics;
/// AutoScaler specification types.
mod resource;
/// AutoScaler control strategies.
mod strategy;
arg_enum! {
/// Log level command line argument.
#[derive(PartialEq, Debug)]
pub enum LogLevelArgument {
Critical,
Error,
Warning,
Info,
Debug,
Trace,
}
}
impl From<LogLevelArgument> for Level {
fn from(level_arg: LogLevelArgument) -> Level {
match level_arg {
LogLevelArgument::Critical => Level::Critical,
LogLevelArgument::Error => Level::Error,
LogLevelArgument::Warning => Level::Warning,
LogLevelArgument::Info => Level::Info,
LogLevelArgument::Debug => Level::Debug,
LogLevelArgument::Trace => Level::Trace,
}
}
}
#[tokio::main]
async fn main() -> Result<(), Error> {
let matches = App::new(crate_name!())
.version(crate_version!())
.about(crate_description!())
.author(crate_authors!())
.arg(
Arg::with_name("LOG_LEVEL")
.long("log-level")
.help("set the application log level")
.takes_value(true)
.possible_values(&LogLevelArgument::variants())
.case_insensitive(true)
.default_value("Info"),
)
.get_matches();
let log_level: Level = value_t!(matches, "LOG_LEVEL", LogLevelArgument)
.unwrap_or_else(|e| e.exit())
.into();
let logger = Logger::root(
StdMutex::new(LevelFilter::new(
slog_json::Json::default(std::io::stdout()),
log_level,
))
.map(slog::Fuse),
o!("application" => crate_name!(), "version" => crate_version!()),
);
info!(logger, "Configured structured logger"; "log_level" => format!("{:?}", log_level));
// Replace the panic handler with one that will exit the process on panics (in any thread).
// This lets Kubernetes restart the process if we hit anything unexpected.
let panic_logger = logger.clone();
let _ = panic::take_hook();
panic::set_hook(Box::new(move |panic_info| {
crit!(panic_logger, "Thread panicked"; "error" => format!("{}", panic_info));
exit(1);
}));
let kube_config = if let Ok(kube_config) = kube::config::incluster_config() {
kube_config
} else {
config::load_kube_config().await.context(Kube {})?
};
let kube_client = APIClient::new(kube_config.clone());
let autoscaler_api: Api<AutoScaler> = Api::customResource(kube_client.clone(), "autoscalers")
.version("v1alpha1")
.group("pangolinscaler.com");
// Handle for managing the lifecycle of subtasks and sending update information
let mut task_handle: HashMap<String, UnboundedSender<AutoScaler>> = HashMap::new();
// Retrieve the current list of autoscalers.
let autoscalers = autoscaler_api
.list(&ListParams::default())
.await
.context(Kube {})?;
for autoscaler in autoscalers {
let task_key = format!(
"{}/{}",
autoscaler.metadata.namespace.as_ref().unwrap(),
autoscaler.metadata.name
);
task_handle.insert(
task_key,
autoscaler_loop(
logger.new(o!(
"autoscaler_namespace" => autoscaler.metadata.namespace.as_ref().unwrap().clone(),
"autoscaler_name" => autoscaler.metadata.name.clone())),
kube_config.clone(),
autoscaler.clone(),
)?,
);
}
// Set up a watcher for autoscaler events.
let informer = Informer::new(autoscaler_api)
.timeout(15)
.init()
.await
.context(Kube {})?;
// Loop enables us to drop and refresh the kubernetes watcher periodically
// reduces the reliance on long lived connections and provides us a bit more resiliency.
loop {
let mut events = match informer
.poll()
.await
.map(|events| events.boxed())
.context(Kube {})
{
Ok(events) => events,
Err(err) => {
error!(logger, "Failed to poll for events"; "error" => format!("{}", err));
// Rely on kubernetes for retry behavior
return Err(err);
}
};
// Loop over all AutoScaler object changes.
while let Some(Ok(event)) = events.next().await {
match event {
WatchEvent::Added(autoscaler) => {
// New AutoScaler has been added. Start a fresh AutoScaler loop.
let autoscaler_namespace = autoscaler.metadata.namespace.as_ref().unwrap();
info!(logger, "Added autoscaler";
"autoscaler_namespace" => autoscaler_namespace,
"autoscaler_name" => &autoscaler.metadata.name);
let task_key = format!("{}/{}", autoscaler_namespace, autoscaler.metadata.name);
task_handle.insert(
task_key,
autoscaler_loop(
logger.new(o!(
"autoscaler_namespace" => autoscaler_namespace.clone(),
"autoscaler_name" => autoscaler.metadata.name.clone())),
kube_config.clone(),
autoscaler.clone(),
)?,
);
}
WatchEvent::Modified(autoscaler) => {
// AutoScaler object has been modified. Send across the updated object.
let autoscaler_namespace = autoscaler.metadata.namespace.as_ref().unwrap();
info!(logger, "Modified autoscaler";
"autoscaler_namespace" => autoscaler_namespace,
"autoscaler_name" => &autoscaler.metadata.name);
let task_key = format!("{}/{}", autoscaler_namespace, autoscaler.metadata.name);
if let Some(task_handle) = task_handle.get_mut(&task_key) {
task_handle.send(autoscaler.clone()).await.unwrap();
} else {
// Somehow we received an update for an object we haven't already created.
// we must have missed the addition of an AutoScaler somehow. Concerning...
warn!(logger, "Adding missing autoscaler";
"autoscaler_namespace" => autoscaler_namespace,
"autoscaler_name" => &autoscaler.metadata.name);
task_handle.insert(
task_key,
autoscaler_loop(
logger.new(o!(
"autoscaler_namespace" => autoscaler_namespace.clone(),
"autoscaler_name" => autoscaler.metadata.name.clone())),
kube_config.clone(),
autoscaler.clone(),
)?,
);
}
}
WatchEvent::Deleted(autoscaler) => {
// AutoScaler object has been deleted. Shutdown all subtasks.
let autoscaler_namespace = autoscaler.metadata.namespace.as_ref().unwrap();
info!(logger, "Deleted autoscaler";
"autoscaler_namespace" => autoscaler_namespace,
"autoscaler_name" => &autoscaler.metadata.name);
let task_key = format!("{}/{}", autoscaler_namespace, autoscaler.metadata.name);
// Dropping the handle will terminate the task.
drop(task_handle.remove(&task_key));
}
WatchEvent::Error(err) => {
// AutoScaler object error.
error!(logger, "Autoscaler error"; "error" => format!("{}", err))
}
}
}
}
}
fn autoscaler_loop(
logger: Logger,
kube_config: kube::config::Configuration,
autoscaler: AutoScaler,
) -> Result<UnboundedSender<AutoScaler>, Error> {
// Create a channel for receiving updated AutoScaler specifications.
let (update_sender, mut update_receiver) = unbounded::<AutoScaler>();
// Create an interval timer for the reconciliation loop.
let period = autoscaler.spec.interval;
let (timer_cancel, timer_tripwire) = Tripwire::new();
let mut timer_cancel = Some(timer_cancel);
// Create an interval timer for the metrics retrieval subtask.
let metric_period = autoscaler.spec.metric.interval;
let (metric_timer_cancel, metric_timer_tripwire) = Tripwire::new();
let mut metric_timer_cancel = Some(metric_timer_cancel);
let autoscaler_namespace = String::from(autoscaler.metadata.namespace.as_ref().unwrap());
let autoscaler = Arc::new(RwLock::new(Some(autoscaler)));
// A repository for storing a window worth of retrieved metrics.
// This will leak a small amount of memory when matching objects get deleted.
let metric_repository: Arc<Mutex<HashMap<String, Vec<f64>>>> =
Arc::new(Mutex::new(HashMap::new()));
// AutoScaler metrics retrieval subtask.
tokio::spawn(metric_retriever_loop(
logger.clone(),
kube_config.clone(),
autoscaler_namespace.clone(),
autoscaler.clone(),
interval(Duration::from_secs(metric_period as u64)).take_until(metric_timer_tripwire),
metric_repository.clone(),
));
// AutoScaler reconciliation subtask.
tokio::spawn(reconciliation_loop(
logger.clone(),
kube_config.clone(),
autoscaler_namespace.clone(),
autoscaler.clone(),
interval(Duration::from_secs(period as u64)).take_until(timer_tripwire),
metric_repository.clone(),
));
// AutoScaler update receiver subtask.
tokio::spawn(async move {
let initial_period = autoscaler.read().await.as_ref().unwrap().spec.interval;
debug!(logger, "Starting autoscaler interval source";
"period" => initial_period);
// Process any changes to an AutoScalers timing. And update our shared AutoScaler object.
while let Some(updated_autoscaler) = update_receiver.next().await {
debug!(logger, "Received autoscaler update event");
drop(timer_cancel.take());
drop(metric_timer_cancel.take());
debug!(logger, "Cancelled existing timer driven tasks");
autoscaler.write().await.replace(updated_autoscaler.clone());
debug!(logger, "Updated autoscaler spec");
// Create new timer sources.
let (updated_timer_cancel, updated_timer_tripwire) = Tripwire::new();
let (updated_metric_timer_cancel, updated_metric_timer_tripwire) = Tripwire::new();
timer_cancel.replace(updated_timer_cancel);
metric_timer_cancel.replace(updated_metric_timer_cancel);
debug!(logger, "Spawning updated timer driven tasks");
// Updated AutoScaler metrics retrieval subtask.
tokio::spawn(metric_retriever_loop(
logger.clone(),
kube_config.clone(),
autoscaler_namespace.clone(),
autoscaler.clone(),
interval(Duration::from_secs(
updated_autoscaler.spec.metric.interval as u64,
))
.take_until(updated_metric_timer_tripwire),
metric_repository.clone(),
));
// Updated AutoScaler reconciliation subtask.
tokio::spawn(reconciliation_loop(
logger.clone(),
kube_config.clone(),
autoscaler_namespace.clone(),
autoscaler.clone(),
interval(Duration::from_secs(updated_autoscaler.spec.interval as u64))
.take_until(updated_timer_tripwire),
metric_repository.clone(),
));
}
// Shutdown interval sources, will lead to the completion of subtasks that depend upon them.
// Eg. is used to propagate a full shutdown.
drop(timer_cancel.take());
drop(metric_timer_cancel.take());
debug!(logger, "Cancelled timer driven tasks");
});
Ok(update_sender)
}
async fn reconciliation_loop(
logger: Logger,
kube_config: kube::config::Configuration,
autoscaler_namespace: String,
autoscaler: Arc<RwLock<Option<AutoScaler>>>,
mut timer: TakeUntil<Interval, Tripwire>,
metric_repository: Arc<Mutex<HashMap<String, Vec<f64>>>>,
) {
debug!(logger, "Starting autoscaler task");
while let Some(_) = timer.next().await {
// Create the strategy fresh each time, to simplify handling autoscaler spec changes.
let strategy = match &autoscaler.read().await.as_ref().unwrap().spec.strategy {
AutoScalerStrategyKind::BangBang => {
if let Some(bang_bang) = &autoscaler.read().await.as_ref().unwrap().spec.bang_bang {
Some(AutoScalerStrategy::BangBang(
BangBangAutoScalerStrategy::new(bang_bang.clone()),
))
} else {
None
}
}
};
if let Some(strategy) = strategy {
// Spawn subtasks to handle reconciliation of each matching object.
spawn_reconciliation_tasks(
logger.clone(),
kube_config.clone(),
autoscaler.clone(),
autoscaler_namespace.clone(),
strategy,
metric_repository.clone(),
)
.await;
} else {
error!(
logger,
"Autoscaler is missing required autoscaling strategy configuration"
);
}
}
debug!(logger, "Stopped autoscaler task");
}
/// Task to pull metrics from all objects associated with an AutoScaler.
async fn metric_retriever_loop(
logger: Logger,
kube_config: kube::config::Configuration,
autoscaler_namespace: String,
autoscaler: Arc<RwLock<Option<AutoScaler>>>,
mut metric_timer: TakeUntil<Interval, Tripwire>,
metric_repository: Arc<Mutex<HashMap<String, Vec<f64>>>>,
) {
debug!(logger, "Starting autoscaler metric task");
while let Some(_) = metric_timer.next().await {
let metric_name = autoscaler
.read()
.await
.as_ref()
.unwrap()
.spec
.metric
.name
.clone();
metrics_retriever_task(
logger.clone(),
kube_config.clone(),
autoscaler_namespace.clone(),
autoscaler.clone(),
metric_repository.clone(),
metric_name,
)
.await;
}
debug!(logger, "Stopped autoscaler metric task");
}
/// For each matching object, spawn a new reconciliation subtask.
async fn spawn_reconciliation_tasks(
logger: Logger,
kube_config: kube::config::Configuration,
autoscaler: Arc<RwLock<Option<AutoScaler>>>,
autoscaler_namespace: String,
strategy: AutoScalerStrategy,
metric_repository: Arc<Mutex<HashMap<String, Vec<f64>>>>,
) {
// For each matching object run the reconciliation task.
if let Ok(kubernetes_objects) = matching_objects(
logger.clone(),
kube_config,
autoscaler_namespace,
autoscaler.clone(),
)
.await
{
for kubernetes_object in kubernetes_objects {
// Resolve the name and namespace of the object.
let (object_namespace, object_name) = kubernetes_object.namespace_and_name();
debug!(logger.clone(), "Autoscaler reconciliation task found matching object";
"object_namespace" => &object_namespace,
"object_name" => &object_name);
// Run all the reconciliation tasks in parallel.
tokio::spawn(reconciliation_task(
logger.new(o!(
"object_namespace" => object_namespace.clone(),
"object_name" => object_name.clone())),
autoscaler.clone(),
kubernetes_object,
object_namespace,
object_name,
strategy.clone(),
metric_repository.clone(),
));
}
}
}
/// Perform any reconciliation tasks required in this iteration.
#[allow(clippy::cognitive_complexity)]
async fn reconciliation_task(
logger: Logger,
autoscaler: Arc<RwLock<Option<AutoScaler>>>,
kubernetes_object: KubernetesObject,
object_namespace: String,
object_name: String,
strategy: AutoScalerStrategy,
metric_repository: Arc<Mutex<HashMap<String, Vec<f64>>>>,
) {
// Ensure the object hasn't been recently modified by another pangolin autoscaler.
match kubernetes_object.last_modified().await {
Ok(Some(last_modified)) => {
// Has it been long enough since our last scaling operation?
// We subtract 5 seconds to account for any lag in this processes reconciliation loop.
let utc_now: DateTime<Utc> = Utc::now();
if utc_now.signed_duration_since(last_modified).num_seconds()
< autoscaler.read().await.as_ref().unwrap().spec.interval as i64 - 5
{
warn!(logger, "Autoscaler skipping object due to having been recently modified by another process");
return;
}
}
Ok(None) => (),
Err(err) => {
error!(logger, "Autoscaler skipping object due to error retrieving annotations";
"error" => format!("{}", err));
return;
}
}
// Get the current number of replicas.
let current_replicas = match kubernetes_object.replicas().await {
Ok(current_replicas) => current_replicas,
Err(err) => {
error!(logger, "Autoscaler skipping object due to error retrieving replica count";
"error" => format!("{}", err));
return;
}
};
// Retrieve the latest window of metrics from the repository
let metric_name = autoscaler
.read()
.await
.as_ref()
.unwrap()
.spec
.metric
.name
.clone();
let metric_key = format!("{}/{}/{}", object_namespace, object_name, metric_name);
let current_metric_value = {
if let Some(metric_values) = metric_repository.lock().await.remove(&metric_key) {
debug!(logger, "Found collected metrics for object";
"count" => metric_values.len());
Some(metric_values.iter().sum::<f64>() / metric_values.len() as f64)
} else {
None
}
};
// Do we have any metrics for this object?
if let Some(current_metric_value) = current_metric_value {
// Evaluate the autoscaling strategy.
if let Some(delta) = strategy.evaluate(current_replicas, current_metric_value) {
info!(logger, "Scaling object based on autoscaler strategy";
"aggregate_metric_value" => current_metric_value,
"current_replicas" => current_replicas,
"delta" => delta);
// Verify the action wouldn't exceed a maximum replicas limit.
if let Some(Some(max_replicas)) = autoscaler
.read()
.await
.as_ref()
.unwrap()
.spec
.limits
.as_ref()
.map(|limit| limit.replicas.as_ref().map(|replicas| replicas.max))
{
if current_replicas as i32 + delta >= max_replicas as i32 {
warn!(logger, "Autoscaler refusing to scale up due to maximum replicas";
"max_replicas" => max_replicas,
"current_replicas" => current_replicas,
"delta" => delta);
return;
}
}
// Verify the action wouldn't fall below the minimum replicas limit.
if let Some(Some(min_replicas)) = autoscaler
.read()
.await
.as_ref()
.unwrap()
.spec
.limits
.as_ref()
.map(|limit| limit.replicas.as_ref().map(|replicas| replicas.min))
{
if current_replicas as i32 + delta <= min_replicas as i32 {
warn!(logger, "Autoscaler refusing to scale down due to minimum replicas";
"min_replicas" => min_replicas,
"current_replicas" => current_replicas,
"delta" => delta);
return;
}
}
// Scale the object.
if let Err(err) = kubernetes_object
.scale((current_replicas as i32 + delta) as u32)
.await
{
error!(logger, "Autoscaler encountered error scaling object";
"current_replicas" => current_replicas,
"delta" => delta,
"error" => format!("{}", err));
return;
}
} else {
info!(logger, "Object does not require scaling";
"aggregate_metric_value" => current_metric_value,
"current_replicas" => current_replicas);
}
} else {
// No metrics are available, there are some innocent causes for this, but most of the time
// it is concerning.
error!(logger, "Skipping scaling object due to no available metrics";
"aggregate_metric_value" => current_metric_value,
"current_replicas" => current_replicas,
"metric_name" => metric_name);
}
}
/// Every metrics retrieval interval run task.
async fn metrics_retriever_task(
logger: Logger,
kube_config: kube::config::Configuration,
autoscaler_namespace: String,
autoscaler: Arc<RwLock<Option<AutoScaler>>>,
metric_repository: Arc<Mutex<HashMap<String, Vec<f64>>>>,
metric_name: String,
) {
if let Ok(kubernetes_objects) = matching_objects(
logger.clone(),
kube_config.clone(),
autoscaler_namespace.clone(),
autoscaler.clone(),
)
.await
{
for kubernetes_object in kubernetes_objects {
// Resolve the name and namespace of the object.
let (object_namespace, object_name) = kubernetes_object.namespace_and_name();
debug!(logger.clone(), "Autoscaler metric task found matching object";
"object_namespace" => &object_namespace,
"object_name" => &object_name);
// Get the list of pod ips associated with this deployment.
let pod_ips_and_ports = match kubernetes_object.pod_ips().await {
Ok(pod_ips) => pod_ips
.iter()
.map(|pod_ip| format!("{}:9090", pod_ip))
.collect::<Vec<_>>(),
Err(err) => {
warn!(logger, "Autoscaler metric task skipping object due to error retrieving pod ips";
"error" => format!("{}", err));
return;
}
};
// Pull metrics from all of the pods.
let current_metric_value = match retrieve_aggregate_metric(
logger.clone(),
pod_ips_and_ports.clone(),
&metric_name,
)
.await
{
Ok(Some(current_metric_value)) => current_metric_value,
Ok(None) => {
warn!(
logger,
"Autoscaler metric task skipping object due to no available metrics"
);
return;
}
Err(err) => {
error!(logger, "Autoscaler metric task skipping object due to error pulling metrics";
"error" => format!("{}", err));
return;
}
};
info!(logger, "Successfully pulled autoscaler metric from pods";
"pod_ips_and_ports" => format!("{:?}", pod_ips_and_ports),
"aggregate_metric_value" => current_metric_value);
// Add the received metrics into our shared queue for later pickup by the
// reconciliation subtask.
let metric_key = format!("{}/{}/{}", object_namespace, object_name, metric_name);
{
let mut metric_repository_writer = metric_repository.lock().await;
metric_repository_writer
.entry(metric_key)
.or_insert_with(Vec::new)
.push(current_metric_value);
}
}
}
}
/// Find a list of matching objects for an AutoScaler.
async fn matching_objects(
logger: Logger,
kube_config: kube::config::Configuration,
autoscaler_namespace: String,
autoscaler: Arc<RwLock<Option<AutoScaler>>>,
) -> Result<Vec<KubernetesObject>, Error> {
let resource_kind = autoscaler.read().await.as_ref().unwrap().spec.kind.clone();
let match_labels = autoscaler
.read()
.await
.as_ref()
.unwrap()
.spec
.selector
.match_labels
.clone();
// Construct a client for the expected kubernetes resource kind.
let kubernetes_resource = match resource_kind {
AutoScalerKubernetesResourceKind::Deployment => {
KubernetesResource::Deployment(KubernetesDeploymentResource::new(
kube_config.clone(),
&autoscaler_namespace,
&match_labels,
))
}
AutoScalerKubernetesResourceKind::ReplicaSet => {
KubernetesResource::ReplicaSet(KubernetesReplicaSetResource::new(
kube_config.clone(),
&autoscaler_namespace,
&match_labels,
))
}
AutoScalerKubernetesResourceKind::StatefulSet => {
KubernetesResource::StatefulSet(KubernetesStatefulSetResource::new(
kube_config.clone(),
&autoscaler_namespace,
&match_labels,
))
}
};
// Get the list of matching kubernetes resources.
match kubernetes_resource.list().await {
Ok(kubernetes_objects) => Ok(kubernetes_objects),
Err(err) => {
warn!(logger, "Autoscaler failed to list objects";
"error" => format!("{}", err));
Err(err)
}
}
}
|
/*
chapter 4
primitive types
functions
*/
fn main() {
fn foo(n: i32) -> i32 { n }
let a: fn(i32) -> i32 = foo;
let b = a(8);
println!("{}", b);
}
// output should be:
/*
8
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.