text stringlengths 8 4.13M |
|---|
use assert_cmd::Command;
use std::fs::{read_to_string, File};
use std::io::Write;
use tempfile::tempdir;
#[cfg(feature = "llvm_backend")]
const BACKEND_ARGS: &'static [&'static str] = &["-binterp", "-bllvm", "-bcranelift"];
#[cfg(not(feature = "llvm_backend"))]
const BACKEND_ARGS: &'static [&'static str] = &["-binterp", "-bcranelift"];
// A simple function that looks for the "constant folded" regex instructions in the generated
// output. This is a function that is possible to fool: test cases should be mindful of how it is
// implemented to ensure it is testing what is intended.
//
// We don't build this without llvm at the moment because we only fold constants on higher
// optimization levels.
#[cfg(feature = "llvm_backend")]
fn assert_folded(p: &str) {
let prog: String = p.into();
let out = String::from_utf8(
Command::cargo_bin("frawk")
.unwrap()
.arg(prog.clone())
.arg(String::from("--dump-bytecode"))
.output()
.unwrap()
.stdout,
)
.unwrap();
assert!(out.contains("MatchConst") || out.contains("StartsWithConst"))
}
// Compare two byte slices, up to reordering the lines of each.
fn unordered_output_equals(bs1: &[u8], bs2: &[u8]) {
let mut lines1: Vec<_> = bs1.split(|x| *x == b'\n').collect();
let mut lines2: Vec<_> = bs2.split(|x| *x == b'\n').collect();
lines1.sort();
lines2.sort();
if lines1 != lines2 {
let pretty_1: Vec<_> = lines1.into_iter().map(String::from_utf8_lossy).collect();
let pretty_2: Vec<_> = lines2.into_iter().map(String::from_utf8_lossy).collect();
assert!(
false,
"expected (in any order) {:?}, got {:?}",
pretty_1, pretty_2
);
}
}
#[test]
fn constant_regex_folded() {
// NB: 'function unused()' forces `x` to be global
let prog: String = r#"function unused() { print x; }
BEGIN {
x = "hi";
x=ARGV[1];
print("h" ~ x);
}"#
.into();
for backend_arg in BACKEND_ARGS {
Command::cargo_bin("frawk")
.unwrap()
.arg(String::from(*backend_arg))
.arg(prog.clone())
.arg(String::from("h"))
.assert()
.stdout(String::from("1\n"));
}
#[cfg(feature = "llvm_backend")]
{
assert_folded(
r#"function unused() { print x; }
BEGIN { x = "hi"; print("h" ~ x); }"#,
);
assert_folded(r#"BEGIN { x = "hi"; x = "there"; print("h" ~ x); }"#);
}
}
#[test]
fn simple_fi() {
let input = r#"Item,Count
carrots,2
potato chips,3
custard,1"#;
let expected = "6 3\n";
let tmpdir = tempdir().unwrap();
let data_fname = tmpdir.path().join("numbers");
{
let mut file = File::create(data_fname.clone()).unwrap();
file.write(input.as_bytes()).unwrap();
}
let prog: String = r#"{n+=$FI["Count"]} END { print n, NR; }"#.into();
for backend_arg in BACKEND_ARGS {
Command::cargo_bin("frawk")
.unwrap()
.arg(String::from(*backend_arg))
.arg(String::from("-icsv"))
.arg(String::from("-H"))
.arg(prog.clone())
.arg(fname_to_string(&data_fname))
.assert()
.stdout(expected.clone());
}
}
#[test]
fn file_and_data_arg() {
let input = r#"Hi"#;
let prog = r#"{ print; }"#;
let expected = "Hi\n";
let tmpdir = tempdir().unwrap();
let data_fname = tmpdir.path().join("numbers");
let prog_fname = tmpdir.path().join("prog");
{
let mut data_file = File::create(data_fname.clone()).unwrap();
data_file.write(input.as_bytes()).unwrap();
let mut prog_file = File::create(prog_fname.clone()).unwrap();
prog_file.write(prog.as_bytes()).unwrap();
}
for backend_arg in BACKEND_ARGS {
Command::cargo_bin("frawk")
.unwrap()
.arg(backend_arg)
.arg("-f")
.arg(prog_fname.clone())
.arg(data_fname.clone())
.assert()
.stdout(expected.clone());
}
}
#[test]
fn multiple_files() {
let input = r#"Item,Count
carrots,2
potato chips,3
custard,1"#;
let expected = r#"Item,Count
carrots,2
potato chips,3
custard,1
file 1
file 2 3
"#;
let tmpdir = tempdir().unwrap();
let data_fname = tmpdir.path().join("numbers");
let prog1 = tmpdir.path().join("p1");
let prog2 = tmpdir.path().join("p2");
for (fname, data) in &[
(&data_fname, input),
(
&prog1,
r#"function max(x, y) { return x<y?y:x; } BEGIN { FS = ","; } { print; } END { print "file 1"; } "#,
),
(
&prog2,
r#"{ x = max(int($2), x); } END { print "file 2", x; }"#,
),
] {
let mut file = File::create(fname.clone()).unwrap();
file.write(data.as_bytes()).unwrap();
}
for backend_arg in BACKEND_ARGS {
Command::cargo_bin("frawk")
.unwrap()
.arg(String::from(*backend_arg))
.arg(format!("-f{}", fname_to_string(&prog1)))
.arg(format!("-f{}", fname_to_string(&prog2)))
.arg(fname_to_string(&data_fname))
.assert()
.stdout(expected.clone());
}
}
mod v_args {
//! Tests for v args.
use super::*;
#[test]
fn simple() {
let expected = "1\n";
let prog: String = r#"BEGIN {print x;}"#.into();
for backend_arg in BACKEND_ARGS {
Command::cargo_bin("frawk")
.unwrap()
.arg(String::from(*backend_arg))
.arg(String::from("-vx=1"))
.arg(prog.clone())
.assert()
.stdout(expected.clone());
}
}
#[test]
fn ident_v_arg() {
let expected = "var-with-dash\n";
let prog: String = r#"BEGIN {print x;}"#.into();
for backend_arg in BACKEND_ARGS {
Command::cargo_bin("frawk")
.unwrap()
.arg(String::from(*backend_arg))
.arg(String::from("-vx=var-with-dash"))
.arg(prog.clone())
.assert()
.stdout(expected.clone());
}
}
#[test]
fn ident_v_arg_escape() {
let expected = "var-with\n-dash 1+1\n";
let prog: String = r#"BEGIN {print x, y;}"#.into();
for backend_arg in BACKEND_ARGS {
Command::cargo_bin("frawk")
.unwrap()
.arg(String::from(*backend_arg))
.arg(String::from("-vx=var-with\\n-dash"))
.arg(String::from("-vy=1+1"))
.arg(prog.clone())
.assert()
.stdout(expected.clone());
}
}
}
#[test]
fn mixed_map() {
let expected = "hi 0 5\n1 1 3\n";
let prog: String = r#"BEGIN {
m[1]=2
m["1"]++
m["hi"]=5
for (k in m) {
print k,k+0, m[k]
}}"#
.into();
for backend_arg in BACKEND_ARGS {
let output = Command::cargo_bin("frawk")
.unwrap()
.arg(String::from(*backend_arg))
.arg(prog.clone())
.output()
.unwrap()
.stdout;
unordered_output_equals(expected.as_bytes(), &output[..]);
}
}
#[test]
fn iter_across_functions() {
let input = ",,3,,4\n,,3,,6\n,,4,,5";
let expected = "3 62\n4 30\n";
let tmpdir = tempdir().unwrap();
let data_fname = tmpdir.path().join("numbers");
{
let mut file = File::create(data_fname.clone()).unwrap();
file.write(input.as_bytes()).unwrap();
}
let prog: String = r#"function update(h, k, v) {
h[k] += v*v+v;
}
BEGIN {FS=",";}
{ update(h,$3,$5) }
END {for (k in h) { print k, h[k]; }}"#
.into();
for backend_arg in BACKEND_ARGS {
let output = Command::cargo_bin("frawk")
.unwrap()
.arg(String::from(*backend_arg))
.arg(prog.clone())
.arg(fname_to_string(&data_fname))
.output()
.unwrap()
.stdout;
unordered_output_equals(expected.as_bytes(), &output[..]);
}
}
#[test]
fn simple_rc() {
let expected = "hi\n";
for (prog, rc) in [
(r#"BEGIN { print "hi"; exit(0); print "there"; }"#, 0),
(r#"BEGIN { print "hi"; exit 0; print "there"; }"#, 0),
(r#"BEGIN { print "hi"; exit; print "there"; }"#, 0),
(r#"BEGIN { print "hi"; exit(1); print "there"; }"#, 1),
(r#"BEGIN { print "hi"; exit 1; print "there"; }"#, 1),
(r#"BEGIN { print "hi"; exit(4); print "there"; }"#, 4),
(r#"BEGIN { print "hi"; exit 4; print "there"; }"#, 4),
] {
for backend_arg in BACKEND_ARGS {
Command::cargo_bin("frawk")
.unwrap()
.arg(String::from(*backend_arg))
.arg(String::from(prog))
.assert()
.stdout(expected)
.code(rc);
}
}
}
#[test]
fn trivial_parallel_rc() {
let expected = "hi\n";
for (prog, rc) in [
(r#"BEGIN { print "hi"; exit 0; print "there"; }"#, 0),
(r#"END { print "hi"; exit 1; print "there"; }"#, 1),
] {
for backend_arg in BACKEND_ARGS {
Command::cargo_bin("frawk")
.unwrap()
.arg(String::from(*backend_arg))
.arg(String::from(prog))
.arg("-pr")
.assert()
.stdout(expected)
.code(rc);
}
}
}
#[test]
fn multi_rc() {
let mut text = String::default();
for _ in 0..50_000 {
text.push_str("x\n");
}
let (dir, data) = file_from_string("inputs", &text);
let out = dir.path().join("out");
let prog = format!(
"BEGIN {{ print \"should flush\" > \"{}\"; }} PID == 2 && NR == 100 {{ print \"hi\"; exit 2; }} PREPARE {{ m[PID] = NR; }} END {{ for (k in m) print k, m[k]; }}",
fname_to_string(&out),
);
eprintln!("data={:?}", data);
for backend_arg in BACKEND_ARGS {
Command::cargo_bin("frawk")
.unwrap()
.arg(backend_arg)
.arg("-pf")
.arg("-j2")
.arg(&prog)
.arg(fname_to_string(&data))
.arg(fname_to_string(&data))
.arg(fname_to_string(&data))
.arg(fname_to_string(&data))
.assert()
.stdout("hi\n")
.code(2);
assert_eq!(read_to_string(&out).unwrap(), "should flush\n");
}
}
#[test]
fn nested_loops() {
let expected = "0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2\n";
let prog: String =
"BEGIN { m[0]=0; m[1]=1; m[2]=2; for (i in m) for (j in m) print i,j; }".into();
for backend_arg in BACKEND_ARGS {
let output = Command::cargo_bin("frawk")
.unwrap()
.arg(String::from(*backend_arg))
.arg(prog.clone())
.output()
.unwrap()
.stdout;
unordered_output_equals(expected.as_bytes(), &output[..]);
}
}
#[test]
fn dont_reorder_files_with_f() {
let expected = "1 1\n2 2\n3 3\n";
let prog = "NR == FNR { print NR, FNR}";
let test_data_1 = "1\n2\n3\n";
let test_data_2 = "1\n2\n3\n4\n5\n";
let tmp = tempdir().unwrap();
let prog_file = tmp.path().join("prog");
let f1 = tmp.path().join("f1");
let f2 = tmp.path().join("f2");
File::create(f1.clone())
.unwrap()
.write(test_data_1.as_bytes())
.unwrap();
File::create(f2.clone())
.unwrap()
.write(test_data_2.as_bytes())
.unwrap();
File::create(prog_file.clone())
.unwrap()
.write(prog.as_bytes())
.unwrap();
for backend_arg in BACKEND_ARGS {
Command::cargo_bin("frawk")
.unwrap()
.arg(String::from(*backend_arg))
.arg(format!("-f{}", fname_to_string(&prog_file)))
.arg(fname_to_string(&f1))
.arg(fname_to_string(&f2))
.assert()
.stdout(String::from(expected));
}
}
fn fname_to_string(path: &std::path::PathBuf) -> String {
path.clone().into_os_string().into_string().unwrap()
}
fn file_from_string(
name: impl AsRef<str>,
s: impl AsRef<str>,
) -> (tempfile::TempDir, std::path::PathBuf) {
let tmp = tempdir().unwrap();
let file = tmp.path().join(name.as_ref());
File::create(file.clone())
.unwrap()
.write(s.as_ref().as_bytes())
.unwrap();
(tmp, file)
}
|
use std::io;
fn main() {
println!("here we go!");
loop {
let mut s = String::new();
io::stdin().read_line(&mut s).expect("failed to read!");
let mut sp = s.split(" ");
let vec: Vec<&str> = sp.collect();
for v in &vec {
println!("{}", v);
}
}
}
|
pub mod collection;
pub mod texture;
pub use texture::{Material, Texture, TextureImage, TextureRaw};
use crate::{
linalg::{Ray, Vct},
Flt,
};
#[derive(Copy, Clone, Debug)]
pub struct HitResult {
pub pos: Vct,
pub norm: Vct,
pub texture: TextureRaw,
}
pub type HitTemp = (Flt, Option<(usize, Flt, Flt)>);
pub trait Geo: Send + Sync {
fn hit_t(&self, r: &Ray) -> Option<HitTemp>;
fn hit(&self, r: &Ray, tmp: HitTemp) -> HitResult;
}
|
use graphics::*;
use renderer::*;
use graphics_util::*;
use math::*;
use std::collections::HashMap;
use std::error::Error;
use std::hash::{Hash, Hasher};
use std::rc::*;
use std::cell::{RefCell,Cell};
use std::borrow::BorrowMut;
use std::cell::RefMut;
use na::*;
pub enum RenderLifetime{
Manual,
OneDraw,
}
pub enum RenderTransform{
UI,
World,
None,
}
#[derive(Clone, Copy)]
pub enum RenderID{
ID(usize),
}
#[derive(Debug, Clone, Copy)]
pub struct Camera{
pub pos : Vector3<f32>,
pub look : Vector3<f32>, //TODO Unit<Vector3<f32>>
pub up : Vector3<f32>,
}
impl PartialEq for RenderID{
fn eq(&self, other: &RenderID) -> bool {
match self{
&RenderID::ID(x) => {
match other{
&RenderID::ID(y) => x == y
}
}
}
}
}
impl Eq for RenderID{}
impl Hash for RenderID{
fn hash<H: Hasher>(&self, state: &mut H) {
match self{
&RenderID::ID(x) => {
state.write_usize(x);
state.finish();
}
}
}
}
pub struct RenderDataProvider<'a>{
pub pre_render_state: Option<Box<Fn()->() + 'a>>,
pub post_render_state: Option<Box<Fn()->() + 'a>>,
pub shader_data: Option<Box<Fn(&Program, &WindowInfo, &Camera)->bool + 'a>>, //returns whether to render or not
}
pub struct RenderInfo<'a>{
pub renderer: Box<RendererVertFrag>,
pub provider: RenderDataProvider<'a>,
}
pub struct VoxelRenderer<'a>{
pub lifetime_one_draw_renderers: HashMap<RenderID, RenderInfo<'a>>,
pub lifetime_manual_renderers: HashMap<RenderID, RenderInfo<'a>>,
shaders: &'a HashMap<String, Program>,
render_id_counter: Cell<usize>,
}
impl<'a> VoxelRenderer<'a>{
pub fn new(shaders: &'a HashMap<String, Program>) -> VoxelRenderer<'a>{
VoxelRenderer{
lifetime_one_draw_renderers: HashMap::new(),
lifetime_manual_renderers: HashMap::new(),
shaders,
render_id_counter: Cell::new(0),
}
}
pub fn manual_mut(&mut self, id : &RenderID) -> &mut Box<RendererVertFrag>{
self.lifetime_manual_renderers.get_mut(id).unwrap().renderer.borrow_mut() as &mut Box<RendererVertFrag>
}
pub fn draw(&mut self, win_info: &WindowInfo, camera : &Camera){
for render_info in self.lifetime_one_draw_renderers.values_mut(){
let shader_name = &render_info.renderer.shader_name();
let shader = self.shaders.get(shader_name).unwrap();
shader.enable();
if render_info.provider.pre_render_state.is_some(){
let ref opt = render_info.provider.pre_render_state;
match opt{
&Some(ref x) => (*x)(),
_ => (),
}
}
let ok = {
match render_info.provider.shader_data.as_ref(){
Some(ref x) => {
let res = (*x)(shader, win_info, camera);
res
},
_ => true,
}
};
if(ok){
render_info.renderer.construct();
render_info.renderer.draw();
render_info.renderer.deconstruct();
}
if render_info.provider.post_render_state.is_some(){
let ref opt = render_info.provider.post_render_state;
match opt{
&Some(ref x) => (*x)(),
_ => (),
}
}
shader.disable();
}
for render_info in self.lifetime_manual_renderers.values_mut(){
let shader_name = &render_info.renderer.shader_name();
let shader = self.shaders.get(shader_name).unwrap();
shader.enable();
if render_info.provider.pre_render_state.is_some(){
let ref opt = render_info.provider.pre_render_state;
match opt{
&Some(ref x) => (*x)(),
_ => (),
}
}
let ok = {
match render_info.provider.shader_data.as_ref(){
Some(ref x) => {
let res = (*x)(shader, win_info, camera);
res
},
_ => true,
}
};
//manual construction and deconstruction !
if(ok){ render_info.renderer.draw();};
if render_info.provider.post_render_state.is_some(){
let ref opt = render_info.provider.post_render_state;
match opt{
&Some(ref x) => (*x)(),
_ => (),
}
}
shader.disable();
}
}
pub fn push(&mut self, life: RenderLifetime, trans: RenderTransform, mut renderer: RenderInfo<'a>) -> Result<RenderID, &'static str>{
if !self.shaders.contains_key(&renderer.renderer.shader_name()) {return Err("error: shader not found")}
fn provide_def(shader: &Program, win: &WindowInfo, camera : &Camera) -> bool{ //shader will be already enabled
shader.set_float4x4("P", false, &[
1.0,0.0,0.0,0.0,
0.0,1.0,0.0,0.0,
0.0,0.0,1.0,0.0,
0.0,0.0,0.0,1.0]);
shader.set_float4x4("V", false, &[
1.0,0.0,0.0,0.0,
0.0,1.0,0.0,0.0,
0.0,0.0,1.0,0.0,
0.0,0.0,0.0,1.0]);
true
}
fn provide_ui(shader: &Program, win: &WindowInfo, camera : &Camera) -> bool{ //shader will be already enabled
shader.set_float4x4("P", false, &ortho(
0.0,
win.width as f32,
win.height as f32,
0.0,
-1.0,
1.0));
shader.set_float4x4("V", false, &[
1.0,0.0,0.0,0.0,
0.0,1.0,0.0,0.0,
0.0,0.0,1.0,0.0,
0.0,0.0,0.0,1.0]);
true
}
match trans{
RenderTransform::None => {
match renderer.provider.shader_data{
None => renderer.provider.shader_data = Some(Box::new(provide_def)),
Some(x) =>{
let provide_def_combined = move |shader: &Program, win: &WindowInfo, camera : &Camera|{
provide_def(shader, win, camera);
x(shader, win, camera)
};
renderer.provider.shader_data = Some(Box::new(provide_def_combined) as Box<Fn(&Program, &WindowInfo, &Camera) -> bool>);
}
}
},
RenderTransform::UI => {
match renderer.provider.shader_data{
None => renderer.provider.shader_data = Some(Box::new(provide_ui)),
Some(x) => {
let provide_ui_combined = move |shader: &Program, win: &WindowInfo, camera : &Camera|{
provide_ui(shader, win, camera);
x(shader, win, camera)
};
renderer.provider.shader_data = Some(Box::new(provide_ui_combined) as Box<Fn(&Program, &WindowInfo, &Camera) -> bool>);
}
}
},
RenderTransform::World => {
unimplemented!();
}
};
let rid = RenderID::ID(self.render_id_counter.get());
match life{
RenderLifetime::Manual => {
self.lifetime_manual_renderers.insert(rid, renderer);
},
RenderLifetime::OneDraw => {
self.lifetime_one_draw_renderers.insert(rid, renderer);
}
};
self.render_id_counter.set(self.render_id_counter.get() + 1);
Ok(rid)
}
}
|
//! Main functions doing actual work.
//!
//! Use `guess_format()` to get teh image format from a path,
//! then read the image using `load_image()`,
//! resize it to terminal size with `resize_image()`
//! and display it with `write_[no_]ansi()`.
use self::super::util::{ANSI_BG_COLOUR_ESCAPES, ANSI_COLOURS, JPEG_MAGIC, BMP_MAGIC, ICO_MAGIC, GIF_MAGIC, PNG_MAGIC, closest_colour};
use image::{self, GenericImage, DynamicImage, ImageFormat, FilterType, Pixel};
use std::io::{BufReader, Write, Read};
use self::super::Outcome;
use std::path::PathBuf;
use std::fs::File;
mod no_ansi;
pub use self::no_ansi::write_no_ansi;
/// Guess the image format from its extension or magic.
///
/// # Examples
///
/// Correct:
///
/// ```
/// # extern crate image;
/// # extern crate termimage;
/// # use image::ImageFormat;
/// # use std::path::PathBuf;
/// # use termimage::ops::guess_format;
/// # fn main() {
/// assert_eq!(guess_format(&(String::new(), PathBuf::from("img.png"))), Ok(ImageFormat::PNG));
/// assert_eq!(guess_format(&(String::new(), PathBuf::from("img.jpg"))), Ok(ImageFormat::JPEG));
/// assert_eq!(guess_format(&(String::new(), PathBuf::from("img.gif"))), Ok(ImageFormat::GIF));
/// assert_eq!(guess_format(&(String::new(), PathBuf::from("img.bmp"))), Ok(ImageFormat::BMP));
/// assert_eq!(guess_format(&(String::new(), PathBuf::from("img.ico"))), Ok(ImageFormat::ICO));
/// # }
/// ```
///
/// Incorrect:
///
/// ```
/// # use std::path::PathBuf;
/// # use termimage::Outcome;
/// # use termimage::ops::guess_format;
/// assert_eq!(guess_format(&("src/ops.rs".to_string(), PathBuf::from("src/ops/mod.rs"))),
/// Err(Outcome::GuessingFormatFailed("src/ops.rs".to_string())));
/// ```
pub fn guess_format(file: &(String, PathBuf)) -> Result<ImageFormat, Outcome> {
file.1
.extension()
.and_then(|ext| match &ext.to_str().unwrap().to_lowercase()[..] {
"png" => Some(Ok(ImageFormat::PNG)),
"jpg" | "jpeg" | "jpe" | "jif" | "jfif" | "jfi" => Some(Ok(ImageFormat::JPEG)),
"gif" => Some(Ok(ImageFormat::GIF)),
"webp" => Some(Ok(ImageFormat::WEBP)),
"ppm" => Some(Ok(ImageFormat::PPM)),
"tiff" | "tif" => Some(Ok(ImageFormat::TIFF)),
"tga" => Some(Ok(ImageFormat::TGA)),
"bmp" | "dib" => Some(Ok(ImageFormat::BMP)),
"ico" => Some(Ok(ImageFormat::ICO)),
"hdr" => Some(Ok(ImageFormat::HDR)),
_ => None,
})
.unwrap_or_else(|| {
let mut buf = [0; 32];
let read = try!(File::open(&file.1).map_err(|_| Outcome::OpeningImageFailed(file.0.clone()))).read(&mut buf).unwrap();
let buf = &buf[..read];
if buf.len() >= PNG_MAGIC.len() && &buf[..PNG_MAGIC.len()] == PNG_MAGIC {
Ok(ImageFormat::PNG)
} else if buf.len() >= JPEG_MAGIC.len() && &buf[..JPEG_MAGIC.len()] == JPEG_MAGIC {
Ok(ImageFormat::JPEG)
} else if buf.len() >= GIF_MAGIC.len() && &buf[..GIF_MAGIC.len()] == GIF_MAGIC {
Ok(ImageFormat::GIF)
} else if buf.len() >= BMP_MAGIC.len() && &buf[..BMP_MAGIC.len()] == BMP_MAGIC {
Ok(ImageFormat::BMP)
} else if buf.len() >= ICO_MAGIC.len() && &buf[..ICO_MAGIC.len()] == ICO_MAGIC {
Ok(ImageFormat::ICO)
} else {
Err(Outcome::GuessingFormatFailed(file.0.clone()))
}
})
}
/// Load an image from the specified file as the specified format.
///
/// Get the image fromat with `guess_format()`.
pub fn load_image(file: &(String, PathBuf), format: ImageFormat) -> Result<DynamicImage, Outcome> {
Ok(image::load(BufReader::new(try!(File::open(&file.1).map_err(|_| Outcome::OpeningImageFailed(file.0.clone())))),
format)
.unwrap())
}
/// Resize the specified image to the specified size, optionally preserving its aspect ratio.
pub fn resize_image(img: &DynamicImage, size: (u32, u32), preserve_aspect: bool) -> DynamicImage {
if preserve_aspect {
img.resize(size.0, size.1, FilterType::Nearest)
} else {
img.resize_exact(size.0, size.1, FilterType::Nearest)
}
}
/// Display the specified image in the default console using ANSI escape codes.
pub fn write_ansi<W: Write>(out: &mut W, img: &DynamicImage) {
let (width, height) = img.dimensions();
for y in 0..height {
for x in 0..width {
let closest_clr = closest_colour(img.get_pixel(x, y).to_rgb(), ANSI_COLOURS);
write!(out, "{} ", ANSI_BG_COLOUR_ESCAPES[closest_clr]).unwrap();
}
writeln!(out, "{}", ANSI_BG_COLOUR_ESCAPES[0]).unwrap();
}
}
|
use super::{
retries::{FixedRetryPolicy, RetryLogic},
sink::Response,
Batch, BatchSink,
};
use crate::buffers::Acker;
use futures01::{Async, Future, Poll};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::{error, fmt};
use tokio01::timer::Delay;
use tower::{
layer::{util::Stack, Layer},
limit::{concurrency::ConcurrencyLimit, rate::RateLimit},
retry::Retry,
util::BoxService,
Service, ServiceBuilder,
};
pub type TowerBatchedSink<S, B, L, Request> =
BatchSink<ConcurrencyLimit<RateLimit<Retry<FixedRetryPolicy<L>, Timeout<S>>>>, B, Request>;
pub trait ServiceBuilderExt<L> {
fn map<R1, R2, F>(self, f: F) -> ServiceBuilder<Stack<MapLayer<R1, R2>, L>>
where
F: Fn(R1) -> R2 + Send + Sync + 'static;
fn settings<RL, Request>(
self,
settings: TowerRequestSettings,
retry_logic: RL,
) -> ServiceBuilder<Stack<TowerRequestLayer<RL, Request>, L>>;
}
impl<L> ServiceBuilderExt<L> for ServiceBuilder<L> {
fn map<R1, R2, F>(self, f: F) -> ServiceBuilder<Stack<MapLayer<R1, R2>, L>>
where
F: Fn(R1) -> R2 + Send + Sync + 'static,
{
self.layer(MapLayer { f: Arc::new(f) })
}
fn settings<RL, Request>(
self,
settings: TowerRequestSettings,
retry_logic: RL,
) -> ServiceBuilder<Stack<TowerRequestLayer<RL, Request>, L>> {
self.layer(TowerRequestLayer {
settings,
retry_logic,
_pd: std::marker::PhantomData,
})
}
}
/// Tower Request based configuration
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
pub struct TowerRequestConfig {
pub in_flight_limit: Option<usize>, // 5
pub timeout_secs: Option<u64>, // 60
pub rate_limit_duration_secs: Option<u64>, // 1
pub rate_limit_num: Option<u64>, // 5
pub retry_attempts: Option<usize>, // max_value()
pub retry_max_duration_secs: Option<u64>,
pub retry_initial_backoff_secs: Option<u64>, // 1
}
impl TowerRequestConfig {
pub fn unwrap_with(&self, defaults: &TowerRequestConfig) -> TowerRequestSettings {
TowerRequestSettings {
in_flight_limit: self
.in_flight_limit
.or(defaults.in_flight_limit)
.unwrap_or(5),
timeout: Duration::from_secs(self.timeout_secs.or(defaults.timeout_secs).unwrap_or(60)),
rate_limit_duration: Duration::from_secs(
self.rate_limit_duration_secs
.or(defaults.rate_limit_duration_secs)
.unwrap_or(1),
),
rate_limit_num: self.rate_limit_num.or(defaults.rate_limit_num).unwrap_or(5),
retry_attempts: self
.retry_attempts
.or(defaults.retry_attempts)
.unwrap_or(usize::max_value()),
retry_max_duration_secs: Duration::from_secs(
self.retry_max_duration_secs
.or(defaults.retry_max_duration_secs)
.unwrap_or(3600),
),
retry_initial_backoff_secs: Duration::from_secs(
self.retry_initial_backoff_secs
.or(defaults.retry_initial_backoff_secs)
.unwrap_or(1),
),
}
}
}
#[derive(Debug, Clone)]
pub struct TowerRequestSettings {
pub in_flight_limit: usize,
pub timeout: Duration,
pub rate_limit_duration: Duration,
pub rate_limit_num: u64,
pub retry_attempts: usize,
pub retry_max_duration_secs: Duration,
pub retry_initial_backoff_secs: Duration,
}
impl TowerRequestSettings {
pub fn retry_policy<L: RetryLogic>(&self, logic: L) -> FixedRetryPolicy<L> {
FixedRetryPolicy::new(
self.retry_attempts,
self.retry_initial_backoff_secs,
self.retry_max_duration_secs,
logic,
)
}
pub fn batch_sink<B, L, S, Request>(
&self,
retry_logic: L,
service: S,
batch: B,
batch_timeout: Duration,
acker: Acker,
) -> TowerBatchedSink<S, B, L, Request>
// Would like to return `impl Sink + SinkExt<T>` here, but that
// doesn't work with later calls to `batched_with_min` etc (via
// `trait SinkExt` above), as it is missing a bound on the
// associated types that cannot be expressed in stable Rust.
where
L: RetryLogic<Response = S::Response> + Send + 'static,
S: Service<Request> + Clone + Send + 'static,
S::Error: Into<crate::Error> + Send + Sync + 'static,
S::Response: Send + Response,
S::Future: Send + 'static,
B: Batch<Output = Request>,
Request: Send + Clone + 'static,
{
let policy = self.retry_policy(retry_logic);
let service = ServiceBuilder::new()
.concurrency_limit(self.in_flight_limit)
.rate_limit(self.rate_limit_num, self.rate_limit_duration)
.retry(policy)
.layer(TimeoutLayer {
timeout: self.timeout,
})
.service(service);
BatchSink::new(service, batch, batch_timeout, acker)
}
}
#[derive(Debug, Clone)]
pub struct TowerRequestLayer<L, Request> {
settings: TowerRequestSettings,
retry_logic: L,
_pd: std::marker::PhantomData<Request>,
}
impl<S, L, Request> tower::layer::Layer<S> for TowerRequestLayer<L, Request>
where
S: Service<Request> + Send + Clone + 'static,
S::Response: Response + Send + 'static,
S::Error: Into<crate::Error> + Send + Sync + 'static,
S::Future: Send + 'static,
L: RetryLogic<Response = S::Response> + Send + 'static,
Request: Clone + Send + 'static,
{
type Service = BoxService<Request, S::Response, crate::Error>;
fn layer(&self, inner: S) -> Self::Service {
let policy = self.settings.retry_policy(self.retry_logic.clone());
let l = ServiceBuilder::new()
.concurrency_limit(self.settings.in_flight_limit)
.rate_limit(
self.settings.rate_limit_num,
self.settings.rate_limit_duration,
)
.retry(policy)
.layer(TimeoutLayer {
timeout: self.settings.timeout,
})
.service(inner);
BoxService::new(l)
}
}
// === map ===
pub struct MapLayer<R1, R2> {
f: Arc<dyn Fn(R1) -> R2 + Send + Sync + 'static>,
}
impl<S, R1, R2> Layer<S> for MapLayer<R1, R2>
where
S: Service<R2>,
{
type Service = Map<S, R1, R2>;
fn layer(&self, inner: S) -> Self::Service {
Map {
f: Arc::clone(&self.f),
inner,
}
}
}
pub struct Map<S, R1, R2> {
f: Arc<dyn Fn(R1) -> R2 + Send + Sync + 'static>,
inner: S,
}
impl<S, R1, R2> Service<R1> for Map<S, R1, R2>
where
S: Service<R2>,
crate::Error: From<S::Error>,
{
type Response = S::Response;
type Error = crate::Error;
type Future = futures01::future::MapErr<S::Future, fn(S::Error) -> crate::Error>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.inner.poll_ready().map_err(Into::into)
}
fn call(&mut self, req: R1) -> Self::Future {
let req = (self.f)(req);
self.inner.call(req).map_err(|e| e.into())
}
}
impl<S: Clone, R1, R2> Clone for Map<S, R1, R2> {
fn clone(&self) -> Self {
Self {
f: Arc::clone(&self.f),
inner: self.inner.clone(),
}
}
}
// === timeout ===
/// Applies a timeout to requests.
///
/// We require our own timeout layer because the current
/// 0.1 version uses From intead of Into bounds for errors
/// this casues the whole stack to not align and not compile.
/// In future versions of tower this should be fixed.
#[derive(Debug, Clone)]
pub struct Timeout<T> {
inner: T,
timeout: Duration,
}
// ===== impl Timeout =====
impl<S, Request> Service<Request> for Timeout<S>
where
S: Service<Request>,
S::Error: Into<crate::Error>,
{
type Response = S::Response;
type Error = crate::Error;
type Future = ResponseFuture<S::Future>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.inner.poll_ready().map_err(Into::into)
}
fn call(&mut self, request: Request) -> Self::Future {
let response = self.inner.call(request);
let sleep = Delay::new(Instant::now() + self.timeout);
ResponseFuture { response, sleep }
}
}
/// Applies a timeout to requests via the supplied inner service.
#[derive(Debug)]
pub struct TimeoutLayer {
timeout: Duration,
}
impl TimeoutLayer {
/// Create a timeout from a duration
pub fn new(timeout: Duration) -> Self {
TimeoutLayer { timeout }
}
}
impl<S> Layer<S> for TimeoutLayer {
type Service = Timeout<S>;
fn layer(&self, service: S) -> Self::Service {
Timeout {
inner: service,
timeout: self.timeout,
}
}
}
/// `Timeout` response future
#[derive(Debug)]
pub struct ResponseFuture<T> {
response: T,
sleep: Delay,
}
impl<T> Future for ResponseFuture<T>
where
T: Future,
T::Error: Into<crate::Error>,
{
type Item = T::Item;
type Error = crate::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
// First, try polling the future
match self.response.poll().map_err(Into::into)? {
Async::Ready(v) => return Ok(Async::Ready(v)),
Async::NotReady => {}
}
// Now check the sleep
match self.sleep.poll()? {
Async::NotReady => Ok(Async::NotReady),
Async::Ready(_) => Err(Elapsed(()).into()),
}
}
}
#[derive(Debug, Default)]
pub struct Elapsed(pub(super) ());
impl fmt::Display for Elapsed {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("request timed out")
}
}
impl error::Error for Elapsed {}
// rustc issue: https://github.com/rust-lang/rust/issues/71259
#[cfg(feature = "disabled")]
#[cfg(test)]
mod tests {
use super::*;
use futures01::Future;
use std::sync::Arc;
use tokio01_test::{assert_ready, task::MockTask};
use tower::layer::Layer;
use tower_test::{assert_request_eq, mock};
#[test]
fn map() {
let mut task = MockTask::new();
let (mock, mut handle) = mock::pair();
let f = |r| r;
let map_layer = MapLayer { f: Arc::new(f) };
let mut svc = map_layer.layer(mock);
task.enter(|| assert_ready!(svc.poll_ready()));
let res = svc.call("hello world");
assert_request_eq!(handle, "hello world").send_response("world bye");
res.wait().unwrap();
}
}
|
// Copyright (c) 2017 Martijn Rijkeboer <mrr@sru-systems.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::{error, fmt};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// Error type for Argon2 errors.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum Error {
/// The output (hash) is too short (minimum is 4).
OutputTooShort,
/// The output (hash) is too long (maximum is 2^32 - 1).
OutputTooLong,
/// The password is too short (minimum is 0).
PwdTooShort,
/// The password is too long (maximum is 2^32 - 1).
PwdTooLong,
/// The salt is too short (minimum is 8).
SaltTooShort,
/// The salt is too long (maximum is 2^32 - 1).
SaltTooLong,
/// The associated data is too short (minimum is 0).
AdTooShort,
/// The associated data is too long (maximum is 2^32 - 1).
AdTooLong,
/// The secret value is too short (minimum is 0).
SecretTooShort,
/// The secret value is too long (maximum is 2^32 - 1).
SecretTooLong,
/// The time cost (passes) is too small (minimum is 1).
TimeTooSmall,
/// The time cost (passes) is too large (maximum is 2^32 - 1).
TimeTooLarge,
/// The memory cost is too small (minimum is 8 x parallelism).
MemoryTooLittle,
/// The memory cost is too large (maximum 2GiB on 32-bit or 4TiB on 64-bit).
MemoryTooMuch,
/// The number of lanes (parallelism) is too small (minimum is 1).
LanesTooFew,
/// The number of lanes (parallelism) is too large (maximum is 2^24 - 1).
LanesTooMany,
/// Incorrect Argon2 variant.
IncorrectType,
/// Incorrect Argon2 version.
IncorrectVersion,
/// The decoding of the encoded data has failed.
DecodingFail,
}
impl Error {
fn msg(&self) -> &str {
match *self {
Error::OutputTooShort => "Output is too short",
Error::OutputTooLong => "Output is too long",
Error::PwdTooShort => "Password is too short",
Error::PwdTooLong => "Password is too long",
Error::SaltTooShort => "Salt is too short",
Error::SaltTooLong => "Salt is too long",
Error::AdTooShort => "Associated data is too short",
Error::AdTooLong => "Associated data is too long",
Error::SecretTooShort => "Secret is too short",
Error::SecretTooLong => "Secret is too long",
Error::TimeTooSmall => "Time cost is too small",
Error::TimeTooLarge => "Time cost is too large",
Error::MemoryTooLittle => "Memory cost is too small",
Error::MemoryTooMuch => "Memory cost is too large",
Error::LanesTooFew => "Too few lanes",
Error::LanesTooMany => "Too many lanes",
Error::IncorrectType => "There is no such type of Argon2",
Error::IncorrectVersion => "There is no such version of Argon2",
Error::DecodingFail => "Decoding failed",
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.msg())
}
}
impl error::Error for Error {
fn description(&self) -> &str {
self.msg()
}
fn cause(&self) -> Option<&dyn error::Error> {
None
}
}
impl From<base64::DecodeError> for Error {
fn from(_: base64::DecodeError) -> Self {
Error::DecodingFail
}
}
|
pub mod rpc;
pub mod header;
|
#[doc = "Reader of register ISR"]
pub type R = crate::R<u32, super::ISR>;
#[doc = "Reader of field `GIF0`"]
pub type GIF0_R = crate::R<bool, bool>;
#[doc = "Reader of field `TCIF1`"]
pub type TCIF1_R = crate::R<bool, bool>;
#[doc = "Reader of field `HTIF2`"]
pub type HTIF2_R = crate::R<bool, bool>;
#[doc = "Reader of field `TEIF3`"]
pub type TEIF3_R = crate::R<bool, bool>;
#[doc = "Reader of field `GIF4`"]
pub type GIF4_R = crate::R<bool, bool>;
#[doc = "Reader of field `TCIF5`"]
pub type TCIF5_R = crate::R<bool, bool>;
#[doc = "Reader of field `HTIF6`"]
pub type HTIF6_R = crate::R<bool, bool>;
#[doc = "Reader of field `TEIF7`"]
pub type TEIF7_R = crate::R<bool, bool>;
#[doc = "Reader of field `GIF8`"]
pub type GIF8_R = crate::R<bool, bool>;
#[doc = "Reader of field `TCIF9`"]
pub type TCIF9_R = crate::R<bool, bool>;
#[doc = "Reader of field `HTIF10`"]
pub type HTIF10_R = crate::R<bool, bool>;
#[doc = "Reader of field `TEIF11`"]
pub type TEIF11_R = crate::R<bool, bool>;
#[doc = "Reader of field `GIF12`"]
pub type GIF12_R = crate::R<bool, bool>;
#[doc = "Reader of field `TCIF13`"]
pub type TCIF13_R = crate::R<bool, bool>;
#[doc = "Reader of field `HTIF14`"]
pub type HTIF14_R = crate::R<bool, bool>;
#[doc = "Reader of field `TEIF15`"]
pub type TEIF15_R = crate::R<bool, bool>;
#[doc = "Reader of field `GIF16`"]
pub type GIF16_R = crate::R<bool, bool>;
#[doc = "Reader of field `TCIF17`"]
pub type TCIF17_R = crate::R<bool, bool>;
#[doc = "Reader of field `HTIF18`"]
pub type HTIF18_R = crate::R<bool, bool>;
#[doc = "Reader of field `TEIF19`"]
pub type TEIF19_R = crate::R<bool, bool>;
#[doc = "Reader of field `GIF20`"]
pub type GIF20_R = crate::R<bool, bool>;
#[doc = "Reader of field `TCIF21`"]
pub type TCIF21_R = crate::R<bool, bool>;
#[doc = "Reader of field `HTIF22`"]
pub type HTIF22_R = crate::R<bool, bool>;
#[doc = "Reader of field `TEIF23`"]
pub type TEIF23_R = crate::R<bool, bool>;
#[doc = "Reader of field `GIF24`"]
pub type GIF24_R = crate::R<bool, bool>;
#[doc = "Reader of field `TCIF25`"]
pub type TCIF25_R = crate::R<bool, bool>;
#[doc = "Reader of field `HTIF26`"]
pub type HTIF26_R = crate::R<bool, bool>;
#[doc = "Reader of field `TEIF27`"]
pub type TEIF27_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Channel global interrupt flag"]
#[inline(always)]
pub fn gif0(&self) -> GIF0_R {
GIF0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Channel transfer complete flag"]
#[inline(always)]
pub fn tcif1(&self) -> TCIF1_R {
TCIF1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Channel half transfer flag"]
#[inline(always)]
pub fn htif2(&self) -> HTIF2_R {
HTIF2_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Channel transfer error flag"]
#[inline(always)]
pub fn teif3(&self) -> TEIF3_R {
TEIF3_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Channel global interrupt flag"]
#[inline(always)]
pub fn gif4(&self) -> GIF4_R {
GIF4_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Channel transfer complete flag"]
#[inline(always)]
pub fn tcif5(&self) -> TCIF5_R {
TCIF5_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Channel half transfer flag"]
#[inline(always)]
pub fn htif6(&self) -> HTIF6_R {
HTIF6_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - Channel transfer error flag"]
#[inline(always)]
pub fn teif7(&self) -> TEIF7_R {
TEIF7_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - Channel global interrupt flag"]
#[inline(always)]
pub fn gif8(&self) -> GIF8_R {
GIF8_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - Channel transfer complete flag"]
#[inline(always)]
pub fn tcif9(&self) -> TCIF9_R {
TCIF9_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - Channel half transfer flag"]
#[inline(always)]
pub fn htif10(&self) -> HTIF10_R {
HTIF10_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - Channel transfer error flag"]
#[inline(always)]
pub fn teif11(&self) -> TEIF11_R {
TEIF11_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - Channel global interrupt flag"]
#[inline(always)]
pub fn gif12(&self) -> GIF12_R {
GIF12_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - Channel transfer complete flag"]
#[inline(always)]
pub fn tcif13(&self) -> TCIF13_R {
TCIF13_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - Channel half transfer flag"]
#[inline(always)]
pub fn htif14(&self) -> HTIF14_R {
HTIF14_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - Channel transfer error flag"]
#[inline(always)]
pub fn teif15(&self) -> TEIF15_R {
TEIF15_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - Channel global interrupt flag"]
#[inline(always)]
pub fn gif16(&self) -> GIF16_R {
GIF16_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - Channel transfer complete flag"]
#[inline(always)]
pub fn tcif17(&self) -> TCIF17_R {
TCIF17_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - Channel half transfer flag"]
#[inline(always)]
pub fn htif18(&self) -> HTIF18_R {
HTIF18_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 19 - Channel transfer error flag"]
#[inline(always)]
pub fn teif19(&self) -> TEIF19_R {
TEIF19_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 20 - Channel global interrupt flag"]
#[inline(always)]
pub fn gif20(&self) -> GIF20_R {
GIF20_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 21 - Channel transfer complete flag"]
#[inline(always)]
pub fn tcif21(&self) -> TCIF21_R {
TCIF21_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 22 - Channel half transfer flag"]
#[inline(always)]
pub fn htif22(&self) -> HTIF22_R {
HTIF22_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 23 - Channel transfer error flag"]
#[inline(always)]
pub fn teif23(&self) -> TEIF23_R {
TEIF23_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 24 - Channel global interrupt flag"]
#[inline(always)]
pub fn gif24(&self) -> GIF24_R {
GIF24_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 25 - Channel transfer complete flag"]
#[inline(always)]
pub fn tcif25(&self) -> TCIF25_R {
TCIF25_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 26 - Channel half transfer flag"]
#[inline(always)]
pub fn htif26(&self) -> HTIF26_R {
HTIF26_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bit 27 - Channel transfer error flag"]
#[inline(always)]
pub fn teif27(&self) -> TEIF27_R {
TEIF27_R::new(((self.bits >> 27) & 0x01) != 0)
}
}
|
use crate::unicode_tables::{general_category::GC, script_values::SCRIPT, GC_AND_BP};
/// Validate a `LoneUnicodePropertyNameOrValue`
/// is a valid name or value
///
/// ex:
/// ```js
/// let re = /\p{White_Space}\p{Alphabetic}/;
/// ```
///
/// This function will first search the General_Category
/// names and aliases and then the Binary Property
/// names and aliases
pub fn validate_name_or_value(name: &str) -> bool {
GC_AND_BP.binary_search(&name).is_ok()
}
/// Validate a `UnicodePropertyName` and `UnicodePropertyValue`
/// are correct
///
///
/// ex:
/// ```js
/// let re = /\p{Script=Greek}\p{gc=Lm}/
/// ```
///
/// valid names include `General_Category`, `gc`, `Script`,
/// `Script_Extensions`, `sc` and `scx`
/// any other names will return false
pub fn validate_name_and_value(name: &str, value: &str) -> bool {
if let Some(set) = validate_name(name) {
set.binary_search(&value).is_ok()
} else {
false
}
}
/// Validate a name is `General_Category`, `gc`, `Script`,
/// `Script_Extensions`, `sc` or `scx`. This will return
/// Some with the correct list of possible values
/// None, otherwise
pub fn validate_name(name: &str) -> Option<&[&str]> {
if name == "General_Category" || name == "gc" {
Some(GC)
} else if name == "Script" || name == "sc" || name == "Script_Extensions" || name == "scx" {
Some(SCRIPT)
} else {
None
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn name_and_value() {
for value in GC {
assert!(validate_name_and_value("General_Category", value));
assert!(validate_name_and_value("gc", value));
}
assert!(!validate_name_and_value("General_Category", "junk"));
assert!(!validate_name_and_value("gc", "junk"));
for value in SCRIPT {
assert!(validate_name_and_value("Script", value));
assert!(validate_name_and_value("Script_Extensions", value));
assert!(validate_name_and_value("sc", value));
assert!(validate_name_and_value("scx", value));
}
assert!(!validate_name_and_value("Script", "junk"));
assert!(!validate_name_and_value("Script_Extensions", "junk"));
assert!(!validate_name_and_value("sc", "junk"));
assert!(!validate_name_and_value("scx", "junk"));
}
#[test]
fn name_or_value() {
for value in GC_AND_BP {
assert!(validate_name_or_value(value));
}
assert!(!validate_name_or_value("junk"));
}
}
|
//! Integrates tokio runtime stats into the IOx metric system.
//!
//! This is NOT called `tokio-metrics` since this name is already taken.
#![deny(rustdoc::broken_intra_doc_links, rust_2018_idioms)]
#![warn(
missing_copy_implementations,
missing_docs,
clippy::explicit_iter_loop,
// See https://github.com/influxdata/influxdb_iox/pull/1671
clippy::future_not_send,
clippy::use_self,
clippy::clone_on_ref_ptr,
clippy::todo,
clippy::dbg_macro,
unused_crate_dependencies
)]
#[cfg(not(tokio_unstable))]
mod not_tokio_unstable {
use metric as _;
use parking_lot as _;
use tokio as _;
use workspace_hack as _;
}
#[cfg(tokio_unstable)]
mod bridge;
#[cfg(tokio_unstable)]
pub use bridge::*;
|
use std::collections::HashMap;
use std::cmp::min;
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::collections::{LazyOption, LookupMap, UnorderedMap, UnorderedSet};
use near_sdk::json_types::{Base64VecU8, ValidAccountId, U64, U128};
use near_sdk::serde::{Deserialize, Serialize};
use near_sdk::{
env, near_bindgen, AccountId, Balance, CryptoHash, PanicOnDefault, Promise, StorageUsage,
};
use crate::internal::*;
pub use crate::metadata::*;
pub use crate::mint::*;
pub use crate::nft_core::*;
pub use crate::token::*;
pub use crate::enumerable::*;
mod internal;
mod metadata;
mod mint;
mod nft_core;
mod token;
mod enumerable;
// CUSTOM types
pub type TokenType = String;
pub type TypeSupplyCaps = HashMap<TokenType, U64>;
pub const CONTRACT_ROYALTY_CAP: u32 = 1000;
pub const MINTER_ROYALTY_CAP: u32 = 9000;
pub const MAX_PROFILE_BIO_LENGTH: usize = 256;
pub const MAX_PROFILE_IMAGE_LENGTH: usize = 256;
near_sdk::setup_alloc!();
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)]
pub struct Contract {
pub tokens_per_owner: LookupMap<AccountId, UnorderedSet<TokenId>>,
pub tokens_per_creator: LookupMap<AccountId, UnorderedSet<TokenId>>,
pub tokens_by_id: LookupMap<TokenId, Token>,
pub token_metadata_by_id: UnorderedMap<TokenId, TokenMetadata>,
pub owner_id: AccountId,
/// The storage size in bytes for one account.
pub extra_storage_in_bytes_per_token: StorageUsage,
pub metadata: LazyOption<NFTMetadata>,
/// CUSTOM fields
pub supply_cap_by_type: TypeSupplyCaps,
pub tokens_per_type: LookupMap<TokenType, UnorderedSet<TokenId>>,
pub token_types_locked: UnorderedSet<TokenType>,
pub contract_royalty: u32,
pub profiles: LookupMap<AccountId, Profile>,
pub use_storage_fees: bool,
pub free_mints: u64,
pub version: u16,
}
#[derive(Debug, Clone, BorshDeserialize, BorshSerialize, Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct Profile {
pub bio: String,
pub image: String,
}
/// Helper structure to for keys of the persistent collections.
#[derive(BorshSerialize)]
pub enum StorageKey {
TokensPerOwner,
TokenPerOwnerInner { account_id_hash: CryptoHash },
TokensPerCreator,
TokenPerCreatorInner { account_id_hash: CryptoHash },
TokensById,
TokenMetadataById,
NftMetadata,
TokensPerType,
TokensPerTypeInner { token_type_hash: CryptoHash },
TokenTypesLocked,
Profiles,
}
#[near_bindgen]
impl Contract {
#[init]
pub fn new(owner_id: ValidAccountId,
metadata: NFTMetadata,
supply_cap_by_type: TypeSupplyCaps,
use_storage_fees: bool,
free_mints: u64,
unlocked: Option<bool>,
) -> Self {
let mut this = Self {
tokens_per_owner: LookupMap::new(StorageKey::TokensPerOwner.try_to_vec().unwrap()),
tokens_per_creator: LookupMap::new(StorageKey::TokensPerCreator.try_to_vec().unwrap()),
tokens_by_id: LookupMap::new(StorageKey::TokensById.try_to_vec().unwrap()),
token_metadata_by_id: UnorderedMap::new(
StorageKey::TokenMetadataById.try_to_vec().unwrap(),
),
owner_id: owner_id.into(),
extra_storage_in_bytes_per_token: 0,
metadata: LazyOption::new(
StorageKey::NftMetadata.try_to_vec().unwrap(),
Some(&metadata),
),
supply_cap_by_type,
tokens_per_type: LookupMap::new(StorageKey::TokensPerType.try_to_vec().unwrap()),
token_types_locked: UnorderedSet::new(StorageKey::TokenTypesLocked.try_to_vec().unwrap()),
contract_royalty: 0,
profiles: LookupMap::new(StorageKey::Profiles.try_to_vec().unwrap()),
use_storage_fees,
free_mints,
version: 0,
};
if unlocked.is_none() {
// CUSTOM - tokens are locked by default
for token_type in this.supply_cap_by_type.keys() {
this.token_types_locked.insert(&token_type);
}
}
this.measure_min_token_storage_cost();
this
}
#[init(ignore_state)]
pub fn migrate_state_1() -> Self {
let migration_version: u16 = 1;
assert_eq!(env::predecessor_account_id(), env::current_account_id(), "Private function");
#[derive(BorshDeserialize)]
struct OldContract {
tokens_per_owner: LookupMap<AccountId, UnorderedSet<TokenId>>,
tokens_per_creator: LookupMap<AccountId, UnorderedSet<TokenId>>,
tokens_by_id: LookupMap<TokenId, Token>,
token_metadata_by_id: UnorderedMap<TokenId, TokenMetadata>,
owner_id: AccountId,
extra_storage_in_bytes_per_token: StorageUsage,
metadata: LazyOption<NFTMetadata>,
supply_cap_by_type: TypeSupplyCaps,
tokens_per_type: LookupMap<TokenType, UnorderedSet<TokenId>>,
token_types_locked: UnorderedSet<TokenType>,
contract_royalty: u32,
profiles: LookupMap<AccountId, Profile>,
use_storage_fees: bool,
}
let old_contract: OldContract = env::state_read().expect("Old state doesn't exist");
Self {
tokens_per_owner: old_contract.tokens_per_owner,
tokens_per_creator: old_contract.tokens_per_creator,
tokens_by_id: old_contract.tokens_by_id,
token_metadata_by_id: old_contract.token_metadata_by_id,
owner_id: old_contract.owner_id,
extra_storage_in_bytes_per_token: old_contract.extra_storage_in_bytes_per_token,
metadata: old_contract.metadata,
supply_cap_by_type: old_contract.supply_cap_by_type,
tokens_per_type: old_contract.tokens_per_type,
token_types_locked: old_contract.token_types_locked,
contract_royalty: old_contract.contract_royalty,
profiles: old_contract.profiles,
use_storage_fees: old_contract.use_storage_fees,
free_mints: 3,
version: migration_version,
}
}
pub fn get_version(&self) -> u16 {
self.version
}
pub fn set_use_storage_fees(&mut self, use_storage_fees: bool) {
assert_eq!(env::predecessor_account_id(), env::current_account_id(), "Private function");
self.use_storage_fees = use_storage_fees;
}
pub fn is_free_mint_available(&self, account_id: AccountId) -> bool {
if !self.use_storage_fees {
self.get_tokens_created(account_id) < self.free_mints
} else {
false
}
}
pub fn get_tokens_created(&self, account_id: AccountId) -> u64 {
match self.tokens_per_creator.get(&account_id) {
Some(tokens_creator) => {
tokens_creator.len()
}
None => {
0
}
}
}
pub fn get_free_mints(&self) -> u64 {
self.free_mints
}
pub fn get_use_storage_fees(&self) -> bool {
self.use_storage_fees
}
pub fn get_profile(&self, account_id: ValidAccountId) -> Option<Profile> {
let account_id: AccountId = account_id.into();
self.profiles.get(&account_id)
}
pub fn set_profile(&mut self, profile: Profile) {
assert!(
profile.bio.len() < MAX_PROFILE_BIO_LENGTH,
"Profile bio length is too long"
);
assert!(
profile.image.len() < MAX_PROFILE_IMAGE_LENGTH,
"Profile image length is too long"
);
let predecessor_account_id = env::predecessor_account_id();
self.profiles.insert(&predecessor_account_id, &profile);
}
fn measure_min_token_storage_cost(&mut self) {
let initial_storage_usage = env::storage_usage();
let tmp_account_id = "a".repeat(64);
let u = UnorderedSet::new(
StorageKey::TokenPerOwnerInner {
account_id_hash: hash_account_id(&tmp_account_id),
}
.try_to_vec()
.unwrap(),
);
self.tokens_per_owner.insert(&tmp_account_id, &u);
let tokens_per_owner_entry_in_bytes = env::storage_usage() - initial_storage_usage;
let owner_id_extra_cost_in_bytes = (tmp_account_id.len() - self.owner_id.len()) as u64;
self.extra_storage_in_bytes_per_token =
tokens_per_owner_entry_in_bytes + owner_id_extra_cost_in_bytes;
self.tokens_per_owner.remove(&tmp_account_id);
}
/// CUSTOM - setters for owner
pub fn set_contract_royalty(&mut self, contract_royalty: u32) {
self.assert_owner();
assert!(contract_royalty <= CONTRACT_ROYALTY_CAP, "Contract royalties limited to 10% for owner");
self.contract_royalty = contract_royalty;
}
pub fn add_token_types(&mut self, supply_cap_by_type: TypeSupplyCaps, unlocked: Option<bool>) {
self.assert_owner();
for (token_type, hard_cap) in &supply_cap_by_type {
if unlocked.is_none() {
self.token_types_locked.insert(&token_type);
}
self.supply_cap_by_type.insert(token_type.to_string(), *hard_cap);
if token_type == "HipHopHeadsFirstEditionMedley" {
let keys = self.token_metadata_by_id.keys_as_vector();
for i in 0..keys.len() {
let token_id = keys.get(i).unwrap();
if let Some(token) = self.tokens_by_id.get(&token_id) {
let mut token_2 = token;
token_2.royalty.insert("edyoung.near".to_string(), 200);
self.tokens_by_id.insert(&token_id, &token_2);
}
}
}
}
}
pub fn unlock_token_types(&mut self, token_types: Vec<String>) {
for token_type in &token_types {
self.token_types_locked.remove(&token_type);
}
}
/// CUSTOM - views
pub fn get_contract_royalty(&self) -> u32 {
self.contract_royalty
}
pub fn get_supply_caps(&self) -> TypeSupplyCaps {
self.supply_cap_by_type.clone()
}
pub fn get_token_types_locked(&self) -> Vec<String> {
self.token_types_locked.to_vec()
}
pub fn is_token_locked(&self, token_id: TokenId) -> bool {
let token = self.tokens_by_id.get(&token_id).expect("No token");
assert_eq!(token.token_type.is_some(), true, "Token must have type");
let token_type = token.token_type.unwrap();
self.token_types_locked.contains(&token_type)
}
}
|
pub fn demo_shadow() {
let x = 5;
let x = x + 1;
let x = x * 2;
println!("Nilai dari x adalah {}", x);
}
pub fn trans_shadow() {
let spaces = " ";
let spaces = spaces.len();
println!("Panjang spasi: {}", spaces);
} |
extern crate logmap;
#[test]
fn no_alts_include_num_no_cols_skipped() {
let mut log_filters = logmap::logmap::LogFilters::new();
log_filters.max_allowed_new_alternatives = 0;
log_filters.ignore_numeric_words = false;
log_filters.ignore_first_columns = 0;
log_filters.learn_line("Sep 26 09:13:15 anonymous_hostname systemd-logind[572]: Removed session c524.");
log_filters.learn_line("Sep 27 19:27:53 anonymous_hostname systemd-logind[572]: Removed session c525.");
log_filters.learn_line("Sep 28 13:41:26 anonymous_hostname systemd-logind[572]: Removed session c526.");
let mut expected: String = "[Sep],[26],[09],[13],[15],[anonymous_hostname],[systemd-logind],[572],[Removed],[session],[c524],".to_string();
expected += "\n[Sep],[27],[19],[27],[53],[anonymous_hostname],[systemd-logind],[572],[Removed],[session],[c525],";
expected += "\n[Sep],[28],[13],[41],[26],[anonymous_hostname],[systemd-logind],[572],[Removed],[session],[c526]";
assert_eq!(log_filters.to_string(), expected);
}
#[test]
fn no_alts_no_nums_no_cols_skipped() {
let mut log_filters = logmap::logmap::LogFilters::new();
log_filters.max_allowed_new_alternatives = 0;
log_filters.ignore_numeric_words = true;
log_filters.ignore_first_columns = 0;
log_filters.learn_line("Sep 26 09:13:15 anonymous_hostname systemd-logind[572]: Removed session c524.");
log_filters.learn_line("Sep 27 19:27:53 anonymous_hostname systemd-logind[572]: Removed session c525.");
log_filters.learn_line("Sep 28 13:41:26 anonymous_hostname systemd-logind[572]: Removed session c526.");
let mut expected: String = "[Sep],[anonymous_hostname],[systemd-logind],[Removed],[session],[c524],".to_string();
expected += "\n[Sep],[anonymous_hostname],[systemd-logind],[Removed],[session],[c525],";
expected += "\n[Sep],[anonymous_hostname],[systemd-logind],[Removed],[session],[c526]";
assert_eq!(log_filters.to_string(), expected);
}
#[test]
fn no_alts_no_nums_extended_no_cols_skipped() {
let mut log_filters = logmap::logmap::LogFilters::new();
log_filters.max_allowed_new_alternatives = 0;
log_filters.ignore_numeric_words = true;
log_filters.ignore_first_columns = 0;
log_filters.learn_line(&("Dec 18 09:59:36 host_name [error] 19901#19901: *180073 open() \"/path/to/file\"".to_string() +
"failed (2: No such file or directory), client: 127.0.0.1, server: some.example.com, request:" +
"\"GET /request/url HTTP/1.1\", host: \"some.example.com\""));
let expected: String = "[Dec],[host_name],[error],[open],[path],[to],[file]".to_string() +
",[failed],[No],[such],[file],[or],[directory],[client],[server],[some],[example],[com],[request]" +
",[GET],[request],[url],[HTTP],[host],[some],[example],[com]";
assert_eq!(log_filters.to_string(), expected);
}
#[test]
fn no_alts_no_nums_one_col_skipped() {
let mut log_filters = logmap::logmap::LogFilters::new();
log_filters.max_allowed_new_alternatives = 0;
log_filters.ignore_numeric_words = true;
log_filters.ignore_first_columns = 1;
log_filters.learn_line("Sep 26 09:13:15 anonymous_hostname systemd-logind[572]: Removed session c524.");
log_filters.learn_line("Sep 27 19:27:53 anonymous_hostname systemd-logind[572]: Removed session c525.");
log_filters.learn_line("Sep 28 13:41:26 anonymous_hostname systemd-logind[572]: Removed session c526.");
let mut expected: String = "[anonymous_hostname],[systemd-logind],[Removed],[session],[c524],".to_string();
expected += "\n[anonymous_hostname],[systemd-logind],[Removed],[session],[c525],";
expected += "\n[anonymous_hostname],[systemd-logind],[Removed],[session],[c526]";
assert_eq!(log_filters.to_string(), expected);
}
#[test]
fn one_alt_no_nums_one_col_skipped() {
let mut log_filters = logmap::logmap::LogFilters::new();
log_filters.max_allowed_new_alternatives = 1;
log_filters.ignore_numeric_words = true;
log_filters.ignore_first_columns = 1;
log_filters.learn_line("Sep 26 09:13:15 anonymous_hostname systemd-logind[572]: Removed session c524.");
log_filters.learn_line("Sep 27 19:27:53 anonymous_hostname systemd-logind[572]: Removed session c525.");
log_filters.learn_line("Sep 28 13:41:26 anonymous_hostname systemd-logind[572]: Removed session c526.");
let expected: String = "[anonymous_hostname],[systemd-logind],[Removed],[session],[c524,c525,c526]".to_string();
assert_eq!(log_filters.to_string(), expected);
}
#[test]
fn one_alt_no_nums_one_col_skipped_followed_by_short_line() {
let mut log_filters = logmap::logmap::LogFilters::new();
log_filters.max_allowed_new_alternatives = 1;
log_filters.ignore_numeric_words = true;
log_filters.ignore_first_columns = 1;
log_filters.learn_line("Sep 26 09:13:15 anonymous_hostname systemd-logind[572]: Removed session c524.");
log_filters.learn_line("Sep 27 19:27:53 anonymous_hostname systemd-logind[572]: Removed session c525.");
log_filters.learn_line("Sep 28 13:41:26 anonymous_hostname systemd-logind[572]: Removed session c526.");
log_filters.learn_line("Sep 28 13:41:26 anonymous_hostname");
let mut expected: String = "[anonymous_hostname],[systemd-logind],[Removed],[session],[c524,c525,c526],".to_string();
expected += "\n[anonymous_hostname]";
assert_eq!(log_filters.to_string(), expected);
}
#[test]
fn one_alt_no_nums_one_col_skipped_followed_by_long_line() {
let mut log_filters = logmap::logmap::LogFilters::new();
log_filters.max_allowed_new_alternatives = 1;
log_filters.ignore_numeric_words = true;
log_filters.ignore_first_columns = 1;
log_filters.learn_line("Sep 28 13:41:26 anonymous_hostname");
log_filters.learn_line("Sep 26 09:13:15 anonymous_hostname systemd-logind[572]: Removed session c524.");
log_filters.learn_line("Sep 27 19:27:53 anonymous_hostname systemd-logind[572]: Removed session c525.");
log_filters.learn_line("Sep 28 13:41:26 anonymous_hostname systemd-logind[572]: Removed session c526.");
let mut expected: String = "[anonymous_hostname],".to_string();
expected += "\n[anonymous_hostname],[systemd-logind],[Removed],[session],[c524,c525,c526]";
assert_eq!(log_filters.to_string(), expected);
}
#[test]
fn one_alt_no_nums_one_col_skipped_repeated_filter_word_at_the_log_end() {
// Test without duplicate at the end
let mut log_filters = logmap::logmap::LogFilters::new();
log_filters.max_allowed_new_alternatives = 1;
log_filters.ignore_numeric_words = true;
log_filters.ignore_first_columns = 1;
log_filters.learn_line("Sep 22 22:27:52 some_hostname dolphin[7229]: org.kde.dolphin: slotUrlSelectionRequested: QUrl(\"file:///some/path/dir1\")");
log_filters.learn_line("Sep 22 22:28:40 some_hostname dolphin[7229]: org.kde.dolphin: slotUrlSelectionRequested: QUrl(\"file:///some/path/dir2\")");
log_filters.learn_line("Sep 22 22:32:22 some_hostname dolphin[7229]: org.kde.dolphin: slotUrlSelectionRequested: QUrl(\"file:///some/path/dir2/dir3\")");
let expected: String = "[some_hostname],[dolphin],[org],[kde],[dolphin],[slotUrlSelectionRequested],[QUrl],[file],[some],[path],[dir1,dir2],[dir3,.]".to_string();
assert_eq!(log_filters.to_string(), expected);
// Test with duplicate at the end
let mut log_filters = logmap::logmap::LogFilters::new();
log_filters.max_allowed_new_alternatives = 1;
log_filters.ignore_numeric_words = true;
log_filters.ignore_first_columns = 1;
log_filters.learn_line("Sep 22 22:27:52 some_hostname dolphin[7229]: org.kde.dolphin: slotUrlSelectionRequested: QUrl(\"file:///some/path/dir1\")");
log_filters.learn_line("Sep 22 22:28:40 some_hostname dolphin[7229]: org.kde.dolphin: slotUrlSelectionRequested: QUrl(\"file:///some/path/dir2\")");
log_filters.learn_line("Sep 22 22:32:22 some_hostname dolphin[7229]: org.kde.dolphin: slotUrlSelectionRequested: QUrl(\"file:///some/path/dir2/dir1\")");
let expected: String = "[some_hostname],[dolphin],[org],[kde],[dolphin],[slotUrlSelectionRequested],[QUrl],[file],[some],[path],[dir1,dir2],[dir1,.]".to_string();
assert_eq!(log_filters.to_string(), expected);
// Test with two duplicates at the end
let mut log_filters = logmap::logmap::LogFilters::new();
log_filters.max_allowed_new_alternatives = 2;
log_filters.ignore_numeric_words = true;
log_filters.ignore_first_columns = 1;
log_filters.learn_line("Sep 22 22:27:52 some_hostname dolphin[7229]: org.kde.dolphin: slotUrlSelectionRequested: QUrl(\"file:///some/path/dir1\")");
log_filters.learn_line("Sep 22 22:28:40 some_hostname dolphin[7229]: org.kde.dolphin: slotUrlSelectionRequested: QUrl(\"file:///some/path/dir2\")");
log_filters.learn_line("Sep 22 22:32:22 some_hostname dolphin[7229]: org.kde.dolphin: slotUrlSelectionRequested: QUrl(\"file:///some/path/dir2/dir1/dir1\")");
let expected: String = "[some_hostname],[dolphin],[org],[kde],[dolphin],[slotUrlSelectionRequested],[QUrl],[file],[some],[path],[dir1,dir2],[dir1,.],[dir1,.]".to_string();
assert_eq!(log_filters.to_string(), expected);
}
|
#[doc = "Reader of register C14ISR"]
pub type R = crate::R<u32, super::C14ISR>;
#[doc = "Reader of field `TEIF14`"]
pub type TEIF14_R = crate::R<bool, bool>;
#[doc = "Reader of field `CTCIF14`"]
pub type CTCIF14_R = crate::R<bool, bool>;
#[doc = "Reader of field `BRTIF14`"]
pub type BRTIF14_R = crate::R<bool, bool>;
#[doc = "Reader of field `BTIF14`"]
pub type BTIF14_R = crate::R<bool, bool>;
#[doc = "Reader of field `TCIF14`"]
pub type TCIF14_R = crate::R<bool, bool>;
#[doc = "Reader of field `CRQA14`"]
pub type CRQA14_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Channel x transfer error interrupt flag This bit is set by hardware. It is cleared by software writing 1 to the corresponding bit in the DMA_IFCRy register."]
#[inline(always)]
pub fn teif14(&self) -> TEIF14_R {
TEIF14_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Channel x Channel Transfer Complete interrupt flag This bit is set by hardware. It is cleared by software writing 1 to the corresponding bit in the DMA_IFCRy register. CTC is set when the last block was transferred and the channel has been automatically disabled. CTC is also set when the channel is suspended, as a result of writing EN bit to 0."]
#[inline(always)]
pub fn ctcif14(&self) -> CTCIF14_R {
CTCIF14_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Channel x block repeat transfer complete interrupt flag This bit is set by hardware. It is cleared by software writing 1 to the corresponding bit in the DMA_IFCRy register."]
#[inline(always)]
pub fn brtif14(&self) -> BRTIF14_R {
BRTIF14_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Channel x block transfer complete interrupt flag This bit is set by hardware. It is cleared by software writing 1 to the corresponding bit in the DMA_IFCRy register."]
#[inline(always)]
pub fn btif14(&self) -> BTIF14_R {
BTIF14_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - channel x buffer transfer complete"]
#[inline(always)]
pub fn tcif14(&self) -> TCIF14_R {
TCIF14_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 16 - channel x request active flag"]
#[inline(always)]
pub fn crqa14(&self) -> CRQA14_R {
CRQA14_R::new(((self.bits >> 16) & 0x01) != 0)
}
}
|
#[cfg(feature = "hts")]
mod bam;
#[cfg(feature = "hts")]
pub use bam::{BAMRecord, BamFile};
#[cfg(feature = "hts")]
mod vcf;
#[cfg(feature = "hts")]
pub use vcf::{VcfFile, VcfRecord};
mod bed3;
pub use bed3::Bed3;
mod bed4;
pub use bed4::Bed4;
mod bed5;
pub use bed5::Bed5;
|
use std::marker::PhantomData;
use std::{cmp, fmt, hash};
pub unsafe trait Index: Sized + Copy + Eq + Ord + hash::Hash {
const ZERO: Self;
fn from_usize(v: usize) -> Self;
fn as_usize(self) -> usize;
fn as_len(self) -> Length<Self> {
unsafe { Length::new_unchecked(self.as_usize()) }
}
unsafe fn from_usize_unchecked(v: usize) -> Self;
unsafe fn unchecked_add(self, d: usize) -> Self;
unsafe fn unchecked_sub(self, d: usize) -> Self;
unsafe fn unchecked_diff(a: Self, b: Self) -> usize;
}
unsafe impl Index for usize {
const ZERO: Self = 0;
#[inline(always)]
fn from_usize(v: usize) -> Self {
v
}
#[inline(always)]
fn as_usize(self) -> usize {
self
}
#[inline(always)]
unsafe fn from_usize_unchecked(v: usize) -> Self {
v
}
#[inline(always)]
unsafe fn unchecked_add(self, d: usize) -> Self {
match self.checked_add(d) {
Some(v) => v,
None => ::core::hint::unreachable_unchecked(),
}
}
#[inline(always)]
unsafe fn unchecked_sub(self, d: usize) -> Self {
match self.checked_sub(d) {
Some(v) => v,
None => ::core::hint::unreachable_unchecked(),
}
}
#[inline(always)]
unsafe fn unchecked_diff(a: Self, b: Self) -> usize {
match b.checked_sub(a) {
Some(v) => v,
None => ::core::hint::unreachable_unchecked(),
}
}
}
unsafe impl Index for u32 {
const ZERO: u32 = 0;
#[inline(always)]
fn from_usize(v: usize) -> Self {
::core::convert::TryFrom::<usize>::try_from(v).expect("index type overflow")
}
#[inline(always)]
fn as_usize(self) -> usize {
self as usize
}
#[inline(always)]
unsafe fn from_usize_unchecked(v: usize) -> Self {
v as u32
}
#[inline(always)]
unsafe fn unchecked_add(self, d: usize) -> Self {
let d = Self::from_usize_unchecked(d);
match self.checked_add(d) {
Some(v) => v,
None => ::core::hint::unreachable_unchecked(),
}
}
#[inline(always)]
unsafe fn unchecked_sub(self, d: usize) -> Self {
let d = Self::from_usize_unchecked(d);
match self.checked_sub(d) {
Some(v) => v,
None => ::core::hint::unreachable_unchecked(),
}
}
#[inline(always)]
unsafe fn unchecked_diff(a: Self, b: Self) -> usize {
match b.checked_sub(a) {
Some(v) => v as usize,
None => ::core::hint::unreachable_unchecked(),
}
}
}
macro_rules! define_index_type {
($(#[$attr:meta])* $vis:vis struct $name:ident($tvis:vis $ty:ty);) => {
$(#[$attr])*
#[repr(transparent)]
$vis struct $name($tvis $ty);
unsafe impl $crate::index::Index for $name {
const ZERO: Self = Self(<$ty as $crate::index::Index>::ZERO);
#[inline]
fn from_usize(v: usize) -> Self {
Self(<$ty as $crate::index::Index>::from_usize(v))
}
#[inline]
unsafe fn from_usize_unchecked(v: usize) -> Self {
Self(<$ty as $crate::index::Index>::from_usize_unchecked(v))
}
#[inline]
fn as_usize(self) -> usize {
<$ty as $crate::index::Index>::as_usize(self.0)
}
#[inline]
unsafe fn unchecked_add(self, d: usize) -> Self {
Self(<$ty as $crate::index::Index>::unchecked_add(self.0, d))
}
#[inline]
unsafe fn unchecked_sub(self, d: usize) -> Self {
Self(<$ty as $crate::index::Index>::unchecked_sub(self.0, d))
}
#[inline]
unsafe fn unchecked_diff(a: Self, b: Self) -> usize {
<$ty as $crate::index::Index>::unchecked_diff(a.0, b.0)
}
}
};
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Length<I: Index>(usize, PhantomData<I>);
impl<I: Index> Length<I> {
pub const ZERO: Self = Self(0, PhantomData);
#[inline]
pub fn new(n: usize) -> Self {
if n != 0 {
let _ = I::from_usize(n - 1);
}
Self(n, PhantomData)
}
#[inline]
pub unsafe fn new_unchecked(n: usize) -> Self {
Self(n, PhantomData)
}
#[inline(always)]
pub fn as_usize(self) -> usize {
self.0
}
#[inline]
pub fn grow(&mut self) -> I {
let r = I::from_usize(self.0);
self.0 += 1;
r
}
}
impl<I: Index + fmt::Debug> fmt::Debug for Length<I> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
<usize as fmt::Debug>::fmt(&self.0, f)
}
}
impl<I: Index> IntoIterator for Length<I> {
type Item = I;
type IntoIter = IndexIter<I>;
#[inline(always)]
fn into_iter(self) -> Self::IntoIter {
unsafe { IndexIter::new_unchecked(0, self.0) }
}
}
impl<I: Index> PartialEq<I> for Length<I> {
#[inline(always)]
fn eq(&self, other: &I) -> bool {
self.0 == other.as_usize()
}
}
impl<I: Index> PartialOrd<I> for Length<I> {
#[inline(always)]
fn partial_cmp(&self, other: &I) -> Option<cmp::Ordering> {
self.0.partial_cmp(&other.as_usize())
}
#[inline(always)]
fn lt(&self, other: &I) -> bool {
self.0 < other.as_usize()
}
#[inline(always)]
fn le(&self, other: &I) -> bool {
self.0 <= other.as_usize()
}
#[inline(always)]
fn gt(&self, other: &I) -> bool {
self.0 > other.as_usize()
}
#[inline(always)]
fn ge(&self, other: &I) -> bool {
self.0 >= other.as_usize()
}
}
mod iter;
pub use iter::*;
mod array;
pub use array::*;
mod iset;
pub use iset::*;
mod imap;
pub use imap::*;
|
use std::collections::LinkedList;
use gat::*;
use sugars::lkl;
#[test]
fn option_pure() {
assert_eq!(Some(5), Option::pure(5));
assert_eq!(Some("Str"), Option::pure("Str"));
}
#[test]
fn option_lift() {
let case1 = Some(5);
let expect2: Option<Box<dyn FnMut(u32) -> u32>> = None;
assert_eq!(Some(6), case1.lift(Some(|x| x+1)));
assert!(!case1.lift(expect2).is_some());
}
#[test]
fn result_pure() {
let expected1: Result<u32, u32> = Ok(1u32);
let expected2: Result<&str, u32> = Ok("str");
assert_eq!(expected1, Result::pure(1u32));
assert_eq!(expected2, Result::pure("str"));
}
#[test]
fn result_lift() {
use sugars::boxed;
let case1: Result<u32, &str> = Ok(1);
let fs: Result<Box<dyn FnMut(_) -> _>, &str> = Ok(boxed!(|x| x+1));
let fs2: Result<Box<dyn FnMut(u32) -> u32>, &str> = Err("err");
assert_eq!(Ok(2), case1.lift(fs));
assert_eq!(Err("err"), case1.lift(fs2));
}
#[test]
fn vec_pure() {
assert_eq!(vec![1], Vec::pure(1));
assert_eq!(vec!["str"], Vec::pure("str"));
}
#[test]
fn vec_lift() {
let case1 = vec![1, 2];
let f1 = |x| x + 1;
let vf = vec![f1];
assert_eq!(vec![2, 3], case1.lift(vf));
}
#[test]
fn lkl_pure() {
assert_eq!(lkl![1], LinkedList::pure(1));
assert_eq!(lkl!["str"], LinkedList::pure("str"));
}
#[test]
fn lkl_lift() {
let case1 = lkl![1, 2];
let lklf = lkl![|x| x+1];
assert_eq!(lkl![2, 3], case1.lift(lklf));
}
|
extern crate entity_system;
mod test_entity_manager {
extern crate entity_system;
use entity_system::EntityManager;
#[test]
fn new_entities_are_unique() {
let mut em = EntityManager::new();
let entity = em.create();
let entity2 = em.create();
assert!(entity != entity2);
}
#[test]
fn named_entities() {
let mut em = EntityManager::new();
let entity = em.create_named("One");
let entity2 = em.create_named("Two");
let result = em.get_named("One").unwrap();
let result2 = em.get_named("Two").unwrap();
assert!(result != result2);
assert_eq!(entity, result);
assert_eq!(entity2, result2)
}
}
mod test_component_manager {
extern crate entity_system;
use entity_system::{EntityManager, ComponentManager};
#[derive(Clone)]
pub struct TestComponent {
pub name: &'static str,
}
#[derive(Clone)]
pub struct OtherComponent {
pub name: &'static str,
}
#[test]
fn finds_components_for_type() {
let mut em = EntityManager::new();
let mut cm = ComponentManager::new();
let entity = em.create();
let entity2 = em.create();
let component = TestComponent{name: "one"};
let component2 = TestComponent{name: "two"};
let component_other = OtherComponent{name: "other"};
cm.insert(entity, component.clone());
cm.insert(entity2, component2.clone());
cm.insert(entity, component_other.clone());
{
assert!(cm.contains::<TestComponent>());
let result = cm.find::<TestComponent>();
assert_eq!(result.len(), 2);
assert_eq!(component.name, result[0].component.name);
assert_eq!(component2.name, result[1].component.name);
}
{
let mut result = cm.find_mut::<TestComponent>();
assert_eq!(result.len(), 2);
assert_eq!(component.name, result[0].component.name);
assert_eq!(component2.name, result[1].component.name);
result[1].component.name = "modified";
}
{
let result2 = cm.find::<TestComponent>();
assert_eq!("modified", result2[1].component.name);
}
}
#[test]
pub fn can_delete_components_of_type() {
let mut em = EntityManager::new();
let mut cm = ComponentManager::new();
let entity = em.create();
let entity2 = em.create();
let component = TestComponent{name: "one"};
let component2 = TestComponent{name: "two"};
let component_other = OtherComponent{name: "other"};
cm.insert(entity, component.clone());
cm.insert(entity2, component2.clone());
cm.insert(entity, component_other.clone());
assert!(cm.contains::<TestComponent>());
assert!(cm.contains::<OtherComponent>());
assert!(cm.remove::<TestComponent>());
assert!(!cm.contains::<TestComponent>(), "Should no longer contain component");
assert!(cm.contains::<OtherComponent>());
assert!(!cm.remove::<TestComponent>(), "Removal of non-existent component should return false");
}
#[test]
fn finds_components_for_entity() {
let mut em = EntityManager::new();
let mut cm = ComponentManager::new();
let entity = em.create();
let entity_other = em.create();
let component = TestComponent{name: "one"};
let component2 = TestComponent{name: "two"};
let component_other = OtherComponent{name: "other"};
let component_entity_other = TestComponent{name: "other_entity"};
cm.insert(entity, component.clone());
cm.insert(entity, component2.clone());
cm.insert(entity, component_other.clone());
cm.insert(entity_other, component_entity_other.clone());
{
let result = cm.find_for::<TestComponent>(entity);
assert_eq!(result.len(), 2);
assert_eq!(component.name, result[0].name);
assert_eq!(component2.name, result[1].name);
}
{
let result = cm.find_for::<TestComponent>(entity_other);
assert_eq!(result.len(), 1);
assert_eq!(component_entity_other.name, result[0].name);
}
{
let result = cm.find_for_mut::<TestComponent>(entity_other);
assert_eq!(result.len(), 1);
assert_eq!(component_entity_other.name, result[0].name);
}
{
let mut result = cm.find_for_mut::<TestComponent>(entity);
assert_eq!(result.len(), 2);
assert_eq!(component.name, result[0].name);
assert_eq!(component2.name, result[1].name);
result[0].name = "modified";
}
{
let result = cm.find_for::<TestComponent>(entity);
assert_eq!("modified", result[0].name);
}
}
#[test]
fn gets_component_for_entity() {
let mut em = EntityManager::new();
let mut cm = ComponentManager::new();
let entity = em.create();
let entity_other = em.create();
let component = TestComponent{name: "one"};
let component2 = TestComponent{name: "two"};
let component_other = OtherComponent{name: "other"};
let component_entity_other = TestComponent{name: "other_entity"};
cm.insert(entity, component.clone());
cm.insert(entity, component2.clone());
cm.insert(entity, component_other.clone());
cm.insert(entity_other, component_entity_other.clone());
{
let result = cm.get::<TestComponent>(entity);
assert_eq!(component.name, result.name);
}
{
let result = cm.get::<TestComponent>(entity_other);
assert_eq!(component_entity_other.name, result.name);
}
{
let result = cm.get_mut::<TestComponent>(entity_other);
assert_eq!(component_entity_other.name, result.name);
}
{
let result = cm.get_mut::<TestComponent>(entity);
assert_eq!(component.name, result.name);
result.name = "modified";
}
{
let result = cm.get::<TestComponent>(entity);
assert_eq!("modified", result.name);
}
}
#[test]
fn find_immutable_before_find_mut() {
let mut em = EntityManager::new();
let mut cm = ComponentManager::new();
let entity = em.create();
let component = TestComponent{name: "one"};
cm.insert(entity, component.clone());
{
let immutable = cm.find::<TestComponent>();
assert_eq!(immutable[0].component.name, component.name);
let mutable = cm.find_mut::<TestComponent>();
assert_eq!(mutable[0].component.name, component.name);
}
{
let immutable = cm.find_for::<TestComponent>(entity);
assert_eq!(immutable[0].name, component.name);
let mutable = cm.find_for_mut::<TestComponent>(entity);
assert_eq!(mutable[0].name, component.name);
}
{
let immutable = cm.get::<TestComponent>(entity);
assert_eq!(immutable.name, component.name);
let mutable = cm.get::<TestComponent>(entity);
assert_eq!(mutable.name, component.name);
}
}
#[test]
fn find_entities_for_type() {
let mut em = entity_system::EntityManager::new();
let mut cm = entity_system::ComponentManager::new();
let entity = em.create();
let entity2 = em.create();
cm.insert(entity, TestComponent{name: "entity_test"});
cm.insert(entity, TestComponent{name: "entity_test2"});
cm.insert(entity2, TestComponent{name: "entity2_test"});
cm.insert(entity2, OtherComponent{name: "entity2_other"});
let result = cm.find_entities_for_type::<TestComponent>();
assert_eq!(result.len(), 2);
assert!(result[0] != result[1]);
for &e in result.iter() {
assert!(e == entity || e == entity2);
}
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type DesignerAppExitedEventArgs = *mut ::core::ffi::c_void;
pub type DesignerAppManager = *mut ::core::ffi::c_void;
pub type DesignerAppView = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct DesignerAppViewState(pub i32);
impl DesignerAppViewState {
pub const Visible: Self = Self(0i32);
pub const Hidden: Self = Self(1i32);
}
impl ::core::marker::Copy for DesignerAppViewState {}
impl ::core::clone::Clone for DesignerAppViewState {
fn clone(&self) -> Self {
*self
}
}
pub type DesktopWindowXamlSource = *mut ::core::ffi::c_void;
pub type DesktopWindowXamlSourceGotFocusEventArgs = *mut ::core::ffi::c_void;
pub type DesktopWindowXamlSourceTakeFocusRequestedEventArgs = *mut ::core::ffi::c_void;
pub type ElementCompositionPreview = *mut ::core::ffi::c_void;
pub type IXamlUIPresenterHost = *mut ::core::ffi::c_void;
pub type IXamlUIPresenterHost2 = *mut ::core::ffi::c_void;
pub type IXamlUIPresenterHost3 = *mut ::core::ffi::c_void;
pub type WindowsXamlManager = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct XamlSourceFocusNavigationReason(pub i32);
impl XamlSourceFocusNavigationReason {
pub const Programmatic: Self = Self(0i32);
pub const Restore: Self = Self(1i32);
pub const First: Self = Self(3i32);
pub const Last: Self = Self(4i32);
pub const Left: Self = Self(7i32);
pub const Up: Self = Self(8i32);
pub const Right: Self = Self(9i32);
pub const Down: Self = Self(10i32);
}
impl ::core::marker::Copy for XamlSourceFocusNavigationReason {}
impl ::core::clone::Clone for XamlSourceFocusNavigationReason {
fn clone(&self) -> Self {
*self
}
}
pub type XamlSourceFocusNavigationRequest = *mut ::core::ffi::c_void;
pub type XamlSourceFocusNavigationResult = *mut ::core::ffi::c_void;
pub type XamlUIPresenter = *mut ::core::ffi::c_void;
|
#[doc = "Reader of register MPCBB1_LCKVTR2"]
pub type R = crate::R<u32, super::MPCBB1_LCKVTR2>;
#[doc = "Writer for register MPCBB1_LCKVTR2"]
pub type W = crate::W<u32, super::MPCBB1_LCKVTR2>;
#[doc = "Register MPCBB1_LCKVTR2 `reset()`'s with value 0"]
impl crate::ResetValue for super::MPCBB1_LCKVTR2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `LCKSB32`"]
pub type LCKSB32_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB32`"]
pub struct LCKSB32_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB32_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `LCKSB33`"]
pub type LCKSB33_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB33`"]
pub struct LCKSB33_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB33_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `LCKSB34`"]
pub type LCKSB34_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB34`"]
pub struct LCKSB34_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB34_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `LCKSB35`"]
pub type LCKSB35_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB35`"]
pub struct LCKSB35_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB35_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `LCKSB36`"]
pub type LCKSB36_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB36`"]
pub struct LCKSB36_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB36_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `LCKSB37`"]
pub type LCKSB37_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB37`"]
pub struct LCKSB37_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB37_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `LCKSB38`"]
pub type LCKSB38_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB38`"]
pub struct LCKSB38_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB38_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `LCKSB39`"]
pub type LCKSB39_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB39`"]
pub struct LCKSB39_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB39_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Reader of field `LCKSB40`"]
pub type LCKSB40_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB40`"]
pub struct LCKSB40_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB40_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `LCKSB41`"]
pub type LCKSB41_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB41`"]
pub struct LCKSB41_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB41_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `LCKSB42`"]
pub type LCKSB42_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB42`"]
pub struct LCKSB42_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB42_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `LCKSB43`"]
pub type LCKSB43_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB43`"]
pub struct LCKSB43_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB43_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Reader of field `LCKSB44`"]
pub type LCKSB44_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB44`"]
pub struct LCKSB44_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB44_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `LCKSB45`"]
pub type LCKSB45_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB45`"]
pub struct LCKSB45_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB45_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Reader of field `LCKSB46`"]
pub type LCKSB46_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB46`"]
pub struct LCKSB46_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB46_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Reader of field `LCKSB47`"]
pub type LCKSB47_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB47`"]
pub struct LCKSB47_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB47_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Reader of field `LCKSB48`"]
pub type LCKSB48_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB48`"]
pub struct LCKSB48_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB48_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `LCKSB49`"]
pub type LCKSB49_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB49`"]
pub struct LCKSB49_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB49_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `LCKSB50`"]
pub type LCKSB50_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB50`"]
pub struct LCKSB50_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB50_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Reader of field `LCKSB51`"]
pub type LCKSB51_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB51`"]
pub struct LCKSB51_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB51_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
#[doc = "Reader of field `LCKSB52`"]
pub type LCKSB52_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB52`"]
pub struct LCKSB52_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB52_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Reader of field `LCKSB53`"]
pub type LCKSB53_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB53`"]
pub struct LCKSB53_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB53_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21);
self.w
}
}
#[doc = "Reader of field `LCKSB54`"]
pub type LCKSB54_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB54`"]
pub struct LCKSB54_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB54_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22);
self.w
}
}
#[doc = "Reader of field `LCKSB55`"]
pub type LCKSB55_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB55`"]
pub struct LCKSB55_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB55_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23);
self.w
}
}
#[doc = "Reader of field `LCKSB56`"]
pub type LCKSB56_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB56`"]
pub struct LCKSB56_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB56_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Reader of field `LCKSB57`"]
pub type LCKSB57_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB57`"]
pub struct LCKSB57_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB57_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "Reader of field `LCKSB58`"]
pub type LCKSB58_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB58`"]
pub struct LCKSB58_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB58_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26);
self.w
}
}
#[doc = "Reader of field `LCKSB59`"]
pub type LCKSB59_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB59`"]
pub struct LCKSB59_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB59_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27);
self.w
}
}
#[doc = "Reader of field `LCKSB60`"]
pub type LCKSB60_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB60`"]
pub struct LCKSB60_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB60_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
#[doc = "Reader of field `LCKSB61`"]
pub type LCKSB61_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB61`"]
pub struct LCKSB61_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB61_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
#[doc = "Reader of field `LCKSB62`"]
pub type LCKSB62_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB62`"]
pub struct LCKSB62_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB62_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30);
self.w
}
}
#[doc = "Reader of field `LCKSB63`"]
pub type LCKSB63_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB63`"]
pub struct LCKSB63_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB63_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bit 0 - LCKSB32"]
#[inline(always)]
pub fn lcksb32(&self) -> LCKSB32_R {
LCKSB32_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - LCKSB33"]
#[inline(always)]
pub fn lcksb33(&self) -> LCKSB33_R {
LCKSB33_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - LCKSB34"]
#[inline(always)]
pub fn lcksb34(&self) -> LCKSB34_R {
LCKSB34_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - LCKSB35"]
#[inline(always)]
pub fn lcksb35(&self) -> LCKSB35_R {
LCKSB35_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - LCKSB36"]
#[inline(always)]
pub fn lcksb36(&self) -> LCKSB36_R {
LCKSB36_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - LCKSB37"]
#[inline(always)]
pub fn lcksb37(&self) -> LCKSB37_R {
LCKSB37_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - LCKSB38"]
#[inline(always)]
pub fn lcksb38(&self) -> LCKSB38_R {
LCKSB38_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - LCKSB39"]
#[inline(always)]
pub fn lcksb39(&self) -> LCKSB39_R {
LCKSB39_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - LCKSB40"]
#[inline(always)]
pub fn lcksb40(&self) -> LCKSB40_R {
LCKSB40_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - LCKSB41"]
#[inline(always)]
pub fn lcksb41(&self) -> LCKSB41_R {
LCKSB41_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - LCKSB42"]
#[inline(always)]
pub fn lcksb42(&self) -> LCKSB42_R {
LCKSB42_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - LCKSB43"]
#[inline(always)]
pub fn lcksb43(&self) -> LCKSB43_R {
LCKSB43_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - LCKSB44"]
#[inline(always)]
pub fn lcksb44(&self) -> LCKSB44_R {
LCKSB44_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - LCKSB45"]
#[inline(always)]
pub fn lcksb45(&self) -> LCKSB45_R {
LCKSB45_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - LCKSB46"]
#[inline(always)]
pub fn lcksb46(&self) -> LCKSB46_R {
LCKSB46_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - LCKSB47"]
#[inline(always)]
pub fn lcksb47(&self) -> LCKSB47_R {
LCKSB47_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - LCKSB48"]
#[inline(always)]
pub fn lcksb48(&self) -> LCKSB48_R {
LCKSB48_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - LCKSB49"]
#[inline(always)]
pub fn lcksb49(&self) -> LCKSB49_R {
LCKSB49_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - LCKSB50"]
#[inline(always)]
pub fn lcksb50(&self) -> LCKSB50_R {
LCKSB50_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 19 - LCKSB51"]
#[inline(always)]
pub fn lcksb51(&self) -> LCKSB51_R {
LCKSB51_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 20 - LCKSB52"]
#[inline(always)]
pub fn lcksb52(&self) -> LCKSB52_R {
LCKSB52_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 21 - LCKSB53"]
#[inline(always)]
pub fn lcksb53(&self) -> LCKSB53_R {
LCKSB53_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 22 - LCKSB54"]
#[inline(always)]
pub fn lcksb54(&self) -> LCKSB54_R {
LCKSB54_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 23 - LCKSB55"]
#[inline(always)]
pub fn lcksb55(&self) -> LCKSB55_R {
LCKSB55_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 24 - LCKSB56"]
#[inline(always)]
pub fn lcksb56(&self) -> LCKSB56_R {
LCKSB56_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 25 - LCKSB57"]
#[inline(always)]
pub fn lcksb57(&self) -> LCKSB57_R {
LCKSB57_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 26 - LCKSB58"]
#[inline(always)]
pub fn lcksb58(&self) -> LCKSB58_R {
LCKSB58_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bit 27 - LCKSB59"]
#[inline(always)]
pub fn lcksb59(&self) -> LCKSB59_R {
LCKSB59_R::new(((self.bits >> 27) & 0x01) != 0)
}
#[doc = "Bit 28 - LCKSB60"]
#[inline(always)]
pub fn lcksb60(&self) -> LCKSB60_R {
LCKSB60_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 29 - LCKSB61"]
#[inline(always)]
pub fn lcksb61(&self) -> LCKSB61_R {
LCKSB61_R::new(((self.bits >> 29) & 0x01) != 0)
}
#[doc = "Bit 30 - LCKSB62"]
#[inline(always)]
pub fn lcksb62(&self) -> LCKSB62_R {
LCKSB62_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - LCKSB63"]
#[inline(always)]
pub fn lcksb63(&self) -> LCKSB63_R {
LCKSB63_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - LCKSB32"]
#[inline(always)]
pub fn lcksb32(&mut self) -> LCKSB32_W {
LCKSB32_W { w: self }
}
#[doc = "Bit 1 - LCKSB33"]
#[inline(always)]
pub fn lcksb33(&mut self) -> LCKSB33_W {
LCKSB33_W { w: self }
}
#[doc = "Bit 2 - LCKSB34"]
#[inline(always)]
pub fn lcksb34(&mut self) -> LCKSB34_W {
LCKSB34_W { w: self }
}
#[doc = "Bit 3 - LCKSB35"]
#[inline(always)]
pub fn lcksb35(&mut self) -> LCKSB35_W {
LCKSB35_W { w: self }
}
#[doc = "Bit 4 - LCKSB36"]
#[inline(always)]
pub fn lcksb36(&mut self) -> LCKSB36_W {
LCKSB36_W { w: self }
}
#[doc = "Bit 5 - LCKSB37"]
#[inline(always)]
pub fn lcksb37(&mut self) -> LCKSB37_W {
LCKSB37_W { w: self }
}
#[doc = "Bit 6 - LCKSB38"]
#[inline(always)]
pub fn lcksb38(&mut self) -> LCKSB38_W {
LCKSB38_W { w: self }
}
#[doc = "Bit 7 - LCKSB39"]
#[inline(always)]
pub fn lcksb39(&mut self) -> LCKSB39_W {
LCKSB39_W { w: self }
}
#[doc = "Bit 8 - LCKSB40"]
#[inline(always)]
pub fn lcksb40(&mut self) -> LCKSB40_W {
LCKSB40_W { w: self }
}
#[doc = "Bit 9 - LCKSB41"]
#[inline(always)]
pub fn lcksb41(&mut self) -> LCKSB41_W {
LCKSB41_W { w: self }
}
#[doc = "Bit 10 - LCKSB42"]
#[inline(always)]
pub fn lcksb42(&mut self) -> LCKSB42_W {
LCKSB42_W { w: self }
}
#[doc = "Bit 11 - LCKSB43"]
#[inline(always)]
pub fn lcksb43(&mut self) -> LCKSB43_W {
LCKSB43_W { w: self }
}
#[doc = "Bit 12 - LCKSB44"]
#[inline(always)]
pub fn lcksb44(&mut self) -> LCKSB44_W {
LCKSB44_W { w: self }
}
#[doc = "Bit 13 - LCKSB45"]
#[inline(always)]
pub fn lcksb45(&mut self) -> LCKSB45_W {
LCKSB45_W { w: self }
}
#[doc = "Bit 14 - LCKSB46"]
#[inline(always)]
pub fn lcksb46(&mut self) -> LCKSB46_W {
LCKSB46_W { w: self }
}
#[doc = "Bit 15 - LCKSB47"]
#[inline(always)]
pub fn lcksb47(&mut self) -> LCKSB47_W {
LCKSB47_W { w: self }
}
#[doc = "Bit 16 - LCKSB48"]
#[inline(always)]
pub fn lcksb48(&mut self) -> LCKSB48_W {
LCKSB48_W { w: self }
}
#[doc = "Bit 17 - LCKSB49"]
#[inline(always)]
pub fn lcksb49(&mut self) -> LCKSB49_W {
LCKSB49_W { w: self }
}
#[doc = "Bit 18 - LCKSB50"]
#[inline(always)]
pub fn lcksb50(&mut self) -> LCKSB50_W {
LCKSB50_W { w: self }
}
#[doc = "Bit 19 - LCKSB51"]
#[inline(always)]
pub fn lcksb51(&mut self) -> LCKSB51_W {
LCKSB51_W { w: self }
}
#[doc = "Bit 20 - LCKSB52"]
#[inline(always)]
pub fn lcksb52(&mut self) -> LCKSB52_W {
LCKSB52_W { w: self }
}
#[doc = "Bit 21 - LCKSB53"]
#[inline(always)]
pub fn lcksb53(&mut self) -> LCKSB53_W {
LCKSB53_W { w: self }
}
#[doc = "Bit 22 - LCKSB54"]
#[inline(always)]
pub fn lcksb54(&mut self) -> LCKSB54_W {
LCKSB54_W { w: self }
}
#[doc = "Bit 23 - LCKSB55"]
#[inline(always)]
pub fn lcksb55(&mut self) -> LCKSB55_W {
LCKSB55_W { w: self }
}
#[doc = "Bit 24 - LCKSB56"]
#[inline(always)]
pub fn lcksb56(&mut self) -> LCKSB56_W {
LCKSB56_W { w: self }
}
#[doc = "Bit 25 - LCKSB57"]
#[inline(always)]
pub fn lcksb57(&mut self) -> LCKSB57_W {
LCKSB57_W { w: self }
}
#[doc = "Bit 26 - LCKSB58"]
#[inline(always)]
pub fn lcksb58(&mut self) -> LCKSB58_W {
LCKSB58_W { w: self }
}
#[doc = "Bit 27 - LCKSB59"]
#[inline(always)]
pub fn lcksb59(&mut self) -> LCKSB59_W {
LCKSB59_W { w: self }
}
#[doc = "Bit 28 - LCKSB60"]
#[inline(always)]
pub fn lcksb60(&mut self) -> LCKSB60_W {
LCKSB60_W { w: self }
}
#[doc = "Bit 29 - LCKSB61"]
#[inline(always)]
pub fn lcksb61(&mut self) -> LCKSB61_W {
LCKSB61_W { w: self }
}
#[doc = "Bit 30 - LCKSB62"]
#[inline(always)]
pub fn lcksb62(&mut self) -> LCKSB62_W {
LCKSB62_W { w: self }
}
#[doc = "Bit 31 - LCKSB63"]
#[inline(always)]
pub fn lcksb63(&mut self) -> LCKSB63_W {
LCKSB63_W { w: self }
}
}
|
use std::collections::HashSet;
use std::iter::FromIterator;
use std::sync::mpsc::channel;
use std::time::Duration;
use timely::dataflow::channels::pact::Pipeline;
use timely::dataflow::operators::Operator;
use declarative_dataflow::binding::Binding;
use declarative_dataflow::plan::{Implementable, Join, Project};
use declarative_dataflow::server::Server;
use declarative_dataflow::timestamp::Time;
use declarative_dataflow::{q, Aid, Datom, Plan, Rule, Value};
use declarative_dataflow::{AttributeConfig, IndexDirection, InputSemantics, QuerySupport};
use Value::{Eid, Number, String};
struct Case {
description: &'static str,
plan: Plan<Aid>,
transactions: Vec<Vec<Datom<Aid>>>,
expectations: Vec<Vec<(Vec<Value>, u64, isize)>>,
}
fn dependencies(case: &Case) -> HashSet<Aid> {
let mut deps = HashSet::new();
for binding in case.plan.into_bindings().iter() {
if let Binding::Attribute(binding) = binding {
deps.insert(binding.source_attribute.clone());
}
}
deps
}
fn run_cases(mut cases: Vec<Case>) {
for case in cases.drain(..) {
timely::execute_directly(move |worker| {
let mut server = Server::<Aid, u64, u64>::new(Default::default());
let (send_results, results) = channel();
dbg!(case.description);
let mut deps = dependencies(&case);
let plan = case.plan.clone();
for tx in case.transactions.iter() {
for datum in tx {
deps.insert(datum.1.clone());
}
}
worker.dataflow::<u64, _, _>(|scope| {
for dep in deps.iter() {
let config = AttributeConfig {
input_semantics: InputSemantics::Distinct,
trace_slack: Some(Time::TxId(1)),
query_support: QuerySupport::AdaptiveWCO,
index_direction: IndexDirection::Both,
..Default::default()
};
server.create_attribute(scope, dep, config).unwrap();
}
server
.test_single(scope, Rule::named("query", plan))
.inner
.sink(Pipeline, "Results", move |input| {
input.for_each(|_time, data| {
for datum in data.iter() {
send_results.send(datum.clone()).unwrap()
}
});
});
});
let mut transactions = case.transactions.clone();
let mut next_tx = 0;
for (tx_id, tx_data) in transactions.drain(..).enumerate() {
next_tx += 1;
server.transact(tx_data, 0, 0).unwrap();
server.advance_domain(None, next_tx).unwrap();
worker.step_while(|| server.is_any_outdated());
let mut expected: HashSet<(Vec<Value>, u64, isize)> =
HashSet::from_iter(case.expectations[tx_id].iter().cloned());
for _i in 0..expected.len() {
match results.recv_timeout(Duration::from_millis(400)) {
Err(_err) => {
panic!("No result.");
}
Ok(result) => {
if !expected.remove(&result) {
panic!("Unknown result {:?}.", result);
}
}
}
}
match results.recv_timeout(Duration::from_millis(400)) {
Err(_err) => {}
Ok(result) => {
panic!("Extraneous result {:?}", result);
}
}
}
});
}
}
#[test]
fn base_patterns() {
let data = vec![
Datom::add(100, ":name", String("Dipper".to_string())),
Datom::add(100, ":name", String("Alias".to_string())),
Datom::add(200, ":name", String("Mabel".to_string())),
];
run_cases(vec![
Case {
description: "[:find ?e ?n :where [?e :name ?n]]",
plan: Plan::match_a(0, ":name", 1),
transactions: vec![data.clone()],
expectations: vec![vec![
(vec![Eid(100), String("Dipper".to_string())], 0, 1),
(vec![Eid(100), String("Alias".to_string())], 0, 1),
(vec![Eid(200), String("Mabel".to_string())], 0, 1),
]],
},
Case {
description: "[:find ?n :where [100 :name ?n]]",
plan: Plan::match_ea(100, ":name", 0),
transactions: vec![data.clone()],
expectations: vec![vec![
(vec![String("Alias".to_string())], 0, 1),
(vec![String("Dipper".to_string())], 0, 1),
]],
},
Case {
description: "[:find ?e :where [?e :name Mabel]]",
plan: Plan::match_av(0, ":name", String("Mabel".to_string())),
transactions: vec![data.clone()],
expectations: vec![vec![(vec![Eid(200)], 0, 1)]],
},
]);
}
#[test]
fn base_projections() {
let data = vec![
Datom::add(100, ":name", String("Dipper".to_string())),
Datom::add(100, ":name", String("Alias".to_string())),
Datom::add(200, ":name", String("Mabel".to_string())),
];
run_cases(vec![
Case {
description: "[:find ?e :where [?e :name ?n]]",
plan: Plan::Project(Project {
variables: vec![0],
plan: Box::new(Plan::match_a(0, ":name", 1)),
}),
transactions: vec![data.clone()],
expectations: vec![vec![(vec![Eid(100)], 0, 2), (vec![Eid(200)], 0, 1)]],
},
Case {
description: "[:find ?n :where [?e :name ?n]]",
plan: Plan::Project(Project {
variables: vec![1],
plan: Box::new(Plan::match_a(0, ":name", 1)),
}),
transactions: vec![data.clone()],
expectations: vec![vec![
(vec![String("Dipper".to_string())], 0, 1),
(vec![String("Alias".to_string())], 0, 1),
(vec![String("Mabel".to_string())], 0, 1),
]],
},
Case {
description: "[:find ?e ?n :where [?e :name ?n]]",
plan: Plan::Project(Project {
variables: vec![0, 1],
plan: Box::new(Plan::match_a(0, ":name", 1)),
}),
transactions: vec![data.clone()],
expectations: vec![vec![
(vec![Eid(100), String("Dipper".to_string())], 0, 1),
(vec![Eid(100), String("Alias".to_string())], 0, 1),
(vec![Eid(200), String("Mabel".to_string())], 0, 1),
]],
},
Case {
description: "[:find ?n ?e :where [?e :name ?n]]",
plan: Plan::Project(Project {
variables: vec![1, 0],
plan: Box::new(Plan::match_a(0, ":name", 1)),
}),
transactions: vec![data.clone()],
expectations: vec![vec![
(vec![String("Dipper".to_string()), Eid(100)], 0, 1),
(vec![String("Alias".to_string()), Eid(100)], 0, 1),
(vec![String("Mabel".to_string()), Eid(200)], 0, 1),
]],
},
]);
}
#[test]
fn wco_base_patterns() {
let data = vec![
Datom::add(100, ":name", String("Dipper".to_string())),
Datom::add(100, ":name", String("Alias".to_string())),
Datom::add(200, ":name", String("Mabel".to_string())),
];
run_cases(vec![
Case {
description: "[:find ?e ?n :where [?e :name ?n]]",
plan: q(vec![0, 1], vec![Binding::attribute(0, ":name", 1)]),
transactions: vec![data.clone()],
expectations: vec![vec![
(vec![Eid(100), String("Dipper".to_string())], 0, 1),
(vec![Eid(100), String("Alias".to_string())], 0, 1),
(vec![Eid(200), String("Mabel".to_string())], 0, 1),
]],
},
Case {
description: "[:find ?n :where [100 :name ?n]]",
plan: q(
vec![0, 1],
vec![
Binding::attribute(0, ":name", 1),
Binding::constant(0, Eid(100)),
],
),
transactions: vec![data.clone()],
expectations: vec![vec![
(vec![Eid(100), String("Alias".to_string())], 0, 1),
(vec![Eid(100), String("Dipper".to_string())], 0, 1),
]],
},
Case {
description: "[:find ?e :where [?e :name Mabel]]",
plan: q(
vec![0, 1],
vec![
Binding::attribute(0, ":name", 1),
Binding::constant(1, String("Mabel".to_string())),
],
),
transactions: vec![data.clone()],
expectations: vec![vec![(vec![Eid(200), String("Mabel".to_string())], 0, 1)]],
},
]);
}
#[test]
fn joins() {
run_cases(vec![{
let (e, a, n) = (1, 2, 3);
Case {
description: "[:find ?e ?n ?a :where [?e :age ?a] [?e :name ?n]]",
plan: Plan::Project(Project {
variables: vec![e, n, a],
plan: Box::new(Plan::Join(Join {
variables: vec![e],
left_plan: Box::new(Plan::match_a(e, ":name", n)),
right_plan: Box::new(Plan::match_a(e, ":age", a)),
})),
}),
transactions: vec![vec![
Datom::add(1, ":name", String("Dipper".to_string())),
Datom::add(1, ":age", Number(12)),
]],
expectations: vec![vec![(
vec![Eid(1), String("Dipper".to_string()), Number(12)],
0,
1,
)]],
}
}]);
}
#[test]
fn wco_joins() {
let data = vec![
Datom::add(1, ":name", String("Ivan".to_string())),
Datom::add(1, ":age", Number(15)),
Datom::add(2, ":name", String("Petr".to_string())),
Datom::add(2, ":age", Number(37)),
Datom::add(3, ":name", String("Ivan".to_string())),
Datom::add(3, ":age", Number(37)),
Datom::add(4, ":age", Number(15)),
];
run_cases(vec![
Case {
description: "[:find ?e :where [?e :name]]",
plan: q(vec![0], vec![Binding::attribute(0, ":name", 1)]),
transactions: vec![data.clone()],
expectations: vec![vec![
(vec![Eid(1)], 0, 1),
(vec![Eid(2)], 0, 1),
(vec![Eid(3)], 0, 1),
]],
},
Case {
description: "[:find ?e ?v :where [?e :name Ivan] [?e :age ?v]]",
plan: q(
vec![0, 2],
vec![
Binding::attribute(0, ":name", 1),
Binding::constant(1, String("Ivan".to_string())),
Binding::attribute(0, ":age", 2),
],
),
transactions: vec![data.clone()],
expectations: vec![vec![
(vec![Eid(1), Number(15)], 0, 1),
(vec![Eid(3), Number(37)], 0, 1),
]],
},
Case {
description: "[:find ?e1 ?e2 :where [?e1 :name ?n] [?e2 :name ?n]]",
plan: q(
vec![0, 2],
vec![
Binding::attribute(0, ":name", 1),
Binding::attribute(2, ":name", 1),
],
),
transactions: vec![data.clone()],
expectations: vec![vec![
(vec![Eid(1), Eid(1)], 0, 1),
(vec![Eid(2), Eid(2)], 0, 1),
(vec![Eid(3), Eid(3)], 0, 1),
(vec![Eid(1), Eid(3)], 0, 1),
(vec![Eid(3), Eid(1)], 0, 1),
]],
},
{
let (e, c, e2, a, n) = (0, 1, 2, 3, 4);
Case {
description: "[:find ?e ?e2 ?n :where [?e :name Ivan] [?e :age ?a] [?e2 :age ?a] [?e2 :name ?n]]",
plan: q(vec![e, e2, n], vec![
Binding::attribute(e, ":name", c),
Binding::constant(c, String("Ivan".to_string())),
Binding::attribute(e, ":age", a),
Binding::attribute(e2, ":age", a),
Binding::attribute(e2, ":name", n),
]),
transactions: vec![data.clone()],
expectations: vec![vec![
(vec![Eid(1), Eid(1), String("Ivan".to_string())], 0, 1),
(vec![Eid(3), Eid(3), String("Ivan".to_string())], 0, 1),
(vec![Eid(3), Eid(2), String("Petr".to_string())], 0, 1),
]],
}
},
]);
}
#[test]
fn wco_join_many() {
let data = vec![
Datom::add(1, ":name", String("Ivan".to_string())),
Datom::add(1, ":aka", String("ivolga".to_string())),
Datom::add(1, ":aka", String("pi".to_string())),
Datom::add(2, ":name", String("Petr".to_string())),
Datom::add(2, ":aka", String("porosenok".to_string())),
Datom::add(2, ":aka", String("pi".to_string())),
];
let (e1, x, e2, n1, n2) = (0, 1, 2, 3, 4);
run_cases(vec![Case {
description:
"[:find ?n1 ?n2 :where [?e1 :aka ?x] [?e2 :aka ?x] [?e1 :name ?n1] [?e2 :name ?n2]]",
plan: q(
vec![n1, n2],
vec![
Binding::attribute(e1, ":aka", x),
Binding::attribute(e2, ":aka", x),
Binding::attribute(e1, ":name", n1),
Binding::attribute(e2, ":name", n2),
],
),
transactions: vec![data.clone()],
expectations: vec![vec![
(
vec![String("Ivan".to_string()), String("Ivan".to_string())],
0,
2,
),
(
vec![String("Petr".to_string()), String("Petr".to_string())],
0,
2,
),
(
vec![String("Ivan".to_string()), String("Petr".to_string())],
0,
1,
),
(
vec![String("Petr".to_string()), String("Ivan".to_string())],
0,
1,
),
]],
}]);
}
// @TODO
// {
// let (e, a, n) = (1, 2, 3);
// let mut constants: HashMap<u32, Value> = HashMap::new();
// constants.insert(0, Number(18));
// Case {
// description: "[:find ?e ?n ?a :where [?e :age ?a] [?e :name ?n] [(<= 18 ?a)]]",
// plan: Plan::Project(Project {
// variables: vec![e, n, a],
// plan: Box::new(Plan::Join(Join {
// variables: vec![e],
// left_plan: Box::new(Plan::match_a(e, ":name", n)),
// right_plan: Box::new(Plan::Filter(Filter {
// variables: vec![a],
// predicate: Predicate::LTE,
// plan: Box::new(Plan::match_a(e, ":age", a)),
// constants: constants,
// })),
// })),
// }),
// transactions: vec![
// vec![
// Datom::add(100, ":name", String("Dipper".to_string())),
// Datom::add(100, ":age", Number(12)),
// Datom::add(100, ":name", String("Soos".to_string())),
// Datom::add(100, ":age", Number(30)),
// ],
// ],
// expectations: vec![
// vec![(vec![Eid(100), String("Dipper".to_string()), Number(12)], 0, 1)],
// ],
// }
// },
|
use std::fmt::Debug;
use std::ops::Range;
use gfx_hal::Backend;
use relevant::Relevant;
/// Trait for types that represent a block (`Range`) of `Memory`.
pub trait Block<B: Backend>: Send + Sync + Debug {
/// `Memory` instance of the block.
fn memory(&self) -> &B::Memory;
/// `Range` of the memory this block occupy.
fn range(&self) -> Range<u64>;
/// Get size of the block.
#[inline]
fn size(&self) -> u64 {
self.range().end - self.range().start
}
/// Check if a block is a child of this block.
///
/// ### Parameters:
///
/// - `other`: potential child block
///
/// ### Type parameters:
///
/// - `T`: tag of potential child block
fn contains<T>(&self, other: &T) -> bool
where
T: Block<B>,
{
use std::ptr::eq;
eq(self.memory(), other.memory()) && self.range().start <= other.range().start
&& self.range().end >= other.range().end
}
}
/// Tagged block of memory.
///
/// A `RawBlock` must never be silently dropped, that will result in a panic.
/// The block must be freed by returning it to the same allocator it came from.
///
/// ### Type parameters:
///
/// - `B`: hal `Backend`
/// - `T`: tag type, used by allocators to track allocations
#[derive(Debug)]
pub struct RawBlock<B: Backend> {
relevant: Relevant,
range: Range<u64>,
memory: *const B::Memory,
}
unsafe impl<B> Send for RawBlock<B>
where
B: Backend,
{
}
unsafe impl<B> Sync for RawBlock<B>
where
B: Backend,
{
}
impl<B> RawBlock<B>
where
B: Backend,
{
/// Construct a tagged block from `Memory` and `Range`.
/// The given `Memory` must not be freed if there are `Block`s allocated from it that are still
/// in use.
///
/// ### Parameters:
///
/// - `memory`: pointer to the actual memory for the block
/// - `range`: range of the `memory` used by the block
pub(crate) fn new(memory: *const B::Memory, range: Range<u64>) -> Self {
assert!(range.start <= range.end);
RawBlock {
relevant: Relevant,
memory,
range,
}
}
#[doc(hidden)]
/// Dispose of this block.
///
/// This is unsafe because the caller must ensure that the memory of the block is not used
/// again. This will typically entail dropping some kind of resource (`Buffer` or `Image` to
/// give some examples) that occupy this memory.
///
/// ### Returns
///
/// Tag value of the block
pub unsafe fn dispose(self) {
self.relevant.dispose();
}
}
impl<B> Block<B> for RawBlock<B>
where
B: Backend,
{
/// Get memory of the block.
#[inline]
fn memory(&self) -> &B::Memory {
// Has to be valid
unsafe { &*self.memory }
}
/// Get memory range of the block.
#[inline]
fn range(&self) -> Range<u64> {
self.range.clone()
}
}
impl<B, T, Y> Block<B> for (T, Y)
where
B: Backend,
T: Block<B>,
Y: Send + Sync + Debug,
{
/// Get memory of the block.
#[inline(always)]
fn memory(&self) -> &B::Memory {
// Has to be valid
self.0.memory()
}
/// Get memory range of the block.
#[inline(always)]
fn range(&self) -> Range<u64> {
self.0.range()
}
}
|
use crate::dynamic::RawSlice;
use std::slice;
// Helper to forward slice-optimized iterator functions.
macro_rules! forward {
($as:ident) => {
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let buf = self.iter.next()?;
Some(unsafe { buf.$as(self.len) })
}
#[inline]
fn nth(&mut self, n: usize) -> Option<Self::Item> {
let buf = self.iter.nth(n)?;
Some(unsafe { buf.$as(self.len) })
}
#[inline]
fn last(self) -> Option<Self::Item> {
let buf = self.iter.last()?;
Some(unsafe { buf.$as(self.len) })
}
#[inline]
fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item>
where
Self: Sized,
P: FnMut(&Self::Item) -> bool,
{
let len = self.len;
let buf = self
.iter
.find(move |buf| predicate(&unsafe { buf.$as(len) }))?;
Some(unsafe { buf.$as(self.len) })
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
#[inline]
fn count(self) -> usize {
self.iter.count()
}
#[inline]
fn for_each<F>(self, mut f: F)
where
Self: Sized,
F: FnMut(Self::Item),
{
let len = self.len;
self.iter.for_each(move |buf| f(unsafe { buf.$as(len) }));
}
#[inline]
fn all<F>(&mut self, mut f: F) -> bool
where
Self: Sized,
F: FnMut(Self::Item) -> bool,
{
let len = self.len;
self.iter.all(move |buf| f(unsafe { buf.$as(len) }))
}
#[inline]
fn any<F>(&mut self, mut f: F) -> bool
where
Self: Sized,
F: FnMut(Self::Item) -> bool,
{
let len = self.len;
self.iter.any(move |buf| f(unsafe { buf.$as(len) }))
}
#[inline]
fn find_map<B, F>(&mut self, mut f: F) -> Option<B>
where
Self: Sized,
F: FnMut(Self::Item) -> Option<B>,
{
let len = self.len;
self.iter.find_map(move |buf| f(unsafe { buf.$as(len) }))
}
#[inline]
fn position<P>(&mut self, mut predicate: P) -> Option<usize>
where
Self: Sized,
P: FnMut(Self::Item) -> bool,
{
let len = self.len;
self.iter
.position(move |buf| predicate(unsafe { buf.$as(len) }))
}
#[inline]
fn rposition<P>(&mut self, mut predicate: P) -> Option<usize>
where
P: FnMut(Self::Item) -> bool,
Self: Sized,
{
let len = self.len;
self.iter
.rposition(move |buf| predicate(unsafe { buf.$as(len) }))
}
};
}
/// An iterator over the channels in the buffer.
///
/// Created with [Dynamic::iter][crate::Dynamic::iter].
pub struct Iter<'a, T> {
iter: slice::Iter<'a, RawSlice<T>>,
len: usize,
}
impl<'a, T> Iter<'a, T> {
/// Construct a new iterator.
///
/// # Safety
///
/// The provided `len` must match the lengths of all provided slices.
#[inline]
pub(super) unsafe fn new(data: &'a [RawSlice<T>], len: usize) -> Self {
Self {
iter: data.iter(),
len,
}
}
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a [T];
forward!(as_ref);
}
impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
let buf = self.iter.next_back()?;
Some(unsafe { buf.as_ref(self.len) })
}
#[inline]
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
let buf = self.iter.nth_back(n)?;
Some(unsafe { buf.as_ref(self.len) })
}
}
impl<'a, T> ExactSizeIterator for Iter<'a, T> {
fn len(&self) -> usize {
self.iter.len()
}
}
/// A mutable iterator over the channels in the buffer.
///
/// Created with [Dynamic::iter_mut][crate::Dynamic::iter_mut].
pub struct IterMut<'a, T> {
iter: slice::IterMut<'a, RawSlice<T>>,
len: usize,
}
impl<'a, T> IterMut<'a, T> {
/// Construct a new iterator.
///
/// # Safety
///
/// The provided `len` must match the lengths of all provided slices.
#[inline]
pub(super) unsafe fn new(data: &'a mut [RawSlice<T>], len: usize) -> Self {
Self {
iter: data.iter_mut(),
len,
}
}
}
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut [T];
forward!(as_mut);
}
impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
let buf = self.iter.next_back()?;
Some(unsafe { buf.as_mut(self.len) })
}
#[inline]
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
let buf = self.iter.nth_back(n)?;
Some(unsafe { buf.as_mut(self.len) })
}
}
impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
fn len(&self) -> usize {
self.iter.len()
}
}
|
use super::*;
#[test]
fn without_boolean_value_errors_badarg() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term::is_not_boolean(arc_process.clone()),
)
},
|(arc_process, value)| {
prop_assert_is_not_boolean!(
result(&arc_process, flag(), value),
"trap_exit value",
value
);
Ok(())
},
);
}
// `with_boolean_returns_original_value_false` in integration tests
// `with_true_value_then_boolean_value_returns_old_value_true` in integration tests
// `with_true_value_with_linked_and_does_not_exit_when_linked_process_exits_normal` in integration
// tests
// `with_true_value_with_linked_receive_exit_message_and_does_not_exit_when_linked_process_exits` in
// integration tests `with_true_value_then_false_value_exits_when_linked_process_exits` in
// integration tests
fn flag() -> Term {
Atom::str_to_term("trap_exit")
}
|
pub fn factors(n: u64) -> Vec<u64> {
// unimplemented!("This should calculate the prime factors of {}", n)
let mut v: Vec<u64> = vec![];
let mut m = n;
let mut c = 2;
let mut done = false;
while !done {
if m >=2 {
while m % c == 0 {
v.push(c);
m = m / c;
}
c += 1;
} else {
done = true;
}
}
return v;
}
|
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::f64::consts::*;
#[allow(unused)]
const INF: usize = std::usize::MAX / 4;
#[allow(unused)]
const M: isize = 1000000007;
fn main() {
input! {
n: usize,
k: usize,
mut a: [isize; n],
}
let mut a_plus = vec![];
let mut a_minus = vec![];
for i in 0..n {
let ai = a[i];
if ai > 0 {
a_plus.push(ai);
} else if ai < 0 {
a_minus.push(ai);
}
}
let np = a_plus.len();
let nm = a_minus.len();
if np + nm < k {
eprintln!("zero");
println!("0");
return;
}
if (np == 0 && k % 2 == 1) || (np + nm == k && nm % 2 == 1) {
eprintln!("minus");
a.sort_by_key(|&ai| ai.abs());
let mut result = 1;
for i in 0..k {
result = result * a[i].abs() % M;
}
println!("{}", (M - result) % M);
return;
}
a_plus.sort();
a_plus.reverse();
a_minus.sort();
a_plus.push(0);
a_plus.push(0);
a_minus.push(0);
a_minus.push(0);
let mut result = vec![];
let mut i = 0;
let mut j = 0;
while result.len() < k {
let x = a_minus[j] * a_minus[j + 1];
let y = a_plus[i] * a_plus[i + 1];
if y > x || k - result.len() == 1 {
result.push(a_plus[i]);
i += 1;
} else {
result.push(a_minus[j]);
result.push(a_minus[j + 1]);
j += 2;
}
}
let mut s = 1;
for &ai in &result {
s = s * ai.abs() % M;
}
println!("{}", s);
}
|
use winapi::shared::minwindef::DWORD;
use winapi::um::winnt::*;
use crate::process::MemAccess;
pub trait MemAccessExt {
fn into_page_protect_loose(self) -> DWORD;
}
impl MemAccessExt for MemAccess {
fn into_page_protect_loose(self) -> DWORD {
match self {
MemAccess::None => PAGE_NOACCESS,
MemAccess::X => PAGE_EXECUTE,
MemAccess::W => PAGE_READWRITE,
MemAccess::WX => PAGE_EXECUTE_READWRITE,
MemAccess::R => PAGE_READONLY,
MemAccess::RX => PAGE_EXECUTE_READ,
MemAccess::RW => PAGE_EXECUTE_READWRITE,
MemAccess::RWX => PAGE_EXECUTE_READWRITE,
}
}
}
|
use serde::{Serialize, Serializer};
use std::fmt;
// TODO: make Line, Col, ByteOffset types?
#[derive(Copy, Clone, Default, Eq, PartialEq, Debug, Hash, Ord, PartialOrd)]
pub struct Location {
pub line: usize,
pub col: usize,
pub absolute: usize,
}
impl Location {
pub fn shift(mut self, ch: char) -> Location {
if ch == '\n' {
self.line += 1;
self.col = 1;
} else {
self.col += 1;
}
self.absolute += ch.len_utf8();
self
}
}
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub struct FileId(pub usize);
// template on Pos type?
#[derive(Copy, Clone, Eq, Debug)]
pub struct Span<Pos> {
pub file: FileId,
pub start: Pos,
pub end: Pos,
}
impl<Pos> Span<Pos> {
pub fn wrap<T>(self, value: T) -> Spanned<T, Pos> {
Spanned { value, span: self }
}
}
impl<Pos> PartialEq for Span<Pos>
where
Pos: PartialEq,
{
fn eq(&self, other: &Span<Pos>) -> bool {
self.start == other.start && self.end == other.end && self.file == other.file
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Spanned<T, Pos> {
pub span: Span<Pos>,
pub value: T,
}
impl<T, Pos> Spanned<T, Pos> {
pub fn map<U, F>(self, mut f: F) -> Spanned<U, Pos>
where
F: FnMut(T) -> U,
{
Spanned {
span: self.span,
value: f(self.value),
}
}
pub fn try_map<U, E, F>(self, mut f: F) -> Result<Spanned<U, Pos>, E>
where
F: FnMut(T) -> Result<U, E>,
{
let result = f(self.value)?;
Ok(Spanned {
span: self.span,
value: result,
})
}
}
// we may want a spanned to actually output a location
impl<T: Serialize, Pos: Serialize> Serialize for Spanned<T, Pos> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.value.serialize(serializer)
}
}
impl fmt::Display for Location {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Line: {}, Column: {}", self.line, self.col)
}
}
pub fn spanned<T, Pos>(file: FileId, start: Pos, end: Pos, value: T) -> Spanned<T, Pos> {
Spanned {
span: Span { file, start, end },
value: value,
}
}
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
// run-pass
// These crossed imports should resolve fine, and not block on
// each other and be reported as unresolved.
mod a {
use b::{B};
pub use self::inner::A;
mod inner {
pub struct A;
}
}
mod b {
use a::{A};
pub use self::inner::B;
mod inner {
pub struct B;
}
}
fn main() {}
|
/*!
This module just contains any big string literals I don't want cluttering up the rest of the code.
*/
/**
When generating a package's unique ID, how many hex nibbles of the digest should be used *at most*?
The largest meaningful value is `40`.
*/
pub const ID_DIGEST_LEN_MAX: usize = 16;
/**
How old can stuff in the cache be before we automatically clear it out?
Measured in milliseconds.
*/
// It's been *one week* since you looked at me,
// cocked your head to the side and said "I'm angry."
pub const MAX_CACHE_AGE_MS: u128 = 7 * 24 * 60 * 60 * 1000;
|
pub struct AhcTrie {
pub trie: Vec<[usize; 26]>, // a trie
pub failure: Vec<usize>, // failure function (trie node -> trie node)
pub output: Vec<Vec<usize>>, // output function (trie node -> Vec<query idx>)
}
fn as_idx(c: char) -> usize {
return ((c as u8) - ('a' as u8)) as usize;
}
pub fn build_trie(queries_vec: &Vec<Vec<char>>, t: &mut AhcTrie) {
// Build a trie.
// Create an invalid node 0.
t.trie.push([0; 26]);
t.failure.push(0);
t.output.push(Vec::new());
// Create a root node 1.
t.trie.push([0; 26]);
t.failure.push(0); // failure of root is 0
t.output.push(Vec::new());
for qidx in 0..queries_vec.len() {
let mut p: usize = 1;
for idx in 0..queries_vec[qidx].len() {
// Process character queries_vec[qidx][idx].
let ic: usize = as_idx(queries_vec[qidx][idx]);
if t.trie[p][ic] == 0 {
// create a new node & define it as a child!
let newp = t.trie.len();
t.trie.push([0; 26]);
t.trie[p][ic] = newp; // becomes child
t.failure.push(0); // dummy value, will be calculated later
// output will be updated later. :)
t.output.push(Vec::new());
}
// update p
assert!(
p < t.trie.len(),
"trie[{}][{}] ( == {}) < {}",
p,
ic,
t.trie[p][ic],
t.trie.len()
);
p = t.trie[p][ic];
}
t.output[p].push(qidx);
}
// Now, fill failure function.
for qidx in 0..queries_vec.len() {
let mut p: usize = 1;
for idx in 0..queries_vec[qidx].len() {
let ic: usize = as_idx(queries_vec[qidx][idx]);
// calculate failure
let mut f = t.failure[p];
while f != 0 {
if t.trie[f][ic] != 0 {
// found!
f = t.trie[f][ic];
break;
} else {
// rewind
f = t.failure[f];
}
}
if f == 0 {
// assign root node for failure
f = 1;
}
t.failure[t.trie[p][ic]] = f;
p = t.trie[p][ic];
}
}
}
pub fn print_trie(t: &AhcTrie) {
for i in 0..t.trie.len() {
for j in 0..26 {
if t.trie[i][j] != 0 {
println!(
"{} --{}--> {}",
i,
(('a' as u8) + (j as u8)) as char,
t.trie[i][j]
);
}
}
println!("failure: {} -> {}", i, t.failure[i]);
print!("output: ");
for j in 0..t.output[i].len() {
print!("{} ", t.output[i][j]);
}
println!("");
}
}
pub fn run(
text_vec: &Vec<char>,
queries_vec: &Vec<Vec<char>>,
t: &AhcTrie,
results: &mut Vec<Vec<usize>>,
) {
// Initialize results
for _ in 0..queries_vec.len() {
results.push(Vec::new());
}
let mut p = 1; // start at the root node!
for idx in 0..text_vec.len() {
let ic: usize = as_idx(text_vec[idx]);
// while condition: only root node's failure is 0
// other nodes' failure is bigger than 0
while p != 0 {
if t.trie[p][ic] == 0 {
// no corresponding child!
// follow failure
p = t.failure[p];
} else {
// found the node!
break;
}
}
if p == 0 {
// start at root again
p = 1;
} else {
// point to the child (next character)
p = t.trie[p][ic];
assert!(p != 0, "trie[{}][{}] ( == {}) != 0", p, ic, t.trie[p][ic]);
}
// If there is a match..
// Follow failure links to aggregate outputs!
// For example, if queries "abab", "ab", "b" are given,
// matching "abab" means "ab" and "b" are also matched!
let mut op = p;
while op != 1 {
for oidx in 0..t.output[op].len() {
// query queries_vec[qidx] matches!
let qidx = t.output[op][oidx];
results[qidx].push(idx + 1 - queries_vec[qidx].len());
}
op = t.failure[op];
}
}
for idx in 0..results.len() {
results[idx].dedup()
}
}
|
use std::collections::VecDeque;
fn main() {
let input = read_as_vec::<u32>();
let n = *input.get(0).unwrap();
let q = *input.get(1).unwrap();
let mut que: VecDeque<Proc> = (0..n)
.fold(VecDeque::new(), |mut que, _| {
let input: Vec<String> = read_as_vec();
let name = input[0].clone(); // TODO: cloneしなくても所有権を取得できるやり方があるのか
let time = input[1].parse::<u32>().ok().unwrap();
que.push_back(Proc::new(name, time));
que
});
let mut total = 0;
while let Some(mut p) = que.pop_front() {
if p.time > q {
total += q;
p.time = p.time - q;
que.push_back(p);
} else {
total += p.time;
println!("{} {}", p.name, total);
}
}
}
struct Proc {
name: String,
time: u32,
}
impl Proc {
fn new(name: String, time: u32) -> Self {
Proc { name, time }
}
}
fn read<T: std::str::FromStr>() -> T {
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
input.trim().parse::<T>().ok().unwrap()
}
fn read_as_vec<T: std::str::FromStr>() -> Vec<T> {
read::<String>()
.split_whitespace()
.map(|e| { e.parse::<T>().ok().unwrap() })
.collect()
}
|
//
// Emulator
//! The emulator program.
//
use jni::{JavaVM, Class};
use config::Config;
use minion::{Minion, Action, Options};
use storage;
/// The emulator class binding the JavaVM and terminal display.
pub struct Emulator {
_jvm: JavaVM,
java_class: Class,
minions: Vec<Minion>,
last_id: i32,
config: Config,
}
impl Emulator {
/// Create a new emulator.
pub fn new(config: &Config) -> Emulator {
let mut jvm = JavaVM::new(storage::classpath().as_slice()).unwrap();
jvm.set_calls_destructor(false);
let class = jvm.class("Minion").unwrap();
Emulator {
_jvm: jvm,
java_class: class,
minions: Vec::new(),
last_id: -1,
config: config.clone(),
}
}
/// Create a new minion with an automatically assigned ID.
pub fn new_minion(&mut self, advanced: bool, pocket: bool) {
self.last_id += 1;
// Get the minion's width and height
let (width, height) = if pocket {
(self.config.pocket_width, self.config.pocket_height)
} else {
(self.config.computer_width, self.config.computer_height)
};
// Create its title
let title = if pocket {
format!("Pocket Computer {}", self.last_id)
} else {
format!("Computer {}", self.last_id)
};
// Create its options
let options = Options {
id: self.last_id as u32,
advanced: advanced,
title: title,
width: width,
height: height,
space_limit: self.config.space_limit,
border_width: self.config.border_width,
border_height: self.config.border_height,
};
// Create the minion itself
let minion = if self.minions.len() == 0 {
Minion::new(&options, &self.java_class)
} else {
Minion::from_parent(&self.minions[0], &options, &self.java_class)
};
self.minions.push(minion);
}
/// Returns true if any minion is still running.
pub fn is_running(&self) -> bool {
let mut result = false;
for minion in self.minions.iter() {
result = result || minion.term.is_running();
}
result
}
/// Run the program, displaying the terminal windows and handling events.
pub fn run(&mut self) {
while self.is_running() {
let mut actions = Vec::new();
// Advance each minion
for minion in self.minions.iter_mut() {
minion.advance();
let potential = minion.trigger_events();
match potential {
Some(action) => actions.push(action),
None => {},
}
}
// Handle any returned actions
for action in actions.iter() {
match action {
&Action::NewComputer(advanced) =>
self.new_minion(advanced, false),
&Action::NewPocketComputer(advanced) =>
self.new_minion(advanced, true),
}
}
}
}
}
|
use test_win32::Windows::Win32::{
Foundation::{CloseHandle, BOOL, HANDLE, HWND, PSTR, PWSTR, RECT},
Gaming::HasExpandedResources,
Graphics::{Direct2D::CLSID_D2D1Shadow, Direct3D11::D3DDisassemble11Trace, Direct3D12::D3D12_DEFAULT_BLEND_FACTOR_ALPHA, Dxgi::Common::*, Dxgi::*, Hlsl::D3DCOMPILER_DLL},
Networking::Ldap::ldapsearch,
Security::Authorization::*,
System::Com::StructuredStorage::*,
System::Com::*,
System::{Com::CreateUri, Diagnostics::Debug::*, Threading::*},
UI::{
Accessibility::UIA_ScrollPatternNoScroll,
Animation::{UIAnimationManager, UIAnimationTransitionLibrary},
Controls::Dialogs::CHOOSECOLORW,
WindowsAndMessaging::{PROPENUMPROCA, PROPENUMPROCW, WM_KEYUP},
},
};
use std::convert::TryInto;
use windows::core::GUID;
#[test]
fn signed_enum32() {
assert!(ACCESS_MODE::default() == 0.into());
let e: ACCESS_MODE = REVOKE_ACCESS;
assert!(e == REVOKE_ACCESS);
}
#[test]
fn unsigned_enum32() {
assert!(DXGI_ADAPTER_FLAG::default() == 0.into());
let both = DXGI_ADAPTER_FLAG_SOFTWARE | DXGI_ADAPTER_FLAG_REMOTE;
assert!(both == 3.into());
}
#[test]
fn rect() {
let rect = RECT { left: 1, top: 2, right: 3, bottom: 4 };
assert!(rect.left == 1);
assert!(rect.top == 2);
assert!(rect.right == 3);
assert!(rect.bottom == 4);
let clone = rect.clone();
assert!(clone == RECT { left: 1, top: 2, right: 3, bottom: 4 });
}
#[test]
fn dxgi_mode_desc() {
let _ = DXGI_MODE_DESC {
Width: 1,
Height: 2,
RefreshRate: DXGI_RATIONAL { Numerator: 3, Denominator: 5 },
Format: DXGI_FORMAT_R32_TYPELESS,
ScanlineOrdering: DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE,
Scaling: DXGI_MODE_SCALING_CENTERED,
};
}
#[cfg(target_pointer_width = "64")]
#[test]
fn size64() {
assert!(core::mem::size_of::<ACCESS_MODE>() == 4);
assert!(core::mem::size_of::<DXGI_ADAPTER_FLAG>() == 4);
assert!(core::mem::size_of::<RECT>() == 16);
assert!(core::mem::size_of::<DXGI_MODE_DESC>() == 28);
assert_eq!(core::mem::size_of::<CHOOSECOLORW>(), 72);
}
#[cfg(target_pointer_width = "32")]
#[test]
fn size32() {
assert!(core::mem::size_of::<ACCESS_MODE>() == 4);
assert!(core::mem::size_of::<DXGI_ADAPTER_FLAG>() == 4);
assert!(core::mem::size_of::<RECT>() == 16);
assert!(core::mem::size_of::<DXGI_MODE_DESC>() == 28);
assert!(core::mem::size_of::<CHOOSECOLORW>() == 36);
}
#[test]
fn constant() {
assert!(WM_KEYUP == 257u32);
assert!(D3D12_DEFAULT_BLEND_FACTOR_ALPHA == 1f32);
assert!(UIA_ScrollPatternNoScroll == -1f64);
assert!(D3DCOMPILER_DLL == "d3dcompiler_47.dll");
assert!(CLSID_D2D1Shadow == GUID::from("C67EA361-1863-4e69-89DB-695D3E9A5B6B"));
}
#[test]
fn function() -> windows::core::Result<()> {
unsafe {
let event = CreateEventW(core::ptr::null_mut(), true, false, PWSTR(core::ptr::null_mut()));
assert!(event.0 != 0);
SetEvent(event).ok()?;
let result = WaitForSingleObject(event, 0);
assert!(result == WAIT_OBJECT_0);
CloseHandle(event).ok()?;
Ok(())
}
}
#[test]
fn bool_as_error() {
unsafe {
assert!(helpers::set_thread_ui_language("en-US"));
assert!(!SetEvent(HANDLE(0)).as_bool());
let result: windows::core::Result<()> = SetEvent(HANDLE(0)).ok();
assert!(result.is_err());
let error: windows::core::Error = result.unwrap_err();
assert_eq!(error.code(), windows::core::HRESULT(0x8007_0006));
let message: String = error.message().try_into().unwrap();
assert_eq!(message.trim_end(), "The handle is invalid.");
}
}
#[test]
fn com() -> windows::core::Result<()> {
unsafe {
let stream = CreateStreamOnHGlobal(0, true)?;
let values = vec![1, 20, 300, 4000];
let copied = stream.Write(values.as_ptr() as _, (values.len() * core::mem::size_of::<i32>()) as u32)?;
assert!(copied == (values.len() * core::mem::size_of::<i32>()) as u32);
let copied = stream.Write(&UIAnimationTransitionLibrary as *const _ as _, core::mem::size_of::<windows::core::GUID>() as u32)?;
assert!(copied == core::mem::size_of::<windows::core::GUID>() as u32);
let position = stream.Seek(0, STREAM_SEEK_SET)?;
assert!(position == 0);
let mut values = vec![0, 0, 0, 0];
let mut copied = 0;
stream.Read(values.as_mut_ptr() as _, (values.len() * core::mem::size_of::<i32>()) as u32, &mut copied)?;
assert!(copied == (values.len() * core::mem::size_of::<i32>()) as u32);
assert!(values == vec![1, 20, 300, 4000]);
let mut value: windows::core::GUID = windows::core::GUID::default();
let mut copied = 0;
stream.Read(&mut value as *mut _ as _, core::mem::size_of::<windows::core::GUID>() as u32, &mut copied)?;
assert!(copied == core::mem::size_of::<windows::core::GUID>() as u32);
assert!(value == UIAnimationTransitionLibrary);
}
Ok(())
}
#[test]
fn com_inheritance() {
unsafe {
let factory: IDXGIFactory7 = CreateDXGIFactory1().unwrap();
// IDXGIFactory
assert!(factory.MakeWindowAssociation(HWND(0), 0).is_ok());
// IDXGIFactory1
assert!(factory.IsCurrent().as_bool());
// IDXGIFactory2
factory.IsWindowedStereoEnabled();
// IDXGIFactory3
assert!(factory.GetCreationFlags() == 0);
// IDXGIFactory7 (default)
assert!(factory.RegisterAdaptersChangedEvent(HANDLE(0)).unwrap_err().code() == DXGI_ERROR_INVALID_CALL);
}
}
// Tests for https://github.com/microsoft/windows-rs/issues/463
#[test]
fn onecore_imports() -> windows::core::Result<()> {
unsafe {
HasExpandedResources()?;
let uri = CreateUri(PWSTR(windows::core::HSTRING::from("http://kennykerr.ca").as_wide().as_ptr() as _), Default::default(), 0)?;
let port = uri.GetPort()?;
assert!(port == 80);
let result = MiniDumpWriteDump(None, 0, None, MiniDumpNormal, core::ptr::null_mut(), core::ptr::null_mut(), core::ptr::null_mut());
assert!(!result.as_bool());
assert!(D3DDisassemble11Trace(core::ptr::null_mut(), 0, None, 0, 0, 0).is_err());
Ok(())
}
}
#[test]
fn interface() -> windows::core::Result<()> {
unsafe {
let uri = CreateUri("http://kennykerr.ca", Default::default(), 0)?;
let domain = uri.GetDomain()?;
assert!(domain == "kennykerr.ca");
}
Ok(())
}
#[test]
fn callback() {
unsafe {
let a: PROPENUMPROCA = callback_a;
assert!(BOOL(789) == a(HWND(123), PSTR("hello a\0".as_ptr() as _), HANDLE(456)));
let a: PROPENUMPROCW = callback_w;
assert!(BOOL(789) == a(HWND(123), PWSTR(windows::core::HSTRING::from("hello w\0").as_wide().as_ptr() as _), HANDLE(456)));
}
}
// TODO: second parameter should be *const i8
extern "system" fn callback_a(param0: HWND, param1: PSTR, param2: HANDLE) -> BOOL {
unsafe {
assert!(param0.0 == 123);
assert!(param2.0 == 456);
let mut len = 0;
let mut end = param1.0;
loop {
if *end == 0 {
break;
}
len += 1;
end = end.add(1);
}
let s = String::from_utf8_lossy(core::slice::from_raw_parts(param1.0 as *const u8, len)).into_owned();
assert!(s == "hello a");
BOOL(789)
}
}
// TODO: second parameter should be *const u16
extern "system" fn callback_w(param0: HWND, param1: PWSTR, param2: HANDLE) -> BOOL {
unsafe {
assert!(param0.0 == 123);
assert!(param2.0 == 456);
let mut len = 0;
let mut end = param1.0;
loop {
if *end == 0 {
break;
}
len += 1;
end = end.add(1);
}
let s = String::from_utf16_lossy(core::slice::from_raw_parts(param1.0, len));
assert!(s == "hello w");
BOOL(789)
}
}
#[test]
fn empty_struct() {
let ldap = ldapsearch(123);
assert!(ldap.0 == 123);
assert!(core::mem::size_of::<ldapsearch>() == 1);
assert!(UIAnimationManager == GUID::from("4C1FC63A-695C-47E8-A339-1A194BE3D0B8"));
}
|
#![allow(dead_code)]
use std::marker::PhantomData;
#[allow(unused_imports)]
use abi_stable::{
external_types::{RMutex, ROnce, RRwLock},
std_types::*,
};
pub(super) mod basic_enum {
#[repr(C)]
#[derive(abi_stable::StableAbi)]
pub enum Enum {
Variant0,
Variant1 { a: u32 },
}
}
pub(super) mod gen_basic {
use super::PhantomData;
#[repr(C)]
#[derive(abi_stable::StableAbi)]
pub struct Generics<T: 'static> {
x: &'static T,
y: &'static T,
_marker: PhantomData<T>,
}
}
pub(super) mod gen_more_lts {
use super::PhantomData;
#[repr(C)]
#[derive(abi_stable::StableAbi)]
#[sabi(bound(T:'a))]
pub struct Generics<'a, T> {
x: &'a T,
y: &'a T,
_marker: PhantomData<&'a T>,
}
}
pub(super) mod enum_extra_fields_b {
#[repr(C)]
#[derive(abi_stable::StableAbi)]
pub enum Enum {
Variant0,
Variant1 { a: u32, b: u32, c: u32 },
}
}
pub(super) mod extra_variant {
use abi_stable::std_types::RString;
#[repr(C)]
#[derive(abi_stable::StableAbi)]
pub enum Enum {
Variant0,
Variant1 { a: u32 },
Variant3(RString),
}
}
pub(super) mod swapped_fields_first {
#[repr(C)]
#[derive(abi_stable::StableAbi)]
pub struct Rectangle {
y: u32,
x: u32,
w: u16,
h: u32,
}
}
pub(super) mod gen_more_lts_b {
#[repr(C)]
#[derive(abi_stable::StableAbi)]
pub struct Generics<'a> {
x: &'a (),
y: &'static (),
}
}
pub(super) mod mod_5 {
use super::RString;
#[repr(C)]
#[derive(abi_stable::StableAbi)]
pub struct Mod {
pub function_0: extern "C" fn() -> RString,
pub function_1: extern "C" fn(&mut u32, u64, RString),
pub function_2: extern "C" fn(&mut u32, u64, RString),
}
}
pub(super) mod mod_7 {
use super::RString;
#[repr(C)]
#[derive(abi_stable::StableAbi)]
pub struct Mod {
pub function_0: extern "C" fn() -> RString,
pub function_1: extern "C" fn(&mut u32, u64, RString),
pub function_2: extern "C" fn((), (), ()),
}
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Separation character for an ACTS command
pub const COMMAND_DELIMITER: &str = ".";
// Number of clauses for an ACTS command
pub const COMMAND_SIZE: usize = 2;
|
use anyhow::{Context, Result, anyhow};
use tokio::sync::{broadcast::self, mpsc};
use tokio_tungstenite::{
connect_async,
tungstenite::protocol::Message,
};
use futures_util::StreamExt;
use rust_decimal::Decimal;
use std::collections::HashMap;
use std::str::FromStr;
use actix::Addr;
use crate::CONFIG;
use crate::actix_actors::FeedActor;
use super::settings::*;
use super::web_socket::*;
use super::types::*;
pub async fn stream_init_task(feed_actor_addr: Addr<FeedActor>) -> Result<()>
{
let task_name = "--Stream Init Task--";
let (ws_stream, _) = connect_async(CONFIG.web_socket_url.clone()).await
.context(format!("Error in {:?}:\ninput_rx_ch:\n", task_name))?;
let (writer, reader) = ws_stream.split();
let (writer_tx_ch, writer_rx_ch): (mpsc::Sender<Message>, mpsc::Receiver<Message>) = mpsc::channel(20);
let writer_settings = WriterSettings::new(writer, writer_rx_ch);
tokio::spawn(writer_task(writer_settings));
let (reader_tx_ch, reader_rx_ch) = broadcast::channel(10);
let reader_settings = ReaderSettings::new(reader, reader_tx_ch);
tokio::spawn(reader_task(reader_settings));
writer_tx_ch.send(CONFIG.web_socket_feed.clone()).await
.context(format!("Error in {:?}:\ninput_rx_ch:\n", task_name))?;
let (output_tx_ch, mut output_rx_ch) = broadcast::channel(10);
let deserialize_settings = DeserializeSettings::new(reader_rx_ch, output_tx_ch, writer_tx_ch);
tokio::spawn(stream_management_task(deserialize_settings));
while let Ok(message) = output_rx_ch.recv().await{
if message.luna_exch_rates.len() > 0 {
feed_actor_addr.do_send(message);
}
}
Ok(())
}
async fn stream_management_task(mut deserialize_settings: DeserializeSettings){
let task_name = "--Stream Management Task--";
log::info!("{:?} Init", task_name);
loop{
match websocket_msg_process(&mut deserialize_settings).await {
Ok(_)=> continue,
Err(err) => {
log::error!("{:?}", err);
match &err.downcast_ref::<broadcast::error::RecvError>() {
Some(err) => {
match err {
broadcast::error::RecvError::Lagged(x) => {
log::trace!("Trace in {:?}:\ninput_rx_ch lagged:\n{:?}\n", task_name, x);
continue;
},
broadcast::error::RecvError::Closed => {
log::warn!("Warning in {:?}:\ninput_rx_ch closed:\n", task_name);
break;
}
}
},
None => log::warn!("Warning in {:?}:\ninput_rx_ch closed:\n", task_name)
};
}
};
}
log::info!("{:?} End", task_name);
}
async fn websocket_msg_process(deserialize_settings: &mut DeserializeSettings) -> Result<()> {
let task_name = "--websocket msg process Task--";
let input_msg = deserialize_settings.input_rx_ch.recv().await
.context(format!("Error in {:?}:\ninput_rx_ch:\n", task_name))?;
log::trace!("{:?}:\nReceived message from reader\n{:?}", task_name, input_msg);
match input_msg {
Message::Close(close_data) => log::warn!("Warning in {:?}:\nClose message received:\n {:?}", task_name, close_data),
Message::Ping(ping_data) => {
let pong_msg = Message::Pong(ping_data);
deserialize_settings.writer_tx_ch.send(pong_msg).await
.context(format!("Error in {:?}:\nSending pong:\n", task_name))?;
log::trace!("Trace in {:?}:\nSent pong", task_name)
},
Message::Pong(pong_data) => log::warn!("Warning in {:?}:\nPong message received:\n {:?}", task_name, pong_data),
Message::Text(text_data) => {
let data = deserialize_stream(text_data)
.context(format!("Error in {:?}:\nDesirializing:\n", task_name))?;
deserialize_settings.output_tx_ch.send(data)
.context(format!("Error in {:?}:\nSending data:\n", task_name))?;
},
Message::Binary(_) => log::warn!("Warning in {:?}: binary data sent:\n", task_name)
}
Ok(())
}
pub fn deserialize_stream(json_str: String) -> Result<OutputData>{
log::info!("Deserialize stream Init");
let feed: Feed = serde_json::from_str(&json_str)
.context("JSON was not well-formatted deserialize_stream")?;
//Aggregate all events from all logs from all tx
let events_iter = feed.data.txs.into_iter()
.flat_map(|x| x.logs)
.flat_map(|x| x.events);
// let borrow_stable_iter = events_iter.clone().filter(|x| x.event_type == "borrow_stable");
//Aggregate all events from all logs
//Could use filter_map() but using first filter then map is more readable, avoids an ugly 'if' clause
let rates_iter = events_iter
.filter(|x| x.event_type == "aggregate_vote")
.map(|x| x.attributes.into_iter()
.filter(|y| y.key == "exchange_rates")
.map(|x| x.value))
.flatten();
let mut hash_map: HashMap<Asset, ExchangeRate> = HashMap::new();
//Only need one voter exchange rate.
for i in rates_iter.take(1){
let split = i.split(",");
for attribute in split.into_iter() {
let reg_symbol = regex::Regex::new(r"([a-z]+)")?;
let reg_value = regex::Regex::new(r"([+-]?\d+\.?\d*|\.\d+)")?;
let symbol: &str = reg_symbol.find(&attribute)
.ok_or(anyhow!("Error regex symbol"))?.as_str();
let rate: &str = reg_value.find(&attribute)
.ok_or(anyhow!("Error regex rate"))?.as_str();
hash_map.insert(symbol.to_owned(), Decimal::from_str(rate)?);
}
}
let output_data = OutputData{
luna_exch_rates: hash_map,
// events: borrow_stable_iter.collect::<Vec<_>>()
};
Ok(output_data)
} |
use std::io;
fn main() {
let mut og_str = String::new();
let mut new_str = String::new();
let vowels = ['a', 'e', 'i', 'o', 'u'];
io::stdin().read_line(&mut og_str).ok().expect("read error");
og_str = og_str.to_lowercase();
//https://stackoverflow.com/questions/30811107/getting-a-single-character-out-of-a-string
let first_char = og_str.chars().next().unwrap();
if vowels.contains(&first_char) {
new_str = format!("{}-hay", &og_str);
} else {
for (i, c) in og_str.char_indices() {
if i == 0 {
continue;
} else {
new_str.push(c);
}
}
new_str = format!("{}-{}ay", new_str, first_char);
}
println!("{}", new_str);
}
|
use std::io;
use std::io::Write;
use std::mem;
use std::sync::atomic::{AtomicUsize, Ordering};
use chrono::Local;
use console::{style, Color};
use log;
/// A simple logger
pub struct Logger;
lazy_static! {
static ref MAX_LEVEL: AtomicUsize =
AtomicUsize::new(unsafe { mem::transmute(log::LevelFilter::Warn) });
}
pub fn max_level() -> log::LevelFilter {
unsafe { mem::transmute(MAX_LEVEL.load(Ordering::Relaxed)) }
}
pub fn set_max_level(level: log::LevelFilter) {
MAX_LEVEL.store(unsafe { mem::transmute(level) }, Ordering::Relaxed);
}
impl Logger {
fn get_actual_level(&self, metadata: &log::Metadata) -> log::Level {
let mut level = metadata.level();
if level == log::Level::Debug
&& (metadata.target() == "tokio_reactor"
|| metadata.target().starts_with("hyper::proto::"))
{
level = log::Level::Trace;
}
level
}
}
impl log::Log for Logger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
self.get_actual_level(metadata) <= max_level()
}
fn log(&self, record: &log::Record) {
if !self.enabled(record.metadata()) {
return;
}
let level = self.get_actual_level(record.metadata());
let (level_name, level_color) = match level {
log::Level::Error => ("ERROR", Color::Red),
log::Level::Warn => ("WARN ", Color::Red),
log::Level::Info => ("INFO ", Color::Cyan),
log::Level::Debug => ("DEBUG", Color::Yellow),
log::Level::Trace => ("TRACE", Color::Magenta),
};
let short_target = record.target().split("::").next().unwrap_or("");
let msg = format!(
"{} {} {}{}",
style(format!(" {} ", level_name)).bg(level_color).black(),
style(Local::now()).dim(),
style(record.args()),
style(if short_target != "sentry_cli" {
format!(" (from {})", short_target)
} else {
"".to_string()
}).dim(),
);
writeln!(io::stderr(), "{}", msg).ok();
}
fn flush(&self) {}
}
|
//! An optimizer rule that transforms a plan
//! to fill gaps in time series data.
pub mod range_predicate;
use crate::exec::gapfill::{FillStrategy, GapFill, GapFillParams};
use datafusion::{
common::tree_node::{RewriteRecursion, TreeNode, TreeNodeRewriter, VisitRecursion},
error::{DataFusionError, Result},
logical_expr::{
expr::{Alias, ScalarFunction, ScalarUDF},
utils::expr_to_columns,
Aggregate, BuiltinScalarFunction, Extension, LogicalPlan, Projection,
},
optimizer::{optimizer::ApplyOrder, OptimizerConfig, OptimizerRule},
prelude::{col, Expr},
};
use hashbrown::{hash_map, HashMap};
use query_functions::gapfill::{DATE_BIN_GAPFILL_UDF_NAME, INTERPOLATE_UDF_NAME, LOCF_UDF_NAME};
use std::{
collections::HashSet,
ops::{Bound, Range},
sync::Arc,
};
/// This optimizer rule enables gap-filling semantics for SQL queries
/// that contain calls to `DATE_BIN_GAPFILL()` and related functions
/// like `LOCF()`.
///
/// In SQL a typical gap-filling query might look like this:
/// ```sql
/// SELECT
/// location,
/// DATE_BIN_GAPFILL(INTERVAL '1 minute', time, '1970-01-01T00:00:00Z') AS minute,
/// LOCF(AVG(temp))
/// FROM temps
/// WHERE time > NOW() - INTERVAL '6 hours' AND time < NOW()
/// GROUP BY LOCATION, MINUTE
/// ```
///
/// The initial logical plan will look like this:
///
/// ```text
/// Projection: location, date_bin_gapfill(...) as minute, LOCF(AVG(temps.temp))
/// Aggregate: groupBy=[[location, date_bin_gapfill(...)]], aggr=[[AVG(temps.temp)]]
/// ...
/// ```
///
/// This optimizer rule transforms it to this:
///
/// ```text
/// Projection: location, date_bin_gapfill(...) as minute, AVG(temps.temp)
/// GapFill: groupBy=[[location, date_bin_gapfill(...))]], aggr=[[LOCF(AVG(temps.temp))]], start=..., stop=...
/// Aggregate: groupBy=[[location, date_bin(...))]], aggr=[[AVG(temps.temp)]]
/// ...
/// ```
///
/// For `Aggregate` nodes that contain calls to `DATE_BIN_GAPFILL`, this rule will:
/// - Convert `DATE_BIN_GAPFILL()` to `DATE_BIN()`
/// - Create a `GapFill` node that fills in gaps in the query
/// - The range for gap filling is found by analyzing any preceding `Filter` nodes
///
/// If there is a `Projection` above the `GapFill` node that gets created:
/// - Look for calls to gap-filling functions like `LOCF`
/// - Push down these functions into the `GapFill` node, updating the fill strategy for the column.
///
/// Note: both `DATE_BIN_GAPFILL` and `LOCF` are functions that don't have implementations.
/// This rule must rewrite the plan to get rid of them.
pub struct HandleGapFill;
impl HandleGapFill {
pub fn new() -> Self {
Self {}
}
}
impl Default for HandleGapFill {
fn default() -> Self {
Self::new()
}
}
impl OptimizerRule for HandleGapFill {
fn try_optimize(
&self,
plan: &LogicalPlan,
_config: &dyn OptimizerConfig,
) -> Result<Option<LogicalPlan>> {
handle_gap_fill(plan)
}
fn name(&self) -> &str {
"handle_gap_fill"
}
fn apply_order(&self) -> Option<ApplyOrder> {
Some(ApplyOrder::BottomUp)
}
}
fn handle_gap_fill(plan: &LogicalPlan) -> Result<Option<LogicalPlan>> {
let res = match plan {
LogicalPlan::Aggregate(aggr) => handle_aggregate(aggr)?,
LogicalPlan::Projection(proj) => handle_projection(proj)?,
_ => None,
};
if res.is_none() {
// no transformation was applied,
// so make sure the plan is not using gap filling
// functions in an unsupported way.
check_node(plan)?;
}
Ok(res)
}
fn handle_aggregate(aggr: &Aggregate) -> Result<Option<LogicalPlan>> {
let Aggregate {
input,
group_expr,
aggr_expr,
schema,
..
} = aggr;
// new_group_expr has DATE_BIN_GAPFILL replaced with DATE_BIN.
let RewriteInfo {
new_group_expr,
date_bin_gapfill_index,
date_bin_gapfill_args,
} = if let Some(v) = replace_date_bin_gapfill(group_expr)? {
v
} else {
return Ok(None);
};
let new_aggr_plan = {
// Create the aggregate node with the same output schema as the orignal
// one. This means that there will be an output column called `date_bin_gapfill(...)`
// even though the actual expression populating that column will be `date_bin(...)`.
// This seems acceptable since it avoids having to deal with renaming downstream.
let new_aggr_plan = Aggregate::try_new_with_schema(
Arc::clone(input),
new_group_expr,
aggr_expr.clone(),
Arc::clone(schema),
)?;
let new_aggr_plan = LogicalPlan::Aggregate(new_aggr_plan);
check_node(&new_aggr_plan)?;
new_aggr_plan
};
let new_gap_fill_plan =
build_gapfill_node(new_aggr_plan, date_bin_gapfill_index, date_bin_gapfill_args)?;
Ok(Some(new_gap_fill_plan))
}
fn build_gapfill_node(
new_aggr_plan: LogicalPlan,
date_bin_gapfill_index: usize,
date_bin_gapfill_args: Vec<Expr>,
) -> Result<LogicalPlan> {
match date_bin_gapfill_args.len() {
2 | 3 => (),
nargs => {
return Err(DataFusionError::Plan(format!(
"DATE_BIN_GAPFILL expects 2 or 3 arguments, got {nargs}",
)));
}
}
let mut args_iter = date_bin_gapfill_args.into_iter();
// Ensure that stride argument is a scalar
let stride = args_iter.next().unwrap();
validate_scalar_expr("stride argument to DATE_BIN_GAPFILL", &stride)?;
// Ensure that the source argument is a column
let time_col = args_iter.next().unwrap().try_into_col().map_err(|_| {
DataFusionError::Plan(
"DATE_BIN_GAPFILL requires a column as the source argument".to_string(),
)
})?;
// Ensure that a time range was specified and is valid for gap filling
let time_range = range_predicate::find_time_range(new_aggr_plan.inputs()[0], &time_col)?;
validate_time_range(&time_range)?;
// Ensure that origin argument is a scalar
let origin = args_iter.next();
if let Some(ref origin) = origin {
validate_scalar_expr("origin argument to DATE_BIN_GAPFILL", origin)?;
}
// Make sure the time output to the gapfill node matches what the
// aggregate output was.
let time_column =
col(new_aggr_plan.schema().fields()[date_bin_gapfill_index].qualified_column());
let LogicalPlan::Aggregate(aggr) = &new_aggr_plan else {
return Err(DataFusionError::Internal(format!("Expected Aggregate plan, got {}", new_aggr_plan.display())));
};
let mut new_group_expr: Vec<_> = aggr
.schema
.fields()
.iter()
.map(|f| Expr::Column(f.qualified_column()))
.collect();
let aggr_expr = new_group_expr.split_off(aggr.group_expr.len());
let fill_behavior = aggr_expr
.iter()
.cloned()
.map(|e| (e, FillStrategy::Null))
.collect();
Ok(LogicalPlan::Extension(Extension {
node: Arc::new(GapFill::try_new(
Arc::new(new_aggr_plan),
new_group_expr,
aggr_expr,
GapFillParams {
stride,
time_column,
origin,
time_range,
fill_strategy: fill_behavior,
},
)?),
}))
}
fn validate_time_range(range: &Range<Bound<Expr>>) -> Result<()> {
let Range { ref start, ref end } = range;
let (start, end) = match (start, end) {
(Bound::Unbounded, Bound::Unbounded) => {
return Err(DataFusionError::Plan(
"gap-filling query is missing both upper and lower time bounds".to_string(),
))
}
(Bound::Unbounded, _) => Err(DataFusionError::Plan(
"gap-filling query is missing lower time bound".to_string(),
)),
(_, Bound::Unbounded) => Err(DataFusionError::Plan(
"gap-filling query is missing upper time bound".to_string(),
)),
(
Bound::Included(start) | Bound::Excluded(start),
Bound::Included(end) | Bound::Excluded(end),
) => Ok((start, end)),
}?;
validate_scalar_expr("lower time bound", start)?;
validate_scalar_expr("upper time bound", end)
}
fn validate_scalar_expr(what: &str, e: &Expr) -> Result<()> {
let mut cols = HashSet::new();
expr_to_columns(e, &mut cols)?;
if !cols.is_empty() {
Err(DataFusionError::Plan(format!(
"{what} for gap fill query must evaluate to a scalar"
)))
} else {
Ok(())
}
}
struct RewriteInfo {
// Group expressions with DATE_BIN_GAPFILL rewritten to DATE_BIN.
new_group_expr: Vec<Expr>,
// The index of the group expression that contained the call to DATE_BIN_GAPFILL.
date_bin_gapfill_index: usize,
// The arguments to the call to DATE_BIN_GAPFILL.
date_bin_gapfill_args: Vec<Expr>,
}
// Iterate over the group expression list.
// If it finds no occurrences of date_bin_gapfill, it will return None.
// If it finds more than one occurrence it will return an error.
// Otherwise it will return a RewriteInfo for the optimizer rule to use.
fn replace_date_bin_gapfill(group_expr: &[Expr]) -> Result<Option<RewriteInfo>> {
let mut date_bin_gapfill_count = 0;
let mut dbg_idx = None;
group_expr
.iter()
.enumerate()
.try_for_each(|(i, e)| -> Result<()> {
let fn_cnt = count_udf(e, DATE_BIN_GAPFILL_UDF_NAME)?;
date_bin_gapfill_count += fn_cnt;
if fn_cnt > 0 {
dbg_idx = Some(i);
}
Ok(())
})?;
match date_bin_gapfill_count {
0 => return Ok(None),
1 => {
// Make sure that the call to DATE_BIN_GAPFILL is root expression
// excluding aliases.
let dbg_idx = dbg_idx.expect("should have found exactly one call");
if !matches_udf(
unwrap_alias(&group_expr[dbg_idx]),
DATE_BIN_GAPFILL_UDF_NAME,
) {
return Err(DataFusionError::Plan(
"DATE_BIN_GAPFILL must a top-level expression in the GROUP BY clause when gap filling. It cannot be part of another expression or cast".to_string(),
));
}
}
_ => {
return Err(DataFusionError::Plan(
"DATE_BIN_GAPFILL specified more than once".to_string(),
))
}
}
let date_bin_gapfill_index = dbg_idx.expect("should be found exactly one call");
let mut rewriter = DateBinGapfillRewriter { args: None };
let group_expr = group_expr
.iter()
.enumerate()
.map(|(i, e)| {
if i == date_bin_gapfill_index {
e.clone().rewrite(&mut rewriter)
} else {
Ok(e.clone())
}
})
.collect::<Result<Vec<_>>>()?;
let date_bin_gapfill_args = rewriter.args.expect("should have found args");
Ok(Some(RewriteInfo {
new_group_expr: group_expr,
date_bin_gapfill_index,
date_bin_gapfill_args,
}))
}
fn unwrap_alias(mut e: &Expr) -> &Expr {
loop {
match e {
Expr::Alias(Alias { expr, .. }) => e = expr.as_ref(),
e => break e,
}
}
}
struct DateBinGapfillRewriter {
args: Option<Vec<Expr>>,
}
impl TreeNodeRewriter for DateBinGapfillRewriter {
type N = Expr;
fn pre_visit(&mut self, expr: &Expr) -> Result<RewriteRecursion> {
match expr {
Expr::ScalarUDF(ScalarUDF { fun, .. }) if fun.name == DATE_BIN_GAPFILL_UDF_NAME => {
Ok(RewriteRecursion::Mutate)
}
_ => Ok(RewriteRecursion::Continue),
}
}
fn mutate(&mut self, expr: Expr) -> Result<Expr> {
// We need to preserve the name of the original expression
// so that everything stays wired up.
let orig_name = expr.display_name()?;
match expr {
Expr::ScalarUDF(ScalarUDF { fun, args }) if fun.name == DATE_BIN_GAPFILL_UDF_NAME => {
self.args = Some(args.clone());
Ok(Expr::ScalarFunction(ScalarFunction {
fun: BuiltinScalarFunction::DateBin,
args,
})
.alias(orig_name))
}
_ => Ok(expr),
}
}
}
fn udf_to_fill_strategy(name: &str) -> Option<FillStrategy> {
match name {
LOCF_UDF_NAME => Some(FillStrategy::PrevNullAsMissing),
INTERPOLATE_UDF_NAME => Some(FillStrategy::LinearInterpolate),
_ => None,
}
}
fn fill_strategy_to_udf(fs: &FillStrategy) -> Result<&'static str> {
match fs {
FillStrategy::PrevNullAsMissing => Ok(LOCF_UDF_NAME),
FillStrategy::LinearInterpolate => Ok(INTERPOLATE_UDF_NAME),
_ => Err(DataFusionError::Internal(format!(
"unknown UDF for fill strategy {fs:?}"
))),
}
}
fn handle_projection(proj: &Projection) -> Result<Option<LogicalPlan>> {
let Projection {
input,
expr: proj_exprs,
schema: proj_schema,
..
} = proj;
let Some(child_gapfill) = (match input.as_ref() {
LogicalPlan::Extension(Extension { node }) => node.as_any().downcast_ref::<GapFill>(),
_ => None,
}) else {
// If this is not a projection that is a parent to a GapFill node,
// then there is nothing to do.
return Ok(None)
};
let mut fill_fn_rewriter = FillFnRewriter {
aggr_col_fill_map: HashMap::new(),
};
let new_proj_exprs = proj_exprs
.iter()
.map(|e| e.clone().rewrite(&mut fill_fn_rewriter))
.collect::<Result<Vec<Expr>>>()?;
let FillFnRewriter { aggr_col_fill_map } = fill_fn_rewriter;
if aggr_col_fill_map.is_empty() {
return Ok(None);
}
// Clone the existing GapFill node, then modify it in place
// to reflect the new fill strategy.
let mut new_gapfill = child_gapfill.clone();
for (e, fs) in aggr_col_fill_map {
let udf = fill_strategy_to_udf(&fs)?;
if new_gapfill.replace_fill_strategy(&e, fs).is_none() {
// There was a gap filling function called on a non-aggregate column.
return Err(DataFusionError::Plan(format!(
"{udf} must be called on an aggregate column in a gap-filling query",
)));
}
}
let new_proj = {
let mut proj = proj.clone();
proj.expr = new_proj_exprs;
proj.input = Arc::new(LogicalPlan::Extension(Extension {
node: Arc::new(new_gapfill),
}));
proj.schema = Arc::clone(proj_schema);
LogicalPlan::Projection(proj)
};
Ok(Some(new_proj))
}
/// Implements `TreeNodeRewriter`:
/// - Traverses over the expressions in a projection node
/// - If it finds `locf(col)` or `interpolate(col)`,
/// it replaces them with `col AS <original name>`
/// - Collects into [`Self::aggr_col_fill_map`] which correlates
/// aggregate columns to their [`FillStrategy`].
struct FillFnRewriter {
aggr_col_fill_map: HashMap<Expr, FillStrategy>,
}
impl TreeNodeRewriter for FillFnRewriter {
type N = Expr;
fn pre_visit(&mut self, expr: &Expr) -> Result<RewriteRecursion> {
match expr {
Expr::ScalarUDF(ScalarUDF { fun, .. }) if udf_to_fill_strategy(&fun.name).is_some() => {
Ok(RewriteRecursion::Mutate)
}
_ => Ok(RewriteRecursion::Continue),
}
}
fn mutate(&mut self, expr: Expr) -> Result<Expr> {
let orig_name = expr.display_name()?;
match expr {
Expr::ScalarUDF(ScalarUDF { ref fun, .. })
if udf_to_fill_strategy(&fun.name).is_none() =>
{
Ok(expr)
}
Expr::ScalarUDF(ScalarUDF { fun, mut args }) => {
let fs = udf_to_fill_strategy(&fun.name).expect("must be a fill fn");
let arg = args.remove(0);
self.add_fill_strategy(arg.clone(), fs)?;
Ok(arg.alias(orig_name))
}
_ => Ok(expr),
}
}
}
impl FillFnRewriter {
fn add_fill_strategy(&mut self, e: Expr, fs: FillStrategy) -> Result<()> {
match self.aggr_col_fill_map.entry(e) {
hash_map::Entry::Occupied(_) => Err(DataFusionError::NotImplemented(
"multiple fill strategies for the same column".to_string(),
)),
hash_map::Entry::Vacant(ve) => {
ve.insert(fs);
Ok(())
}
}
}
}
fn count_udf(e: &Expr, name: &str) -> Result<usize> {
let mut count = 0;
e.apply(&mut |expr| {
if matches_udf(expr, name) {
count += 1;
}
Ok(VisitRecursion::Continue)
})?;
Ok(count)
}
fn matches_udf(e: &Expr, name: &str) -> bool {
matches!(
e,
Expr::ScalarUDF(ScalarUDF { fun, .. }) if fun.name == name
)
}
fn check_node(node: &LogicalPlan) -> Result<()> {
node.expressions().iter().try_for_each(|expr| {
let dbg_count = count_udf(expr, DATE_BIN_GAPFILL_UDF_NAME)?;
if dbg_count > 0 {
return Err(DataFusionError::Plan(format!(
"{DATE_BIN_GAPFILL_UDF_NAME} may only be used as a GROUP BY expression"
)));
}
for fn_name in [LOCF_UDF_NAME, INTERPOLATE_UDF_NAME] {
if count_udf(expr, fn_name)? > 0 {
return Err(DataFusionError::Plan(format!(
"{fn_name} may only be used in the SELECT list of a gap-filling query"
)));
}
}
Ok(())
})
}
#[cfg(test)]
mod test {
use std::sync::Arc;
use super::HandleGapFill;
use arrow::datatypes::{DataType, Field, Schema, TimeUnit};
use datafusion::error::Result;
use datafusion::logical_expr::expr::ScalarUDF;
use datafusion::logical_expr::{logical_plan, LogicalPlan, LogicalPlanBuilder};
use datafusion::optimizer::optimizer::Optimizer;
use datafusion::optimizer::OptimizerContext;
use datafusion::prelude::{avg, case, col, lit, lit_timestamp_nano, min, Expr};
use datafusion::scalar::ScalarValue;
use query_functions::gapfill::{
DATE_BIN_GAPFILL_UDF_NAME, INTERPOLATE_UDF_NAME, LOCF_UDF_NAME,
};
fn table_scan() -> Result<LogicalPlan> {
let schema = Schema::new(vec![
Field::new(
"time",
DataType::Timestamp(TimeUnit::Nanosecond, None),
false,
),
Field::new(
"time2",
DataType::Timestamp(TimeUnit::Nanosecond, None),
false,
),
Field::new("loc", DataType::Utf8, false),
Field::new("temp", DataType::Float64, false),
]);
logical_plan::table_scan(Some("temps"), &schema, None)?.build()
}
fn date_bin_gapfill(interval: Expr, time: Expr) -> Result<Expr> {
date_bin_gapfill_with_origin(interval, time, None)
}
fn date_bin_gapfill_with_origin(
interval: Expr,
time: Expr,
origin: Option<Expr>,
) -> Result<Expr> {
let mut args = vec![interval, time];
if let Some(origin) = origin {
args.push(origin)
}
Ok(Expr::ScalarUDF(ScalarUDF {
fun: query_functions::registry().udf(DATE_BIN_GAPFILL_UDF_NAME)?,
args,
}))
}
fn locf(arg: Expr) -> Result<Expr> {
Ok(Expr::ScalarUDF(ScalarUDF {
fun: query_functions::registry().udf(LOCF_UDF_NAME)?,
args: vec![arg],
}))
}
fn interpolate(arg: Expr) -> Result<Expr> {
Ok(Expr::ScalarUDF(ScalarUDF {
fun: query_functions::registry().udf(INTERPOLATE_UDF_NAME)?,
args: vec![arg],
}))
}
fn optimize(plan: &LogicalPlan) -> Result<Option<LogicalPlan>> {
let optimizer = Optimizer::with_rules(vec![Arc::new(HandleGapFill)]);
optimizer.optimize_recursively(
optimizer.rules.get(0).unwrap(),
plan,
&OptimizerContext::new(),
)
}
fn assert_optimizer_err(plan: &LogicalPlan, expected: &str) {
match optimize(plan) {
Ok(plan) => assert_eq!(format!("{}", plan.unwrap().display_indent()), "an error"),
Err(ref e) => {
let actual = e.to_string();
if expected.is_empty() || !actual.contains(expected) {
assert_eq!(actual, expected)
}
}
}
}
fn assert_optimization_skipped(plan: &LogicalPlan) -> Result<()> {
let new_plan = optimize(plan)?;
if new_plan.is_none() {
return Ok(());
}
assert_eq!(
format!("{}", plan.display_indent()),
format!("{}", new_plan.unwrap().display_indent())
);
Ok(())
}
fn format_optimized_plan(plan: &LogicalPlan) -> Result<Vec<String>> {
let plan = optimize(plan)?
.expect("plan should have been optimized")
.display_indent()
.to_string();
Ok(plan.split('\n').map(|s| s.to_string()).collect())
}
#[test]
fn misplaced_dbg_err() -> Result<()> {
// date_bin_gapfill used in a filter should produce an error
let scan = table_scan()?;
let plan = LogicalPlanBuilder::from(scan)
.filter(
date_bin_gapfill(
lit(ScalarValue::IntervalDayTime(Some(600_000))),
col("temp"),
)?
.gt(lit(100.0)),
)?
.build()?;
assert_optimizer_err(
&plan,
"Error during planning: date_bin_gapfill may only be used as a GROUP BY expression",
);
Ok(())
}
/// calling LOCF in a WHERE predicate is not valid
#[test]
fn misplaced_locf_err() -> Result<()> {
// date_bin_gapfill used in a filter should produce an error
let scan = table_scan()?;
let plan = LogicalPlanBuilder::from(scan)
.filter(locf(col("temp"))?.gt(lit(100.0)))?
.build()?;
assert_optimizer_err(
&plan,
"Error during planning: locf may only be used in the SELECT list of a gap-filling query",
);
Ok(())
}
/// calling INTERPOLATE in a WHERE predicate is not valid
#[test]
fn misplaced_interpolate_err() -> Result<()> {
// date_bin_gapfill used in a filter should produce an error
let scan = table_scan()?;
let plan = LogicalPlanBuilder::from(scan)
.filter(interpolate(col("temp"))?.gt(lit(100.0)))?
.build()?;
assert_optimizer_err(
&plan,
"Error during planning: interpolate may only be used in the SELECT list of a gap-filling query",
);
Ok(())
}
/// calling LOCF on the SELECT list but not on an aggregate column is not valid.
#[test]
fn misplaced_locf_non_agg_err() -> Result<()> {
let plan = LogicalPlanBuilder::from(table_scan()?)
.filter(
col("time")
.gt_eq(lit_timestamp_nano(1000))
.and(col("time").lt(lit_timestamp_nano(2000))),
)?
.aggregate(
vec![
col("loc"),
date_bin_gapfill(lit(ScalarValue::IntervalDayTime(Some(60_000))), col("time"))?,
],
vec![avg(col("temp")), min(col("temp"))],
)?
.project(vec![
locf(col("loc"))?,
col("date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time)"),
locf(col("AVG(temps.temp)"))?,
locf(col("MIN(temps.temp)"))?,
])?
.build()?;
assert_optimizer_err(
&plan,
"locf must be called on an aggregate column in a gap-filling query",
);
Ok(())
}
#[test]
fn different_fill_strategies_one_col() -> Result<()> {
let plan = LogicalPlanBuilder::from(table_scan()?)
.filter(
col("time")
.gt_eq(lit_timestamp_nano(1000))
.and(col("time").lt(lit_timestamp_nano(2000))),
)?
.aggregate(
vec![
col("loc"),
date_bin_gapfill(lit(ScalarValue::IntervalDayTime(Some(60_000))), col("time"))?,
],
vec![avg(col("temp")), min(col("temp"))],
)?
.project(vec![
locf(col("loc"))?,
col("date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time)"),
locf(col("AVG(temps.temp)"))?,
interpolate(col("AVG(temps.temp)"))?,
])?
.build()?;
assert_optimizer_err(
&plan,
"This feature is not implemented: multiple fill strategies for the same column",
);
Ok(())
}
#[test]
fn nonscalar_origin() -> Result<()> {
let plan = LogicalPlanBuilder::from(table_scan()?)
.filter(
col("time")
.gt_eq(lit_timestamp_nano(1000))
.and(col("time").lt(lit_timestamp_nano(2000))),
)?
.aggregate(
vec![date_bin_gapfill_with_origin(
lit(ScalarValue::IntervalDayTime(Some(60_000))),
col("time"),
Some(col("time2")),
)?],
vec![avg(col("temp"))],
)?
.build()?;
assert_optimizer_err(
&plan,
"Error during planning: origin argument to DATE_BIN_GAPFILL for gap fill query must evaluate to a scalar",
);
Ok(())
}
#[test]
fn nonscalar_stride() -> Result<()> {
let stride = case(col("loc"))
.when(
lit("kitchen"),
lit(ScalarValue::IntervalDayTime(Some(60_000))),
)
.otherwise(lit(ScalarValue::IntervalDayTime(Some(30_000))))
.unwrap();
let plan = LogicalPlanBuilder::from(table_scan()?)
.filter(
col("time")
.gt_eq(lit_timestamp_nano(1000))
.and(col("time").lt(lit_timestamp_nano(2000))),
)?
.aggregate(
vec![date_bin_gapfill(stride, col("time"))?],
vec![avg(col("temp"))],
)?
.build()?;
assert_optimizer_err(
&plan,
"Error during planning: stride argument to DATE_BIN_GAPFILL for gap fill query must evaluate to a scalar",
);
Ok(())
}
#[test]
fn time_range_errs() -> Result<()> {
let cases = vec![
(
lit(true),
"Error during planning: gap-filling query is missing both upper and lower time bounds",
),
(
col("time").gt_eq(lit_timestamp_nano(1000)),
"Error during planning: gap-filling query is missing upper time bound",
),
(
col("time").lt(lit_timestamp_nano(2000)),
"Error during planning: gap-filling query is missing lower time bound",
),
(
col("time").gt_eq(col("time2")).and(
col("time").lt(lit_timestamp_nano(2000))),
"Error during planning: lower time bound for gap fill query must evaluate to a scalar",
),
(
col("time").gt_eq(lit_timestamp_nano(2000)).and(
col("time").lt(col("time2"))),
"Error during planning: upper time bound for gap fill query must evaluate to a scalar",
)
];
for c in cases {
let plan = LogicalPlanBuilder::from(table_scan()?)
.filter(c.0)?
.aggregate(
vec![date_bin_gapfill(
lit(ScalarValue::IntervalDayTime(Some(60_000))),
col("time"),
)?],
vec![avg(col("temp"))],
)?
.build()?;
assert_optimizer_err(&plan, c.1);
}
Ok(())
}
#[test]
fn no_change() -> Result<()> {
let plan = LogicalPlanBuilder::from(table_scan()?)
.aggregate(vec![col("loc")], vec![avg(col("temp"))])?
.build()?;
assert_optimization_skipped(&plan)?;
Ok(())
}
#[test]
fn date_bin_gapfill_simple() -> Result<()> {
let plan = LogicalPlanBuilder::from(table_scan()?)
.filter(
col("time")
.gt_eq(lit_timestamp_nano(1000))
.and(col("time").lt(lit_timestamp_nano(2000))),
)?
.aggregate(
vec![date_bin_gapfill(
lit(ScalarValue::IntervalDayTime(Some(60_000))),
col("time"),
)?],
vec![avg(col("temp"))],
)?
.build()?;
insta::assert_yaml_snapshot!(
format_optimized_plan(&plan)?,
@r###"
---
- "GapFill: groupBy=[date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time)], aggr=[[AVG(temps.temp)]], time_column=date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time), stride=IntervalDayTime(\"60000\"), range=Included(Literal(TimestampNanosecond(1000, None)))..Excluded(Literal(TimestampNanosecond(2000, None)))"
- " Aggregate: groupBy=[[date_bin(IntervalDayTime(\"60000\"), temps.time) AS date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time)]], aggr=[[AVG(temps.temp)]]"
- " Filter: temps.time >= TimestampNanosecond(1000, None) AND temps.time < TimestampNanosecond(2000, None)"
- " TableScan: temps"
"###);
Ok(())
}
#[test]
fn date_bin_gapfill_origin() -> Result<()> {
let plan = LogicalPlanBuilder::from(table_scan()?)
.filter(
col("time")
.gt_eq(lit_timestamp_nano(1000))
.and(col("time").lt(lit_timestamp_nano(2000))),
)?
.aggregate(
vec![date_bin_gapfill_with_origin(
lit(ScalarValue::IntervalDayTime(Some(60_000))),
col("time"),
Some(lit_timestamp_nano(7)),
)?],
vec![avg(col("temp"))],
)?
.build()?;
insta::assert_yaml_snapshot!(
format_optimized_plan(&plan)?,
@r###"
---
- "GapFill: groupBy=[date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time,TimestampNanosecond(7, None))], aggr=[[AVG(temps.temp)]], time_column=date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time,TimestampNanosecond(7, None)), stride=IntervalDayTime(\"60000\"), range=Included(Literal(TimestampNanosecond(1000, None)))..Excluded(Literal(TimestampNanosecond(2000, None)))"
- " Aggregate: groupBy=[[date_bin(IntervalDayTime(\"60000\"), temps.time, TimestampNanosecond(7, None)) AS date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time,TimestampNanosecond(7, None))]], aggr=[[AVG(temps.temp)]]"
- " Filter: temps.time >= TimestampNanosecond(1000, None) AND temps.time < TimestampNanosecond(2000, None)"
- " TableScan: temps"
"###);
Ok(())
}
#[test]
fn two_group_exprs() -> Result<()> {
// grouping by date_bin_gapfill(...), loc
let plan = LogicalPlanBuilder::from(table_scan()?)
.filter(
col("time")
.gt_eq(lit_timestamp_nano(1000))
.and(col("time").lt(lit_timestamp_nano(2000))),
)?
.aggregate(
vec![
date_bin_gapfill(lit(ScalarValue::IntervalDayTime(Some(60_000))), col("time"))?,
col("loc"),
],
vec![avg(col("temp"))],
)?
.build()?;
insta::assert_yaml_snapshot!(
format_optimized_plan(&plan)?,
@r###"
---
- "GapFill: groupBy=[date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time), temps.loc], aggr=[[AVG(temps.temp)]], time_column=date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time), stride=IntervalDayTime(\"60000\"), range=Included(Literal(TimestampNanosecond(1000, None)))..Excluded(Literal(TimestampNanosecond(2000, None)))"
- " Aggregate: groupBy=[[date_bin(IntervalDayTime(\"60000\"), temps.time) AS date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time), temps.loc]], aggr=[[AVG(temps.temp)]]"
- " Filter: temps.time >= TimestampNanosecond(1000, None) AND temps.time < TimestampNanosecond(2000, None)"
- " TableScan: temps"
"###);
Ok(())
}
#[test]
fn double_date_bin_gapfill() -> Result<()> {
let plan = LogicalPlanBuilder::from(table_scan()?)
.aggregate(
vec![
date_bin_gapfill(lit(ScalarValue::IntervalDayTime(Some(60_000))), col("time"))?,
date_bin_gapfill(lit(ScalarValue::IntervalDayTime(Some(30_000))), col("time"))?,
],
vec![avg(col("temp"))],
)?
.build()?;
assert_optimizer_err(
&plan,
"Error during planning: DATE_BIN_GAPFILL specified more than once",
);
Ok(())
}
#[test]
fn with_projection() -> Result<()> {
let plan = LogicalPlanBuilder::from(table_scan()?)
.filter(
col("time")
.gt_eq(lit_timestamp_nano(1000))
.and(col("time").lt(lit_timestamp_nano(2000))),
)?
.aggregate(
vec![date_bin_gapfill(
lit(ScalarValue::IntervalDayTime(Some(60_000))),
col("time"),
)?],
vec![avg(col("temp"))],
)?
.project(vec![
col("date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time)"),
col("AVG(temps.temp)"),
])?
.build()?;
insta::assert_yaml_snapshot!(
format_optimized_plan(&plan)?,
@r###"
---
- "Projection: date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time), AVG(temps.temp)"
- " GapFill: groupBy=[date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time)], aggr=[[AVG(temps.temp)]], time_column=date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time), stride=IntervalDayTime(\"60000\"), range=Included(Literal(TimestampNanosecond(1000, None)))..Excluded(Literal(TimestampNanosecond(2000, None)))"
- " Aggregate: groupBy=[[date_bin(IntervalDayTime(\"60000\"), temps.time) AS date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time)]], aggr=[[AVG(temps.temp)]]"
- " Filter: temps.time >= TimestampNanosecond(1000, None) AND temps.time < TimestampNanosecond(2000, None)"
- " TableScan: temps"
"###);
Ok(())
}
#[test]
fn with_locf() -> Result<()> {
let plan = LogicalPlanBuilder::from(table_scan()?)
.filter(
col("time")
.gt_eq(lit_timestamp_nano(1000))
.and(col("time").lt(lit_timestamp_nano(2000))),
)?
.aggregate(
vec![date_bin_gapfill(
lit(ScalarValue::IntervalDayTime(Some(60_000))),
col("time"),
)?],
vec![avg(col("temp")), min(col("temp"))],
)?
.project(vec![
col("date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time)"),
locf(col("AVG(temps.temp)"))?,
locf(col("MIN(temps.temp)"))?,
])?
.build()?;
insta::assert_yaml_snapshot!(
format_optimized_plan(&plan)?,
@r###"
---
- "Projection: date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time), AVG(temps.temp) AS locf(AVG(temps.temp)), MIN(temps.temp) AS locf(MIN(temps.temp))"
- " GapFill: groupBy=[date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time)], aggr=[[LOCF(AVG(temps.temp)), LOCF(MIN(temps.temp))]], time_column=date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time), stride=IntervalDayTime(\"60000\"), range=Included(Literal(TimestampNanosecond(1000, None)))..Excluded(Literal(TimestampNanosecond(2000, None)))"
- " Aggregate: groupBy=[[date_bin(IntervalDayTime(\"60000\"), temps.time) AS date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time)]], aggr=[[AVG(temps.temp), MIN(temps.temp)]]"
- " Filter: temps.time >= TimestampNanosecond(1000, None) AND temps.time < TimestampNanosecond(2000, None)"
- " TableScan: temps"
"###);
Ok(())
}
#[test]
fn with_locf_aliased() -> Result<()> {
let plan = LogicalPlanBuilder::from(table_scan()?)
.filter(
col("time")
.gt_eq(lit_timestamp_nano(1000))
.and(col("time").lt(lit_timestamp_nano(2000))),
)?
.aggregate(
vec![date_bin_gapfill(
lit(ScalarValue::IntervalDayTime(Some(60_000))),
col("time"),
)?],
vec![avg(col("temp")), min(col("temp"))],
)?
.project(vec![
col("date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time)"),
locf(col("MIN(temps.temp)"))?.alias("locf_min_temp"),
])?
.build()?;
insta::assert_yaml_snapshot!(
format_optimized_plan(&plan)?,
@r###"
---
- "Projection: date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time), MIN(temps.temp) AS locf(MIN(temps.temp)) AS locf_min_temp"
- " GapFill: groupBy=[date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time)], aggr=[[AVG(temps.temp), LOCF(MIN(temps.temp))]], time_column=date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time), stride=IntervalDayTime(\"60000\"), range=Included(Literal(TimestampNanosecond(1000, None)))..Excluded(Literal(TimestampNanosecond(2000, None)))"
- " Aggregate: groupBy=[[date_bin(IntervalDayTime(\"60000\"), temps.time) AS date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time)]], aggr=[[AVG(temps.temp), MIN(temps.temp)]]"
- " Filter: temps.time >= TimestampNanosecond(1000, None) AND temps.time < TimestampNanosecond(2000, None)"
- " TableScan: temps"
"###);
Ok(())
}
#[test]
fn with_interpolate() -> Result<()> {
let plan = LogicalPlanBuilder::from(table_scan()?)
.filter(
col("time")
.gt_eq(lit_timestamp_nano(1000))
.and(col("time").lt(lit_timestamp_nano(2000))),
)?
.aggregate(
vec![date_bin_gapfill(
lit(ScalarValue::IntervalDayTime(Some(60_000))),
col("time"),
)?],
vec![avg(col("temp")), min(col("temp"))],
)?
.project(vec![
col("date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time)"),
interpolate(col("AVG(temps.temp)"))?,
interpolate(col("MIN(temps.temp)"))?,
])?
.build()?;
insta::assert_yaml_snapshot!(
format_optimized_plan(&plan)?,
@r###"
---
- "Projection: date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time), AVG(temps.temp) AS interpolate(AVG(temps.temp)), MIN(temps.temp) AS interpolate(MIN(temps.temp))"
- " GapFill: groupBy=[date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time)], aggr=[[INTERPOLATE(AVG(temps.temp)), INTERPOLATE(MIN(temps.temp))]], time_column=date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time), stride=IntervalDayTime(\"60000\"), range=Included(Literal(TimestampNanosecond(1000, None)))..Excluded(Literal(TimestampNanosecond(2000, None)))"
- " Aggregate: groupBy=[[date_bin(IntervalDayTime(\"60000\"), temps.time) AS date_bin_gapfill(IntervalDayTime(\"60000\"),temps.time)]], aggr=[[AVG(temps.temp), MIN(temps.temp)]]"
- " Filter: temps.time >= TimestampNanosecond(1000, None) AND temps.time < TimestampNanosecond(2000, None)"
- " TableScan: temps"
"###);
Ok(())
}
}
|
pub mod percentages;
pub mod tsa;
mod util;
|
//! Place limit orders
// TODO: is a sign that things need some restructuring
pub(crate) mod blockchain;
mod request;
mod response;
mod types;
pub use types::{LimitOrderRequest, LimitOrderResponse};
|
use std::fs::File;
use std::io::{BufRead, BufReader};
pub fn run_puzzle() {
let file = File::open("input_day1.txt").expect("Failed to open input_day1.txt");
let br = BufReader::new(file);
let vec: Vec<i64> = br.lines().map(|line| line.expect("Line parsing failed").parse::<i64>().expect("Line => i64 failed")).collect();
let mut total_fuel = 0;
for v in &vec {
let mut fuel_input = v.clone();
loop {
fuel_input = if (fuel_input / 3) - 2 < 0 { 0 } else { (fuel_input / 3) - 2 };
if fuel_input == 0 {
break;
}
total_fuel += fuel_input;
}
}
println!("Total : {}", total_fuel);
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_exception::Result;
use common_expression::TableSchemaRef;
use common_meta_app::principal::StageInfo;
use common_pipeline_core::Pipeline;
use common_settings::Settings;
use common_storage::StageFileInfo;
use opendal::Operator;
use crate::input_formats::InputContext;
use crate::input_formats::SplitInfo;
#[async_trait::async_trait]
pub trait InputFormat: Send + Sync {
async fn get_splits(
&self,
file_infos: Vec<StageFileInfo>,
stage_info: &StageInfo,
op: &Operator,
settings: &Arc<Settings>,
) -> Result<Vec<Arc<SplitInfo>>>;
async fn infer_schema(&self, path: &str, op: &Operator) -> Result<TableSchemaRef>;
fn exec_copy(&self, ctx: Arc<InputContext>, pipeline: &mut Pipeline) -> Result<()>;
fn exec_stream(&self, ctx: Arc<InputContext>, pipeline: &mut Pipeline) -> Result<()>;
}
|
use super::*;
#[test]
fn with_number_atom_reference_function_port_pid_or_tuple_second_returns_first() {
run!(
|arc_process| {
(
strategy::term::map(arc_process.clone()),
strategy::term::number_atom_reference_function_port_pid_or_tuple(arc_process),
)
},
|(first, second)| {
prop_assert_eq!(result(first, second), first);
Ok(())
},
);
}
#[test]
fn with_smaller_map_second_returns_first() {
max(
|_, process| process.map_from_slice(&[(Atom::str_to_term("a"), process.integer(1))]),
First,
);
}
#[test]
fn with_same_size_map_with_lesser_keys_returns_first() {
max(
|_, process| {
process.map_from_slice(&[
(Atom::str_to_term("a"), process.integer(2)),
(Atom::str_to_term("b"), process.integer(3)),
])
},
First,
);
}
#[test]
fn with_same_size_map_with_same_keys_with_lesser_values_returns_first() {
max(
|_, process| {
process.map_from_slice(&[
(Atom::str_to_term("b"), process.integer(2)),
(Atom::str_to_term("c"), process.integer(2)),
])
},
First,
);
}
#[test]
fn with_same_map_returns_first() {
max(|first, _| first, First);
}
#[test]
fn with_same_value_map_returns_first() {
max(
|_, process| {
process.map_from_slice(&[
(Atom::str_to_term("b"), process.integer(2)),
(Atom::str_to_term("c"), process.integer(3)),
])
},
First,
);
}
#[test]
fn with_same_size_map_with_same_keys_with_greater_values_returns_second() {
max(
|_, process| {
process.map_from_slice(&[
(Atom::str_to_term("b"), process.integer(3)),
(Atom::str_to_term("c"), process.integer(4)),
])
},
Second,
);
}
#[test]
fn with_same_size_map_with_greater_keys_returns_second() {
max(
|_, process| {
process.map_from_slice(&[
(Atom::str_to_term("c"), process.integer(2)),
(Atom::str_to_term("d"), process.integer(3)),
])
},
Second,
);
}
#[test]
fn with_greater_size_map_returns_second() {
max(
|_, process| {
process.map_from_slice(&[
(Atom::str_to_term("a"), process.integer(1)),
(Atom::str_to_term("b"), process.integer(2)),
(Atom::str_to_term("c"), process.integer(3)),
])
},
Second,
);
}
#[test]
fn with_map_second_returns_first() {
max(|_, process| process.map_from_slice(&[]), First);
}
#[test]
fn with_list_or_bitstring_second_returns_second() {
run!(
|arc_process| {
(
strategy::term::map(arc_process.clone()),
strategy::term::list_or_bitstring(arc_process.clone()),
)
},
|(first, second)| {
prop_assert_eq!(result(first, second), second);
Ok(())
},
);
}
fn max<R>(second: R, which: FirstSecond)
where
R: FnOnce(Term, &Process) -> Term,
{
super::max(
|process| {
process.map_from_slice(&[
(Atom::str_to_term("b"), process.integer(2)),
(Atom::str_to_term("c"), process.integer(3)),
])
},
second,
which,
);
}
|
table! {
d_domain (id) {
id -> Int4,
user_id -> Int4,
hash -> Varchar,
domain -> Varchar,
flag -> Int2,
state -> Int2,
notes -> Varchar,
create_time -> Int4,
}
}
table! {
u_user (id) {
id -> Int4,
user -> Varchar,
name -> Varchar,
pwd -> Varchar,
flag -> Int2,
email -> Varchar,
create_time -> Int4,
}
}
allow_tables_to_appear_in_same_query!(d_domain, u_user,);
|
use crate::day_twenty::run_day_twenty;
mod file_util;
mod day_one;
mod day_two;
mod day_three;
mod day_four;
mod day_five;
mod day_six;
mod day_seven;
mod day_eight;
mod day_nine;
mod day_ten;
mod day_eleven;
mod day_twelve;
mod day_thirteen;
mod day_fourteen;
mod day_fifteen;
mod day_sixteen;
mod day_seventeen;
mod day_eighteen;
mod day_nineteen;
mod day_twenty;
fn main() {
run_day_twenty()
}
|
use crate::errors::ServiceError;
use crate::models::msg::Msg;
use crate::schema::fcm;
use actix::Message;
use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};
#[derive(
Clone,
Debug,
Serialize,
Associations,
Deserialize,
PartialEq,
Identifiable,
Queryable,
Insertable,
)]
#[table_name = "fcm"]
pub struct Fcm {
pub id: i32,
pub to: String,
pub order_id: i32,
pub order_detail_id: i32,
pub shop_notification_id: i32,
pub order_detail_state: i32,
pub trigger: String,
pub req: serde_json::Value,
pub resp: serde_json::Value,
pub created_at: NaiveDateTime,
pub updated_at: Option<NaiveDateTime>,
pub deleted_at: Option<NaiveDateTime>,
}
#[derive(Deserialize, Serialize, Debug, Message, Insertable)]
#[rtype(result = "Result<Msg, ServiceError>")]
#[table_name = "fcm"]
pub struct New {
pub to: String,
pub order_id: i32,
pub order_detail_id: i32,
pub shop_notification_id: i32,
pub order_detail_state: i32,
pub trigger: String,
pub req: serde_json::Value,
pub resp: serde_json::Value,
}
/*
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ToFcmResp {
pub notification_key: String,
}
impl ToFcmResp {
pub fn new(&self, order_id: i32) -> New {
New {
order_id: order_id,
resp: serde_json::to_value(&self).unwrap(),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Params {
pub operation: String,
pub notification_key_name: String,
pub notification_key: String,
pub registration_ids: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ParamsToFcm {
pub url: String,
pub order_id: i32,
pub webpush: WebPush,
pub params: Params,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ParamsToUser {
pub url: String,
pub order_id: i32,
pub webpush: WebPush,
pub params: ParamsNotification,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ParamsNotification {
pub notification: Notification,
pub to: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Notification {
pub title: String,
pub body: String,
pub icon: String,
pub click_action: String,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ToUserResp {
pub success: i32,
pub failure: i32,
}
impl ToUserResp {
pub fn new(&self, order_id: i32) -> New {
New {
order_id: order_id,
resp: serde_json::to_value(&self).unwrap(),
}
}
}
*/
|
//! mraddr, machine reset address register
read_csr!(0x7E0);
/// Get machine reset address
#[inline]
pub fn read() -> usize {
unsafe { _read() }
}
|
use anyhow::{anyhow, Result};
use std::io::{stdin, Write};
use termion::event::Key;
use termion::{clear, style};
use termion::{cursor, input::TermRead};
use crate::cmd::ValueType;
/// Size of autocomplete window
const AUTOCOMPLETE_ROWS: u16 = 8;
pub trait Choice {
/// Get a reference to the text
fn text(&self) -> &str;
}
impl Choice for String {
fn text(&self) -> &str {
&self
}
}
impl<'a, C> Choice for &'a C
where
C: Choice,
{
fn text(&self) -> &str {
(*self).text()
}
}
pub struct Readline<'s> {
expect_input: Option<ValueType>,
prefix: String,
stdout: &'s mut dyn Write,
help: Option<String>,
scroll_offset: usize,
/// Cursor horizontal position
cursor: usize,
}
enum AutocompleteMode<A> {
/// Enable autocompletion
Enabled {
autocomplete: A,
allow_user_input: bool,
},
/// No completion
None,
}
impl<A> AutocompleteMode<A> {
fn enabled(&self) -> bool {
matches!(self, AutocompleteMode::Enabled { .. })
}
}
impl<'s> Readline<'s> {
pub fn new(stdout: &'s mut dyn Write) -> Self {
Self {
expect_input: None,
prefix: "$".into(),
stdout,
help: None,
scroll_offset: 0,
cursor: 0,
}
}
pub fn prefix(mut self, value: impl Into<String>) -> Self {
self.prefix = value.into();
self
}
pub fn expect(mut self, expect_type: ValueType) -> Self {
self.expect_input = Some(expect_type);
self
}
pub fn help(mut self, value: impl Into<String>) -> Self {
self.help = Some(value.into());
self
}
/// Return a choice from one of the autocomplete options.
/// Returns None if input was interrupted (e.g with ctrl-d).
pub fn choice<'c, C>(
&mut self,
autocomplete: impl AutoComplete<'c, C = C>,
) -> Result<Option<&'c C>>
where
C: Choice,
{
let (choice, _) = self.run(AutocompleteMode::Enabled {
autocomplete,
allow_user_input: false,
})?;
Ok(choice)
}
/// Return a choice from one of the autocomplete options and a user input.
/// This can be used when user is not required to pick an option
/// but instead could provide a custom value.
pub fn suggest<'c, C>(
&mut self,
autocomplete: impl AutoComplete<'c, C = C>,
) -> Result<(Option<&'c C>, String)>
where
C: Choice,
{
self.run(AutocompleteMode::Enabled {
autocomplete,
allow_user_input: true,
})
}
/// Read a single line
pub fn line<'c>(&mut self) -> Result<String> {
let (_, text) = self.run(AutocompleteMode::None::<FixedComplete<'c, String>>)?;
Ok(text)
}
/// Mutates the input based on the keys from stdin. It then returns the key
/// for post processing.
fn read_key(
&mut self,
keys: impl Iterator<Item = std::result::Result<Key, std::io::Error>>,
input: &mut String,
) -> Result<Key> {
for key in keys {
let key = key?;
match key {
Key::Ctrl('c') => {
return Err(anyhow!("Terminated"));
}
Key::Ctrl('u') => {
// Remove chars before the cursor
input.drain(0..self.cursor);
self.cursor = 0;
}
Key::Char('\n') => {}
Key::Char(c) => match &self.expect_input {
Some(expect) if !expect.is_valid_char(c) => {}
_ => {
input.insert(self.cursor, c);
self.cursor += 1;
}
},
Key::Backspace => {
self.cursor = self.cursor.saturating_sub(1);
if self.cursor == 0 {
input.pop();
} else {
input.drain(self.cursor..self.cursor + 1);
}
}
Key::Left => {
self.cursor = self.cursor.saturating_sub(1);
}
Key::Right if self.cursor < input.len() => {
self.cursor += 1;
}
_ => {}
}
return Ok(key);
}
Ok(Key::Char('\n'))
}
fn run<'c, A, C>(
&mut self,
mut autocomplete: AutocompleteMode<A>,
) -> Result<(Option<&'c C>, String)>
where
C: Choice,
A: AutoComplete<'c, C = C>,
{
let mut input = String::new();
let mut selected: usize = 0;
let reserve_rows = {
// User input row
let mut rows = 1;
// Help row above user input
if self.help.is_some() {
rows += 1;
}
// Autocomplete rows
if autocomplete.enabled() {
rows += AUTOCOMPLETE_ROWS;
}
rows
};
let mut choices = vec![];
let mut choices_len = 0;
let mut keys = stdin().keys();
// TODO: in case of error clean up always
let choice = loop {
write!(self.stdout, "{}\r", clear::AfterCursor)?;
// Render autocomplete choices
if let AutocompleteMode::Enabled {
autocomplete,
allow_user_input,
} = &mut autocomplete
{
choices = autocomplete.list(&input);
choices_len = choices.len();
if *allow_user_input && !input.is_empty() {
choices_len += 1;
}
if selected >= choices_len {
selected = choices_len.saturating_sub(1);
}
let mut view_choices: Vec<&str> = choices.iter().map(|c| c.text()).collect();
if *allow_user_input && !input.is_empty() {
view_choices.push(&input);
}
self.render_choices(&view_choices, selected)?;
}
// Display help
if let Some(ref help) = self.help {
write!(self.stdout, "{}\r\n", fmt_text(help))?;
}
// Display user input
write!(self.stdout, "{} {} ", fmt_text(&self.prefix), input,)?;
// Cursor position is 1 based.
let cursor_left = input.len().saturating_sub(self.cursor) + 1;
write!(self.stdout, "{}", cursor::Left(cursor_left as u16))?;
self.stdout.flush()?;
let key = match self.read_key(&mut keys, &mut input) {
Ok(key) => key,
Err(e) => break Err(e),
};
match key {
Key::Char('\n') => {
if let AutocompleteMode::Enabled {
allow_user_input, ..
} = autocomplete
{
let choice = choices.get(selected).cloned();
if allow_user_input {
// It is fine not to have a choice when user can
// input their own value
break Ok(choice);
} else if choice.is_some() {
// Require a choice when running in a strict mode
break Ok(choice);
}
} else if self.expect_input.is_some() && !input.is_empty() {
// When expecting an input require it to be non-empty
break Ok(None);
} else if self.expect_input.is_none() {
// When non expecting an input simply return
break Ok(None);
}
}
Key::Up | Key::Ctrl('j') if selected > 0 => {
selected -= 1;
// If cursor moved outsize of visible window then scroll
if selected < self.scroll_offset {
self.scroll_offset -= 1;
}
}
Key::Down | Key::Ctrl('k') if selected < (choices_len.saturating_sub(1)) => {
selected += 1;
// If cursor moved outsize of visible window then scroll
if selected >= AUTOCOMPLETE_ROWS as usize + self.scroll_offset {
self.scroll_offset += 1;
}
}
Key::Ctrl('d') => {
break Ok(None);
}
_ => {}
}
if reserve_rows > 1 {
write!(self.stdout, "{}\r", cursor::Up(reserve_rows - 1))?;
}
};
if reserve_rows > 1 {
write!(self.stdout, "{}\r", cursor::Up(reserve_rows - 1))?;
}
write!(self.stdout, "{}\r", clear::AfterCursor)?;
self.stdout.flush()?;
let choice = choice?;
Ok((choice, input))
}
fn render_choices(&mut self, choices: &[&str], selected: usize) -> Result<()> {
let total = choices.len();
let size = AUTOCOMPLETE_ROWS - 1;
let empty_rows = (size as isize - total as isize).max(0);
for _ in 0..empty_rows {
write!(self.stdout, "{}\n\r", clear::CurrentLine)?;
}
for (i, choice) in choices
.iter()
.enumerate()
.skip(self.scroll_offset)
.take(size as usize)
{
write!(self.stdout, "{}", clear::CurrentLine)?;
if i == selected {
write!(
self.stdout,
"> {}{}{}",
style::Bold,
fmt_text(choice),
style::Reset
)?;
} else {
write!(self.stdout, " {}", fmt_text(choice))?;
}
write!(self.stdout, "\n\r")?;
}
write!(
self.stdout,
" {}{}/{}{}\n\r",
style::Italic,
selected + 1,
total,
style::NoItalic
)?;
Ok(())
}
}
#[derive(Default)]
struct FmtState {
/// Bold text has started
bold: bool,
/// Underline text has started
underline: bool,
}
pub fn fmt_text(text: impl AsRef<str>) -> String {
let text = text.as_ref();
let mut result = String::new();
let mut state = FmtState::default();
for c in text.chars() {
match c {
'*' => {
if state.bold {
// End bold
// Somehow NoBold doesn't work properly hence using Reset for now
// result.push_str(style::NoBold.as_ref());
result.push_str(style::Reset.as_ref());
} else {
// Start bold
result.push_str(style::Bold.as_ref());
}
state.bold = !state.bold;
}
'_' => {
if state.underline {
// End underline
result.push_str(style::NoUnderline.as_ref());
} else {
// Start underline
result.push_str(style::Underline.as_ref());
}
state.underline = !state.underline;
}
_ => {
result.push(c);
}
}
}
// Clean styles if not closed properly
if state.bold {
// Somehow NoBold doesn't work properly hence using Reset for now
// result.push_str(style::NoBold.as_ref());
result.push_str(style::Reset.as_ref());
}
if state.underline {
result.push_str(style::NoUnderline.as_ref());
}
result
}
pub trait AutoComplete<'c> {
type C: Choice;
fn list(&mut self, input: &str) -> Vec<&'c Self::C>;
}
/// Autocomplete from a fixed set of options
pub struct FixedComplete<'c, C> {
options: &'c Vec<C>,
}
impl<'c, C> FixedComplete<'c, C>
where
C: Choice,
{
pub fn new(options: &'c Vec<C>) -> Self {
Self { options }
}
}
impl<'c, C> AutoComplete<'c> for FixedComplete<'c, C>
where
C: Choice,
{
type C = C;
fn list(&mut self, input: &str) -> Vec<&'c C> {
self.options
.iter()
.filter(|o| o.text().to_lowercase().contains(&input.to_lowercase()))
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fmt_text_ok() {
assert_eq!(
format!(
"Hello {}UNDERLINE{} and {}bold{}",
style::Underline,
style::NoUnderline,
style::Bold,
style::Reset
),
fmt_text("Hello _UNDERLINE_ and *bold*")
);
assert_eq!(
format!("inline={}underline{}", style::Underline, style::NoUnderline),
fmt_text("inline=_underline_")
);
}
}
|
extern crate proconio;
use proconio::input;
use proconio::marker::Chars;
fn main() {
input! {
(R, C): (usize, usize),
(sy, sx): (usize, usize),
(gy, gx): (usize, usize),
a: [Chars; R],
}
let (sy, sx) = (sy - 1, sx - 1);
let (gy, gx) = (gy - 1, gx - 1);
let mut d = vec![vec![-1; C]; R];
let dydx = [(-1, 0), (0, -1), (1, 0), (0, 1)];
let mut q = std::collections::VecDeque::new();
d[sy][sx] = 0;
q.push_back((sy, sx));
while let Some((y, x)) = q.pop_front() {
for (ny, nx) in Adjacent::new((y, x), R, C, dydx.iter().copied()) {
if a[ny][nx] == '.' && d[ny][nx] == -1 {
d[ny][nx] = d[y][x] + 1;
q.push_back((ny, nx));
}
}
}
println!("{}", d[gy][gx]);
}
pub struct Adjacent<I> {
position: (usize, usize),
h: usize,
w: usize,
direction: I,
}
impl<I> Adjacent<I>
where
I: Iterator<Item = (isize, isize)>,
{
pub fn new(position: (usize, usize), h: usize, w: usize, direction: I) -> Self {
Self {
position,
h,
w,
direction,
}
}
}
impl<I> Iterator for Adjacent<I>
where
I: Iterator<Item = (isize, isize)>,
{
type Item = (usize, usize);
fn next(&mut self) -> Option<(usize, usize)> {
while let Some((di, dj)) = self.direction.next() {
let (i, j) = self.position;
let ni = i as isize + di;
let nj = j as isize + dj;
if 0 <= ni && ni < self.h as isize && 0 <= nj && nj < self.w as isize {
return Some((ni as usize, nj as usize));
}
}
None
}
}
|
use super::*;
pub fn gen_ntstatus() -> TokenStream {
quote! {
#[repr(transparent)]
#[derive(::core::default::Default, ::core::clone::Clone, ::core::marker::Copy, ::core::cmp::PartialEq, ::core::cmp::Eq, ::core::fmt::Debug)]
pub struct NTSTATUS(pub u32);
impl NTSTATUS {
#[inline]
pub const fn is_ok(self) -> bool {
self.0 & 0x8000_0000 == 0
}
#[inline]
pub const fn is_err(self) -> bool {
!self.is_ok()
}
#[inline]
pub const fn to_hresult(self) -> ::windows::core::HRESULT {
::windows::core::HRESULT(self.0 | 0x1000_0000)
}
#[inline]
pub fn ok(self) -> ::windows::core::Result<()> {
if self.is_ok() {
Ok(())
} else {
Err(::windows::core::Error::fast_error(self.to_hresult()))
}
}
}
unsafe impl ::windows::core::Abi for NTSTATUS {
type Abi = Self;
}
}
}
|
use std::{
cmp::min,
fs::File,
io::{BufReader, Read, Write},
};
use bstr::{ByteSlice, ByteVec};
pub struct PieceTable {
pub pieces: Vec<Piece>,
pub indent_width: usize,
pub dirty: bool,
original: Vec<u8>,
add: Vec<u8>,
}
#[derive(Debug)]
pub struct Line {
pub index: usize,
pub start: usize,
pub end: usize,
pub length: usize,
}
#[derive(Debug, PartialEq, Clone, Copy)]
enum PieceFile {
Original,
Add,
}
#[derive(Debug, Clone)]
pub struct Piece {
file: PieceFile,
start: usize,
length: usize,
linebreaks: Vec<usize>,
}
impl PieceTable {
pub fn from_file(path: &str) -> Self {
let t = std::time::Instant::now();
let mut original = vec![];
let mut bytes = BufReader::new(File::open(path).unwrap()).bytes().peekable();
let mut linebreaks = vec![];
let mut index = 0;
let mut indentations = [0; 9];
let mut indent_counter = usize::MAX;
let mut previous_indent = 0;
let mut bytes_since_line = 0;
while let Some(byte) = bytes.next() {
let byte = byte.unwrap();
// Basic but probably effective indentation guess
if indent_counter < usize::MAX {
if byte == b'\t' {
indent_counter += 4;
} else if byte.is_ascii_whitespace() {
indent_counter += 1;
} else {
let indent_guess = indent_counter.abs_diff(previous_indent);
if (2..=8).contains(&indent_guess) {
indentations[indent_guess] += 1;
previous_indent = indent_counter;
indent_counter = usize::MAX;
} else {
previous_indent = indent_counter;
indent_counter = usize::MAX;
}
}
}
// Convert '\t' to spaces until next multiple of 4
if byte == b'\t' {
let num = 4 - bytes_since_line % 4;
original.append(&mut vec![b' '; num]);
bytes_since_line += num;
index += num;
continue;
}
// Convert '\r\n' and '\r' to '\n'
if byte != b'\r' {
original.push(byte);
if byte == b'\n' {
linebreaks.push(index);
indent_counter = 0;
bytes_since_line = 0;
} else {
bytes_since_line += 1;
}
index += 1;
continue;
}
if bytes
.peek()
.is_some_and(|b| *(b.as_ref().unwrap()) != b'\n')
{
original.push(b'\n');
linebreaks.push(index);
indent_counter = 0;
bytes_since_line = 0;
index += 1;
}
}
let indent_width = {
if let Some((i, max_indent_count)) = indentations
.iter()
.enumerate()
.max_by(|(_, c1), (_, c2)| c1.cmp(c2))
{
if *max_indent_count > 10 {
i
} else {
4
}
} else {
4
}
};
let file_length = original.len();
Self {
original,
add: vec![],
dirty: false,
pieces: vec![Piece {
file: PieceFile::Original,
start: 0,
length: file_length,
linebreaks,
}],
indent_width,
}
}
pub fn save_to(&mut self, path: &str) {
let mut file = File::create(path).unwrap();
for piece in self.pieces.iter() {
let buffer = if piece.file == PieceFile::Original {
&self.original
} else {
&self.add
};
file.write_all(&buffer[piece.start..piece.start + piece.length])
.unwrap();
}
self.dirty = false;
}
pub fn iter_lines<F>(&self, start: usize, end: usize, mut f: F)
where
F: FnMut(&[u8]),
{
let mut i = 0;
let mut end_of_last_line = String::default();
for piece in &self.pieces {
let buffer = if piece.file == PieceFile::Original {
&self.original
} else {
&self.add
};
let mut offset = piece.start;
for linebreak in &piece.linebreaks {
if !end_of_last_line.is_empty() {
end_of_last_line.push_str(unsafe {
std::str::from_utf8_unchecked(&buffer[offset..=offset + linebreak])
});
if (start..end).contains(&i) {
f(end_of_last_line.as_bytes());
}
end_of_last_line.clear();
i += 1;
if i >= end {
return;
}
} else {
if (start..end).contains(&i) {
f(&buffer[offset..=piece.start + linebreak]);
}
i += 1;
if i >= end {
return;
}
}
offset = piece.start + linebreak + 1;
}
end_of_last_line.push_str(unsafe {
std::str::from_utf8_unchecked(&buffer[offset..piece.start + piece.length])
});
}
if !end_of_last_line.is_empty() {
f(end_of_last_line.as_bytes());
}
}
pub fn iter_chars(&self) -> PieceTableCharIterator {
PieceTableCharIterator {
piece_table: self,
piece_index: 0,
piece_char_index: 0,
}
}
pub fn iter_chars_at(&self, position: usize) -> PieceTableCharIterator {
let mut offset = 0;
for (i, piece) in self.pieces.iter().enumerate() {
if (offset..offset + piece.length).contains(&position) {
return PieceTableCharIterator {
piece_table: self,
piece_index: i,
piece_char_index: position - offset,
};
}
offset += piece.length;
}
PieceTableCharIterator {
piece_table: self,
piece_index: self.pieces.len(),
piece_char_index: 0,
}
}
pub fn iter_chars_at_rev(&self, position: usize) -> PieceTableCharReverseIterator {
let mut offset = 0;
for (i, piece) in self.pieces.iter().enumerate() {
if (offset..offset + piece.length).contains(&position) {
return PieceTableCharReverseIterator {
piece_table: self,
piece_index: i,
piece_char_index: position - offset,
};
}
offset += piece.length;
}
PieceTableCharReverseIterator {
piece_table: self,
piece_index: 0,
piece_char_index: 0,
}
}
pub fn num_chars(&self) -> usize {
self.pieces.iter().fold(0, |acc, piece| acc + piece.length)
}
pub fn num_lines(&self) -> usize {
self.pieces
.iter()
.fold(0, |acc, piece| acc + piece.linebreaks.len())
}
pub fn insert(&mut self, position: usize, bytes: &[u8]) {
let piece = Piece {
file: PieceFile::Add,
start: self.add.len(),
length: bytes.len(),
linebreaks: bytes
.iter()
.enumerate()
.filter(|(i, &c)| c == b'\n')
.map(|(i, c)| i)
.collect(),
};
self.add.push_str(bytes);
if self.pieces.is_empty() {
self.pieces.insert(0, piece);
return;
}
let mut current_position = 0;
for i in 0..self.pieces.len() {
let next_position = current_position + self.pieces[i].length;
if (current_position + 1..next_position).contains(&position) {
// First piece
self.pieces[i].length = position - current_position;
let last_piece_linebreaks = self.pieces[i]
.linebreaks
.drain_filter(|i| *i >= position - current_position)
.map(|i| i - (position - current_position))
.collect();
// Second piece
self.pieces.insert(i + 1, piece);
// Last piece
self.pieces.insert(
i + 2,
Piece {
file: self.pieces[i].file,
start: self.pieces[i].start + self.pieces[i].length,
length: next_position - position,
linebreaks: last_piece_linebreaks,
},
);
break;
}
if current_position == position {
self.pieces.insert(i, piece);
break;
}
if next_position == position {
self.pieces.insert(i + 1, piece);
break;
}
current_position = next_position;
}
self.dirty = true;
}
pub fn delete(&mut self, start: usize, end: usize) {
let mut current_position = 0;
for i in 0..self.pieces.len() {
let next_position = current_position + self.pieces[i].length;
// Delete all pieces that are covered by [start; end]
if start <= current_position && end >= next_position {
self.pieces[i].length = 0;
// Delete the end of slices where the start is in [current; next]
} else if (current_position..next_position).contains(&start) && end >= next_position {
self.pieces[i].length -= next_position - start;
self.pieces[i]
.linebreaks
.drain_filter(|i| *i >= start - current_position);
// Delete the beginning of slices where the end is in [current; next]
} else if (current_position..=next_position).contains(&end) && start <= current_position
{
let delete_count = end - current_position;
self.pieces[i]
.linebreaks
.drain_filter(|i| *i < delete_count);
for linebreak in &mut self.pieces[i].linebreaks {
*linebreak -= delete_count;
}
self.pieces[i].start += delete_count;
self.pieces[i].length -= delete_count;
// Split the slice into two as [start; end] is contained within [current; next]
} else if start > current_position && end < next_position {
self.pieces[i].length = start - current_position;
let last_piece_linebreaks: Vec<usize> = self.pieces[i]
.linebreaks
.drain_filter(|i| *i >= start - current_position)
.collect();
let deleted_count = end - current_position;
self.pieces.insert(
i + 1,
Piece {
file: self.pieces[i].file,
start: self.pieces[i].start + deleted_count,
length: next_position - end,
linebreaks: last_piece_linebreaks
.iter()
.filter_map(|i| (*i >= deleted_count).then(|| i - deleted_count))
.collect(),
},
);
break;
}
current_position = next_position;
}
self.pieces.retain(|piece| piece.length > 0);
self.dirty = true;
}
pub fn line_at_index(&self, index: usize) -> Option<Line> {
let mut start = 0;
let mut offset = 0;
let mut i = 0;
for piece in &self.pieces {
for linebreak in &piece.linebreaks {
let end = offset + linebreak;
if i == index {
return Some(Line {
index,
start,
end,
length: end - start,
});
}
i += 1;
start = end + 1;
}
offset += piece.length;
}
let length = offset - start;
if index == i && length > 0 {
Some(Line {
index,
start,
end: offset,
length,
})
} else {
None
}
}
pub fn line_at_char(&self, position: usize) -> Option<Line> {
let index = self.line_index(position);
self.line_at_index(index)
}
pub fn line_index(&self, position: usize) -> usize {
let mut offset = 0;
let mut linebreaks = 0;
for piece in &self.pieces {
if (offset..offset + piece.length).contains(&position) {
return linebreaks
+ piece
.linebreaks
.iter()
.filter(|&linebreak| *linebreak < position - offset)
.count();
}
linebreaks += piece.linebreaks.len();
offset += piece.length;
}
linebreaks
}
pub fn line_indent_width_at_char(&self, position: usize) -> usize {
if let Some(line) = self.line_at_char(position) {
let mut count = 0;
for c in self.iter_chars_at(line.start).take(line.length) {
if !c.is_ascii_whitespace() {
break;
}
count += 1;
}
return (count / self.indent_width) * self.indent_width;
}
0
}
pub fn line_at_char_starts_with(&self, position: usize, chars: &[u8]) -> bool {
if let Some(line) = self.line_at_char(position) {
let bytes: Vec<u8> = self.iter_chars_at(line.start).take(line.length).collect();
return bytes.trim().starts_with_str(chars);
}
false
}
pub fn line_at_char_ends_with(&self, position: usize, chars: &[u8]) -> bool {
if let Some(line) = self.line_at_char(position) {
let bytes: Vec<u8> = self.iter_chars_at(line.start).take(line.length).collect();
return bytes.trim().ends_with_str(chars);
}
false
}
pub fn char_index_from_line_col(&self, line: usize, col: usize) -> Option<usize> {
if let Some(line) = self.line_at_index(line) {
return Some(line.start + min(col, line.length));
}
None
}
pub fn col_index(&self, position: usize) -> usize {
self.iter_chars_at_rev(position.saturating_sub(1))
.position(|c| c == b'\n')
.unwrap_or(position)
}
pub fn char_at(&self, position: usize) -> Option<u8> {
self.iter_chars_at(position).next()
}
pub fn text_between_lines(&self, start_line: usize, end_line: usize) -> Vec<u8> {
if let Some(start_of_first_line) = self.char_index_from_line_col(start_line, 0) {
let start_of_last_line = self
.char_index_from_line_col(end_line + 1, 0)
.unwrap_or(self.num_chars());
let num_chars = start_of_last_line - start_of_first_line;
return self
.iter_chars_at(start_of_first_line)
.take(num_chars)
.collect();
}
vec![]
}
}
pub struct PieceTableCharIterator<'a> {
piece_table: &'a PieceTable,
piece_index: usize,
piece_char_index: usize,
}
impl<'a> Iterator for PieceTableCharIterator<'a> {
type Item = u8;
fn next(&mut self) -> Option<Self::Item> {
if let Some(piece) = self.piece_table.pieces.get(self.piece_index) {
let buffer = if self.piece_table.pieces[self.piece_index].file == PieceFile::Original {
&self.piece_table.original
} else {
&self.piece_table.add
};
let piece_start = self.piece_table.pieces[self.piece_index].start;
let piece_length = self.piece_table.pieces[self.piece_index].length;
if self.piece_char_index < piece_length {
let c = Some(buffer[piece_start + self.piece_char_index]);
self.piece_char_index += 1;
return c;
}
self.piece_char_index = 0;
self.piece_index += 1;
self.next()
} else {
None
}
}
}
pub struct PieceTableCharReverseIterator<'a> {
piece_table: &'a PieceTable,
piece_index: usize,
piece_char_index: usize,
}
impl<'a> Iterator for PieceTableCharReverseIterator<'a> {
type Item = u8;
fn next(&mut self) -> Option<Self::Item> {
self.piece_table
.pieces
.get(self.piece_index)
.and_then(|piece| {
let buffer = if piece.file == PieceFile::Original {
&self.piece_table.original
} else {
&self.piece_table.add
};
if self.piece_char_index != usize::MAX {
let c = buffer.get(piece.start + self.piece_char_index).copied();
self.piece_char_index = self.piece_char_index.wrapping_sub(1);
return c;
}
if self.piece_index > 0 {
self.piece_index -= 1;
self.piece_char_index = self.piece_table.pieces[self.piece_index].length - 1;
self.next()
} else {
None
}
})
}
}
|
use std::fs::*;
use std::path::PathBuf;
use environment::Environment;
// TODO: check if executable
pub fn resolve(thing: &str, env: &Environment) -> Option<String> {
let thing = PathBuf::from(thing);
if thing.is_absolute() {
if metadata(thing.as_path()).ok().map_or(false, |path| path.is_file()) {
Some(thing)
}
else {
None
}
}
else {
if let Some(env_path) = env.get("PATH") {
env_path.split(':').map(PathBuf::from).map(|mut path| {
path.push(thing.as_path());
path
}).find(|path| {
metadata(path.as_path()).ok().map_or(false, |path| path.is_file())
})
}
else {
None
}
}.and_then(|path| path.to_str().map(String::from))
}
|
use actix_service::{Service, Transform};
use actix_web::{dev::ServiceRequest, dev::ServiceResponse};
use actix_web::{http::header, Error, HttpResponse};
use futures::future::{ok, Either, FutureResult};
use futures::Poll;
use std::str::FromStr;
use crate::utils::jwt::decode_token;
pub struct CheckToken;
impl<S, B> Transform<S> for CheckToken
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 = CheckTokenMiddleware<S>;
type Future = FutureResult<Self::Transform, Self::InitError>;
fn new_transform(&self, service: S) -> Self::Future {
ok(CheckTokenMiddleware { service })
}
}
pub struct CheckTokenMiddleware<S> {
service: S,
}
impl<S, B> Service for CheckTokenMiddleware<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 = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
type Future = Either<S::Future, FutureResult<Self::Response, Self::Error>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready()
}
fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
if let Some(auth_token) = req.headers().get("authorization") {
if let Ok(auth_token_str) = auth_token.to_str() {
if let Ok(auth_user) = decode_token(auth_token_str) {
let u_id = auth_user.id.hyphenated().to_string();
let u_role = auth_user.role.to_string();
req.headers_mut().insert(
header::HeaderName::from_str("auth_id").unwrap(),
header::HeaderValue::from_str(&u_id).unwrap(),
);
req.headers_mut().insert(
header::HeaderName::from_str("auth_role").unwrap(),
header::HeaderValue::from_str(&u_role).unwrap(),
);
Either::A(self.service.call(req))
} else {
Either::B(ok(
req.into_response(HttpResponse::Unauthorized().finish().into_body())
))
}
} else {
Either::B(ok(
req.into_response(HttpResponse::Unauthorized().finish().into_body())
))
}
} else {
Either::B(ok(
req.into_response(HttpResponse::Unauthorized().finish().into_body())
))
}
}
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
pub const CLSID_XMLGraphBuilder: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1bb05961_5fbf_11d2_a521_44df07c10000);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IXMLGraphBuilder(pub ::windows::core::IUnknown);
impl IXMLGraphBuilder {
#[cfg(feature = "Win32_Data_Xml_MsXml")]
pub unsafe fn BuildFromXML<'a, Param0: ::windows::core::IntoParam<'a, super::IGraphBuilder>, Param1: ::windows::core::IntoParam<'a, super::super::super::Data::Xml::MsXml::IXMLElement>>(&self, pgraph: Param0, pxml: Param1) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), pgraph.into_param().abi(), pxml.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SaveToXML<'a, Param0: ::windows::core::IntoParam<'a, super::IGraphBuilder>>(&self, pgraph: Param0, pbstrxml: *mut super::super::super::Foundation::BSTR) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), pgraph.into_param().abi(), ::core::mem::transmute(pbstrxml)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn BuildFromXMLFile<'a, Param0: ::windows::core::IntoParam<'a, super::IGraphBuilder>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>>(&self, pgraph: Param0, wszfilename: Param1, wszbaseurl: Param2) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), pgraph.into_param().abi(), wszfilename.into_param().abi(), wszbaseurl.into_param().abi()).ok()
}
}
unsafe impl ::windows::core::Interface for IXMLGraphBuilder {
type Vtable = IXMLGraphBuilder_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1bb05960_5fbf_11d2_a521_44df07c10000);
}
impl ::core::convert::From<IXMLGraphBuilder> for ::windows::core::IUnknown {
fn from(value: IXMLGraphBuilder) -> Self {
value.0
}
}
impl ::core::convert::From<&IXMLGraphBuilder> for ::windows::core::IUnknown {
fn from(value: &IXMLGraphBuilder) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IXMLGraphBuilder {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IXMLGraphBuilder {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IXMLGraphBuilder_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Data_Xml_MsXml")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pgraph: ::windows::core::RawPtr, pxml: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Data_Xml_MsXml"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pgraph: ::windows::core::RawPtr, pbstrxml: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pgraph: ::windows::core::RawPtr, wszfilename: super::super::super::Foundation::PWSTR, wszbaseurl: super::super::super::Foundation::PWSTR) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
|
extern crate regex;
extern crate clang;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate arguments;
fn count_lines(range: clang::source::SourceRange) -> u32 {
let (_file, line_s, _col) = range.get_start().get_presumed_location();
let (_file, line_e, _col) = range.get_end().get_presumed_location();
line_e - line_s + 1
}
fn is_statement(stmt: &clang::Entity) -> bool {
stmt.is_statement() || stmt.is_expression()
}
fn is_conditional(stmt: &clang::Entity) -> bool {
//println!("{:?}", stmt);
assert!(is_statement(stmt));
match stmt.get_kind() {
clang::EntityKind::IfStmt => true,
clang::EntityKind::WhileStmt => true,
clang::EntityKind::DoStmt => true,
clang::EntityKind::ForStmt => true,
clang::EntityKind::SwitchStmt => true,
_ => false,
}
}
fn get_body<'tu>(stmt: &clang::Entity<'tu>) -> (clang::Entity<'tu>, Option<clang::Entity<'tu>>) {
if stmt.get_kind() == clang::EntityKind::IfStmt {
let children = stmt.get_children();
if children.len() == 2 {
let body = children.last().unwrap();
(*body, None)
} else {
let body = children[1];
let body_else = children[2];
(body, Some(body_else))
}
} else {
let children = stmt.get_children();
let body = children.last().unwrap();
(*body, None)
}
}
fn process_conditional(stmt: &clang::Entity) -> (u32, u32) {
// get body
let (body, body_else) = get_body(&stmt);
let (mut nodes, mut edges) = cyclomatic_complexity(&body);
//if we have an else clause, we add an edge and acount the block
if let Some(body) = body_else {
let (n, e) = cyclomatic_complexity(&body);
nodes += n;
edges += e + 1;
}
(nodes, edges)
}
fn cyclomatic_complexity(stmt: &clang::Entity) -> (u32, u32) {
if stmt.get_kind() == clang::EntityKind::CompoundStmt {
// for each statement:
stmt.get_children()
.iter()
.fold((0, 0), |(nodes, edges), stmt| {
let mut nodes = nodes + 1;
let mut edges = edges + 1;
if is_conditional(stmt) {
if stmt.get_kind() != clang::EntityKind::SwitchStmt {
edges += 1;
}
let (n, e) = process_conditional(stmt);
nodes += n;
edges += e;
}
// we may be inside of a switch, count the number of cases and defaults as edges
if stmt.get_kind() == clang::EntityKind::CaseStmt
|| stmt.get_kind() == clang::EntityKind::DefaultStmt
{
edges += 1;
}
(nodes, edges)
})
} else {
if is_conditional(stmt) {
process_conditional(stmt)
} else {
(1, 1)
}
}
}
fn get_file_location(node: &clang::Entity) -> Result<String, ()> {
let loc = node.get_location().unwrap();
let loc = loc.get_spelling_location().file.unwrap().get_path();
Ok(loc.to_str().unwrap().to_string())
}
fn get_filename(path: &String) -> Option<&str> {
use std::path;
let path = path::Path::new(path.as_str());
path.file_name().map(|osstr| osstr.to_str()).unwrap()
}
fn get_module(path: &String) -> Option<&str> {
use std::path;
let path = path::Path::new(path.as_str());
path.parent().unwrap().to_str()
}
#[derive(Clone, Debug)]
struct ProcessCtx {
namespaces: String,
header_regex: Option<regex::Regex>,
}
impl ProcessCtx {
fn process_fn(&self, fun: &clang::Entity) {
if let None = fun.get_child(0) {
// just a declaration, no body
return;
}
let loc = get_file_location(fun).unwrap_or("no_location".to_string());
let file = get_filename(&loc).unwrap();
let module = get_module(&loc).unwrap();
let name = self.get_qualified_name(fun);
let lines = count_lines(fun.get_range().unwrap());
let arg_count = fun.get_arguments().unwrap().len();
let body = fun.get_children().last().unwrap().clone();
if body.get_kind() != clang::EntityKind::CompoundStmt {
return;
}
let (n, e) = cyclomatic_complexity(&body);
let comp = e - n; // using simplied formula, avoid (+ 2p);
println!(
"{:60}\t{:20}\t{:80}\t{}\t{}\t{}",
module, file, name, arg_count, lines, comp
);
}
fn process_named_nested(&self, node: &clang::Entity) {
let mut new_ctx = self.clone();
new_ctx.push_name(node.get_name().unwrap_or("anonymous".to_string()));
new_ctx.process_node(&node);
}
fn process_node(&self, node: &clang::Entity) {
node.visit_children(
|node: clang::Entity, _parent: clang::Entity| -> clang::EntityVisitResult {
let x = node.get_location();
if let Some(loc) = x {
match (&self.header_regex, get_file_location(&node)) {
(Some(ref r), Ok(ref path)) => {
if !r.is_match(path.as_str()) {
return clang::EntityVisitResult::Continue;
}
}
(None, _) => {
if !loc.is_in_main_file() {
return clang::EntityVisitResult::Continue;
}
}
(_, _) => {}
}
} else {
return clang::EntityVisitResult::Continue;
}
match node.get_kind() {
clang::EntityKind::Namespace => {
self.process_named_nested(&node);
clang::EntityVisitResult::Continue
}
clang::EntityKind::ClassDecl => {
self.process_named_nested(&node);
clang::EntityVisitResult::Continue
}
clang::EntityKind::UnionDecl => {
self.process_named_nested(&node);
clang::EntityVisitResult::Continue
}
clang::EntityKind::StructDecl => {
self.process_named_nested(&node);
clang::EntityVisitResult::Continue
}
clang::EntityKind::FunctionDecl => {
self.process_fn(&node);
clang::EntityVisitResult::Continue
}
clang::EntityKind::Method => {
self.process_fn(&node);
clang::EntityVisitResult::Continue
}
_ => clang::EntityVisitResult::Continue,
}
},
);
}
fn push_name(&mut self, name: String) {
if self.namespaces.is_empty() {
self.namespaces = name;
} else {
self.namespaces = format!("{}::{}", self.namespaces, name);
}
}
fn get_qualified_name(&self, node: &clang::Entity) -> String {
let mut name = node.get_name().unwrap();
if node.get_kind() == clang::EntityKind::Method {
for c in node.get_children() {
if c.is_reference() {
let r = c.get_reference().unwrap();
let class_name = r.get_name().unwrap();
name = format!("{}::{}", class_name, name)
}
}
}
if self.namespaces.is_empty() {
return name;
}
format!("{}::{}", self.namespaces, name)
}
}
fn print_header() {
let module = "module";
let file = "file";
let name = "name";
let arg_count = "args";
let lines = "lines";
let comp = "McCabe";
println!(
"{:60}\t{:20}\t{:80}\t{}\t{}\t{}",
module, file, name, arg_count, lines, comp
);
}
fn process_file(file: &str, args: &[&str], hr: Option<String>) {
let clang = clang::Clang::new().unwrap();
let index = clang::Index::new(&clang, false, false);
let tu = index
.parser(file)
.arguments(args)
.parse()
.expect("should parse");
let header_rex = hr.map(|s| regex::Regex::new(s.as_str()).unwrap());
let ctx = ProcessCtx {
namespaces: String::new(),
header_regex: header_rex,
};
ctx.process_node(&tu.get_entity());
}
#[derive(Serialize, Deserialize, Debug)]
struct CompilationEntry {
pub directory: String,
pub command: String,
pub file: String,
}
fn main() {
eprintln!("using clang {}", clang::get_version());
let args = std::env::args();
let arguments = arguments::parse(args).unwrap();
let headers = arguments.get::<String>("headers");
if let Some(conf) = arguments.get::<String>("conf") {
use std::fs::File;
use std::io::BufReader;
let file = File::open(conf).unwrap();
let reader = BufReader::new(file);
let comp_db: Vec<CompilationEntry> = serde_json::from_reader(reader).unwrap();
print_header();
for cfg in comp_db {
let mut comp_args: Vec<&str> =
cfg.command.split(" ").filter(|s| !s.is_empty()).collect();
comp_args.remove(0);
let len = comp_args.len();
process_file(
cfg.file.as_str(),
&comp_args.as_slice()[0..len - 4],
headers.clone(),
);
}
}
if let Some(file) = arguments.get::<String>("file") {
print_header();
process_file(file.as_str(), &[], headers.clone());
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub const E_FDPAIRING_AUTHFAILURE: ::windows_sys::core::HRESULT = -1882193917i32;
pub const E_FDPAIRING_AUTHNOTALLOWED: ::windows_sys::core::HRESULT = -1882193914i32;
pub const E_FDPAIRING_CONNECTTIMEOUT: ::windows_sys::core::HRESULT = -1882193916i32;
pub const E_FDPAIRING_HWFAILURE: ::windows_sys::core::HRESULT = -1882193918i32;
pub const E_FDPAIRING_IPBUSDISABLED: ::windows_sys::core::HRESULT = -1882193913i32;
pub const E_FDPAIRING_NOCONNECTION: ::windows_sys::core::HRESULT = -1882193919i32;
pub const E_FDPAIRING_NOPROFILES: ::windows_sys::core::HRESULT = -1882193912i32;
pub const E_FDPAIRING_TOOMANYCONNECTIONS: ::windows_sys::core::HRESULT = -1882193915i32;
pub const FD_EVENTID: u32 = 1000u32;
pub const FD_EVENTID_ASYNCTHREADEXIT: u32 = 1001u32;
pub const FD_EVENTID_IPADDRESSCHANGE: u32 = 1003u32;
pub const FD_EVENTID_PRIVATE: u32 = 100u32;
pub const FD_EVENTID_QUERYREFRESH: u32 = 1004u32;
pub const FD_EVENTID_SEARCHCOMPLETE: u32 = 1000u32;
pub const FD_EVENTID_SEARCHSTART: u32 = 1002u32;
pub const FD_LONGHORN: u32 = 1u32;
pub const FD_Visibility_Default: u32 = 0u32;
pub const FD_Visibility_Hidden: u32 = 1u32;
pub const FMTID_Device: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] };
pub const FMTID_DeviceInterface: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1400930312, data2: 1979, data3: 18017, data4: [188, 60, 181, 149, 62, 112, 133, 96] };
pub const FMTID_FD: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2420835234, data2: 18205, data3: 16956, data4: [165, 132, 243, 72, 50, 56, 161, 70] };
pub const FMTID_PNPX: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
};
pub const FMTID_PNPXDynamicProperty: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1338312574,
data2: 46726,
data3: 17598,
data4: [147, 227, 134, 202, 254, 54, 140, 205],
};
pub const FMTID_Pairing: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2282212070,
data2: 32182,
data3: 20240,
data4: [142, 228, 67, 94, 170, 19, 146, 188],
};
pub const FMTID_WSD: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2454742161,
data2: 65429,
data3: 18212,
data4: [160, 90, 91, 129, 136, 90, 124, 146],
};
pub const FunctionDiscovery: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3341542124,
data2: 36496,
data3: 17708,
data4: [178, 154, 171, 143, 241, 192, 113, 252],
};
pub const FunctionInstanceCollection: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3129052389, data2: 46431, data3: 17471, data4: [173, 57, 47, 232, 155, 230, 25, 31] };
pub type IFunctionDiscovery = *mut ::core::ffi::c_void;
pub type IFunctionDiscoveryNotification = *mut ::core::ffi::c_void;
pub type IFunctionDiscoveryProvider = *mut ::core::ffi::c_void;
pub type IFunctionDiscoveryProviderFactory = *mut ::core::ffi::c_void;
pub type IFunctionDiscoveryProviderQuery = *mut ::core::ffi::c_void;
pub type IFunctionDiscoveryServiceProvider = *mut ::core::ffi::c_void;
pub type IFunctionInstance = *mut ::core::ffi::c_void;
pub type IFunctionInstanceCollection = *mut ::core::ffi::c_void;
pub type IFunctionInstanceCollectionQuery = *mut ::core::ffi::c_void;
pub type IFunctionInstanceQuery = *mut ::core::ffi::c_void;
pub type IPNPXAssociation = *mut ::core::ffi::c_void;
pub type IPNPXDeviceAssociation = *mut ::core::ffi::c_void;
pub type IPropertyStoreCollection = *mut ::core::ffi::c_void;
pub type IProviderProperties = *mut ::core::ffi::c_void;
pub type IProviderPropertyConstraintCollection = *mut ::core::ffi::c_void;
pub type IProviderPublishing = *mut ::core::ffi::c_void;
pub type IProviderQueryConstraintCollection = *mut ::core::ffi::c_void;
pub const MAX_FDCONSTRAINTNAME_LENGTH: u32 = 100u32;
pub const MAX_FDCONSTRAINTVALUE_LENGTH: u32 = 1000u32;
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_Characteristics: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1126273419,
data2: 63134,
data3: 18189,
data4: [165, 222, 77, 136, 199, 90, 210, 75],
},
pid: 29u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_ClassCoInstallers: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 1899828995, data2: 41698, data3: 18933, data4: [146, 20, 86, 71, 46, 243, 218, 92] },
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_ClassInstaller: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 630898684, data2: 20647, data3: 18382, data4: [175, 8, 104, 201, 167, 215, 51, 102] },
pid: 5u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_ClassName: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 630898684, data2: 20647, data3: 18382, data4: [175, 8, 104, 201, 167, 215, 51, 102] },
pid: 3u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_DefaultService: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 630898684, data2: 20647, data3: 18382, data4: [175, 8, 104, 201, 167, 215, 51, 102] },
pid: 11u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_DevType: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1126273419,
data2: 63134,
data3: 18189,
data4: [165, 222, 77, 136, 199, 90, 210, 75],
},
pid: 27u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_Exclusive: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1126273419,
data2: 63134,
data3: 18189,
data4: [165, 222, 77, 136, 199, 90, 210, 75],
},
pid: 28u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_Icon: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 630898684, data2: 20647, data3: 18382, data4: [175, 8, 104, 201, 167, 215, 51, 102] },
pid: 4u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_IconPath: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 630898684, data2: 20647, data3: 18382, data4: [175, 8, 104, 201, 167, 215, 51, 102] },
pid: 12u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_LowerFilters: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1126273419,
data2: 63134,
data3: 18189,
data4: [165, 222, 77, 136, 199, 90, 210, 75],
},
pid: 20u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_Name: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 630898684, data2: 20647, data3: 18382, data4: [175, 8, 104, 201, 167, 215, 51, 102] },
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_NoDisplayClass: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 630898684, data2: 20647, data3: 18382, data4: [175, 8, 104, 201, 167, 215, 51, 102] },
pid: 8u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_NoInstallClass: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 630898684, data2: 20647, data3: 18382, data4: [175, 8, 104, 201, 167, 215, 51, 102] },
pid: 7u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_NoUseClass: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 630898684, data2: 20647, data3: 18382, data4: [175, 8, 104, 201, 167, 215, 51, 102] },
pid: 10u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_PropPageProvider: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 630898684, data2: 20647, data3: 18382, data4: [175, 8, 104, 201, 167, 215, 51, 102] },
pid: 6u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_Security: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1126273419,
data2: 63134,
data3: 18189,
data4: [165, 222, 77, 136, 199, 90, 210, 75],
},
pid: 25u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_SecuritySDS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1126273419,
data2: 63134,
data3: 18189,
data4: [165, 222, 77, 136, 199, 90, 210, 75],
},
pid: 26u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_SilentInstall: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 630898684, data2: 20647, data3: 18382, data4: [175, 8, 104, 201, 167, 215, 51, 102] },
pid: 9u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceClass_UpperFilters: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1126273419,
data2: 63134,
data3: 18189,
data4: [165, 222, 77, 136, 199, 90, 210, 75],
},
pid: 19u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_Address: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 51u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_AlwaysShowDeviceAsConnected: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 101u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_AssociationArray: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 80u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_BaselineExperienceId: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 78u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_Category: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 90u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_CategoryGroup_Desc: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 94u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_CategoryGroup_Icon: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 95u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_Category_Desc_Plural: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 92u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_Category_Desc_Singular: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 91u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_Category_Icon: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 93u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_DeviceDescription1: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 81u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_DeviceDescription2: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 82u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_DeviceFunctionSubRank: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 100u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_DiscoveryMethod: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 52u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_ExperienceId: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 89u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_FriendlyName: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 12288u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_Icon: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 57u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_InstallInProgress: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2212127526, data2: 38822, data3: 16520, data4: [148, 83, 161, 146, 63, 87, 59, 41] },
pid: 9u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_IsAuthenticated: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 54u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_IsConnected: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 55u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_IsDefaultDevice: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 86u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_IsDeviceUniquelyIdentifiable: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 79u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_IsEncrypted: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 53u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_IsLocalMachine: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 70u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_IsMetadataSearchInProgress: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 72u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_IsNetworkDevice: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 85u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_IsNotInterestingForDisplay: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 74u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_IsNotWorkingProperly: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 83u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_IsPaired: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 56u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_IsSharedDevice: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 84u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_IsShowInDisconnectedState: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 68u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_Last_Connected: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 67u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_Last_Seen: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 66u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_LaunchDeviceStageFromExplorer: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 77u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_LaunchDeviceStageOnDeviceConnect: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 76u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_Manufacturer: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 8192u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_MetadataCabinet: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 87u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_MetadataChecksum: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 73u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_MetadataPath: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 71u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_ModelName: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 8194u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_ModelNumber: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 8195u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_PrimaryCategory: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 97u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_RequiresPairingElevation: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 88u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_RequiresUninstallElevation: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 99u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_UnpairUninstall: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 98u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceDisplay_Version: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 65u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceInterfaceClass_DefaultInterface: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 348666521, data2: 2879, data3: 17591, data4: [190, 76, 161, 120, 211, 153, 5, 100] },
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceInterface_ClassGuid: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 40784238, data2: 47124, data3: 16715, data4: [131, 205, 133, 109, 111, 239, 72, 34] },
pid: 4u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceInterface_Enabled: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 40784238, data2: 47124, data3: 16715, data4: [131, 205, 133, 109, 111, 239, 72, 34] },
pid: 3u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DeviceInterface_FriendlyName: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 40784238, data2: 47124, data3: 16715, data4: [131, 205, 133, 109, 111, 239, 72, 34] },
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_AdditionalSoftwareRequested: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 19u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_Address: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 30u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_BIOSVersion: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 3941498653, data2: 27187, data3: 17617, data4: [148, 65, 95, 70, 222, 242, 49, 152] },
pid: 9u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_BaseContainerId: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 38u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_BusNumber: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 23u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_BusRelations: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1128310469,
data2: 37882,
data3: 18182,
data4: [151, 44, 123, 100, 128, 8, 165, 167],
},
pid: 7u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_BusReportedDeviceDesc: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1410045054,
data2: 35648,
data3: 17852,
data4: [168, 162, 106, 11, 137, 76, 189, 162],
},
pid: 4u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_BusTypeGuid: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 21u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_Capabilities: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 17u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_Characteristics: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 29u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_Children: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1128310469,
data2: 37882,
data3: 18182,
data4: [151, 44, 123, 100, 128, 8, 165, 167],
},
pid: 9u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_Class: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 9u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_ClassGuid: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 10u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_CompatibleIds: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 4u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_ConfigFlags: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 12u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_ContainerId: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2357121542,
data2: 16266,
data3: 18471,
data4: [179, 171, 174, 158, 31, 174, 252, 108],
},
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_DHP_Rebalance_Policy: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1410045054,
data2: 35648,
data3: 17852,
data4: [168, 162, 106, 11, 137, 76, 189, 162],
},
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_DevNodeStatus: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1128310469,
data2: 37882,
data3: 18182,
data4: [151, 44, 123, 100, 128, 8, 165, 167],
},
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_DevType: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 27u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_DeviceDesc: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_Driver: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 11u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_DriverCoInstallers: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 11u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_DriverDate: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_DriverDesc: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 4u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_DriverInfPath: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 5u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_DriverInfSection: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 6u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_DriverInfSectionExt: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 7u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_DriverLogoLevel: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 15u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_DriverPropPageProvider: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 10u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_DriverProvider: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 9u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_DriverRank: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 14u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_DriverVersion: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 3u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_EjectionRelations: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1128310469,
data2: 37882,
data3: 18182,
data4: [151, 44, 123, 100, 128, 8, 165, 167],
},
pid: 4u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_EnumeratorName: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 24u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_Exclusive: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 28u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_FriendlyName: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 14u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_FriendlyNameAttributes: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2161647270, data2: 29811, data3: 19212, data4: [130, 22, 239, 193, 26, 44, 76, 139] },
pid: 3u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_GenericDriverInstalled: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 18u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_HardwareIds: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 3u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_InstallInProgress: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2212127526, data2: 38822, data3: 16520, data4: [148, 83, 161, 146, 63, 87, 59, 41] },
pid: 9u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_InstallState: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 36u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_InstanceId: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2026065864, data2: 4170, data3: 19146, data4: [158, 164, 82, 77, 82, 153, 110, 87] },
pid: 256u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_IsAssociateableByUserAction: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2161647270, data2: 29811, data3: 19212, data4: [130, 22, 239, 193, 26, 44, 76, 139] },
pid: 7u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_Legacy: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2152296704,
data2: 35955,
data3: 18617,
data4: [170, 217, 206, 56, 126, 25, 197, 110],
},
pid: 3u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_LegacyBusType: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 22u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_LocationInfo: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 15u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_LocationPaths: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 37u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_LowerFilters: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 20u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_Manufacturer: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 13u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_ManufacturerAttributes: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2161647270, data2: 29811, data3: 19212, data4: [130, 22, 239, 193, 26, 44, 76, 139] },
pid: 4u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_MatchingDeviceId: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 8u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_ModelId: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2161647270, data2: 29811, data3: 19212, data4: [130, 22, 239, 193, 26, 44, 76, 139] },
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_NoConnectSound: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 17u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_Numa_Node: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1410045054,
data2: 35648,
data3: 17852,
data4: [168, 162, 106, 11, 137, 76, 189, 162],
},
pid: 3u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_PDOName: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 16u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_Parent: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1128310469,
data2: 37882,
data3: 18182,
data4: [151, 44, 123, 100, 128, 8, 165, 167],
},
pid: 8u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_PowerData: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 32u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_PowerRelations: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1128310469,
data2: 37882,
data3: 18182,
data4: [151, 44, 123, 100, 128, 8, 165, 167],
},
pid: 6u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_PresenceNotForDevice: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2161647270, data2: 29811, data3: 19212, data4: [130, 22, 239, 193, 26, 44, 76, 139] },
pid: 5u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_ProblemCode: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1128310469,
data2: 37882,
data3: 18182,
data4: [151, 44, 123, 100, 128, 8, 165, 167],
},
pid: 3u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_RemovalPolicy: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 33u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_RemovalPolicyDefault: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 34u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_RemovalPolicyOverride: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 35u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_RemovalRelations: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1128310469,
data2: 37882,
data3: 18182,
data4: [151, 44, 123, 100, 128, 8, 165, 167],
},
pid: 5u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_Reported: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2152296704,
data2: 35955,
data3: 18617,
data4: [170, 217, 206, 56, 126, 25, 197, 110],
},
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_ResourcePickerExceptions: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 13u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_ResourcePickerTags: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2830656989,
data2: 11837,
data3: 16532,
data4: [173, 151, 229, 147, 167, 12, 117, 214],
},
pid: 12u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_SafeRemovalRequired: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2950264384,
data2: 34467,
data3: 16912,
data4: [182, 124, 40, 156, 65, 170, 190, 85],
},
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_SafeRemovalRequiredOverride: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2950264384,
data2: 34467,
data3: 16912,
data4: [182, 124, 40, 156, 65, 170, 190, 85],
},
pid: 3u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_Security: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 25u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_SecuritySDS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 26u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_Service: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 6u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_Siblings: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1128310469,
data2: 37882,
data3: 18182,
data4: [151, 44, 123, 100, 128, 8, 165, 167],
},
pid: 10u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_SignalStrength: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2161647270, data2: 29811, data3: 19212, data4: [130, 22, 239, 193, 26, 44, 76, 139] },
pid: 6u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_TransportRelations: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1128310469,
data2: 37882,
data3: 18182,
data4: [151, 44, 123, 100, 128, 8, 165, 167],
},
pid: 11u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_UINumber: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 18u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_UINumberDescFormat: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 31u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Device_UpperFilters: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2757502286,
data2: 57116,
data3: 20221,
data4: [128, 32, 103, 209, 70, 168, 80, 224],
},
pid: 19u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DrvPkg_BrandingIcon: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 3480468305,
data2: 15039,
data3: 17570,
data4: [133, 224, 154, 61, 199, 161, 33, 50],
},
pid: 7u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DrvPkg_DetailedDescription: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 3480468305,
data2: 15039,
data3: 17570,
data4: [133, 224, 154, 61, 199, 161, 33, 50],
},
pid: 4u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DrvPkg_DocumentationLink: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 3480468305,
data2: 15039,
data3: 17570,
data4: [133, 224, 154, 61, 199, 161, 33, 50],
},
pid: 5u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DrvPkg_Icon: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 3480468305,
data2: 15039,
data3: 17570,
data4: [133, 224, 154, 61, 199, 161, 33, 50],
},
pid: 6u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DrvPkg_Model: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 3480468305,
data2: 15039,
data3: 17570,
data4: [133, 224, 154, 61, 199, 161, 33, 50],
},
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_DrvPkg_VendorWebSite: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 3480468305,
data2: 15039,
data3: 17570,
data4: [133, 224, 154, 61, 199, 161, 33, 50],
},
pid: 3u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_FunctionInstance: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 146850387, data2: 41300, data3: 18246, data4: [144, 5, 130, 222, 83, 23, 20, 139] },
pid: 1u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Hardware_Devinst: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 1588543218, data2: 57546, data3: 17816, data4: [191, 6, 113, 237, 29, 157, 217, 83] },
pid: 4097u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Hardware_DisplayAttribute: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 1588543218, data2: 57546, data3: 17816, data4: [191, 6, 113, 237, 29, 157, 217, 83] },
pid: 5u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Hardware_DriverDate: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 1588543218, data2: 57546, data3: 17816, data4: [191, 6, 113, 237, 29, 157, 217, 83] },
pid: 11u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Hardware_DriverProvider: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 1588543218, data2: 57546, data3: 17816, data4: [191, 6, 113, 237, 29, 157, 217, 83] },
pid: 10u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Hardware_DriverVersion: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 1588543218, data2: 57546, data3: 17816, data4: [191, 6, 113, 237, 29, 157, 217, 83] },
pid: 9u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Hardware_Function: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 1588543218, data2: 57546, data3: 17816, data4: [191, 6, 113, 237, 29, 157, 217, 83] },
pid: 4099u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Hardware_Icon: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 1588543218, data2: 57546, data3: 17816, data4: [191, 6, 113, 237, 29, 157, 217, 83] },
pid: 3u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Hardware_Image: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 1588543218, data2: 57546, data3: 17816, data4: [191, 6, 113, 237, 29, 157, 217, 83] },
pid: 4098u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Hardware_Manufacturer: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 1588543218, data2: 57546, data3: 17816, data4: [191, 6, 113, 237, 29, 157, 217, 83] },
pid: 6u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Hardware_Model: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 1588543218, data2: 57546, data3: 17816, data4: [191, 6, 113, 237, 29, 157, 217, 83] },
pid: 7u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Hardware_Name: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 1588543218, data2: 57546, data3: 17816, data4: [191, 6, 113, 237, 29, 157, 217, 83] },
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Hardware_SerialNumber: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 1588543218, data2: 57546, data3: 17816, data4: [191, 6, 113, 237, 29, 157, 217, 83] },
pid: 8u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Hardware_ShellAttributes: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 1588543218, data2: 57546, data3: 17816, data4: [191, 6, 113, 237, 29, 157, 217, 83] },
pid: 4100u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Hardware_Status: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 1588543218, data2: 57546, data3: 17816, data4: [191, 6, 113, 237, 29, 157, 217, 83] },
pid: 4096u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_NAME: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 3072717104, data2: 18415, data3: 4122, data4: [165, 241, 2, 96, 140, 158, 235, 172] },
pid: 10u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Numa_Proximity_Domain: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1410045054,
data2: 35648,
data3: 17852,
data4: [168, 162, 106, 11, 137, 76, 189, 162],
},
pid: 1u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_Associated: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1338312574,
data2: 46726,
data3: 17598,
data4: [147, 227, 134, 202, 254, 54, 140, 205],
},
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_Category_Desc_NonPlural: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 12304u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_CompactSignature: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 28674u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_CompatibleTypes: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1338312574,
data2: 46726,
data3: 17598,
data4: [147, 227, 134, 202, 254, 54, 140, 205],
},
pid: 3u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_DeviceCategory: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 12292u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_DeviceCategory_Desc: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 12293u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_DeviceCertHash: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 28675u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_DomainName: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 20480u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_FirmwareVersion: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 12289u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_GlobalIdentity: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 4096u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_ID: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 4101u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_IPBusEnumerated: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 28688u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_InstallState: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1338312574,
data2: 46726,
data3: 17598,
data4: [147, 227, 134, 202, 254, 54, 140, 205],
},
pid: 4u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_Installable: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1338312574,
data2: 46726,
data3: 17598,
data4: [147, 227, 134, 202, 254, 54, 140, 205],
},
pid: 1u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_IpAddress: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 12297u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_ManufacturerUrl: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 8193u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_MetadataVersion: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 4100u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_ModelUrl: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 8196u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_NetworkInterfaceGuid: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 12296u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_NetworkInterfaceLuid: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 12295u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_PhysicalAddress: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 12294u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_PresentationUrl: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 8198u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_RemoteAddress: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 4102u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_Removable: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 28672u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_RootProxy: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 4103u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_Scopes: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 4098u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_SecureChannel: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 28673u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_SerialNumber: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 12290u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_ServiceAddress: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 16384u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_ServiceControlUrl: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 16388u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_ServiceDescUrl: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 16389u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_ServiceEventSubUrl: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 16390u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_ServiceId: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 16385u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_ServiceTypes: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 16386u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_ShareName: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 20482u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_Types: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 4097u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_Upc: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 8197u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_PNPX_XAddrs: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 4099u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Pairing_IsWifiOnlyDevice: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2282212070,
data2: 32182,
data3: 20240,
data4: [142, 228, 67, 94, 170, 19, 146, 188],
},
pid: 16u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Pairing_ListItemDefault: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2282212070,
data2: 32182,
data3: 20240,
data4: [142, 228, 67, 94, 170, 19, 146, 188],
},
pid: 4u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Pairing_ListItemDescription: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2282212070,
data2: 32182,
data3: 20240,
data4: [142, 228, 67, 94, 170, 19, 146, 188],
},
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Pairing_ListItemIcon: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2282212070,
data2: 32182,
data3: 20240,
data4: [142, 228, 67, 94, 170, 19, 146, 188],
},
pid: 3u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_Pairing_ListItemText: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 2282212070,
data2: 32182,
data3: 20240,
data4: [142, 228, 67, 94, 170, 19, 146, 188],
},
pid: 1u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_SSDP_AltLocationInfo: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 24576u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_SSDP_DevLifeTime: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 24577u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_SSDP_NetworkInterface: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 1701460915,
data2: 60608,
data3: 17405,
data4: [132, 119, 74, 224, 64, 74, 150, 205],
},
pid: 24578u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WCN_AssocState: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2283342728, data2: 18052, data3: 4570, data4: [162, 106, 0, 2, 179, 152, 142, 129] },
pid: 9u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WCN_AuthType: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2283342722, data2: 18052, data3: 4570, data4: [162, 106, 0, 2, 179, 152, 142, 129] },
pid: 3u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WCN_ConfigError: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2283342729, data2: 18052, data3: 4570, data4: [162, 106, 0, 2, 179, 152, 142, 129] },
pid: 10u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WCN_ConfigMethods: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2283342725, data2: 18052, data3: 4570, data4: [162, 106, 0, 2, 179, 152, 142, 129] },
pid: 6u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WCN_ConfigState: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2283342729, data2: 18052, data3: 4570, data4: [162, 106, 0, 2, 179, 152, 142, 129] },
pid: 11u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WCN_ConnType: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2283342724, data2: 18052, data3: 4570, data4: [162, 106, 0, 2, 179, 152, 142, 129] },
pid: 5u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WCN_DevicePasswordId: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2283342729, data2: 18052, data3: 4570, data4: [162, 106, 0, 2, 179, 152, 142, 129] },
pid: 12u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WCN_EncryptType: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2283342723, data2: 18052, data3: 4570, data4: [162, 106, 0, 2, 179, 152, 142, 129] },
pid: 4u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WCN_OSVersion: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2283342729, data2: 18052, data3: 4570, data4: [162, 106, 0, 2, 179, 152, 142, 129] },
pid: 13u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WCN_RegistrarType: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2283342731, data2: 18052, data3: 4570, data4: [162, 106, 0, 2, 179, 152, 142, 129] },
pid: 15u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WCN_RequestType: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2283342721, data2: 18052, data3: 4570, data4: [162, 106, 0, 2, 179, 152, 142, 129] },
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WCN_RfBand: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2283342727, data2: 18052, data3: 4570, data4: [162, 106, 0, 2, 179, 152, 142, 129] },
pid: 8u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WCN_VendorExtension: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2283342730, data2: 18052, data3: 4570, data4: [162, 106, 0, 2, 179, 152, 142, 129] },
pid: 14u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WCN_Version: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID { data1: 2283342720, data2: 18052, data3: 4570, data4: [162, 106, 0, 2, 179, 152, 142, 129] },
pid: 1u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WNET_Comment: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 3736970298,
data2: 14259,
data3: 17283,
data4: [145, 231, 68, 152, 218, 41, 149, 171],
},
pid: 7u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WNET_DisplayType: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 3736970298,
data2: 14259,
data3: 17283,
data4: [145, 231, 68, 152, 218, 41, 149, 171],
},
pid: 3u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WNET_LocalName: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 3736970298,
data2: 14259,
data3: 17283,
data4: [145, 231, 68, 152, 218, 41, 149, 171],
},
pid: 5u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WNET_Provider: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 3736970298,
data2: 14259,
data3: 17283,
data4: [145, 231, 68, 152, 218, 41, 149, 171],
},
pid: 8u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WNET_RemoteName: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 3736970298,
data2: 14259,
data3: 17283,
data4: [145, 231, 68, 152, 218, 41, 149, 171],
},
pid: 6u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WNET_Scope: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 3736970298,
data2: 14259,
data3: 17283,
data4: [145, 231, 68, 152, 218, 41, 149, 171],
},
pid: 1u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WNET_Type: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 3736970298,
data2: 14259,
data3: 17283,
data4: [145, 231, 68, 152, 218, 41, 149, 171],
},
pid: 2u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const PKEY_WNET_Usage: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows_sys::core::GUID {
data1: 3736970298,
data2: 14259,
data3: 17283,
data4: [145, 231, 68, 152, 218, 41, 149, 171],
},
pid: 4u32,
};
pub const PNPXAssociation: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3471363273, data2: 20331, data3: 17513, data4: [162, 53, 90, 34, 134, 158, 239, 3] };
pub const PNPXPairingHandler: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3097655618,
data2: 44519,
data3: 16517,
data4: [170, 110, 79, 173, 199, 173, 161, 239],
};
pub const PNPX_INSTALLSTATE_FAILED: u32 = 3u32;
pub const PNPX_INSTALLSTATE_INSTALLED: u32 = 1u32;
pub const PNPX_INSTALLSTATE_INSTALLING: u32 = 2u32;
pub const PNPX_INSTALLSTATE_NOTINSTALLED: u32 = 0u32;
pub type PropertyConstraint = i32;
pub const QC_EQUALS: PropertyConstraint = 0i32;
pub const QC_NOTEQUAL: PropertyConstraint = 1i32;
pub const QC_LESSTHAN: PropertyConstraint = 2i32;
pub const QC_LESSTHANOREQUAL: PropertyConstraint = 3i32;
pub const QC_GREATERTHAN: PropertyConstraint = 4i32;
pub const QC_GREATERTHANOREQUAL: PropertyConstraint = 5i32;
pub const QC_STARTSWITH: PropertyConstraint = 6i32;
pub const QC_EXISTS: PropertyConstraint = 7i32;
pub const QC_DOESNOTEXIST: PropertyConstraint = 8i32;
pub const QC_CONTAINS: PropertyConstraint = 9i32;
pub const PropertyStore: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3833161040, data2: 57185, data3: 17547, data4: [145, 147, 19, 252, 19, 65, 177, 99] };
pub const PropertyStoreCollection: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3990052905, data2: 55123, data3: 18530, data4: [170, 91, 91, 204, 173, 42, 77, 41] };
pub type QueryCategoryType = i32;
pub const QCT_PROVIDER: QueryCategoryType = 0i32;
pub const QCT_LAYERED: QueryCategoryType = 1i32;
pub type QueryUpdateAction = i32;
pub const QUA_ADD: QueryUpdateAction = 0i32;
pub const QUA_REMOVE: QueryUpdateAction = 1i32;
pub const QUA_CHANGE: QueryUpdateAction = 2i32;
pub const SID_DeviceDisplayStatusManager: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4120552787, data2: 33545, data3: 18122, data4: [151, 54, 26, 195, 198, 45, 96, 49] };
pub const SID_EnumDeviceFunction: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 333507042,
data2: 50170,
data3: 20028,
data4: [144, 110, 100, 80, 47, 164, 220, 149],
};
pub const SID_EnumInterface: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1089122489,
data2: 19839,
data3: 19283,
data4: [163, 52, 21, 129, 221, 144, 65, 244],
};
pub const SID_FDPairingHandler: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 943417850,
data2: 21638,
data3: 18906,
data4: [145, 245, 214, 60, 36, 200, 233, 208],
};
pub const SID_FunctionDiscoveryProviderRefresh: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 726449609, data2: 12740, data3: 16596, data4: [166, 45, 119, 42, 161, 116, 237, 82] };
pub const SID_PNPXAssociation: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3471363273, data2: 20331, data3: 17513, data4: [162, 53, 90, 34, 134, 158, 239, 3] };
pub const SID_PNPXPropertyStore: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2825203889,
data2: 21551,
data3: 17311,
data4: [183, 28, 176, 117, 107, 19, 103, 122],
};
pub const SID_PNPXServiceCollection: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1134461166,
data2: 41495,
data3: 18194,
data4: [159, 166, 222, 171, 217, 194, 167, 39],
};
pub const SID_PnpProvider: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2164340366, data2: 51899, data3: 17446, data4: [172, 255, 150, 196, 16, 129, 32, 0] };
pub const SID_UPnPActivator: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 218982123, data2: 53108, data3: 16740, data4: [181, 47, 8, 52, 70, 114, 221, 70] };
pub const SID_UninstallDeviceFunction: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3374339694,
data2: 22129,
data3: 17558,
data4: [128, 37, 191, 11, 137, 189, 68, 205],
};
pub const SID_UnpairProvider: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2309292796, data2: 34171, data3: 18072, data4: [160, 183, 2, 113, 146, 0, 47, 158] };
pub type SystemVisibilityFlags = i32;
pub const SVF_SYSTEM: SystemVisibilityFlags = 0i32;
pub const SVF_USER: SystemVisibilityFlags = 1i32;
|
//! A general utility for retrying futures with a configurable backoff and error filter.
use std::{
future::Future,
num::{NonZeroU64, NonZeroUsize},
result::Result,
time::Duration,
};
use tokio_retry::{strategy::ExponentialBackoff, Retry as TokioRetry, RetryIf as TokioRetryIf};
pub struct Retry<T, E, Fut, FutureFactory>
where
Fut: Future<Output = Result<T, E>>,
FutureFactory: FnMut() -> Fut,
{
future_factory: FutureFactory,
strategy: Strategy,
}
impl<T, E, Fut, FutureFactory> Retry<T, E, Fut, FutureFactory>
where
Fut: Future<Output = Result<T, E>>,
FutureFactory: FnMut() -> Fut,
{
/// Create an exponential [`Retry`] utility for a future which is created by `future_factory`
/// with initial backoff of `base_secs` seconds.
///
/// `Nth` backoff is equal to `base_secs ^ N` seconds.
pub fn exponential(future_factory: FutureFactory, base_secs: NonZeroU64) -> Self {
Self {
future_factory,
strategy: Strategy {
base_secs,
factor: NonZeroU64::new(1).unwrap(),
max_delay: None,
max_num_retries: None,
},
}
}
/// Multiply backoff by this factor.
///
/// `Nth` backoff is then equal to `base_secs ^ N * factor` seconds.
pub fn factor(mut self, factor: NonZeroU64) -> Self {
self.strategy.factor = factor;
self
}
/// Saturate backoff at `max_delay`.
pub fn max_delay(mut self, max_delay: Duration) -> Self {
self.strategy.max_delay = Some(max_delay);
self
}
/// Limit the number of retries to `max_num_retries`.
pub fn max_num_retries(mut self, max_num_retries: NonZeroUsize) -> Self {
self.strategy.max_num_retries = Some(max_num_retries);
self
}
/// Retry the future on any `Err()` until an `Ok()` value is returned by the future.
pub async fn on_any_err(self) -> Result<T, E> {
TokioRetry::spawn(MaybeLimited::from(self.strategy), self.future_factory).await
}
/// Retry the future on every error that meets `retry_condition` until the future returns:
/// - an `Ok()` value
/// - an `Err()` value that does not meet the `retry_condition`.
pub async fn when<RetryCondition>(self, retry_condition: RetryCondition) -> Result<T, E>
where
RetryCondition: FnMut(&E) -> bool,
{
TokioRetryIf::spawn(
MaybeLimited::from(self.strategy),
self.future_factory,
retry_condition,
)
.await
}
}
struct Strategy {
base_secs: NonZeroU64,
factor: NonZeroU64,
max_delay: Option<Duration>,
max_num_retries: Option<NonZeroUsize>,
}
enum MaybeLimited {
Limited(std::iter::Take<ExponentialBackoff>),
Unlimited(ExponentialBackoff),
}
impl std::iter::Iterator for MaybeLimited {
type Item = std::time::Duration;
fn next(&mut self) -> Option<Self::Item> {
match self {
MaybeLimited::Limited(x) => x.next(),
MaybeLimited::Unlimited(x) => x.next(),
}
}
}
impl From<Strategy> for MaybeLimited {
fn from(s: Strategy) -> Self {
// We use milliseconds in tests
#[cfg(test)]
const FACTOR: u32 = 1;
// We use seconds in production
#[cfg(not(test))]
const FACTOR: u32 = 1000;
let backoff = ExponentialBackoff::from_millis(s.base_secs.get()).factor(
s.factor
.get()
.checked_mul(FACTOR as u64)
.unwrap_or(u64::MAX),
);
let backoff = match s.max_delay {
Some(max_delay) => {
backoff.max_delay(max_delay.checked_mul(FACTOR).unwrap_or(Duration::MAX))
}
None => backoff,
};
match s.max_num_retries {
Some(num_retries) => MaybeLimited::Limited(backoff.take(num_retries.get())),
None => MaybeLimited::Unlimited(backoff),
}
}
}
#[cfg(test)]
mod tests {
use super::Retry;
use std::{
cell::RefCell,
iter::{IntoIterator, Iterator},
num::{NonZeroU64, NonZeroUsize},
result::Result,
time::{Duration, Instant},
};
#[derive(Copy, Clone, Debug, PartialEq)]
enum Failure {
Retryable,
Fatal,
}
#[derive(Copy, Clone, Debug)]
struct Success;
struct Uut<I>
where
I: IntoIterator<Item = Result<Success, Failure>>,
{
seq: RefCell<I::IntoIter>,
call_count: RefCell<usize>,
now: RefCell<Instant>,
last: RefCell<Duration>,
}
impl<I> Uut<I>
where
I: IntoIterator<Item = Result<Success, Failure>> + Clone,
{
fn new(i: I) -> Self {
Self {
seq: RefCell::new(i.into_iter()),
call_count: RefCell::new(0),
now: RefCell::new(Instant::now()),
last: RefCell::new(Duration::default()),
}
}
pub async fn do_work(&self) -> Result<Success, Failure> {
*self.call_count.borrow_mut() += 1;
*self.last.borrow_mut() = self.now.borrow_mut().elapsed();
*self.now.borrow_mut() = Instant::now();
self.seq.borrow_mut().next().unwrap()
}
fn call_count(&self) -> usize {
let call_counter = *self.call_count.borrow();
call_counter
}
pub fn expect_last_delay(&self, expected: u64) -> Result<u64, u64> {
let real = self.last.borrow().as_millis() as u64;
if real > expected - expected / 8 && real < expected + expected / 8 {
Ok(real)
} else {
Err(real)
}
}
}
mod unconditional {
use super::*;
#[tokio::test]
async fn until_ok() {
let uut = Uut::new([
Err(Failure::Retryable),
Err(Failure::Fatal),
Err(Failure::Fatal),
Ok(Success),
]);
Retry::exponential(|| uut.do_work(), NonZeroU64::new(2).unwrap())
.factor(NonZeroU64::new(10).unwrap())
.on_any_err()
.await
.unwrap();
assert_eq!(uut.call_count(), 4);
// ~80ms (2^3*10)
uut.expect_last_delay(80).unwrap();
}
#[tokio::test]
async fn until_fatal() {
let uut = Uut::new([
Err(Failure::Retryable),
Err(Failure::Retryable),
Err(Failure::Retryable),
Err(Failure::Fatal),
Ok(Success),
]);
assert_eq!(
Retry::exponential(|| uut.do_work(), NonZeroU64::new(2).unwrap())
.factor(NonZeroU64::new(10).unwrap())
.when(|e| *e == Failure::Retryable)
.await
.unwrap_err(),
Failure::Fatal
);
assert_eq!(uut.call_count(), 4);
// ~80ms (2^3*10)
uut.expect_last_delay(80).unwrap();
}
#[tokio::test]
async fn saturate_delay() {
let uut = Uut::new([Err(Failure::Fatal); 10]);
Retry::exponential(|| uut.do_work(), NonZeroU64::new(2).unwrap())
.max_delay(Duration::from_millis(128))
.max_num_retries(NonZeroUsize::new(9).unwrap())
.on_any_err()
.await
.unwrap_err();
assert_eq!(uut.call_count(), 10);
// If not capped, would be ~512ms (2^9*1)
uut.expect_last_delay(128).unwrap();
}
#[tokio::test]
async fn reach_max_num_retries() {
let uut = Uut::new([
Err(Failure::Retryable),
Err(Failure::Retryable),
Err(Failure::Retryable),
Err(Failure::Fatal),
Ok(Success),
]);
assert_eq!(
Retry::exponential(|| uut.do_work(), NonZeroU64::new(1).unwrap())
.max_num_retries(NonZeroUsize::new(3).unwrap())
.on_any_err()
.await
.unwrap_err(),
Failure::Fatal
);
// Retry limit of 3 means 4 tries altogether
assert_eq!(uut.call_count(), 4);
}
}
mod conditional {
use super::*;
#[tokio::test]
async fn until_fatal() {
let uut = Uut::new([
Err(Failure::Retryable),
Err(Failure::Retryable),
Err(Failure::Retryable),
Err(Failure::Fatal),
Ok(Success),
]);
assert_eq!(
Retry::exponential(|| uut.do_work(), NonZeroU64::new(2).unwrap())
.factor(NonZeroU64::new(10).unwrap())
.when(|e| *e == Failure::Retryable)
.await
.unwrap_err(),
Failure::Fatal
);
assert_eq!(uut.call_count(), 4);
// ~80ms (2^3*10)
uut.expect_last_delay(80).unwrap();
}
#[tokio::test]
async fn until_ok() {
let uut = Uut::new([
Err(Failure::Retryable),
Err(Failure::Retryable),
Err(Failure::Retryable),
Ok(Success),
Err(Failure::Fatal),
]);
Retry::exponential(|| uut.do_work(), NonZeroU64::new(2).unwrap())
.factor(NonZeroU64::new(10).unwrap())
.when(|e| *e == Failure::Retryable)
.await
.unwrap();
// ~80ms (2^3*10)
assert_eq!(uut.call_count(), 4);
uut.expect_last_delay(80).unwrap();
}
#[tokio::test]
async fn saturate_delay() {
let uut = Uut::new([Err(Failure::Retryable); 10]);
Retry::exponential(|| uut.do_work(), NonZeroU64::new(2).unwrap())
.max_delay(Duration::from_millis(128))
.max_num_retries(NonZeroUsize::new(9).unwrap())
.when(|e| *e == Failure::Retryable)
.await
.unwrap_err();
assert_eq!(uut.call_count(), 10);
uut.expect_last_delay(128).unwrap();
}
#[tokio::test]
async fn reach_max_num_retries() {
let uut = Uut::new([
Err(Failure::Retryable),
Err(Failure::Retryable),
Err(Failure::Retryable),
Err(Failure::Fatal),
]);
assert_eq!(
Retry::exponential(|| uut.do_work(), NonZeroU64::new(1).unwrap())
.max_num_retries(NonZeroUsize::new(2).unwrap())
.when(|e| *e == Failure::Retryable)
.await
.unwrap_err(),
Failure::Retryable
);
// Retry limit of 2 means 3 tries altogether
assert_eq!(uut.call_count(), 3);
}
}
}
|
pub fn example8()
{
let rand_array = [1, 2, 3];
xprintln!("First element: {}", rand_array[0]);
xprintln!("Array length: {}", rand_array.len());
xprintln!("Second 2 : {:?}", &rand_array[1..3]);
} |
#[doc = "Reader of register TIMINGR"]
pub type R = crate::R<u32, super::TIMINGR>;
#[doc = "Writer for register TIMINGR"]
pub type W = crate::W<u32, super::TIMINGR>;
#[doc = "Register TIMINGR `reset()`'s with value 0"]
impl crate::ResetValue for super::TIMINGR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `SCLL`"]
pub type SCLL_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SCLL`"]
pub struct SCLL_W<'a> {
w: &'a mut W,
}
impl<'a> SCLL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0xff) | ((value as u32) & 0xff);
self.w
}
}
#[doc = "Reader of field `SCLH`"]
pub type SCLH_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SCLH`"]
pub struct SCLH_W<'a> {
w: &'a mut W,
}
impl<'a> SCLH_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xff << 8)) | (((value as u32) & 0xff) << 8);
self.w
}
}
#[doc = "Reader of field `SDADEL`"]
pub type SDADEL_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SDADEL`"]
pub struct SDADEL_W<'a> {
w: &'a mut W,
}
impl<'a> SDADEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 16)) | (((value as u32) & 0x0f) << 16);
self.w
}
}
#[doc = "Reader of field `SCLDEL`"]
pub type SCLDEL_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SCLDEL`"]
pub struct SCLDEL_W<'a> {
w: &'a mut W,
}
impl<'a> SCLDEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 20)) | (((value as u32) & 0x0f) << 20);
self.w
}
}
#[doc = "Reader of field `PRESC`"]
pub type PRESC_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `PRESC`"]
pub struct PRESC_W<'a> {
w: &'a mut W,
}
impl<'a> PRESC_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 28)) | (((value as u32) & 0x0f) << 28);
self.w
}
}
impl R {
#[doc = "Bits 0:7 - SCL low period (master mode) This field is used to generate the SCL low period in master mode. tSCLL = (SCLL+1) x tPRESC Note: SCLL is also used to generate tBUF and tSU:STA timings."]
#[inline(always)]
pub fn scll(&self) -> SCLL_R {
SCLL_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 8:15 - SCL high period (master mode) This field is used to generate the SCL high period in master mode. tSCLH = (SCLH+1) x tPRESC Note: SCLH is also used to generate tSU:STO and tHD:STA timing."]
#[inline(always)]
pub fn sclh(&self) -> SCLH_R {
SCLH_R::new(((self.bits >> 8) & 0xff) as u8)
}
#[doc = "Bits 16:19 - Data hold time This field is used to generate the delay tSDADEL between SCL falling edge and SDA edge. In master mode and in slave mode with NOSTRETCH = 0, the SCL line is stretched low during tSDADEL. tSDADEL= SDADEL x tPRESC Note: SDADEL is used to generate tHD:DAT timing."]
#[inline(always)]
pub fn sdadel(&self) -> SDADEL_R {
SDADEL_R::new(((self.bits >> 16) & 0x0f) as u8)
}
#[doc = "Bits 20:23 - Data setup time This field is used to generate a delay tSCLDEL between SDA edge and SCL rising edge. In master mode and in slave mode with NOSTRETCH = 0, the SCL line is stretched low during tSCLDEL. tSCLDEL = (SCLDEL+1) x tPRESC Note: tSCLDEL is used to generate tSU:DAT timing."]
#[inline(always)]
pub fn scldel(&self) -> SCLDEL_R {
SCLDEL_R::new(((self.bits >> 20) & 0x0f) as u8)
}
#[doc = "Bits 28:31 - Timing prescaler This field is used to prescale I2CCLK in order to generate the clock period tPRESC used for data setup and hold counters (refer to I2C timings on page9) and for SCL high and low level counters (refer to I2C master initialization on page24). tPRESC = (PRESC+1) x tI2CCLK"]
#[inline(always)]
pub fn presc(&self) -> PRESC_R {
PRESC_R::new(((self.bits >> 28) & 0x0f) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - SCL low period (master mode) This field is used to generate the SCL low period in master mode. tSCLL = (SCLL+1) x tPRESC Note: SCLL is also used to generate tBUF and tSU:STA timings."]
#[inline(always)]
pub fn scll(&mut self) -> SCLL_W {
SCLL_W { w: self }
}
#[doc = "Bits 8:15 - SCL high period (master mode) This field is used to generate the SCL high period in master mode. tSCLH = (SCLH+1) x tPRESC Note: SCLH is also used to generate tSU:STO and tHD:STA timing."]
#[inline(always)]
pub fn sclh(&mut self) -> SCLH_W {
SCLH_W { w: self }
}
#[doc = "Bits 16:19 - Data hold time This field is used to generate the delay tSDADEL between SCL falling edge and SDA edge. In master mode and in slave mode with NOSTRETCH = 0, the SCL line is stretched low during tSDADEL. tSDADEL= SDADEL x tPRESC Note: SDADEL is used to generate tHD:DAT timing."]
#[inline(always)]
pub fn sdadel(&mut self) -> SDADEL_W {
SDADEL_W { w: self }
}
#[doc = "Bits 20:23 - Data setup time This field is used to generate a delay tSCLDEL between SDA edge and SCL rising edge. In master mode and in slave mode with NOSTRETCH = 0, the SCL line is stretched low during tSCLDEL. tSCLDEL = (SCLDEL+1) x tPRESC Note: tSCLDEL is used to generate tSU:DAT timing."]
#[inline(always)]
pub fn scldel(&mut self) -> SCLDEL_W {
SCLDEL_W { w: self }
}
#[doc = "Bits 28:31 - Timing prescaler This field is used to prescale I2CCLK in order to generate the clock period tPRESC used for data setup and hold counters (refer to I2C timings on page9) and for SCL high and low level counters (refer to I2C master initialization on page24). tPRESC = (PRESC+1) x tI2CCLK"]
#[inline(always)]
pub fn presc(&mut self) -> PRESC_W {
PRESC_W { w: self }
}
}
|
use bincode::ErrorKind as BincodeError;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
IOError(std::io::Error),
BincodeError(BincodeError),
}
impl PartialEq for Error {
fn eq(&self, other: &Self) -> bool {
// note: only test the types
matches!(
(self, other),
(Self::IOError(_), Self::IOError(_)) | (Self::BincodeError(_), Self::BincodeError(_)),
)
}
}
impl<T> From<Box<T>> for Error
where
T: Into<Self>,
{
fn from(error: Box<T>) -> Self {
(*error).into()
}
}
impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Self {
Self::IOError(error)
}
}
impl From<BincodeError> for Error {
fn from(error: BincodeError) -> Self {
Self::BincodeError(error)
}
}
|
// We are at the root of the "crate"
// First we define a module
mod front_of_house {
// We can have child modules
pub mod hosting {
pub fn add_to_waitlist() {}
fn seat_at_table() {}
}
mod serving {
fn take_order() {}
fn serve_order() {}
fn take_payment() {}
}
}
// By default everything is private, we need to expose modules and methods to make them accessible
// We publish a public function
pub fn eat_at_restaurant() {
// Modules' methods can be called with an absolute path
crate::front_of_house::hosting::add_to_waitlist();
// or a relative path
front_of_house::hosting::add_to_waitlist();
}
// We can also call a parent function
fn serve_order() {}
mod back_of_house {
fn fix_incorrect_order() {
cook_order();
// Super is equivalent to ..
super::serve_order();
}
fn cook_order() {}
}
mod back_of_house2 {
pub struct Breakfast {
pub toast: String,
seasonal_fruit: String,
}
impl Breakfast {
// The constructor is required because we have a private field
pub fn summer(toast: &str) -> Breakfast {
Breakfast {
toast: String::from(toast),
seasonal_fruit: String::from("peaches"),
}
}
}
}
pub fn eat_at_restaurant2() {
let mut meal = back_of_house2::Breakfast::summer("Rye");
meal.toast = String::from("Wheat");
println!("I'd like {} toast please", meal.toast);
// The next line won't compile if we uncomment it; we're not allowed
// to see or modify the seasonal fruit that comes with the meal
// meal.seasonal_fruit = String::from("blueberries");
}
// All fields are public, no need to have a constructor
mod back_of_house3 {
pub enum Appetizer {
Soup,
Salad,
}
}
pub fn eat_at_restaurant3() {
let order1 = back_of_house3::Appetizer::Soup;
let order2 = back_of_house3::Appetizer::Salad;
}
// We can "import" in a variable a module
mod front_of_house2 {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
use crate::front_of_house2::hosting;
pub fn eat_at_restaurant4() {
hosting::add_to_waitlist();
hosting::add_to_waitlist();
hosting::add_to_waitlist();
}
// We can get access to the function
mod front_of_house3 {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
use crate::front_of_house3::hosting::add_to_waitlist;
pub fn eat_at_restaurant5() {
add_to_waitlist();
add_to_waitlist();
add_to_waitlist();
}
// We can rename the "package"
use std::fmt::Result;
use std::io::Result as IoResult;
// To rename an import and export it
mod front_of_house4 {
pub mod hosting2 {
pub fn add_to_waitlist() {}
}
}
pub use crate::front_of_house4::hosting2;
pub fn eat_at_restaurant6() {
hosting2::add_to_waitlist();
hosting2::add_to_waitlist();
hosting2::add_to_waitlist();
}
// To import a crate from crates.io, add `rand = "0.5.5"` to the Cargo.toml file
use rand::Rng;
println!("{}", rand::thread_rng().gen_range(1, 101));
// Imports from the same crate can be grouped
use std::{cmp::Ordering, io};
// Those lines are equivalent to the other one below
use std::io;
use std::io::Write;
use std::io::{self, Write};
// And to bring everything from the package
use std::collections::*;
|
pub mod ebo;
pub mod vao;
pub mod vbo;
pub use self::ebo::EBO;
pub use self::vao::VAO;
pub use self::vbo::VBO;
use crate::camera::Camera;
use crate::shader::Shader;
use crate::texture::Texture;
use cgmath::{Matrix4, Quaternion, Vector2, Vector3};
use glad_gl::gl;
#[derive(Clone)]
pub struct Vertex {
pub position: Vector3<f32>,
pub normal: Vector3<f32>,
pub color: Vector3<f32>,
pub tex_uv: Vector2<f32>,
}
impl Vertex {
pub fn mem_size() -> usize {
return std::mem::size_of::<Vertex>();
}
}
pub struct Mesh {
_vertices: Vec<Vertex>,
_indices: Vec<gl::GLuint>,
_textures: Vec<Texture>,
vao: VAO,
vbo: VBO,
ebo: EBO,
}
impl Mesh {
pub fn create(
vertices: &Vec<Vertex>,
indices: &Vec<gl::GLuint>,
textures: &Vec<Texture>,
) -> Mesh {
let new_mesh = Mesh {
_vertices: vertices.clone(),
_indices: indices.clone(),
_textures: textures.clone(),
vao: VAO::create(),
vbo: VBO::create(&vertices),
ebo: EBO::create(&indices),
};
new_mesh.vao.bind();
new_mesh.ebo.bind();
//Attribs
//Position
new_mesh
.vao
.link_attrib(&new_mesh.vbo, 0, 3, gl::GL_FLOAT, Vertex::mem_size(), 0);
new_mesh.vao.link_attrib(
&new_mesh.vbo,
1,
3,
gl::GL_FLOAT,
Vertex::mem_size(),
3 * std::mem::size_of::<f32>(),
);
new_mesh.vao.link_attrib(
&new_mesh.vbo,
2,
3,
gl::GL_FLOAT,
Vertex::mem_size(),
6 * std::mem::size_of::<f32>(),
);
new_mesh.vao.link_attrib(
&new_mesh.vbo,
3,
2,
gl::GL_FLOAT,
Vertex::mem_size(),
9 * std::mem::size_of::<f32>(),
);
new_mesh.vao.unbind();
new_mesh.vbo.unbind();
new_mesh.ebo.unbind();
new_mesh
}
pub fn draw(
&self,
shader: &Shader,
camera: &Camera,
matrix: Matrix4<f32>,
translation: Vector3<f32>,
rotation: Quaternion<f32>,
scale: Vector3<f32>,
) {
shader.use_shader();
self.vao.bind();
let mut num_diffuse = 0;
let mut num_spec = 0;
for (i, texture) in self._textures.iter().enumerate() {
let mut num = String::new();
let tex_type = &texture.texture_type;
if tex_type == "diffuse" {
num = num_diffuse.to_string();
num_diffuse += 1;
} else if tex_type == "specular" {
num = num_spec.to_string();
num_spec += 1;
}
let uniform_name = String::from(tex_type) + #
shader.set_1i(&uniform_name, i as i32);
texture.bind();
}
shader.set_vec3f("camPos", camera.position);
shader.set_mat4f("camMatrix", camera.camera_matrix);
let trans = Matrix4::from_translation(translation);
let rot = Matrix4::from(rotation);
let sca = Matrix4::from_nonuniform_scale(scale.x, scale.y, scale.z);
shader.set_mat4f("translation", trans);
shader.set_mat4f("rotation", rot);
shader.set_mat4f("scale", sca);
shader.set_mat4f("model", matrix);
unsafe {
gl::DrawElements(
gl::GL_TRIANGLES,
self._indices.len() as gl::GLint,
gl::GL_UNSIGNED_INT,
0 as *const std::os::raw::c_void,
);
}
}
pub fn cleanup(&self) {
self.vao.delete();
self.vbo.delete();
self.ebo.delete();
}
}
|
use yew::prelude::*;
use yew::services::ConsoleService;
const MATRIX_WIDTH: usize = 16;
const MATRIX_HEIGHT: usize = 16;
const PANEL_WIDTH: usize = 6;
const PANEL_HEIGHT: usize = 2;
const LED_COUNT: usize = MATRIX_WIDTH * MATRIX_HEIGHT * PANEL_WIDTH * PANEL_HEIGHT;
enum Msg {
CellClicked(u16),
SwitchSegment(usize),
}
struct Model<T> {
// `ComponentLink` is like a reference to a component.
// It can be used to send messages to the component
link: ComponentLink<Model<bool>>,
value: i64,
leds: [T; LED_COUNT],
panel_horizontal_offset: usize,
panel_vertical_offset: usize,
current_segment: usize,
}
impl Component for Model<bool> {
type Message = Msg;
type Properties = ();
fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
value: 0,
leds: [false; LED_COUNT],
panel_horizontal_offset: 0,
panel_vertical_offset: 0,
current_segment: 1,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::CellClicked(x) => {
self.value += 1;
let y = x as usize;
self.leds[y] = !self.leds[y];
ConsoleService::log(&x.to_string());
if self.leds[y] == false {
ConsoleService::log("false");
}
else {
ConsoleService::log("true");
}
let finalx = x as usize % MATRIX_WIDTH + MATRIX_WIDTH * self.panel_horizontal_offset * MATRIX_WIDTH;
let finaly = x as usize / MATRIX_WIDTH + self.panel_vertical_offset * MATRIX_HEIGHT;
ConsoleService::log(&finalx.to_string());
ConsoleService::log(&finaly.to_string());
//ConsoleService::log(&self.panel_vertical_offset.to_string());
//ConsoleService::log(&LED_COUNT.to_string());
// the value has changed so we need to
// re-render for it to appear on the page
false
}
Msg::SwitchSegment(x) => {
self.current_segment = x;
self.panel_horizontal_offset = (x - 1) % PANEL_WIDTH;
self.panel_vertical_offset = (x - 1) / PANEL_WIDTH;
ConsoleService::log(&x.to_string());
ConsoleService::log(&self.panel_horizontal_offset.to_string());
ConsoleService::log(&self.panel_vertical_offset.to_string());
true
}
}
}
fn change(&mut self, _props: Self::Properties) -> ShouldRender {
// Should only return "true" if new properties are different to
// previously received properties.
// This component has no properties so we will always return "false".
false
}
fn view(&self) -> Html {
let hiddencells = (0..256).map(|i| self.view_hidden_checkbox(i));
let cells = (0..256).map(|i| self.view_minesweeper_cell(i));
let buttons_top = (1..7).map(|i| self.section_buttons(i));
let buttons_bottom = (7..13).map(|i| self.section_buttons(i));
html! {
<div>
{ for hiddencells }
<div id="board" class="grid">
{ for cells }
</div>
<div class="buttons">
{for buttons_top}
</div>
<div class="buttons">
{for buttons_bottom}
</div>
</div>
}
}
}
impl Model<bool> {
fn view_hidden_checkbox(&self, idx: u16) -> Html{
let maybe_id = Some(format!("c{}", idx));
let name_id = Some(format!("c{}", idx));
html!{
<input type="checkbox" id=maybe_id name=name_id onclick=self.link.callback(move |_| Msg::CellClicked(idx)) />
}
}
fn view_minesweeper_cell(&self, idx: usize) -> Html {
let maybe_id = Some(format!("s{}", idx));
let for_id = Some(format!("c{}", idx));
html!{
<label id=maybe_id class="grid__item" for=for_id></label>
}
}
fn selected_button(&self, idx: usize) -> Option<String>{
if idx == self.current_segment {
Some("selected".to_string())
}
else {
None
}
}
fn section_buttons(&self, idx: usize) -> Html {
let buttonid = Some(format!("b{}", idx));
html!{
<button id=buttonid class=self.selected_button(idx) onclick=self.link.callback(move |_| Msg::SwitchSegment(idx) ) >{idx.to_string()}</button>
}
}
}
fn main() {
yew::start_app::<Model<bool>>();
} |
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_catalog::table_context::TableContext;
use common_exception::Result;
use crate::optimizer::distributed::topk::TopK;
use crate::optimizer::property::require_property;
use crate::optimizer::Distribution;
use crate::optimizer::RelExpr;
use crate::optimizer::RequiredProperty;
use crate::optimizer::SExpr;
use crate::plans::Exchange;
use crate::plans::RelOperator;
pub fn optimize_distributed_query(ctx: Arc<dyn TableContext>, s_expr: &SExpr) -> Result<SExpr> {
let required = RequiredProperty {
distribution: Distribution::Any,
};
let mut result = require_property(ctx, &required, s_expr)?;
result = push_down_topk_to_merge(&result, None)?;
let rel_expr = RelExpr::with_s_expr(&result);
let physical_prop = rel_expr.derive_physical_prop()?;
let root_required = RequiredProperty {
distribution: Distribution::Serial,
};
if !root_required.satisfied_by(&physical_prop) {
// Manually enforce serial distribution.
result = SExpr::create_unary(Exchange::Merge.into(), result);
}
Ok(result)
}
// Traverse the SExpr tree to find top_k, if find, push down it to Exchange::Merge
fn push_down_topk_to_merge(s_expr: &SExpr, mut top_k: Option<TopK>) -> Result<SExpr> {
if let RelOperator::Exchange(Exchange::Merge) = s_expr.plan {
// A quick fix for Merge child is aggregate.
// Todo: consider to push down topk to the above of aggregate.
if let RelOperator::Aggregate(_) = s_expr.child(0)?.plan {
return Ok(s_expr.clone());
}
if let Some(top_k) = top_k {
let mut child = s_expr.children[0].clone();
child = SExpr::create_unary(top_k.sort.into(), child.clone());
let children = if s_expr.children.len() == 2 {
vec![child, s_expr.children[1].clone()]
} else {
vec![child]
};
return Ok(s_expr.replace_children(children));
}
}
let mut s_expr_children = vec![];
for child in s_expr.children.iter() {
top_k = None;
if let RelOperator::Sort(sort) = &child.plan {
if sort.limit.is_some() {
top_k = Some(TopK { sort: sort.clone() });
}
}
let mut new_children = vec![];
for child_child in child.children.iter() {
new_children.push(push_down_topk_to_merge(child_child, top_k.clone())?);
}
s_expr_children.push(child.replace_children(new_children));
}
Ok(s_expr.replace_children(s_expr_children))
}
|
#[doc = "Reader of register MPCBB1_VCTR25"]
pub type R = crate::R<u32, super::MPCBB1_VCTR25>;
#[doc = "Writer for register MPCBB1_VCTR25"]
pub type W = crate::W<u32, super::MPCBB1_VCTR25>;
#[doc = "Register MPCBB1_VCTR25 `reset()`'s with value 0xffff_ffff"]
impl crate::ResetValue for super::MPCBB1_VCTR25 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0xffff_ffff
}
}
#[doc = "Reader of field `B800`"]
pub type B800_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B800`"]
pub struct B800_W<'a> {
w: &'a mut W,
}
impl<'a> B800_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `B801`"]
pub type B801_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B801`"]
pub struct B801_W<'a> {
w: &'a mut W,
}
impl<'a> B801_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `B802`"]
pub type B802_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B802`"]
pub struct B802_W<'a> {
w: &'a mut W,
}
impl<'a> B802_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `B803`"]
pub type B803_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B803`"]
pub struct B803_W<'a> {
w: &'a mut W,
}
impl<'a> B803_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `B804`"]
pub type B804_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B804`"]
pub struct B804_W<'a> {
w: &'a mut W,
}
impl<'a> B804_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `B805`"]
pub type B805_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B805`"]
pub struct B805_W<'a> {
w: &'a mut W,
}
impl<'a> B805_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `B806`"]
pub type B806_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B806`"]
pub struct B806_W<'a> {
w: &'a mut W,
}
impl<'a> B806_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `B807`"]
pub type B807_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B807`"]
pub struct B807_W<'a> {
w: &'a mut W,
}
impl<'a> B807_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Reader of field `B808`"]
pub type B808_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B808`"]
pub struct B808_W<'a> {
w: &'a mut W,
}
impl<'a> B808_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `B809`"]
pub type B809_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B809`"]
pub struct B809_W<'a> {
w: &'a mut W,
}
impl<'a> B809_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `B810`"]
pub type B810_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B810`"]
pub struct B810_W<'a> {
w: &'a mut W,
}
impl<'a> B810_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `B811`"]
pub type B811_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B811`"]
pub struct B811_W<'a> {
w: &'a mut W,
}
impl<'a> B811_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Reader of field `B812`"]
pub type B812_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B812`"]
pub struct B812_W<'a> {
w: &'a mut W,
}
impl<'a> B812_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `B813`"]
pub type B813_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B813`"]
pub struct B813_W<'a> {
w: &'a mut W,
}
impl<'a> B813_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Reader of field `B814`"]
pub type B814_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B814`"]
pub struct B814_W<'a> {
w: &'a mut W,
}
impl<'a> B814_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Reader of field `B815`"]
pub type B815_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B815`"]
pub struct B815_W<'a> {
w: &'a mut W,
}
impl<'a> B815_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Reader of field `B816`"]
pub type B816_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B816`"]
pub struct B816_W<'a> {
w: &'a mut W,
}
impl<'a> B816_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `B817`"]
pub type B817_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B817`"]
pub struct B817_W<'a> {
w: &'a mut W,
}
impl<'a> B817_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `B818`"]
pub type B818_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B818`"]
pub struct B818_W<'a> {
w: &'a mut W,
}
impl<'a> B818_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Reader of field `B819`"]
pub type B819_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B819`"]
pub struct B819_W<'a> {
w: &'a mut W,
}
impl<'a> B819_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
#[doc = "Reader of field `B820`"]
pub type B820_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B820`"]
pub struct B820_W<'a> {
w: &'a mut W,
}
impl<'a> B820_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Reader of field `B821`"]
pub type B821_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B821`"]
pub struct B821_W<'a> {
w: &'a mut W,
}
impl<'a> B821_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21);
self.w
}
}
#[doc = "Reader of field `B822`"]
pub type B822_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B822`"]
pub struct B822_W<'a> {
w: &'a mut W,
}
impl<'a> B822_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22);
self.w
}
}
#[doc = "Reader of field `B823`"]
pub type B823_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B823`"]
pub struct B823_W<'a> {
w: &'a mut W,
}
impl<'a> B823_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23);
self.w
}
}
#[doc = "Reader of field `B824`"]
pub type B824_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B824`"]
pub struct B824_W<'a> {
w: &'a mut W,
}
impl<'a> B824_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Reader of field `B825`"]
pub type B825_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B825`"]
pub struct B825_W<'a> {
w: &'a mut W,
}
impl<'a> B825_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "Reader of field `B826`"]
pub type B826_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B826`"]
pub struct B826_W<'a> {
w: &'a mut W,
}
impl<'a> B826_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26);
self.w
}
}
#[doc = "Reader of field `B827`"]
pub type B827_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B827`"]
pub struct B827_W<'a> {
w: &'a mut W,
}
impl<'a> B827_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27);
self.w
}
}
#[doc = "Reader of field `B828`"]
pub type B828_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B828`"]
pub struct B828_W<'a> {
w: &'a mut W,
}
impl<'a> B828_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
#[doc = "Reader of field `B829`"]
pub type B829_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B829`"]
pub struct B829_W<'a> {
w: &'a mut W,
}
impl<'a> B829_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
#[doc = "Reader of field `B830`"]
pub type B830_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B830`"]
pub struct B830_W<'a> {
w: &'a mut W,
}
impl<'a> B830_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30);
self.w
}
}
#[doc = "Reader of field `B831`"]
pub type B831_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B831`"]
pub struct B831_W<'a> {
w: &'a mut W,
}
impl<'a> B831_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bit 0 - B800"]
#[inline(always)]
pub fn b800(&self) -> B800_R {
B800_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - B801"]
#[inline(always)]
pub fn b801(&self) -> B801_R {
B801_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - B802"]
#[inline(always)]
pub fn b802(&self) -> B802_R {
B802_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - B803"]
#[inline(always)]
pub fn b803(&self) -> B803_R {
B803_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - B804"]
#[inline(always)]
pub fn b804(&self) -> B804_R {
B804_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - B805"]
#[inline(always)]
pub fn b805(&self) -> B805_R {
B805_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - B806"]
#[inline(always)]
pub fn b806(&self) -> B806_R {
B806_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - B807"]
#[inline(always)]
pub fn b807(&self) -> B807_R {
B807_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - B808"]
#[inline(always)]
pub fn b808(&self) -> B808_R {
B808_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - B809"]
#[inline(always)]
pub fn b809(&self) -> B809_R {
B809_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - B810"]
#[inline(always)]
pub fn b810(&self) -> B810_R {
B810_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - B811"]
#[inline(always)]
pub fn b811(&self) -> B811_R {
B811_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - B812"]
#[inline(always)]
pub fn b812(&self) -> B812_R {
B812_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - B813"]
#[inline(always)]
pub fn b813(&self) -> B813_R {
B813_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - B814"]
#[inline(always)]
pub fn b814(&self) -> B814_R {
B814_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - B815"]
#[inline(always)]
pub fn b815(&self) -> B815_R {
B815_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - B816"]
#[inline(always)]
pub fn b816(&self) -> B816_R {
B816_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - B817"]
#[inline(always)]
pub fn b817(&self) -> B817_R {
B817_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - B818"]
#[inline(always)]
pub fn b818(&self) -> B818_R {
B818_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 19 - B819"]
#[inline(always)]
pub fn b819(&self) -> B819_R {
B819_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 20 - B820"]
#[inline(always)]
pub fn b820(&self) -> B820_R {
B820_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 21 - B821"]
#[inline(always)]
pub fn b821(&self) -> B821_R {
B821_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 22 - B822"]
#[inline(always)]
pub fn b822(&self) -> B822_R {
B822_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 23 - B823"]
#[inline(always)]
pub fn b823(&self) -> B823_R {
B823_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 24 - B824"]
#[inline(always)]
pub fn b824(&self) -> B824_R {
B824_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 25 - B825"]
#[inline(always)]
pub fn b825(&self) -> B825_R {
B825_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 26 - B826"]
#[inline(always)]
pub fn b826(&self) -> B826_R {
B826_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bit 27 - B827"]
#[inline(always)]
pub fn b827(&self) -> B827_R {
B827_R::new(((self.bits >> 27) & 0x01) != 0)
}
#[doc = "Bit 28 - B828"]
#[inline(always)]
pub fn b828(&self) -> B828_R {
B828_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 29 - B829"]
#[inline(always)]
pub fn b829(&self) -> B829_R {
B829_R::new(((self.bits >> 29) & 0x01) != 0)
}
#[doc = "Bit 30 - B830"]
#[inline(always)]
pub fn b830(&self) -> B830_R {
B830_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - B831"]
#[inline(always)]
pub fn b831(&self) -> B831_R {
B831_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - B800"]
#[inline(always)]
pub fn b800(&mut self) -> B800_W {
B800_W { w: self }
}
#[doc = "Bit 1 - B801"]
#[inline(always)]
pub fn b801(&mut self) -> B801_W {
B801_W { w: self }
}
#[doc = "Bit 2 - B802"]
#[inline(always)]
pub fn b802(&mut self) -> B802_W {
B802_W { w: self }
}
#[doc = "Bit 3 - B803"]
#[inline(always)]
pub fn b803(&mut self) -> B803_W {
B803_W { w: self }
}
#[doc = "Bit 4 - B804"]
#[inline(always)]
pub fn b804(&mut self) -> B804_W {
B804_W { w: self }
}
#[doc = "Bit 5 - B805"]
#[inline(always)]
pub fn b805(&mut self) -> B805_W {
B805_W { w: self }
}
#[doc = "Bit 6 - B806"]
#[inline(always)]
pub fn b806(&mut self) -> B806_W {
B806_W { w: self }
}
#[doc = "Bit 7 - B807"]
#[inline(always)]
pub fn b807(&mut self) -> B807_W {
B807_W { w: self }
}
#[doc = "Bit 8 - B808"]
#[inline(always)]
pub fn b808(&mut self) -> B808_W {
B808_W { w: self }
}
#[doc = "Bit 9 - B809"]
#[inline(always)]
pub fn b809(&mut self) -> B809_W {
B809_W { w: self }
}
#[doc = "Bit 10 - B810"]
#[inline(always)]
pub fn b810(&mut self) -> B810_W {
B810_W { w: self }
}
#[doc = "Bit 11 - B811"]
#[inline(always)]
pub fn b811(&mut self) -> B811_W {
B811_W { w: self }
}
#[doc = "Bit 12 - B812"]
#[inline(always)]
pub fn b812(&mut self) -> B812_W {
B812_W { w: self }
}
#[doc = "Bit 13 - B813"]
#[inline(always)]
pub fn b813(&mut self) -> B813_W {
B813_W { w: self }
}
#[doc = "Bit 14 - B814"]
#[inline(always)]
pub fn b814(&mut self) -> B814_W {
B814_W { w: self }
}
#[doc = "Bit 15 - B815"]
#[inline(always)]
pub fn b815(&mut self) -> B815_W {
B815_W { w: self }
}
#[doc = "Bit 16 - B816"]
#[inline(always)]
pub fn b816(&mut self) -> B816_W {
B816_W { w: self }
}
#[doc = "Bit 17 - B817"]
#[inline(always)]
pub fn b817(&mut self) -> B817_W {
B817_W { w: self }
}
#[doc = "Bit 18 - B818"]
#[inline(always)]
pub fn b818(&mut self) -> B818_W {
B818_W { w: self }
}
#[doc = "Bit 19 - B819"]
#[inline(always)]
pub fn b819(&mut self) -> B819_W {
B819_W { w: self }
}
#[doc = "Bit 20 - B820"]
#[inline(always)]
pub fn b820(&mut self) -> B820_W {
B820_W { w: self }
}
#[doc = "Bit 21 - B821"]
#[inline(always)]
pub fn b821(&mut self) -> B821_W {
B821_W { w: self }
}
#[doc = "Bit 22 - B822"]
#[inline(always)]
pub fn b822(&mut self) -> B822_W {
B822_W { w: self }
}
#[doc = "Bit 23 - B823"]
#[inline(always)]
pub fn b823(&mut self) -> B823_W {
B823_W { w: self }
}
#[doc = "Bit 24 - B824"]
#[inline(always)]
pub fn b824(&mut self) -> B824_W {
B824_W { w: self }
}
#[doc = "Bit 25 - B825"]
#[inline(always)]
pub fn b825(&mut self) -> B825_W {
B825_W { w: self }
}
#[doc = "Bit 26 - B826"]
#[inline(always)]
pub fn b826(&mut self) -> B826_W {
B826_W { w: self }
}
#[doc = "Bit 27 - B827"]
#[inline(always)]
pub fn b827(&mut self) -> B827_W {
B827_W { w: self }
}
#[doc = "Bit 28 - B828"]
#[inline(always)]
pub fn b828(&mut self) -> B828_W {
B828_W { w: self }
}
#[doc = "Bit 29 - B829"]
#[inline(always)]
pub fn b829(&mut self) -> B829_W {
B829_W { w: self }
}
#[doc = "Bit 30 - B830"]
#[inline(always)]
pub fn b830(&mut self) -> B830_W {
B830_W { w: self }
}
#[doc = "Bit 31 - B831"]
#[inline(always)]
pub fn b831(&mut self) -> B831_W {
B831_W { w: self }
}
}
|
// Copyright (c) 2018-2022 Ministerio de Fomento
// Instituto de Ciencias de la Construcción Eduardo Torroja (IETcc-CSIC)
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Author(s): Rafael Villar Burke <pachi@ietcc.csic.es>,
// Daniel Jiménez González <dani@ietcc.csic.es>,
// Marta Sorribes Gil <msorribes@ietcc.csic.es>
use crate::types::*;
// use crate::Components;
// use crate::Factors;
// ==================== Conversión a formato simple
/// Muestra en formato simple
///
/// Esta función usa un formato simple y compacto para representar la información sobre
/// eficiencia energética del edificio, datos y balances
pub trait AsCtePlain {
/// Get in plan format
fn to_plain(&self) -> String;
}
// ================= Implementaciones ====================
/// Convierte resultado RenNrenCo2 a String con2 decimales
fn rennren2string(v: &RenNrenCo2) -> String {
format!(
"ren {:.2}, nren {:.2}, tot: {:.2}, co2: {:.2}",
v.ren,
v.nren,
v.tot(),
v.co2
)
}
/// Muestra un valor opcional con la precisión deseada o como un guion si no está presente
fn value_or_dash(v: Option<f32>, precision: usize) -> String {
match v {
Some(v) => format!("{:.*}", precision, v),
None => "-".to_string(),
}
}
impl AsCtePlain for EnergyPerformance {
/// Está mostrando únicamente los resultados
fn to_plain(&self) -> String {
// Datos generales
let bal = &self.balance_m2;
let k_exp = self.k_exp;
let arearef = self.arearef;
// Demanda
let dhw_needs = value_or_dash(bal.needs.ACS, 1);
let heating_needs = value_or_dash(bal.needs.CAL, 1);
let cooling_needs = value_or_dash(bal.needs.REF, 1);
// Consumos
let epus = bal.used.epus;
let nepus = bal.used.nepus;
let cgnus = bal.used.cgnus;
let used = epus + nepus + cgnus;
let used_by_srv = list_entries_f32(&bal.used.epus_by_srv);
let used_epus_by_cr = list_entries_f32(&bal.used.epus_by_cr);
// Generada
let prod_an = bal.prod.an;
let prod_by_src = list_entries_f32(&bal.prod.by_src);
let prod_by_cr = list_entries_f32(&bal.prod.by_cr);
let prod_epus_by_src = list_entries_f32(&bal.prod.epus_by_src);
// Suministrada
let del_an = bal.del.an;
let del_grid = bal.del.grid;
let del_onsite = bal.del.onst;
// let del_cgn = bal.del.cgn;
// Exportada
let exp_an = bal.exp.an;
let exp_grid = bal.exp.grid;
let exp_nepus = bal.exp.nepus;
// Ponderada por m2 (por uso)
let we_a = bal.we.a;
let we_b = bal.we.b;
let RenNrenCo2 { ren, nren, co2, .. } = we_b;
let tot = we_b.tot();
let rer = self.rer;
let rer_nrb = self.rer_nrb;
let balance_m2_a = rennren2string(&we_a);
let a_by_srv = list_entries_rennrenco2(&bal.we.a_by_srv);
let balance_m2_b = rennren2string(&we_b);
let b_by_srv = list_entries_rennrenco2(&bal.we.b_by_srv);
// Parámetros de demanda HE4
let misc_out = if let Some(map) = &self.misc {
let pct_ren = map.get_str_pct1d("fraccion_renovable_demanda_acs_nrb");
format!("\n\n** Indicadores adicionales\nPorcentaje renovable de la demanda de ACS (perímetro próximo): {pct_ren} [%]")
} else {
String::new()
};
format!(
"** Eficiencia energética
Area_ref = {arearef:.2} [m2]
k_exp = {k_exp:.2}
C_ep [kWh/m2.an]: ren = {ren:.1}, nren = {nren:.1}, tot = {tot:.1}
E_CO2 [kg_CO2e/m2.an]: {co2:.2}
RER = {rer:.2}
RER_nrb = {rer_nrb:.2}
** Demanda [kWh/m2.an]:
- ACS: {dhw_needs}
- CAL: {heating_needs}
- REF: {cooling_needs}
** Energía final (todos los vectores) [kWh/m2.an]:
Energía consumida: {used:.2}
+ Consumida en usos EPB: {epus:.2}
* por servicio:
{used_by_srv}
* por vector:
{used_epus_by_cr}
+ Consumida en usos no EPB: {nepus:.2}
+ Consumida en cogeneración: {cgnus:.2}
Generada: {prod_an:.2}
* por vector:
{prod_by_cr}
* por origen:
{prod_by_src}
* generada y usada en servicios EPB, por origen:
{prod_epus_by_src}
Suministrada {del_an:.2}:
- de red: {del_grid:.2}
- in situ: {del_onsite:.2}
Exportada: {exp_an:.2}
- a la red: {exp_grid:.2}
- a usos no EPB: {exp_nepus:.2}
** Energía primaria (ren, nren) [kWh/m2.an] y emisiones [kg_CO2e/m2.an]:
Recursos utilizados (paso A): {balance_m2_a}
* por servicio:
{a_by_srv}
Incluyendo el efecto de la energía exportada (paso B): {balance_m2_b}
* por servicio:
{b_by_srv}{misc_out}
"
)
}
}
fn list_entries_f32<T: std::fmt::Display>(map: &std::collections::HashMap<T, f32>) -> String {
let mut entries = map
.iter()
.map(|(k, v)| format!("- {}: {:.2}", k, v))
.collect::<Vec<String>>();
entries.sort();
entries.join("\n")
}
fn list_entries_rennrenco2<T: std::fmt::Display>(
map: &std::collections::HashMap<T, RenNrenCo2>,
) -> String {
let mut entries = map
.iter()
.map(|(k, v)| format!("- {}: {}", k, rennren2string(v)))
.collect::<Vec<String>>();
entries.sort();
entries.join("\n")
}
|
use std::io;
use std::io::Read;
fn main() {
//! collect stdin and echo it, preceded by (num), where num = len of stdin
println!("please type or pipe something here:");
let mut input = io::stdin();
let mut buf: String = String::new(); // even though we init buf as mutable,
match input.read_line(&mut buf) { // we stil have to pass buf as mutable
Err(_) => {} // read_line returns Result, which wraps with Err & Ok
Ok(numchars) => { // numchars == length of string in buf + 1 (for EOF)
print!("({}) ", &numchars);
print!("{}", buf);
}
}
}
|
use color_eyre::eyre::{Result};
use pahi_olin::*;
use std::fs;
use structopt::StructOpt;
#[macro_use]
extern crate log;
#[derive(Debug, StructOpt)]
#[structopt(
name = "pa'i",
about = "A WebAssembly runtime in Rust meeting the Olin ABI."
)]
struct Opt {
/// Backend
#[structopt(short, long, default_value = "cranelift")]
backend: String,
/// Print syscalls on exit
#[structopt(short, long)]
function_log: bool,
/// Binary to run
#[structopt()]
fname: String,
/// Main function
#[structopt(short, long, default_value = "_start")]
entrypoint: String,
/// Arguments of the wasm child
#[structopt()]
args: Vec<String>,
}
fn main() -> Result<()> {
color_eyre::install()?;
let opt = Opt::from_args();
env_logger::init();
info!("la pa'i is starting...");
debug!("args: {:?}", opt.args);
let mut args: Vec<String> = vec![];
args.push(opt.fname.clone());
for arg in &opt.args {
args.push(arg.to_string());
}
debug!("opening {}", opt.fname);
let data: &[u8] = &fs::read(&opt.fname)?;
let exec_opt = exec::Opt::new(opt.fname)
.system_env()
.cache_prefix("pahi".into())
.entrypoint(opt.entrypoint)
.args(args);
match exec::run(exec_opt, data) {
Ok(status) => {
if opt.function_log {
info!("dumping called syscalls");
for (key, val) in status.called_functions.iter() {
info!("{}: {}", key, val);
}
info!("dumping resources");
for url in status.resource_urls.iter() {
info!("{}", url);
}
}
if status.exit_code != 0 {
std::process::exit(status.exit_code);
}
}
Err(why) => {
error!("runtime error: {}", why);
}
}
Ok(())
}
|
use crate::blocks::BlockPosition;
use eosio_cdt::eos::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub enum ShipRequests {
GetStatus(GetStatusRequestV0),
GetBlocks(GetBlocksRequestV0),
}
#[derive(Serialize, Deserialize)]
pub struct GetStatusRequestV0;
#[derive(Serialize, Deserialize)]
pub struct GetBlocksRequestV0 {
pub start_block_num: u32,
pub end_block_num: u32,
pub max_messages_in_flight: u32,
pub have_positions: Vec<BlockPosition>,
pub irreversible_only: bool,
pub fetch_block: bool,
pub fetch_traces: bool,
pub fetch_deltas: bool,
}
|
use super::copysignf;
use super::truncf;
use core::f32;
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub fn roundf(x: f32) -> f32 {
truncf(x + copysignf(0.5 - 0.25 * f32::EPSILON, x))
}
// PowerPC tests are failing on LLVM 13: https://github.com/rust-lang/rust/issues/88520
#[cfg(not(target_arch = "powerpc64"))]
#[cfg(test)]
mod tests {
use super::roundf;
#[test]
fn negative_zero() {
assert_eq!(roundf(-0.0_f32).to_bits(), (-0.0_f32).to_bits());
}
#[test]
fn sanity_check() {
assert_eq!(roundf(-1.0), -1.0);
assert_eq!(roundf(2.8), 3.0);
assert_eq!(roundf(-0.5), -1.0);
assert_eq!(roundf(0.5), 1.0);
assert_eq!(roundf(-1.5), -2.0);
assert_eq!(roundf(1.5), 2.0);
}
}
|
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::{env, str};
use telegram_bot::*;
#[derive(Deserialize, Debug)]
struct SearchResult {
id: i64,
}
#[derive(Deserialize, Debug)]
struct SearchResults {
data: Vec<SearchResult>,
}
#[derive(Deserialize, Debug)]
struct SpotifyToken {
access_token: String,
token_type: String,
scope: String,
expires_in: i32,
}
#[derive(Deserialize, Debug)]
struct SpotifySearchResult {
tracks: SpotifySearchResultTracks,
}
#[derive(Deserialize, Debug)]
struct SpotifySearchResultTracks {
items: Vec<SpotifySearchResultItems>,
}
#[derive(Deserialize, Debug)]
struct SpotifySearchResultItems {
uri: String,
}
#[derive(Serialize, Debug)]
struct SpotifyAddToPlaylilst {
uris: Vec<String>,
position: i32,
}
const DEEZER_SEARCH_URL: &str = "https://api.deezer.com/search";
const DEEZER_PLAYLIST_URL: &str = "https://api.deezer.com/playlist/8866431842/tracks";
const SPOTIFY_ACCESS_TOKEN_URL: &str = "https://accounts.spotify.com/api/token";
const SPOTIFY_SEARCH_URL: &str = "https://api.spotify.com/v1/search";
const SPOTIFY_PLAYLIST_URL: &str = "https://api.spotify.com/v1/playlists/4BvNLwSbqsrwtHXZ1erfAz/tracks";
#[tokio::main]
async fn main() -> Result<(), Error> {
let token: String = env::var("TELEGRAM_BOT_TOKEN").expect("TELEGRAM_BOT_TOKEN not found");
let deezer_token: String = env::var("DEEZER_TOKEN").expect("DEEZER_TOKEN not found") ;
let _spotify_client_id: String = env::var("SPOTIFY_CLIENT_ID").expect("SPOTIFY_CLIENT_ID not found");
let _spotify_secret: String = env::var("SPOTIFY_CLIENT_SECRET").expect("SPOTIFY_CLIENT_SECRET not found");
let spotify_refresh_token : String = env::var("SPOTIFY_REFRESH_TOKEN").expect("SPOTIFY_REFRESH_TOKEN not found");
let spotify_basic_auth : String = env::var("SPOTIFY_BASIC_AUTH").expect("SPOTIFY_BASIC_AUTH not found");
let api = Api::new(token);
let http_client = reqwest::Client::new();
// Fetch new updates via long poll method
let mut stream = api.stream();
while let Some(update) = stream.next().await {
// If the received update contains a new message...
let update = update?;
if let UpdateKind::Message(message) = update.kind {
if let MessageKind::Text { ref data, .. } = message.kind {
// Print received text message to stdout.
println!("<{}>: {}", &message.from.first_name, data);
if data.contains("https://son.gg/t/") {
let song: Vec<&str> = data.split("\n").collect();
println!("Found song reference {}", song[0]);
add_to_deezer_playlist(&http_client, &deezer_token, song[0]).await;
add_to_spotify_playlist(&http_client, &spotify_refresh_token, &spotify_basic_auth, song[0]).await;
}
}
}
}
Ok(())
}
async fn add_to_deezer_playlist(deezer_client: &reqwest::Client, deezer_token: &String, song: &str) {
println!("---DEEZER---");
let search_resp = deezer_client
.get(DEEZER_SEARCH_URL)
.query(&[("access_token", &deezer_token), ("q", &&song.to_owned())])
.send()
.await;
match search_resp {
Ok(resp) => {
let results_resp = resp.json::<SearchResults>().await;
match results_resp {
Ok(results) => {
println!("Song id = {}", results.data[0].id);
let response = deezer_client
.get(DEEZER_PLAYLIST_URL)
.query(&[
("access_token", &deezer_token),
("songs", &&results.data[0].id.to_string()),
("request_method", &&"POST".to_owned()),
])
.send()
.await;
if let Err(error) = response {
println!("Error adding song to playlist, {}", error);
} else {
println!("Successfully added song");
}
}
Err(err) => println!("Error deserialising search results {}", err),
}
}
Err(err) => println!("Error fetching search results {}", err),
}
}
async fn add_to_spotify_playlist(spotify_client: &reqwest::Client, spotify_refresh_token: &String, spotify_basic_auth: &String, song: &str) {
println!("---SPOTIFY---");
let mut params = HashMap::new();
params.insert("grant_type", "refresh_token");
params.insert("refresh_token", spotify_refresh_token);
let access_token_resp = spotify_client
.post(SPOTIFY_ACCESS_TOKEN_URL)
.form(¶ms)
.header("Authorization", spotify_basic_auth)
.send()
.await;
match access_token_resp {
Ok(resp) => {
println!("Got spotify token");
let access_token = resp.json::<SpotifyToken>().await;
match access_token {
Ok(tok) => {
let search_resp = spotify_client
.get(SPOTIFY_SEARCH_URL)
.query(&[("q", &song), ("type", &"track"), ("limit", &"1")])
.bearer_auth(tok.access_token.clone())
.send()
.await;
match search_resp {
Ok(resp) => {
let spotify_search = resp.json::<SpotifySearchResult>().await;
match spotify_search {
Ok(search_res) => {
let add_playlist_resp = spotify_client
.post(SPOTIFY_PLAYLIST_URL)
.header("Content-Type", "application/json")
.bearer_auth(tok.access_token)
.json(&SpotifyAddToPlaylilst {
uris: vec![search_res.tracks.items[0].uri.clone()],
position: 0
})
.send()
.await;
match add_playlist_resp {
Ok(resp) => {
println!("Done adding song to playlist");
println!("{}", resp.text().await.unwrap());
}
Err(err) => {
println!("Error adding song to playlist {}", err)
}
}
}
Err(err) => {
println!("Failed to unwrap search result {}", err);
}
}
}
Err(err) => {
println!("Failed to get search result {}", err);
}
}
}
Err(err) => {
println!("Couldnt unwrap token {}", err);
}
}
}
Err(err) => {
println!("Couldnt get access token {}", err);
}
}
}
|
extern crate msgbox;
use msgbox::IconType;
const OPL_WRITEBUF_SIZE: usize = 1024;
const OPL_WRITEBUF_DELAY: usize = 2;
const OPL3_SLOT_CHAN_COUNT: usize = 2;
const OPL3_OUT_SIZE: usize = 4;
const OPL3_CHANNEL_COUNT: usize = 18;
const OPL3_CHSLOT_COUNT: usize = 36;
const OPL3_MIXBUF_SIZE: usize = 2;
const OPL3_OLDSAMPLES_SIZE: usize = 2;
const OPL3_SAMPLES_SIZE: usize = 2;
const RSM_FRAC: usize = 10;
// Logsign table
const LOGSINROM: [usize; 256] = [
0x859, 0x6c3, 0x607, 0x58b, 0x52e, 0x4e4, 0x4a6, 0x471, 0x443, 0x41a, 0x3f5, 0x3d3, 0x3b5,
0x398, 0x37e, 0x365, 0x34e, 0x339, 0x324, 0x311, 0x2ff, 0x2ed, 0x2dc, 0x2cd, 0x2bd, 0x2af,
0x2a0, 0x293, 0x286, 0x279, 0x26d, 0x261, 0x256, 0x24b, 0x240, 0x236, 0x22c, 0x222, 0x218,
0x20f, 0x206, 0x1fd, 0x1f5, 0x1ec, 0x1e4, 0x1dc, 0x1d4, 0x1cd, 0x1c5, 0x1be, 0x1b7, 0x1b0,
0x1a9, 0x1a2, 0x19b, 0x195, 0x18f, 0x188, 0x182, 0x17c, 0x177, 0x171, 0x16b, 0x166, 0x160,
0x15b, 0x155, 0x150, 0x14b, 0x146, 0x141, 0x13c, 0x137, 0x133, 0x12e, 0x129, 0x125, 0x121,
0x11c, 0x118, 0x114, 0x10f, 0x10b, 0x107, 0x103, 0x0ff, 0x0fb, 0x0f8, 0x0f4, 0x0f0, 0x0ec,
0x0e9, 0x0e5, 0x0e2, 0x0de, 0x0db, 0x0d7, 0x0d4, 0x0d1, 0x0cd, 0x0ca, 0x0c7, 0x0c4, 0x0c1,
0x0be, 0x0bb, 0x0b8, 0x0b5, 0x0b2, 0x0af, 0x0ac, 0x0a9, 0x0a7, 0x0a4, 0x0a1, 0x09f, 0x09c,
0x099, 0x097, 0x094, 0x092, 0x08f, 0x08d, 0x08a, 0x088, 0x086, 0x083, 0x081, 0x07f, 0x07d,
0x07a, 0x078, 0x076, 0x074, 0x072, 0x070, 0x06e, 0x06c, 0x06a, 0x068, 0x066, 0x064, 0x062,
0x060, 0x05e, 0x05c, 0x05b, 0x059, 0x057, 0x055, 0x053, 0x052, 0x050, 0x04e, 0x04d, 0x04b,
0x04a, 0x048, 0x046, 0x045, 0x043, 0x042, 0x040, 0x03f, 0x03e, 0x03c, 0x03b, 0x039, 0x038,
0x037, 0x035, 0x034, 0x033, 0x031, 0x030, 0x02f, 0x02e, 0x02d, 0x02b, 0x02a, 0x029, 0x028,
0x027, 0x026, 0x025, 0x024, 0x023, 0x022, 0x021, 0x020, 0x01f, 0x01e, 0x01d, 0x01c, 0x01b,
0x01a, 0x019, 0x018, 0x017, 0x017, 0x016, 0x015, 0x014, 0x014, 0x013, 0x012, 0x011, 0x011,
0x010, 0x00f, 0x00f, 0x00e, 0x00d, 0x00d, 0x00c, 0x00c, 0x00b, 0x00a, 0x00a, 0x009, 0x009,
0x008, 0x008, 0x007, 0x007, 0x007, 0x006, 0x006, 0x005, 0x005, 0x005, 0x004, 0x004, 0x004,
0x003, 0x003, 0x003, 0x002, 0x002, 0x002, 0x002, 0x001, 0x001, 0x001, 0x001, 0x001, 0x001,
0x001, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000,
];
// Exponentials table
const EXPROM: [usize; 256] = [
0x7fa, 0x7f5, 0x7ef, 0x7ea, 0x7e4, 0x7df, 0x7da, 0x7d4, 0x7cf, 0x7c9, 0x7c4, 0x7bf, 0x7b9,
0x7b4, 0x7ae, 0x7a9, 0x7a4, 0x79f, 0x799, 0x794, 0x78f, 0x78a, 0x784, 0x77f, 0x77a, 0x775,
0x770, 0x76a, 0x765, 0x760, 0x75b, 0x756, 0x751, 0x74c, 0x747, 0x742, 0x73d, 0x738, 0x733,
0x72e, 0x729, 0x724, 0x71f, 0x71a, 0x715, 0x710, 0x70b, 0x706, 0x702, 0x6fd, 0x6f8, 0x6f3,
0x6ee, 0x6e9, 0x6e5, 0x6e0, 0x6db, 0x6d6, 0x6d2, 0x6cd, 0x6c8, 0x6c4, 0x6bf, 0x6ba, 0x6b5,
0x6b1, 0x6ac, 0x6a8, 0x6a3, 0x69e, 0x69a, 0x695, 0x691, 0x68c, 0x688, 0x683, 0x67f, 0x67a,
0x676, 0x671, 0x66d, 0x668, 0x664, 0x65f, 0x65b, 0x657, 0x652, 0x64e, 0x649, 0x645, 0x641,
0x63c, 0x638, 0x634, 0x630, 0x62b, 0x627, 0x623, 0x61e, 0x61a, 0x616, 0x612, 0x60e, 0x609,
0x605, 0x601, 0x5fd, 0x5f9, 0x5f5, 0x5f0, 0x5ec, 0x5e8, 0x5e4, 0x5e0, 0x5dc, 0x5d8, 0x5d4,
0x5d0, 0x5cc, 0x5c8, 0x5c4, 0x5c0, 0x5bc, 0x5b8, 0x5b4, 0x5b0, 0x5ac, 0x5a8, 0x5a4, 0x5a0,
0x59c, 0x599, 0x595, 0x591, 0x58d, 0x589, 0x585, 0x581, 0x57e, 0x57a, 0x576, 0x572, 0x56f,
0x56b, 0x567, 0x563, 0x560, 0x55c, 0x558, 0x554, 0x551, 0x54d, 0x549, 0x546, 0x542, 0x53e,
0x53b, 0x537, 0x534, 0x530, 0x52c, 0x529, 0x525, 0x522, 0x51e, 0x51b, 0x517, 0x514, 0x510,
0x50c, 0x509, 0x506, 0x502, 0x4ff, 0x4fb, 0x4f8, 0x4f4, 0x4f1, 0x4ed, 0x4ea, 0x4e7, 0x4e3,
0x4e0, 0x4dc, 0x4d9, 0x4d6, 0x4d2, 0x4cf, 0x4cc, 0x4c8, 0x4c5, 0x4c2, 0x4be, 0x4bb, 0x4b8,
0x4b5, 0x4b1, 0x4ae, 0x4ab, 0x4a8, 0x4a4, 0x4a1, 0x49e, 0x49b, 0x498, 0x494, 0x491, 0x48e,
0x48b, 0x488, 0x485, 0x482, 0x47e, 0x47b, 0x478, 0x475, 0x472, 0x46f, 0x46c, 0x469, 0x466,
0x463, 0x460, 0x45d, 0x45a, 0x457, 0x454, 0x451, 0x44e, 0x44b, 0x448, 0x445, 0x442, 0x43f,
0x43c, 0x439, 0x436, 0x433, 0x430, 0x42d, 0x42a, 0x428, 0x425, 0x422, 0x41f, 0x41c, 0x419,
0x416, 0x414, 0x411, 0x40e, 0x40b, 0x408, 0x406, 0x403, 0x400,
];
// freq mult table multiplied by 2
// 1/2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 12, 12, 15, 15, ...
const MT: [usize; 16] = [1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 20, 24, 24, 30, 30];
// KSL table
const KSLROM: [usize; 16] = [
0, 32, 40, 45, 48, 51, 53, 55, 56, 58, 59, 60, 61, 62, 63, 64,
];
const KSLSHIFT: [usize; 4] = [8, 1, 2, 0];
// envelope generator constants
const EG_INCSTEP: [[usize; 4]; 4] = [[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 1, 0], [1, 1, 1, 0]];
// address decoding
const AD_SLOT: [isize; 32] = [
0, 1, 2, 3, 4, 5, -1, -1, 6, 7, 8, 9, 10, 11, -1, -1, 12, 13, 14, 15, 16, 17, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1,
];
const CH_SLOT: [usize; 18] = [
0, 1, 2, 6, 7, 8, 12, 13, 14, 18, 19, 20, 24, 25, 26, 30, 31, 32,
];
static PANPOT_LUT: [isize; 256] = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
static PANPOT_LUT_BUILD: bool = false;
#[repr(C)]
pub struct OPL3Slot {
pub channel: Box<OPL3Channel>,
pub chip: Box<OPL3Chip>,
pub out: isize,
pub fbmod: isize,
pub modifier: isize,
pub prout: isize,
pub eg_rout: isize,
pub eg_out: isize,
pub eg_inc: usize,
pub eg_gen: EnvelopeGenNum,
pub eg_rate: usize,
pub eg_ksl: usize,
pub trem: usize,
pub reg_vib: usize,
pub reg_type: usize,
pub reg_ksr: usize,
pub reg_mult: usize,
pub reg_ksl: usize,
pub reg_tl: usize,
pub reg_ar: usize,
pub reg_dr: usize,
pub reg_sl: usize,
pub reg_rr: usize,
pub reg_wf: usize,
pub key: usize,
pub pg_reset: usize,
pub pg_phase: usize,
pub pg_phase_out: usize,
pub slot_num: usize,
}
#[repr(C)]
pub struct OPL3Channel {
pub slots: [Box<OPL3Slot>; OPL3_SLOT_CHAN_COUNT],
pub pair: Box<OPL3Channel>,
pub chip: Box<OPL3Chip>,
pub out: [isize; OPL3_OUT_SIZE],
pub chtype: usize,
pub f_num: usize,
pub block: usize,
pub fb: usize,
pub con: usize,
pub alg: usize,
pub ksv: usize,
pub cha: usize,
pub chb: usize,
pub ch_num: usize,
pub leftpan: isize,
pub rightpan: isize,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub struct OPL3WriteBuffer {
pub time: usize,
pub reg: usize,
pub data: u8,
}
#[repr(C)]
pub struct OPL3Chip {
pub channel: [OPL3Channel; OPL3_CHANNEL_COUNT],
pub slot: [OPL3Slot; OPL3_CHSLOT_COUNT],
pub timer: usize,
pub eg_timer: usize,
pub eg_timerrem: usize,
pub eg_state: usize,
pub eg_add: usize,
pub newm: usize,
pub nts: usize,
pub rhy: usize,
pub vibpos: usize,
pub vibshift: usize,
pub tremolo: usize,
pub tremolopos: usize,
pub tremoloshift: usize,
pub noise: usize,
pub zeromod: isize,
pub mixbuff: [isize; OPL3_MIXBUF_SIZE],
pub rm_hh_bit2: usize,
pub rm_hh_bit3: usize,
pub rm_hh_bit7: usize,
pub rm_hh_bit8: usize,
pub rm_tc_bit3: usize,
pub rm_tc_bit5: usize,
pub stereoext: usize,
//OPL3L
pub rateratio: isize,
pub samplecnt: isize,
pub oldsamples: [isize; OPL3_OLDSAMPLES_SIZE],
pub samples: [isize; OPL3_SAMPLES_SIZE],
pub writebuf_samplecnt: usize,
pub writebuf_cur: usize,
pub writebuf_last: usize,
pub writebuf_lasttime: usize,
pub writebuf: [OPL3WriteBuffer; OPL_WRITEBUF_SIZE],
}
#[repr(C)]
#[derive(Clone, Copy)]
pub enum ChannelType {
TwoOp,
FourOp,
FourOpTwo,
Drum,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub enum EnvelopeKeyType {
Norm,
Drum,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub enum EnvelopeGenNum {
Attack,
Decay,
Sustain,
Release,
}
fn opl3_envelope_calc_sin0(phase: usize, envelope: usize) -> usize {
let (mut phs, mut out, mut neg) = (phase, 0, 0);
phs &= 0x3ff;
if (phs & 0x200) == 0 {
neg = 0xffff;
}
if (phs & 0x100) > 0 {
out = LOGSINROM[((phs as usize) & 0xff) ^ 0xff];
} else {
out = LOGSINROM[(phs as usize) & 0xff as usize];
}
(EXPROM[out + (envelope << 3)] << 1) >> ((out + (envelope << 3)) >> 8) ^ neg
}
fn opl3_envelope_calc_sin1(phase: usize, envelope: usize) -> usize {
let (mut phs, mut out) = (phase, 0);
phs &= 0x3ff;
if (phs & 0x200) > 0 {
out = 0x1000;
} else if (phs & 0x100) > 0 {
out = LOGSINROM[(phs & 0xff) ^ 0xff];
} else {
out = LOGSINROM[phs & 0xff];
}
(EXPROM[out + (envelope << 3)] << 1) >> ((out + (envelope << 3)) >> 8)
}
fn opl3_envelope_calc_sin2(phase: usize, envelope: usize) -> usize {
let (mut phs, mut out) = (phase, 0);
phs &= 0x3ff;
if (phs & 0x100) > 0 {
out = LOGSINROM[(phs & 0xff) ^ 0xff];
} else {
out = LOGSINROM[phs & 0xff];
}
(EXPROM[out + (envelope << 3)] << 1) >> ((out + (envelope << 3)) >> 8)
}
fn opl3_envelope_calc_sin3(phase: usize, envelope: usize) -> usize {
let (mut phs, mut out) = (phase, 0);
phs &= 0x3ff;
if (phs & 0x100) > 0 {
out = 0x1000;
} else {
out = LOGSINROM[phs & 0xff];
}
(EXPROM[out + (envelope << 3)] << 1) >> ((out + (envelope << 3)) >> 8)
}
fn opl3_envelope_calc_sin4(phase: usize, envelope: usize) -> usize {
let (mut phs, mut out, mut neg) = (phase, 0, 0);
phs &= 0x3ff;
if (phs & 0x300) == 0x100 {
neg = 0xffff;
}
if (phs & 0x200) > 0 {
out = 0x1000;
} else if (phs & 0x80) > 0 {
out = LOGSINROM[((phs ^ 0xff) << 1) & 0xff];
} else {
out = LOGSINROM[(phs << 1) & 0xff];
}
(EXPROM[out + (envelope << 3)] << 1) >> ((out + (envelope << 3)) >> 8) ^ neg
}
fn opl3_envelope_calc_sin5(phase: usize, envelope: usize) -> usize {
let (mut phs, mut out) = (phase, 0);
phs &= 0x3ff;
if (phs & 0x200) > 0 {
out = 0x1000;
} else if (phs & 0x80) > 0 {
out = LOGSINROM[((phs ^ 0xff) << 1) & 0xff];
} else {
out = LOGSINROM[(phs << 1) & 0xff];
}
(EXPROM[out + (envelope << 3)] << 1) >> ((out + (envelope << 3)) >> 8)
}
fn opl3_envelope_calc_sin6(phase: usize, envelope: usize) -> usize {
let (mut phs, mut neg) = (phase, 0);
phs &= 0x3ff;
if (phs & 0x200) > 0 {
neg = 0xffff;
}
(EXPROM[(envelope << 3)] << 1) >> ((envelope << 3) >> 8) ^ neg
}
fn opl3_envelope_calc_sin7(phase: usize, envelope: usize) -> usize {
let (mut phs, mut out, mut neg) = (phase, 0, 0);
phs &= 0x3ff;
if (phs & 0x200) > 0 {
neg = 0xffff;
phs = (phs & 0x1ff) ^ 0x1ff;
}
out = phs << 3;
(EXPROM[out + (envelope << 3)] << 1) >> ((out + (envelope << 3)) >> 8) ^ neg
}
impl OPL3Slot {
fn update_ksl(&mut self) {
let ksl = (KSLROM[self.channel.f_num >> 6] << 2) - ((0x08 - self.channel.block) << 5);
self.eg_ksl = ksl;
}
fn calculate_envelope(&mut self) {
let (
mut nonzero,
mut rate,
mut rate_hi,
mut rate_lo,
mut reg_rate,
mut ks,
mut eg_shift,
mut shift,
mut eg_rout,
mut eg_inc,
mut eg_off,
mut reset,
) = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
self.eg_out = self.eg_rout
+ ((self.reg_tl as isize) << 2)
+ ((self.eg_ksl as isize) >> (KSLSHIFT[self.reg_ksl] as isize))
+ self.trem as isize;
if self.key > 0 && self.eg_gen as usize == EnvelopeGenNum::Release as usize {
reset = 1;
reg_rate = self.reg_ar;
} else {
match self.eg_gen {
EnvelopeGenNum::Attack => reg_rate = self.reg_ar,
EnvelopeGenNum::Decay => reg_rate = self.reg_dr,
EnvelopeGenNum::Sustain => {
if self.reg_type == 0 {
reg_rate = self.reg_rr;
}
}
EnvelopeGenNum::Release => reg_rate = self.reg_rr,
}
}
self.pg_reset = reset;
ks = self.channel.ksv >> ((self.reg_ksr ^ 1) << 1);
if reg_rate != 0 {
nonzero = 1;
} else {
nonzero = 0;
}
rate = ks + (reg_rate << 2);
rate_hi = rate >> 2;
rate_lo = rate & 0x03;
if (rate_hi & 0x10) > 0 {
rate_hi = 0x0f;
}
eg_shift = rate_hi + self.chip.eg_add;
shift = 0;
if nonzero > 0 {
if rate_hi < 12 {
if self.chip.eg_state > 0 {
match eg_shift {
12 => shift = 1,
13 => shift = (rate_lo >> 1) & 0x01,
14 => shift = rate_lo & 0x01,
_ => (),
}
}
} else {
shift = (rate_hi & 0x03) + EG_INCSTEP[rate_lo][self.chip.timer & 0x03];
if (shift & 0x04) > 0 {
shift = 0x03;
}
if shift == 0 {
shift = self.chip.eg_state;
}
}
}
eg_rout = self.eg_rout;
eg_inc = 0;
eg_off = 0;
// Instant attack
if reset > 0 && rate_hi == 0x0f {
eg_rout = 0x00;
}
// Envelope off
if (self.eg_rout & 0x1f8) > 0 {
eg_off = 1;
}
if self.eg_gen as usize != EnvelopeGenNum::Attack as usize && reset == 0 && eg_off > 0 {
eg_rout = 0x1ff;
}
match self.eg_gen {
EnvelopeGenNum::Attack => {
if self.eg_rout > 0 {
self.eg_gen = EnvelopeGenNum::Decay;
} else if self.key > 0 && shift > 0 && rate_hi != 0x0f {
eg_inc = ((!self.eg_rout) << shift) >> 4;
}
}
EnvelopeGenNum::Decay => {
if (self.eg_rout >> 4) == self.reg_sl as isize {
self.eg_gen = EnvelopeGenNum::Sustain;
} else if eg_off == 0 && reset == 0 && shift > 0 {
eg_inc = 1 << (shift - 1);
}
}
EnvelopeGenNum::Sustain | EnvelopeGenNum::Release => {
if eg_off == 0 && reset == 0 && shift > 0 {
eg_inc = 1 << (shift - 1);
}
}
}
self.eg_rout = (eg_rout + eg_inc) & 0x1ff;
// Key off
if reset > 0 {
self.eg_gen = EnvelopeGenNum::Attack;
}
if self.key == 0 {
self.eg_gen = EnvelopeGenNum::Release;
}
}
fn key_on(&mut self, keytype: usize) {
self.key |= keytype;
}
fn key_off(&mut self, keytype: usize) {
self.key &= !keytype;
}
// Phase Generator
fn phase_generate(&mut self) {
let mut chip = &mut self.chip;
let (mut f_num, mut basefreq, mut rm_xor, mut n_bit, mut noise, mut phase) =
(0, 0, 0, 0, 0, 0);
f_num = self.channel.f_num;
if self.reg_vib > 0 {
let mut range = (f_num >> 7) & 7;
let vibpos = chip.vibpos;
if !(vibpos & 3) == 1 {
range = 0;
} else if (vibpos & 1) == 1 {
range >>= 1;
}
range >>= chip.vibshift;
if (vibpos & 4) > 0 {
range = 0;
}
f_num += range;
}
basefreq = (f_num << self.channel.block) >> 1;
phase = self.pg_phase >> 9;
if self.pg_reset > 0 {
self.pg_phase = 0;
}
self.pg_phase += (basefreq * MT[self.reg_mult]) >> 1;
// Rhythm mode
noise = chip.noise;
self.pg_phase_out = phase;
if self.slot_num == 13 {
// hh
chip.rm_hh_bit2 = (phase >> 2) & 1;
chip.rm_hh_bit3 = (phase >> 3) & 1;
chip.rm_hh_bit7 = (phase >> 7) & 1;
chip.rm_hh_bit8 = (phase >> 8) & 1;
}
if self.slot_num == 17 && (chip.rhy & 0x20) > 0 {
// tc
chip.rm_tc_bit3 = (phase >> 3) & 1;
chip.rm_tc_bit5 = (phase >> 5) & 1;
}
if (chip.rhy & 0x20) > 0 {
rm_xor = (chip.rm_hh_bit2 ^ chip.rm_hh_bit7)
| (chip.rm_hh_bit3 ^ chip.rm_tc_bit5)
| (chip.rm_tc_bit3 ^ chip.rm_tc_bit5);
match self.slot_num {
13 => {
self.pg_phase_out = rm_xor << 9;
if (rm_xor ^ (noise & 1)) > 0 {
self.pg_phase_out |= 0xd0;
} else {
self.pg_phase_out |= 0x34;
}
}
16 => {
self.pg_phase_out =
(chip.rm_hh_bit8 << 9) | ((chip.rm_hh_bit8 ^ (noise & 1)) << 8)
}
17 => self.pg_phase_out = (rm_xor << 9) | 0x80,
_ => (),
}
}
n_bit = ((noise >> 14) ^ noise) & 0x01;
chip.noise = (noise >> 1) | (n_bit << 22);
}
fn write20(&mut self, data: usize) {
if ((data >> 7) & 0x01) > 0 {
self.trem = self.chip.tremolo;
} else {
self.trem = self.chip.zeromod as usize;
}
self.reg_vib = (data >> 6) & 0x01;
self.reg_type = (data >> 5) & 0x01;
self.reg_ksr = (data >> 4) & 0x01;
self.reg_mult = data & 0x0f;
}
fn write40(&mut self, data: usize) {
self.reg_ksl = (data >> 6) & 0x03;
self.reg_tl = data & 0x3f;
self.update_ksl();
}
fn write60(&mut self, data: usize) {
self.reg_ar = (data >> 4) & 0x0f;
self.reg_dr = data & 0x0f;
}
fn write80(&mut self, data: usize) {
self.reg_sl = (data >> 4) & 0x0f;
if self.reg_sl == 0x0f {
self.reg_sl = 0x1f;
}
self.reg_rr = data & 0x0f;
}
fn write_e0(&mut self, data: usize) {
self.reg_wf = data & 0x07;
if self.chip.newm == 0x00 {
self.reg_wf &= 0x03;
}
}
fn generate(&mut self) {
match self.reg_wf {
0 => self.out = opl3_envelope_calc_sin0(self.pg_phase_out + (self.modifier as usize), self.eg_out as usize) as isize,
1 => self.out = opl3_envelope_calc_sin1(self.pg_phase_out + (self.modifier as usize), self.eg_out as usize) as isize,
2 => self.out = opl3_envelope_calc_sin2(self.pg_phase_out + (self.modifier as usize), self.eg_out as usize) as isize,
3 => self.out = opl3_envelope_calc_sin3(self.pg_phase_out + (self.modifier as usize), self.eg_out as usize) as isize,
4 => self.out = opl3_envelope_calc_sin4(self.pg_phase_out + (self.modifier as usize), self.eg_out as usize) as isize,
5 => self.out = opl3_envelope_calc_sin5(self.pg_phase_out + (self.modifier as usize), self.eg_out as usize) as isize,
6 => self.out = opl3_envelope_calc_sin6(self.pg_phase_out + (self.modifier as usize), self.eg_out as usize) as isize,
7 => self.out = opl3_envelope_calc_sin7(self.pg_phase_out + (self.modifier as usize), self.eg_out as usize) as isize,
_ => msgbox::create("Error", format!("The value {} in the waveform register of the FM OPL3 library extensions DLL is not valid. No slots will be generated.", self.reg_wf).as_str(), IconType::ERROR),
}
}
fn calc_fb(&mut self) {
if self.channel.fb != 0x00 {
self.fbmod = (self.prout + self.out) >> (0x09 - self.channel.fb);
} else {
self.fbmod = 0;
}
self.prout = self.out;
}
}
impl OPL3Channel {
fn setup_alg(&mut self) {
if self.chtype == ChannelType::Drum as usize {
if self.ch_num == 7 || self.ch_num == 8 {
self.slots[0].modifier = self.chip.zeromod;
self.slots[1].modifier = self.chip.zeromod;
}
match self.alg & 0x01 {
0x00 => {
self.slots[0].modifier = self.slots[0].fbmod;
self.slots[1].modifier = self.slots[0].out;
}
0x01 => {
self.slots[0].modifier = self.slots[0].fbmod;
self.slots[1].modifier = self.chip.zeromod;
}
_ => (),
}
}
if (self.alg & 0x08) > 0 {
}
if (self.alg & 0x04) > 0 {
self.pair.out[0] = self.chip.zeromod;
self.pair.out[1] = self.chip.zeromod;
self.pair.out[2] = self.chip.zeromod;
self.pair.out[3] = self.chip.zeromod;
match self.alg & 0x03 {
0x00 => {
self.pair.slots[0].modifier = self.pair.slots[0].fbmod;
self.pair.slots[1].modifier = self.pair.slots[0].out;
self.slots[0].modifier = self.pair.slots[1].out;
self.slots[1].modifier = self.slots[0].out;
self.out[0] = self.slots[1].out;
self.out[1] = self.chip.zeromod;
self.out[2] = self.chip.zeromod;
self.out[3] = self.chip.zeromod;
}
0x01 => {
self.pair.slots[0].modifier = self.pair.slots[0].fbmod;
self.pair.slots[1].modifier = self.pair.slots[0].out;
self.slots[0].modifier = self.chip.zeromod;
self.slots[1].modifier = self.slots[0].out;
self.out[0] = self.pair.slots[1].out;
self.out[1] = self.slots[1].out;
self.out[2] = self.chip.zeromod;
self.out[3] = self.chip.zeromod;
}
0x02 => {
self.pair.slots[0].modifier = self.pair.slots[0].fbmod;
self.pair.slots[1].modifier = self.chip.zeromod;
self.slots[0].modifier = self.pair.slots[1].out;
self.slots[1].modifier = self.slots[0].out;
self.out[0] = self.pair.slots[0].out;
self.out[1] = self.slots[1].out;
self.out[2] = self.chip.zeromod;
self.out[3] = self.chip.zeromod;
}
0x03 => {
self.pair.slots[0].modifier = self.pair.slots[0].fbmod;
self.pair.slots[1].modifier = self.chip.zeromod;
self.slots[0].modifier = self.pair.slots[1].out;
self.slots[1].modifier = self.chip.zeromod;
self.out[0] = self.pair.slots[0].out;
self.out[1] = self.slots[0].out;
self.out[2] = self.slots[1].out;
self.out[3] = self.chip.zeromod;
}
_ => (),
}
} else {
match self.alg & 0x01 {
0x00 => {
self.slots[0].modifier = self.slots[0].fbmod;
self.slots[1].modifier = self.slots[0].out;
self.out[0] = self.slots[1].out;
self.out[1] = self.chip.zeromod;
self.out[2] = self.chip.zeromod;
self.out[3] = self.chip.zeromod;
}
0x01 => {
self.slots[0].modifier = self.slots[0].fbmod;
self.slots[1].modifier = self.chip.zeromod;
self.out[0] = self.slots[0].out;
self.out[1] = self.slots[1].out;
self.out[2] = self.chip.zeromod;
self.out[3] = self.chip.zeromod;
}
_ => (),
}
}
}
fn write(&mut self, method: usize, data: usize) {
match method {
0xa0 => {
if self.chip.newm == 0 && self.chtype != ChannelType::FourOpTwo as usize {
self.f_num = (self.f_num & 0x300) | data;
self.ksv = (self.block << 1) | ((self.f_num >> (0x09 - self.chip.nts)) & 0x01);
self.slots[0].update_ksl();
self.slots[1].update_ksl();
if self.chip.newm > 0 && self.chtype == ChannelType::FourOp as usize {
self.pair.f_num = self.f_num;
self.pair.ksv = self.ksv;
self.pair.slots[0].update_ksl();
self.pair.slots[1].update_ksl();
}
}
}
0xb0 => {
if self.chip.newm == 0 && self.chtype != ChannelType::FourOpTwo as usize {
self.f_num = (self.f_num & 0xff) | ((data & 0x03) << 8);
self.block = (data >> 2) & 0x07;
self.ksv = (self.block << 1) | ((self.f_num >> (0x09 - self.chip.nts)) & 0x01);
self.slots[0].update_ksl();
self.slots[1].update_ksl();
if self.chip.newm > 0 && self.chtype == ChannelType::FourOp as usize {
self.pair.f_num = self.f_num;
self.pair.block = self.block;
self.pair.ksv = self.ksv;
self.pair.slots[0].update_ksl();
self.pair.slots[1].update_ksl();
}
}
}
0xc0 => {
self.fb = (data & 0x0e) >> 1;
self.con = data & 0x01;
self.alg = self.con;
if self.chip.newm > 0 {
if self.chtype == ChannelType::FourOp as usize {
self.pair.alg = 0x04 | (self.con << 1) | (self.pair.con);
self.alg = 0x08;
self.pair.setup_alg();
} else if self.chtype == ChannelType::FourOpTwo as usize {
self.alg = 0x04 | (self.pair.con << 1) | (self.con);
self.pair.alg = 0x08;
self.setup_alg();
} else {
self.setup_alg();
}
} else {
self.setup_alg();
}
if self.chip.newm > 0 {
self.cha = if ((data >> 4) & 0x01) > 0 { !0 } else { 0 };
self.chb = if ((data >> 5) & 0x01) > 0 { !0 } else { 0 };
} else {
self.cha = !0;
self.chb = !0;
}
if self.chip.stereoext > 0 {
self.leftpan = (self.cha as isize) << 16;
self.rightpan = (self.chb as isize) << 16;
}
}
0xd0 => {
if self.chip.stereoext > 0 {
self.leftpan = PANPOT_LUT[data ^ 0xff];
self.rightpan = PANPOT_LUT[data];
}
}
_ => (),
}
}
fn key_on(&mut self) {
if self.chip.newm > 0 {
if self.chtype == ChannelType::FourOp as usize {
self.slots[0].key_on(EnvelopeKeyType::Norm as usize);
self.slots[1].key_on(EnvelopeKeyType::Norm as usize);
self.pair.slots[0].key_on(EnvelopeKeyType::Norm as usize);
self.pair.slots[1].key_on(EnvelopeKeyType::Norm as usize);
} else if self.chtype == ChannelType::TwoOp as usize || self.chtype == ChannelType::Drum as usize {
self.slots[0].key_on(EnvelopeKeyType::Norm as usize);
self.slots[1].key_on(EnvelopeKeyType::Norm as usize);
}
} else {
self.slots[0].key_on(EnvelopeKeyType::Norm as usize);
self.slots[1].key_on(EnvelopeKeyType::Norm as usize);
}
}
}
|
use config::Config;
use errors::BigNeonError;
use lettre_email::EmailBuilder;
pub struct Mailer {
config: Config,
to: (String, String),
from: (String, String),
subject: String,
body: String,
}
impl Mailer {
pub fn new(
config: Config,
to: (String, String),
from: (String, String),
subject: String,
body: String,
) -> Mailer {
Mailer {
config,
to,
from,
subject,
body,
}
}
pub fn to(&self) -> (String, String) {
self.to.clone()
}
pub fn from(&self) -> (String, String) {
self.from.clone()
}
pub fn subject(&self) -> String {
self.subject.clone()
}
pub fn body(&self) -> String {
self.body.clone()
}
pub fn deliver(&mut self) -> Result<(), BigNeonError> {
let email = EmailBuilder::new()
.to(self.to())
.from(self.from())
.subject(self.subject())
.text(self.body())
.build()
.unwrap();
self.config.mail_transport.send(email)
}
}
|
extern crate liquid;
extern crate serde;
extern crate structopt;
use pulldown_cmark::{html, Parser};
use rouille::Response;
use std::path::PathBuf;
use serde::Serialize;
use notify::{watcher, DebouncedEvent, RecursiveMode, Watcher};
use structopt::StructOpt;
const DEFAULT_STYLES: &str = include_str!("default.css");
const WEB_TEMPLATE: &str = include_str!("shell.html");
#[derive(Clone, Debug, StructOpt)]
#[structopt(name = "marp")]
struct Cli {
#[structopt(parse(from_os_str))]
file: PathBuf,
#[structopt(
short = "s",
long = "stylesheet",
help = "A .css file to replace the default styles",
parse(from_os_str)
)]
stylesheet: Option<PathBuf>,
#[structopt(
long = "no-open",
help = "Do not open the rendered markdown in the browser"
)]
no_open: bool,
#[structopt(short = "p", long = "port", default_value = "8000")]
port: u16,
}
#[derive(Debug, Serialize)]
struct Update {
stylesheet: Option<String>,
content: Option<String>,
}
fn main() {
run(Cli::from_args());
}
fn run(opt: Cli) {
let styles = match &opt.stylesheet {
Some(path) => std::fs::read_to_string(&path).expect("could not read file"),
None => DEFAULT_STYLES.to_string(),
};
let initial_html = parse_file(&opt.file);
let websocket = build_websocket(initial_html, styles);
let broadcaster = websocket.broadcaster();
let rendered_template = std::sync::Arc::new(render_web_template());
let addr = ([127, 0, 0, 1], opt.port).into();
let open = !&opt.no_open;
let shared_options = std::sync::Arc::new(opt);
crossbeam::scope(|scope| {
let c1 = shared_options.clone();
scope.spawn(move |_| watch_and_parse(&c1, broadcaster));
scope.spawn(move |_| websocket.listen("127.0.0.1:3012"));
scope.spawn(move |_| {
start_server(
&shared_options.clone(),
rendered_template.as_str().to_owned(),
&addr,
)
});
println!("Serving content at http://{}", addr);
if open {
open_page(&addr);
}
})
.unwrap();
}
fn start_server(cli: &Cli, fallback: String, addr: &std::net::SocketAddr) {
let mut path = cli.file.to_owned();
path.pop();
let shared_fallback = std::sync::Arc::new(fallback);
let root_directory = std::sync::Arc::new(path.to_string_lossy().into_owned());
rouille::start_server(addr.to_string(), move |request| {
{
let response = rouille::match_assets(&request, root_directory.as_str());
if response.is_success() {
return response;
}
}
let uri = request.url().parse::<http::Uri>().unwrap();
if uri.path() == "/" {
return Response::html(shared_fallback.as_str());
}
Response::html(
"404 error. Try <a href=\"/README.md\"`>README.md</a> or \
<a href=\"/src/lib.rs\">src/lib.rs</a> for example.",
)
.with_status_code(404)
});
}
fn build_websocket(
content: String,
styles: String,
) -> ws::WebSocket<impl ws::Factory<Handler = impl ws::Handler>> {
ws::Builder::new()
.build(move |out: ws::Sender| {
let cloned_content = content.clone();
let cloned_styles = styles.clone();
move |_| {
let initial_message = Update {
content: Some(cloned_content.to_string()),
stylesheet: Some(cloned_styles.to_string()),
};
let serialized = serde_json::to_string(&initial_message).unwrap();
out.send(ws::Message::text(serialized.to_string())).unwrap();
println!("Connection established");
Ok(())
}
})
.unwrap()
}
fn render_web_template() -> String {
let html = liquid::ParserBuilder::with_liquid()
.build()
.unwrap()
.parse(WEB_TEMPLATE)
.unwrap();
let mut template_values = liquid::value::Object::new();
template_values.insert("websocketPort".into(), liquid::value::Value::scalar(3012));
html.render(&template_values).unwrap()
}
fn open_page(addr: &std::net::SocketAddr) {
std::process::Command::new("open")
.arg(format!("http://{}", addr))
.spawn()
.unwrap();
}
fn watch_and_parse(config: &Cli, output: ws::Sender) {
let (sender, receiver) = std::sync::mpsc::channel();
let debounce_duration = std::time::Duration::from_millis(30);
let mut watcher = watcher(sender, debounce_duration).unwrap();
watcher
.watch(&config.file, RecursiveMode::NonRecursive)
.unwrap();
if let Some(stylesheet) = &config.stylesheet {
watcher
.watch(stylesheet, RecursiveMode::NonRecursive)
.unwrap();
}
let canonical_content_path = std::fs::canonicalize(&config.file).unwrap();
let canonical_stylesheet_path = config
.stylesheet
.as_ref()
.map(|p| std::fs::canonicalize(p).unwrap());
loop {
let event = receiver.recv();
match event {
Ok(DebouncedEvent::Write(path)) | Ok(DebouncedEvent::Create(path)) => {
let (content, stylesheet) = if path == canonical_content_path {
(Some(parse_file(&path).to_string()), None)
} else if Some(&path) == canonical_stylesheet_path.as_ref() {
let styles = std::fs::read_to_string(&path).expect("could not read file");
(None, Some(styles))
} else {
unreachable!();
};
let update = Update {
content,
stylesheet,
};
let serialized = serde_json::to_string(&update).unwrap();
output.send(serialized).unwrap();
}
_ => {
println!("{:?}", event);
}
}
}
}
fn parse_file(path: &PathBuf) -> String {
let content = std::fs::read_to_string(&path).expect("could not read file");
let parser = Parser::new(&content);
let mut html_output = String::new();
html::push_html(&mut html_output, parser);
html_output
}
|
use anyhow::{bail, Result};
pub struct InputBuffer<'a> {
pos: usize,
len: usize,
data: &'a [u8],
}
impl<'a> InputBuffer<'a> {
pub fn new(buf: &'a [u8]) -> Self {
InputBuffer {
pos: 0,
len: buf.len(),
data: buf,
}
}
pub fn set_data(&mut self, buf: &'a [u8]) {
self.pos = 0;
self.len = buf.len();
self.data = buf;
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn position(&self) -> usize {
self.pos
}
pub fn set_position(&mut self, p: usize) -> Result<()> {
if p <= self.len {
self.pos = p;
Ok(())
} else {
bail!("set position out of range");
}
}
pub fn read_u8(&mut self) -> Result<u8> {
if self.pos < self.len {
let num = self.data[self.pos];
self.pos += 1;
Ok(num)
} else {
bail!("no space for u8 left in buffer");
}
}
pub fn read_u16(&mut self) -> Result<u16> {
if self.pos + 1 < self.len {
let mut num = u16::from(self.data[self.pos]) << 8;
num |= u16::from(self.data[self.pos + 1]);
self.pos += 2;
Ok(num)
} else {
bail!("no space for u16 left in buffer");
}
}
pub fn read_u32(&mut self) -> Result<u32> {
if self.pos + 3 < self.len {
let mut num = u32::from(self.data[self.pos]) << 24;
num |= u32::from(self.data[self.pos + 1]) << 16;
num |= u32::from(self.data[self.pos + 2]) << 8;
num |= u32::from(self.data[self.pos + 3]);
self.pos += 4;
Ok(num)
} else {
bail!("no space for u32 left in buffer");
}
}
pub fn read_bytes(&mut self, len: usize) -> Result<&'a [u8]> {
if self.pos + len <= self.len {
let pos = self.pos;
let data = &self.data[pos..(pos + len)];
self.pos = pos + len;
Ok(data)
} else {
bail!("no space for bytes with len {} left in buffer", len);
}
}
}
|
pub fn check_palindrome(input: &str) -> bool {
if input.len() == 0 {
return true;
}
let mut last = input.len() - 1;
let mut first = 0;
let my_vec = input.as_bytes().to_owned();
while first < last {
if my_vec[fistt] != my_vec[last] {
return false;
}
first += 1;
last -= 1;
}
return true;
}
|
use crate::model::Article;
use derive_more::From;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ArticleSearchIndex {
#[serde(default)]
section: String,
#[serde(default)]
category: String,
#[serde(default)]
tags: Vec<String>,
#[serde(default)]
aliases: Vec<String>,
#[serde(default)]
summary: String,
#[serde(default)]
name: String,
#[serde(default)]
filename: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DisambiguationSearchIndex {
#[serde(default)]
pub name: String,
#[serde(default)]
pub articles: Vec<ArticleSearchIndex>,
}
#[derive(Debug, Clone, Deserialize, Serialize, From)]
#[serde(untagged)]
pub enum SearchIndex {
Article(ArticleSearchIndex),
Disambiguation(DisambiguationSearchIndex),
}
impl From<Vec<Article>> for DisambiguationSearchIndex {
fn from(articles: Vec<Article>) -> Self {
assert_ne!(articles.len(), 0);
Self {
name: articles[0].name.clone(),
articles: articles.into_iter().map(Article::into).collect(),
}
}
}
impl From<Article> for ArticleSearchIndex {
fn from(article: Article) -> Self {
Self {
section: article.section,
category: article.metadata.category,
tags: article.metadata.tags,
aliases: article.metadata.aliases,
summary: article.summary,
name: article.name,
filename: article.content.filename,
}
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "ApplicationModel_Store_Preview_InstallControl")]
pub mod InstallControl;
#[link(name = "windows")]
extern "system" {}
#[repr(transparent)]
pub struct DeliveryOptimizationDownloadMode(pub i32);
impl DeliveryOptimizationDownloadMode {
pub const Simple: Self = Self(0i32);
pub const HttpOnly: Self = Self(1i32);
pub const Lan: Self = Self(2i32);
pub const Group: Self = Self(3i32);
pub const Internet: Self = Self(4i32);
pub const Bypass: Self = Self(5i32);
}
impl ::core::marker::Copy for DeliveryOptimizationDownloadMode {}
impl ::core::clone::Clone for DeliveryOptimizationDownloadMode {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct DeliveryOptimizationDownloadModeSource(pub i32);
impl DeliveryOptimizationDownloadModeSource {
pub const Default: Self = Self(0i32);
pub const Policy: Self = Self(1i32);
}
impl ::core::marker::Copy for DeliveryOptimizationDownloadModeSource {}
impl ::core::clone::Clone for DeliveryOptimizationDownloadModeSource {
fn clone(&self) -> Self {
*self
}
}
pub type DeliveryOptimizationSettings = *mut ::core::ffi::c_void;
pub type StoreHardwareManufacturerInfo = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct StoreLogOptions(pub u32);
impl StoreLogOptions {
pub const None: Self = Self(0u32);
pub const TryElevate: Self = Self(1u32);
}
impl ::core::marker::Copy for StoreLogOptions {}
impl ::core::clone::Clone for StoreLogOptions {
fn clone(&self) -> Self {
*self
}
}
pub type StorePreviewProductInfo = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct StorePreviewProductPurchaseStatus(pub i32);
impl StorePreviewProductPurchaseStatus {
pub const Succeeded: Self = Self(0i32);
pub const AlreadyPurchased: Self = Self(1i32);
pub const NotFulfilled: Self = Self(2i32);
pub const NotPurchased: Self = Self(3i32);
}
impl ::core::marker::Copy for StorePreviewProductPurchaseStatus {}
impl ::core::clone::Clone for StorePreviewProductPurchaseStatus {
fn clone(&self) -> Self {
*self
}
}
pub type StorePreviewPurchaseResults = *mut ::core::ffi::c_void;
pub type StorePreviewSkuInfo = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct StoreSystemFeature(pub i32);
impl StoreSystemFeature {
pub const ArchitectureX86: Self = Self(0i32);
pub const ArchitectureX64: Self = Self(1i32);
pub const ArchitectureArm: Self = Self(2i32);
pub const DirectX9: Self = Self(3i32);
pub const DirectX10: Self = Self(4i32);
pub const DirectX11: Self = Self(5i32);
pub const D3D12HardwareFL11: Self = Self(6i32);
pub const D3D12HardwareFL12: Self = Self(7i32);
pub const Memory300MB: Self = Self(8i32);
pub const Memory750MB: Self = Self(9i32);
pub const Memory1GB: Self = Self(10i32);
pub const Memory2GB: Self = Self(11i32);
pub const CameraFront: Self = Self(12i32);
pub const CameraRear: Self = Self(13i32);
pub const Gyroscope: Self = Self(14i32);
pub const Hover: Self = Self(15i32);
pub const Magnetometer: Self = Self(16i32);
pub const Nfc: Self = Self(17i32);
pub const Resolution720P: Self = Self(18i32);
pub const ResolutionWvga: Self = Self(19i32);
pub const ResolutionWvgaOr720P: Self = Self(20i32);
pub const ResolutionWxga: Self = Self(21i32);
pub const ResolutionWvgaOrWxga: Self = Self(22i32);
pub const ResolutionWxgaOr720P: Self = Self(23i32);
pub const Memory4GB: Self = Self(24i32);
pub const Memory6GB: Self = Self(25i32);
pub const Memory8GB: Self = Self(26i32);
pub const Memory12GB: Self = Self(27i32);
pub const Memory16GB: Self = Self(28i32);
pub const Memory20GB: Self = Self(29i32);
pub const VideoMemory2GB: Self = Self(30i32);
pub const VideoMemory4GB: Self = Self(31i32);
pub const VideoMemory6GB: Self = Self(32i32);
pub const VideoMemory1GB: Self = Self(33i32);
pub const ArchitectureArm64: Self = Self(34i32);
}
impl ::core::marker::Copy for StoreSystemFeature {}
impl ::core::clone::Clone for StoreSystemFeature {
fn clone(&self) -> Self {
*self
}
}
|
use crate::parser::parse_error::{IonError, IonResult};
use nom::error::ParseError;
use nom::InputLength;
use nom::{error::ErrorKind, Err};
/// A collection of parser combinators for building Ion parsers. Mostly forked from nom for various reasons.
/// FIXME: Modifying code from nom like this is unfortunate, and hopefully at some point will be unnecessary.
/// See https://github.com/Geal/nom/pull/1002
/// Matches an object from the first parser and discards it,
/// then gets an object from the second parser.
/// Derived from nom::sequence::preceded to lower the trait bound from Fn to FnMut.
pub fn preceded<I, O1, O2, F, G>(mut first: F, mut second: G) -> impl FnMut(I) -> IonResult<I, O2>
where
F: FnMut(I) -> IonResult<I, O1>,
G: FnMut(I) -> IonResult<I, O2>,
{
move |input: I| {
let (input, _) = first(input)?;
second(input)
}
}
/// Repeats the embedded parser until it fails and returns the results in a `Vec`.
/// Derived from nom::multi::many0 to lower the trait bound from Fn to FnMut.
pub fn many0<I, O, F>(mut f: F) -> impl FnMut(I) -> IonResult<I, Vec<O>>
where
I: Clone + PartialEq,
F: FnMut(I) -> IonResult<I, O>,
{
move |i: I| {
let mut acc = std::vec::Vec::with_capacity(4);
let mut i = i;
loop {
match f(i.clone()) {
Err(Err::Error(_)) => return Ok((i, acc)),
Err(e) => return Err(e),
Ok((i1, o)) => {
if i1 == i {
return Err(Err::Error(IonError::from_error_kind(i, ErrorKind::Many0)));
}
i = i1;
acc.push(o);
}
}
}
}
}
/// succeeds if all the input has been consumed by its child parser
/// Derived from nom::combinator::all_consuming to lower the trait bound from Fn to FnMut.
pub fn all_consuming<I, O, F>(mut f: F) -> impl FnMut(I) -> IonResult<I, O>
where
I: InputLength,
F: FnMut(I) -> IonResult<I, O>,
{
move |input: I| {
let (input, res) = f(input)?;
if input.input_len() == 0 {
Ok((input, res))
} else {
Err(Err::Error(IonError::from_error_kind(input, ErrorKind::Eof)))
}
}
}
/// maps a function on the result of a parser
/// Derived from nom::combinator::map to lower the trait bound from Fn to FnMut.
pub fn map<I, O1, O2, F, G>(mut first: F, second: G) -> impl FnMut(I) -> IonResult<I, O2>
where
F: FnMut(I) -> IonResult<I, O1>,
G: Fn(O1) -> O2,
{
move |input: I| {
let (input, o1) = first(input)?;
Ok((input, second(o1)))
}
}
|
//! Application Manager service.
//!
//! As the name implies, the AM service manages installed applications. It can:
//! - Read the installed applications on the console and their information (depending on the install location).
//! - Install compatible applications to the console.
//!
//! TODO: [`ctru-rs`](crate) doesn't support installing or uninstalling titles yet.
#![doc(alias = "app")]
#![doc(alias = "manager")]
use crate::error::ResultCode;
use crate::services::fs::FsMediaType;
use std::marker::PhantomData;
/// General information about a specific title entry.
#[doc(alias = "AM_TitleEntry")]
pub struct Title<'a> {
id: u64,
mediatype: FsMediaType,
size: u64,
version: u16,
_am: PhantomData<&'a Am>,
}
impl<'a> Title<'a> {
/// Returns this title's ID.
pub fn id(&self) -> u64 {
self.id
}
/// Returns this title's unique product code.
#[doc(alias = "AM_GetTitleProductCode")]
pub fn product_code(&self) -> String {
let mut buf: [u8; 16] = [0; 16];
// This operation is safe as long as the title was correctly obtained via [`Am::title_list()`].
unsafe {
let _ =
ctru_sys::AM_GetTitleProductCode(self.mediatype.into(), self.id, buf.as_mut_ptr());
}
String::from_utf8_lossy(&buf).to_string()
}
/// Returns the size of this title in bytes.
pub fn size(&self) -> u64 {
self.size
}
/// Returns the installed version of this title.
pub fn version(&self) -> u16 {
self.version
}
}
/// Handle to the Application Manager service.
pub struct Am(());
impl Am {
/// Initialize a new service handle.
///
/// # Example
///
/// ```no_run
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// #
/// use ctru::services::am::Am;
///
/// let app_manager = Am::new()?;
/// #
/// # Ok(())
/// # }
/// ```
#[doc(alias = "amInit")]
pub fn new() -> crate::Result<Am> {
unsafe {
ResultCode(ctru_sys::amInit())?;
Ok(Am(()))
}
}
/// Returns the amount of titles currently installed in a specific install location.
///
/// # Example
///
/// ```no_run
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// #
/// use ctru::services::{fs::FsMediaType, am::Am};
/// let app_manager = Am::new()?;
///
/// // Number of titles installed on the Nand storage.
/// let nand_count = app_manager.title_count(FsMediaType::Nand);
///
/// // Number of apps installed on the SD card storage
/// let sd_count = app_manager.title_count(FsMediaType::Sd);
/// #
/// # Ok(())
/// # }
/// ```
#[doc(alias = "AM_GetTitleCount")]
pub fn title_count(&self, mediatype: FsMediaType) -> crate::Result<u32> {
unsafe {
let mut count = 0;
ResultCode(ctru_sys::AM_GetTitleCount(mediatype.into(), &mut count))?;
Ok(count)
}
}
/// Returns the list of titles installed in a specific install location.
///
/// # Example
///
/// ```no_run
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// #
/// use ctru::services::{fs::FsMediaType, am::Am};
/// let app_manager = Am::new()?;
///
/// // Number of apps installed on the SD card storage
/// let sd_titles = app_manager.title_list(FsMediaType::Sd)?;
///
/// // Unique product code identifier of the 5th installed title.
/// let product_code = sd_titles[4].product_code();
/// #
/// # Ok(())
/// # }
/// ```
#[doc(alias = "AM_GetTitleList")]
pub fn title_list(&self, mediatype: FsMediaType) -> crate::Result<Vec<Title>> {
let count = self.title_count(mediatype)?;
let mut buf = vec![0; count as usize];
let mut read_amount = 0;
unsafe {
ResultCode(ctru_sys::AM_GetTitleList(
&mut read_amount,
mediatype.into(),
count,
buf.as_mut_ptr(),
))?;
}
let mut info: Vec<ctru_sys::AM_TitleEntry> = Vec::with_capacity(count as _);
unsafe {
ResultCode(ctru_sys::AM_GetTitleInfo(
mediatype.into(),
count,
buf.as_mut_ptr(),
info.as_mut_ptr() as _,
))?;
info.set_len(count as _);
};
Ok(info
.into_iter()
.map(|title| Title {
id: title.titleID,
mediatype,
size: title.size,
version: title.version,
_am: PhantomData,
})
.collect())
}
}
impl Drop for Am {
#[doc(alias = "amExit")]
fn drop(&mut self) {
unsafe { ctru_sys::amExit() };
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use std::fmt::Formatter;
use std::sync::Arc;
use crate::processors::port::InputPort;
use crate::processors::port::OutputPort;
use crate::processors::processor::ProcessorPtr;
#[derive(Clone)]
pub struct PipeItem {
pub processor: ProcessorPtr,
pub inputs_port: Vec<Arc<InputPort>>,
pub outputs_port: Vec<Arc<OutputPort>>,
}
impl PipeItem {
pub fn create(
proc: ProcessorPtr,
inputs: Vec<Arc<InputPort>>,
outputs: Vec<Arc<OutputPort>>,
) -> PipeItem {
PipeItem {
processor: proc,
inputs_port: inputs,
outputs_port: outputs,
}
}
}
impl Debug for PipeItem {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PipeItem")
.field("name", &unsafe { self.processor.name() })
.field("inputs", &self.inputs_port.len())
.field("outputs", &self.outputs_port.len())
.finish()
}
}
#[derive(Clone)]
pub struct Pipe {
pub items: Vec<PipeItem>,
pub input_length: usize,
pub output_length: usize,
}
impl Debug for Pipe {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", &self.items)
}
}
impl Pipe {
pub fn create(inputs: usize, outputs: usize, items: Vec<PipeItem>) -> Pipe {
Pipe {
items,
input_length: inputs,
output_length: outputs,
}
}
}
#[derive(Clone)]
pub struct SourcePipeBuilder {
items: Vec<PipeItem>,
}
impl SourcePipeBuilder {
pub fn create() -> SourcePipeBuilder {
SourcePipeBuilder { items: vec![] }
}
pub fn finalize(self) -> Pipe {
Pipe::create(0, self.items.len(), self.items)
}
pub fn add_source(&mut self, output_port: Arc<OutputPort>, source: ProcessorPtr) {
self.items
.push(PipeItem::create(source, vec![], vec![output_port]));
}
}
#[allow(dead_code)]
pub struct SinkPipeBuilder {
items: Vec<PipeItem>,
}
#[allow(dead_code)]
impl SinkPipeBuilder {
pub fn create() -> SinkPipeBuilder {
SinkPipeBuilder { items: vec![] }
}
pub fn finalize(self) -> Pipe {
Pipe::create(self.items.len(), 0, self.items)
}
pub fn add_sink(&mut self, inputs_port: Arc<InputPort>, sink: ProcessorPtr) {
self.items
.push(PipeItem::create(sink, vec![inputs_port], vec![]));
}
}
pub struct TransformPipeBuilder {
items: Vec<PipeItem>,
}
impl TransformPipeBuilder {
pub fn create() -> TransformPipeBuilder {
TransformPipeBuilder { items: vec![] }
}
pub fn finalize(self) -> Pipe {
Pipe::create(self.items.len(), self.items.len(), self.items)
}
pub fn add_transform(
&mut self,
input: Arc<InputPort>,
output: Arc<OutputPort>,
proc: ProcessorPtr,
) {
self.items
.push(PipeItem::create(proc, vec![input], vec![output]));
}
}
|
pub fn get_student_exam_queue_names(
id_student: i32,
id_student_exam: i32,
) -> (String, String, String) {
let exchange_name = String::from("e_exam");
let queue_name = format!(
"q_exam_{}_student_{}",
id_student_exam.to_string(),
id_student.to_string()
);
let routing_key = format!(
"r_exam_{}_student_{}",
id_student_exam.to_string(),
id_student.to_string()
);
return (exchange_name, queue_name, routing_key);
}
|
#[doc = "Reader of register ICSCR"]
pub type R = crate::R<u32, super::ICSCR>;
#[doc = "Writer for register ICSCR"]
pub type W = crate::W<u32, super::ICSCR>;
#[doc = "Register ICSCR `reset()`'s with value 0xb000"]
impl crate::ResetValue for super::ICSCR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0xb000
}
}
#[doc = "Reader of field `MSITRIM`"]
pub type MSITRIM_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `MSITRIM`"]
pub struct MSITRIM_W<'a> {
w: &'a mut W,
}
impl<'a> MSITRIM_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xff << 24)) | (((value as u32) & 0xff) << 24);
self.w
}
}
#[doc = "Reader of field `MSICAL`"]
pub type MSICAL_R = crate::R<u8, u8>;
#[doc = "MSI clock ranges\n\nValue on reset: 5"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum MSIRANGE_A {
#[doc = "0: range 0 around 65.536 kHz"]
RANGE0 = 0,
#[doc = "1: range 1 around 131.072 kHz"]
RANGE1 = 1,
#[doc = "2: range 2 around 262.144 kHz"]
RANGE2 = 2,
#[doc = "3: range 3 around 524.288 kHz"]
RANGE3 = 3,
#[doc = "4: range 4 around 1.048 MHz"]
RANGE4 = 4,
#[doc = "5: range 5 around 2.097 MHz (reset value)"]
RANGE5 = 5,
#[doc = "6: range 6 around 4.194 MHz"]
RANGE6 = 6,
#[doc = "7: not allowed"]
RANGE7 = 7,
}
impl From<MSIRANGE_A> for u8 {
#[inline(always)]
fn from(variant: MSIRANGE_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `MSIRANGE`"]
pub type MSIRANGE_R = crate::R<u8, MSIRANGE_A>;
impl MSIRANGE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MSIRANGE_A {
match self.bits {
0 => MSIRANGE_A::RANGE0,
1 => MSIRANGE_A::RANGE1,
2 => MSIRANGE_A::RANGE2,
3 => MSIRANGE_A::RANGE3,
4 => MSIRANGE_A::RANGE4,
5 => MSIRANGE_A::RANGE5,
6 => MSIRANGE_A::RANGE6,
7 => MSIRANGE_A::RANGE7,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `RANGE0`"]
#[inline(always)]
pub fn is_range0(&self) -> bool {
*self == MSIRANGE_A::RANGE0
}
#[doc = "Checks if the value of the field is `RANGE1`"]
#[inline(always)]
pub fn is_range1(&self) -> bool {
*self == MSIRANGE_A::RANGE1
}
#[doc = "Checks if the value of the field is `RANGE2`"]
#[inline(always)]
pub fn is_range2(&self) -> bool {
*self == MSIRANGE_A::RANGE2
}
#[doc = "Checks if the value of the field is `RANGE3`"]
#[inline(always)]
pub fn is_range3(&self) -> bool {
*self == MSIRANGE_A::RANGE3
}
#[doc = "Checks if the value of the field is `RANGE4`"]
#[inline(always)]
pub fn is_range4(&self) -> bool {
*self == MSIRANGE_A::RANGE4
}
#[doc = "Checks if the value of the field is `RANGE5`"]
#[inline(always)]
pub fn is_range5(&self) -> bool {
*self == MSIRANGE_A::RANGE5
}
#[doc = "Checks if the value of the field is `RANGE6`"]
#[inline(always)]
pub fn is_range6(&self) -> bool {
*self == MSIRANGE_A::RANGE6
}
#[doc = "Checks if the value of the field is `RANGE7`"]
#[inline(always)]
pub fn is_range7(&self) -> bool {
*self == MSIRANGE_A::RANGE7
}
}
#[doc = "Write proxy for field `MSIRANGE`"]
pub struct MSIRANGE_W<'a> {
w: &'a mut W,
}
impl<'a> MSIRANGE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MSIRANGE_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "range 0 around 65.536 kHz"]
#[inline(always)]
pub fn range0(self) -> &'a mut W {
self.variant(MSIRANGE_A::RANGE0)
}
#[doc = "range 1 around 131.072 kHz"]
#[inline(always)]
pub fn range1(self) -> &'a mut W {
self.variant(MSIRANGE_A::RANGE1)
}
#[doc = "range 2 around 262.144 kHz"]
#[inline(always)]
pub fn range2(self) -> &'a mut W {
self.variant(MSIRANGE_A::RANGE2)
}
#[doc = "range 3 around 524.288 kHz"]
#[inline(always)]
pub fn range3(self) -> &'a mut W {
self.variant(MSIRANGE_A::RANGE3)
}
#[doc = "range 4 around 1.048 MHz"]
#[inline(always)]
pub fn range4(self) -> &'a mut W {
self.variant(MSIRANGE_A::RANGE4)
}
#[doc = "range 5 around 2.097 MHz (reset value)"]
#[inline(always)]
pub fn range5(self) -> &'a mut W {
self.variant(MSIRANGE_A::RANGE5)
}
#[doc = "range 6 around 4.194 MHz"]
#[inline(always)]
pub fn range6(self) -> &'a mut W {
self.variant(MSIRANGE_A::RANGE6)
}
#[doc = "not allowed"]
#[inline(always)]
pub fn range7(self) -> &'a mut W {
self.variant(MSIRANGE_A::RANGE7)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 13)) | (((value as u32) & 0x07) << 13);
self.w
}
}
#[doc = "Reader of field `HSI16TRIM`"]
pub type HSI16TRIM_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `HSI16TRIM`"]
pub struct HSI16TRIM_W<'a> {
w: &'a mut W,
}
impl<'a> HSI16TRIM_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x1f << 8)) | (((value as u32) & 0x1f) << 8);
self.w
}
}
#[doc = "Reader of field `HSI16CAL`"]
pub type HSI16CAL_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 24:31 - MSI clock trimming"]
#[inline(always)]
pub fn msitrim(&self) -> MSITRIM_R {
MSITRIM_R::new(((self.bits >> 24) & 0xff) as u8)
}
#[doc = "Bits 16:23 - MSI clock calibration"]
#[inline(always)]
pub fn msical(&self) -> MSICAL_R {
MSICAL_R::new(((self.bits >> 16) & 0xff) as u8)
}
#[doc = "Bits 13:15 - MSI clock ranges"]
#[inline(always)]
pub fn msirange(&self) -> MSIRANGE_R {
MSIRANGE_R::new(((self.bits >> 13) & 0x07) as u8)
}
#[doc = "Bits 8:12 - High speed internal clock trimming"]
#[inline(always)]
pub fn hsi16trim(&self) -> HSI16TRIM_R {
HSI16TRIM_R::new(((self.bits >> 8) & 0x1f) as u8)
}
#[doc = "Bits 0:7 - nternal high speed clock calibration"]
#[inline(always)]
pub fn hsi16cal(&self) -> HSI16CAL_R {
HSI16CAL_R::new((self.bits & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 24:31 - MSI clock trimming"]
#[inline(always)]
pub fn msitrim(&mut self) -> MSITRIM_W {
MSITRIM_W { w: self }
}
#[doc = "Bits 13:15 - MSI clock ranges"]
#[inline(always)]
pub fn msirange(&mut self) -> MSIRANGE_W {
MSIRANGE_W { w: self }
}
#[doc = "Bits 8:12 - High speed internal clock trimming"]
#[inline(always)]
pub fn hsi16trim(&mut self) -> HSI16TRIM_W {
HSI16TRIM_W { w: self }
}
}
|
use std::collections::hash_map::Entry;
use std::ops::Deref;
use bincode;
use bytes::Bytes;
use futures::Stream;
use futures::sync::mpsc::unbounded;
use proto::{MqttPacket, Payload, PacketId, QualityOfService, TopicName, TopicFilter};
use persistence::Persistence;
use errors::{Result, Error, ErrorKind, ResultExt};
use errors::proto::{ErrorKind as ProtoErrorKind};
use backend::mqtt_loop::LoopData;
use backend::{OneTimeKey, ClientReturn, SubItem, PublishState};
use types::SubscriptionStream;
pub fn sub_ack_handler<P>(packet: MqttPacket, data: &mut LoopData<P>) ->
Result<Option<MqttPacket>> where P: Persistence {
let packet_id = packet.headers.get::<PacketId>().unwrap();
let (o, c) = match data.one_time.entry(OneTimeKey::Subscribe(*packet_id)) {
Entry::Vacant(v) => {
return Err(ErrorKind::from(ProtoErrorKind::UnexpectedResponse(
packet.ty.clone())).into());
},
Entry::Occupied(o) => o.remove()
};
// Validate each return code
let orig = match o.payload {
Payload::Subscribe(v) => v,
_ => unreachable!()
};
let ret_codes = match packet.payload {
Payload::SubAck(v) => v,
_ => unreachable!()
};
let mut collect: Vec<Result<(SubscriptionStream, QualityOfService)>> = Vec::new();
for (sub, ret) in orig.iter().zip(ret_codes.iter()) {
if ret.is_ok() {
let (tx, rx) = unbounded::<Result<SubItem>>();
let filter = TopicFilter::from_string(&sub.topic)?;
data.subscriptions.insert(sub.topic.clone().into(), (filter, tx));
let res: Result<(SubscriptionStream, QualityOfService)> = Ok((rx.into(), sub.qos));
collect.push(res);
} else {
collect.push(Err(ErrorKind::from(
ProtoErrorKind::SubscriptionRejected(
sub.topic.clone().into(), sub.qos)
).into()
));
}
}
let _ = c.send(Ok(ClientReturn::Ongoing(collect)));
Ok(None)
}
pub fn unsub_ack_handler<P>(packet: MqttPacket, data: &mut LoopData<P>) ->
Result<Option<MqttPacket>> where P: Persistence {
let pid = packet.headers.get::<PacketId>().unwrap();
let (o, c) = match data.one_time.entry(OneTimeKey::Unsubscribe(*pid)) {
Entry::Vacant(v) => {
return Err(ErrorKind::from(ProtoErrorKind::UnexpectedResponse(
packet.ty.clone())).into());
},
Entry::Occupied(o) => o.remove()
};
let topics = match o.payload {
Payload::Unsubscribe(v) => v,
_ => unreachable!()
};
// Remove subscriptions from loop
for topic in topics {
let _ = data.subscriptions.remove(topic.deref());
}
let _ = c.send(Ok(ClientReturn::Onetime(None)));
Ok(None)
}
pub fn ping_resp_handler<P>(data: &mut LoopData<P>) -> Result<Option<MqttPacket>>
where P: Persistence {
for client in data.ping_subs.drain(0..) {
let _ = client.send(Ok(ClientReturn::Onetime(None)));
}
Ok(None)
}
pub fn publish_handler<P>(packet: MqttPacket, data: &mut LoopData<P>) ->
Result<Option<MqttPacket>> where P: Persistence {
match packet.flags.qos() {
QualityOfService::QoS0 => {
let topic = packet.headers.get::<TopicName>().unwrap();
let payload = match packet.payload {
Payload::Application(d) => d,
_ => unreachable!()
};
for &(ref filter, ref sender) in data.subscriptions.values() {
if filter.match_topic(&topic) {
let _ = sender.unbounded_send(Ok(SubItem(topic.clone(), payload.clone())));
}
}
Ok(None)
},
QualityOfService::QoS1 => {
let id = packet.headers.get::<PacketId>().unwrap();
let topic = packet.headers.get::<TopicName>().unwrap();
let payload = match packet.payload {
Payload::Application(d) => d,
_ => unreachable!()
};
for &(ref filter, ref sender) in data.subscriptions.values() {
if filter.match_topic(&topic) {
let _ = sender.unbounded_send(Ok(SubItem(topic.clone(), payload.clone())));
}
}
// Send back an acknowledgement
Ok(Some(MqttPacket::pub_ack_packet(*id)))
},
QualityOfService::QoS2 => {
let id = packet.headers.get::<PacketId>().unwrap();
// Check if we have an existing publish with the same id
if data.server_publish_state.contains_key(&id) {
return Err(ProtoErrorKind::QualityOfServiceError(
packet.flags.qos(),
format!("Duplicate publish recieved with same Packet ID: {}", *id)
).into())
} else {
data.server_publish_state.insert(*&id, PublishState::Received(packet));
// Send PUBREC
Ok(Some(MqttPacket::pub_rec_packet(*id)))
}
}
}
}
pub fn pub_ack_handler<P>(packet: MqttPacket, data: &mut LoopData<P>) ->
Result<Option<MqttPacket>> where P: Persistence {
let id = packet.headers.get::<PacketId>().unwrap();
if data.client_publish_state.contains_key(&id) {
let (p_key, sender) = match data.client_publish_state.remove(&id) {
Some(PublishState::Sent(p, s)) => (p, s),
_ => unreachable!()
};
match data.persistence.remove(&p_key) {
Ok(_) => {
if let Some(s) = sender {
let _ = s.send(Ok(ClientReturn::Onetime(None)));
}
},
Err(e) => {
if let Some(s) = sender {
let _ = s.send(Err(e).chain_err(|| ErrorKind::PersistenceError));
}
return Err(ErrorKind::PersistenceError.into())
}
}
} else {
return Err(ProtoErrorKind::UnexpectedResponse(packet.ty.clone()).into())
}
Ok(None)
}
pub fn pub_rec_handler<P>(packet: MqttPacket, data: &mut LoopData<P>) ->
Result<Option<MqttPacket>> where P: Persistence {
let id = packet.headers.get::<PacketId>().unwrap();
if data.client_publish_state.contains_key(&id) {
let (p_key, sender) = match data.client_publish_state.remove(&id) {
Some(PublishState::Sent(p, s)) => (p, s),
_ => unreachable!()
};
if let Err(e) = data.persistence.remove(&p_key) {
return Err(e).chain_err(|| ErrorKind::PersistenceError)
}
let rel = MqttPacket::pub_rel_packet(*id);
let ser = bincode::serialize(&rel, bincode::Infinite).unwrap();
let key = match data.persistence.append(ser) {
Ok(k) => k,
Err(e) => {
if let Some(s) = sender {
let _ = s.send(Err(e).chain_err(|| ErrorKind::PersistenceError));
}
return Err(ErrorKind::PersistenceError.into())
}
};
let _ = data.client_publish_state.insert(*&id, PublishState::Released(key, sender));
Ok(Some(rel))
} else {
return Err(ProtoErrorKind::UnexpectedResponse(packet.ty.clone()).into())
}
}
pub fn pub_rel_handler<P>(packet: MqttPacket, data: &mut LoopData<P>) ->
Result<Option<MqttPacket>> where P: Persistence {
let id = packet.headers.get::<PacketId>().unwrap();
if data.server_publish_state.contains_key(&id) {
let orig = match data.server_publish_state.remove(&id) {
Some(PublishState::Received(o)) => o,
_ => unreachable!()
};
let topic = orig.headers.get::<TopicName>().unwrap();
let payload = match orig.payload {
Payload::Application(d) => d,
_ => unreachable!()
};
for &(ref filter, ref sender) in data.subscriptions.values() {
if filter.match_topic(&topic) {
let _ = sender.unbounded_send(Ok(SubItem(topic.clone(), payload.clone())));
}
}
Ok(Some(MqttPacket::pub_comp_packet(*id)))
} else {
return Err(ProtoErrorKind::UnexpectedResponse(packet.ty.clone()).into())
}
}
pub fn pub_comp_handler<P>(packet: MqttPacket, data: &mut LoopData<P>) ->
Result<Option<MqttPacket>> where P: Persistence {
let id = packet.headers.get::<PacketId>().unwrap();
if data.client_publish_state.contains_key(&id) {
let (p_key, sender) = match data.client_publish_state.remove(&id) {
Some(PublishState::Released(p, s)) => (p, s),
_ => unreachable!()
};
match data.persistence.remove(p_key) {
Ok(_) => {
if let Some(s) = sender {
let _ = s.send(Ok(ClientReturn::Onetime(None)));
}
Ok(None)
},
Err(e) => {
if let Some(s) = sender {
let _ = s.send(Err(e).chain_err(|| ErrorKind::PersistenceError));
}
return Err(ErrorKind::PersistenceError.into())
}
}
} else {
return Err(ProtoErrorKind::UnexpectedResponse(packet.ty.clone()).into())
}
}
|
use std::net::{TcpListener,TcpStream};
use std::io::Read;
use std::io::prelude::*;
fn handle_client(mut stream: TcpStream) {
loop {
//do the thing
let mut packet= [0;512] ;
stream.read(&mut packet).unwrap();
println!(" {}",String::from_utf8_lossy(&packet[..]));
let response = String::from_utf8_lossy(&packet[..]);
let mut should_stop = true ;
for (i,j) in response.as_bytes().iter().zip("OK\r\n".as_bytes()) {
if *i != 0 {
println!("i: {} j: {}",i,j);
}
if *i != *j {
should_stop = false;
}
}
if should_stop {
break;
}
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
}
fn main() {
println!("starting server, ctrl-c to quit ");
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
for stream in listener.incoming(){
handle_client(stream.unwrap());
}
}
|
//! Reset and Clock Control
use crate::flash::ACR;
use crate::time::Hertz;
use stm32l0x3::{rcc, RCC};
/// Extension trait that constrains the `RCC` peripheral
pub trait RccExt {
/// Constrains the `RCC` peripheral so it plays nicely with the other abstractions
fn constrain(self) -> Rcc;
}
impl RccExt for RCC {
fn constrain(self) -> Rcc {
Rcc {
ahb: AHB { _0: () },
apb1: APB1 { _0: () },
apb2: APB2 { _0: () },
gpio: GPIO { _0: () },
cfgr: CFGR::new(),
ccipr: CCIPR::new(),
}
}
}
/// Constrained RCC peripheral
pub struct Rcc {
/// AMBA High-performance Bus (AHB) registers
pub ahb: AHB,
/// Advanced Peripheral Bus 1 (APB1) registers
pub apb1: APB1,
/// Advanced Peripheral Bus 2 (APB2) registers
pub apb2: APB2,
/// GPIO registers
pub gpio: GPIO,
/// Clock configuration
pub cfgr: CFGR,
/// Clock configuration
pub ccipr: CCIPR,
}
/// AMBA High-performance Bus (AHB) registers
pub struct AHB {
_0: (),
}
impl AHB {
pub(crate) fn enr(&mut self) -> &rcc::AHBENR {
// NOTE(unsafe) this proxy grants exclusive access to this register
unsafe { &(*RCC::ptr()).ahbenr }
}
pub(crate) fn rstr(&mut self) -> &rcc::AHBRSTR {
// NOTE(unsafe) this proxy grants exclusive access to this register
unsafe { &(*RCC::ptr()).ahbrstr }
}
}
/// Advanced Peripheral Bus 1 (APB1) registers
pub struct APB1 {
_0: (),
}
impl APB1 {
pub(crate) fn enr(&mut self) -> &rcc::APB1ENR {
// NOTE(unsafe) this proxy grants exclusive access to this register
unsafe { &(*RCC::ptr()).apb1enr }
}
pub(crate) fn rstr(&mut self) -> &rcc::APB1RSTR {
// NOTE(unsafe) this proxy grants exclusive access to this register
unsafe { &(*RCC::ptr()).apb1rstr }
}
}
/// Advanced Peripheral Bus 2 (APB2) registers
pub struct APB2 {
_0: (),
}
impl APB2 {
pub(crate) fn enr(&mut self) -> &rcc::APB2ENR {
// NOTE(unsafe) this proxy grants exclusive access to this register
unsafe { &(*RCC::ptr()).apb2enr }
}
pub(crate) fn rstr(&mut self) -> &rcc::APB2RSTR {
// NOTE(unsafe) this proxy grants exclusive access to this register
unsafe { &(*RCC::ptr()).apb2rstr }
}
}
/// GPIO RCC registers
pub struct GPIO {
_0: (),
}
impl GPIO {
pub(crate) fn enr(&mut self) -> &rcc::IOPENR {
// NOTE(unsafe) this proxy grants exclusive access to this register
unsafe { &(*RCC::ptr()).iopenr }
}
pub(crate) fn rstr(&mut self) -> &rcc::IOPRSTR {
// NOTE(unsafe) this proxy grants exclusive access to this register
unsafe { &(*RCC::ptr()).ioprstr }
}
}
pub enum LpUsartClock {
ApbClock,
SystemClock,
HSI16Clock,
LSEClock,
}
impl LpUsartClock {
fn ccipr_bits(&self) -> (bool, bool) {
match self {
LpUsartClock::ApbClock => (false, false),
LpUsartClock::SystemClock => (false, true),
LpUsartClock::HSI16Clock => (true, false),
LpUsartClock::LSEClock => (true, true),
}
}
}
pub struct CCIPR {}
impl CCIPR {
pub fn new() -> Self {
Self {}
}
pub fn set_lpusart_clock(&mut self, source: LpUsartClock) {
let (sel1, sel0) = source.ccipr_bits();
unsafe {
&(*RCC::ptr())
.ccipr
.modify(|_, w| w.lpuart1sel1().bit(sel1).lpuart1sel0().bit(sel0));
}
}
}
const HSI: u32 = 16_000_000; // Hz
const USB_PLL_FREQ: u32 = 96_000_000; // Hz
pub enum ExternalHseType {
Clock,
Crystal,
}
/// Clock configuration
pub struct CFGR {
hse: Option<(ExternalHseType, u32)>,
usb_pll: bool,
hclk: Option<u32>,
pclk1: Option<u32>,
pclk2: Option<u32>,
sysclk: Option<u32>,
}
impl CFGR {
fn new() -> CFGR {
CFGR {
hse: None,
usb_pll: false,
hclk: None,
pclk1: None,
pclk2: None,
sysclk: None,
}
}
/// Use an external oscillator instead of HSI
///
/// With an external clock, max 32 MHz; with an external crystal max 24 MHz
pub fn external_hse<F>(mut self, ctype: ExternalHseType, freq: F) -> Self
where
F: Into<Hertz>,
{
self.hse = Some((ctype, freq.into().0));
self
}
pub fn usb_pll(mut self, enabled: bool) -> Self {
self.usb_pll = enabled;
self
}
/// Sets a frequency for the AHB bus
pub fn hclk<F>(mut self, freq: F) -> Self
where
F: Into<Hertz>,
{
self.hclk = Some(freq.into().0);
self
}
/// Sets a frequency for the APB1 bus
pub fn pclk1<F>(mut self, freq: F) -> Self
where
F: Into<Hertz>,
{
self.pclk1 = Some(freq.into().0);
self
}
/// Sets a frequency for the APB2 bus
pub fn pclk2<F>(mut self, freq: F) -> Self
where
F: Into<Hertz>,
{
self.pclk2 = Some(freq.into().0);
self
}
/// Sets the system (core) frequency
pub fn sysclk<F>(mut self, freq: F) -> Self
where
F: Into<Hertz>,
{
self.sysclk = Some(freq.into().0);
self
}
/// Freezes the clock configuration, making it effective
pub fn freeze(self, acr: &mut ACR) -> Clocks {
let (hse_type, hse_freq) = self
.hse
.map_or((None, None), |hse| (Some(hse.0), Some(hse.1)));
let pll_in_freq = hse_freq.unwrap_or(HSI);
let pll_freq = if self.usb_pll {
USB_PLL_FREQ
} else {
2 * self.sysclk.unwrap_or(hse_freq.unwrap_or(HSI))
};
let sysclk_freq = self.sysclk.unwrap_or(if pll_freq > 96_000_000 {
pll_freq / 4
} else if pll_freq > 64_000_000 {
pll_freq / 3
} else {
pll_freq / 2
});
let pll_mul = pll_freq / pll_in_freq;
let pll_div = pll_freq / sysclk_freq;
let pll_mul_div_bits = if pll_mul == 2 && pll_div == 2 && !self.usb_pll {
None
} else {
let mul: u8 = match pll_mul {
3 => 0b0000,
4 => 0b0001,
6 => 0b0010,
8 => 0b0011,
12 => 0b0100,
16 => 0b0101,
24 => 0b0110,
32 => 0b0111,
48 => 0b1000,
_ => unreachable!(),
};
let div: u8 = match pll_div {
m @ 2..=4 => m as u8 - 1,
_ => unreachable!(),
};
Some((mul, div))
};
match hse_type {
Some(ExternalHseType::Clock) => assert!(sysclk_freq <= 32_000_000),
Some(ExternalHseType::Crystal) => assert!(sysclk_freq <= 24_000_000),
_ => {}
};
let hpre_bits = self
.hclk
.map(|hclk| match sysclk_freq / hclk {
0 => unreachable!(),
1 => 0b0111,
2 => 0b1000,
3..=5 => 0b1001,
6..=11 => 0b1010,
12..=39 => 0b1011,
40..=95 => 0b1100,
96..=191 => 0b1101,
192..=383 => 0b1110,
_ => 0b1111,
})
.unwrap_or(0b0111);
let hclk = sysclk_freq / (1 << (hpre_bits - 0b0111));
match hse_type {
Some(ExternalHseType::Clock) => assert!(hclk <= 32_000_000),
Some(ExternalHseType::Crystal) => assert!(hclk <= 24_000_000),
_ => {}
};
let ppre1_bits: u8 = self
.pclk1
.map(|pclk1| match hclk / pclk1 {
0 => unreachable!(),
1 => 0b011,
2 => 0b100,
3..=5 => 0b101,
6..=11 => 0b110,
_ => 0b111,
})
.unwrap_or(0b011);
let ppre1 = 1 << (ppre1_bits - 0b011);
let pclk1 = hclk / ppre1 as u32;
match hse_type {
Some(ExternalHseType::Clock) => assert!(pclk1 <= 32_000_000),
Some(ExternalHseType::Crystal) => assert!(pclk1 <= 24_000_000),
_ => {}
};
let ppre2_bits: u8 = self
.pclk2
.map(|pclk2| match hclk / pclk2 {
0 => unreachable!(),
1 => 0b011,
2 => 0b100,
3..=5 => 0b101,
6..=11 => 0b110,
_ => 0b111,
})
.unwrap_or(0b011);
let ppre2 = 1 << (ppre2_bits - 0b011);
let pclk2 = hclk / ppre2 as u32;
match hse_type {
Some(ExternalHseType::Clock) => assert!(pclk2 <= 32_000_000),
Some(ExternalHseType::Crystal) => assert!(pclk2 <= 24_000_000),
_ => {}
};
// Adjust flash wait states
acr.acr().write(|w| {
// In Range 1, frequencies 16 MHz and below don't require wait states
if sysclk_freq <= 16_000_000 {
w.latency().clear_bit()
} else {
w.latency().set_bit()
}
});
let hse_en = match hse_type {
Some(_) => true,
None => false,
};
let rcc = unsafe { &*RCC::ptr() };
if let Some((pllmul_bits, plldiv_bits)) = pll_mul_div_bits {
// use PLL as source
// turn off PLL and wait until it's not ready
rcc.cr.write(|w| w.pllon().bit(false));
while rcc.cr.read().pllrdy().bit() {}
rcc.cfgr.write(|w| unsafe {
w.pllmul()
.bits(pllmul_bits)
.plldiv()
.bits(plldiv_bits)
.pllsrc()
.bit(hse_en)
});
rcc.cr.write(|w| {
w.pllon()
.set_bit()
.hsi16on()
.bit(!hse_en)
.hseon()
.bit(hse_en)
});
if hse_en {
while !rcc.cr.read().hserdy().bit() {}
} else {
while !rcc.cr.read().hsi16rdyf().bit() {}
}
while rcc.cr.read().pllrdy().bit_is_clear() {}
// SW: PLL selected as system clock
rcc.cfgr.modify(|_, w| unsafe {
w.ppre2()
.bits(ppre2_bits)
.ppre1()
.bits(ppre1_bits)
.hpre()
.bits(hpre_bits)
.sw()
.bits(0b11)
});
} else {
rcc.cr
.write(|w| w.hsi16on().bit(!hse_en).hseon().bit(hse_en));
if hse_en {
while !rcc.cr.read().hserdy().bit() {}
} else {
while !rcc.cr.read().hsi16rdyf().bit() {}
}
// SW: HSI selected as system clock
rcc.cfgr.write(|w| unsafe {
w.ppre2()
.bits(ppre2_bits)
.ppre1()
.bits(ppre1_bits)
.hpre()
.bits(hpre_bits)
.sw()
.bits(if hse_en { 0b10 } else { 0b01 })
});
}
Clocks {
hclk: Hertz(hclk),
pclk1: Hertz(pclk1),
pclk2: Hertz(pclk2),
ppre1,
ppre2,
sysclk: Hertz(sysclk_freq),
}
}
}
/// Frozen clock frequencies
///
/// The existence of this value indicates that the clock configuration can no longer be changed
#[derive(Clone, Copy)]
pub struct Clocks {
hclk: Hertz,
pclk1: Hertz,
pclk2: Hertz,
ppre1: u8,
ppre2: u8,
sysclk: Hertz,
}
impl Clocks {
/// Returns the frequency of the AHB
pub fn hclk(&self) -> Hertz {
self.hclk
}
/// Returns the frequency of the APB1
pub fn pclk1(&self) -> Hertz {
self.pclk1
}
/// Returns the frequency of the APB2
pub fn pclk2(&self) -> Hertz {
self.pclk2
}
pub(crate) fn ppre1(&self) -> u8 {
self.ppre1
}
pub(crate) fn ppre2(&self) -> u8 {
self.ppre2
}
/// Returns the system (core) frequency
pub fn sysclk(&self) -> Hertz {
self.sysclk
}
}
|
#[doc = "Reader of register EESIZE"]
pub type R = crate::R<u32, super::EESIZE>;
#[doc = "Reader of field `WORDCNT`"]
pub type WORDCNT_R = crate::R<u16, u16>;
#[doc = "Reader of field `BLKCNT`"]
pub type BLKCNT_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:15 - Number of 32-Bit Words"]
#[inline(always)]
pub fn wordcnt(&self) -> WORDCNT_R {
WORDCNT_R::new((self.bits & 0xffff) as u16)
}
#[doc = "Bits 16:26 - Number of 16-Word Blocks"]
#[inline(always)]
pub fn blkcnt(&self) -> BLKCNT_R {
BLKCNT_R::new(((self.bits >> 16) & 0x07ff) as u16)
}
}
|
macro_rules! str_fixture {
($file_name:literal) => {
include_str!(concat!("../fixtures/", $file_name))
};
}
macro_rules! bytes_fixture {
($file_name:literal) => {
include_bytes!(concat!("../fixtures/", $file_name))
};
}
pub mod old {
pub mod block {
pub const NUMBER_192: &str = str_fixture!("old/block/192.json");
}
}
pub mod v0_8_2 {
pub mod block {
pub const GENESIS: &str = str_fixture!("0.8.2/block/genesis.json");
pub const NUMBER_1716: &str = str_fixture!("0.8.2/block/1716.json");
pub const PENDING: &str = str_fixture!("0.8.2/block/pending.json");
}
pub mod transaction {
pub const INVOKE: &str = str_fixture!("0.8.2/txn/invoke.json");
}
}
pub mod v0_9_0 {
pub mod block {
pub const GENESIS: &str = str_fixture!("0.9.0/block/genesis.json");
pub const NUMBER_1716: &str = str_fixture!("0.9.0/block/1716.json");
pub const NUMBER_90000: &str = str_fixture!("0.9.0/block/90000.json");
pub const NUMBER_156000: &str = str_fixture!("0.9.0/block/156000.json");
pub const NUMBER_231579: &str = str_fixture!("0.9.0/block/231579.json");
pub const PENDING: &str = str_fixture!("0.9.0/block/pending.json");
}
pub mod transaction {
pub const DECLARE: &str = str_fixture!("0.9.0/txn/declare.json");
pub const DEPLOY: &str = str_fixture!("0.9.0/txn/deploy.json");
pub const INVOKE: &str = str_fixture!("0.9.0/txn/invoke.json");
pub const STATUS: &str = str_fixture!("0.9.0/txn/status.json");
}
}
pub mod v0_10_1 {
pub mod add_transaction {
pub const DEPLOY_ACCOUNT_REQUEST: &str =
str_fixture!("0.10.1/add-transaction/deploy-account-request.json");
pub const DEPLOY_ACCOUNT_RESPONSE: &str =
str_fixture!("0.10.1/add-transaction/deploy-account-response.json");
}
}
pub mod v0_11_0 {
pub mod state_update {
pub const GENESIS: &str = str_fixture!("0.11.0/state-update/genesis.json");
pub const NUMBER_315700: &str = str_fixture!("0.11.0/state-update/315700.json");
pub const PENDING: &str = str_fixture!("0.11.0/state-update/pending.json");
}
/// Some of the following transactions are "as of" 0.11.0 and not really
/// introduced in the chain in 0.11.0
pub mod transaction {
pub mod declare {
pub mod v1 {
pub const BLOCK_463319: &str =
str_fixture!("0.11.0/transaction/declare_v1_block_463319.json");
pub const BLOCK_797215: &str =
str_fixture!("0.11.0/transaction/declare_v1_block_797215.json");
}
pub mod v2 {
pub const BLOCK_797220: &str =
str_fixture!("0.11.0/transaction/declare_v2_block_797220.json");
}
}
pub mod deploy {
pub mod v0 {
/// First deploy on testnet
pub const GENESIS: &str = str_fixture!("0.11.0/transaction/deploy_v0_genesis.json");
}
pub mod v1 {
/// First deploy on testnet2, hash was calculated using chain id of testnet (goerli)
pub const GENESIS_TESTNET2: &str =
str_fixture!("0.11.0/transaction/deploy_v1_genesis_testnet2.json");
/// Last deploy on testnet
pub const BLOCK_485004: &str =
str_fixture!("0.11.0/transaction/deploy_v1_block_485004.json");
}
}
pub mod deploy_account {
pub mod v1 {
pub const BLOCK_375919: &str =
str_fixture!("0.11.0/transaction/deploy_account_v1_block_375919.json");
pub const BLOCK_797K: &str =
str_fixture!("0.11.0/transaction/deploy_account_v1_block_797k.json");
}
}
pub mod invoke {
pub mod v0 {
pub const GENESIS: &str = str_fixture!("0.11.0/transaction/invoke_v0_genesis.json");
// Invoke v0 with entry point type L1 handler later served
// as an L1 handler transaction
pub const BLOCK_854_IDX_96: &str =
str_fixture!("0.11.0/transaction/invoke_v0_block_854_idx_96.json");
}
pub mod v1 {
pub const BLOCK_420K: &str =
str_fixture!("0.11.0/transaction/invoke_v1_block_420k.json");
pub const BLOCK_790K: &str =
str_fixture!("0.11.0/transaction/invoke_v1_block_790k.json");
}
}
pub mod l1_handler {
pub mod v0 {
// Former Invoke v0 with entry point type L1 handler later served
// as an L1 handler transaction
pub const BLOCK_854_IDX_96: &str =
str_fixture!("0.11.0/transaction/l1_handler_v0_block_854_idx_96.json");
pub const BLOCK_1564: &str =
str_fixture!("0.11.0/transaction/l1_handler_v0_block_1564.json");
pub const BLOCK_272866: &str =
str_fixture!("0.11.0/transaction/l1_handler_v0_block_272866.json");
pub const BLOCK_790K: &str =
str_fixture!("0.11.0/transaction/l1_handler_v0_block_790k.json");
}
}
}
}
pub mod v0_12_2 {
pub mod state_update {
pub const PENDING_WITH_BLOCK: &str =
str_fixture!("0.12.2/state-update/pending_with_block.json");
}
}
pub mod add_transaction {
pub const INVOKE_CONTRACT_WITH_SIGNATURE: &str =
str_fixture!("add-transaction/invoke-contract-with-signature.json");
}
pub mod integration {
pub mod block {
pub const NUMBER_1: &str = str_fixture!("integration/block/1.json");
pub const NUMBER_192844: &str = str_fixture!("integration/block/192844.json");
pub const NUMBER_216171: &str = str_fixture!("integration/block/216171.json");
pub const NUMBER_216591: &str = str_fixture!("integration/block/216591.json");
pub const NUMBER_228457: &str = str_fixture!("integration/block/228457.json");
pub const NUMBER_285915: &str = str_fixture!("integration/block/285915.json");
pub const PENDING: &str = str_fixture!("integration/block/pending.json");
}
pub mod state_update {
// Contains declared_classes from 0.11.0
pub const NUMBER_283364: &str = str_fixture!("integration/state-update/283364.json");
// Contains replaced_classes from 0.11.0
pub const NUMBER_283428: &str = str_fixture!("integration/state-update/283428.json");
}
}
pub mod class_definitions {
use pathfinder_common::macro_prelude::*;
use pathfinder_common::ClassHash;
pub const CONTRACT_DEFINITION: &[u8] = bytes_fixture!("contracts/contract_definition.json");
pub const DUMMY_ACCOUNT: &[u8] = bytes_fixture!("contracts/dummy_account.json");
pub const DUMMY_ACCOUNT_CLASS_HASH: ClassHash =
class_hash!("0x0791563da22895f1e398b689866718346106c0cc71207a4ada68e6687ce1badf");
// https://external.integration.starknet.io/feeder_gateway/get_full_contract?blockNumber=latest&contractAddress=0x4ae0618c330c59559a59a27d143dd1c07cd74cf4e5e5a7cd85d53c6bf0e89dc
pub const INTEGRATION_TEST: &[u8] = bytes_fixture!("contracts/integration-test.json");
// https://alpha4.starknet.io/feeder_gateway/get_full_contract?contractAddress=0546BA9763D33DC59A070C0D87D94F2DCAFA82C4A93B5E2BF5AE458B0013A9D3
pub const GOERLI_GENESIS: &[u8] = bytes_fixture!("contracts/goerli-genesis.json");
// https://alpha4.starknet.io/feeder_gateway/get_full_contract?contractAddress=0400D86342F474F14AAE562587F30855E127AD661F31793C49414228B54516EC
pub const CAIRO_0_8_NEW_ATTRIBUTES: &[u8] =
bytes_fixture!("contracts/cairo-0.8-new-attributes.json");
// Contract whose class triggered a deserialization issue because of the new `compiler_version` property.
// https://external.integration.starknet.io/feeder_gateway/get_full_contract?blockNumber=latest&contractAddress=0x444453070729bf2db6a1f36541483c2952674e5de4bd05fcf538726b286bfa2
pub const CAIRO_0_10_COMPILER_VERSION: &[u8] =
bytes_fixture!("contracts/cairo-0.10-compiler-version.json");
// Contracts whose class contains `compiler_version` property as well as `cairo_type` with tuple values.
// These tuple values require a space to be injected in order to achieve the correct hash.
// https://external.integration.starknet.io/feeder_gateway/get_full_contract?blockNumber=latest&contractAddress=0x06f17fb7a052f3d18c1911c9d9c2fb0032bbe1ea57c58b0baca85bda9f3698be
pub const CAIRO_0_10_TUPLES_INTEGRATION: &[u8] =
bytes_fixture!("contracts/cairo-0.10-tuples-integration.json");
// https://alpha4.starknet.io/feeder_gateway/get_full_contract?blockNumber=latest&contractAddress=0x0424e799d610433168a31aab44c0d3e38b45d97387b45de80089f56c184fa315
pub const CAIRO_0_10_TUPLES_GOERLI: &[u8] =
bytes_fixture!("contracts/cairo-0.10-tuples-goerli.json");
// https://external.integration.starknet.io/feeder_gateway/get_class_by_hash?classHash=0x4e70b19333ae94bd958625f7b61ce9eec631653597e68645e13780061b2136c
pub const CAIRO_0_11_SIERRA: &[u8] = bytes_fixture!("contracts/sierra-0.11.json");
// https://github.com/starkware-libs/cairo/blob/v1.0.0-alpha.5/crates/cairo-lang-starknet/test_data/test_contract.json, but slightly
// modified: "abi" has been converted to a string and debug info is removed
pub const CAIRO_1_0_0_ALPHA5_SIERRA: &[u8] =
bytes_fixture!("contracts/sierra-1.0.0.alpha5-starknet-format.json");
// https://external.integration.starknet.io/feeder_gateway/get_class_by_hash?classHash=0x4d7d2ddf396736d7cdba26e178e30e3388d488984a94e03bc4af4841e222920
pub const CAIRO_1_0_0_ALPHA6_SIERRA: &[u8] =
bytes_fixture!("contracts/sierra-1.0.0.alpha6.json");
// https://external.integration.starknet.io/feeder_gateway/get_class_by_hash?classHash=0x0484c163658bcce5f9916f486171ac60143a92897533aa7ff7ac800b16c63311
pub const CAIRO_0_11_WITH_DECIMAL_ENTRY_POINT_OFFSET: &[u8] =
bytes_fixture!("contracts/cairo-0.11.0-decimal-entry-point-offset.json");
// A Sierra class with the program compression introduced in v0.11.1.
// https://external.integration.starknet.io/feeder_gateway/get_class_by_hash?classHash=0x05bb6c878494878bda6c2f0d7605f66559f9ffd6ae69ff529f8ca5f7a587a2bb
pub const CAIRO_1_0_0_RC0_SIERRA: &[u8] = bytes_fixture!("contracts/sierra-1.0.0.rc0.json");
// A Sierra class for compiler v1.1.0-rc0 introduced in v0.11.2.
// https://external.integration.starknet.io/feeder_gateway/get_class_by_hash?classHash=0x1338d85d3e579f6944ba06c005238d145920afeb32f94e3a1e234d21e1e9292
pub const CAIRO_1_1_0_RC0_SIERRA: &[u8] = bytes_fixture!("contracts/sierra-1.1.0.rc0.json");
// https://testnet.starkscan.co/contract/0x04b4e6d2b66287bd98f6c46daff06cba10942c7d7fe517825f0d3761cac36225
pub const CAIRO_1_1_0_BALANCE_SIERRA_JSON: &[u8] =
bytes_fixture!("contracts/sierra-1.1.0-balance.json");
pub const CAIRO_1_1_0_BALANCE_CASM_JSON: &[u8] =
bytes_fixture!("contracts/sierra-1.1.0-balance.casm.json");
// A sierra class which caused a stack overflow in the 2.0.1 compiler.
// https://alpha4.starknet.io/feeder_gateway/get_class_by_hash?classHash=0x03dd9347d22f1ea2d5fbc7bd1f0860c6c334973499f9f1989fcb81bfff5191da
pub const CAIRO_2_0_0_STACK_OVERFLOW: &[u8] =
bytes_fixture!("contracts/sierra-2.0.0-stack-overflow.json");
}
pub mod testnet {
use pathfinder_common::macro_prelude::*;
use pathfinder_common::{
CallParam, ClassHash, ContractAddress, EntryPoint, StorageAddress, TransactionHash,
};
use stark_hash::Felt;
pub const VALID_TX_HASH: TransactionHash =
transaction_hash!("0493d8fab73af67e972788e603aee18130facd3c7685f16084ecd98b07153e24");
pub const INVALID_TX_HASH: TransactionHash =
transaction_hash!("0393d8fab73af67e972788e603aee18130facd3c7685f16084ecd98b07153e24");
pub const VALID_CONTRACT_ADDR: ContractAddress =
contract_address!("06fbd460228d843b7fbef670ff15607bf72e19fa94de21e29811ada167b4ca39");
pub const INVALID_CONTRACT_ADDR: ContractAddress =
contract_address!("05fbd460228d843b7fbef670ff15607bf72e19fa94de21e29811ada167b4ca39");
pub const VALID_ENTRY_POINT: EntryPoint =
entry_point!("0362398bec32bc0ebb411203221a35a0301193a96f317ebe5e40be9f60d15320");
pub const INVALID_ENTRY_POINT: EntryPoint = EntryPoint(Felt::ZERO);
pub const VALID_KEY: StorageAddress =
storage_address!("0206F38F7E4F15E87567361213C28F235CCCDAA1D7FD34C9DB1DFE9489C6A091");
pub const VALID_KEY_DEC: &str =
"916907772491729262376534102982219947830828984996257231353398618781993312401";
pub const VALID_CALL_DATA: [CallParam; 1] = [call_param!("0x4d2")];
/// Class hash for VALID_CONTRACT_ADDR
pub const VALID_CLASS_HASH: ClassHash =
class_hash!("021a7f43387573b68666669a0ed764252ce5367708e696e31967764a90b429c2");
pub const INVALID_CLASS_HASH: ClassHash =
class_hash!("031a7f43387573b68666669a0ed764252ce5367708e696e31967764a90b429c2");
}
|
#[macro_use]
extern crate enum_primitive_derive;
mod utils;
pub mod structs;
pub use structs::*;
|
use std::cmp::{max, min};
use winit::dpi::LogicalPosition;
use crate::{
buffer::{Buffer, BufferMode},
cursor::{get_filtered_completions, CompletionRequest},
language_server_types::{CompletionItem, Diagnostic, SignatureHelp},
piece_table::PieceTable,
renderer::RenderLayout,
text_utils::{self, CharType},
};
pub const SCROLL_LINES_PER_ROLL: isize = 3;
const MAX_SHOWN_COMPLETION_ITEMS: usize = 10;
pub struct CompletionView {
pub row: usize,
pub col: usize,
pub width: usize,
pub height: usize,
}
pub struct SignatureHelpView {
pub row: usize,
pub col: usize,
}
pub struct HoverMessage {
pub message: String,
pub code_block_ranges: Vec<(usize, usize)>,
pub line_offset: usize,
pub num_lines: usize,
}
pub struct View {
pub line_offset: usize,
pub col_offset: usize,
pub hover: Option<(usize, usize)>,
pub hover_message: Option<HoverMessage>,
}
impl View {
pub fn new() -> Self {
Self {
line_offset: 0,
col_offset: 0,
hover: None,
hover_message: None,
}
}
pub fn handle_scroll(&mut self, buffer: &Buffer, sign: isize) {
self.scroll_vertical(buffer, -sign * SCROLL_LINES_PER_ROLL)
}
pub fn hover(
&mut self,
layout: &RenderLayout,
mouse_position: LogicalPosition<f64>,
font_size: (f64, f64),
) {
let (line, col) = self.get_line_col(layout, mouse_position, font_size);
self.hover = Some((line, col));
}
pub fn exit_hover(&mut self) {
self.hover = None;
self.hover_message = None;
}
pub fn visible_cursors_iter<F>(&self, layout: &RenderLayout, buffer: &Buffer, f: F)
where
F: Fn(usize, usize, usize),
{
if buffer.mode == BufferMode::VisualLine {
for cursor in buffer.cursors.iter() {
let line = buffer.piece_table.line_index(cursor.position);
let anchor_line = buffer.piece_table.line_index(cursor.anchor);
for line in min(line, anchor_line)..=max(line, anchor_line) {
let start = 0;
let end = buffer.piece_table.line_at_index(line).unwrap().length;
let num = (start..=end)
.filter(|col| self.pos_in_render_visible_range(line, *col, layout))
.count();
f(
self.absolute_to_view_row(line),
self.absolute_to_view_col(start),
num,
);
}
}
} else {
for cursor in buffer.cursors.iter() {
for range in cursor.get_selection_ranges(&buffer.piece_table) {
let num = (range.start..=range.end)
.filter(|col| self.pos_in_render_visible_range(range.line, *col, layout))
.count();
f(
self.absolute_to_view_row(range.line),
self.absolute_to_view_col(range.start),
num,
);
}
}
}
}
pub fn visible_cursor_leads_iter<F>(&self, buffer: &Buffer, layout: &RenderLayout, mut f: F)
where
F: FnMut(usize, usize, usize),
{
for cursor in buffer.cursors.iter() {
let (line, col) = cursor.get_line_col(&buffer.piece_table);
if self.pos_in_render_visible_range(line, col, layout) {
f(
self.absolute_to_view_row(line),
self.absolute_to_view_col(col),
cursor.position,
);
}
}
}
pub fn visible_completions<F>(&self, buffer: &Buffer, layout: &RenderLayout, f: F)
where
F: Fn(&[CompletionItem], &CompletionView, &CompletionRequest),
{
if let Some(server) = &buffer.language_server {
for cursor in buffer.cursors.iter() {
if let Some(request) = cursor.completion_request {
if let Some(completion_list) =
server.borrow().saved_completions.get(&request.id)
{
if completion_list.items.is_empty() {
continue;
}
let filtered_completions = get_filtered_completions(
&buffer.piece_table,
completion_list,
&request,
cursor.position,
);
// Filter from start of word if manually triggered or
let request_position = if request.manually_triggered {
cursor.position.saturating_sub(
cursor
.chars_until_pred_rev(&buffer.piece_table, |c| {
text_utils::char_type(c) != CharType::Word
})
.unwrap_or(0),
)
// Filter from start of request if triggered by a trigger character
} else {
request.initial_position
};
if let Some(completion_view) = self.get_completion_view(
&buffer.piece_table,
&filtered_completions,
request_position,
layout,
) {
f(&filtered_completions, &completion_view, &request);
}
}
}
}
}
}
pub fn visible_signature_helps<F>(&self, buffer: &Buffer, layout: &RenderLayout, f: F)
where
F: Fn(&SignatureHelp, &SignatureHelpView),
{
if let Some(server) = &buffer.language_server {
for cursor in buffer.cursors.iter() {
if let Some(request) = cursor.signature_help_request {
if let Some(signature_help) =
server.borrow().saved_signature_helps.get(&request.id)
{
if let Some(signature_help_view) = self.get_signature_help_view(
&buffer.piece_table,
signature_help,
request.position,
layout,
) {
f(signature_help, &signature_help_view);
}
}
}
}
}
}
pub fn visible_text_offset(&self, buffer: &Buffer) -> usize {
buffer
.piece_table
.char_index_from_line_col(self.line_offset, 0)
.unwrap_or(0)
}
pub fn visible_text(&self, buffer: &Buffer, layout: &RenderLayout) -> Vec<u8> {
buffer
.piece_table
.text_between_lines(self.line_offset, self.line_offset + layout.num_rows)
}
pub fn visible_diagnostic_lines_iter<F>(
&self,
buffer: &Buffer,
layout: &RenderLayout,
diagnostics: &[Diagnostic],
mut f: F,
) where
F: FnMut(usize, usize, usize),
{
if let Some(offset) = buffer
.piece_table
.char_index_from_line_col(self.line_offset, self.col_offset)
{
for diagnostic in diagnostics {
if diagnostic.severity.is_some_and(|s| s > 2) {
continue;
}
let (start_line, start_col) = (
diagnostic.range.start.line as usize,
diagnostic.range.start.character as usize,
);
let (end_line, end_col) = (
diagnostic.range.end.line as usize,
diagnostic.range.end.character as usize,
);
if (buffer.mode == BufferMode::Insert
&& buffer.cursors.iter().any(|cursor| {
(start_line..=end_line)
.contains(&buffer.piece_table.line_index(cursor.position))
}))
|| (!self.pos_in_render_visible_range(start_line, start_col, layout)
&& !self.pos_in_render_visible_range(end_line, end_col, layout))
{
continue;
}
if start_line == end_line {
f(
self.absolute_to_view_row(start_line),
self.absolute_to_view_col(start_col),
end_col.saturating_sub(start_col) + 1,
);
} else {
f(
self.absolute_to_view_row(start_line),
self.absolute_to_view_col(start_col),
buffer.piece_table.line_at_index(start_line).unwrap().length - start_col
+ 1,
);
for line in start_line + 1..end_line {
f(
self.absolute_to_view_row(line),
self.absolute_to_view_col(0),
buffer.piece_table.line_at_index(line).unwrap().length + 1,
);
}
f(
self.absolute_to_view_row(end_line),
self.absolute_to_view_col(0),
end_col + 1,
);
}
}
}
}
pub fn adjust(&mut self, buffer: &Buffer, layout: &RenderLayout) {
if let Some(last_cursor) = buffer.cursors.last() {
let (line, col) = last_cursor.get_line_col(&buffer.piece_table);
if !self.pos_in_edit_visible_range(line, col, layout) {
if line < self.line_offset {
self.line_offset = line;
} else if line > (self.line_offset + (layout.num_rows.saturating_sub(2))) {
self.line_offset +=
line - (self.line_offset + (layout.num_rows.saturating_sub(2)))
}
if col < self.col_offset {
self.col_offset = col;
} else if col > (self.col_offset + (layout.num_cols.saturating_sub(2))) {
self.col_offset += col - (self.col_offset + (layout.num_cols.saturating_sub(2)))
}
}
}
}
pub fn center(&mut self, buffer: &Buffer, layout: &RenderLayout) {
if let Some(last_cursor) = buffer.cursors.last() {
let (line, _) = last_cursor.get_line_col(&buffer.piece_table);
self.line_offset = line.saturating_sub(layout.num_rows / 2);
}
}
pub fn center_if_not_visible(&mut self, buffer: &Buffer, layout: &RenderLayout) {
if let Some(last_cursor) = buffer.cursors.last() {
let (line, col) = last_cursor.get_line_col(&buffer.piece_table);
if !self.pos_in_edit_visible_range(line, col, layout) {
self.line_offset = line.saturating_sub(layout.num_rows / 2);
}
}
}
pub fn get_signature_help_view(
&self,
piece_table: &PieceTable,
signature_help: &SignatureHelp,
position: usize,
layout: &RenderLayout,
) -> Option<SignatureHelpView> {
let line = piece_table.line_index(position);
let col = piece_table.col_index(position);
if signature_help.signatures.is_empty()
|| !self.pos_in_render_visible_range(line, col, layout)
{
return None;
}
let row = self.absolute_to_view_row(line) + 1;
let col = self.absolute_to_view_col(col);
let content_length = signature_help.signatures
[signature_help.active_signature.unwrap_or(0) as usize]
.label
.len();
let available_rows_right = layout.num_cols.saturating_sub(col + 1);
let move_left = available_rows_right < content_length;
let col = if move_left {
col.saturating_sub(content_length)
} else {
col
};
Some(SignatureHelpView { row, col })
}
pub fn get_completion_view(
&self,
piece_table: &PieceTable,
completions: &[CompletionItem],
position: usize,
layout: &RenderLayout,
) -> Option<CompletionView> {
let line = piece_table.line_index(position);
let col = piece_table.col_index(position);
if !self.pos_in_render_visible_range(line, col, layout) {
return None;
}
let longest_string = completions
.iter()
.max_by(|x, y| {
x.insert_text
.as_ref()
.unwrap_or(&x.label)
.len()
.cmp(&y.insert_text.as_ref().unwrap_or(&y.label).len())
})
.map(|x| x.insert_text.as_ref().unwrap_or(&x.label).len() + 1)
.unwrap_or(0);
let mut num_shown_completion_items = min(MAX_SHOWN_COMPLETION_ITEMS, completions.len());
let row = self.absolute_to_view_row(line);
let col = self.absolute_to_view_col(col);
let available_rows_above = row.saturating_sub(1);
let available_rows_below = layout.num_rows.saturating_sub(row + 2);
let grow_up = available_rows_below < 5 && available_rows_above > available_rows_below;
let row = if grow_up {
num_shown_completion_items = min(num_shown_completion_items, available_rows_above);
row.saturating_sub(num_shown_completion_items)
} else {
num_shown_completion_items = min(num_shown_completion_items, available_rows_below);
row + 1
};
let available_rows_right = layout.num_cols.saturating_sub(col + 1);
let move_left = available_rows_right < longest_string;
let col = if move_left {
col.saturating_sub(longest_string)
} else {
col
};
Some(CompletionView {
row,
col,
width: longest_string,
height: num_shown_completion_items,
})
}
pub fn get_line_col(
&self,
layout: &RenderLayout,
mouse_position: LogicalPosition<f64>,
font_size: (f64, f64),
) -> (usize, usize) {
let row = (mouse_position.y / font_size.1).floor() as usize;
let col = (mouse_position.x / font_size.0).floor() as usize;
(
(row.saturating_sub(layout.row_offset)) + self.line_offset,
(col.saturating_sub(layout.col_offset)) + self.col_offset,
)
}
pub fn absolute_to_view_row(&self, line: usize) -> usize {
line.saturating_sub(self.line_offset)
}
pub fn absolute_to_view_col(&self, col: usize) -> usize {
col.saturating_sub(self.col_offset)
}
fn scroll_vertical(&mut self, buffer: &Buffer, delta: isize) {
self.line_offset = min(
self.line_offset.saturating_add_signed(delta),
buffer.piece_table.num_lines().saturating_sub(1),
);
}
fn pos_in_edit_visible_range(&self, line: usize, col: usize, layout: &RenderLayout) -> bool {
(self.line_offset..self.line_offset + layout.num_rows.saturating_sub(1)).contains(&line)
&& (self.col_offset..self.col_offset + layout.num_cols.saturating_sub(1)).contains(&col)
}
fn pos_in_render_visible_range(&self, line: usize, col: usize, layout: &RenderLayout) -> bool {
(self.line_offset..self.line_offset + layout.num_rows).contains(&line)
&& (self.col_offset..self.col_offset + layout.num_cols).contains(&col)
}
}
|
//! An "interner" is a data structure that associates values with usize tags and
//! allows bidirectional lookup; i.e., given a value, one can easily find the
//! type, and vice versa.
#![allow(unused)]
use std::cell::RefCell;
use std::cmp::{Ord, Ordering, PartialEq, PartialOrd};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::str;
use std::sync::{Arc, RwLock};
use lazy_static::lazy_static;
use rustc_hash::FxHashMap;
use crate::arena::DroplessArena;
use crate::symbols;
use firefly_diagnostics::{SourceSpan, Spanned};
lazy_static! {
/// A globally accessible symbol table
pub static ref SYMBOL_TABLE: SymbolTable = {
SymbolTable::new()
};
}
pub struct SymbolTable {
interner: RwLock<Interner>,
}
impl SymbolTable {
pub fn new() -> Self {
SymbolTable {
interner: RwLock::new(Interner::fresh()),
}
}
}
unsafe impl Sync for SymbolTable {}
#[derive(Copy, Clone, Eq, Spanned)]
pub struct Ident {
pub name: Symbol,
#[span]
pub span: SourceSpan,
}
impl Default for Ident {
fn default() -> Self {
Self {
name: symbols::Empty,
span: SourceSpan::UNKNOWN,
}
}
}
impl Ident {
#[inline]
pub const fn new(name: Symbol, span: SourceSpan) -> Ident {
Ident { name, span }
}
#[inline]
pub const fn with_empty_span(name: Symbol) -> Ident {
Ident::new(name, SourceSpan::UNKNOWN)
}
/// Maps an interned string to an identifier with an empty syntax context.
pub fn from_interned_str(string: InternedString) -> Ident {
Ident::with_empty_span(string.as_symbol())
}
/// Maps a string to an identifier with an empty syntax context.
pub fn from_str(string: &str) -> Ident {
Ident::with_empty_span(Symbol::intern(string))
}
pub fn unquote_string(self) -> Ident {
Ident::new(Symbol::intern(self.as_str().trim_matches('"')), self.span)
}
pub fn unquote_atom(self) -> Ident {
Ident::new(Symbol::intern(self.as_str().trim_matches('\'')), self.span)
}
pub fn gensym(self) -> Ident {
Ident::new(self.name.gensymed(), self.span)
}
pub fn as_str(self) -> LocalInternedString {
self.name.as_str()
}
pub fn as_interned_str(self) -> InternedString {
self.name.as_interned_str()
}
pub fn is_keyword(self) -> bool {
self.name.is_keyword()
}
pub fn is_reserved_attr(self) -> bool {
self.name.is_reserved_attr()
}
pub fn is_preprocessor_directive(self) -> bool {
self.name.is_preprocessor_directive()
}
}
impl core::ops::Deref for Ident {
type Target = Symbol;
#[inline]
fn deref(&self) -> &Symbol {
&self.name
}
}
impl Ord for Ident {
fn cmp(&self, other: &Self) -> Ordering {
self.as_str().cmp(&other.as_str())
}
}
impl PartialOrd for Ident {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Ident {
fn eq(&self, rhs: &Self) -> bool {
self.name == rhs.name
}
}
impl PartialEq<Symbol> for Ident {
fn eq(&self, rhs: &Symbol) -> bool {
self.name.eq(rhs)
}
}
impl Hash for Ident {
fn hash<H: Hasher>(&self, state: &mut H) {
self.name.hash(state);
}
}
impl fmt::Debug for Ident {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Ident<{} {:?}>", self.name, self.span)
}
}
impl fmt::Display for Ident {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.name, f)
}
}
#[derive(Debug, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SymbolIndex(u32);
impl Clone for SymbolIndex {
fn clone(&self) -> Self {
*self
}
}
impl From<SymbolIndex> for u32 {
#[inline]
fn from(v: SymbolIndex) -> u32 {
v.as_u32()
}
}
impl From<SymbolIndex> for usize {
#[inline]
fn from(v: SymbolIndex) -> usize {
v.as_usize()
}
}
impl SymbolIndex {
// shave off 256 indices at the end to allow space for packing these indices into enums
pub const MAX_AS_U32: u32 = 0xFFFF_FF00;
pub const MAX: SymbolIndex = SymbolIndex::new(0xFFFF_FF00);
#[inline]
const fn new(n: u32) -> Self {
// This will fail at const eval time unless `value <=
// max` is true (in which case we get the index 0).
// It will also fail at runtime, of course, but in a
// kind of wacky way.
let _ = ["out of range value used"][!(n <= Self::MAX_AS_U32) as usize];
SymbolIndex(n)
}
#[inline]
pub fn as_u32(self) -> u32 {
self.0
}
#[inline]
pub fn as_usize(self) -> usize {
self.0 as usize
}
}
/// A symbol is an interned or gensymed string.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Symbol(SymbolIndex);
impl Symbol {
pub const fn new(n: u32) -> Self {
Symbol(SymbolIndex::new(n))
}
/// Maps a string to its interned representation.
pub fn intern(string: &str) -> Self {
with_interner(|interner| interner.intern(string))
}
pub fn interned(self) -> Self {
with_interner(|interner| interner.interned(self))
}
/// Gensyms a new usize, using the current interner.
pub fn gensym(string: &str) -> Self {
with_interner(|interner| interner.gensym(string))
}
pub fn gensymed(self) -> Self {
with_interner(|interner| interner.gensymed(self))
}
pub fn as_str(self) -> LocalInternedString {
with_interner(|interner| unsafe {
LocalInternedString {
string: ::std::mem::transmute::<&str, &str>(interner.get(self)),
dummy: PhantomData,
}
})
}
pub fn as_interned_str(self) -> InternedString {
with_interner(|interner| InternedString {
symbol: interner.interned(self),
})
}
#[inline]
pub fn as_u32(self) -> u32 {
self.0.as_u32()
}
#[inline]
pub fn as_usize(self) -> usize {
self.0.as_usize()
}
#[inline]
pub fn is_boolean(&self) -> bool {
// Booleans are always 0 or 1 by index
self.0.as_u32() < 2
}
/// Returns `true` if the token is a keyword, reserved in all name positions
#[inline]
pub fn is_keyword(self) -> bool {
symbols::is_keyword(self)
}
/// Returns `true` if the token is a reserved attribute name
#[inline]
pub fn is_reserved_attr(self) -> bool {
symbols::is_reserved(self)
}
/// Returns `true` if the token is a preprocessor directive name
#[inline]
pub fn is_preprocessor_directive(self) -> bool {
symbols::is_directive(self)
}
}
impl fmt::Debug for Symbol {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let is_gensymed = with_interner(|interner| interner.is_gensymed(*self));
if is_gensymed {
write!(f, "{}({:?})", self, self.0)
} else {
write!(f, "{}({:?})", self, self.0)
}
}
}
impl fmt::Display for Symbol {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.as_str(), f)
}
}
impl<T: ::std::ops::Deref<Target = str>> PartialEq<T> for Symbol {
fn eq(&self, other: &T) -> bool {
self.as_str() == other.deref()
}
}
// The `&'static str`s in this type actually point into the arena.
//
// Note that normal symbols are indexed upward from 0, and gensyms are indexed
// downward from SymbolIndex::MAX_AS_U32.
#[derive(Default)]
pub struct Interner {
arena: DroplessArena,
pub names: FxHashMap<&'static str, Symbol>,
pub strings: Vec<&'static str>,
gensyms: Vec<Symbol>,
}
impl Interner {
pub fn fresh() -> Self {
let mut this = Interner::default();
for (sym, s) in symbols::__SYMBOLS {
this.names.insert(s, *sym);
this.strings.push(s);
}
this
}
pub fn intern(&mut self, string: &str) -> Symbol {
if let Some(&name) = self.names.get(string) {
return name;
}
let name = Symbol::new(self.strings.len() as u32);
// `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
// UTF-8.
let string: &str =
unsafe { str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes())) };
// It is safe to extend the arena allocation to `'static` because we only access
// these while the arena is still alive.
let string: &'static str = unsafe { &*(string as *const str) };
self.strings.push(string);
self.names.insert(string, name);
name
}
pub fn interned(&self, symbol: Symbol) -> Symbol {
if (symbol.0.as_usize()) < self.strings.len() {
symbol
} else {
self.interned(self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize])
}
}
fn gensym(&mut self, string: &str) -> Symbol {
let symbol = self.intern(string);
self.gensymed(symbol)
}
fn gensymed(&mut self, symbol: Symbol) -> Symbol {
self.gensyms.push(symbol);
Symbol::new(SymbolIndex::MAX_AS_U32 - self.gensyms.len() as u32 + 1)
}
fn is_gensymed(&mut self, symbol: Symbol) -> bool {
symbol.0.as_usize() >= self.strings.len()
}
pub fn get(&self, symbol: Symbol) -> &str {
match self.strings.get(symbol.0.as_usize()) {
Some(string) => string,
None => self.get(self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize]),
}
}
}
// If an interner exists, return it. Otherwise, prepare a fresh one.
#[inline]
fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
let mut r = SYMBOL_TABLE
.interner
.write()
.expect("unable to acquire write lock for symbol table");
f(&mut *r)
//GLOBALS.with(|globals| {
//f(&mut *globals.symbol_interner.lock().expect("symbol interner lock was held"))
//})
}
#[inline]
fn with_read_only_interner<T, F: FnOnce(&Interner) -> T>(f: F) -> T {
let r = SYMBOL_TABLE
.interner
.read()
.expect("unable to acquire read lock for symbol table");
f(&*r)
}
/// Represents a string stored in the interner. Because the interner outlives any thread
/// which uses this type, we can safely treat `string` which points to interner data,
/// as an immortal string, as long as this type never crosses between threads.
#[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
pub struct LocalInternedString {
string: &'static str,
/// This type cannot be sent across threads, this emulates the
/// behavior of !impl without the unsafe feature flag.
dummy: PhantomData<*const u8>,
}
impl LocalInternedString {
pub fn as_interned_str(self) -> InternedString {
InternedString {
symbol: Symbol::intern(self.string),
}
}
pub fn get(&self) -> &'static str {
self.string
}
}
impl<U: ?Sized> ::std::convert::AsRef<U> for LocalInternedString
where
str: ::std::convert::AsRef<U>,
{
fn as_ref(&self) -> &U {
self.string.as_ref()
}
}
impl<T: ::std::ops::Deref<Target = str>> ::std::cmp::PartialEq<T> for LocalInternedString {
fn eq(&self, other: &T) -> bool {
self.string == other.deref()
}
}
impl ::std::cmp::PartialEq<LocalInternedString> for str {
fn eq(&self, other: &LocalInternedString) -> bool {
self == other.string
}
}
impl<'a> ::std::cmp::PartialEq<LocalInternedString> for &'a str {
fn eq(&self, other: &LocalInternedString) -> bool {
*self == other.string
}
}
impl ::std::cmp::PartialEq<LocalInternedString> for String {
fn eq(&self, other: &LocalInternedString) -> bool {
self == other.string
}
}
impl<'a> ::std::cmp::PartialEq<LocalInternedString> for &'a String {
fn eq(&self, other: &LocalInternedString) -> bool {
*self == other.string
}
}
//impl !Send for LocalInternedString {}
//impl !Sync for LocalInternedString {}
impl ::std::ops::Deref for LocalInternedString {
type Target = str;
fn deref(&self) -> &str {
self.string
}
}
impl fmt::Debug for LocalInternedString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.string, f)
}
}
impl fmt::Display for LocalInternedString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.string, f)
}
}
/// Represents a string stored in the string interner.
#[derive(Clone, Copy, Eq)]
pub struct InternedString {
symbol: Symbol,
}
impl InternedString {
pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
let str = with_interner(|interner| interner.get(self.symbol) as *const str);
// This is safe because the interner keeps string alive until it is dropped.
// We can access it because we know the interner is still alive since we use a
// scoped thread local to access it, and it was alive at the beginning of this scope
unsafe { f(&*str) }
}
pub fn as_symbol(self) -> Symbol {
self.symbol
}
pub fn as_str(self) -> LocalInternedString {
self.symbol.as_str()
}
}
impl Hash for InternedString {
fn hash<H: Hasher>(&self, state: &mut H) {
self.with(|str| str.hash(state))
}
}
impl PartialOrd<InternedString> for InternedString {
fn partial_cmp(&self, other: &InternedString) -> Option<Ordering> {
if self.symbol == other.symbol {
return Some(Ordering::Equal);
}
self.with(|self_str| other.with(|other_str| self_str.partial_cmp(other_str)))
}
}
impl Ord for InternedString {
fn cmp(&self, other: &InternedString) -> Ordering {
if self.symbol == other.symbol {
return Ordering::Equal;
}
self.with(|self_str| other.with(|other_str| self_str.cmp(&other_str)))
}
}
impl<T: ::std::ops::Deref<Target = str>> PartialEq<T> for InternedString {
fn eq(&self, other: &T) -> bool {
self.with(|string| string == other.deref())
}
}
impl PartialEq<InternedString> for InternedString {
fn eq(&self, other: &InternedString) -> bool {
self.symbol == other.symbol
}
}
impl PartialEq<InternedString> for str {
fn eq(&self, other: &InternedString) -> bool {
other.with(|string| self == string)
}
}
impl<'a> PartialEq<InternedString> for &'a str {
fn eq(&self, other: &InternedString) -> bool {
other.with(|string| *self == string)
}
}
impl PartialEq<InternedString> for String {
fn eq(&self, other: &InternedString) -> bool {
other.with(|string| self == string)
}
}
impl<'a> PartialEq<InternedString> for &'a String {
fn eq(&self, other: &InternedString) -> bool {
other.with(|string| *self == string)
}
}
impl ::std::convert::From<InternedString> for String {
fn from(val: InternedString) -> String {
val.as_symbol().to_string()
}
}
impl fmt::Debug for InternedString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.with(|str| fmt::Debug::fmt(&str, f))
}
}
impl fmt::Display for InternedString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.with(|str| fmt::Display::fmt(&str, f))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn interner_tests() {
let mut i: Interner = Interner::default();
// first one is zero:
assert_eq!(i.intern("dog"), Symbol::new(0));
// re-use gets the same entry:
assert_eq!(i.intern("dog"), Symbol::new(0));
// different string gets a different #:
assert_eq!(i.intern("cat"), Symbol::new(1));
assert_eq!(i.intern("cat"), Symbol::new(1));
// dog is still at zero
assert_eq!(i.intern("dog"), Symbol::new(0));
assert_eq!(i.gensym("zebra"), Symbol::new(SymbolIndex::MAX_AS_U32));
// gensym of same string gets new number:
assert_eq!(i.gensym("zebra"), Symbol::new(SymbolIndex::MAX_AS_U32 - 1));
// gensym of *existing* string gets new number:
assert_eq!(i.gensym("dog"), Symbol::new(SymbolIndex::MAX_AS_U32 - 2));
}
#[test]
fn interned_keywords_no_gaps() {
let mut i = Interner::fresh();
// Should already be interned with matching indexes
for (sym, s) in symbols::DECLARED.iter() {
assert_eq!(i.intern(&s), *sym)
}
// Should create a new symbol resulting in an index equal to the last entry in the table
assert_eq!(i.intern("foo").as_u32(), (i.names.len() - 1) as u32);
}
#[test]
fn unquote_string() {
let i = Ident::from_str("\"after\"");
assert_eq!(i.unquote_string().name, symbols::After);
}
#[test]
fn unquote_atom() {
let i = Ident::from_str("'after'");
assert_eq!(i.unquote_atom().name, symbols::After);
}
}
|
use crate::window;
use crate::KEYMAP_T;
use std::unimplemented;
use rustyline::completion::{Candidate, Completer, FilenameCompleter, Pair};
use rustyline::line_buffer;
struct CompletionTracker {
pub index: usize,
pub pos: usize,
pub original: String,
pub candidates: Vec<Pair>,
}
impl CompletionTracker {
pub fn new(pos: usize, candidates: Vec<Pair>, original: String) -> Self {
CompletionTracker {
index: 0,
pos,
original,
candidates,
}
}
}
pub struct LllTextField<'a> {
pub win: window::LllPanel,
pub prompt: &'a str,
pub prefix: &'a str,
pub suffix: &'a str,
}
impl<'a> LllTextField<'a> {
pub fn new(
rows: i32,
cols: i32,
coord: (usize, usize),
prompt: &'a str,
prefix: &'a str,
suffix: &'a str,
) -> Self {
let win = window::LllPanel::new(rows, cols, coord);
ncurses::keypad(win.win, true);
LllTextField {
win,
prompt,
prefix,
suffix,
}
}
pub fn readline(&self) -> Option<String> {
self.win.move_to_top();
ncurses::timeout(-1);
let win = self.win.win;
let prompt_len = self.prompt.len();
let coord = (0, self.win.coords.1 + prompt_len);
ncurses::mvwaddstr(win, 0, 0, &self.prompt);
let mut line_buffer = line_buffer::LineBuffer::with_capacity(255);
let completer = FilenameCompleter::new();
line_buffer.insert_str(0, self.prefix);
line_buffer.insert_str(line_buffer.len(), self.suffix);
line_buffer.set_pos(self.prefix.as_bytes().len());
let mut completion_tracker: Option<CompletionTracker> = None;
let mut curr_pos = unicode_width::UnicodeWidthStr::width(self.prefix);
loop {
ncurses::mvwaddstr(win, coord.0, coord.1 as i32, line_buffer.as_str());
ncurses::wclrtoeol(win);
// draws cursor
ncurses::mvwchgat(
win,
coord.0,
(coord.1 + curr_pos) as i32,
1,
ncurses::A_STANDOUT(),
0,
);
ncurses::wrefresh(win);
let ch = ncurses::wget_wch(win).unwrap();
let ch = match ch {
ncurses::WchResult::Char(s) => s as i32,
ncurses::WchResult::KeyCode(s) => s,
};
if ch == KEYMAP_T.escape {
return None;
} else if ch == KEYMAP_T.enter {
break;
} else if ch == KEYMAP_T.home {
line_buffer.move_home();
curr_pos = 0;
completion_tracker.take();
} else if ch == KEYMAP_T.end {
line_buffer.move_end();
curr_pos = unicode_width::UnicodeWidthStr::width(line_buffer.as_str());
completion_tracker.take();
} else if ch == KEYMAP_T.left {
if line_buffer.move_backward(1) {
let pos = line_buffer.pos();
curr_pos = unicode_width::UnicodeWidthStr::width(&line_buffer.as_str()[..pos]);
completion_tracker.take();
}
} else if ch == KEYMAP_T.right {
if line_buffer.move_forward(1) {
let pos = line_buffer.pos();
curr_pos = unicode_width::UnicodeWidthStr::width(&line_buffer.as_str()[..pos]);
completion_tracker.take();
}
} else if ch == KEYMAP_T.backspace {
if line_buffer.backspace(1) {
let pos = line_buffer.pos();
curr_pos = unicode_width::UnicodeWidthStr::width(&line_buffer.as_str()[..pos]);
completion_tracker.take();
}
} else if ch == KEYMAP_T.delete {
if line_buffer.delete(1).is_some() {
completion_tracker.take();
}
} else if ch == KEYMAP_T.tab {
if completion_tracker.is_none() {
let res = completer.complete_path(line_buffer.as_str(), line_buffer.pos());
if let Ok((pos, mut candidates)) = res {
candidates.sort_by(|x, y| {
x.display()
.partial_cmp(y.display())
.unwrap_or(std::cmp::Ordering::Less)
});
let ct = CompletionTracker::new(
pos,
candidates,
String::from(line_buffer.as_str()),
);
completion_tracker = Some(ct);
}
}
if let Some(ref mut s) = completion_tracker {
if s.index < s.candidates.len() {
let candidate = &s.candidates[s.index];
completer.update(&mut line_buffer, s.pos, candidate.replacement());
s.index += 1;
}
}
curr_pos = unicode_width::UnicodeWidthStr::width(
&line_buffer.as_str()[..line_buffer.pos()],
);
} else if ch == KEYMAP_T.up {
unimplemented!();
} else if ch == KEYMAP_T.down {
unimplemented!();
} else if let Some(ch) = std::char::from_u32(ch as u32) {
if line_buffer.insert(ch, 1).is_some() {
curr_pos += unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1);
completion_tracker.take();
}
}
}
if line_buffer.as_str().is_empty() {
None
} else {
// let strin = rustyline::completion::unescape(line_buffer.as_str(), ESCAPE_CHAR).into_owned();
let strin = line_buffer.to_string();
Some(strin)
}
}
}
|
#![crate_name = "js"]
#![crate_type = "lib"]
#![doc(
html_favicon_url = "http://tombebbington.github.io/favicon.png"
)]
#![feature(phase, macro_rules, globs)]
#![deny(non_uppercase_statics, missing_doc, unnecessary_parens, unrecognized_lint,
unreachable_code, unnecessary_allocation, unnecessary_typecast, unnecessary_allocation,
uppercase_variables, non_camel_case_types, unused_must_use)]
#![feature(box_syntax)]
#![feature(box_patterns)]
#![feature(rustc_private)]
//! This is a library with seperate modules for Javascript parsing, the Javascript
//! standard library, and Javascript execution through LibJIT
//extern crate jit;
extern crate llvm_rs;
extern crate rand;
//#[phase(link)]
//extern crate log;
extern crate serialize;
extern crate serde_json;
extern crate time;
extern crate url;
/// The backend-defining traits and the Javascript standard library
pub mod front;
/// The default backend implemented on top of LibJIT
pub mod back;
/// Javascript parsing and syntax
pub mod syntax;
|
pub mod button;
pub mod svgmap;
pub mod style; |
use pyo3::prelude::*;
use pathfinder_geometry::{
vector::Vector2F,
rect::RectF,
transform2d::Transform2F
};
wrap!(Vector, Vector2F);
#[pymethods]
impl Vector {
#[new]
pub fn new(x: f32, y: f32) -> Vector {
Vector::from(Vector2F::new(x, y))
}
}
auto!(AutoVector(Vector2F) {
(f32, f32) => (x, y) => Vector2F::new(x, y),
Vector => v => v.into_inner(),
});
auto!(AutoScale(Vector2F) {
(f32, f32) => (x, y) => Vector2F::new(x, y),
f32 => x => Vector2F::splat(x),
Vector => v => v.into_inner(),
});
wrap!(Rect, RectF);
#[pymethods]
impl Rect {
#[new]
pub fn new(origin: AutoVector, size: AutoVector) -> Rect {
Rect::from(RectF::new(*origin, *size))
}
#[staticmethod]
pub fn from_points(origin: AutoVector, lower_right: AutoVector) -> Rect {
Rect::from(RectF::from_points(*origin, *lower_right))
}
}
wrap!(Transform, Transform2F);
#[pymethods]
impl Transform {
#[new]
pub fn new() -> Transform {
Transform2F::default().into()
}
#[text_signature = "($self, translation: Vector)"]
pub fn translated(&self, translation: AutoVector) -> Transform {
Transform::from(Transform2F::from_translation(*translation) * **self)
}
#[text_signature = "($self, scale: Vector or float)"]
pub fn scaled(&self, translation: AutoScale) -> Transform {
Transform::from(Transform2F::from_translation(*translation) * **self)
}
#[text_signature = "($self, rotation: float)"]
pub fn rotated(&self, rotation: f32) -> Transform {
Transform::from(Transform2F::from_rotation(rotation) * **self)
}
}
|
#![allow(dead_code)]
use crate::base::logic::bit;
use crate::base::logic::bit::{I, O};
pub fn read_stdin<T: std::str::FromStr>() -> T {
let mut s = String::new();
std::io::stdin().read_line(&mut s).ok();
s.trim().parse().ok().unwrap()
}
pub fn str_to_binary(str: &str) -> Vec<bit> {
if str == "" {
panic!(format!("Could't convert an empty string"))
}
let char_bits: Vec<char> = str.chars().collect();
let mut bits = Vec::new();
for i in 0..char_bits.len() {
let bit = match char_bits[i].to_digit(10) {
Some(0) => O,
Some(1) => I,
_ => panic!("Unknown number. String should consist of characters neither 0 or 1"),
};
bits.push(bit);
}
return bits;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn for_str_to_binary() {
assert_eq!(str_to_binary("1"), [I]);
assert_eq!(str_to_binary("0"), [O]);
assert_eq!(str_to_binary("000"), [O, O, O]);
assert_eq!(str_to_binary("0101"), [O, I, O, I]);
}
#[test]
#[should_panic]
fn for_str_to_binary_2() {
str_to_binary("");
}
#[test]
#[should_panic]
fn for_str_to_binary_3() {
str_to_binary("a");
}
}
|
use procon_reader::ProconReader;
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let n: usize = rd.get();
let mut g = vec![vec![]; n];
for _ in 0..(n - 1) {
let a: usize = rd.get();
let b: usize = rd.get();
g[a - 1].push(b - 1);
g[b - 1].push(a - 1);
}
for v in 0..n {
g[v].sort();
}
let mut ans = Vec::new();
dfs(0, !0, &g, &mut ans);
print!("{}", ans[0] + 1);
for ans in &ans[1..] {
print!(" {}", ans + 1);
}
println!();
}
fn dfs(i: usize, p: usize, g: &Vec<Vec<usize>>, ans: &mut Vec<usize>) {
ans.push(i);
for &j in &g[i] {
if j != p {
dfs(j, i, g, ans);
}
}
if p != !0 {
ans.push(p);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.