text
stringlengths
8
4.13M
use crate::compiling::v1::assemble::prelude::*; /// Compile a range expression. impl Assemble for ast::ExprRange { fn assemble(&self, c: &mut Compiler<'_>, needs: Needs) -> CompileResult<Asm> { let span = self.span(); log::trace!("ExprRange => {:?}", c.source.source(span)); let guard = c.scopes.push_child(span)?; if needs.value() { let from = if let Some(from) = &self.from { from.assemble(c, needs)?.apply(c)?; c.asm.push( Inst::Variant { variant: InstVariant::Some, }, from.span(), ); from.span() } else { c.asm.push( Inst::Variant { variant: InstVariant::None, }, span, ); span }; c.scopes.decl_anon(from)?; let to = if let Some(to) = &self.to { to.assemble(c, needs)?.apply(c)?; c.asm.push( Inst::Variant { variant: InstVariant::Some, }, to.span(), ); to.span() } else { c.asm.push( Inst::Variant { variant: InstVariant::None, }, span, ); span }; c.scopes.decl_anon(to)?; let limits = match &self.limits { ast::ExprRangeLimits::HalfOpen(..) => InstRangeLimits::HalfOpen, ast::ExprRangeLimits::Closed(..) => InstRangeLimits::Closed, }; c.asm.push(Inst::Range { limits }, span); c.scopes.undecl_anon(span, 2)?; } else { if let Some(from) = &self.from { from.assemble(c, needs)?.apply(c)?; } if let Some(to) = &self.to { to.assemble(c, needs)?.apply(c)?; } } c.scopes.pop(guard, span)?; Ok(Asm::top(span)) } }
use std::collections::HashMap; use crate::core::{Part, Solution}; pub fn solve(part: Part, input: String) -> String { match part { Part::P1 => Day07::solve_part_one(input), Part::P2 => Day07::solve_part_two(input), } } const MAX_DIR_SIZE: i32 = 100_000; const SYSTEM_SPACE: i32 = 70_000_000; const UPDATES_SIZE: i32 = 30_000_000; struct Dir { size: i32, dirs: Vec<String>, } impl Dir { fn total_size(&self, dirs: &HashMap<String, Dir>) -> i32 { self.dirs.iter().fold(self.size, |total, key| { total + dirs[key].total_size(dirs) }) } } struct Day07; impl Solution for Day07 { fn solve_part_one(input: String) -> String { let mut path = vec![]; let directories: HashMap<String, Dir> = input .split("$ cd ") .filter_map(|section| { let mut lines = section.lines(); let dir = match lines.next() { None => return None, Some("..") => { path.pop(); return None }, Some(dir) => dir, }; path.push(dir); let cwd = path.join(""); let mut size = 0; let mut dirs = Vec::new(); for line in lines.skip(1) { let (first, second) = line.split_once(' ').unwrap(); if let Ok(file_size) = first.parse::<i32>() { size += file_size; } else { dirs.push(format!("{}{}", cwd, second)); } } Some((cwd, Dir { size, dirs })) }) .collect(); directories .values() .map(|dir| dir.total_size(&directories)) .filter(|size| size < &MAX_DIR_SIZE) .sum::<i32>() .to_string() } fn solve_part_two(input: String) -> String { let mut path = vec![]; let directories: HashMap<String, Dir> = input .split("$ cd ") .filter_map(|section| { let mut lines = section.lines(); let dir = match lines.next() { None => return None, Some("..") => { path.pop(); return None }, Some(dir) => dir, }; path.push(dir); let cwd = path.join(""); let mut size = 0; let mut dirs = Vec::new(); for line in lines.skip(1) { let (first, second) = line.split_once(' ').unwrap(); if let Ok(file_size) = first.parse::<i32>() { size += file_size; } else { dirs.push(format!("{}{}", cwd, second)); } } Some((cwd, Dir { size, dirs })) }) .collect(); let needed_space = UPDATES_SIZE - (SYSTEM_SPACE - directories["/"].total_size(&directories)); directories .values() .filter_map(|dir| { let size = dir.total_size(&directories); if size >= needed_space { Some(size) } else { None } }) .min() .unwrap() .to_string() } }
use crate::error::{CamlError, Error}; use crate::tag::Tag; use crate::{sys, OCaml, OCamlRef, Runtime}; /// Size is an alias for the platform specific integer type used to store size values pub type Size = sys::Size; /// Value wraps the native OCaml `value` type transparently, this means it has the /// same representation as an `ocaml_sys::Value` #[derive(Debug, Copy, PartialEq, PartialOrd)] #[repr(transparent)] pub struct Value(pub sys::Value); impl Clone for Value { fn clone(&self) -> Value { unsafe { Value::new(self.0) } } } /// `IntoValue` is used to convert from Rust types to OCaml values pub unsafe trait IntoValue { /// Convert to OCaml value fn into_value(self, rt: &Runtime) -> Value; } /// `FromValue` is used to convert from OCaml values to Rust types pub unsafe trait FromValue { /// Convert from OCaml value fn from_value(v: Value) -> Self; } unsafe impl IntoValue for Value { fn into_value(self, _rt: &Runtime) -> Value { unsafe { Value::new(self.0) } } } unsafe impl FromValue for Value { #[inline] fn from_value(v: Value) -> Value { v } } unsafe impl<'a, T> IntoValue for OCaml<'a, T> { fn into_value(self, _rt: &Runtime) -> Value { unsafe { Value::new(self.raw()) } } } unsafe impl<'a, T> IntoValue for OCamlRef<'a, T> { fn into_value(self, _rt: &Runtime) -> Value { unsafe { Value::new(self.get_raw()) } } } unsafe impl crate::interop::ToOCaml<Value> for Value { fn to_ocaml<'a>(&self, gc: &'a mut Runtime) -> OCaml<'a, Value> { unsafe { OCaml::new(gc, self.0) } } } unsafe impl<'a> crate::interop::FromOCaml<Value> for Value { fn from_ocaml(v: OCaml<Value>) -> Value { unsafe { Value::new(v.raw()) } } } const NONE: Value = unsafe { Value::new(sys::NONE) }; const UNIT: Value = unsafe { Value::new(sys::UNIT) }; impl Value { /// Convert from `Value` into `interop::OCaml<T>` pub unsafe fn interop<'a, T>(&self, rt: &'a Runtime) -> OCaml<'a, T> { OCaml::new(rt, self.0) } /// Returns a named value registered by OCaml pub unsafe fn named<T: FromValue>(name: &str) -> Option<T> { let s = match crate::util::CString::new(name) { Ok(s) => s, Err(_) => return None, }; let named = sys::caml_named_value(s.as_ptr()); if named.is_null() { return None; } Some(FromValue::from_value(Value::new(*named))) } /// Allocate a new value with the given size and tag. pub unsafe fn alloc(rt: &Runtime, n: usize, tag: Tag) -> Value { crate::frame!(rt: (x) { x = Value::new(sys::caml_alloc(n, tag.into())); x }) } /// Allocate a new tuple value pub unsafe fn alloc_tuple(rt: &Runtime, n: usize) -> Value { crate::frame!(rt: (x) { x = Value::new(sys::caml_alloc_tuple(n)); x }) } /// Allocate a new small value with the given size and tag pub unsafe fn alloc_small(rt: &Runtime, n: usize, tag: Tag) -> Value { crate::frame!(rt: (x) { x = Value::new(sys::caml_alloc_small(n, tag.into())); x }) } /// Allocate a new value with a finalizer /// /// This calls `caml_alloc_final` under-the-hood, which can has less than ideal performance /// behavior. In most cases you should prefer `Pointer::alloc_custom` when possible. pub unsafe fn alloc_final<T>( rt: &Runtime, finalizer: unsafe extern "C" fn(Value), cfg: Option<(usize, usize)>, ) -> Value { let (used, max) = cfg.unwrap_or((0, 1)); crate::frame!(rt: (x) { Value::new(sys::caml_alloc_final( core::mem::size_of::<T>(), core::mem::transmute(finalizer), used, max )) }) } /// Allocate custom value pub unsafe fn alloc_custom<T: crate::Custom>(rt: &Runtime) -> Value { let size = core::mem::size_of::<T>(); crate::frame!(rt: (x) { x = Value::new(sys::caml_alloc_custom(T::ops() as *const _ as *const sys::custom_operations, size, T::USED, T::MAX)); x }) } /// Allocate an abstract pointer value, it is best to ensure the value is /// on the heap using `Box::into_raw(Box::from(...))` to create the pointer /// and `Box::from_raw` to free it pub unsafe fn alloc_abstract_ptr<T>(rt: &Runtime, ptr: *mut T) -> Value { let x = Self::alloc(rt, 1, Tag::ABSTRACT); let dest = x.0 as *mut *mut T; *dest = ptr; x } /// Create a new Value from an existing OCaml `value` #[inline] pub const unsafe fn new(v: sys::Value) -> Value { Value(v) } /// Get array length pub unsafe fn array_length(self) -> usize { sys::caml_array_length(self.0) } /// See caml_register_global_root pub unsafe fn register_global_root(&mut self) { sys::caml_register_global_root(&mut self.0) } /// Set caml_remove_global_root pub unsafe fn remove_global_root(&mut self) { sys::caml_remove_global_root(&mut self.0) } /// Get the tag for the underlying OCaml `value` pub unsafe fn tag(self) -> Tag { sys::tag_val(self.0).into() } /// Convert a boolean to OCaml value pub const unsafe fn bool(b: bool) -> Value { Value::int(b as crate::Int) } /// Allocate and copy a string value pub unsafe fn string<S: AsRef<str>>(rt: &Runtime, s: S) -> Value { s.as_ref().into_value(rt) } /// Allocate and copy a byte array value pub unsafe fn bytes<S: AsRef<[u8]>>(rt: &Runtime, s: S) -> Value { s.as_ref().into_value(rt) } /// Convert from a pointer to an OCaml string back to an OCaml value /// /// # Safety /// This function assumes that the `str` argument has been allocated by OCaml pub unsafe fn of_str(s: &str) -> Value { Value::new(s.as_ptr() as isize) } /// Convert from a pointer to an OCaml string back to an OCaml value /// /// # Safety /// This function assumes that the `&[u8]` argument has been allocated by OCaml pub unsafe fn of_bytes(s: &[u8]) -> Value { Value::new(s.as_ptr() as isize) } /// OCaml Some value pub unsafe fn some<V: IntoValue>(rt: &Runtime, v: V) -> Value { crate::frame!(rt: (x) { x = Value::new(sys::caml_alloc(1, 0)); x.store_field(rt, 0, v); x }) } /// OCaml None value #[inline(always)] pub const fn none() -> Value { NONE } /// OCaml Unit value #[inline(always)] pub const fn unit() -> Value { UNIT } /// Create a variant value pub unsafe fn variant(rt: &Runtime, tag: u8, value: Option<Value>) -> Value { crate::frame!(rt: (x) { match value { Some(v) => { x = Value::new(sys::caml_alloc(1, tag)); x.store_field(rt, 0, v) }, None => x = Value::new(sys::caml_alloc(0, tag)), } x }) } /// Result.Ok value pub unsafe fn result_ok(rt: &Runtime, value: impl Into<Value>) -> Value { Self::variant(rt, 0, Some(value.into())) } /// Result.Error value pub unsafe fn result_error(rt: &Runtime, value: impl Into<Value>) -> Value { Self::variant(rt, 1, Some(value.into())) } /// Create an OCaml `int` pub const unsafe fn int(i: crate::Int) -> Value { Value::new(sys::val_int(i)) } /// Create an OCaml `int` pub const unsafe fn uint(i: crate::Uint) -> Value { Value::new(sys::val_int(i as crate::Int)) } /// Create an OCaml `Int64` from `i64` pub unsafe fn int64(rt: &Runtime, i: i64) -> Value { crate::frame!(rt: (x) { x = Value::new(sys::caml_copy_int64(i)); x }) } /// Create an OCaml `Int32` from `i32` pub unsafe fn int32(rt: &Runtime, i: i32) -> Value { crate::frame!(rt: (x) { x = Value::new(sys::caml_copy_int32(i)); x }) } /// Create an OCaml `Nativeint` from `isize` pub unsafe fn nativeint(rt: &Runtime, i: isize) -> Value { frame!(rt: (x) { x = Value::new(sys::caml_copy_nativeint(i)); x }) } /// Create an OCaml `Float` from `f64` pub unsafe fn float(rt: &Runtime, d: f64) -> Value { frame!(rt: (x) { x = Value::new(sys::caml_copy_double(d)); x }) } /// Check if a Value is an integer or block, returning true if /// the underlying value is a block pub unsafe fn is_block(self) -> bool { sys::is_block(self.0) } /// Check if a Value is an integer or block, returning true if /// the underlying value is an integer pub unsafe fn is_long(self) -> bool { sys::is_long(self.0) } /// Get index of underlying OCaml block value pub unsafe fn field<T: FromValue>(self, i: Size) -> T { T::from_value(Value::new(*sys::field(self.0, i))) } /// Set index of underlying OCaml block value pub unsafe fn store_field<V: IntoValue>(&mut self, rt: &Runtime, i: Size, val: V) { sys::store_field(self.0, i, val.into_value(rt).0) } /// Convert an OCaml `int` to `isize` pub const unsafe fn int_val(self) -> isize { sys::int_val(self.0) } /// Convert an OCaml `Float` to `f64` pub unsafe fn float_val(self) -> f64 { *(self.0 as *const f64) } /// Convert an OCaml `Int32` to `i32` pub unsafe fn int32_val(self) -> i32 { *self.custom_ptr_val::<i32>() } /// Convert an OCaml `Int64` to `i64` pub unsafe fn int64_val(self) -> i64 { *self.custom_ptr_val::<i64>() } /// Convert an OCaml `Nativeint` to `isize` pub unsafe fn nativeint_val(self) -> isize { *self.custom_ptr_val::<isize>() } /// Get pointer to data stored in an OCaml custom value pub unsafe fn custom_ptr_val<T>(self) -> *const T { sys::field(self.0, 1) as *const T } /// Get mutable pointer to data stored in an OCaml custom value pub unsafe fn custom_ptr_val_mut<T>(self) -> *mut T { sys::field(self.0, 1) as *mut T } /// Get pointer to the pointer contained by Value pub unsafe fn abstract_ptr_val<T>(self) -> *const T { *(self.0 as *const *const T) } /// Get mutable pointer to the pointer contained by Value pub unsafe fn abstract_ptr_val_mut<T>(self) -> *mut T { *(self.0 as *mut *mut T) } /// Get underlying string pointer pub unsafe fn string_val(&self) -> &str { let len = crate::sys::caml_string_length(self.0); let ptr = crate::sys::string_val(self.0); let slice = ::core::slice::from_raw_parts(ptr, len); ::core::str::from_utf8(slice).expect("Invalid UTF-8") } /// Get underlying bytes pointer pub unsafe fn bytes_val(&self) -> &[u8] { let len = crate::sys::caml_string_length(self.0); let ptr = crate::sys::string_val(self.0); ::core::slice::from_raw_parts(ptr, len) } /// Get mutable string pointer pub unsafe fn string_val_mut(&mut self) -> &mut str { let len = crate::sys::caml_string_length(self.0); let ptr = crate::sys::string_val(self.0); let slice = ::core::slice::from_raw_parts_mut(ptr, len); ::core::str::from_utf8_mut(slice).expect("Invalid UTF-8") } /// Get mutable bytes pointer pub unsafe fn bytes_val_mut(&mut self) -> &mut [u8] { let len = crate::sys::caml_string_length(self.0); let ptr = crate::sys::string_val(self.0); ::core::slice::from_raw_parts_mut(ptr, len) } /// Extract OCaml exception pub unsafe fn exception<A: FromValue>(self) -> Option<A> { if !self.is_exception_result() { return None; } Some(A::from_value(Value::new(crate::sys::extract_exception( self.0, )))) } /// Call a closure with a single argument, returning an exception value pub unsafe fn call<A: IntoValue>(self, rt: &Runtime, arg: A) -> Result<Value, Error> { if self.tag() != Tag::CLOSURE { return Err(Error::NotCallable); } let mut v = crate::frame!(rt: (res) { res = Value::new(sys::caml_callback_exn(self.0, arg.into_value(rt).0)); res }); if v.is_exception_result() { v = v.exception().unwrap(); Err(CamlError::Exception(v).into()) } else { Ok(v) } } /// Call a closure with two arguments, returning an exception value pub unsafe fn call2<A: IntoValue, B: IntoValue>( self, rt: &Runtime, arg1: A, arg2: B, ) -> Result<Value, Error> { if self.tag() != Tag::CLOSURE { return Err(Error::NotCallable); } let mut v = crate::frame!(rt: (res) { res = Value::new(sys::caml_callback2_exn(self.0, arg1.into_value(rt).0, arg2.into_value(rt).0)); res }); if v.is_exception_result() { v = v.exception().unwrap(); Err(CamlError::Exception(v).into()) } else { Ok(v) } } /// Call a closure with three arguments, returning an exception value pub unsafe fn call3<A: IntoValue, B: IntoValue, C: IntoValue>( self, rt: &Runtime, arg1: A, arg2: B, arg3: C, ) -> Result<Value, Error> { if self.tag() != Tag::CLOSURE { return Err(Error::NotCallable); } let mut v = crate::frame!(rt: (res) { res = Value::new(sys::caml_callback3_exn( self.0, arg1.into_value(rt).0, arg2.into_value(rt).0, arg3.into_value(rt).0, )); res }); if v.is_exception_result() { v = v.exception().unwrap(); Err(CamlError::Exception(v).into()) } else { Ok(v) } } /// Call a closure with `n` arguments, returning an exception value pub unsafe fn call_n<A: AsRef<[Value]>>(self, rt: &Runtime, args: A) -> Result<Value, Error> { if self.tag() != Tag::CLOSURE { return Err(Error::NotCallable); } let n = args.as_ref().len(); let x = args.as_ref(); let mut v = crate::frame!(rt: (res) { res = Value::new(sys::caml_callbackN_exn( self.0, n, x.as_ptr() as *mut sys::Value, )); res }); if v.is_exception_result() { v = v.exception().unwrap(); Err(CamlError::Exception(v).into()) } else { Ok(v) } } /// Modify an OCaml value in place pub unsafe fn modify<V: IntoValue>(&mut self, rt: &Runtime, v: V) { sys::caml_modify(&mut self.0, v.into_value(rt).0) } /// Determines if the current value is an exception pub unsafe fn is_exception_result(self) -> bool { crate::sys::is_exception_result(self.0) } /// Get hash variant as OCaml value pub unsafe fn hash_variant<S: AsRef<str>>(rt: &Runtime, name: S, a: Option<Value>) -> Value { let s = crate::util::CString::new(name.as_ref()).expect("Invalid C string"); let hash = Value::new(sys::caml_hash_variant(s.as_ptr() as *const u8)); match a { Some(x) => { let mut output = Value::alloc_small(rt, 2, Tag(0)); output.store_field(rt, 0, hash); output.store_field(rt, 1, x); output } None => hash, } } /// Get object method pub unsafe fn method<S: AsRef<str>>(self, rt: &Runtime, name: S) -> Option<Value> { if self.tag() != Tag::OBJECT { return None; } let v = sys::caml_get_public_method(self.0, Self::hash_variant(rt, name, None).0); if v == 0 { return None; } Some(Value::new(v)) } /// Initialize OCaml value using `caml_initialize` pub unsafe fn initialize(&mut self, value: Value) { sys::caml_initialize(&mut self.0, value.0) } #[cfg(not(feature = "no-std"))] unsafe fn slice<'a>(self) -> &'a [Value] { ::core::slice::from_raw_parts( (self.0 as *const Value).offset(-1), sys::wosize_val(self.0) + 1, ) } /// This will recursively clone any OCaml value /// The new value is allocated inside the OCaml heap, /// and may end up being moved or garbage collected. pub unsafe fn deep_clone_to_ocaml(self, rt: &Runtime) -> Self { if self.is_long() { return self; } let wosize = sys::wosize_val(self.0); let val1 = Self::alloc(rt, wosize, self.tag()); let ptr0 = self.0 as *const sys::Value; let ptr1 = val1.0 as *mut sys::Value; if self.tag() >= Tag::NO_SCAN { ptr0.copy_to_nonoverlapping(ptr1, wosize); return val1; } for i in 0..(wosize as isize) { sys::caml_initialize( ptr1.offset(i), Value::new(ptr0.offset(i).read()).deep_clone_to_ocaml(rt).0, ); } val1 } /// This will recursively clone any OCaml value /// The new value is allocated outside of the OCaml heap, and should /// only be used for storage inside Rust structures. #[cfg(not(feature = "no-std"))] pub unsafe fn deep_clone_to_rust(self) -> Self { if self.is_long() { return self; } if self.tag() >= Tag::NO_SCAN { let slice0 = Value::slice(self); let vec1 = slice0.to_vec(); let ptr1 = vec1.as_ptr(); core::mem::forget(vec1); return Value::new(ptr1.offset(1) as isize); } let slice0 = Value::slice(self); let vec1: Vec<Value> = slice0 .iter() .enumerate() .map(|(i, v)| if i == 0 { *v } else { v.deep_clone_to_rust() }) .collect(); let ptr1 = vec1.as_ptr(); core::mem::forget(vec1); Value::new(ptr1.offset(1) as isize) } }
//! Method with non-deserializable argument type. use near_bindgen::near_bindgen; use borsh::{BorshDeserialize, BorshSerialize}; #[near_bindgen] #[derive(Default, BorshDeserialize, BorshSerialize)] struct Storage { data: Vec<u64>, } #[near_bindgen] impl Storage { pub fn insert(&mut self) -> impl Iterator<Item=&u64> { self.data.iter() } } fn main() {}
extern crate tiff; use tiff::ColorType; use tiff::decoder::{Decoder, DecodingResult, ifd::Tag, ifd::Value}; use std::fs::File; #[test] fn test_gray_u8() { let img_file = File::open("./tests/images/minisblack-1c-8b.tiff").expect("Cannot find test image!"); let mut decoder = Decoder::new(img_file).expect("Cannot create decoder"); assert_eq!(decoder.colortype().unwrap(), ColorType::Gray(8)); let img_res = decoder.read_image(); assert!(img_res.is_ok()); } #[test] fn test_rgb_u8() { let img_file = File::open("./tests/images/rgb-3c-8b.tiff").expect("Cannot find test image!"); let mut decoder = Decoder::new(img_file).expect("Cannot create decoder"); assert_eq!(decoder.colortype().unwrap(), ColorType::RGB(8)); let img_res = decoder.read_image(); assert!(img_res.is_ok()); } #[test] fn test_gray_u16() { let img_file = File::open("./tests/images/minisblack-1c-16b.tiff").expect("Cannot find test image!"); let mut decoder = Decoder::new(img_file).expect("Cannot create decoder"); assert_eq!(decoder.colortype().unwrap(), ColorType::Gray(16)); let img_res = decoder.read_image(); assert!(img_res.is_ok()); } #[test] fn test_rgb_u16() { let img_file = File::open("./tests/images/rgb-3c-16b.tiff").expect("Cannot find test image!"); let mut decoder = Decoder::new(img_file).expect("Cannot create decoder"); assert_eq!(decoder.colortype().unwrap(), ColorType::RGB(16)); let img_res = decoder.read_image(); assert!(img_res.is_ok()); } #[test] fn test_string_tags() { // these files have null-terminated strings for their Software tag. One has extra bytes after // the null byte, so we check both to ensure that we're truncating properly let filenames = vec!["minisblack-1c-16b.tiff", "rgb-3c-16b.tiff"]; for filename in filenames.iter() { let path = format!("./tests/images/{}", filename); let img_file = File::open(path).expect("can't open file"); let mut decoder = Decoder::new(img_file).expect("Cannot create decoder"); let software= decoder.get_tag(Tag::Software).unwrap(); match software { Value::Ascii(s) => assert_eq!(s, String::from("GraphicsMagick 1.2 unreleased Q16 http://www.GraphicsMagick.org/")), _ => assert!(false) }; } } // TODO: GrayA support //#[test] //fn test_gray_alpha_u8() //{ //let img_file = File::open("./tests/images/minisblack-2c-8b-alpha.tiff").expect("Cannot find test image!"); //let mut decoder = Decoder::new(img_file).expect("Cannot create decoder"); //assert_eq!(decoder.colortype().unwrap(), ColorType::GrayA(8)); //let img_res = decoder.read_image(); //assert!(img_res.is_ok()); //}
//! C API wrappers to create Telamon Kernels. use crate::Device; use libc; use num::rational::Ratio; use std::{self, sync::Arc}; use telamon::ir; use telamon_utils::*; pub use telamon::ir::op::Rounding; use super::error::TelamonStatus; /// Creates a function signature that must be deallocated with /// `telamon_ir_signature_free`. #[no_mangle] pub unsafe extern "C" fn telamon_ir_signature_new( name: *const libc::c_char, ) -> *const ir::Signature { let name = unwrap!(std::ffi::CStr::from_ptr(name).to_str()); Arc::into_raw(Arc::new(ir::Signature::new(name.to_string()))) } /// Deallocates a signature created with `telamon_ir_signature_new`. #[no_mangle] pub unsafe extern "C" fn telamon_ir_signature_free(signature: *const ir::Signature) { std::mem::drop(Arc::from_raw(signature)); } /// Returns the parameter at the given position. #[no_mangle] pub unsafe extern "C" fn telamon_ir_signature_param( signature: *const ir::Signature, index: usize, ) -> *const ir::Parameter { &*(*signature).params[index] } /// Adds a scalar parameter to the function signature. #[no_mangle] pub unsafe extern "C" fn telamon_ir_signature_add_scalar( signature: *mut ir::Signature, name: *const libc::c_char, t: *const ir::Type, ) { let name = unwrap!(std::ffi::CStr::from_ptr(name).to_str()); (*signature).add_scalar(name.to_string(), *t); } /// Adds an array parameter to the function signature. #[no_mangle] pub unsafe extern "C" fn telamon_ir_signature_add_array( signature: *mut ir::Signature, name: *const libc::c_char, element_type: *const ir::Type, device: *const Device, ) { let name = unwrap!(std::ffi::CStr::from_ptr(name).to_str()); (*signature).add_array(&*(*device).0, name.to_string(), *element_type) } /// Creates an integer type that must be freed with `telamon_ir_type_free`. #[no_mangle] pub unsafe extern "C" fn telamon_ir_type_new_int(num_bits: u16) -> *mut ir::Type { Box::into_raw(Box::new(ir::Type::I(num_bits))) } /// Creates a floating point type that must be freed with `telamon_ir_type_free`. #[no_mangle] pub unsafe extern "C" fn telamon_ir_type_new_float(num_bits: u16) -> *mut ir::Type { Box::into_raw(Box::new(ir::Type::F(num_bits))) } /// Frees a type allocated with `telamon_ir_type_new_int` or `telamon_ir_type_new_float`. #[no_mangle] pub unsafe extern "C" fn telamon_ir_type_free(t: *mut ir::Type) { std::mem::drop(Box::from_raw(t)); } /// Opaque type that abstracts away the lifetime parameter of `ir::Function` so that /// cbindgen generates the bindings. #[derive(Clone)] pub struct Function(ir::Function<()>); impl Into<ir::Function<()>> for Function { fn into(self) -> ir::Function<()> { self.0 } } /// Creates a function to optimize. The function must be freed with /// `telamon_ir_function_free`. `signature` and `device` must outlive the function. #[no_mangle] pub unsafe extern "C" fn telamon_ir_function_new( signature: *const ir::Signature, device: *const Device, ) -> *mut Function { Box::into_raw(Box::new(Function(ir::Function::new( Arc::clone(&Arc::from_raw(signature)), Arc::clone(&Arc::from_raw((*device).0)), )))) } /// Frees a function allocated with `telamon_ir_function_new`. #[no_mangle] pub unsafe extern "C" fn telamon_ir_function_free(function: *mut Function) { std::mem::drop(Box::from_raw(function)); } /// Adds an instruction performing the given operator in the given dimensions to the /// function. Writes the unique identifier of the instruction in `inst_id`. Returns /// `Ok` except if an error occurs. Takes ownership of the operator /// but does not keeps any reference to `dimensions`. #[no_mangle] pub unsafe extern "C" fn telamon_ir_function_add_instruction( function: *mut Function, operator: *mut Operator, dimensions: *const ir::DimId, num_dimensions: usize, inst_id: *mut ir::InstId, ) -> TelamonStatus { let dimensions = std::slice::from_raw_parts(dimensions, num_dimensions); let dim_set = dimensions.iter().cloned().collect(); let operator = Box::from_raw(operator).0; *inst_id = unwrap_or_exit!((*function).0.add_inst(operator, dim_set)); TelamonStatus::Ok } /// Adds a logical dimension of the given size to the function. In practice, this creates a /// dimension for each tiling level plus one. Takes ownership of `size` and writes the unique /// identifier of the logical dimension in `logical_id`. Writes the ids of the dimensions, from the /// outermost to the innermost, in `dim_ids`. `dim_ids` must be at least of size `num_tiles + 1`. /// Returns `Ok` except if an error occurs. #[no_mangle] pub unsafe extern "C" fn telamon_ir_function_add_dimensions( function: *mut Function, size: *mut Size, tile_sizes: *const u32, num_tiles: usize, logical_id: *mut ir::LogicalDimId, dim_ids: *mut ir::DimId, ) -> TelamonStatus { let tile_sizes = std::slice::from_raw_parts(tile_sizes, num_tiles); let tiling_factors = vec![tile_sizes.iter().product::<u32>()]; let tile_sizes = tile_sizes.iter().map(|&s| VecSet::new(vec![s])).collect(); let size = Box::from_raw(size).0; let (ldim, dims) = unwrap_or_exit!((*function).0.add_logical_dim( size, tiling_factors.into(), tile_sizes )); *logical_id = ldim; std::ptr::copy_nonoverlapping(dims.as_ptr(), dim_ids, num_tiles + 1); TelamonStatus::Ok } /// Opaque type that abstracts away the lifetime parameter of `ir::Size` so cbindgen /// can generate bindings. pub struct Size(ir::Size); /// Create a size equal to: /// ``` /// const_factor * param_factors[0] * .. * param_factors[num_params-1] /// ``` /// The size must be freed calling `telamon_ir_size_free` or passed to a function that /// takes its ownership. // TODO(bclement): Adapt to Arc<Parameters> /* #[no_mangle] pub unsafe extern "C" fn telamon_ir_size_new( const_factor: u32, param_factors: *const *const ir::Parameter, num_params: usize, max_val: u32, ) -> *mut Size { let parameters = std::slice::from_raw_parts(param_factors, num_params) .iter() .map(|&ptr| Arc::new(*ptr)) .collect(); let size = ir::Size::new(const_factor, parameters, max_val); Box::into_raw(Box::new(Size(size))) }*/ /// Frees a size allocated with `telamon_ir_size_new`. #[no_mangle] pub unsafe extern "C" fn telamon_ir_size_free(size: *mut Size) { std::mem::drop(Box::from_raw(size)); } /// Opaque type that abstracts away the lifetime parameter of `ir::SizeiPartial` so /// cbindgen can generate bindings. pub struct PartialSize(ir::PartialSize); /// Converts an `ir::Size` into an `ir::PartialSize`. #[no_mangle] pub unsafe extern "C" fn telamon_ir_size_into_partial( size: *mut Size, ) -> *mut PartialSize { let size = Box::from_raw(size).0.into(); Box::into_raw(Box::new(PartialSize(size))) } /// Returns the size of a dimension. #[no_mangle] pub unsafe extern "C" fn telamon_ir_dimension_size( function: *const Function, dim: ir::DimId, ) -> *mut PartialSize { let size = (*function).0.dim(dim).size().clone(); Box::into_raw(Box::new(PartialSize(size))) } /// Multiplies `lhs` by `rhs`. #[no_mangle] pub unsafe extern "C" fn telamon_ir_size_mul( lhs: *mut PartialSize, rhs: *const PartialSize, ) { (*lhs).0 *= &(*rhs).0; } /// Opaque type that abstracts away the lifetime parameter of `ir::Operand` so that /// cbindgen can generate bindings. pub struct Operand(ir::Operand<()>); /// Create a constant integer operand. The provided type must be an integer type. /// Returns `null` if an error is encountered. #[no_mangle] pub unsafe extern "C" fn telamon_ir_operand_new_int( t: *const ir::Type, value: i64, ) -> *mut Operand { unwrap_or_exit!(ir::TypeError::check_integer(*t), null); let type_len = unwrap!((*t).len_byte()) as u16; let operand = ir::Operand::new_int((num::BigInt::from(value), 8 * type_len)); Box::into_raw(Box::new(Operand(operand))) } /// Creates a constant floating point operand. The provided type must be a float type. /// Returns `null` if an error is encountered. #[no_mangle] pub unsafe extern "C" fn telamon_ir_operand_new_float( t: *const ir::Type, value: libc::c_double, ) -> *mut Operand { unwrap_or_exit!(ir::TypeError::check_float(*t), null); let type_len = unwrap!((*t).len_byte()) as u16; let value = unwrap!(Ratio::from_float(value)); let operand = ir::Operand::new_float((value, type_len)); Box::into_raw(Box::new(Operand(operand))) } /// Creates an operand that fetches the value of a parameter. The created operand holds /// a reference to `parameter`. // TODO(bclement): Adapt to Arc<Parameter> /* #[no_mangle] pub unsafe extern "C" fn telamon_ir_operand_new_parameter( parameter: *const ir::Parameter, ) -> *mut Operand { let operand = ir::Operand::Param(Arc::new(*parameter)); Box::into_raw(Box::new(Operand(operand))) } */ /// Creates an operand that returns the current index on a dimension. #[no_mangle] pub unsafe extern "C" fn telamon_ir_operand_new_index(dim: ir::DimId) -> *mut Operand { let operand = ir::Operand::Index(dim); Box::into_raw(Box::new(Operand(operand))) } /// Creates an operand that references the value of an instruction. The value of the /// instruction is transmitted point-to-point between the source dimensions (`src_dims`, /// in which the instruction is produced) and destination dimensions (`dst_dims`, in which /// the operand is used). `num_mapped_dims` indicates the number of dimensions in /// `src_dims` and in `dst_dims`. If `allow_tmp_mem` is non-zero, Telamon can allocate /// memory to transfer data between the two loop nests. Otherwise, it makes sure the data /// can be stored in registers (for example by fusing or unrolling loops). #[no_mangle] pub unsafe extern "C" fn telamon_ir_operand_new_inst( function: *const Function, inst: ir::InstId, src_dims: *const ir::DimId, dst_dims: *const ir::DimId, num_mapped_dims: usize, allow_tmp_mem: libc::c_int, ) -> *mut Operand { let inst = (*function).0.inst(inst); let dim_map = dim_map_from_arrays(src_dims, dst_dims, num_mapped_dims); let dim_map_scope = if allow_tmp_mem == 0 { ir::DimMapScope::Thread } else { ir::DimMapScope::Global(()) }; let operand = ir::Operand::new_inst(inst, dim_map, dim_map_scope); Box::into_raw(Box::new(Operand(operand))) } /// Creates an operand that take the value of `init_inst` the first time is is encountered /// and then reuse the value produced by the instruction using the operand, effectivelly /// creating a reduction. The value is is transmitted point-to-point between the source /// dimensions (`src_dims`, in which `init_inst` is produced) and destination dimensions /// (`dst_dims`, in which the operand is used). `num_mapped_dims` indicates the number of /// dimensions in `src_dims` and in `dst_dims`. `reduction_dims` indicates on which /// dimensions the reduction occurs: values are not reused accross other dimensions. #[no_mangle] pub unsafe extern "C" fn telamon_ir_operand_new_reduction( function: *const Function, init_inst: ir::InstId, src_dims: *const ir::DimId, dst_dims: *const ir::DimId, num_mapped_dims: usize, reduction_dims: *const ir::DimId, num_reduction_dims: usize, ) -> *mut Operand { let init = (*function).0.inst(init_inst); let reduction_dims = std::slice::from_raw_parts(reduction_dims, num_reduction_dims).to_vec(); let dim_map = dim_map_from_arrays(src_dims, dst_dims, num_mapped_dims); let operand = ir::Operand::new_reduce(init, dim_map, reduction_dims); Box::into_raw(Box::new(Operand(operand))) } /// Helper function that creates a `DimMap` from C arrays of dimensions. Does not holds /// references after the function exits. unsafe fn dim_map_from_arrays( src_dims: *const ir::DimId, dst_dims: *const ir::DimId, num_mapped_dims: usize, ) -> ir::DimMap { let src_dims = std::slice::from_raw_parts(src_dims, num_mapped_dims); let dst_dims = std::slice::from_raw_parts(dst_dims, num_mapped_dims); let dims = src_dims.iter().cloned().zip(dst_dims.iter().cloned()); ir::DimMap::new(dims) } /// Opaque type that abstracts away the lifetime parameter of `ir::Operator` so that /// cbindgen can generate bindings. pub struct Operator(ir::Operator<()>); /// Creates a `mov` operator. Takes ownership of `operand`. #[no_mangle] pub unsafe extern "C" fn telamon_ir_operator_new_mov( operand: *mut Operand, ) -> *mut Operator { let operator = ir::Operator::UnaryOp(ir::UnaryOp::Mov, Box::from_raw(operand).0); Box::into_raw(Box::new(Operator(operator))) } /// Creates a binary operator. Takes ownership of the operands. #[no_mangle] pub unsafe extern "C" fn telamon_ir_operator_new_binop( binop: ir::BinOp, lhs: *mut Operand, rhs: *mut Operand, rounding: ir::op::Rounding, ) -> *mut Operator { let lhs = Box::from_raw(lhs).0; let rhs = Box::from_raw(rhs).0; let operator = ir::Operator::BinOp(binop, lhs, rhs, rounding); Box::into_raw(Box::new(Operator(operator))) } /// Creates a `mul` operator. The return type can either be the operands type or, if the /// multplication operates on integers, a type twice the size of the input. Takes /// ownership of both `lhs` and `rhs`. No references to `return_type` is hold after the /// function returns. #[no_mangle] pub unsafe extern "C" fn telamon_ir_operator_new_mul( lhs: *mut Operand, rhs: *mut Operand, rounding: ir::op::Rounding, return_type: *const ir::Type, ) -> *mut Operator { let lhs = Box::from_raw(lhs).0; let rhs = Box::from_raw(rhs).0; let operator = ir::Operator::Mul(lhs, rhs, rounding, *return_type); Box::into_raw(Box::new(Operator(operator))) } /// Creates a `mad` operator, that computes `mul_lhs * mul_rhs + add_rhs`. If the operator /// operates on integer, the type of `add_rhs` can either be the type of both `mul_lhs` /// and `mul_rhs` or an integer type having twice the size of the multiplied types. Takes /// ownership of `mul_lhs`, `mul_rhs` and `add_rhs`. #[no_mangle] pub unsafe extern "C" fn telamon_ir_operator_new_mad( mul_lhs: *mut Operand, mul_rhs: *mut Operand, add_rhs: *mut Operand, rounding: ir::op::Rounding, ) -> *mut Operator { let mul_lhs = Box::from_raw(mul_lhs).0; let mul_rhs = Box::from_raw(mul_rhs).0; let add_rhs = Box::from_raw(add_rhs).0; let operator = ir::Operator::Mad(mul_lhs, mul_rhs, add_rhs, rounding); Box::into_raw(Box::new(Operator(operator))) } /// Creates a `cast` operator. Takes ownership of `operand`. No reference to `return_type` /// is hold after the function returns. #[no_mangle] pub unsafe extern "C" fn telamon_ir_operator_new_cast( operand: *mut Operand, return_type: *const ir::Type, ) -> *mut Operator { let operand = Box::from_raw(operand).0; let operator = ir::Operator::UnaryOp(ir::UnaryOp::Cast(*return_type), operand); Box::into_raw(Box::new(Operator(operator))) } /// Creates an operator that loads a tensor stored in memory. Takes the ownership of /// `base_address` and creates copies of `strided_dims`, `strides` and `loaded_type`. /// This function also adds the necessary address computation code to `function`. #[no_mangle] pub unsafe extern "C" fn telamon_ir_operator_new_tensor_load( function: *mut Function, array_id: *const ir::MemId, base_address: *mut Operand, strided_dims: *const ir::DimId, strides: *const PartialSize, num_strided_dims: usize, loaded_type: *const ir::Type, ) -> *mut Operator { let tensor_access = tensor_access( function, array_id, base_address, strided_dims, strides, num_strided_dims, ); let (address, access_pattern) = unwrap_or_exit!(tensor_access, null); let operator = ir::Operator::Ld(*loaded_type, address, access_pattern); Box::into_raw(Box::new(Operator(operator))) } /// Creates an operator that stores a tensor in memory. Takes the ownership of /// `base_address` and `value` and creates copies of `strided_dims`, `strides` and /// `loaded_type`. This function also adds the necessary address computation code to /// `function`. #[no_mangle] pub unsafe extern "C" fn telamon_ir_operator_new_tensor_store( function: *mut Function, array_id: *const ir::MemId, base_address: *mut Operand, strided_dims: *const ir::DimId, strides: *const PartialSize, num_strided_dims: usize, value: *mut Operand, ) -> *mut Operator { let tensor_access = tensor_access( function, array_id, base_address, strided_dims, strides, num_strided_dims, ); let (address, access_pattern) = unwrap_or_exit!(tensor_access, null); let value = Box::from_raw(value).0; let operator = ir::Operator::St(address, value, true, access_pattern); Box::into_raw(Box::new(Operator(operator))) } /// Helper function that generates the address and the access pattern of a tensor /// memory access. Takes the ownership of `base_adress`, and creates copies of /// `strided_dims` and `strides`. unsafe fn tensor_access( function: *mut Function, array_id: *const ir::MemId, base_address: *mut Operand, strided_dims: *const ir::DimId, strides: *const PartialSize, num_strided_dims: usize, ) -> Result<(ir::Operand<()>, ir::AccessPattern), ir::Error> { let base_address = Box::from_raw(base_address).0; let ptr_type = base_address.t(); let strided_dims = std::slice::from_raw_parts(strided_dims, num_strided_dims); let strides = std::slice::from_raw_parts(strides, num_strided_dims); let address = if strided_dims.is_empty() { base_address } else { let dims = (0..num_strided_dims) .map(|i| (strided_dims[i], strides[i].0.clone())) .collect(); let ind_var = ir::InductionVar::new(dims, base_address)?; let ind_var_id = (*function).0.add_ind_var(ind_var); ir::Operand::InductionVar(ind_var_id, ptr_type) }; let dims = (0..num_strided_dims) .map(|i| (strided_dims[i], strides[i].0.clone())) .collect(); let access_pattern = ir::AccessPattern::Tensor { mem_id: if array_id.is_null() { None } else { Some(*array_id) }, dims, }; Ok((address, access_pattern)) }
#![feature(native_link_modifiers)] #![feature(native_link_modifiers_bundle)] #![feature(static_nobundle)] #[link(name = "foo", kind = "static", modifiers = "-bundle")] extern "C" { fn bar() -> i32; } pub fn rust_bar() -> i32 { unsafe { bar() } }
use super::error::*; use super::symbol::*; use super::script_type_description::*; use futures::*; use gluon::vm::api::*; /// /// Indicates the updates that can occur to a notebook /// #[derive(Clone, PartialEq, Debug)] pub enum NotebookUpdate { /// A symbol has been specified to define a namespace DefinedNamespaceSymbol(FloScriptSymbol), /// A symbol has been specified as an input symbol, accepting data of the specified type DefinedInputSymbol(FloScriptSymbol, ScriptTypeDescription), /// A symbol has been specified as an output symbol, providing data of the specified type DefinedOutputSymbol(FloScriptSymbol, ScriptTypeDescription), /// An output symbol was added but it could not be defined due to an error OutputSymbolError(FloScriptSymbol, FloScriptError), /// A series of updates has been performed in a particular namespace WithNamespace(FloScriptSymbol, Vec<NotebookUpdate>), /// A symbol has been removed from the notebook UndefinedSymbol(FloScriptSymbol) } /// /// FloScripts are evaluated as 'notebooks'. A notebook is a collection of scripts that provide outputs as /// streams. Inputs similarly are provided as streams. /// pub trait FloScriptNotebook : Sized+Send+Sync { /// The type of the stream used to receive updates from this notebook type UpdateStream : Stream<Item=NotebookUpdate, Error=()>+Send; /// Retrieves a stream of updates for this notebook fn updates(&self) -> Self::UpdateStream; /// Retrieves a notebook containing the symbols in the specified namespace fn namespace(&self, symbol: FloScriptSymbol) -> Option<Self>; /// Attaches an input stream to an input symbol. This will replace any existing input stream for that symbol if there is one. fn attach_input<InputStream: 'static+Stream<Error=()>+Send>(&self, symbol: FloScriptSymbol, input: InputStream) -> FloScriptResult<()> where InputStream::Item: ScriptType; /// Creates an output stream to receive the results from a script associated with the specified symbol /// /// We currently limit ourselves to types that are supported in Gluon; once Rust fully supports specialization, it will be possible to /// remove this limit in order to implement the notebook trait on other scripting engines (specialization would make it possible to /// return type errors at runtime instead of compile time and avoid restricting the types here). fn receive_output<OutputItem: 'static+ScriptType>(&self, symbol: FloScriptSymbol) -> FloScriptResult<Box<dyn Stream<Item=OutputItem, Error=()>+Send>> where OutputItem: for<'vm, 'value> Getable<'vm, 'value> + VmType + Send + 'static, <OutputItem as VmType>::Type: Sized; /// Receives the output stream for the specified symbol as a state stream (which will only return the most recently available symbol when polled) fn receive_output_state<OutputItem: 'static+ScriptType>(&self, symbol: FloScriptSymbol) -> FloScriptResult<Box<dyn Stream<Item=OutputItem, Error=()>+Send>> where OutputItem: for<'vm, 'value> Getable<'vm, 'value> + VmType + Send + 'static, <OutputItem as VmType>::Type: Sized; }
use std::ffi::CString; use cql_ffi::collection::set::CassSet; use cql_ffi::collection::map::CassMap; use cql_ffi::collection::list::CassList; use cql_ffi::error::CassError; use cql_ffi::uuid::CassUuid; use cql_ffi::inet::CassInet; use cql_ffi::result::CassResult; use cql_ffi::consistency::CassConsistency; use cql_ffi::udt::CassUserType; use cql_bindgen::CassStatement as _CassStatement; use cql_bindgen::cass_statement_new; //use cql_bindgen::cass_statement_new_n; use cql_bindgen::cass_statement_free; use cql_bindgen::cass_statement_add_key_index; use cql_bindgen::cass_statement_set_keyspace; //use cql_bindgen::cass_statement_set_keyspace_n; use cql_bindgen::cass_statement_set_consistency; use cql_bindgen::cass_statement_set_serial_consistency; use cql_bindgen::cass_statement_set_paging_size; use cql_bindgen::cass_statement_set_paging_state; use cql_bindgen::cass_statement_bind_null; use cql_bindgen::cass_statement_bind_int32; use cql_bindgen::cass_statement_bind_int64; use cql_bindgen::cass_statement_bind_float; use cql_bindgen::cass_statement_bind_double; use cql_bindgen::cass_statement_bind_bool; use cql_bindgen::cass_statement_bind_string; use cql_bindgen::cass_statement_bind_bytes; //use cql_bindgen::cass_statement_bind_tuple; //use cql_bindgen::cass_statement_bind_tuple_by_name; use cql_bindgen::cass_statement_bind_user_type; //use cql_bindgen::cass_statement_bind_user_type_by_name; use cql_bindgen::cass_statement_bind_collection; //use cql_bindgen::cass_statement_bind_decimal; use cql_bindgen::cass_statement_bind_inet; use cql_bindgen::cass_statement_bind_uuid; use cql_bindgen::cass_statement_bind_int32_by_name; use cql_bindgen::cass_statement_bind_int64_by_name; use cql_bindgen::cass_statement_bind_float_by_name; use cql_bindgen::cass_statement_bind_double_by_name; use cql_bindgen::cass_statement_bind_bool_by_name; use cql_bindgen::cass_statement_bind_string_by_name; use cql_bindgen::cass_statement_bind_bytes_by_name; //use cql_bindgen::cass_statement_bind_custom_by_name; use cql_bindgen::cass_statement_bind_collection_by_name; //use cql_bindgen::cass_statement_bind_decimal_by_name; use cql_bindgen::cass_statement_bind_inet_by_name; use cql_bindgen::cass_statement_bind_uuid_by_name; pub struct CassStatement(pub *mut _CassStatement); impl Drop for CassStatement { fn drop(&mut self) { unsafe { self.free() } } } pub enum CassBindable { } impl CassStatement { unsafe fn free(&mut self) { cass_statement_free(self.0) } pub fn bind(&mut self, params: Vec<CassBindable>) { let _ = params; unimplemented!(); } pub fn new(query: &str, parameter_count: u64) -> Self { unsafe { let query = CString::new(query).unwrap(); CassStatement(cass_statement_new(query.as_ptr(), parameter_count)) } } pub fn add_key_index(&mut self, index: u64) -> Result<&Self, CassError> { unsafe { CassError::build( cass_statement_add_key_index(self.0,index) ).wrap(self) } } pub fn set_keyspace(&mut self, keyspace: String) -> Result<&Self, CassError> { unsafe { let keyspace = CString::new(keyspace).unwrap(); CassError::build( cass_statement_set_keyspace(self.0,(keyspace.as_ptr())) ).wrap(self) } } pub fn set_consistency(&mut self, consistency: CassConsistency) -> Result<&Self, CassError> { unsafe { CassError::build( cass_statement_set_consistency(self.0,consistency.0) ).wrap(self) } } pub fn set_serial_consistency(&mut self, serial_consistency: CassConsistency) -> Result<&mut Self, CassError> { unsafe { CassError::build( cass_statement_set_serial_consistency(self.0,serial_consistency.0) ).wrap(self) } } pub fn set_paging_size(&mut self, page_size: i32) -> Result<&mut Self, CassError> { unsafe { CassError::build( cass_statement_set_paging_size(self.0,page_size) ).wrap(self) } } pub fn set_paging_state(&mut self, result: &CassResult) -> Result<&mut Self, CassError> { unsafe { try!( CassError::build( cass_statement_set_paging_state(self.0,result.0) ).wrap(()) ); Ok(self) } } pub fn bind_null(&mut self, index: u64) -> Result<&mut Self, CassError> { unsafe { CassError::build( cass_statement_bind_null(self.0,index) ).wrap(self) } } pub fn bind_int32(&mut self, index: u64, value: i32) -> Result<&mut Self, CassError> { unsafe { CassError::build( cass_statement_bind_int32(self.0,index, value) ).wrap(self) } } pub fn bind_int64(&mut self, index: u64, value: i64) -> Result<&mut Self, CassError> { unsafe { CassError::build( cass_statement_bind_int64(self.0,index, value) ).wrap(self) } } pub fn bind_float(&mut self, index: u64, value: f32) -> Result<&mut Self, CassError> { unsafe { CassError::build( cass_statement_bind_float(self.0,index, value) ).wrap(self) } } pub fn bind_double(&mut self, index: u64, value: f64) -> Result<&mut Self, CassError> { unsafe { CassError::build( cass_statement_bind_double(self.0,index, value) ).wrap(self) } } pub fn bind_bool(&mut self, index: u64, value: bool) -> Result<&mut Self, CassError> { unsafe { CassError::build( cass_statement_bind_bool( self.0, index, if value{1} else {0} ) ).wrap(self) } } pub fn bind_string(&mut self, index: u64, value: &str) -> Result<&mut Self, CassError> { unsafe { let value = CString::new(value).unwrap(); CassError::build( cass_statement_bind_string( self.0,index, value.as_ptr() ) ).wrap(self) } } pub fn bind_bytes(&mut self, index: u64, value: Vec<u8>) -> Result<&mut Self, CassError> { unsafe { CassError::build( cass_statement_bind_bytes( self.0, index, value.as_ptr(), value.len() as u64 ) ).wrap(self) } } pub fn bind_map(&mut self, index: u64, collection: CassMap) -> Result<&mut Self, CassError> { unsafe { CassError::build( cass_statement_bind_collection(self.0,index,collection.0) ).wrap(self) } } pub fn bind_set(&mut self, index: u64, collection: CassSet) -> Result<&mut Self, CassError> { unsafe { CassError::build( cass_statement_bind_collection(self.0,index,collection.0) ).wrap(self) } } pub fn bind_list(&mut self, index: u64, collection: CassList) -> Result<&mut Self, CassError> { unsafe { CassError::build( cass_statement_bind_collection(self.0,index,collection.0) ).wrap(self) } } pub fn bind_uuid(&mut self, index: u64, value: CassUuid) -> Result<&mut Self, CassError> { unsafe { CassError::build( cass_statement_bind_uuid(self.0,index, value.0) ).wrap(self) } } pub fn bind_inet(&mut self, index: u64, value: CassInet) -> Result<&mut Self, CassError> { unsafe { CassError::build( cass_statement_bind_inet(self.0,index, value.0) ).wrap(self) } } pub fn bind_user_type(&mut self, index: u64, value: CassUserType) -> Result<&mut Self, CassError> { unsafe { CassError::build( cass_statement_bind_user_type( self.0, index, value.0 ) ).wrap(self) } } // pub fn bind_decimal<'a>(&'a self, // index: cass_size_t, // value: String) // -> Result<&'a Self, CassError> { // unsafe { // CassError::build( // cass_statement_bind_decimal( // self.0, // index, // value // ) // ).wrap(&self) // } // } // pub fn bind_custom(&mut self, // index: u64, // size: u64, // output: *mut *mut u8) // -> Result<&mut Self, CassError> { // unsafe { // CassError::build( // cass_statement_bind_custom( // self.0, // index, // size, // output // ) // ).wrap(self) // } // } pub fn bind_int32_by_name(&mut self, name: &str, value: i32) -> Result<&mut Self, CassError> { unsafe { let name = CString::new(name).unwrap(); CassError::build( cass_statement_bind_int32_by_name( self.0, name.as_ptr(), value ) ).wrap(self) } } pub fn bind_int64_by_name(&mut self, name: &str, value: i64) -> Result<&mut Self, CassError> { unsafe { CassError::build( cass_statement_bind_int64_by_name( self.0, CString::new(name).unwrap().as_ptr(), value ) ).wrap(self) } } pub fn bind_float_by_name(&mut self, name: &str, value: f32) -> Result<&mut Self, CassError> { unsafe { let name = CString::new(name).unwrap(); CassError::build( cass_statement_bind_float_by_name( self.0,name.as_ptr(), value ) ).wrap(self) } } pub fn bind_double_by_name(&mut self, name: &str, value: f64) -> Result<&mut Self, CassError> { unsafe { let name = CString::new(name).unwrap(); CassError::build( cass_statement_bind_double_by_name( self.0, name.as_ptr(), value ) ).wrap(self) } } pub fn bind_bool_by_name(&mut self, name: &str, value: bool) -> Result<&mut Self, CassError> { unsafe { let name = CString::new(name).unwrap(); CassError::build( cass_statement_bind_bool_by_name( self.0, name.as_ptr(), if value {1} else {0} ) ).wrap(self) } } pub fn bind_string_by_name(&mut self, name: &str, value: &str) -> Result<&mut Self, CassError> { unsafe { let name = CString::new(name).unwrap(); let value = CString::new(value).unwrap(); let result = cass_statement_bind_string_by_name(self.0, name.as_ptr(), value.as_ptr()); CassError::build(result).wrap(self) } } pub fn bind_bytes_by_name(&mut self, name: &str, mut value: Vec<u8>) -> Result<&mut Self, CassError> { unsafe { let name = CString::new(name).unwrap(); let val = value.as_mut_ptr(); let result = cass_statement_bind_bytes_by_name(self.0, name.as_ptr(), val, value.len() as u64); CassError::build(result).wrap(self) } } pub fn bind_uuid_by_name(&mut self, name: &str, value: CassUuid) -> Result<&mut Self, CassError> { unsafe { let name = CString::new(name).unwrap(); CassError::build( cass_statement_bind_uuid_by_name( self.0, name.as_ptr(), value.0 ) ).wrap(self) } } pub fn bind_inet_by_name(&mut self, name: &str, value: CassInet) -> Result<&mut Self, CassError> { unsafe { let name = CString::new(name).unwrap(); CassError::build( cass_statement_bind_inet_by_name( self.0, name.as_ptr(), value.0 ) ).wrap(self) } } // pub fn bind_decimal_by_name<'a>(&'a self, // name: &str, // value: String) // -> Result<&'a Self, CassError> { // unsafe { // let name = CString::new(name).unwrap(); // CassError::build( // cass_statement_bind_decimal_by_name( // self.0, // name.as_ptr(), // value // ) // ).wrap(&self) // } // } // pub fn bind_custom_by_name(&mut self, // name: &str, // size: u64, // output: *mut *mut u8) // -> Result<&mut Self, CassError> { // unsafe { // let name = CString::new(name).unwrap(); // CassError::build( // cass_statement_bind_custom_by_name( // self.0, // name.as_ptr(), // size, output // ) // ).wrap(self) // } // } pub fn bind_set_by_name(&mut self, name: &str, collection: CassSet) -> Result<&mut Self, CassError> { unsafe { let name = CString::new(name).unwrap(); CassError::build( cass_statement_bind_collection_by_name( self.0, name.as_ptr(), collection.0 ) ).wrap(self) } } }
// Copyright 2020-2021, The Tremor Team // // 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 tremor_pipeline::{query::Query, FN_REGISTRY}; use crate::api::prelude::*; #[derive(Serialize)] struct PipelineWrap { pub query: String, instances: Vec<String>, } pub async fn list_artefact(req: Request) -> Result<Response> { let repo = &req.state().world.repo; let result: Vec<_> = repo .list_pipelines() .await? .iter() .filter_map(|v| v.artefact().map(String::from)) .collect(); reply(req, result, false, StatusCode::Ok).await } pub async fn publish_artefact(mut req: Request) -> Result<Response> { match content_type(&req) { Some(ResourceType::Trickle) => { let body = req.body_string().await?; let aggr_reg = tremor_script::registry::aggr(); let module_path = tremor_script::path::load(); let query = Query::parse( &module_path, &body, "<API>", vec![], &*FN_REGISTRY.lock()?, &aggr_reg, )?; let id = query.id().ok_or_else(|| { Error::new( StatusCode::UnprocessableEntity, r#"no `#!config id = "trickle-id"` directive provided"#.into(), ) })?; let url = build_url(&["pipeline", id])?; let repo = &req.state().world.repo; let result = repo .publish_pipeline(&url, false, query) .await .map(|result| result.source().to_string())?; reply_trickle_flat(req, result, true, StatusCode::Created).await } Some(_) | None => Err(Error::new( StatusCode::UnsupportedMediaType, "No content type provided".into(), )), } } pub async fn reply_trickle_flat( req: Request, result_in: String, persist: bool, ok_code: StatusCode, ) -> Result<Response> { if persist { let world = &req.state().world; world.save_config().await?; } match accept(&req) { ResourceType::Json | ResourceType::Yaml => serialize(accept(&req), &result_in, ok_code), ResourceType::Trickle => { let mut r = Response::new(ok_code); r.insert_header(headers::CONTENT_TYPE, ResourceType::Trickle.as_str()); r.set_body(result_in); Ok(r) } } } pub async fn reply_trickle_instanced( req: Request, mut result_in: String, instances: Vec<String>, persist: bool, ok_code: StatusCode, ) -> Result<Response> { if persist { let world = &req.state().world; world.save_config().await?; } match accept(&req) { ResourceType::Json | ResourceType::Yaml => serialize(accept(&req), &result_in, ok_code), ResourceType::Trickle => { let mut r = Response::new(ok_code); r.insert_header(headers::CONTENT_TYPE, ResourceType::Trickle.as_str()); let instances = instances.join("# * "); result_in.push_str("\n# Instances:\n# * "); result_in.push_str(&instances); r.set_body(result_in); Ok(r) } } } pub async fn unpublish_artefact(req: Request) -> Result<Response> { let id = req.param("aid").unwrap_or_default(); let url = build_url(&["pipeline", id])?; let repo = &req.state().world.repo; let result = repo .unpublish_pipeline(&url) .await .map(|result| result.source().to_string())?; reply_trickle_flat(req, result, true, StatusCode::Ok).await } pub async fn get_artefact(req: Request) -> Result<Response> { let id = req.param("aid").unwrap_or_default(); let url = build_url(&["pipeline", id])?; let repo = &req.state().world.repo; let result = repo .find_pipeline(&url) .await? .ok_or_else(Error::not_found)?; reply_trickle_instanced( req, result.artefact.source().to_string(), result .instances .iter() .filter_map(|v| v.instance().map(String::from)) .collect(), false, StatusCode::Ok, ) .await }
use ggez::graphics::{self, DrawMode, Drawable, Mesh, MeshBuilder}; use ggez::{Context, GameResult}; use nalgebra as na; #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] pub enum DrawableHandle { Circle, Box, } pub struct Assets { drawables: Vec<Box<Drawable>>, } impl Assets { pub fn new(ctx: &mut Context) -> GameResult<Assets> { let mut drawables = Vec::<Box<Drawable>>::with_capacity(DrawableHandle::Box as usize + 1); drawables.push(Box::new(Mesh::new_circle( ctx, DrawMode::Fill, na::Point2::origin(), 5.0, 0.1, )?)); drawables.push(Box::new(Mesh::new_polygon( ctx, DrawMode::Fill, &[ na::Point2::new(-5.0, -5.0), na::Point2::new(5.0, -5.0), na::Point2::new(5.0, 5.0), na::Point2::new(-5.0, 5.0), ], )?)); Ok(Assets { drawables }) } pub fn fetch_drawable(&self, handle: DrawableHandle) -> &Drawable { self.drawables[handle as usize].as_ref() } }
#![cfg(feature = "serde")] use debugid::{CodeId, DebugId}; use uuid::Uuid; #[test] fn test_deserialize_debugid() { assert_eq!( DebugId::from_parts( Uuid::parse_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75").unwrap(), 0, ), serde_json::from_str("\"dfb8e43a-f242-3d73-a453-aeb6a777ef75\"").unwrap(), ); } #[test] fn test_serialize_debugid() { let id = DebugId::from_parts( Uuid::parse_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75").unwrap(), 0, ); assert_eq!( "\"dfb8e43a-f242-3d73-a453-aeb6a777ef75\"", serde_json::to_string(&id).unwrap(), ); } #[test] fn test_deserialize_codeid() { assert_eq!( CodeId::new("dfb8e43af2423d73a453aeb6a777ef75".into()), serde_json::from_str("\"dfb8e43af2423d73a453aeb6a777ef75\"").unwrap(), ); } #[test] fn test_serialize_codeid() { assert_eq!( "\"dfb8e43af2423d73a453aeb6a777ef75\"", serde_json::to_string(&CodeId::new("dfb8e43af2423d73a453aeb6a777ef75".into())).unwrap(), ); }
use std::io::{self, Write}; use byteorder::{LittleEndian, BigEndian, WriteBytesExt}; use super::{Value, Tag, Vec2, Vec3, Vec4, Box2, Writer}; pub struct BinaryWriter<W> { output: W } fn get_type(value: &Value) -> u8 { match value { &Value::Bool(_) => 0x00, &Value::Int(_) => 0x01, &Value::Double(_) => 0x02, &Value::Vec2(_) => 0x03, &Value::Vec3(_) => 0x04, &Value::Vec4(_) => 0x05, &Value::Box2(_) => 0x06, &Value::String(_) => 0x07, &Value::Blob(_) => 0x08, &Value::Tag(_) => 0xee, &Value::BoolArray(_) => 0x80, &Value::IntArray(_) => 0x81, &Value::DoubleArray(_) => 0x82, &Value::Vec2Array(_) => 0x83, &Value::Vec3Array(_) => 0x84, &Value::Vec4Array(_) => 0x85, &Value::Box2Array(_) => 0x86, } } impl<W: Write> BinaryWriter<W> { pub fn new(output: W) -> BinaryWriter<W> { BinaryWriter { output: output } } pub fn into_inner(self) -> W { self.output } fn write_tag(&mut self, value: Tag) -> io::Result<()> { self.output.write_u32::<BigEndian>(value) } fn write_bool(&mut self, value: bool) -> io::Result<()> { self.output.write_all(&[ if value { 0x01 } else { 0x00 } ]) } fn write_uint(&mut self, value: u64) -> io::Result<()> { let mut buffer = Vec::with_capacity(10); let mut value = value; loop { let mut byte = (value & 0x7f) as u8; value >>= 7; if value != 0 { byte |= 0x80; } buffer.push(byte); if value == 0 { break; } } self.output.write_all(&buffer) } fn write_sint(&mut self, value: i64) -> io::Result<()> { self.write_uint(if value < 0 { !(value << 1) } else { value << 1 } as u64) } fn write_int(&mut self, value: i32) -> io::Result<()> { self.write_sint(value as i64) } fn write_double(&mut self, value: f64) -> io::Result<()> { self.output.write_f64::<LittleEndian>(value) } fn write_vec2(&mut self, value: Vec2) -> io::Result<()> { try!(self.write_double(value.0)); try!(self.write_double(value.1)); Ok(()) } fn write_vec3(&mut self, value: Vec3) -> io::Result<()> { try!(self.write_double(value.0)); try!(self.write_double(value.1)); try!(self.write_double(value.2)); Ok(()) } fn write_vec4(&mut self, value: Vec4) -> io::Result<()> { try!(self.write_double(value.0)); try!(self.write_double(value.1)); try!(self.write_double(value.2)); try!(self.write_double(value.3)); Ok(()) } fn write_box2(&mut self, value: Box2) -> io::Result<()> { try!(self.write_vec2(value.0)); try!(self.write_vec2(value.1)); Ok(()) } fn write_string(&mut self, value: &Box<str>) -> io::Result<()> { let bytes = value.as_bytes(); try!(self.write_uint(bytes.len() as u64)); self.output.write_all(bytes) } fn write_blob(&mut self, value: &Box<[u8]>) -> io::Result<()> { try!(self.write_uint(value.len() as u64)); self.output.write_all(value) } fn write_array<T, F>(&mut self, values: &Box<[T]>, f: F) -> io::Result<()> where F: Fn(&mut Self, T) -> io::Result<()>, T: Copy { try!(self.write_uint(values.len() as u64)); for &v in values.iter() { try!(f(self, v)); } Ok(()) } } impl<W: Write> Writer for BinaryWriter<W> { fn write_start(&mut self) -> io::Result<()> { self.output.write_all(&[0xfe]) } fn write_end(&mut self) -> io::Result<()> { self.output.write_all(&[0xef]) } fn write_value(&mut self, value: &Value) -> io::Result<()> { try!(self.output.write_all(&[get_type(value)])); match value { &Value::Bool(value) => self.write_bool(value), &Value::Int(value) => self.write_int(value), &Value::Double(value) => self.write_double(value), &Value::Vec2(value) => self.write_vec2(value), &Value::Vec3(value) => self.write_vec3(value), &Value::Vec4(value) => self.write_vec4(value), &Value::Box2(value) => self.write_box2(value), &Value::String(ref value) => self.write_string(value), &Value::Blob(ref value) => self.write_blob(value), &Value::Tag(value) => self.write_tag(value), &Value::BoolArray(ref values) => self.write_array(values, BinaryWriter::write_bool), &Value::IntArray(ref values) => self.write_array(values, BinaryWriter::write_int), &Value::DoubleArray(ref values) => self.write_array(values, BinaryWriter::write_double), &Value::Vec2Array(ref values) => self.write_array(values, BinaryWriter::write_vec2), &Value::Vec3Array(ref values) => self.write_array(values, BinaryWriter::write_vec3), &Value::Vec4Array(ref values) => self.write_array(values, BinaryWriter::write_vec4), &Value::Box2Array(ref values) => self.write_array(values, BinaryWriter::write_box2), } } } #[cfg(test)] mod tests { use super::*; use super::super::{Value, Writer}; use std::io::Cursor; #[test] fn write_simple() { let mut writer = BinaryWriter::new(Cursor::new(Vec::new())); writer.write_start().unwrap(); writer.write_end().unwrap(); assert_eq!(writer.output.into_inner(), vec![ 0xfe, 0xef ]); } #[test] fn write_simple_values() { let mut writer = BinaryWriter::new(Cursor::new(Vec::new())); writer.write_value(&Value::Bool(false)).unwrap(); writer.write_value(&Value::Bool(true)).unwrap(); writer.write_value(&Value::Int(0)).unwrap(); writer.write_value(&Value::Int(6)).unwrap(); writer.write_value(&Value::Int(128)).unwrap(); writer.write_value(&Value::Int(1000)).unwrap(); writer.write_value(&Value::Int(-310138)).unwrap(); writer.write_value(&Value::Double(67245.375)).unwrap(); writer.write_value(&Value::Vec2((67245.375, 3464.85))).unwrap(); writer.write_value(&Value::Vec3((67245.375, 3464.85, -8769.4565))).unwrap(); writer.write_value(&Value::Vec4((67245.375, 3464.85, -8769.4565, -1882.52))).unwrap(); writer.write_value(&Value::Box2(((67245.375, 3464.85), (-8769.4565, -1882.52)))).unwrap(); writer.write_value(&Value::Tag(tag!(S H A P))).unwrap(); assert_eq!(writer.output.into_inner(), vec![ 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x01, 0x0c, 0x01, 0x80, 0x02, 0x01, 0xd0, 0x0f, 0x01, 0xf3, 0xed, 0x25, 0x02, 0x00, 0x00, 0x00, 0x00, 0xd6, 0x6a, 0xf0, 0x40, 0x03, 0x00, 0x00, 0x00, 0x00, 0xd6, 0x6a, 0xf0, 0x40, 0x33, 0x33, 0x33, 0x33, 0xb3, 0x11, 0xab, 0x40, 0x04, 0x00, 0x00, 0x00, 0x00, 0xd6, 0x6a, 0xf0, 0x40, 0x33, 0x33, 0x33, 0x33, 0xb3, 0x11, 0xab, 0x40, 0x50, 0x8d, 0x97, 0x6e, 0xba, 0x20, 0xc1, 0xc0, 0x05, 0x00, 0x00, 0x00, 0x00, 0xd6, 0x6a, 0xf0, 0x40, 0x33, 0x33, 0x33, 0x33, 0xb3, 0x11, 0xab, 0x40, 0x50, 0x8d, 0x97, 0x6e, 0xba, 0x20, 0xc1, 0xc0, 0xae, 0x47, 0xe1, 0x7a, 0x14, 0x6a, 0x9d, 0xc0, 0x06, 0x00, 0x00, 0x00, 0x00, 0xd6, 0x6a, 0xf0, 0x40, 0x33, 0x33, 0x33, 0x33, 0xb3, 0x11, 0xab, 0x40, 0x50, 0x8d, 0x97, 0x6e, 0xba, 0x20, 0xc1, 0xc0, 0xae, 0x47, 0xe1, 0x7a, 0x14, 0x6a, 0x9d, 0xc0, 0xee, 0x53, 0x48, 0x41, 0x50, ]); } #[test] fn write_string() { let mut writer = BinaryWriter::new(Cursor::new(Vec::new())); writer.write_value(&Value::String("".to_string().into_boxed_str())).unwrap(); writer.write_value(&Value::String("Hello".to_string().into_boxed_str())).unwrap(); writer.write_value(&Value::String("Héllø".to_string().into_boxed_str())).unwrap(); writer.write_value(&Value::String( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, \ sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \ Ut enim ad minim veniam".to_string().into_boxed_str())).unwrap(); assert_eq!(writer.output.into_inner(), vec![ 0x07, 0x00, 0x07, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x07, 0x07, 0x48, 0xc3, 0xa9, 0x6c, 0x6c, 0xc3, 0xb8, 0x07, 0x93, 0x01, 0x4c, 0x6f, 0x72, 0x65, 0x6d, 0x20, 0x69, 0x70, 0x73, 0x75, 0x6d, 0x20, 0x64, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x73, 0x69, 0x74, 0x20, 0x61, 0x6d, 0x65, 0x74, 0x2c, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x63, 0x74, 0x65, 0x74, 0x75, 0x72, 0x20, 0x61, 0x64, 0x69, 0x70, 0x69, 0x73, 0x63, 0x69, 0x6e, 0x67, 0x20, 0x65, 0x6c, 0x69, 0x74, 0x2c, 0x20, 0x73, 0x65, 0x64, 0x20, 0x64, 0x6f, 0x20, 0x65, 0x69, 0x75, 0x73, 0x6d, 0x6f, 0x64, 0x20, 0x74, 0x65, 0x6d, 0x70, 0x6f, 0x72, 0x20, 0x69, 0x6e, 0x63, 0x69, 0x64, 0x69, 0x64, 0x75, 0x6e, 0x74, 0x20, 0x75, 0x74, 0x20, 0x6c, 0x61, 0x62, 0x6f, 0x72, 0x65, 0x20, 0x65, 0x74, 0x20, 0x64, 0x6f, 0x6c, 0x6f, 0x72, 0x65, 0x20, 0x6d, 0x61, 0x67, 0x6e, 0x61, 0x20, 0x61, 0x6c, 0x69, 0x71, 0x75, 0x61, 0x2e, 0x20, 0x55, 0x74, 0x20, 0x65, 0x6E, 0x69, 0x6D, 0x20, 0x61, 0x64, 0x20, 0x6D, 0x69, 0x6E, 0x69, 0x6D, 0x20, 0x76, 0x65, 0x6E, 0x69, 0x61, 0x6D, ]); } #[test] fn write_blob() { let mut writer = BinaryWriter::new(Cursor::new(Vec::new())); writer.write_value(&Value::Blob(vec![].into_boxed_slice())).unwrap(); writer.write_value(&Value::Blob(vec![0x48, 0x65, 0x6c, 0x6c, 0x6f].into_boxed_slice())).unwrap(); writer.write_value(&Value::Blob(vec![0x48, 0xc3, 0xa9, 0x6c, 0x6c, 0xc3, 0xb8].into_boxed_slice())).unwrap(); writer.write_value(&Value::Blob(vec![ 0x4c, 0x6f, 0x72, 0x65, 0x6d, 0x20, 0x69, 0x70, 0x73, 0x75, 0x6d, 0x20, 0x64, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x73, 0x69, 0x74, 0x20, 0x61, 0x6d, 0x65, 0x74, 0x2c, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x63, 0x74, 0x65, 0x74, 0x75, 0x72, 0x20, 0x61, 0x64, 0x69, 0x70, 0x69, 0x73, 0x63, 0x69, 0x6e, 0x67, 0x20, 0x65, 0x6c, 0x69, 0x74, 0x2c, 0x20, 0x73, 0x65, 0x64, 0x20, 0x64, 0x6f, 0x20, 0x65, 0x69, 0x75, 0x73, 0x6d, 0x6f, 0x64, 0x20, 0x74, 0x65, 0x6d, 0x70, 0x6f, 0x72, 0x20, 0x69, 0x6e, 0x63, 0x69, 0x64, 0x69, 0x64, 0x75, 0x6e, 0x74, 0x20, 0x75, 0x74, 0x20, 0x6c, 0x61, 0x62, 0x6f, 0x72, 0x65, 0x20, 0x65, 0x74, 0x20, 0x64, 0x6f, 0x6c, 0x6f, 0x72, 0x65, 0x20, 0x6d, 0x61, 0x67, 0x6e, 0x61, 0x20, 0x61, 0x6c, 0x69, 0x71, 0x75, 0x61, 0x2e, 0x20, 0x55, 0x74, 0x20, 0x65, 0x6e, 0x69, 0x6d, 0x20, 0x61, 0x64, 0x20, 0x6d, 0x69, 0x6e, 0x69, 0x6d, 0x20, 0x76, 0x65, 0x6e, 0x69, 0x61, 0x6d, ].into_boxed_slice())).unwrap(); assert_eq!(writer.output.into_inner(), vec![ 0x08, 0x00, 0x08, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x08, 0x07, 0x48, 0xc3, 0xa9, 0x6c, 0x6c, 0xc3, 0xb8, 0x08, 0x93, 0x01, 0x4c, 0x6f, 0x72, 0x65, 0x6d, 0x20, 0x69, 0x70, 0x73, 0x75, 0x6d, 0x20, 0x64, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x73, 0x69, 0x74, 0x20, 0x61, 0x6d, 0x65, 0x74, 0x2c, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x63, 0x74, 0x65, 0x74, 0x75, 0x72, 0x20, 0x61, 0x64, 0x69, 0x70, 0x69, 0x73, 0x63, 0x69, 0x6e, 0x67, 0x20, 0x65, 0x6c, 0x69, 0x74, 0x2c, 0x20, 0x73, 0x65, 0x64, 0x20, 0x64, 0x6f, 0x20, 0x65, 0x69, 0x75, 0x73, 0x6d, 0x6f, 0x64, 0x20, 0x74, 0x65, 0x6d, 0x70, 0x6f, 0x72, 0x20, 0x69, 0x6e, 0x63, 0x69, 0x64, 0x69, 0x64, 0x75, 0x6e, 0x74, 0x20, 0x75, 0x74, 0x20, 0x6c, 0x61, 0x62, 0x6f, 0x72, 0x65, 0x20, 0x65, 0x74, 0x20, 0x64, 0x6f, 0x6c, 0x6f, 0x72, 0x65, 0x20, 0x6d, 0x61, 0x67, 0x6e, 0x61, 0x20, 0x61, 0x6c, 0x69, 0x71, 0x75, 0x61, 0x2e, 0x20, 0x55, 0x74, 0x20, 0x65, 0x6e, 0x69, 0x6d, 0x20, 0x61, 0x64, 0x20, 0x6d, 0x69, 0x6e, 0x69, 0x6d, 0x20, 0x76, 0x65, 0x6e, 0x69, 0x61, 0x6d, ]); } #[test] fn write_arrays() { let mut writer = BinaryWriter::new(Cursor::new(Vec::new())); writer.write_value(&Value::BoolArray(vec![].into_boxed_slice())).unwrap(); writer.write_value(&Value::BoolArray(vec![ true, false, true ].into_boxed_slice())).unwrap(); writer.write_value(&Value::IntArray(vec![].into_boxed_slice())).unwrap(); writer.write_value(&Value::IntArray(vec![ 6, 128, 1000 ].into_boxed_slice())).unwrap(); writer.write_value(&Value::DoubleArray(vec![].into_boxed_slice())).unwrap(); writer.write_value(&Value::DoubleArray(vec![ 67245.375, 3464.85, -8769.4565 ].into_boxed_slice())).unwrap(); writer.write_value(&Value::Vec2Array(vec![].into_boxed_slice())).unwrap(); writer.write_value(&Value::Vec2Array(vec![ (67245.375, 3464.85), (-8769.4565, -1882.52) ].into_boxed_slice())).unwrap(); writer.write_value(&Value::Vec3Array(vec![].into_boxed_slice())).unwrap(); writer.write_value(&Value::Vec3Array(vec![ (67245.375, 3464.85, -8769.4565), (-1882.52, 67245.375, 3464.85), ].into_boxed_slice())).unwrap(); writer.write_value(&Value::Vec4Array(vec![].into_boxed_slice())).unwrap(); writer.write_value(&Value::Vec4Array(vec![ (67245.375, 3464.85, -8769.4565, -1882.52), (-1882.52, -8769.4565, 3464.85, 67245.375), ].into_boxed_slice())).unwrap(); writer.write_value(&Value::Box2Array(vec![].into_boxed_slice())).unwrap(); writer.write_value(&Value::Box2Array(vec![ ((67245.375, 3464.85), (-8769.4565, -1882.52)), ((-1882.52, -8769.4565), (3464.85, 67245.375)), ].into_boxed_slice())).unwrap(); assert_eq!(writer.output.into_inner(), vec![ 0x80, 0x00, 0x80, 0x03, 0x01, 0x00, 0x01, 0x81, 0x00, 0x81, 0x03, 0x0c, 0x80, 0x02, 0xd0, 0x0f, 0x82, 0x00, 0x82, 0x03, 0x00, 0x00, 0x00, 0x00, 0xd6, 0x6a, 0xf0, 0x40, 0x33, 0x33, 0x33, 0x33, 0xb3, 0x11, 0xab, 0x40, 0x50, 0x8d, 0x97, 0x6e, 0xba, 0x20, 0xc1, 0xc0, 0x83, 0x00, 0x83, 0x02, 0x00, 0x00, 0x00, 0x00, 0xd6, 0x6a, 0xf0, 0x40, 0x33, 0x33, 0x33, 0x33, 0xb3, 0x11, 0xab, 0x40, 0x50, 0x8d, 0x97, 0x6e, 0xba, 0x20, 0xc1, 0xc0, 0xae, 0x47, 0xe1, 0x7a, 0x14, 0x6a, 0x9d, 0xc0, 0x84, 0x00, 0x84, 0x02, 0x00, 0x00, 0x00, 0x00, 0xd6, 0x6a, 0xf0, 0x40, 0x33, 0x33, 0x33, 0x33, 0xb3, 0x11, 0xab, 0x40, 0x50, 0x8d, 0x97, 0x6e, 0xba, 0x20, 0xc1, 0xc0, 0xae, 0x47, 0xe1, 0x7a, 0x14, 0x6a, 0x9d, 0xc0, 0x00, 0x00, 0x00, 0x00, 0xd6, 0x6a, 0xf0, 0x40, 0x33, 0x33, 0x33, 0x33, 0xb3, 0x11, 0xab, 0x40, 0x85, 0x00, 0x85, 0x02, 0x00, 0x00, 0x00, 0x00, 0xd6, 0x6a, 0xf0, 0x40, 0x33, 0x33, 0x33, 0x33, 0xb3, 0x11, 0xab, 0x40, 0x50, 0x8d, 0x97, 0x6e, 0xba, 0x20, 0xc1, 0xc0, 0xae, 0x47, 0xe1, 0x7a, 0x14, 0x6a, 0x9d, 0xc0, 0xae, 0x47, 0xe1, 0x7a, 0x14, 0x6a, 0x9d, 0xc0, 0x50, 0x8d, 0x97, 0x6e, 0xba, 0x20, 0xc1, 0xc0, 0x33, 0x33, 0x33, 0x33, 0xb3, 0x11, 0xab, 0x40, 0x00, 0x00, 0x00, 0x00, 0xd6, 0x6a, 0xf0, 0x40, 0x86, 0x00, 0x86, 0x02, 0x00, 0x00, 0x00, 0x00, 0xd6, 0x6a, 0xf0, 0x40, 0x33, 0x33, 0x33, 0x33, 0xb3, 0x11, 0xab, 0x40, 0x50, 0x8d, 0x97, 0x6e, 0xba, 0x20, 0xc1, 0xc0, 0xae, 0x47, 0xe1, 0x7a, 0x14, 0x6a, 0x9d, 0xc0, 0xae, 0x47, 0xe1, 0x7a, 0x14, 0x6a, 0x9d, 0xc0, 0x50, 0x8d, 0x97, 0x6e, 0xba, 0x20, 0xc1, 0xc0, 0x33, 0x33, 0x33, 0x33, 0xb3, 0x11, 0xab, 0x40, 0x00, 0x00, 0x00, 0x00, 0xd6, 0x6a, 0xf0, 0x40, ]); } }
#[cfg(target_family = "windows")] use crate::platform::windows::RawTerminal; #[cfg(target_family = "unix")] use crate::platform::unix::RawTerminal; /// Enumarations of colors, maybe remove the `None` option and change the /// signature of some methods that use it to `Option<Color>` #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum Color { Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, DarkGray, Gray, Blue, Green, Cyan, Red, Magenta, Yellow, White, None } /// Representation of a handle to the current terminal, allows writting to it /// for the moment pub struct Terminal { raw_terminal: RawTerminal, } impl Terminal { /// Instantiates a new `Terminal` pub fn new() -> Self { Terminal { raw_terminal: RawTerminal::new() } } /// Writes to the console specifing the foreground and /// background colors pub fn write(&self, msg: &str, fg: Color, bg: Color) { // Call to the platfrom dependent underlying `RawTerminal` self.raw_terminal.write(msg, fg, bg); } /* For linux specific should be better to use low level tty, maybe the ansi * option should be implemented as a tooglable feature * #[cfg(target_family = "unix")] pub fn write(&self, msg: &str, fg: Color, bg: Color) { let fg_enum = match fg { Color::None => 39, Color::Black => 30, Color::DarkRed => 31, Color::DarkGreen => 32, Color::DarkYellow => 33, Color::DarkBlue => 34, Color::DarkMagenta => 35, Color::DarkCyan => 36, Color::Gray=> 37, Color::DarkGray => 91, Color::Red => 91, Color::Green => 92, Color::Yellow => 93, Color::Blue => 94, Color::Magenta => 95, Color::Cyan => 96, Color::White => 97 }; let bg_enum = match bg { Color::None => 49, Color::Black => 40, Color::DarkRed => 41, Color::DarkGreen => 42, Color::DarkYellow => 43, Color::DarkBlue => 44, Color::DarkMagenta => 45, Color::DarkCyan => 46, Color::Gray=> 47, Color::DarkGray => 101, Color::Red => 101, Color::Green => 102, Color::Yellow => 103, Color::Blue => 104, Color::Magenta => 105, Color::Cyan => 106, Color::White => 107 }; let io = std::io::stdout(); let mut handle = io.lock(); handle.write(format!("\x1b[{};{}m{}\x1b[0m", fg_enum, bg_enum, msg).as_bytes()).unwrap(); handle.flush().unwrap(); } */ /// Prints `msg` adding a line break at the end pub fn writeln(&self, msg: &str, fg: Color, bg: Color) { self.write(msg, fg, bg); // Faster than `println!` print!("\n"); } }
use crate::encrypt::encrypt::{encryption, string_count}; use crate::decrypt::decrypt::decrypt; use crate::msg::msg::{menu, input}; use crate::pgr::pgr::pgr_function; mod msg; mod encrypt; mod decrypt; mod pgr; fn main() { use std::io::{stdin,stdout,Write}; let mut text = "Ned Flanders"; let mut key = "Homer"; let mut option = 0; while (option < 4) { menu(); option = input().parse().unwrap(); if option == 1{ println!("The text is: {}",text); println!("The key is: {}",key); } if option == 2{ let text_bytes = text.as_bytes(); let cypher_text = encryption(text.parse().unwrap(), key.parse().unwrap(), text_bytes); println!("Encrypting text..."); println!("The Cyphertext is: {:?}",cypher_text); } if option == 3{ let text_bytes = text.as_bytes(); let cypher_text = encryption(text.parse().unwrap(), key.parse().unwrap(), text_bytes); let diference = string_count(text.parse().unwrap()) - string_count(key.parse().unwrap()); let key_string = pgr_function(key.parse().unwrap(), text.parse().unwrap(), diference); let decrypt_text = decrypt(&*cypher_text, &*key_string); let text = String::from_utf8_lossy(&*decrypt_text); println!("The Decrypt Text is: {}", text); } } }
use std::io; use std::sync::{Mutex, Arc}; use std::io::{TcpListener, TcpStream, Listener, Acceptor}; use std::io::net::tcp::TcpAcceptor; use std::comm::{Receiver, Sender, channel}; struct Server { #[allow(dead_code)] game: GameWorld, port: u16, acceptor: TcpAcceptor, players: Arc<Mutex<Vec<PlayerHandle>>> } struct PlayerHandle { channel: Sender<()>, } #[deriving(Clone, Send)] struct GameWorld; enum Command { Look, } impl Server { fn new(host: &str, port: u16) -> io::IoResult<Server> { let a : TcpAcceptor = try!(TcpListener::bind((host, port)).unwrap().listen()); let game = GameWorld::new(); let players = Arc::new(Mutex::new(Vec::new())); let server = Server { acceptor: a.clone(), game: game.clone(), port: port, players: players.clone(), }; spawn(proc() { let mut a2 = a.clone(); for socket in a2.incoming() { match socket { Ok(s) => { let game_clone = game.clone(); let (snd, rec) = channel::<()>(); spawn(proc() {game_clone.handle(s, rec)}); players.clone().lock().push(PlayerHandle {channel: snd}); }, Err(ref e) if e.kind == io::IoErrorKind::EndOfFile => break, Err(e) => panic!( "unexpected error accepting connection: {}", e), } } }); Ok(server) } #[cfg(test)] fn new_test_server() -> Server { use std::rand::random; for _ in range(0u, 100) { match Server::new("127.0.0.1", random()) { Ok(s) => { return s }, Err(_) => (), // try again! } } panic!("Unable to bind to a port for the test server!"); } fn close(&mut self) { let _ = self.acceptor.close_accept(); let players = self.players.lock(); for player in players.iter() { let _ = player.channel.send_opt(()); } } } impl Drop for Server { fn drop(&mut self) { self.close(); println!("Dropped server"); } } impl GameWorld { pub fn new() -> GameWorld { GameWorld // lol } pub fn handle(&self, mut socket : TcpStream, close_rc: Receiver<()>) { let line_rc : Receiver<String> = GameWorld::get_lines(socket.clone()); socket.write(b">> ").unwrap(); loop { select! { ln = line_rc.recv_opt() => { let line = match ln { Ok(l) => l, Err(_) => return, // connection closed by user }; let response = match self.parse(line) { Some(Command::Look) => "You are in a dark and spooky cave. You are likely to be eaten by a grue.\n", None => "I have no idea what you just said there chief.\n" }; socket.write(response.as_bytes()).unwrap(); socket.write(b">> ").unwrap(); }, () = close_rc.recv() => { let _ = socket.write(b"\n\nServer is going down hard.\n"); let _ = socket.close_read(); let _ = socket.close_write(); return; } } } } pub fn get_lines<R: Reader + Send>(reader: R) -> Receiver<String> { let (snd, rcv) = channel(); spawn(proc() { for line in io::BufferedReader::new(reader).lines() { let line = match line { Ok(l) => l, Err(_) => { continue; } }; snd.send(line); } }); rcv } pub fn parse(&self, s : String) -> Option<Command> { println!("{}", s); match s.as_slice().trim() { "l" | "look" => Some(Command::Look), _ => None } } } #[test] fn test_connect_and_disconnect() { let server = Server::new_test_server(); let mut stream = TcpStream::connect(("127.0.0.1", server.port)); stream.write(b"look\n").unwrap(); let mut reader = io::BufferedReader::new(stream); let line = reader.read_line().unwrap(); assert_eq!(">> You are in a dark and spooky cave. You are likely to be eaten by a grue.\n", line); } #[cfg(not(test))] fn main() { let mut s = Server::new("127.0.0.1", 8482).unwrap(); // Now that our accept loop is running, wait for the program to be // requested to exit. println!("Listening on port {}", s.port); println!("Admin shell:"); print!(">> "); for line in io::BufferedReader::new(io::stdio::stdin()).lines() { if let Ok(line) = line { if line.trim() == "exit" { s.close(); break; } } print!(">> "); } }
extern crate reqwest; extern crate reventsource; fn main() -> Result<(), Box<dyn std::error::Error>> { let client = reqwest::Client::builder() .proxy(reqwest::Proxy::https("http://127.0.0.1:7777")?) .timeout(None) .build()?; let resp = client .get("https://hacker-news.firebaseio.com/v0/updates.json?print=pretty") .header(reqwest::header::ACCEPT, "text/event-stream") .send()?; println!("{:#?}", resp); let c = reventsource::new(resp); for result in c { let event = result?; println!("Event:\n{}", event); } Ok(()) }
/// `match` for parsers /// /// When parsers have unique prefixes to test for, this offers better performance over /// [`alt`][crate::combinator::alt] though it might be at the cost of duplicating parts of your grammar /// if you needed to [`peek`][crate::combinator::peek]. /// /// For tight control over the error in a catch-all case, use [`fail`][crate::combinator::fail]. /// /// # Example /// /// ```rust /// use winnow::prelude::*; /// use winnow::combinator::dispatch; /// # use winnow::token::any; /// # use winnow::combinator::peek; /// # use winnow::combinator::preceded; /// # use winnow::combinator::success; /// # use winnow::combinator::fail; /// /// fn escaped(input: &mut &str) -> PResult<char> { /// preceded('\\', escape_seq_char).parse_next(input) /// } /// /// fn escape_seq_char(input: &mut &str) -> PResult<char> { /// dispatch! {any; /// 'b' => success('\u{8}'), /// 'f' => success('\u{c}'), /// 'n' => success('\n'), /// 'r' => success('\r'), /// 't' => success('\t'), /// '\\' => success('\\'), /// '"' => success('"'), /// _ => fail::<_, char, _>, /// } /// .parse_next(input) /// } /// /// assert_eq!(escaped.parse_peek("\\nHello"), Ok(("Hello", '\n'))); /// ``` #[macro_export] macro_rules! dispatch { ($match_parser: expr; $( $pat:pat $(if $pred:expr)? => $expr: expr ),+ $(,)? ) => { $crate::trace::trace("dispatch", move |i: &mut _| { use $crate::Parser; let initial = $match_parser.parse_next(i)?; match initial { $( $pat $(if $pred)? => $expr.parse_next(i), )* } }) } } macro_rules! succ ( (0, $submac:ident ! ($($rest:tt)*)) => ($submac!(1, $($rest)*)); (1, $submac:ident ! ($($rest:tt)*)) => ($submac!(2, $($rest)*)); (2, $submac:ident ! ($($rest:tt)*)) => ($submac!(3, $($rest)*)); (3, $submac:ident ! ($($rest:tt)*)) => ($submac!(4, $($rest)*)); (4, $submac:ident ! ($($rest:tt)*)) => ($submac!(5, $($rest)*)); (5, $submac:ident ! ($($rest:tt)*)) => ($submac!(6, $($rest)*)); (6, $submac:ident ! ($($rest:tt)*)) => ($submac!(7, $($rest)*)); (7, $submac:ident ! ($($rest:tt)*)) => ($submac!(8, $($rest)*)); (8, $submac:ident ! ($($rest:tt)*)) => ($submac!(9, $($rest)*)); (9, $submac:ident ! ($($rest:tt)*)) => ($submac!(10, $($rest)*)); (10, $submac:ident ! ($($rest:tt)*)) => ($submac!(11, $($rest)*)); (11, $submac:ident ! ($($rest:tt)*)) => ($submac!(12, $($rest)*)); (12, $submac:ident ! ($($rest:tt)*)) => ($submac!(13, $($rest)*)); (13, $submac:ident ! ($($rest:tt)*)) => ($submac!(14, $($rest)*)); (14, $submac:ident ! ($($rest:tt)*)) => ($submac!(15, $($rest)*)); (15, $submac:ident ! ($($rest:tt)*)) => ($submac!(16, $($rest)*)); (16, $submac:ident ! ($($rest:tt)*)) => ($submac!(17, $($rest)*)); (17, $submac:ident ! ($($rest:tt)*)) => ($submac!(18, $($rest)*)); (18, $submac:ident ! ($($rest:tt)*)) => ($submac!(19, $($rest)*)); (19, $submac:ident ! ($($rest:tt)*)) => ($submac!(20, $($rest)*)); (20, $submac:ident ! ($($rest:tt)*)) => ($submac!(21, $($rest)*)); );
fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let r1: usize = rd.get(); let c1: usize = rd.get(); let r2: usize = rd.get(); let c2: usize = rd.get(); let mo = 1_000_000_000 + 7; let binom = Binom::new(r2 + c2 + 2, mo); let g = |r: usize, c: usize| { (0..=r) .map(|i| binom.get(i + c + 1, c)) .fold(0, |acc, x| (acc + x) % mo) }; let ans = g(r2, c2) - g(r1 - 1, c2) - g(r2, c1 - 1) + g(r1 - 1, c1 - 1); println!("{}", ans.rem_euclid(mo)); } use std::fmt::Debug; use std::str::FromStr; pub struct ProconReader<R> { r: R, line: String, i: usize, } impl<R: std::io::BufRead> ProconReader<R> { pub fn new(reader: R) -> Self { Self { r: reader, line: String::new(), i: 0, } } pub fn get<T>(&mut self) -> T where T: FromStr, <T as FromStr>::Err: Debug, { self.skip_blanks(); assert!(self.i < self.line.len()); assert_ne!(&self.line[self.i..=self.i], " "); let line = &self.line[self.i..]; let end = line.find(' ').unwrap_or_else(|| line.len()); let s = &line[..end]; self.i += end; s.parse() .unwrap_or_else(|_| panic!("parse error `{}`", self.line)) } fn skip_blanks(&mut self) { loop { let start = self.line[self.i..].find(|ch| ch != ' '); match start { Some(j) => { self.i += j; break; } None => { self.line.clear(); self.i = 0; let num_bytes = self.r.read_line(&mut self.line).unwrap(); assert!(num_bytes > 0, "reached EOF :("); self.line = self.line.trim_end_matches(&['\r', '\n'][..]).to_string(); } } } } pub fn get_vec<T>(&mut self, n: usize) -> Vec<T> where T: FromStr, <T as FromStr>::Err: Debug, { (0..n).map(|_| self.get()).collect() } } pub trait BinomialCoefficient { type Output; fn get(&self, n: usize, k: usize) -> Self::Output; } pub struct Binom { size: usize, mo: i64, fac: Vec<i64>, inv_fac: Vec<i64>, } impl Binom { pub fn new(size: usize, mo: i64) -> Self { let mut fac = vec![0; size]; let mut inv = vec![0; size]; let mut inv_fac = vec![0; size]; fac[0] = 1; fac[1] = 1; inv[1] = 1; inv_fac[0] = 1; inv_fac[1] = 1; for i in 2..size { fac[i] = fac[i - 1] * (i as i64) % mo; inv[i] = (-inv[(mo as usize) % i] * (mo / (i as i64))).rem_euclid(mo); inv_fac[i] = inv_fac[i - 1] * inv[i] % mo; } Self { size, mo, fac, inv_fac, } } } impl BinomialCoefficient for Binom { type Output = i64; fn get(&self, n: usize, k: usize) -> Self::Output { assert!(n < self.size); if n < k { return 0; } ((self.fac[n] * self.inv_fac[k]) % self.mo * self.inv_fac[n - k]) % self.mo } }
extern crate matrix; use matrix::prelude::*; use std::vec::Vec; // Finds an optimal binary search tree by dynamic programming // Input: An array p[1..n] of search probabilities for a sorted list of n keys // Output: Average number of comparisons in successful searches in the // optimal BST and table r of subtrees' roots in the optimal BST fn optimal_bst(p: &Vec<f64>) -> (f64, Compressed<usize>) { let n = p.len(); let mut c = Compressed::<f64>::zero((n + 2, n + 1)); let mut r = Compressed::<usize>::zero((n + 2, n + 1)); for i in 1..(n + 1) { c.set((i, i - 1), 0.0); c.set((i, i), p[i - 1]); r.set((i, i), i); } c.set((n + 1, n), 0.0); // diagonal count for d in 1..n { for i in 1..(n - d + 1) { let j = i + d; let mut minval = f64::INFINITY; let mut kmin = 0; for k in i..(j + 1) { let c_sum = c.get((i, k - 1)) + c.get((k + 1, j)); if c_sum < minval { minval = c_sum; kmin = k; } } r.set((i, j), kmin); let mut sum = p[i - 1]; for s in (i + 1)..(j + 1) { sum = sum + p[s - 1]; } c.set((i, j), minval + sum); } } (c.get((1, n)), r) } fn main() { // use example search probabilities from book let p: Vec::<f64> = vec![0.1, 0.2, 0.4, 0.3]; let opt = optimal_bst(&p); println!("Average number of comparisons in successful searches: {}", opt.0); println!("Root table:"); for i in 1..opt.1.rows() { for j in 0..opt.1.columns() { print!("\t{}", opt.1.get((i, j))); } print!("\n"); } }
//! Ffi-safe wrapper types around the //! [crossbeam-channel](https://crates.io/crates/crossbeam-channel/) //! channel types. #![allow(clippy::missing_const_for_fn)] use std::{ fmt::{self, Debug}, marker::PhantomData, time::Duration, }; use crossbeam_channel::{ Receiver, RecvError, RecvTimeoutError, SendError, SendTimeoutError, Sender, TryRecvError, TrySendError, }; use core_extensions::SelfOps; use crate::{ marker_type::UnsafeIgnoredType, pointer_trait::AsPtr, prefix_type::WithMetadata, sabi_types::RRef, std_types::{RBox, RDuration, RErr, ROk, ROption, RResult}, traits::{ErasedType, IntoReprRust}, }; mod errors; mod extern_fns; mod iteration; #[cfg(all(test, not(feature = "test_miri_track_raw")))] mod tests; use self::errors::{ RRecvError, RRecvTimeoutError, RSendError, RSendTimeoutError, RTryRecvError, RTrySendError, }; pub use self::iteration::{RIntoIter, RIter}; /////////////////////////////////////////////////////////////////////////////// /// Creates a receiver that can never receive any value. /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// let rx = mpmc::never::<()>(); /// /// assert_eq!(rx.try_recv().ok(), None); /// /// ``` pub fn never<T>() -> RReceiver<T> { crossbeam_channel::never::<T>().into() } /// Creates a channel which can hold up to `capacity` elements in its internal queue. /// /// If `capacity==0`,the value must be sent to a receiver in the middle of a `recv` call. /// /// # Panics /// /// Panics if `capacity >= usize::max_value() / 4`. /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// let (tx, rx) = mpmc::bounded::<u32>(3); /// /// std::thread::spawn(move || { /// tx.send(10).unwrap(); /// tx.send(11).unwrap(); /// tx.send(12).unwrap(); /// }); /// /// assert_eq!(rx.recv().unwrap(), 10); /// assert_eq!(rx.recv().unwrap(), 11); /// assert_eq!(rx.recv().unwrap(), 12); /// assert!(rx.try_recv().is_err()); /// /// ``` /// pub fn bounded<T>(capacity: usize) -> (RSender<T>, RReceiver<T>) { let (tx, rx) = crossbeam_channel::bounded::<T>(capacity); (tx.into(), rx.into()) } /// Creates a channel which can hold an unbounded amount elements in its internal queue. /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// let (tx, rx) = mpmc::unbounded::<&'static str>(); /// /// let join_guard = std::thread::spawn(move || { /// assert_eq!(rx.recv().unwrap(), "foo"); /// assert_eq!(rx.recv().unwrap(), "bar"); /// assert_eq!(rx.recv().unwrap(), "baz"); /// assert!(rx.try_recv().is_err()); /// }); /// /// tx.send("foo").unwrap(); /// tx.send("bar").unwrap(); /// tx.send("baz").unwrap(); /// /// join_guard.join().unwrap(); /// /// ``` /// /// pub fn unbounded<T>() -> (RSender<T>, RReceiver<T>) { let (tx, rx) = crossbeam_channel::unbounded::<T>(); (tx.into(), rx.into()) } /////////////////////////////////////////////////////////////////////////////// /// The sender end of a channel, /// which can be either bounded or unbounded. /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// let (tx, rx) = mpmc::bounded::<&'static str>(1024); /// /// std::thread::spawn(move || { /// for _ in 0..4 { /// tx.send("Are we there yet.").unwrap(); /// } /// }); /// /// assert_eq!(rx.recv().unwrap(), "Are we there yet."); /// assert_eq!(rx.recv().unwrap(), "Are we there yet."); /// assert_eq!(rx.recv().unwrap(), "Are we there yet."); /// assert_eq!(rx.recv().unwrap(), "Are we there yet."); /// assert!(rx.recv().is_err()); /// /// /// ``` /// /// #[repr(C)] #[derive(StableAbi)] pub struct RSender<T> { channel: RBox<ErasedSender<T>>, vtable: VTable_Ref<T>, } impl<T> RSender<T> { fn vtable(&self) -> VTable_Ref<T> { self.vtable } /// Blocks until `value` is either sent,or the the other end is disconnected. /// /// If the channel queue is full,this will block to send `value`. /// /// If the channel is disconnected,this will return an error with `value`. /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// let (tx, rx) = mpmc::bounded::<u32>(3); /// /// tx.send(1057).unwrap(); /// /// drop(rx); /// assert!(tx.send(0).is_err()); /// /// ``` /// pub fn send(&self, value: T) -> Result<(), SendError<T>> { let vtable = self.vtable(); vtable.send()(self.channel.as_rref(), value).piped(result_from) } /// Immediately sends `value`,or returns with an error. /// /// An error will be returned in these 2 conditions: /// /// - the channel is full. /// /// - the channel has been disconnected. /// /// If the channel has a capacity of 0,it will only send `value` if /// the other end is calling `recv`. /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// let (tx, rx) = mpmc::bounded::<bool>(1); /// /// tx.try_send(true).unwrap(); /// assert!(tx.try_send(true).unwrap_err().is_full()); /// /// drop(rx); /// assert!(tx.try_send(false).unwrap_err().is_disconnected()); /// /// ``` /// /// pub fn try_send(&self, value: T) -> Result<(), TrySendError<T>> { let vtable = self.vtable(); vtable.try_send()(self.channel.as_rref(), value).piped(result_from) } /// Blocks until a timeout to send `value`. /// /// An error will be returned in these 2 conditions: /// /// - the value could not be sent before the timeout. /// /// - the channel has been disconnected. /// /// If the channel has a capacity of 0,it will only send `value` if /// the other end calls `recv` before the timeout. /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// use std::time::Duration; /// /// let (tx, rx) = mpmc::bounded::<()>(1); /// /// let timeout = Duration::from_millis(1); /// /// tx.send_timeout((), timeout).unwrap(); /// assert!(tx.send_timeout((), timeout).unwrap_err().is_timeout()); /// /// drop(rx); /// assert!(tx.send_timeout((), timeout).unwrap_err().is_disconnected()); /// /// ``` /// pub fn send_timeout(&self, value: T, timeout: Duration) -> Result<(), SendTimeoutError<T>> { let vtable = self.vtable(); vtable.send_timeout()(self.channel.as_rref(), value, timeout.into()).piped(result_from) } /// Returns true if there are no values in the channel queue. /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// let (tx, rx) = mpmc::bounded::<()>(1); /// /// assert!(tx.is_empty()); /// /// tx.send(()).unwrap(); /// assert!(!tx.is_empty()); /// /// rx.recv().unwrap(); /// assert!(tx.is_empty()); /// ``` pub fn is_empty(&self) -> bool { let vtable = self.vtable(); vtable.sender_is_empty()(self.channel.as_rref()) } /// Returns true if the channel queue is full. /// /// This always returns true for channels constructed with `bounded(0)`. /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// let (tx, rx) = mpmc::bounded::<()>(2); /// /// assert!(!tx.is_full()); /// /// tx.send(()).unwrap(); /// assert!(!tx.is_full()); /// /// tx.send(()).unwrap(); /// assert!(tx.is_full()); /// /// rx.recv().unwrap(); /// assert!(!tx.is_full()); /// ``` pub fn is_full(&self) -> bool { let vtable = self.vtable(); vtable.sender_is_full()(self.channel.as_rref()) } /// Returns the amount of values in the channel queue. /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// let (tx, rx) = mpmc::bounded::<()>(2); /// /// assert_eq!(tx.len(), 0); /// /// tx.send(()).unwrap(); /// assert_eq!(tx.len(), 1); /// /// tx.send(()).unwrap(); /// assert_eq!(tx.len(), 2); /// /// rx.recv().unwrap(); /// assert_eq!(tx.len(), 1); /// /// ``` pub fn len(&self) -> usize { let vtable = self.vtable(); vtable.sender_len()(self.channel.as_rref()) } /// Returns the amount of values the channel queue can hold. /// /// This returns None if the channel is unbounded. /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// { /// let (tx, rx) = mpmc::bounded::<()>(2); /// assert_eq!(tx.capacity(), Some(2)); /// } /// { /// let (tx, rx) = mpmc::unbounded::<()>(); /// assert_eq!(tx.capacity(), None); /// } /// /// ``` pub fn capacity(&self) -> Option<usize> { let vtable = self.vtable(); vtable.sender_capacity()(self.channel.as_rref()).into_rust() } } impl<T> Clone for RSender<T> { /// Clones this channel end,getting another handle into the channel. /// /// Note that this allocates an RBox<_>. fn clone(&self) -> Self { let vtable = self.vtable(); Self { channel: vtable.clone_sender()(self.channel.as_rref()), vtable: self.vtable, } } } impl<T> Debug for RSender<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Debug::fmt("RSender{..}", f) } } unsafe impl<T: Send> Sync for RSender<T> {} unsafe impl<T: Send> Send for RSender<T> {} impl_from_rust_repr! { impl[T] From<Sender<T>> for RSender<T> { fn(this){ Self{ channel:ErasedSender::from_unerased_value(this), vtable: MakeVTable::<T>::VTABLE, } } } } /////////////////////////////////////////////////////////////////////////////// /// The receiver end of a channel, /// which can be either bounded or unbounded. /// /// # Examples /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// let (tx, rx) = mpmc::unbounded::<&'static str>(); /// /// let join_guard = std::thread::spawn(move || { /// assert_eq!(rx.recv().unwrap(), "PING"); /// assert_eq!(rx.recv().unwrap(), "PING"); /// assert_eq!(rx.recv().unwrap(), "PING"); /// assert_eq!(rx.recv().unwrap(), "PING"); /// assert!(rx.try_recv().unwrap_err().is_empty()); /// }); /// /// for _ in 0..4 { /// tx.send("PING").unwrap(); /// } /// /// join_guard.join().unwrap(); /// /// assert!(tx.send("").is_err()); /// /// ``` /// #[repr(C)] #[derive(StableAbi)] pub struct RReceiver<T> { channel: RBox<ErasedReceiver<T>>, vtable: VTable_Ref<T>, } impl<T> RReceiver<T> { fn vtable(&self) -> VTable_Ref<T> { self.vtable } /// Blocks until a value is either received,or the the other end is disconnected. /// /// If the channel queue is empty,this will block to receive a value. /// /// This will return an error if the channel is disconnected. /// /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// let (tx, rx) = mpmc::bounded::<&'static str>(3); /// /// tx.send("J__e H____y").unwrap(); /// assert_eq!(rx.recv().unwrap(), "J__e H____y"); /// /// drop(tx); /// assert!(rx.recv().is_err()); /// /// ``` /// pub fn recv(&self) -> Result<T, RecvError> { let vtable = self.vtable(); vtable.recv()(self.channel.as_rref()).piped(result_from) } /// Immediately receives a value,or returns with an error. /// /// An error will be returned in these 2 conditions: /// /// - the channel is empty. /// /// - the channel has been disconnected. /// /// If the channel has a capacity of 0,it will only receive a value if /// the other end is calling `send`. /// /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// let (tx, rx) = mpmc::bounded::<&'static str>(3); /// /// assert!(rx.try_recv().is_err()); /// /// tx.send("D__e S_____r").unwrap(); /// assert_eq!(rx.try_recv().unwrap(), "D__e S_____r"); /// /// drop(tx); /// assert!(rx.try_recv().is_err()); /// /// ``` pub fn try_recv(&self) -> Result<T, TryRecvError> { let vtable = self.vtable(); vtable.try_recv()(self.channel.as_rref()).piped(result_from) } /// Blocks until a timeout to receive a value. /// /// An error will be returned in these 2 conditions: /// /// - A value could not be received before the timeout. /// /// - the channel has been disconnected. /// /// If the channel has a capacity of 0,it will only receive a value if /// the other end calls `send` before the timeout. /// /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// use std::time::Duration; /// /// let (tx, rx) = mpmc::bounded::<&'static str>(3); /// /// let timeout = Duration::from_millis(1); /// /// assert!(rx.recv_timeout(timeout).unwrap_err().is_timeout()); /// /// tx.send("D__e S_____r").unwrap(); /// assert_eq!(rx.recv_timeout(timeout).unwrap(), "D__e S_____r"); /// /// drop(tx); /// assert!(rx.recv_timeout(timeout).unwrap_err().is_disconnected()); /// /// ``` /// pub fn recv_timeout(&self, timeout: Duration) -> Result<T, RecvTimeoutError> { let vtable = self.vtable(); vtable.recv_timeout()(self.channel.as_rref(), timeout.into()).piped(result_from) } /// Returns true if there are no values in the channel queue. /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// let (tx, rx) = mpmc::bounded::<()>(1); /// /// assert!(rx.is_empty()); /// /// tx.send(()).unwrap(); /// assert!(!rx.is_empty()); /// /// rx.recv().unwrap(); /// assert!(rx.is_empty()); /// ``` pub fn is_empty(&self) -> bool { let vtable = self.vtable(); vtable.receiver_is_empty()(self.channel.as_rref()) } /// Returns true if the channel queue is full. /// /// This always returns true for channels constructed with `bounded(0)`. /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// let (tx, rx) = mpmc::bounded::<()>(2); /// /// assert!(!rx.is_full()); /// /// tx.send(()).unwrap(); /// assert!(!rx.is_full()); /// /// tx.send(()).unwrap(); /// assert!(rx.is_full()); /// /// rx.recv().unwrap(); /// assert!(!rx.is_full()); /// ``` pub fn is_full(&self) -> bool { let vtable = self.vtable(); vtable.receiver_is_full()(self.channel.as_rref()) } /// Returns the amount of values in the channel queue. /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// let (tx, rx) = mpmc::bounded::<()>(2); /// /// assert_eq!(rx.len(), 0); /// /// tx.send(()).unwrap(); /// assert_eq!(rx.len(), 1); /// /// tx.send(()).unwrap(); /// assert_eq!(rx.len(), 2); /// /// rx.recv().unwrap(); /// assert_eq!(rx.len(), 1); /// /// ``` pub fn len(&self) -> usize { let vtable = self.vtable(); vtable.receiver_len()(self.channel.as_rref()) } /// Returns the amount of values the channel queue can hold. /// /// This returns None if the channel is unbounded. /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// { /// let (tx, rx) = mpmc::bounded::<()>(2); /// assert_eq!(rx.capacity(), Some(2)); /// } /// { /// let (tx, rx) = mpmc::unbounded::<()>(); /// assert_eq!(rx.capacity(), None); /// } /// /// ``` pub fn capacity(&self) -> Option<usize> { let vtable = self.vtable(); vtable.receiver_capacity()(self.channel.as_rref()).into_rust() } /// Creates an Iterator that receives values from the channel. /// /// # Example /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// use std::thread; /// /// let (tx, rx) = mpmc::bounded::<usize>(1); /// /// thread::spawn(move || { /// for i in 0..1000 { /// tx.send(i).unwrap(); /// } /// }); /// /// for (i, n) in rx.iter().enumerate() { /// assert_eq!(i, n); /// } /// /// ``` pub fn iter(&self) -> RIter<'_, T> { RIter { channel: self } } } impl<'a, T> IntoIterator for &'a RReceiver<T> { type Item = T; type IntoIter = RIter<'a, T>; /// Creates an Iterator that receives values from the channel. #[inline] fn into_iter(self) -> RIter<'a, T> { self.iter() } } impl<T> IntoIterator for RReceiver<T> { type Item = T; type IntoIter = RIntoIter<T>; /// Creates an Iterator that receives values from the channel. #[inline] fn into_iter(self) -> RIntoIter<T> { RIntoIter { channel: self } } } impl<T> Clone for RReceiver<T> { /// Clones this channel end,getting another handle into the channel. /// /// Note that this allocates an RBox<_>. fn clone(&self) -> Self { let vtable = self.vtable(); Self { channel: vtable.clone_receiver()(self.channel.as_rref()), vtable: self.vtable, } } } impl<T> Debug for RReceiver<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Debug::fmt("RReceiver{..}", f) } } unsafe impl<T: Send> Sync for RReceiver<T> {} unsafe impl<T: Send> Send for RReceiver<T> {} impl_from_rust_repr! { impl[T] From<Receiver<T>> for RReceiver<T> { fn(this){ Self{ channel:ErasedReceiver::from_unerased_value(this), vtable:MakeVTable::<T>::VTABLE, } } } } /////////////////////////////////////////////////////////////////////////////// #[inline] fn result_from<T, E0, E1>(res: RResult<T, E0>) -> Result<T, E1> where E0: Into<E1>, { match res { ROk(x) => Ok(x), RErr(e) => Err(e.into()), } } #[repr(C)] #[derive(StableAbi)] struct ErasedSender<T>(PhantomData<T>, UnsafeIgnoredType<Sender<T>>); impl<T> ErasedType<'_> for ErasedSender<T> { type Unerased = Sender<T>; } #[repr(C)] #[derive(StableAbi)] struct ErasedReceiver<T>(PhantomData<T>, UnsafeIgnoredType<Receiver<T>>); impl<T> ErasedType<'_> for ErasedReceiver<T> { type Unerased = Receiver<T>; } /////////////////////////////////////////////////////////////////////////////// #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix))] #[sabi(missing_field(panic))] //#[sabi(debug_print)] struct VTable<T> { send: extern "C" fn(this: RRef<'_, ErasedSender<T>>, T) -> RResult<(), RSendError<T>>, try_send: extern "C" fn(this: RRef<'_, ErasedSender<T>>, T) -> RResult<(), RTrySendError<T>>, send_timeout: extern "C" fn( this: RRef<'_, ErasedSender<T>>, value: T, timeout: RDuration, ) -> RResult<(), RSendTimeoutError<T>>, clone_sender: extern "C" fn(this: RRef<'_, ErasedSender<T>>) -> RBox<ErasedSender<T>>, sender_is_empty: extern "C" fn(this: RRef<'_, ErasedSender<T>>) -> bool, sender_is_full: extern "C" fn(this: RRef<'_, ErasedSender<T>>) -> bool, sender_len: extern "C" fn(this: RRef<'_, ErasedSender<T>>) -> usize, sender_capacity: extern "C" fn(this: RRef<'_, ErasedSender<T>>) -> ROption<usize>, recv: extern "C" fn(this: RRef<'_, ErasedReceiver<T>>) -> RResult<T, RRecvError>, try_recv: extern "C" fn(this: RRef<'_, ErasedReceiver<T>>) -> RResult<T, RTryRecvError>, recv_timeout: extern "C" fn( this: RRef<'_, ErasedReceiver<T>>, timeout: RDuration, ) -> RResult<T, RRecvTimeoutError>, clone_receiver: extern "C" fn(this: RRef<'_, ErasedReceiver<T>>) -> RBox<ErasedReceiver<T>>, receiver_is_empty: extern "C" fn(this: RRef<'_, ErasedReceiver<T>>) -> bool, receiver_is_full: extern "C" fn(this: RRef<'_, ErasedReceiver<T>>) -> bool, receiver_len: extern "C" fn(this: RRef<'_, ErasedReceiver<T>>) -> usize, #[sabi(last_prefix_field)] receiver_capacity: extern "C" fn(this: RRef<'_, ErasedReceiver<T>>) -> ROption<usize>, } struct MakeVTable<'a, T>(&'a T); impl<'a, T: 'a> MakeVTable<'a, T> { const VALUE: VTable<T> = VTable { send: ErasedSender::send, try_send: ErasedSender::try_send, send_timeout: ErasedSender::send_timeout, clone_sender: ErasedSender::clone, sender_is_empty: ErasedSender::is_empty, sender_is_full: ErasedSender::is_full, sender_len: ErasedSender::len, sender_capacity: ErasedSender::capacity, recv: ErasedReceiver::recv, try_recv: ErasedReceiver::try_recv, recv_timeout: ErasedReceiver::recv_timeout, clone_receiver: ErasedReceiver::clone, receiver_is_empty: ErasedReceiver::is_empty, receiver_is_full: ErasedReceiver::is_full, receiver_len: ErasedReceiver::len, receiver_capacity: ErasedReceiver::capacity, }; staticref! { const WM_VALUE: WithMetadata<VTable<T>> = WithMetadata::new(Self::VALUE) } // The VTABLE for this type in this executable/library const VTABLE: VTable_Ref<T> = VTable_Ref(Self::WM_VALUE.as_prefix()); }
// 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 crate::context::Context; use crate::decoded::Decoded; use crate::error::Error; use crate::result::Result; use crate::variant::Variant; use crate::version::Version; use base64::{engine::general_purpose, Engine as _}; /// Structure containing the options. struct Options { mem_cost: u32, time_cost: u32, parallelism: u32, } /// Gets the base64 encoded length of a byte slice with the specified length. pub fn base64_len(length: u32) -> u32 { let olen = (length / 3) << 2; match length % 3 { 2 => olen + 3, 1 => olen + 2, _ => olen, } } /// Attempts to decode the encoded string slice. pub fn decode_string(encoded: &str) -> Result<Decoded> { let items: Vec<&str> = encoded.split('$').collect(); if items.len() == 6 { decode_empty(items[0])?; let variant = decode_variant(items[1])?; let version = decode_version(items[2])?; let options = decode_options(items[3])?; let salt = general_purpose::STANDARD_NO_PAD.decode(items[4])?; let hash = general_purpose::STANDARD_NO_PAD.decode(items[5])?; Ok(Decoded { variant, version, mem_cost: options.mem_cost, time_cost: options.time_cost, parallelism: options.parallelism, salt, hash, }) } else if items.len() == 5 { decode_empty(items[0])?; let variant = decode_variant(items[1])?; let options = decode_options(items[2])?; let salt = general_purpose::STANDARD_NO_PAD.decode(items[3])?; let hash = general_purpose::STANDARD_NO_PAD.decode(items[4])?; Ok(Decoded { variant, version: Version::Version10, mem_cost: options.mem_cost, time_cost: options.time_cost, parallelism: options.parallelism, salt, hash, }) } else { Err(Error::DecodingFail) } } fn decode_empty(str: &str) -> Result<()> { if str == "" { Ok(()) } else { Err(Error::DecodingFail) } } fn decode_options(str: &str) -> Result<Options> { let items: Vec<&str> = str.split(',').collect(); if items.len() == 3 { Ok(Options { mem_cost: decode_option(items[0], "m")?, time_cost: decode_option(items[1], "t")?, parallelism: decode_option(items[2], "p")?, }) } else { Err(Error::DecodingFail) } } fn decode_option(str: &str, name: &str) -> Result<u32> { let items: Vec<&str> = str.split('=').collect(); if items.len() == 2 { if items[0] == name { decode_u32(items[1]) } else { Err(Error::DecodingFail) } } else { Err(Error::DecodingFail) } } fn decode_u32(str: &str) -> Result<u32> { match str.parse() { Ok(i) => Ok(i), Err(_) => Err(Error::DecodingFail), } } fn decode_variant(str: &str) -> Result<Variant> { Variant::from_str(str) } fn decode_version(str: &str) -> Result<Version> { let items: Vec<&str> = str.split('=').collect(); if items.len() == 2 { if items[0] == "v" { Version::from_str(items[1]) } else { Err(Error::DecodingFail) } } else { Err(Error::DecodingFail) } } /// Encodes the hash and context. pub fn encode_string(context: &Context, hash: &[u8]) -> String { format!( "${}$v={}$m={},t={},p={}${}${}", context.config.variant, context.config.version, context.config.mem_cost, context.config.time_cost, context.config.lanes, general_purpose::STANDARD_NO_PAD.encode(context.salt), general_purpose::STANDARD_NO_PAD.encode(hash), ) } /// Gets the string length of the specified number. pub fn num_len(number: u32) -> u32 { let mut len = 1; let mut num = number; while num >= 10 { len += 1; num /= 10; } len } #[cfg(test)] mod tests { use crate::config::Config; use crate::context::Context; use crate::decoded::Decoded; use crate::encoding::{base64_len, decode_string, encode_string, num_len}; use crate::error::Error; use crate::variant::Variant; use crate::version::Version; #[test] fn base64_len_returns_correct_length() { let tests = vec![ (1, 2), (2, 3), (3, 4), (4, 6), (5, 7), (6, 8), (7, 10), (8, 11), (9, 12), (10, 14), ]; for (len, expected) in tests { let actual = base64_len(len); assert_eq!(actual, expected); } } #[test] fn decode_string_with_version10_returns_correct_result() { let encoded = "$argon2i$v=16$m=4096,t=3,p=1\ $c2FsdDEyMzQ$MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI"; let expected = Decoded { variant: Variant::Argon2i, version: Version::Version10, mem_cost: 4096, time_cost: 3, parallelism: 1, salt: b"salt1234".to_vec(), hash: b"12345678901234567890123456789012".to_vec(), }; let actual = decode_string(encoded).unwrap(); assert_eq!(actual, expected); } #[test] fn decode_string_with_version13_returns_correct_result() { let encoded = "$argon2i$v=19$m=4096,t=3,p=1\ $c2FsdDEyMzQ$MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI"; let expected = Decoded { variant: Variant::Argon2i, version: Version::Version13, mem_cost: 4096, time_cost: 3, parallelism: 1, salt: b"salt1234".to_vec(), hash: b"12345678901234567890123456789012".to_vec(), }; let actual = decode_string(encoded).unwrap(); assert_eq!(actual, expected); } #[test] fn decode_string_without_version_returns_correct_result() { let encoded = "$argon2i$m=4096,t=3,p=1\ $c2FsdDEyMzQ$MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI"; let expected = Decoded { variant: Variant::Argon2i, version: Version::Version10, mem_cost: 4096, time_cost: 3, parallelism: 1, salt: b"salt1234".to_vec(), hash: b"12345678901234567890123456789012".to_vec(), }; let actual = decode_string(encoded).unwrap(); assert_eq!(actual, expected); } #[test] fn decode_string_without_variant_returns_error_result() { let encoded = "$m=4096,t=3,p=1\ $c2FsdDEyMzQ=$MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; let result = decode_string(encoded); assert_eq!(result, Err(Error::DecodingFail)); } #[test] fn decode_string_with_empty_variant_returns_error_result() { let encoded = "$$m=4096,t=3,p=1\ $c2FsdDEyMzQ=$MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; let result = decode_string(encoded); assert_eq!(result, Err(Error::DecodingFail)); } #[test] fn decode_string_with_invalid_variant_returns_error_result() { let encoded = "$argon$m=4096,t=3,p=1\ $c2FsdDEyMzQ=$MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; let result = decode_string(encoded); assert_eq!(result, Err(Error::DecodingFail)); } #[test] fn decode_string_without_mem_cost_returns_error_result() { let encoded = "$argon2i$t=3,p=1\ $c2FsdDEyMzQ=$MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; let result = decode_string(encoded); assert_eq!(result, Err(Error::DecodingFail)); } #[test] fn decode_string_with_empty_mem_cost_returns_error_result() { let encoded = "$argon2i$m=,t=3,p=1\ $c2FsdDEyMzQ=$MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; let result = decode_string(encoded); assert_eq!(result, Err(Error::DecodingFail)); } #[test] fn decode_string_with_non_numeric_mem_cost_returns_error_result() { let encoded = "$argon2i$m=a,t=3,p=1\ $c2FsdDEyMzQ=$MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; let result = decode_string(encoded); assert_eq!(result, Err(Error::DecodingFail)); } #[test] fn decode_string_without_time_cost_returns_error_result() { let encoded = "$argon2i$m=4096,p=1\ $c2FsdDEyMzQ=$MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; let result = decode_string(encoded); assert_eq!(result, Err(Error::DecodingFail)); } #[test] fn decode_string_with_empty_time_cost_returns_error_result() { let encoded = "$argon2i$m=4096,t=,p=1\ $c2FsdDEyMzQ=$MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; let result = decode_string(encoded); assert_eq!(result, Err(Error::DecodingFail)); } #[test] fn decode_string_with_non_numeric_time_cost_returns_error_result() { let encoded = "$argon2i$m=4096,t=a,p=1\ $c2FsdDEyMzQ=$MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; let result = decode_string(encoded); assert_eq!(result, Err(Error::DecodingFail)); } #[test] fn decode_string_without_parallelism_returns_error_result() { let encoded = "$argon2i$m=4096,t=3\ $c2FsdDEyMzQ=$MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; let result = decode_string(encoded); assert_eq!(result, Err(Error::DecodingFail)); } #[test] fn decode_string_with_empty_parallelism_returns_error_result() { let encoded = "$argon2i$m=4096,t=3,p=\ $c2FsdDEyMzQ=$MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; let result = decode_string(encoded); assert_eq!(result, Err(Error::DecodingFail)); } #[test] fn decode_string_with_non_numeric_parallelism_returns_error_result() { let encoded = "$argon2i$m=4096,t=3,p=a\ $c2FsdDEyMzQ=$MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; let result = decode_string(encoded); assert_eq!(result, Err(Error::DecodingFail)); } #[test] fn decode_string_without_salt_returns_error_result() { let encoded = "$argon2i$m=4096,t=3,p=1\ $MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; let result = decode_string(encoded); assert_eq!(result, Err(Error::DecodingFail)); } #[test] fn decode_string_without_hash_returns_error_result() { let encoded = "$argon2i$m=4096,t=3,p=a\ $c2FsdDEyMzQ="; let result = decode_string(encoded); assert_eq!(result, Err(Error::DecodingFail)); } #[test] fn decode_string_with_empty_hash_returns_error_result() { let encoded = "$argon2i$m=4096,t=3,p=a\ $c2FsdDEyMzQ=$"; let result = decode_string(encoded); assert_eq!(result, Err(Error::DecodingFail)); } #[test] fn encode_string_returns_correct_string() { let hash = b"12345678901234567890123456789012".to_vec(); let config = Config { ad: &[], hash_length: hash.len() as u32, lanes: 1, mem_cost: 4096, secret: &[], time_cost: 3, variant: Variant::Argon2i, version: Version::Version13, }; let pwd = b"password".to_vec(); let salt = b"salt1234".to_vec(); let context = Context::new(config, &pwd, &salt).unwrap(); let expected = "$argon2i$v=19$m=4096,t=3,p=1\ $c2FsdDEyMzQ$MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI"; let actual = encode_string(&context, &hash); assert_eq!(actual, expected); } #[test] fn num_len_returns_correct_length() { let tests = vec![ (1, 1), (10, 2), (110, 3), (1230, 4), (12340, 5), (123457, 6), ]; for (num, expected) in tests { let actual = num_len(num); assert_eq!(actual, expected); } } }
use crate::utils::*; use tokio::prelude::*; const N_LENGTH_BYTES: usize = 4; const LENGTH_LIMIT: usize = 100_000; pub async fn framed_read<T: serde::de::DeserializeOwned>(stream: &mut (impl AsyncRead + Unpin)) -> Result<T> { let mut length_bytes = [0; N_LENGTH_BYTES]; stream.read_exact(&mut length_bytes).await?; let length: u32 = bincode::deserialize(&length_bytes)?; let length = length as usize; if length > LENGTH_LIMIT { return Err(format!("reading: messages cannot be longer than {} bytes", LENGTH_LIMIT).into()); } let mut buffer = vec![0; length]; if length > 0 { stream.read_exact(&mut buffer).await.ann_err("reading message")?; } Ok(bincode::deserialize(&buffer).ann_err("deserializing message")?) } pub async fn framed_write<T: serde::Serialize>(stream: &mut (impl AsyncWrite + Unpin), msg: &T) -> R { let msg = bincode::serialize(msg).ann_err("serializing message")?; if msg.len() > LENGTH_LIMIT { return Err(format!("writing: messages cannot be longer than {} bytes", LENGTH_LIMIT).into()); } let length: u32 = msg.len() as u32; stream .write_all(&bincode::serialize(&length).ann_err("serializing message")?) .await .ann_err("writing length")?; if length > 0 { stream.write_all(&msg).await.ann_err("writing message")?; } Ok(()) }
mod event; mod exchange; mod orderbook; mod types; mod utils; mod server; mod protocol; mod messages; use std::sync::Arc; use tokio::sync::Mutex; use crate::exchange::*; use crate::server::Server; extern crate log; #[tokio::main] async fn main() { let symbols = "GOOG,MSFT"; let symbols_vec: Vec<String> = symbols.split(',').map(|s| s.to_string()).collect(); // Create the exchange. let exch = Exchange::new(Some(symbols_vec)); let result = Server{ exchange: Arc::new(Mutex::new(exch)) }.start().await; match result { Ok(()) => (), Err(e) => eprintln!("error: {}", e), } }
use crate::consts; use crate::error::{Error, ErrorCode, Result}; use crate::read; use serde::de; use std::io; use serde::forward_to_deserialize_any; pub fn from_reader<'de, R, T>(read: R) -> Result<T> where R: io::Read, T: de::DeserializeOwned, { let read = read::IoRead::new(read); let mut de = Deserializer::new(read); T::deserialize(&mut de) } pub struct Deserializer<R> { read: R, } impl<'de, R> Deserializer<R> where R: read::Read<'de>, { pub fn new(read: R) -> Self { Deserializer { read } } pub fn into_inner(self) -> R { self.read } } #[inline] fn invalid_bool_byte() -> Error { Error::syntax(ErrorCode::InvalidBoolByte, 0) } impl<'de, 'a, R> de::Deserializer<'de> for &'a mut Deserializer<R> where R: read::Read<'de>, { type Error = Error; #[inline] fn deserialize_any<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { match self.read.peek_u8()? { Some(consts::TYPE_ID_BYTE) => self.deserialize_i8(visitor), _ => unimplemented!(), } } fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { match self.read.read_byte_inner()? { 1 => visitor.visit_bool(true), 0 => visitor.visit_bool(false), _ => Err(invalid_bool_byte()), } } fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { visitor.visit_i8(self.read.read_byte_inner()?) } forward_to_deserialize_any! { i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum identifier ignored_any } }
use std::slice; use super::events::StockMoveEvent; pub type ItemCode = String; pub type LocationCode = String; pub type Quantity = u32; pub trait Event<S> { type Output; fn apply_to(&self, state: S) -> Self::Output; } pub trait Restore<E> { fn restore(self, events: slice::Iter<E>) -> Self; } #[allow(dead_code)] #[derive(Debug, Clone)] pub enum Stock { Unmanaged { item: ItemCode, location: LocationCode }, Managed { item: ItemCode, location: LocationCode, qty: Quantity, assigned: Quantity }, } #[allow(dead_code)] impl Stock { pub fn managed_new(item: ItemCode, location: LocationCode) -> Self { Self::Managed { item, location, qty: 0, assigned: 0 } } pub fn unmanaged_new(item: ItemCode, location: LocationCode) -> Self { Self::Unmanaged { item, location } } pub fn eq_id(&self, item: &ItemCode, location: &LocationCode) -> bool { match self { Self::Managed { item: it, location: loc, .. } | Self::Unmanaged { item: it, location: loc } => it == item && loc == location } } pub fn is_sufficient(&self, v: Quantity) -> bool { match self { Self::Managed { qty, assigned, .. } => v + assigned <= *qty, Self::Unmanaged { .. } => true, } } fn update(&self, qty: Quantity, assigned: Quantity) -> Self { match self { Self::Managed { item, location, .. } => { Self::Managed { item: item.clone(), location: location.clone(), qty, assigned, } }, Self::Unmanaged { .. } => self.clone(), } } fn update_qty(&self, qty: Quantity) -> Self { match self { Self::Managed { assigned, .. } => self.update(qty, *assigned), Self::Unmanaged { .. } => self.clone(), } } fn update_assigned(&self, assigned: Quantity) -> Self { match self { Self::Managed { qty, .. } => self.update(*qty, assigned), Self::Unmanaged { .. } => self.clone(), } } } #[derive(Debug, Default, Clone, PartialEq)] pub struct StockMoveInfo { item: ItemCode, qty: Quantity, from: LocationCode, to: LocationCode, } #[allow(dead_code)] #[derive(Debug, Clone, PartialEq)] pub enum StockMove { Nothing, Draft { info: StockMoveInfo }, Completed { info: StockMoveInfo, outgoing: Quantity, incoming: Quantity }, Cancelled { info: StockMoveInfo }, Assigned { info: StockMoveInfo, assigned: Quantity }, Shipped { info: StockMoveInfo, outgoing: Quantity }, Arrived { info: StockMoveInfo, outgoing: Quantity, incoming: Quantity }, AssignFailed { info: StockMoveInfo }, ShipmentFailed { info: StockMoveInfo }, } type MoveEvent = StockMoveEvent<ItemCode, LocationCode, Quantity>; type MoveResult = Option<(StockMove, MoveEvent)>; #[allow(dead_code)] impl StockMove { pub fn initial_state() -> Self { Self::Nothing } pub fn start(&self, item: ItemCode, qty: Quantity, from: LocationCode, to: LocationCode) -> MoveResult { if qty < 1 { return None } let event = StockMoveEvent::Started { item: item.clone(), qty: qty, from: from.clone(), to: to.clone() }; self.apply_event(event) } pub fn complete(&self) -> MoveResult { self.apply_event(StockMoveEvent::Completed) } pub fn cancel(&self) -> MoveResult { self.apply_event(StockMoveEvent::Cancelled) } pub fn assign(&self, stock: &Stock) -> MoveResult { if let Some(info) = self.info() { if stock.eq_id(&info.item, &info.from) { let assigned = if stock.is_sufficient(info.qty) { info.qty } else { 0 }; return self.apply_event( StockMoveEvent::Assigned { item: info.item.clone(), from: info.from.clone(), assigned, } ) } } None } pub fn ship(&self, outgoing: Quantity) -> MoveResult { let ev = match self { Self::Assigned { info, assigned } => { Some(StockMoveEvent::AssignShipped { item: info.item.clone(), from: info.from.clone(), outgoing, assigned: assigned.clone(), }) }, _ => { self.info() .map(|i| StockMoveEvent::Shipped { item: i.item.clone(), from: i.from.clone(), outgoing, } ) }, }; ev.and_then(|e| self.apply_event(e)) } pub fn arrive(&self, incoming: Quantity) -> MoveResult { self.info() .and_then(|i| self.apply_event(StockMoveEvent::Arrived { item: i.item.clone(), to: i.to.clone(), incoming, }) ) } fn info(&self) -> Option<StockMoveInfo> { match self { Self::Draft { info } | Self::Completed { info, .. } | Self::Cancelled { info } | Self::Assigned { info, .. } | Self::AssignFailed { info, .. } | Self::Shipped { info, .. } | Self::ShipmentFailed { info } | Self::Arrived { info, .. } => { Some(info.clone()) }, Self::Nothing => None, } } fn apply_event(&self, event: MoveEvent) -> MoveResult { let new_state = event.apply_to(self.clone()); Some((new_state, event)) .filter(|r| r.0 != *self) } } impl Event<StockMove> for MoveEvent { type Output = StockMove; fn apply_to(&self, state: StockMove) -> Self::Output { match self { Self::Started { item, qty, from, to } => { if state == StockMove::Nothing { StockMove::Draft { info: StockMoveInfo { item: item.clone(), qty: qty.clone(), from: from.clone(), to: to.clone(), } } } else { state } }, Self::Completed => { if let StockMove::Arrived { info, outgoing, incoming } = state { StockMove::Completed { info: info.clone(), outgoing, incoming } } else { state } }, Self::Cancelled => { if let StockMove::Draft { info } = state { StockMove::Cancelled { info: info.clone() } } else { state } }, Self::Assigned { item, from, assigned } => { match state { StockMove::Draft { info } if info.item == *item && info.from == *from => { if *assigned > 0 { StockMove::Assigned { info: info.clone(), assigned: assigned.clone(), } } else { StockMove::AssignFailed { info: info.clone() } } }, _ => state, } }, Self::Shipped { item, from, outgoing } => { match state { StockMove::Draft { info } if info.item == *item && info.from == *from => { if *outgoing > 0 { StockMove::Shipped { info: info.clone(), outgoing: outgoing.clone(), } } else { StockMove::ShipmentFailed { info: info.clone() } } }, _ => state, } }, Self::AssignShipped { item, from, outgoing, .. } => { match state { StockMove::Assigned { info, .. } if info.item == *item && info.from == *from => { if *outgoing > 0 { StockMove::Shipped { info: info.clone(), outgoing: outgoing.clone(), } } else { StockMove::ShipmentFailed { info: info.clone() } } }, _ => state, } }, Self::Arrived { item, to, incoming } => { match state { StockMove::Draft { info } if info.item == *item && info.to == *to => { StockMove::Arrived { info: info.clone(), outgoing: 0, incoming: *incoming, } }, StockMove::Shipped { info, outgoing } if info.item == *item && info.to == *to => { StockMove::Arrived { info: info.clone(), outgoing, incoming: *incoming, } }, _ => state, } }, } } } impl Event<Stock> for MoveEvent { type Output = Stock; fn apply_to(&self, state: Stock) -> Self::Output { match &state { Stock::Unmanaged { .. } => state, Stock::Managed { item: s_item, location: s_loc, qty: s_qty, assigned: s_assigned } => { match self { Self::Assigned { item, from, assigned } if s_item == item && s_loc == from => { state.update_assigned( s_assigned + assigned ) }, Self::Shipped { item, from, outgoing } if s_item == item && s_loc == from => { state.update_qty( s_qty.checked_sub(*outgoing).unwrap_or(0) ) }, Self::AssignShipped { item, from, outgoing, assigned } if s_item == item && s_loc == from => { state.update( s_qty.checked_sub(*outgoing).unwrap_or(0), s_assigned.checked_sub(*assigned).unwrap_or(0), ) }, Self::Arrived { item, to, incoming } if s_item == item && s_loc == to => { state.update_qty( s_qty + incoming ) }, _ => state, } }, } } } impl<S, E> Restore<&E> for S where Self: Clone, E: Event<Self, Output = Self>, { fn restore(self, events: slice::Iter<&E>) -> Self { events.fold(self, |acc, ev| ev.apply_to(acc.clone())) } }
//! Coverage maps as static mut array use crate::EDGES_MAP_SIZE; /// The map for edges. pub static mut EDGES_MAP: [u8; EDGES_MAP_SIZE] = [0; EDGES_MAP_SIZE]; /// The max count of edges tracked. pub static mut MAX_EDGES_NUM: usize = 0;
//! System Applets. //! //! Applets are small integrated programs that the OS makes available to the developer to streamline commonly needed functionality. //! Thanks to these integrations the developer can avoid wasting time re-implementing common features and instead use a more reliable base for their application. //! //! Unlike [services](crate::services), applets aren't accessed via a system subprocess (which would require obtaining a special handle at runtime). //! Instead, the application builds a configuration storing the various parameters which is then used to "launch" the applet. //! //! Applets block execution of the thread that launches them as long as the user doesn't close the applet. pub mod mii_selector; pub mod swkbd;
//! The module keeping track of the state of the game. use crate::error::GameError; use game_loop::{Renderer, Updater}; /// The state of the game. #[derive(Debug, Default)] pub(crate) struct GameState { updates: usize, renders: usize, } impl Updater for GameState { type Error = GameError; fn update(&mut self) -> Result<(), Self::Error> { self.updates += 1; Ok(()) } } impl Renderer for GameState { type Error = GameError; fn render(&mut self, _remainder: f32) -> Result<(), Self::Error> { self.renders += 1; Ok(()) } }
// Copyright 2019 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. use failure::Error; use serde_json::{from_value, to_value, Value}; use crate::setui::types::{JsonMutation, LoginOverrideMode, SetUiResult}; use fidl_fuchsia_setui::*; use fuchsia_component::client::connect_to_service; /// Facade providing access to SetUi interfaces. #[derive(Debug)] pub struct SetUiFacade { setui_svc: SetUiServiceProxy, } impl SetUiFacade { pub fn new() -> Result<SetUiFacade, Error> { let setui_svc = connect_to_service::<SetUiServiceMarker>().expect("Failed to connect to SetUi"); Ok(SetUiFacade { setui_svc }) } /// Sets the value of a given settings object. Returns once operation has completed. pub async fn mutate(&self, args: Value) -> Result<Value, Error> { let json_mutation: JsonMutation = from_value(args)?; print!("{:?}", json_mutation); let mut mutation: Mutation; let setting_type: SettingType; match json_mutation { JsonMutation::Account { operation: _, login_override } => { // TODO(isma): Is there a way to just use the fidl enum? let login_override: LoginOverride = match login_override { LoginOverrideMode::None => LoginOverride::None, LoginOverrideMode::AutologinGuest => LoginOverride::AutologinGuest, LoginOverrideMode::AuthProvider => LoginOverride::AuthProvider, }; mutation = Mutation::AccountMutationValue(AccountMutation { operation: Some(AccountOperation::SetLoginOverride), login_override: Some(login_override), }); setting_type = SettingType::Account; } } match self.setui_svc.mutate(setting_type, &mut mutation).await?.return_code { ReturnCode::Ok => Ok(to_value(SetUiResult::Success)?), ReturnCode::Failed => bail!("Update settings failed"), ReturnCode::Unsupported => bail!("Update settings unsupported"), } } }
// Copyright 2019-2020 PolkaX. Licensed under MIT or Apache-2.0. use serde_cbor::Value; use super::{Amt, Item, Node, BITS_PER_SUBKEY, WIDTH}; use crate::blocks::Blocks; use crate::error::*; impl<B> Amt<B> where B: Blocks, { /// this function would use in anywhere to traverse the trie, do not need flush first. pub fn for_each<F>(&self, f: &mut F) -> Result<()> where F: FnMut(u64, &Value) -> Result<()>, { traversing(&self.bs, &self.root, self.height, 0, f) } /// Subtract removes all elements of 'or' from 'self' pub fn subtract(&mut self, or: Self) -> Result<()> { or.for_each(&mut |key, _| { // if not find, do not handle error match self.delete(key) { Ok(_) | Err(AmtIpldError::NotFound(_)) => Ok(()), Err(e) => Err(e), } }) } } fn traversing<B, F>(bs: &B, node: &Node, height: u64, prefix_key: u64, f: &mut F) -> Result<()> where B: Blocks, F: FnMut(u64, &Value) -> Result<()>, { let prefix = prefix_key << BITS_PER_SUBKEY; if height == 0 { for i in 0..WIDTH { if node.get_bit(i) { let current_key = prefix + i as u64; let index = node.bit_to_index(i); f(current_key, &node.leafs[index])?; } } return Ok(()); } let mut branches = node.branches.borrow_mut(); for i in 0..WIDTH { if node.get_bit(i) { let current_key = prefix + i as u64; let index = node.bit_to_index(i); branches[index].load_item(bs)?; if let Item::Ptr(node) = &branches[index] { traversing(bs, node, height - 1, current_key, f)?; } else { unreachable!("after `load_item`, Item must be `Ptr`") } } } Ok(()) } impl<B> Amt<B> where B: Blocks, { /// `iter()` is equal to `for_each` now(could use before `flush()`). /// but `iter()` would cast more resource pub fn iter(&self) -> Iter<B> { let node_ref = &self.root; let prefix_key_list = (0..WIDTH) .map(|prefix_key| (prefix_key, node_ref.get_bit(prefix_key))) .filter(|(_, need)| *need) .map(|(pref, _)| pref as u64) .collect::<Vec<_>>(); let init_node = &self.root as *const Node; let init = if self.height == 0 { Traversing::Leaf(0, (prefix_key_list, init_node)) } else { Traversing::Branch(prefix_key_list, init_node) }; Iter { size: self.count, count: 0, stack: vec![init], bs: &self.bs, } } } /// this `Iter` only could be used for FlushedRoot, due to current module use child_cache to store child, /// and the child ref is under `RefCell`. So that we could only iterate the tree after flushing. /// if someone do not what iterating the free after flushing, could use `for_each`. pub struct Iter<'a, B> where B: Blocks, { size: u64, count: u64, stack: Vec<Traversing>, // blocks ref, use for load node from cid bs: &'a B, } enum Traversing { Leaf(usize, (Vec<u64>, *const Node)), Branch(Vec<u64>, *const Node), } impl<'a, B> Iterator for Iter<'a, B> where B: Blocks, { type Item = (u64, &'a Value); /// it's safe to use unsafe here, for except root node, every node is in heap, /// and be refered from root node. thus we use unsafe to avoid lifetime check /// and mutable check. /// notice iterator would load node for cid, thus after iter, all tree is in /// `Ptr` mode, in other word, is being expanded fn next(&mut self) -> Option<Self::Item> { let last = match self.stack.pop() { Some(last) => last, None => { return None; } }; match last { Traversing::Leaf(pos, (keys, leaf_node)) => { let r = unsafe { (*leaf_node).leafs.get(pos).map(|v| (keys[pos], v)) }; match r { Some(v) => { let pos = pos + 1; self.stack.push(Traversing::Leaf(pos, (keys, leaf_node))); self.count += 1; Some(v) } None => self.next(), } } Traversing::Branch(keys, node_ref) => { unsafe { let node = &(*node_ref); let mut children = vec![]; for (b, key) in node.branches.borrow_mut().iter_mut().zip(keys.into_iter()) { b.load_item(self.bs).ok()?; if let Item::Ptr(child_node) = b { let prefix_key_list = (0..WIDTH) .map(|prefix_key| (prefix_key, child_node.get_bit(prefix_key))) .filter(|(_, need)| *need) .map(|(pref, _)| (key << BITS_PER_SUBKEY) + pref as u64) .collect::<Vec<_>>(); let node_ptr = child_node.as_ref() as *const Node; if !child_node.leafs.is_empty() { children.push(Traversing::Leaf(0, (prefix_key_list, node_ptr))); } else { children.push(Traversing::Branch(prefix_key_list, node_ptr)); } } } self.stack.extend(children.into_iter().rev()); } self.next() } } } fn size_hint(&self) -> (usize, Option<usize>) { let hint = (self.size - self.count) as usize; (hint, Some(hint)) } }
// Copyright 2012 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. #![feature(box_syntax)] #[derive(Copy, Clone)] struct Foo { f: isize, } impl Foo { fn foo(self: Foo, x: isize) -> isize { self.f + x } fn bar(self: &Foo, x: isize) -> isize { self.f + x } fn baz(self: Box<Foo>, x: isize) -> isize { self.f + x } } #[derive(Copy, Clone)] struct Bar<T> { f: T, } impl<T> Bar<T> { fn foo(self: Bar<T>, x: isize) -> isize { x } fn bar<'a>(self: &'a Bar<T>, x: isize) -> isize { x } fn baz(self: Bar<T>, x: isize) -> isize { x } } fn main() { let foo: Box<_> = box Foo { f: 1, }; println!("{} {} {}", foo.foo(2), foo.bar(2), foo.baz(2)); let bar: Box<_> = box Bar { f: 1, }; println!("{} {} {}", bar.foo(2), bar.bar(2), bar.baz(2)); let bar: Box<Bar<isize>> = bar; println!("{} {} {}", bar.foo(2), bar.bar(2), bar.baz(2)); }
use coruscant_nbt::to_string_transcript; use serde::Serialize; // there is a (probable) serde bug here! // https://github.com/serde-rs/serde/issues/1584 #[derive(Serialize)] #[serde(rename = "book")] struct Book { resolved: Option<i8>, #[serde(flatten)] extra: Option<Extra>, } #[derive(Serialize)] struct Extra { generation: i32, author: &'static str, title: &'static str, } fn main() -> coruscant_nbt::Result<()> { let b1 = Book { resolved: None, extra: None, }; let b2 = Book { resolved: Some(1), extra: None, }; let e1 = Extra { generation: 0, author: "luojia65", title: "hello", }; let b3 = Book { resolved: Some(1), extra: Some(e1), }; println!("== Unresolved: does not contain `resolved` key"); println!("{}", to_string_transcript(&b1)?); println!("== Resolved: contains `resolved` key"); println!("{}", to_string_transcript(&b2)?); println!("== With extra: contains flattened `generation` key, etc."); println!("{}", to_string_transcript(&b3)?); Ok(()) }
use std::collections::HashMap; use std::io::Cursor; use base64; use rocket::request; use rocket::request::FromRequest; use rocket::{response, Outcome, Request, Response}; use crate::models::stat; use crate::models::stat::StatFromType; use crate::repo::DomainRepo; use crate::{conn, util}; pub struct Pack { hash: String, pack: HashMap<String, String>, client_ip: String, } impl Pack { fn decode_pack(pack: &String, map: &mut HashMap<String, String>) { let u = base64::decode(pack).unwrap_or(vec![]); let pack_str = String::from_utf8(u).unwrap(); let url = url::form_urlencoded::parse(pack_str.as_bytes()); for (key, value) in url.into_owned() { map.insert(key.clone(), value.clone()); } } fn get<T: Into<String>>(&self, k: T) -> Option<String> { match self.pack.get(&k.into()) { Some(s) => Some(s.to_owned()), _ => None, } } fn get_from(&self) -> String { if let Some(query) = self.get("query") { for it in stat::INTERNAL_STAT_FROM_VEC.iter() { if it.detect_type == StatFromType::Query as i16 { if query.contains(&it.keyword) { return it.key.clone(); } } } } if let Some(host) = self.get("host") { for it in stat::INTERNAL_STAT_FROM_VEC.iter() { if it.detect_type == StatFromType::Host as i16 { if host.contains(&it.keyword) { return it.key.clone(); } } } } if let Some(referer) = self.get("referer") { for it in stat::INTERNAL_STAT_FROM_VEC.iter() { if it.detect_type == StatFromType::Referer as i16 { if referer.contains(&it.keyword) { return it.key.clone(); } } } } if let Some(user_agent) = self.get("user_agent") { for it in stat::INTERNAL_STAT_FROM_VEC.iter() { if it.detect_type == StatFromType::UserAgent as i16 { if user_agent.contains(&it.keyword) { return it.key.clone(); } } } } String::from("") } fn get_referer(&self) -> String { if let Some(referer) = self.get("referer") { if let Some(i) = referer.find("//") { let s = &referer[i + 2..]; if let Some(i) = s.find("/") { return s[..i].to_owned(); } } } return String::from(""); } fn get_os(&self) -> String { if let Some(user_agent) = self.get("user_agent") { if user_agent.contains("Mac OS X") { return String::from("Mac"); } if user_agent.contains("Windows") { return String::from("Windows"); } if user_agent.contains("Linux") { return String::from("Linux"); } if user_agent.contains("Android") { return String::from("Android"); } if user_agent.contains("iPhone") { return String::from("IPhone"); } } String::from("") } } impl<'f, 'r> FromRequest<'f, 'r> for Pack { type Error = !; fn from_request(request: &'f Request<'r>) -> request::Outcome<Self, !> { let string = request.uri().query().unwrap(); let url = url::form_urlencoded::parse(string.as_bytes()); let mut hash: String = String::from(""); let mut mp = HashMap::new(); for (key, value) in url.into_owned() { match key.as_str() { "hash" => hash = value, "pack" => Self::decode_pack(&value, &mut mp), _ => {} } } let mut client_ip = String::from(""); if let Some(ip) = request.client_ip() { client_ip = ip.to_string(); } Outcome::Success(Pack { hash, pack: mp, client_ip, }) } } fn response<'a>(s: String) -> response::Result<'a> { Response::build() .raw_header("Content-Type", "text/javascript;charset=utf-8") .raw_status(200, "") .sized_body(Cursor::new(s)) .ok() } #[derive(Serialize, Debug)] pub struct PostResult { // 来源 pub from: String, // 来源主机 pub referer: String, // 设备系统 pub device_os: String, // 客户端IP pub client_ip: String, // 用户区域 pub user_district: String, // 用户大致位置 pub user_place: String, } #[get("/site_po")] pub fn site_po<'a>(pack: Pack) -> response::Result<'a> { let conn = conn(); let _d = DomainRepo::get_domain(&conn, pack.hash.to_owned()); dbg!(&pack.pack); let callback = pack.get("callback").unwrap_or("_callback".to_string()); // 获取位置 let district = util::ip_district(pack.client_ip.clone()); // 包装结果 let pr = PostResult { from: pack.get_from(), referer: pack.get_referer(), device_os: pack.get_os(), client_ip: pack.client_ip.clone(), user_district: district.0, user_place: district.1, }; let mut s = String::from(callback); s.push_str("("); s.push_str(&serde_json::to_string(&json!(pr)).unwrap()); //s.push_str(&pack_str); s.push_str(");"); response(s) }
// Copyright 2014 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. // pretty-expanded FIXME #23616 #![feature(box_syntax)] struct Element; macro_rules! foo { ($tag: expr, $string: expr) => { if $tag == $string { let element: Box<_> = box Element; unsafe { return std::mem::transmute::<_, usize>(element); } } } } fn bar() -> usize { foo!("a", "b"); 0 } fn main() { bar(); }
use crate::{ testing::data::Wallet, testing::scenario::scenario_builder::ScenarioBuilderError, value::Value, }; use super::{StakePoolTemplate, WalletTemplate}; use std::collections::{HashMap, HashSet}; #[derive(Clone, Debug)] pub struct WalletTemplateBuilder { alias: String, delagate_alias: Option<String>, ownership_alias: Option<String>, initial_value: Option<Value>, } impl WalletTemplateBuilder { pub fn new(alias: &str) -> Self { WalletTemplateBuilder { alias: alias.to_owned(), delagate_alias: None, ownership_alias: None, initial_value: None, } } pub fn with(&mut self, value: u64) -> &mut Self { self.initial_value = Some(Value(value)); self } pub fn owns(&mut self, ownership_alias: &str) -> &mut Self { self.ownership_alias = Some(ownership_alias.to_owned()); self } pub fn delegates_to(&mut self, delegates_to_alias: &str) -> &mut Self { self.delagate_alias = Some(delegates_to_alias.to_owned()); self } pub fn build(&self) -> Result<WalletTemplate, ScenarioBuilderError> { let value = self .initial_value .ok_or(ScenarioBuilderError::UndefinedValueForWallet { alias: self.alias.clone(), })?; Ok(WalletTemplate { alias: self.alias.clone(), stake_pool_delegate_alias: self.delagate_alias.clone(), stake_pool_owner_alias: self.ownership_alias.clone(), initial_value: value.clone(), }) } } pub struct StakePoolTemplateBuilder { ownership_map: HashMap<String, HashSet<WalletTemplate>>, delegation_map: HashMap<String, HashSet<WalletTemplate>>, } impl StakePoolTemplateBuilder { pub fn new(initials: &Vec<WalletTemplate>) -> Self { StakePoolTemplateBuilder { ownership_map: Self::build_ownersip_map(initials), delegation_map: Self::build_delegation_map(initials), } } pub fn build_stake_pool_templates( &self, wallets: Vec<Wallet>, ) -> Result<Vec<StakePoolTemplate>, ScenarioBuilderError> { self.defined_stake_pools_aliases() .iter() .map(|stake_pool_alias| { let owners = self.ownership_map.get(stake_pool_alias).ok_or( ScenarioBuilderError::NoOwnersForStakePool { alias: stake_pool_alias.to_string(), }, )?; let owners_public_keys = wallets .iter() .filter(|w| owners.iter().any(|u| u.alias() == w.alias())) .map(|w| w.public_key()) .collect(); Ok(StakePoolTemplate { alias: stake_pool_alias.to_string(), owners: owners_public_keys, }) }) .collect() } pub fn defined_stake_pools_aliases(&self) -> HashSet<String> { self.ownership_map .clone() .into_iter() .chain(self.delegation_map.clone()) .map(|(k, _)| k) .collect() } fn build_ownersip_map( initials: &Vec<WalletTemplate>, ) -> HashMap<String, HashSet<WalletTemplate>> { let mut output: HashMap<String, HashSet<WalletTemplate>> = HashMap::new(); for wallet_template in initials.iter().filter(|w| w.owns_stake_pool().is_some()) { let delegate_alias = wallet_template.owns_stake_pool().unwrap(); match output.contains_key(&delegate_alias) { true => { output .get_mut(&delegate_alias) .unwrap() .insert(wallet_template.clone()); } false => { let mut delegation_aliases = HashSet::new(); delegation_aliases.insert(wallet_template.clone()); output.insert(delegate_alias, delegation_aliases); } } } output } fn build_delegation_map( initials: &Vec<WalletTemplate>, ) -> HashMap<String, HashSet<WalletTemplate>> { let mut output: HashMap<String, HashSet<WalletTemplate>> = HashMap::new(); for wallet_template in initials .iter() .filter(|w| w.delegates_stake_pool().is_some()) { let stake_pool_alias = wallet_template.delegates_stake_pool().unwrap(); match output.contains_key(&stake_pool_alias) { true => { output .get_mut(&stake_pool_alias) .unwrap() .insert(wallet_template.clone()); } false => { let mut ownership_aliases = HashSet::new(); ownership_aliases.insert(wallet_template.clone()); output.insert(stake_pool_alias.to_string(), ownership_aliases); } } } output } }
use std::collections::HashMap; use petgraph::Graph; use petgraph::graph::NodeIndex; use super::graph::{Node, Edge}; pub fn normalize(graph: &mut Graph<Node, Edge>, layers_map: &mut HashMap<NodeIndex, usize>) { for e in graph.edge_indices() { let edge = graph[e].clone(); let (u, v) = graph.edge_endpoints(e).unwrap(); let h_u = *layers_map.get(&u).unwrap(); let h_v = *layers_map.get(&v).unwrap(); let length = h_v - h_u; if length == 1 { continue; } let mut w0 = u; for i in h_u + 1..h_v { let w1 = graph.add_node(Node::new_dummy()); layers_map.insert(w1, i); graph.add_edge(w0, w1, Edge::new_split(&edge)); w0 = w1; } graph.add_edge(w0, v, Edge::new_split(&edge)); graph.remove_edge(e); } } #[cfg(test)] mod tests { use petgraph::Graph; use super::*; #[test] fn it_works() { let mut graph = Graph::new(); let u1 = graph.add_node(Node::new()); let u2 = graph.add_node(Node::new()); let u3 = graph.add_node(Node::new()); graph.add_edge(u1, u2, Edge::new()); graph.add_edge(u1, u3, Edge::new_reversed()); graph.add_edge(u2, u3, Edge::new()); let mut layers_map = HashMap::new(); layers_map.insert(u1, 0); layers_map.insert(u2, 1); layers_map.insert(u3, 2); normalize(&mut graph, &mut layers_map); assert_eq!(graph.node_count(), 4); assert_eq!(graph.edge_count(), 4); } }
use rltk::GameState; use rltk::RGB; use rltk::Rltk; use specs::prelude::*; use specs_derive::Component; mod map; pub use map::*; mod player; pub use player::*; mod components; pub use components::*; mod rectangle; mod visibility_system; pub use visibility_system::*; pub struct State { ecs: World } impl GameState for State { fn tick(&mut self, ctx: &mut Rltk){ ctx.cls(); player_input(self, ctx); self.run_systems(); draw_map(&self.ecs, ctx); let positions = self.ecs.read_storage::<Position>(); let renderables = self.ecs.read_storage::<Renderable>(); for (pos, render) in (&positions, &renderables).join() { ctx.set(pos.x, pos.y, render.fg, render.bg, render.glyph); } } } struct LeftWalker {} impl<'a> System<'a> for LeftWalker { type SystemData = (ReadStorage<'a, LeftMover>, WriteStorage<'a, Position>); fn run(&mut self, (lefty, mut pos): (ReadStorage<'a, LeftMover>, WriteStorage<'a, Position>)){ for (_lefty, pos) in (&lefty, &mut pos).join() { pos.x -= 1; if pos.x < 0 { pos.x = 79; } } } } impl State { fn run_systems(&mut self){ let mut lw = LeftWalker{}; lw.run_now(&self.ecs); let mut vis= VisibilitySystem{}; vis.run_now(&self.ecs); self.ecs.maintain(); } } #[derive(Component, Debug)] pub struct Player {} fn main() -> rltk::BError { use rltk::RltkBuilder; let context = RltkBuilder::simple80x50() .with_title("Rogue Clone") .build()?; let mut gs = State{ ecs: World::new() }; gs.ecs.register::<Position>(); gs.ecs.register::<Renderable>(); gs.ecs.register::<LeftMover>(); gs.ecs.register::<Player>(); gs.ecs.register::<Viewshed>(); let map = Map::new_map_rooms_and_corridors(); let (player_x, player_y) = map.rooms[0].center(); gs.ecs.insert(map); gs.ecs.create_entity() .with(Position {x:player_x, y:player_y}) .with(Renderable { glyph: rltk::to_cp437('@'), fg: RGB::named(rltk::YELLOW), bg: RGB::named(rltk::BLACK), }) .with(Player{}) .with(Viewshed{ visible_tiles: Vec::new(), range: 8, dirty: true, }) .build(); rltk::main_loop(context, gs) }
// This file is part of Substrate. // Copyright (C) 2019-2021 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! The reservable currency trait. use super::Currency; use super::super::misc::BalanceStatus; use crate::dispatch::{DispatchResult, DispatchError}; /// A currency where funds can be reserved from the user. pub trait ReservableCurrency<AccountId>: Currency<AccountId> { /// Same result as `reserve(who, value)` (but without the side-effects) assuming there /// are no balance changes in the meantime. fn can_reserve(who: &AccountId, value: Self::Balance) -> bool; /// Deducts up to `value` from reserved balance of `who`. This function cannot fail. /// /// As much funds up to `value` will be deducted as possible. If the reserve balance of `who` /// is less than `value`, then a non-zero second item will be returned. fn slash_reserved( who: &AccountId, value: Self::Balance ) -> (Self::NegativeImbalance, Self::Balance); /// The amount of the balance of a given account that is externally reserved; this can still get /// slashed, but gets slashed last of all. /// /// This balance is a 'reserve' balance that other subsystems use in order to set aside tokens /// that are still 'owned' by the account holder, but which are suspendable. /// /// When this balance falls below the value of `ExistentialDeposit`, then this 'reserve account' /// is deleted: specifically, `ReservedBalance`. /// /// `system::AccountNonce` is also deleted if `FreeBalance` is also zero (it also gets /// collapsed to zero if it ever becomes less than `ExistentialDeposit`. fn reserved_balance(who: &AccountId) -> Self::Balance; /// Moves `value` from balance to reserved balance. /// /// If the free balance is lower than `value`, then no funds will be moved and an `Err` will /// be returned to notify of this. This is different behavior than `unreserve`. fn reserve(who: &AccountId, value: Self::Balance) -> DispatchResult; /// Moves up to `value` from reserved balance to free balance. This function cannot fail. /// /// As much funds up to `value` will be moved as possible. If the reserve balance of `who` /// is less than `value`, then the remaining amount will be returned. /// /// # NOTES /// /// - This is different from `reserve`. /// - If the remaining reserved balance is less than `ExistentialDeposit`, it will /// invoke `on_reserved_too_low` and could reap the account. fn unreserve(who: &AccountId, value: Self::Balance) -> Self::Balance; /// Moves up to `value` from reserved balance of account `slashed` to balance of account /// `beneficiary`. `beneficiary` must exist for this to succeed. If it does not, `Err` will be /// returned. Funds will be placed in either the `free` balance or the `reserved` balance, /// depending on the `status`. /// /// As much funds up to `value` will be deducted as possible. If this is less than `value`, /// then `Ok(non_zero)` will be returned. fn repatriate_reserved( slashed: &AccountId, beneficiary: &AccountId, value: Self::Balance, status: BalanceStatus, ) -> Result<Self::Balance, DispatchError>; } pub trait NamedReservableCurrency<AccountId>: ReservableCurrency<AccountId> { /// An identifier for a reserve. Used for disambiguating different reserves so that /// they can be individually replaced or removed. type ReserveIdentifier; /// Deducts up to `value` from reserved balance of `who`. This function cannot fail. /// /// As much funds up to `value` will be deducted as possible. If the reserve balance of `who` /// is less than `value`, then a non-zero second item will be returned. fn slash_reserved_named( id: &Self::ReserveIdentifier, who: &AccountId, value: Self::Balance ) -> (Self::NegativeImbalance, Self::Balance); /// The amount of the balance of a given account that is externally reserved; this can still get /// slashed, but gets slashed last of all. /// /// This balance is a 'reserve' balance that other subsystems use in order to set aside tokens /// that are still 'owned' by the account holder, but which are suspendable. /// /// When this balance falls below the value of `ExistentialDeposit`, then this 'reserve account' /// is deleted: specifically, `ReservedBalance`. /// /// `system::AccountNonce` is also deleted if `FreeBalance` is also zero (it also gets /// collapsed to zero if it ever becomes less than `ExistentialDeposit`. fn reserved_balance_named(id: &Self::ReserveIdentifier, who: &AccountId) -> Self::Balance; /// Moves `value` from balance to reserved balance. /// /// If the free balance is lower than `value`, then no funds will be moved and an `Err` will /// be returned to notify of this. This is different behavior than `unreserve`. fn reserve_named(id: &Self::ReserveIdentifier, who: &AccountId, value: Self::Balance) -> DispatchResult; /// Moves up to `value` from reserved balance to free balance. This function cannot fail. /// /// As much funds up to `value` will be moved as possible. If the reserve balance of `who` /// is less than `value`, then the remaining amount will be returned. /// /// # NOTES /// /// - This is different from `reserve`. /// - If the remaining reserved balance is less than `ExistentialDeposit`, it will /// invoke `on_reserved_too_low` and could reap the account. fn unreserve_named(id: &Self::ReserveIdentifier, who: &AccountId, value: Self::Balance) -> Self::Balance; /// Moves up to `value` from reserved balance of account `slashed` to balance of account /// `beneficiary`. `beneficiary` must exist for this to succeed. If it does not, `Err` will be /// returned. Funds will be placed in either the `free` balance or the `reserved` balance, /// depending on the `status`. /// /// As much funds up to `value` will be deducted as possible. If this is less than `value`, /// then `Ok(non_zero)` will be returned. fn repatriate_reserved_named( id: &Self::ReserveIdentifier, slashed: &AccountId, beneficiary: &AccountId, value: Self::Balance, status: BalanceStatus, ) -> Result<Self::Balance, DispatchError>; /// Ensure the reserved balance is equal to `value`. /// /// This will reserve extra amount of current reserved balance is less than `value`. /// And unreserve if current reserved balance is greater than `value`. fn ensure_reserved_named(id: &Self::ReserveIdentifier, who: &AccountId, value: Self::Balance) -> DispatchResult { let current = Self::reserved_balance_named(id, who); if current > value { // we always have enough balance to unreserve here Self::unreserve_named(id, who, current - value); Ok(()) } else if value > current { // we checked value > current Self::reserve_named(id, who, value - current) } else { // current == value Ok(()) } } /// Unreserve all the named reserved balances, returning unreserved amount. /// /// Is a no-op if the value to be unreserved is zero. fn unreserve_all_named(id: &Self::ReserveIdentifier, who: &AccountId) -> Self::Balance { let value = Self::reserved_balance_named(id, who); Self::slash_reserved_named(id, who, value); value } /// Slash all the reserved balance, returning the negative imbalance created. /// /// Is a no-op if the value to be slashed is zero. fn slash_all_reserved_named(id: &Self::ReserveIdentifier, who: &AccountId) -> Self::NegativeImbalance { let value = Self::reserved_balance_named(id, who); Self::slash_reserved_named(id, who, value).0 } /// Move all the named reserved balance of one account into the balance of another, according to `status`. /// If `status` is `Reserved`, the balance will be reserved with given `id`. /// /// Is a no-op if: /// - the value to be moved is zero; or /// - the `slashed` id equal to `beneficiary` and the `status` is `Reserved`. fn repatriate_all_reserved_named( id: &Self::ReserveIdentifier, slashed: &AccountId, beneficiary: &AccountId, status: BalanceStatus, ) -> DispatchResult { let value = Self::reserved_balance_named(id, slashed); Self::repatriate_reserved_named(id, slashed, beneficiary, value, status).map(|_| ()) } }
#[macro_use] mod prelude; mod config; mod memtable; mod primitives; mod sstable; mod table; mod time; mod tombstones; #[cfg(test)] mod testutils; use std::collections::HashMap; fn main() { let arr = [1u8, 2u8]; let r = &arr[0..]; println!("{}", r[0]); println!("{}", r[1]); let asdf = std::panic::catch_unwind(|| println!("{}", r[2])); println!("yo"); println!("{:?}", asdf); let mut m = HashMap::new(); m.insert(1, "yo"); println!("{:?}, {:?}", m.get(&1), m.get(&2)); m.insert(2, "yeah"); println!("{:?}, {:?}", m.get(&1), m.get(&2)); }
use super::Part; use crate::codec::{Decode, Encode}; use crate::spacecenter::ReferenceFrame; use crate::{remote_type, RemoteObject, Vector3}; remote_type!( /// The component of an Engine or RCS part that generates thrust. Can obtained by /// calling` Engine::thrusters()` or `RCS::thrusters()`. /// /// # Note /// Engines can consist of multiple thrusters. For example, the S3 KS-25x4 “Mammoth” has four /// rocket nozzels, and so consists of four thrusters. object SpaceCenter.Thruster { properties: { { Part { /// Returns the part object for this thruster. /// /// **Game Scenes**: All get: part -> Part } } { ThrustReferenceFrame { /// Returns a reference frame that is fixed relative to the thruster and /// orientated with its thrust direction (Thruster.thrustDirection(ReferenceFrame)). /// For gimballed engines, this takes into account the current rotation of the gimbal. /// /// * The origin is at the position of thrust for this thruster /// (`Thruster::thrust_position()`). /// * The axes rotate with the thrust direction. This is the direction in which the /// thruster expels propellant, including any gimballing. /// * The y-axis points along the thrust direction. /// * The x-axis and z-axis are perpendicular to the thrust direction. /// /// **Game Scenes**: All get: thrust_reference_frame -> ReferenceFrame } } { Gimballed { /// Returns whether the thruster is gimballed. /// /// **Game Scenes**: All get: is_gimballed -> bool } } { GimbalAngle { /// Returns the current gimbal angle in the pitch, roll and yaw axes, in degrees. /// /// **Game Scenes**: All get: gimbal_angle -> f32 } } } methods: { { /// The position at which the thruster generates thrust, in the given reference frame. /// For gimballed engines, this takes into account the current rotation of the gimbal. /// /// **Game Scenes**: All /// /// # Arguments /// * `reference_frame` - The reference frame that the returned position vector is in. /// /// # Return /// The position as a vector. fn thrust_position(reference_frame: &ReferenceFrame) -> Vector3 { ThrustPosition(reference_frame) } } { /// The direction of the force generated by the thruster, in the given reference frame. /// This is opposite to the direction in which the thruster expels propellant. /// For gimballed engines, this takes into account the current rotation of the gimbal. /// /// **Game Scenes**: All /// /// # Arguments /// * `reference_frame` - The reference frame that the returned direction is in. /// /// # Return /// The direction as a unit vector. fn thrust_direction(reference_frame: &ReferenceFrame) -> Vector3 { ThrustDirection(reference_frame) } } { /// Position around which the gimbal pivots. /// /// **Game Scenes**: All /// /// # Arguments /// * `reference_frame` - The reference frame that the returned position vector is in. /// /// # Return /// The position as a vector. fn gimbal_position(reference_frame: &ReferenceFrame) -> Vector3 { GimbalPosition(reference_frame) } } { /// The position at which the thruster generates thrust, when the engine is in /// its initial position (no gimballing), in the given reference frame. /// /// **Game Scenes**: All /// /// # Arguments /// * `reference_frame` - The reference frame that the returned position vector is in. /// /// # Return /// The position as a vector. /// /// # Notes /// This position can move when the gimbal rotates. This is because the thrust /// position and gimbal position are not necessarily the same. fn initial_thrust_position(reference_frame: &ReferenceFrame) -> Vector3 { InitialThrustPosition(reference_frame) } } { /// The direction of the force generated by the thruster, when the engine is in its /// initial position (no gimballing), in the given reference frame. This is /// opposite to the direction in which the thruster expels propellant. /// /// **Game Scenes**: All /// /// # Arguments /// * `reference_frame` - The reference frame that the returned direction is in. /// /// # Return /// The direction as a unit vector. fn initial_thrust_direction(reference_frame: &ReferenceFrame) -> Vector3 { InitialThrustDirection(reference_frame) } } } });
use crate::label_sequence::LabelSequence; use crate::name::lower_case; use crate::name::Name; use crate::name::NameComparisonResult; use crate::name::NameRelation; use std::{cmp, fmt}; #[derive(Debug, Clone, Eq, PartialEq)] pub struct LabelSlice<'a> { data: &'a [u8], offsets: &'a [u8], first_label: usize, last_label: usize, } impl<'a> LabelSlice<'a> { pub fn from_name(name: &'a Name) -> LabelSlice { LabelSlice { data: name.raw_data(), offsets: name.offsets(), first_label: 0, last_label: name.label_count() - 1, } } pub fn from_label_sequence(ls: &'a LabelSequence) -> LabelSlice { LabelSlice { data: ls.data(), offsets: ls.offsets(), first_label: 0, last_label: ls.label_count() - 1, } } #[inline] pub fn offsets(&self) -> &'a [u8] { &self.offsets[self.first_label..=self.last_label] } #[inline] pub fn data(&self) -> &'a [u8] { let first_label_index: usize = usize::from(self.offsets[self.first_label]); &self.data[first_label_index..first_label_index + self.len()] } #[inline] pub fn len(&self) -> usize { let last_label_len: u8 = self.data[usize::from(self.offsets[self.last_label])] + 1; usize::from(self.offsets[self.last_label] - self.offsets[self.first_label] + last_label_len) } #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 } #[inline] pub fn first_label(&self) -> usize { self.first_label } #[inline] pub fn last_label(&self) -> usize { self.last_label } #[inline] pub fn label_count(&self) -> usize { self.last_label - self.first_label + 1 } pub fn equals(&self, other: &LabelSlice, case_sensitive: bool) -> bool { if self.len() != other.len() { false } else if case_sensitive { self.data() == other.data() } else { self.data().eq_ignore_ascii_case(other.data()) } } pub fn compare(&self, other: &LabelSlice, case_sensitive: bool) -> NameComparisonResult { let mut nlabels: usize = 0; let mut l1: usize = self.label_count(); let mut l2: usize = other.label_count(); let ldiff = (l1 as isize) - (l2 as isize); let mut l = cmp::min(l1, l2); while l > 0 { l -= 1; l1 -= 1; l2 -= 1; let mut pos1: usize = usize::from(self.offsets[l1 + self.first_label]); let mut pos2: usize = usize::from(other.offsets[l2 + other.first_label]); let count1: usize = usize::from(self.data[pos1]); let count2: usize = usize::from(other.data[pos2]); pos1 += 1; pos2 += 1; let cdiff: isize = (count1 as isize) - (count2 as isize); let mut count = cmp::min(count1, count2); while count > 0 { let mut label1: u8 = self.data[pos1]; let mut label2: u8 = other.data[pos2]; let chdiff: i8; if !case_sensitive { label1 = lower_case(label1 as usize); label2 = lower_case(label2 as usize); } chdiff = (label1) as i8 - (label2) as i8; if chdiff != 0 { return NameComparisonResult { order: chdiff, common_label_count: nlabels as u8, relation: if nlabels == 0 { NameRelation::None } else { NameRelation::CommonAncestor }, }; } count -= 1; pos1 += 1; pos2 += 1; } if cdiff != 0 { return NameComparisonResult { order: cdiff as i8, common_label_count: nlabels as u8, relation: if nlabels == 0 { NameRelation::None } else { NameRelation::CommonAncestor }, }; } nlabels += 1; } NameComparisonResult { order: ldiff as i8, common_label_count: nlabels as u8, relation: if ldiff < 0 { NameRelation::SuperDomain } else if ldiff > 0 { NameRelation::SubDomain } else { NameRelation::Equal }, } } #[inline] pub fn strip_left(&mut self, index: usize) { assert!(index < self.label_count()); self.first_label += index; } #[inline] pub fn strip_right(&mut self, index: usize) { assert!(index < self.label_count()); self.last_label -= index; } } impl<'a> fmt::Display for LabelSlice<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut buf = Vec::with_capacity(self.len()); let special_char: Vec<u8> = vec![0x22, 0x28, 0x29, 0x2E, 0x3B, 0x5C, 0x40, 0x24]; //" ( ) . ; \\ @ $ let mut i = 0; let data = self.data(); while i < self.len() { let mut count = data[i as usize]; i += 1; if count == 0 { buf.push(b'.'); break; } if !buf.is_empty() { buf.push(b'.'); } while count > 0 { count -= 1; let c: u8 = data[i as usize]; i += 1; if special_char.contains(&c) { buf.push(b'\\'); buf.push(c); } else if c > 0x20 && c < 0x7f { buf.push(c); } else { buf.push(0x5c); buf.push(0x30 + ((c / 100) % 10)); buf.push(0x30 + ((c / 10) % 10)); buf.push(0x30 + (c % 10)); } } } write!(f, "{}", unsafe { String::from_utf8_unchecked(buf) }) } } #[cfg(test)] mod test { use super::*; use crate::name::Name; #[test] fn test_label_slice_new() { //0377777705626169647503636f6d00 let n1 = Name::new("www.baidu.com.").unwrap(); let ls1 = LabelSlice::from_name(&n1); assert_eq!( ls1.data, [3, 119, 119, 119, 5, 98, 97, 105, 100, 117, 3, 99, 111, 109, 0] ); assert_eq!(ls1.offsets, [0, 4, 10, 14]); assert_eq!(ls1.first_label, 0); assert_eq!(ls1.last_label, 3); let n2 = Name::new("www.baidu.coM.").unwrap(); let ls2 = LabelSlice::from_name(&n2); assert_eq!( ls2.data, [3, 119, 119, 119, 5, 98, 97, 105, 100, 117, 3, 99, 111, 77, 0] ); assert_eq!(ls2.offsets, [0, 4, 10, 14]); assert_eq!(ls2.first_label, 0); assert_eq!(ls2.last_label, 3); assert_eq!( ls1.data(), [3, 119, 119, 119, 5, 98, 97, 105, 100, 117, 3, 99, 111, 109, 0] ); assert_eq!( ls2.data(), [3, 119, 119, 119, 5, 98, 97, 105, 100, 117, 3, 99, 111, 77, 0] ); assert_eq!(ls1.equals(&ls2, false), true); assert_eq!(ls1.equals(&ls2, true), false); let grand_parent = Name::new("com").unwrap(); let ls_grand_parent = LabelSlice::from_name(&grand_parent); let parent = Name::new("BaIdU.CoM").unwrap(); let ls_parent = LabelSlice::from_name(&parent); let child = Name::new("wWw.bAiDu.cOm").unwrap(); let mut ls_child = LabelSlice::from_name(&child); let brother = Name::new("AaA.bAiDu.cOm").unwrap(); let ls_brother = LabelSlice::from_name(&brother); let other = Name::new("aAa.BaIdu.cN").unwrap(); let mut ls_other = LabelSlice::from_name(&other); assert_eq!( ls_grand_parent.compare(&ls_parent, false).relation, NameRelation::SuperDomain ); assert_eq!( ls_parent.compare(&ls_child, false).relation, NameRelation::SuperDomain ); assert_eq!( ls_child.compare(&ls_parent, false).relation, NameRelation::SubDomain ); assert_eq!( ls_child.compare(&ls_grand_parent, false).relation, NameRelation::SubDomain ); assert_eq!( ls_child.compare(&ls_brother, false).relation, NameRelation::CommonAncestor ); assert_eq!( ls_child.compare(&ls_child, false).relation, NameRelation::Equal ); ls_child.strip_left(1); ls_other.strip_left(1); assert_eq!( ls_child.compare(&ls_other, false).relation, NameRelation::CommonAncestor ); ls_child.strip_right(1); ls_other.strip_right(1); assert_eq!( ls_child.compare(&ls_other, false).relation, NameRelation::None ); let ls_name = Name::new("1.www.google.com").unwrap(); let mut ls_slice = LabelSlice::from_name(&ls_name); ls_slice.strip_left(1); ls_slice.strip_right(1); let first_label = ls_slice.first_label(); assert_eq!(first_label, 1); let last_label = ls_slice.last_label(); assert_eq!(last_label, 3); let ls_sequence = ls_name.into_label_sequence(first_label, last_label); let ls_slice2 = LabelSlice::from_label_sequence(&ls_sequence); let ls_name_2 = Name::new("www.google.com.").unwrap(); let mut ls_slice3 = LabelSlice::from_name(&ls_name_2); ls_slice3.strip_right(1); assert_eq!( ls_slice2.compare(&ls_slice3, false).relation, NameRelation::Equal ); } #[test] fn test_label_slice_root() { let n1 = Name::new(".").unwrap(); let ls1 = LabelSlice::from_name(&n1); assert_eq!(ls1.len(), 1); let ls2 = LabelSlice::from_name(&n1); assert_eq!(ls2.len(), 1); } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub const PERCEPTIONFIELD_StateStream_TimeStamps: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2861064473, data2: 62255, data3: 18879, data4: [146, 202, 249, 221, 247, 132, 210, 151], }; #[repr(C)] pub struct PERCEPTION_PAYLOAD_FIELD { pub FieldId: ::windows_sys::core::GUID, pub OffsetInBytes: u32, pub SizeInBytes: u32, } impl ::core::marker::Copy for PERCEPTION_PAYLOAD_FIELD {} impl ::core::clone::Clone for PERCEPTION_PAYLOAD_FIELD { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct PERCEPTION_STATE_STREAM_TIMESTAMPS { pub InputTimestampInQpcCounts: i64, pub AvailableTimestampInQpcCounts: i64, } impl ::core::marker::Copy for PERCEPTION_STATE_STREAM_TIMESTAMPS {} impl ::core::clone::Clone for PERCEPTION_STATE_STREAM_TIMESTAMPS { fn clone(&self) -> Self { *self } }
pub use self::plugins::*; pub use self::systems::*; mod plugins; mod systems;
use gatt::characteristics as ch; use gatt::services as srv; use gatt::{CharacteristicProperties, Registration}; pub(crate) fn add(registration: &mut Registration<super::Token>) { // Generic Attirbute registration.add_primary_service(srv::GENERIC_ATTRIBUTE); // ServiceChanged registration.add_characteristic( ch::SERVICE_CHANGED, vec![0x00], CharacteristicProperties::INDICATE, ); }
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] #[serde(tag = "kind")] pub enum Body { Ping(PingBody), //LogShow(LogShowBody), LogAdd(LogAddBody), //LogDelete(LogDeleteBody), //LogList(LogListBody), MessageAdd(MessageAddBody), //IteratorAdd(IteratorAddBody), //IteratorList(IteratorListBody), //IteratorNext(IteratorNextBody), //IteratorDelete(IteratorDeleteBody), } /// Used to check if server is responding #[derive(Serialize, Deserialize, Debug)] pub struct PingBody { /// ID of the message. Unique to this connection. pub id: u64, } #[derive(Serialize, Deserialize, Debug)] pub struct LogAddBody { /// ID of the message. Unique to this connection. pub id: u64, pub name: String, } #[derive(Serialize, Deserialize, Debug)] pub struct MessageAddBody { pub id: u64, pub body: String, }
use anyhow::{anyhow, bail, Result}; #[tokio::main] async fn main() -> Result<()> { let client = Client::new()?; let lock = client.request_lock().await?; println!("Got lock: {:?}", lock); let cols = Colours { led0: Colour::rgb(255, 0, 0), led1: Colour::rgb(255, 0, 0), led2: Colour::rgb(255, 0, 0), led3: Colour::rgb(255, 0, 0), led4: Colour::rgb(255, 0, 0), led5: Colour::rgb(255, 0, 0), led6: Colour::rgb(255, 0, 0), led7: Colour::rgb(255, 0, 0), led8: Colour::rgb(255, 0, 0), led9: Colour::rgb(255, 0, 0), }; println!("Setting colours: {:?}", cols); client.set_colour(&lock, cols).await?; Ok(()) } #[derive(Debug, Clone)] struct Lock { hash: String, } #[derive(Clone, Debug, serde::Deserialize)] struct Status { code: u64, description: String, } #[derive(Clone, Debug, serde::Deserialize)] struct LockResponse { hash: Option<String>, maxtime: Option<f64>, status: Status, } #[derive(Clone, Debug, serde::Serialize)] struct Colour(Vec<u8>); impl Colour { pub fn rgb(red: u8, green: u8, blue: u8) -> Self { Self(vec![red, green, blue]) } } #[derive(Debug, Clone, serde::Serialize)] struct Colours { #[serde(rename = "0")] led0: Colour, #[serde(rename = "1")] led1: Colour, #[serde(rename = "2")] led2: Colour, #[serde(rename = "3")] led3: Colour, #[serde(rename = "4")] led4: Colour, #[serde(rename = "5")] led5: Colour, #[serde(rename = "6")] led6: Colour, #[serde(rename = "7")] led7: Colour, #[serde(rename = "8")] led8: Colour, #[serde(rename = "9")] led9: Colour, } #[derive(serde::Serialize)] #[serde(rename_all = "camelCase")] struct SetColourRequest { hash: String, colours: String, } struct Client { client: reqwest::Client, } impl Client { fn new() -> Result<Self> { let client = reqwest::ClientBuilder::new().build()?; Ok(Self { client }) } async fn set_colour(&self, lock: &Lock, cols: Colours) -> Result<()> { let colorsjson = serde_json::to_string(&cols).expect("Serializing colors"); let req = SetColourRequest { hash: lock.hash.clone(), colours: colorsjson, }; let res = self .client .get("http://api.colourbynumbers.org/cbn-live/setColours") .header("Accept", "application/json") .header("Accept-Language", "sv-se") .header("Connection", "keep-alive") .query(&req) .send() .await?; let body = res.text().await?; println!("Got response: {}", body); Ok(()) } async fn request_lock(&self) -> Result<Lock> { let res = self .client .get("http://api.colourbynumbers.org/cbn-live/requestLock") .header("Accept", "application/json") .header("Accept-Language", "sv-se") .header("Connection", "keep-alive") .send() .await?; let bs = res.bytes().await?; let res = serde_json::from_slice::<LockResponse>(&bs).map_err(|err| { anyhow!( "Failed to deserialize response:\n{}\n as json: {}", String::from_utf8_lossy(&bs), err ) })?; match res.status.code { 0 => Err(anyhow!("Busy")), 1 => Ok(Lock { hash: res.hash.ok_or_else(|| anyhow!("Hash missing from resp"))?, }), n => { bail!( "Unknown status `{}` with body: {}", n, String::from_utf8_lossy(&bs) ); } } } } #[cfg(test)] mod tests { use super::*; #[test] fn colour_serialize() { let col = Colour::rgb(128, 127, 129); assert_eq!(r#"[128,127,129]"#, serde_json::to_string(&col).unwrap()) } #[test] fn colours_serialize() { let cols = Colours { led0: Colour::rgb(255, 0, 0), led1: Colour::rgb(255, 0, 0), led2: Colour::rgb(255, 0, 0), led3: Colour::rgb(255, 0, 0), led4: Colour::rgb(255, 0, 0), led5: Colour::rgb(255, 0, 0), led6: Colour::rgb(255, 0, 0), led7: Colour::rgb(255, 0, 0), led8: Colour::rgb(255, 0, 0), led9: Colour::rgb(255, 0, 0), }; let s = serde_urlencoded::to_string(&cols).expect("Urlencoding"); assert_eq!(s, "bas"); } }
pub fn demo() { println!("函数以snake case风格命名"); println!("{}", return_method()); } fn return_method() -> i32 { println!("函数当结尾不以分号结尾则为返回值"); 1 }
use crate::mock::*; use super::*; use hex_literal::hex; #[test] fn no_previous_chain() { ExtBuilder::default().build().execute_with(|| { assert_eq!(GenesisHistory::previous_chain(), Chain::default()); }) } #[test] fn some_previous_chain() { let chain = Chain { genesis_hash: vec![1,2,3].into(), last_block_hash: vec![6,6,6].into() }; ExtBuilder { chain: chain.clone() }.build().execute_with(|| { assert_eq!(GenesisHistory::previous_chain(), chain.clone()); }) } #[test] fn construct_using_hex() { let chain = Chain { genesis_hash: hex!["aa"].to_vec().into(), last_block_hash: hex!["bb"].to_vec().into() }; ExtBuilder { chain: chain.clone() }.build().execute_with(|| { assert_eq!(GenesisHistory::previous_chain(), chain.clone()); }) } #[test] fn sample_data() { let chain = Chain { genesis_hash: hex!["0ed32bfcab4a83517fac88f2aa7cbc2f88d3ab93be9a12b6188a036bf8a943c2"].to_vec().into(), last_block_hash: hex!["5800478f2cac4166d40c1ebe80dddbec47275d4b102f228b8a3af54d86d64837"].to_vec().into() }; ExtBuilder { chain: chain.clone() }.build().execute_with(|| { assert_eq!(GenesisHistory::previous_chain(), chain.clone()); }) }
#[doc = "Reader of register CR"] pub type R = crate::R<u32, super::CR>; #[doc = "Writer for register CR"] pub type W = crate::W<u32, super::CR>; #[doc = "Register CR `reset()`'s with value 0"] impl crate::ResetValue for super::CR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `DBG_SLEEP`"] pub type DBG_SLEEP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_SLEEP`"] pub struct DBG_SLEEP_W<'a> { w: &'a mut W, } impl<'a> DBG_SLEEP_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 `DBG_STOP`"] pub type DBG_STOP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_STOP`"] pub struct DBG_STOP_W<'a> { w: &'a mut W, } impl<'a> DBG_STOP_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 `DBG_STANDBY`"] pub type DBG_STANDBY_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_STANDBY`"] pub struct DBG_STANDBY_W<'a> { w: &'a mut W, } impl<'a> DBG_STANDBY_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 `TRACE_IOEN`"] pub type TRACE_IOEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TRACE_IOEN`"] pub struct TRACE_IOEN_W<'a> { w: &'a mut W, } impl<'a> TRACE_IOEN_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 `TRACE_MODE`"] pub type TRACE_MODE_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TRACE_MODE`"] pub struct TRACE_MODE_W<'a> { w: &'a mut W, } impl<'a> TRACE_MODE_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 6)) | (((value as u32) & 0x03) << 6); self.w } } #[doc = "Reader of field `DBG_IWDG_STOP`"] pub type DBG_IWDG_STOP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_IWDG_STOP`"] pub struct DBG_IWDG_STOP_W<'a> { w: &'a mut W, } impl<'a> DBG_IWDG_STOP_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 `DBG_WWDG_STOP`"] pub type DBG_WWDG_STOP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_WWDG_STOP`"] pub struct DBG_WWDG_STOP_W<'a> { w: &'a mut W, } impl<'a> DBG_WWDG_STOP_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 `DBG_TIM1_STOP`"] pub type DBG_TIM1_STOP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_TIM1_STOP`"] pub struct DBG_TIM1_STOP_W<'a> { w: &'a mut W, } impl<'a> DBG_TIM1_STOP_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 `DBG_TIM2_STOP`"] pub type DBG_TIM2_STOP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_TIM2_STOP`"] pub struct DBG_TIM2_STOP_W<'a> { w: &'a mut W, } impl<'a> DBG_TIM2_STOP_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 `DBG_TIM3_STOP`"] pub type DBG_TIM3_STOP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_TIM3_STOP`"] pub struct DBG_TIM3_STOP_W<'a> { w: &'a mut W, } impl<'a> DBG_TIM3_STOP_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 `DBG_TIM4_STOP`"] pub type DBG_TIM4_STOP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_TIM4_STOP`"] pub struct DBG_TIM4_STOP_W<'a> { w: &'a mut W, } impl<'a> DBG_TIM4_STOP_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 `DBG_I2C1_SMBUS_TIMEOUT`"] pub type DBG_I2C1_SMBUS_TIMEOUT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_I2C1_SMBUS_TIMEOUT`"] pub struct DBG_I2C1_SMBUS_TIMEOUT_W<'a> { w: &'a mut W, } impl<'a> DBG_I2C1_SMBUS_TIMEOUT_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 `DBG_I2C2_SMBUS_TIMEOUT`"] pub type DBG_I2C2_SMBUS_TIMEOUT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_I2C2_SMBUS_TIMEOUT`"] pub struct DBG_I2C2_SMBUS_TIMEOUT_W<'a> { w: &'a mut W, } impl<'a> DBG_I2C2_SMBUS_TIMEOUT_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 `DBG_TIM5_STOP`"] pub type DBG_TIM5_STOP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_TIM5_STOP`"] pub struct DBG_TIM5_STOP_W<'a> { w: &'a mut W, } impl<'a> DBG_TIM5_STOP_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 `DBG_TIM6_STOP`"] pub type DBG_TIM6_STOP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_TIM6_STOP`"] pub struct DBG_TIM6_STOP_W<'a> { w: &'a mut W, } impl<'a> DBG_TIM6_STOP_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 `DBG_TIM7_STOP`"] pub type DBG_TIM7_STOP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_TIM7_STOP`"] pub struct DBG_TIM7_STOP_W<'a> { w: &'a mut W, } impl<'a> DBG_TIM7_STOP_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 `DBG_TIM15_STOP`"] pub type DBG_TIM15_STOP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_TIM15_STOP`"] pub struct DBG_TIM15_STOP_W<'a> { w: &'a mut W, } impl<'a> DBG_TIM15_STOP_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 `DBG_TIM16_STOP`"] pub type DBG_TIM16_STOP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_TIM16_STOP`"] pub struct DBG_TIM16_STOP_W<'a> { w: &'a mut W, } impl<'a> DBG_TIM16_STOP_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 `DBG_TIM17_STOP`"] pub type DBG_TIM17_STOP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_TIM17_STOP`"] pub struct DBG_TIM17_STOP_W<'a> { w: &'a mut W, } impl<'a> DBG_TIM17_STOP_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 `DBG_TIM12_STOP`"] pub type DBG_TIM12_STOP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_TIM12_STOP`"] pub struct DBG_TIM12_STOP_W<'a> { w: &'a mut W, } impl<'a> DBG_TIM12_STOP_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 `DBG_TIM13_STOP`"] pub type DBG_TIM13_STOP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_TIM13_STOP`"] pub struct DBG_TIM13_STOP_W<'a> { w: &'a mut W, } impl<'a> DBG_TIM13_STOP_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 `DBG_TIM14_STOP`"] pub type DBG_TIM14_STOP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DBG_TIM14_STOP`"] pub struct DBG_TIM14_STOP_W<'a> { w: &'a mut W, } impl<'a> DBG_TIM14_STOP_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 } } impl R { #[doc = "Bit 0 - DBG_SLEEP"] #[inline(always)] pub fn dbg_sleep(&self) -> DBG_SLEEP_R { DBG_SLEEP_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - DBG_STOP"] #[inline(always)] pub fn dbg_stop(&self) -> DBG_STOP_R { DBG_STOP_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - DBG_STANDBY"] #[inline(always)] pub fn dbg_standby(&self) -> DBG_STANDBY_R { DBG_STANDBY_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 5 - TRACE_IOEN"] #[inline(always)] pub fn trace_ioen(&self) -> TRACE_IOEN_R { TRACE_IOEN_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bits 6:7 - TRACE_MODE"] #[inline(always)] pub fn trace_mode(&self) -> TRACE_MODE_R { TRACE_MODE_R::new(((self.bits >> 6) & 0x03) as u8) } #[doc = "Bit 8 - DBG_IWDG_STOP"] #[inline(always)] pub fn dbg_iwdg_stop(&self) -> DBG_IWDG_STOP_R { DBG_IWDG_STOP_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - DBG_WWDG_STOP"] #[inline(always)] pub fn dbg_wwdg_stop(&self) -> DBG_WWDG_STOP_R { DBG_WWDG_STOP_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - DBG_TIM1_STOP"] #[inline(always)] pub fn dbg_tim1_stop(&self) -> DBG_TIM1_STOP_R { DBG_TIM1_STOP_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - DBG_TIM2_STOP"] #[inline(always)] pub fn dbg_tim2_stop(&self) -> DBG_TIM2_STOP_R { DBG_TIM2_STOP_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - DBG_TIM3_STOP"] #[inline(always)] pub fn dbg_tim3_stop(&self) -> DBG_TIM3_STOP_R { DBG_TIM3_STOP_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - DBG_TIM4_STOP"] #[inline(always)] pub fn dbg_tim4_stop(&self) -> DBG_TIM4_STOP_R { DBG_TIM4_STOP_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 15 - DBG_I2C1_SMBUS_TIMEOUT"] #[inline(always)] pub fn dbg_i2c1_smbus_timeout(&self) -> DBG_I2C1_SMBUS_TIMEOUT_R { DBG_I2C1_SMBUS_TIMEOUT_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 16 - DBG_I2C2_SMBUS_TIMEOUT"] #[inline(always)] pub fn dbg_i2c2_smbus_timeout(&self) -> DBG_I2C2_SMBUS_TIMEOUT_R { DBG_I2C2_SMBUS_TIMEOUT_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 18 - DBG_TIM5_STOP"] #[inline(always)] pub fn dbg_tim5_stop(&self) -> DBG_TIM5_STOP_R { DBG_TIM5_STOP_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - DBG_TIM6_STOP"] #[inline(always)] pub fn dbg_tim6_stop(&self) -> DBG_TIM6_STOP_R { DBG_TIM6_STOP_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 20 - DBG_TIM7_STOP"] #[inline(always)] pub fn dbg_tim7_stop(&self) -> DBG_TIM7_STOP_R { DBG_TIM7_STOP_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 22 - DBG_TIM15_STOP"] #[inline(always)] pub fn dbg_tim15_stop(&self) -> DBG_TIM15_STOP_R { DBG_TIM15_STOP_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 23 - DBG_TIM16_STOP"] #[inline(always)] pub fn dbg_tim16_stop(&self) -> DBG_TIM16_STOP_R { DBG_TIM16_STOP_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 24 - DBG_TIM17_STOP"] #[inline(always)] pub fn dbg_tim17_stop(&self) -> DBG_TIM17_STOP_R { DBG_TIM17_STOP_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 25 - DBG_TIM12_STOP"] #[inline(always)] pub fn dbg_tim12_stop(&self) -> DBG_TIM12_STOP_R { DBG_TIM12_STOP_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 26 - DBG_TIM13_STOP"] #[inline(always)] pub fn dbg_tim13_stop(&self) -> DBG_TIM13_STOP_R { DBG_TIM13_STOP_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 27 - DBG_TIM14_STOP"] #[inline(always)] pub fn dbg_tim14_stop(&self) -> DBG_TIM14_STOP_R { DBG_TIM14_STOP_R::new(((self.bits >> 27) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - DBG_SLEEP"] #[inline(always)] pub fn dbg_sleep(&mut self) -> DBG_SLEEP_W { DBG_SLEEP_W { w: self } } #[doc = "Bit 1 - DBG_STOP"] #[inline(always)] pub fn dbg_stop(&mut self) -> DBG_STOP_W { DBG_STOP_W { w: self } } #[doc = "Bit 2 - DBG_STANDBY"] #[inline(always)] pub fn dbg_standby(&mut self) -> DBG_STANDBY_W { DBG_STANDBY_W { w: self } } #[doc = "Bit 5 - TRACE_IOEN"] #[inline(always)] pub fn trace_ioen(&mut self) -> TRACE_IOEN_W { TRACE_IOEN_W { w: self } } #[doc = "Bits 6:7 - TRACE_MODE"] #[inline(always)] pub fn trace_mode(&mut self) -> TRACE_MODE_W { TRACE_MODE_W { w: self } } #[doc = "Bit 8 - DBG_IWDG_STOP"] #[inline(always)] pub fn dbg_iwdg_stop(&mut self) -> DBG_IWDG_STOP_W { DBG_IWDG_STOP_W { w: self } } #[doc = "Bit 9 - DBG_WWDG_STOP"] #[inline(always)] pub fn dbg_wwdg_stop(&mut self) -> DBG_WWDG_STOP_W { DBG_WWDG_STOP_W { w: self } } #[doc = "Bit 10 - DBG_TIM1_STOP"] #[inline(always)] pub fn dbg_tim1_stop(&mut self) -> DBG_TIM1_STOP_W { DBG_TIM1_STOP_W { w: self } } #[doc = "Bit 11 - DBG_TIM2_STOP"] #[inline(always)] pub fn dbg_tim2_stop(&mut self) -> DBG_TIM2_STOP_W { DBG_TIM2_STOP_W { w: self } } #[doc = "Bit 12 - DBG_TIM3_STOP"] #[inline(always)] pub fn dbg_tim3_stop(&mut self) -> DBG_TIM3_STOP_W { DBG_TIM3_STOP_W { w: self } } #[doc = "Bit 13 - DBG_TIM4_STOP"] #[inline(always)] pub fn dbg_tim4_stop(&mut self) -> DBG_TIM4_STOP_W { DBG_TIM4_STOP_W { w: self } } #[doc = "Bit 15 - DBG_I2C1_SMBUS_TIMEOUT"] #[inline(always)] pub fn dbg_i2c1_smbus_timeout(&mut self) -> DBG_I2C1_SMBUS_TIMEOUT_W { DBG_I2C1_SMBUS_TIMEOUT_W { w: self } } #[doc = "Bit 16 - DBG_I2C2_SMBUS_TIMEOUT"] #[inline(always)] pub fn dbg_i2c2_smbus_timeout(&mut self) -> DBG_I2C2_SMBUS_TIMEOUT_W { DBG_I2C2_SMBUS_TIMEOUT_W { w: self } } #[doc = "Bit 18 - DBG_TIM5_STOP"] #[inline(always)] pub fn dbg_tim5_stop(&mut self) -> DBG_TIM5_STOP_W { DBG_TIM5_STOP_W { w: self } } #[doc = "Bit 19 - DBG_TIM6_STOP"] #[inline(always)] pub fn dbg_tim6_stop(&mut self) -> DBG_TIM6_STOP_W { DBG_TIM6_STOP_W { w: self } } #[doc = "Bit 20 - DBG_TIM7_STOP"] #[inline(always)] pub fn dbg_tim7_stop(&mut self) -> DBG_TIM7_STOP_W { DBG_TIM7_STOP_W { w: self } } #[doc = "Bit 22 - DBG_TIM15_STOP"] #[inline(always)] pub fn dbg_tim15_stop(&mut self) -> DBG_TIM15_STOP_W { DBG_TIM15_STOP_W { w: self } } #[doc = "Bit 23 - DBG_TIM16_STOP"] #[inline(always)] pub fn dbg_tim16_stop(&mut self) -> DBG_TIM16_STOP_W { DBG_TIM16_STOP_W { w: self } } #[doc = "Bit 24 - DBG_TIM17_STOP"] #[inline(always)] pub fn dbg_tim17_stop(&mut self) -> DBG_TIM17_STOP_W { DBG_TIM17_STOP_W { w: self } } #[doc = "Bit 25 - DBG_TIM12_STOP"] #[inline(always)] pub fn dbg_tim12_stop(&mut self) -> DBG_TIM12_STOP_W { DBG_TIM12_STOP_W { w: self } } #[doc = "Bit 26 - DBG_TIM13_STOP"] #[inline(always)] pub fn dbg_tim13_stop(&mut self) -> DBG_TIM13_STOP_W { DBG_TIM13_STOP_W { w: self } } #[doc = "Bit 27 - DBG_TIM14_STOP"] #[inline(always)] pub fn dbg_tim14_stop(&mut self) -> DBG_TIM14_STOP_W { DBG_TIM14_STOP_W { w: self } } }
// Copyright (c) 2017-present PyO3 Project and Contributors //! Python Number Interface //! Trait and support implementation for implementing number protocol use crate::callback::IntoPyCallbackOutput; use crate::{ffi, FromPyObject, PyClass, PyObject}; /// Number interface #[allow(unused_variables)] pub trait PyNumberProtocol<'p>: PyClass { fn __add__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberAddProtocol<'p>, { unimplemented!() } fn __sub__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberSubProtocol<'p>, { unimplemented!() } fn __mul__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberMulProtocol<'p>, { unimplemented!() } fn __matmul__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberMatmulProtocol<'p>, { unimplemented!() } fn __truediv__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberTruedivProtocol<'p>, { unimplemented!() } fn __floordiv__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberFloordivProtocol<'p>, { unimplemented!() } fn __mod__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberModProtocol<'p>, { unimplemented!() } fn __divmod__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberDivmodProtocol<'p>, { unimplemented!() } fn __pow__(lhs: Self::Left, rhs: Self::Right, modulo: Option<Self::Modulo>) -> Self::Result where Self: PyNumberPowProtocol<'p>, { unimplemented!() } fn __lshift__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberLShiftProtocol<'p>, { unimplemented!() } fn __rshift__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberRShiftProtocol<'p>, { unimplemented!() } fn __and__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberAndProtocol<'p>, { unimplemented!() } fn __xor__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberXorProtocol<'p>, { unimplemented!() } fn __or__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberOrProtocol<'p>, { unimplemented!() } fn __radd__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRAddProtocol<'p>, { unimplemented!() } fn __rsub__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRSubProtocol<'p>, { unimplemented!() } fn __rmul__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRMulProtocol<'p>, { unimplemented!() } fn __rmatmul__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRMatmulProtocol<'p>, { unimplemented!() } fn __rtruediv__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRTruedivProtocol<'p>, { unimplemented!() } fn __rfloordiv__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRFloordivProtocol<'p>, { unimplemented!() } fn __rmod__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRModProtocol<'p>, { unimplemented!() } fn __rdivmod__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRDivmodProtocol<'p>, { unimplemented!() } fn __rpow__(&'p self, other: Self::Other, modulo: Option<Self::Modulo>) -> Self::Result where Self: PyNumberRPowProtocol<'p>, { unimplemented!() } fn __rlshift__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRLShiftProtocol<'p>, { unimplemented!() } fn __rrshift__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRRShiftProtocol<'p>, { unimplemented!() } fn __rand__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRAndProtocol<'p>, { unimplemented!() } fn __rxor__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRXorProtocol<'p>, { unimplemented!() } fn __ror__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberROrProtocol<'p>, { unimplemented!() } fn __iadd__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIAddProtocol<'p>, { unimplemented!() } fn __isub__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberISubProtocol<'p>, { unimplemented!() } fn __imul__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIMulProtocol<'p>, { unimplemented!() } fn __imatmul__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIMatmulProtocol<'p>, { unimplemented!() } fn __itruediv__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberITruedivProtocol<'p>, { unimplemented!() } fn __ifloordiv__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIFloordivProtocol<'p>, { unimplemented!() } fn __imod__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIModProtocol<'p>, { unimplemented!() } fn __ipow__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIPowProtocol<'p>, { unimplemented!() } fn __ilshift__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberILShiftProtocol<'p>, { unimplemented!() } fn __irshift__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIRShiftProtocol<'p>, { unimplemented!() } fn __iand__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIAndProtocol<'p>, { unimplemented!() } fn __ixor__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIXorProtocol<'p>, { unimplemented!() } fn __ior__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIOrProtocol<'p>, { unimplemented!() } // Unary arithmetic fn __neg__(&'p self) -> Self::Result where Self: PyNumberNegProtocol<'p>, { unimplemented!() } fn __pos__(&'p self) -> Self::Result where Self: PyNumberPosProtocol<'p>, { unimplemented!() } fn __abs__(&'p self) -> Self::Result where Self: PyNumberAbsProtocol<'p>, { unimplemented!() } fn __invert__(&'p self) -> Self::Result where Self: PyNumberInvertProtocol<'p>, { unimplemented!() } fn __complex__(&'p self) -> Self::Result where Self: PyNumberComplexProtocol<'p>, { unimplemented!() } fn __int__(&'p self) -> Self::Result where Self: PyNumberIntProtocol<'p>, { unimplemented!() } fn __float__(&'p self) -> Self::Result where Self: PyNumberFloatProtocol<'p>, { unimplemented!() } fn __index__(&'p self) -> Self::Result where Self: PyNumberIndexProtocol<'p>, { unimplemented!() } fn __round__(&'p self, ndigits: Option<Self::NDigits>) -> Self::Result where Self: PyNumberRoundProtocol<'p>, { unimplemented!() } } pub trait PyNumberAddProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberSubProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberMulProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberMatmulProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberTruedivProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberFloordivProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberModProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberDivmodProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberPowProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Modulo: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberLShiftProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberRShiftProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberAndProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberXorProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberOrProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberRAddProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberRSubProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberRMulProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberRMatmulProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberRTruedivProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberRFloordivProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberRModProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberRDivmodProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberRPowProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Modulo: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberRLShiftProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberRRShiftProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberRAndProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberRXorProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberROrProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberIAddProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<()>; } pub trait PyNumberISubProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<()>; } pub trait PyNumberIMulProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<()>; } pub trait PyNumberIMatmulProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<()>; } pub trait PyNumberITruedivProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<()>; } pub trait PyNumberIFloordivProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<()>; } pub trait PyNumberIModProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<()>; } pub trait PyNumberIDivmodProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<()>; } pub trait PyNumberIPowProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<()>; } pub trait PyNumberILShiftProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<()>; } pub trait PyNumberIRShiftProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<()>; } pub trait PyNumberIAndProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<()>; } pub trait PyNumberIXorProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<()>; } pub trait PyNumberIOrProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: IntoPyCallbackOutput<()>; } pub trait PyNumberNegProtocol<'p>: PyNumberProtocol<'p> { type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberPosProtocol<'p>: PyNumberProtocol<'p> { type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberAbsProtocol<'p>: PyNumberProtocol<'p> { type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberInvertProtocol<'p>: PyNumberProtocol<'p> { type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberComplexProtocol<'p>: PyNumberProtocol<'p> { type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberIntProtocol<'p>: PyNumberProtocol<'p> { type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberFloatProtocol<'p>: PyNumberProtocol<'p> { type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberRoundProtocol<'p>: PyNumberProtocol<'p> { type NDigits: FromPyObject<'p>; type Result: IntoPyCallbackOutput<PyObject>; } pub trait PyNumberIndexProtocol<'p>: PyNumberProtocol<'p> { type Result: IntoPyCallbackOutput<PyObject>; } #[doc(hidden)] impl ffi::PyNumberMethods { pub(crate) fn from_nb_bool(nb_bool: ffi::inquiry) -> *mut Self { let mut nm = ffi::PyNumberMethods_INIT; nm.nb_bool = Some(nb_bool); Box::into_raw(Box::new(nm)) } pub fn set_add<T>(&mut self) where T: for<'p> PyNumberAddProtocol<'p>, { self.nb_add = py_binary_num_func!(PyNumberAddProtocol, T::__add__); } pub fn set_radd<T>(&mut self) where T: for<'p> PyNumberRAddProtocol<'p>, { self.nb_add = py_binary_reversed_num_func!(PyNumberRAddProtocol, T::__radd__); } pub fn set_sub<T>(&mut self) where T: for<'p> PyNumberSubProtocol<'p>, { self.nb_subtract = py_binary_num_func!(PyNumberSubProtocol, T::__sub__); } pub fn set_rsub<T>(&mut self) where T: for<'p> PyNumberRSubProtocol<'p>, { self.nb_subtract = py_binary_reversed_num_func!(PyNumberRSubProtocol, T::__rsub__); } pub fn set_mul<T>(&mut self) where T: for<'p> PyNumberMulProtocol<'p>, { self.nb_multiply = py_binary_num_func!(PyNumberMulProtocol, T::__mul__); } pub fn set_rmul<T>(&mut self) where T: for<'p> PyNumberRMulProtocol<'p>, { self.nb_multiply = py_binary_reversed_num_func!(PyNumberRMulProtocol, T::__rmul__); } pub fn set_mod<T>(&mut self) where T: for<'p> PyNumberModProtocol<'p>, { self.nb_remainder = py_binary_num_func!(PyNumberModProtocol, T::__mod__); } pub fn set_divmod<T>(&mut self) where T: for<'p> PyNumberDivmodProtocol<'p>, { self.nb_divmod = py_binary_num_func!(PyNumberDivmodProtocol, T::__divmod__); } pub fn set_rdivmod<T>(&mut self) where T: for<'p> PyNumberRDivmodProtocol<'p>, { self.nb_divmod = py_binary_reversed_num_func!(PyNumberRDivmodProtocol, T::__rdivmod__); } pub fn set_pow<T>(&mut self) where T: for<'p> PyNumberPowProtocol<'p>, { self.nb_power = py_ternary_num_func!(PyNumberPowProtocol, T::__pow__); } pub fn set_rpow<T>(&mut self) where T: for<'p> PyNumberRPowProtocol<'p>, { self.nb_power = py_ternary_reversed_num_func!(PyNumberRPowProtocol, T::__rpow__); } pub fn set_neg<T>(&mut self) where T: for<'p> PyNumberNegProtocol<'p>, { self.nb_negative = py_unary_func!(PyNumberNegProtocol, T::__neg__); } pub fn set_pos<T>(&mut self) where T: for<'p> PyNumberPosProtocol<'p>, { self.nb_positive = py_unary_func!(PyNumberPosProtocol, T::__pos__); } pub fn set_abs<T>(&mut self) where T: for<'p> PyNumberAbsProtocol<'p>, { self.nb_absolute = py_unary_func!(PyNumberAbsProtocol, T::__abs__); } pub fn set_invert<T>(&mut self) where T: for<'p> PyNumberInvertProtocol<'p>, { self.nb_invert = py_unary_func!(PyNumberInvertProtocol, T::__invert__); } pub fn set_lshift<T>(&mut self) where T: for<'p> PyNumberLShiftProtocol<'p>, { self.nb_lshift = py_binary_num_func!(PyNumberLShiftProtocol, T::__lshift__); } pub fn set_rlshift<T>(&mut self) where T: for<'p> PyNumberRLShiftProtocol<'p>, { self.nb_lshift = py_binary_reversed_num_func!(PyNumberRLShiftProtocol, T::__rlshift__); } pub fn set_rshift<T>(&mut self) where T: for<'p> PyNumberRShiftProtocol<'p>, { self.nb_rshift = py_binary_num_func!(PyNumberRShiftProtocol, T::__rshift__); } pub fn set_rrshift<T>(&mut self) where T: for<'p> PyNumberRRShiftProtocol<'p>, { self.nb_rshift = py_binary_reversed_num_func!(PyNumberRRShiftProtocol, T::__rrshift__); } pub fn set_and<T>(&mut self) where T: for<'p> PyNumberAndProtocol<'p>, { self.nb_and = py_binary_num_func!(PyNumberAndProtocol, T::__and__); } pub fn set_rand<T>(&mut self) where T: for<'p> PyNumberRAndProtocol<'p>, { self.nb_and = py_binary_reversed_num_func!(PyNumberRAndProtocol, T::__rand__); } pub fn set_xor<T>(&mut self) where T: for<'p> PyNumberXorProtocol<'p>, { self.nb_xor = py_binary_num_func!(PyNumberXorProtocol, T::__xor__); } pub fn set_rxor<T>(&mut self) where T: for<'p> PyNumberRXorProtocol<'p>, { self.nb_xor = py_binary_reversed_num_func!(PyNumberRXorProtocol, T::__rxor__); } pub fn set_or<T>(&mut self) where T: for<'p> PyNumberOrProtocol<'p>, { self.nb_or = py_binary_num_func!(PyNumberOrProtocol, T::__or__); } pub fn set_ror<T>(&mut self) where T: for<'p> PyNumberROrProtocol<'p>, { self.nb_or = py_binary_reversed_num_func!(PyNumberROrProtocol, T::__ror__); } pub fn set_int<T>(&mut self) where T: for<'p> PyNumberIntProtocol<'p>, { self.nb_int = py_unary_func!(PyNumberIntProtocol, T::__int__); } pub fn set_float<T>(&mut self) where T: for<'p> PyNumberFloatProtocol<'p>, { self.nb_float = py_unary_func!(PyNumberFloatProtocol, T::__float__); } pub fn set_iadd<T>(&mut self) where T: for<'p> PyNumberIAddProtocol<'p>, { self.nb_inplace_add = py_binary_self_func!(PyNumberIAddProtocol, T::__iadd__); } pub fn set_isub<T>(&mut self) where T: for<'p> PyNumberISubProtocol<'p>, { self.nb_inplace_subtract = py_binary_self_func!(PyNumberISubProtocol, T::__isub__); } pub fn set_imul<T>(&mut self) where T: for<'p> PyNumberIMulProtocol<'p>, { self.nb_inplace_multiply = py_binary_self_func!(PyNumberIMulProtocol, T::__imul__); } pub fn set_imod<T>(&mut self) where T: for<'p> PyNumberIModProtocol<'p>, { self.nb_inplace_remainder = py_binary_self_func!(PyNumberIModProtocol, T::__imod__); } pub fn set_ipow<T>(&mut self) where T: for<'p> PyNumberIPowProtocol<'p>, { self.nb_inplace_power = py_dummy_ternary_self_func!(PyNumberIPowProtocol, T::__ipow__) } pub fn set_ilshift<T>(&mut self) where T: for<'p> PyNumberILShiftProtocol<'p>, { self.nb_inplace_lshift = py_binary_self_func!(PyNumberILShiftProtocol, T::__ilshift__); } pub fn set_irshift<T>(&mut self) where T: for<'p> PyNumberIRShiftProtocol<'p>, { self.nb_inplace_rshift = py_binary_self_func!(PyNumberIRShiftProtocol, T::__irshift__); } pub fn set_iand<T>(&mut self) where T: for<'p> PyNumberIAndProtocol<'p>, { self.nb_inplace_and = py_binary_self_func!(PyNumberIAndProtocol, T::__iand__); } pub fn set_ixor<T>(&mut self) where T: for<'p> PyNumberIXorProtocol<'p>, { self.nb_inplace_xor = py_binary_self_func!(PyNumberIXorProtocol, T::__ixor__); } pub fn set_ior<T>(&mut self) where T: for<'p> PyNumberIOrProtocol<'p>, { self.nb_inplace_or = py_binary_self_func!(PyNumberIOrProtocol, T::__ior__); } pub fn set_floordiv<T>(&mut self) where T: for<'p> PyNumberFloordivProtocol<'p>, { self.nb_floor_divide = py_binary_num_func!(PyNumberFloordivProtocol, T::__floordiv__); } pub fn set_rfloordiv<T>(&mut self) where T: for<'p> PyNumberRFloordivProtocol<'p>, { self.nb_floor_divide = py_binary_reversed_num_func!(PyNumberRFloordivProtocol, T::__rfloordiv__); } pub fn set_truediv<T>(&mut self) where T: for<'p> PyNumberTruedivProtocol<'p>, { self.nb_true_divide = py_binary_num_func!(PyNumberTruedivProtocol, T::__truediv__); } pub fn set_rtruediv<T>(&mut self) where T: for<'p> PyNumberRTruedivProtocol<'p>, { self.nb_true_divide = py_binary_reversed_num_func!(PyNumberRTruedivProtocol, T::__rtruediv__); } pub fn set_ifloordiv<T>(&mut self) where T: for<'p> PyNumberIFloordivProtocol<'p>, { self.nb_inplace_floor_divide = py_binary_self_func!(PyNumberIFloordivProtocol, T::__ifloordiv__); } pub fn set_itruediv<T>(&mut self) where T: for<'p> PyNumberITruedivProtocol<'p>, { self.nb_inplace_true_divide = py_binary_self_func!(PyNumberITruedivProtocol, T::__itruediv__); } pub fn set_index<T>(&mut self) where T: for<'p> PyNumberIndexProtocol<'p>, { self.nb_index = py_unary_func!(PyNumberIndexProtocol, T::__index__); } pub fn set_matmul<T>(&mut self) where T: for<'p> PyNumberMatmulProtocol<'p>, { self.nb_matrix_multiply = py_binary_num_func!(PyNumberMatmulProtocol, T::__matmul__); } pub fn set_rmatmul<T>(&mut self) where T: for<'p> PyNumberRMatmulProtocol<'p>, { self.nb_matrix_multiply = py_binary_reversed_num_func!(PyNumberRMatmulProtocol, T::__rmatmul__); } pub fn set_imatmul<T>(&mut self) where T: for<'p> PyNumberIMatmulProtocol<'p>, { self.nb_inplace_matrix_multiply = py_binary_self_func!(PyNumberIMatmulProtocol, T::__imatmul__); } }
use lazy_static::lazy_static; use std::{ops, sync::Arc}; /// Docker client pub struct Client { inner_client: Arc<shiplift::Docker>, } impl Client { /// Construct a new unique Docker Client. Unless you know you need /// a unique Client, you should probably `use Client::default()` which /// uses a global Docker client internally pub fn new() -> Self { Self { inner_client: Arc::new(shiplift::Docker::new()), } } } impl Default for Client { /// Construct a new Docker Client. Internally this client uses a globally /// shared client with a connection pool. fn default() -> Self { global_client() } } impl ops::Deref for Client { type Target = shiplift::Docker; fn deref(&self) -> &Self::Target { &self.inner_client } } impl From<shiplift::Docker> for Client { /// Create a new Docker Client from a shiplift::Docker object /// /// # Example /// ``` /// use harbourmaster::Client; /// /// let client = Client::from(shiplift::Docker::new()); /// ``` fn from(docker: shiplift::Docker) -> Self { Client { inner_client: Arc::new(docker), } } } impl From<Arc<shiplift::Docker>> for Client { fn from(inner_client: Arc<shiplift::Docker>) -> Self { Client { inner_client } } } impl From<&Arc<shiplift::Docker>> for Client { fn from(inner_client: &Arc<shiplift::Docker>) -> Self { Client { inner_client: Arc::clone(inner_client), } } } impl From<&Client> for Client { fn from(client: &Client) -> Self { Client { inner_client: Arc::clone(&client.inner_client), } } } lazy_static! { static ref CLIENT: Client = Client::new(); } fn global_client() -> Client { let r: &Client = &CLIENT; Client::from(r) }
//! To run this code, clone the rusty_engine repository and run the command: //! //! cargo run --release --example music //! This is an example of playing a music preset. For playing your own music file, please see the //! `sound` example. use rusty_engine::prelude::*; fn main() { let mut game = Game::new(); let msg = game.add_text( "msg", "You can play looping music presets that are included in the asset pack. For example:", ); msg.translation.y = 50.0; let msg2 = game.add_text( "msg2", "engine.audio_manager.play_music(MusicPreset::Classy8Bit, 1.0);", ); msg2.translation.y = -50.0; msg2.font = "font/FiraMono-Medium.ttf".to_string(); game.audio_manager.play_music(MusicPreset::Classy8Bit, 1.0); game.run(()); }
use std::process::Command; use std::str; use dialoguer::PasswordInput; use super::cli; pub fn read_access_token() -> String { //! Reads in a user's personal access token from GitHub. println!("Please paste your personal access token from GitHub below."); PasswordInput::new() .with_prompt("Token") .interact() .expect("Failed to read token") } pub fn is_git_repo() -> bool { //! Returns whether the current repo is a git repository. let command = Command::new("git") .arg("status") .output() .expect("Failed to execute `git status`"); let output = str::from_utf8(&command.stdout).unwrap().trim(); !output.is_empty() } pub fn get_remote_name(is_dry_run: bool) -> Option<String> { //! Executes the command `git remote get-url origin`. //! Parses the result to return a string of the form :username/:repo //! if successful. Otherwise, returns None if there is no remote. let command = Command::new("git") .arg("remote") .arg("get-url") .arg("origin") .output() .expect("Failed to execute `git remote get-url origin`"); let output = str::from_utf8(&command.stdout).unwrap(); // Output is of the form https://github.com/:username/:repo.git // So we must remove the protocol/domain and .git suffix. let split: Vec<&str> = output.split("github.com/").collect(); if split.len() < 2 { match is_dry_run { true => { cli::print_warning( "No remote found. Searching for TODOs anyways.", ); return Some(String::new()); } false => { cli::print_error("No remote found."); return None; } } } let remote = split[1].to_string(); let vec: Vec<&str> = remote.split(".git").collect(); Some(vec[0].to_string()) } pub fn get_tracked_files() -> Vec<String> { //! Executes the command `git ls-tree -r {branch} --name-only`. //! Parses the output to return a vector of file paths that represents //! all files tracked by git. let branch = get_branch_name(); let command = Command::new("git") .arg("ls-tree") .arg("-r") .arg(branch) .arg("--name-only") .output() .expect("Failed to execute `git ls-tree -r master --name-only`"); let output = str::from_utf8(&command.stdout).unwrap(); let files: Vec<&str> = output.split("\n").collect(); files .into_iter() .map(|string| string.to_string()) .filter(|string| !string.is_empty()) .collect() } fn get_branch_name() -> String { //! Executes the command `git rev-parse --abbrev-ref HEAD`. //! Returns the output which represents the current branch the user is on. let command = Command::new("git") .arg("rev-parse") .arg("--abbrev-ref") .arg("HEAD") .output() .expect("Failed to execute `git rev-parse --abbrev-ref HEAD`"); let output = str::from_utf8(&command.stdout).unwrap(); output.trim().to_string() }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::EISC { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct EPI_EISC_TOUTR { bits: bool, } impl EPI_EISC_TOUTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_EISC_TOUTW<'a> { w: &'a mut W, } impl<'a> _EPI_EISC_TOUTW<'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 &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct EPI_EISC_RSTALLR { bits: bool, } impl EPI_EISC_RSTALLR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_EISC_RSTALLW<'a> { w: &'a mut W, } impl<'a> _EPI_EISC_RSTALLW<'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 &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct EPI_EISC_WTFULLR { bits: bool, } impl EPI_EISC_WTFULLR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_EISC_WTFULLW<'a> { w: &'a mut W, } impl<'a> _EPI_EISC_WTFULLW<'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 &= !(1 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct EPI_EISC_DMARDICR { bits: bool, } impl EPI_EISC_DMARDICR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_EISC_DMARDICW<'a> { w: &'a mut W, } impl<'a> _EPI_EISC_DMARDICW<'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 &= !(1 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct EPI_EISC_DMAWRICR { bits: bool, } impl EPI_EISC_DMAWRICR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_EISC_DMAWRICW<'a> { w: &'a mut W, } impl<'a> _EPI_EISC_DMAWRICW<'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 &= !(1 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Timeout Error"] #[inline(always)] pub fn epi_eisc_tout(&self) -> EPI_EISC_TOUTR { let bits = ((self.bits >> 0) & 1) != 0; EPI_EISC_TOUTR { bits } } #[doc = "Bit 1 - Read Stalled Error"] #[inline(always)] pub fn epi_eisc_rstall(&self) -> EPI_EISC_RSTALLR { let bits = ((self.bits >> 1) & 1) != 0; EPI_EISC_RSTALLR { bits } } #[doc = "Bit 2 - Write FIFO Full Error"] #[inline(always)] pub fn epi_eisc_wtfull(&self) -> EPI_EISC_WTFULLR { let bits = ((self.bits >> 2) & 1) != 0; EPI_EISC_WTFULLR { bits } } #[doc = "Bit 3 - Read uDMA Interrupt Clear"] #[inline(always)] pub fn epi_eisc_dmardic(&self) -> EPI_EISC_DMARDICR { let bits = ((self.bits >> 3) & 1) != 0; EPI_EISC_DMARDICR { bits } } #[doc = "Bit 4 - Write uDMA Interrupt Clear"] #[inline(always)] pub fn epi_eisc_dmawric(&self) -> EPI_EISC_DMAWRICR { let bits = ((self.bits >> 4) & 1) != 0; EPI_EISC_DMAWRICR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Timeout Error"] #[inline(always)] pub fn epi_eisc_tout(&mut self) -> _EPI_EISC_TOUTW { _EPI_EISC_TOUTW { w: self } } #[doc = "Bit 1 - Read Stalled Error"] #[inline(always)] pub fn epi_eisc_rstall(&mut self) -> _EPI_EISC_RSTALLW { _EPI_EISC_RSTALLW { w: self } } #[doc = "Bit 2 - Write FIFO Full Error"] #[inline(always)] pub fn epi_eisc_wtfull(&mut self) -> _EPI_EISC_WTFULLW { _EPI_EISC_WTFULLW { w: self } } #[doc = "Bit 3 - Read uDMA Interrupt Clear"] #[inline(always)] pub fn epi_eisc_dmardic(&mut self) -> _EPI_EISC_DMARDICW { _EPI_EISC_DMARDICW { w: self } } #[doc = "Bit 4 - Write uDMA Interrupt Clear"] #[inline(always)] pub fn epi_eisc_dmawric(&mut self) -> _EPI_EISC_DMAWRICW { _EPI_EISC_DMAWRICW { w: self } } }
#[macro_use] extern crate ruru; extern crate hyper; pub mod server; pub mod ruby_utils; use ruru::VM; #[no_mangle] pub extern fn initialize_busy() { // VM::require("rack/builder"); server::init(); }
// Copyright 2021 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_base::base::escape_for_key; use common_exception::ErrorCode; use common_exception::Result; use common_meta_app::principal::UserIdentity; use common_meta_app::principal::UserInfo; use common_meta_kvapi::kvapi; use common_meta_kvapi::kvapi::UpsertKVReq; use common_meta_types::MatchSeq; use common_meta_types::MatchSeqExt; use common_meta_types::MetaError; use common_meta_types::Operation; use common_meta_types::SeqV; use crate::serde::deserialize_struct; use crate::serde::serialize_struct; use crate::user::user_api::UserApi; static USER_API_KEY_PREFIX: &str = "__fd_users"; pub struct UserMgr { kv_api: Arc<dyn kvapi::KVApi<Error = MetaError>>, user_prefix: String, } impl UserMgr { pub fn create(kv_api: Arc<dyn kvapi::KVApi<Error = MetaError>>, tenant: &str) -> Result<Self> { if tenant.is_empty() { return Err(ErrorCode::TenantIsEmpty( "Tenant can not empty(while user mgr create)", )); } Ok(UserMgr { kv_api, user_prefix: format!("{}/{}", USER_API_KEY_PREFIX, escape_for_key(tenant)?), }) } async fn upsert_user_info( &self, user_info: &UserInfo, seq: MatchSeq, ) -> common_exception::Result<u64> { let user_key = format_user_key(&user_info.name, &user_info.hostname); let key = format!("{}/{}", self.user_prefix, escape_for_key(&user_key)?); let value = serialize_struct(user_info, ErrorCode::IllegalUserInfoFormat, || "")?; let kv_api = self.kv_api.clone(); let res = kv_api .upsert_kv(UpsertKVReq::new(&key, seq, Operation::Update(value), None)) .await?; match res.result { Some(SeqV { seq: s, .. }) => Ok(s), None => Err(ErrorCode::UnknownUser(format!( "unknown user, or seq not match {}", user_info.name ))), } } } #[async_trait::async_trait] impl UserApi for UserMgr { async fn add_user(&self, user_info: UserInfo) -> common_exception::Result<u64> { let user_identity = UserIdentity::new(&user_info.name, &user_info.hostname); if user_identity.is_root() { return Err(ErrorCode::UserAlreadyExists(format!( "User cannot be created with builtin user name {}", user_info.name ))); } let match_seq = MatchSeq::Exact(0); let user_key = format_user_key(&user_info.name, &user_info.hostname); let key = format!("{}/{}", self.user_prefix, escape_for_key(&user_key)?); let value = serialize_struct(&user_info, ErrorCode::IllegalUserInfoFormat, || "")?; let kv_api = self.kv_api.clone(); let upsert_kv = kv_api.upsert_kv(UpsertKVReq::new( &key, match_seq, Operation::Update(value), None, )); let res = upsert_kv.await?.added_or_else(|v| { ErrorCode::UserAlreadyExists(format!("User already exists, seq [{}]", v.seq)) })?; Ok(res.seq) } async fn get_user(&self, user: UserIdentity, seq: MatchSeq) -> Result<SeqV<UserInfo>> { let user_key = format_user_key(&user.username, &user.hostname); let key = format!("{}/{}", self.user_prefix, escape_for_key(&user_key)?); let res = self.kv_api.get_kv(&key).await?; let seq_value = res.ok_or_else(|| ErrorCode::UnknownUser(format!("unknown user {}", user_key)))?; match seq.match_seq(&seq_value) { Ok(_) => Ok(SeqV::new( seq_value.seq, deserialize_struct(&seq_value.data, ErrorCode::IllegalUserInfoFormat, || "")?, )), Err(_) => Err(ErrorCode::UnknownUser(format!("unknown user {}", user_key))), } } async fn get_users(&self) -> Result<Vec<SeqV<UserInfo>>> { let user_prefix = self.user_prefix.clone(); let values = self.kv_api.prefix_list_kv(user_prefix.as_str()).await?; let mut r = vec![]; for (_key, val) in values { let u = deserialize_struct(&val.data, ErrorCode::IllegalUserInfoFormat, || "")?; r.push(SeqV::new(val.seq, u)); } Ok(r) } async fn update_user_with<F>( &self, user: UserIdentity, seq: MatchSeq, f: F, ) -> Result<Option<u64>> where F: FnOnce(&mut UserInfo) + Send, { let SeqV { seq, data: mut user_info, .. } = self.get_user(user, seq).await?; f(&mut user_info); let seq = self .upsert_user_info(&user_info, MatchSeq::Exact(seq)) .await?; Ok(Some(seq)) } async fn drop_user(&self, user: UserIdentity, seq: MatchSeq) -> Result<()> { let user_key = format_user_key(&user.username, &user.hostname); let key = format!("{}/{}", self.user_prefix, escape_for_key(&user_key)?); let res = self .kv_api .upsert_kv(UpsertKVReq::new(&key, seq, Operation::Delete, None)) .await?; if res.prev.is_some() && res.result.is_none() { Ok(()) } else { Err(ErrorCode::UnknownUser(format!("unknown user {}", user_key))) } } } fn format_user_key(username: &str, hostname: &str) -> String { format!("'{}'@'{}'", username, hostname) }
#![feature(iter_array_chunks)] use std::collections::{HashMap, HashSet}; fn priority(item: u8) -> u8 { let base = if item.is_ascii_lowercase() { b'a' } else { b'A' - 26 }; (item - base) + 1 } type Rucksack<'a> = (&'a [u8], &'a [u8]); fn rucksack(input: &[u8]) -> Rucksack { let middle = input.len() / 2; input.split_at(middle) } fn rucksacks(input: &str) -> impl Iterator<Item = Rucksack> { input.lines().map(|l| rucksack(l.as_bytes())) } fn part1(input: &str) -> u32 { rucksacks(input) .map(|(fst, sec)| { let fst: HashSet<u8> = fst.iter().cloned().collect(); let sec: HashSet<u8> = sec.iter().cloned().collect(); fst.intersection(&sec) .map(|item| priority(*item) as u32) .sum::<u32>() }) .sum() } type Group<'a> = [&'a [u8]; 3]; fn groups(input: &str) -> impl Iterator<Item = Group> { input.lines().map(|l| l.as_bytes()).array_chunks() } fn part2(input: &str) -> u32 { groups(input) .map(|group| { let mut counts: HashMap<u8, u8> = HashMap::new(); for sack in group { let set: HashSet<u8> = sack.iter().cloned().collect(); for item in set { *counts.entry(item).or_insert(0) += 1; } } counts .into_iter() .filter_map(|(k, v)| (v == 3).then(|| priority(k) as u32)) .sum::<u32>() }) .sum() } #[cfg(test)] const TEST_INPUT: &str = "\ vJrwpWtwJgWrhcsFMMfFFhFp jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL PmmdzqPrVvPwwTWBwg wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn ttgJtRGJQctTZtZT CrZsJsPPZsGzwwsLwLmpwMDw"; aoc::tests! { fn priority: b'a' => 1; b'z' => 26; b'A' => 27; b'Z' => 52; fn rucksack: b"vJrwpWtwJgWrhcsFMMfFFhFp" => (b"vJrwpWtwJgWr".as_slice(), b"hcsFMMfFFhFp".as_slice()); fn part1: TEST_INPUT => 157; in => 8233; fn part2: TEST_INPUT => 70; in => 2821; } aoc::main!(part1, part2);
use std::collections::HashMap; use std::fs; fn main() { const PART: u8 = 2; const MAX_DIR: u8 = 4; let mut cur_dir = 0; let input = fs::read_to_string("inputs/day1.txt").unwrap(); //let input = "R8, R4, R4, R8"; let toks = input .split(",") .map(|s| s.trim().to_string()) .collect::<Vec<String>>(); let mut x = 0; let mut y = 0; let mut visits: HashMap<(i32, i32), u8> = HashMap::new(); visits.insert((x, y), 1); let mut done = false; let mut loc: (i32, i32) = (0, 0); for i in &toks { let lr = &i[0..1]; match lr { "L" => { cur_dir = (cur_dir - 1) % MAX_DIR; } "R" => { cur_dir = (cur_dir + 1) % MAX_DIR; } _ => {} } let steps = i[1..].parse::<i32>().unwrap(); let old_x = x; let old_y = y; match cur_dir { 0 => { y -= steps; if PART == 2 { for ny in y..old_y { if visits.contains_key(&(x, ny)) { done = true; loc = (x, ny); break; } visits.insert((x, ny), 1); } } } 1 => { x += steps; if PART == 2 { for nx in old_x + 1..x + 1 { if visits.contains_key(&(nx, y)) { done = true; loc = (nx, y); break; } visits.insert((nx, y), 1); } } } 2 => { y += steps; if PART == 2 { for ny in old_y + 1..y + 1 { if visits.contains_key(&(x, ny)) { done = true; loc = (x, ny); break; } visits.insert((x, ny), 1); } } } 3 => { x -= steps; if PART == 2 { for nx in x..old_x { if visits.contains_key(&(nx, y)) { done = true; loc = (nx, y); break; } visits.insert((nx, y), 1); } } } _ => { panic!("bad dir"); } } if done { break; } } if PART == 1 { let distance = x.abs() + y.abs(); println!("distance: {}", distance); } if PART == 2 { let distance = loc.0.abs() + loc.1.abs(); println!("distance: {}", distance); } }
use std::io::Read; fn read<T: std::str::FromStr>() -> T { let token: String = std::io::stdin() .bytes() .map(|c| c.ok().unwrap() as char) .skip_while(|c| c.is_whitespace()) .take_while(|c| !c.is_whitespace()) .collect(); token.parse().ok().unwrap() } fn main() { let mut n: i32 = read(); let mut i1 = 0; let mut mx = n; while n != 1 { if n % 2 == 0 { n = n / 2; } else { n = n * 3 + 1; } i1 += 1; mx = std::cmp::max(mx, n); } println!("{}", i1); println!("{}", mx); }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppListEntry(pub ::windows::core::IInspectable); impl AppListEntry { pub fn DisplayInfo(&self) -> ::windows::core::Result<super::AppDisplayInfo> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::AppDisplayInfo>(result__) } } #[cfg(feature = "Foundation")] pub fn LaunchAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } pub fn AppUserModelId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IAppListEntry2>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(all(feature = "Foundation", feature = "System"))] pub fn LaunchForUserAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::System::User>>(&self, user: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = &::windows::core::Interface::cast::<IAppListEntry3>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), user.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } pub fn AppInfo(&self) -> ::windows::core::Result<super::AppInfo> { let this = &::windows::core::Interface::cast::<IAppListEntry4>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::AppInfo>(result__) } } } unsafe impl ::windows::core::RuntimeType for AppListEntry { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Core.AppListEntry;{ef00f07f-2108-490a-877a-8a9f17c25fad})"); } unsafe impl ::windows::core::Interface for AppListEntry { type Vtable = IAppListEntry_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xef00f07f_2108_490a_877a_8a9f17c25fad); } impl ::windows::core::RuntimeName for AppListEntry { const NAME: &'static str = "Windows.ApplicationModel.Core.AppListEntry"; } impl ::core::convert::From<AppListEntry> for ::windows::core::IUnknown { fn from(value: AppListEntry) -> Self { value.0 .0 } } impl ::core::convert::From<&AppListEntry> for ::windows::core::IUnknown { fn from(value: &AppListEntry) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppListEntry { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a AppListEntry { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AppListEntry> for ::windows::core::IInspectable { fn from(value: AppListEntry) -> Self { value.0 } } impl ::core::convert::From<&AppListEntry> for ::windows::core::IInspectable { fn from(value: &AppListEntry) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppListEntry { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a AppListEntry { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AppListEntry {} unsafe impl ::core::marker::Sync for AppListEntry {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AppRestartFailureReason(pub i32); impl AppRestartFailureReason { pub const RestartPending: AppRestartFailureReason = AppRestartFailureReason(0i32); pub const NotInForeground: AppRestartFailureReason = AppRestartFailureReason(1i32); pub const InvalidUser: AppRestartFailureReason = AppRestartFailureReason(2i32); pub const Other: AppRestartFailureReason = AppRestartFailureReason(3i32); } impl ::core::convert::From<i32> for AppRestartFailureReason { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AppRestartFailureReason { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AppRestartFailureReason { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Core.AppRestartFailureReason;i4)"); } impl ::windows::core::DefaultType for AppRestartFailureReason { type DefaultType = Self; } pub struct CoreApplication {} impl CoreApplication { pub fn Id() -> ::windows::core::Result<::windows::core::HSTRING> { Self::ICoreApplication(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } #[cfg(feature = "Foundation")] pub fn Suspending<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventHandler<super::SuspendingEventArgs>>>(handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { Self::ICoreApplication(|this| unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) }) } #[cfg(feature = "Foundation")] pub fn RemoveSuspending<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(token: Param0) -> ::windows::core::Result<()> { Self::ICoreApplication(|this| unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }) } #[cfg(feature = "Foundation")] pub fn Resuming<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventHandler<::windows::core::IInspectable>>>(handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { Self::ICoreApplication(|this| unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) }) } #[cfg(feature = "Foundation")] pub fn RemoveResuming<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(token: Param0) -> ::windows::core::Result<()> { Self::ICoreApplication(|this| unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }) } #[cfg(feature = "Foundation_Collections")] pub fn Properties() -> ::windows::core::Result<super::super::Foundation::Collections::IPropertySet> { Self::ICoreApplication(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IPropertySet>(result__) }) } pub fn GetCurrentView() -> ::windows::core::Result<CoreApplicationView> { Self::ICoreApplication(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<CoreApplicationView>(result__) }) } pub fn Run<'a, Param0: ::windows::core::IntoParam<'a, IFrameworkViewSource>>(viewsource: Param0) -> ::windows::core::Result<()> { Self::ICoreApplication(|this| unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), viewsource.into_param().abi()).ok() }) } #[cfg(feature = "Foundation")] pub fn RunWithActivationFactories<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::IGetActivationFactory>>(activationfactorycallback: Param0) -> ::windows::core::Result<()> { Self::ICoreApplication(|this| unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), activationfactorycallback.into_param().abi()).ok() }) } pub fn Exit() -> ::windows::core::Result<()> { Self::ICoreApplicationExit(|this| unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }) } #[cfg(feature = "Foundation")] pub fn Exiting<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventHandler<::windows::core::IInspectable>>>(handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { Self::ICoreApplicationExit(|this| unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) }) } #[cfg(feature = "Foundation")] pub fn RemoveExiting<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(token: Param0) -> ::windows::core::Result<()> { Self::ICoreApplicationExit(|this| unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }) } #[cfg(feature = "Foundation")] pub fn UnhandledErrorDetected<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventHandler<UnhandledErrorDetectedEventArgs>>>(handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { Self::ICoreApplicationUnhandledError(|this| unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) }) } #[cfg(feature = "Foundation")] pub fn RemoveUnhandledErrorDetected<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(token: Param0) -> ::windows::core::Result<()> { Self::ICoreApplicationUnhandledError(|this| unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }) } pub fn IncrementApplicationUseCount() -> ::windows::core::Result<()> { Self::ICoreApplicationUseCount(|this| unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }) } pub fn DecrementApplicationUseCount() -> ::windows::core::Result<()> { Self::ICoreApplicationUseCount(|this| unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this)).ok() }) } #[cfg(feature = "Foundation_Collections")] pub fn Views() -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<CoreApplicationView>> { Self::ICoreImmersiveApplication(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<CoreApplicationView>>(result__) }) } pub fn CreateNewView<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(runtimetype: Param0, entrypoint: Param1) -> ::windows::core::Result<CoreApplicationView> { Self::ICoreImmersiveApplication(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), runtimetype.into_param().abi(), entrypoint.into_param().abi(), &mut result__).from_abi::<CoreApplicationView>(result__) }) } pub fn MainView() -> ::windows::core::Result<CoreApplicationView> { Self::ICoreImmersiveApplication(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<CoreApplicationView>(result__) }) } pub fn CreateNewViewFromMainView() -> ::windows::core::Result<CoreApplicationView> { Self::ICoreImmersiveApplication2(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<CoreApplicationView>(result__) }) } pub fn CreateNewViewWithViewSource<'a, Param0: ::windows::core::IntoParam<'a, IFrameworkViewSource>>(viewsource: Param0) -> ::windows::core::Result<CoreApplicationView> { Self::ICoreImmersiveApplication3(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), viewsource.into_param().abi(), &mut result__).from_abi::<CoreApplicationView>(result__) }) } #[cfg(all(feature = "ApplicationModel_Activation", feature = "Foundation"))] pub fn BackgroundActivated<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventHandler<super::Activation::BackgroundActivatedEventArgs>>>(handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { Self::ICoreApplication2(|this| unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) }) } #[cfg(feature = "Foundation")] pub fn RemoveBackgroundActivated<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(token: Param0) -> ::windows::core::Result<()> { Self::ICoreApplication2(|this| unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }) } #[cfg(feature = "Foundation")] pub fn LeavingBackground<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventHandler<super::LeavingBackgroundEventArgs>>>(handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { Self::ICoreApplication2(|this| unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) }) } #[cfg(feature = "Foundation")] pub fn RemoveLeavingBackground<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(token: Param0) -> ::windows::core::Result<()> { Self::ICoreApplication2(|this| unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }) } #[cfg(feature = "Foundation")] pub fn EnteredBackground<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventHandler<super::EnteredBackgroundEventArgs>>>(handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { Self::ICoreApplication2(|this| unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) }) } #[cfg(feature = "Foundation")] pub fn RemoveEnteredBackground<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(token: Param0) -> ::windows::core::Result<()> { Self::ICoreApplication2(|this| unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }) } pub fn EnablePrelaunch(value: bool) -> ::windows::core::Result<()> { Self::ICoreApplication2(|this| unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value).ok() }) } #[cfg(feature = "Foundation")] pub fn RequestRestartAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(launcharguments: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AppRestartFailureReason>> { Self::ICoreApplication3(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), launcharguments.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AppRestartFailureReason>>(result__) }) } #[cfg(all(feature = "Foundation", feature = "System"))] pub fn RequestRestartForUserAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::System::User>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(user: Param0, launcharguments: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AppRestartFailureReason>> { Self::ICoreApplication3(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), user.into_param().abi(), launcharguments.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AppRestartFailureReason>>(result__) }) } pub fn ICoreApplication<R, F: FnOnce(&ICoreApplication) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<CoreApplication, ICoreApplication> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn ICoreApplicationExit<R, F: FnOnce(&ICoreApplicationExit) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<CoreApplication, ICoreApplicationExit> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn ICoreApplicationUnhandledError<R, F: FnOnce(&ICoreApplicationUnhandledError) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<CoreApplication, ICoreApplicationUnhandledError> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn ICoreApplicationUseCount<R, F: FnOnce(&ICoreApplicationUseCount) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<CoreApplication, ICoreApplicationUseCount> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn ICoreImmersiveApplication<R, F: FnOnce(&ICoreImmersiveApplication) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<CoreApplication, ICoreImmersiveApplication> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn ICoreImmersiveApplication2<R, F: FnOnce(&ICoreImmersiveApplication2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<CoreApplication, ICoreImmersiveApplication2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn ICoreImmersiveApplication3<R, F: FnOnce(&ICoreImmersiveApplication3) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<CoreApplication, ICoreImmersiveApplication3> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn ICoreApplication2<R, F: FnOnce(&ICoreApplication2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<CoreApplication, ICoreApplication2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn ICoreApplication3<R, F: FnOnce(&ICoreApplication3) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<CoreApplication, ICoreApplication3> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for CoreApplication { const NAME: &'static str = "Windows.ApplicationModel.Core.CoreApplication"; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct CoreApplicationView(pub ::windows::core::IInspectable); impl CoreApplicationView { #[cfg(feature = "UI_Core")] pub fn CoreWindow(&self) -> ::windows::core::Result<super::super::UI::Core::CoreWindow> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::UI::Core::CoreWindow>(result__) } } #[cfg(all(feature = "ApplicationModel_Activation", feature = "Foundation"))] pub fn Activated<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<CoreApplicationView, super::Activation::IActivatedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveActivated<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } pub fn IsMain(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsHosted(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "UI_Core")] pub fn Dispatcher(&self) -> ::windows::core::Result<super::super::UI::Core::CoreDispatcher> { let this = &::windows::core::Interface::cast::<ICoreApplicationView2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::UI::Core::CoreDispatcher>(result__) } } pub fn IsComponent(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<ICoreApplicationView3>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn TitleBar(&self) -> ::windows::core::Result<CoreApplicationViewTitleBar> { let this = &::windows::core::Interface::cast::<ICoreApplicationView3>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<CoreApplicationViewTitleBar>(result__) } } #[cfg(feature = "Foundation")] pub fn HostedViewClosing<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<CoreApplicationView, HostedViewClosingEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = &::windows::core::Interface::cast::<ICoreApplicationView3>(self)?; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveHostedViewClosing<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<ICoreApplicationView3>(self)?; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "Foundation_Collections")] pub fn Properties(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IPropertySet> { let this = &::windows::core::Interface::cast::<ICoreApplicationView5>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IPropertySet>(result__) } } #[cfg(feature = "System")] pub fn DispatcherQueue(&self) -> ::windows::core::Result<super::super::System::DispatcherQueue> { let this = &::windows::core::Interface::cast::<ICoreApplicationView6>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::System::DispatcherQueue>(result__) } } } unsafe impl ::windows::core::RuntimeType for CoreApplicationView { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Core.CoreApplicationView;{638bb2db-451d-4661-b099-414f34ffb9f1})"); } unsafe impl ::windows::core::Interface for CoreApplicationView { type Vtable = ICoreApplicationView_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x638bb2db_451d_4661_b099_414f34ffb9f1); } impl ::windows::core::RuntimeName for CoreApplicationView { const NAME: &'static str = "Windows.ApplicationModel.Core.CoreApplicationView"; } impl ::core::convert::From<CoreApplicationView> for ::windows::core::IUnknown { fn from(value: CoreApplicationView) -> Self { value.0 .0 } } impl ::core::convert::From<&CoreApplicationView> for ::windows::core::IUnknown { fn from(value: &CoreApplicationView) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for CoreApplicationView { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a CoreApplicationView { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<CoreApplicationView> for ::windows::core::IInspectable { fn from(value: CoreApplicationView) -> Self { value.0 } } impl ::core::convert::From<&CoreApplicationView> for ::windows::core::IInspectable { fn from(value: &CoreApplicationView) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for CoreApplicationView { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a CoreApplicationView { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct CoreApplicationViewTitleBar(pub ::windows::core::IInspectable); impl CoreApplicationViewTitleBar { pub fn SetExtendViewIntoTitleBar(&self, value: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value).ok() } } pub fn ExtendViewIntoTitleBar(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SystemOverlayLeftInset(&self) -> ::windows::core::Result<f64> { let this = self; unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__) } } pub fn SystemOverlayRightInset(&self) -> ::windows::core::Result<f64> { let this = self; unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__) } } pub fn Height(&self) -> ::windows::core::Result<f64> { let this = self; unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__) } } #[cfg(feature = "Foundation")] pub fn LayoutMetricsChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<CoreApplicationViewTitleBar, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveLayoutMetricsChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } pub fn IsVisible(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Foundation")] pub fn IsVisibleChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<CoreApplicationViewTitleBar, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveIsVisibleChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for CoreApplicationViewTitleBar { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Core.CoreApplicationViewTitleBar;{006d35e3-e1f1-431b-9508-29b96926ac53})"); } unsafe impl ::windows::core::Interface for CoreApplicationViewTitleBar { type Vtable = ICoreApplicationViewTitleBar_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x006d35e3_e1f1_431b_9508_29b96926ac53); } impl ::windows::core::RuntimeName for CoreApplicationViewTitleBar { const NAME: &'static str = "Windows.ApplicationModel.Core.CoreApplicationViewTitleBar"; } impl ::core::convert::From<CoreApplicationViewTitleBar> for ::windows::core::IUnknown { fn from(value: CoreApplicationViewTitleBar) -> Self { value.0 .0 } } impl ::core::convert::From<&CoreApplicationViewTitleBar> for ::windows::core::IUnknown { fn from(value: &CoreApplicationViewTitleBar) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for CoreApplicationViewTitleBar { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a CoreApplicationViewTitleBar { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<CoreApplicationViewTitleBar> for ::windows::core::IInspectable { fn from(value: CoreApplicationViewTitleBar) -> Self { value.0 } } impl ::core::convert::From<&CoreApplicationViewTitleBar> for ::windows::core::IInspectable { fn from(value: &CoreApplicationViewTitleBar) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for CoreApplicationViewTitleBar { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a CoreApplicationViewTitleBar { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct HostedViewClosingEventArgs(pub ::windows::core::IInspectable); impl HostedViewClosingEventArgs { #[cfg(feature = "Foundation")] pub fn GetDeferral(&self) -> ::windows::core::Result<super::super::Foundation::Deferral> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Deferral>(result__) } } } unsafe impl ::windows::core::RuntimeType for HostedViewClosingEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Core.HostedViewClosingEventArgs;{d238943c-b24e-4790-acb5-3e4243c4ff87})"); } unsafe impl ::windows::core::Interface for HostedViewClosingEventArgs { type Vtable = IHostedViewClosingEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd238943c_b24e_4790_acb5_3e4243c4ff87); } impl ::windows::core::RuntimeName for HostedViewClosingEventArgs { const NAME: &'static str = "Windows.ApplicationModel.Core.HostedViewClosingEventArgs"; } impl ::core::convert::From<HostedViewClosingEventArgs> for ::windows::core::IUnknown { fn from(value: HostedViewClosingEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&HostedViewClosingEventArgs> for ::windows::core::IUnknown { fn from(value: &HostedViewClosingEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HostedViewClosingEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a HostedViewClosingEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<HostedViewClosingEventArgs> for ::windows::core::IInspectable { fn from(value: HostedViewClosingEventArgs) -> Self { value.0 } } impl ::core::convert::From<&HostedViewClosingEventArgs> for ::windows::core::IInspectable { fn from(value: &HostedViewClosingEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HostedViewClosingEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a HostedViewClosingEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for HostedViewClosingEventArgs {} unsafe impl ::core::marker::Sync for HostedViewClosingEventArgs {} #[repr(transparent)] #[doc(hidden)] pub struct IAppListEntry(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppListEntry { type Vtable = IAppListEntry_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xef00f07f_2108_490a_877a_8a9f17c25fad); } #[repr(C)] #[doc(hidden)] pub struct IAppListEntry_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppListEntry2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppListEntry2 { type Vtable = IAppListEntry2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd0a618ad_bf35_42ac_ac06_86eeeb41d04b); } #[repr(C)] #[doc(hidden)] pub struct IAppListEntry2_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppListEntry3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppListEntry3 { type Vtable = IAppListEntry3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6099f28d_fc32_470a_bc69_4b061a76ef2e); } #[repr(C)] #[doc(hidden)] pub struct IAppListEntry3_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "System"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, user: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "System")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppListEntry4(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppListEntry4 { type Vtable = IAppListEntry4_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2a131ed2_56f5_487c_8697_5166f3b33da0); } #[repr(C)] #[doc(hidden)] pub struct IAppListEntry4_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ICoreApplication(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreApplication { type Vtable = ICoreApplication_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0aacf7a4_5e1d_49df_8034_fb6a68bc5ed1); } #[repr(C)] #[doc(hidden)] pub struct ICoreApplication_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, viewsource: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, activationfactorycallback: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ICoreApplication2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreApplication2 { type Vtable = ICoreApplication2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x998681fb_1ab6_4b7f_be4a_9a0645224c04); } #[repr(C)] #[doc(hidden)] pub struct ICoreApplication2_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "ApplicationModel_Activation", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "ApplicationModel_Activation", feature = "Foundation")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ICoreApplication3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreApplication3 { type Vtable = ICoreApplication3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfeec0d39_598b_4507_8a67_772632580a57); } #[repr(C)] #[doc(hidden)] pub struct ICoreApplication3_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, launcharguments: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "System"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, user: ::windows::core::RawPtr, launcharguments: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "System")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ICoreApplicationExit(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreApplicationExit { type Vtable = ICoreApplicationExit_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcf86461d_261e_4b72_9acd_44ed2ace6a29); } #[repr(C)] #[doc(hidden)] pub struct ICoreApplicationExit_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ICoreApplicationUnhandledError(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreApplicationUnhandledError { type Vtable = ICoreApplicationUnhandledError_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf0e24ab0_dd09_42e1_b0bc_e0e131f78d7e); } impl ICoreApplicationUnhandledError { #[cfg(feature = "Foundation")] pub fn UnhandledErrorDetected<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventHandler<UnhandledErrorDetectedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveUnhandledErrorDetected<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for ICoreApplicationUnhandledError { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{f0e24ab0-dd09-42e1-b0bc-e0e131f78d7e}"); } impl ::core::convert::From<ICoreApplicationUnhandledError> for ::windows::core::IUnknown { fn from(value: ICoreApplicationUnhandledError) -> Self { value.0 .0 } } impl ::core::convert::From<&ICoreApplicationUnhandledError> for ::windows::core::IUnknown { fn from(value: &ICoreApplicationUnhandledError) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICoreApplicationUnhandledError { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ICoreApplicationUnhandledError { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ICoreApplicationUnhandledError> for ::windows::core::IInspectable { fn from(value: ICoreApplicationUnhandledError) -> Self { value.0 } } impl ::core::convert::From<&ICoreApplicationUnhandledError> for ::windows::core::IInspectable { fn from(value: &ICoreApplicationUnhandledError) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ICoreApplicationUnhandledError { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ICoreApplicationUnhandledError { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ICoreApplicationUnhandledError_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ICoreApplicationUseCount(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreApplicationUseCount { type Vtable = ICoreApplicationUseCount_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x518dc408_c077_475b_809e_0bc0c57e4b74); } #[repr(C)] #[doc(hidden)] pub struct ICoreApplicationUseCount_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ICoreApplicationView(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreApplicationView { type Vtable = ICoreApplicationView_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x638bb2db_451d_4661_b099_414f34ffb9f1); } #[repr(C)] #[doc(hidden)] pub struct ICoreApplicationView_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "UI_Core")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Core"))] usize, #[cfg(all(feature = "ApplicationModel_Activation", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "ApplicationModel_Activation", feature = "Foundation")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ICoreApplicationView2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreApplicationView2 { type Vtable = ICoreApplicationView2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x68eb7adf_917f_48eb_9aeb_7de53e086ab1); } #[repr(C)] #[doc(hidden)] pub struct ICoreApplicationView2_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "UI_Core")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Core"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ICoreApplicationView3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreApplicationView3 { type Vtable = ICoreApplicationView3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x07ebe1b3_a4cf_4550_ab70_b07e85330bc8); } #[repr(C)] #[doc(hidden)] pub struct ICoreApplicationView3_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ICoreApplicationView5(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreApplicationView5 { type Vtable = ICoreApplicationView5_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2bc095a8_8ef0_446d_9e60_3a3e0428c671); } #[repr(C)] #[doc(hidden)] pub struct ICoreApplicationView5_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ICoreApplicationView6(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreApplicationView6 { type Vtable = ICoreApplicationView6_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc119d49a_0679_49ba_803f_b79c5cf34cca); } #[repr(C)] #[doc(hidden)] pub struct ICoreApplicationView6_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "System")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "System"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ICoreApplicationViewTitleBar(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreApplicationViewTitleBar { type Vtable = ICoreApplicationViewTitleBar_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x006d35e3_e1f1_431b_9508_29b96926ac53); } #[repr(C)] #[doc(hidden)] pub struct ICoreApplicationViewTitleBar_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ICoreImmersiveApplication(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreImmersiveApplication { type Vtable = ICoreImmersiveApplication_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1ada0e3e_e4a2_4123_b451_dc96bf800419); } #[repr(C)] #[doc(hidden)] pub struct ICoreImmersiveApplication_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, runtimetype: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, entrypoint: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ICoreImmersiveApplication2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreImmersiveApplication2 { type Vtable = ICoreImmersiveApplication2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x828e1e36_e9e3_4cfc_9b66_48b78ea9bb2c); } #[repr(C)] #[doc(hidden)] pub struct ICoreImmersiveApplication2_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ICoreImmersiveApplication3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreImmersiveApplication3 { type Vtable = ICoreImmersiveApplication3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x34a05b2f_ee0d_41e5_8314_cf10c91bf0af); } #[repr(C)] #[doc(hidden)] pub struct ICoreImmersiveApplication3_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, viewsource: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IFrameworkView(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IFrameworkView { type Vtable = IFrameworkView_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfaab5cd0_8924_45ac_ad0f_a08fae5d0324); } impl IFrameworkView { pub fn Initialize<'a, Param0: ::windows::core::IntoParam<'a, CoreApplicationView>>(&self, applicationview: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), applicationview.into_param().abi()).ok() } } #[cfg(feature = "UI_Core")] pub fn SetWindow<'a, Param0: ::windows::core::IntoParam<'a, super::super::UI::Core::CoreWindow>>(&self, window: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), window.into_param().abi()).ok() } } pub fn Load<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, entrypoint: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), entrypoint.into_param().abi()).ok() } } pub fn Run(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this)).ok() } } pub fn Uninitialize(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this)).ok() } } } unsafe impl ::windows::core::RuntimeType for IFrameworkView { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{faab5cd0-8924-45ac-ad0f-a08fae5d0324}"); } impl ::core::convert::From<IFrameworkView> for ::windows::core::IUnknown { fn from(value: IFrameworkView) -> Self { value.0 .0 } } impl ::core::convert::From<&IFrameworkView> for ::windows::core::IUnknown { fn from(value: &IFrameworkView) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IFrameworkView { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IFrameworkView { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IFrameworkView> for ::windows::core::IInspectable { fn from(value: IFrameworkView) -> Self { value.0 } } impl ::core::convert::From<&IFrameworkView> for ::windows::core::IInspectable { fn from(value: &IFrameworkView) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IFrameworkView { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IFrameworkView { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IFrameworkView_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, applicationview: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "UI_Core")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, window: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Core"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, entrypoint: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IFrameworkViewSource(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IFrameworkViewSource { type Vtable = IFrameworkViewSource_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcd770614_65c4_426c_9494_34fc43554862); } impl IFrameworkViewSource { pub fn CreateView(&self) -> ::windows::core::Result<IFrameworkView> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<IFrameworkView>(result__) } } } unsafe impl ::windows::core::RuntimeType for IFrameworkViewSource { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{cd770614-65c4-426c-9494-34fc43554862}"); } impl ::core::convert::From<IFrameworkViewSource> for ::windows::core::IUnknown { fn from(value: IFrameworkViewSource) -> Self { value.0 .0 } } impl ::core::convert::From<&IFrameworkViewSource> for ::windows::core::IUnknown { fn from(value: &IFrameworkViewSource) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IFrameworkViewSource { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IFrameworkViewSource { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IFrameworkViewSource> for ::windows::core::IInspectable { fn from(value: IFrameworkViewSource) -> Self { value.0 } } impl ::core::convert::From<&IFrameworkViewSource> for ::windows::core::IInspectable { fn from(value: &IFrameworkViewSource) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IFrameworkViewSource { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IFrameworkViewSource { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IFrameworkViewSource_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IHostedViewClosingEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IHostedViewClosingEventArgs { type Vtable = IHostedViewClosingEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd238943c_b24e_4790_acb5_3e4243c4ff87); } #[repr(C)] #[doc(hidden)] pub struct IHostedViewClosingEventArgs_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IUnhandledError(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IUnhandledError { type Vtable = IUnhandledError_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9459b726_53b5_4686_9eaf_fa8162dc3980); } #[repr(C)] #[doc(hidden)] pub struct IUnhandledError_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IUnhandledErrorDetectedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IUnhandledErrorDetectedEventArgs { type Vtable = IUnhandledErrorDetectedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x679ab78b_b336_4822_ac40_0d750f0b7a2b); } #[repr(C)] #[doc(hidden)] pub struct IUnhandledErrorDetectedEventArgs_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct UnhandledError(pub ::windows::core::IInspectable); impl UnhandledError { pub fn Handled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn Propagate(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this)).ok() } } } unsafe impl ::windows::core::RuntimeType for UnhandledError { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Core.UnhandledError;{9459b726-53b5-4686-9eaf-fa8162dc3980})"); } unsafe impl ::windows::core::Interface for UnhandledError { type Vtable = IUnhandledError_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9459b726_53b5_4686_9eaf_fa8162dc3980); } impl ::windows::core::RuntimeName for UnhandledError { const NAME: &'static str = "Windows.ApplicationModel.Core.UnhandledError"; } impl ::core::convert::From<UnhandledError> for ::windows::core::IUnknown { fn from(value: UnhandledError) -> Self { value.0 .0 } } impl ::core::convert::From<&UnhandledError> for ::windows::core::IUnknown { fn from(value: &UnhandledError) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for UnhandledError { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a UnhandledError { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<UnhandledError> for ::windows::core::IInspectable { fn from(value: UnhandledError) -> Self { value.0 } } impl ::core::convert::From<&UnhandledError> for ::windows::core::IInspectable { fn from(value: &UnhandledError) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for UnhandledError { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a UnhandledError { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for UnhandledError {} unsafe impl ::core::marker::Sync for UnhandledError {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct UnhandledErrorDetectedEventArgs(pub ::windows::core::IInspectable); impl UnhandledErrorDetectedEventArgs { pub fn UnhandledError(&self) -> ::windows::core::Result<UnhandledError> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<UnhandledError>(result__) } } } unsafe impl ::windows::core::RuntimeType for UnhandledErrorDetectedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Core.UnhandledErrorDetectedEventArgs;{679ab78b-b336-4822-ac40-0d750f0b7a2b})"); } unsafe impl ::windows::core::Interface for UnhandledErrorDetectedEventArgs { type Vtable = IUnhandledErrorDetectedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x679ab78b_b336_4822_ac40_0d750f0b7a2b); } impl ::windows::core::RuntimeName for UnhandledErrorDetectedEventArgs { const NAME: &'static str = "Windows.ApplicationModel.Core.UnhandledErrorDetectedEventArgs"; } impl ::core::convert::From<UnhandledErrorDetectedEventArgs> for ::windows::core::IUnknown { fn from(value: UnhandledErrorDetectedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&UnhandledErrorDetectedEventArgs> for ::windows::core::IUnknown { fn from(value: &UnhandledErrorDetectedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for UnhandledErrorDetectedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a UnhandledErrorDetectedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<UnhandledErrorDetectedEventArgs> for ::windows::core::IInspectable { fn from(value: UnhandledErrorDetectedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&UnhandledErrorDetectedEventArgs> for ::windows::core::IInspectable { fn from(value: &UnhandledErrorDetectedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for UnhandledErrorDetectedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a UnhandledErrorDetectedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for UnhandledErrorDetectedEventArgs {} unsafe impl ::core::marker::Sync for UnhandledErrorDetectedEventArgs {}
//! A [`DmlSink`] decorator to make request [`IngestOp`] durable in a //! write-ahead log. //! //! [`DmlSink`]: crate::dml_sink::DmlSink //! [`IngestOp`]: crate::dml_payload::IngestOp pub(crate) mod reference_tracker; pub(crate) mod rotate_task; mod traits; pub(crate) mod wal_sink;
use std::cmp::Ordering; use std::collections::VecDeque; use std::str::FromStr; use crate::error::Error; use crate::intcode::{Prog, ProgState}; #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] pub enum Type { Empty, Wall, Block, HorizontalPaddle, Ball, } impl FromStr for Type { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "0" => Ok(Type::Empty), "1" => Ok(Type::Wall), "2" => Ok(Type::Block), "3" => Ok(Type::HorizontalPaddle), "4" => Ok(Type::Ball), _ => Err(Error::UnknownValue), } } } #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] pub struct Pos { x: i64, y: i64, } #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] pub struct Tile { pub pos: Pos, pub tile_id: Type, } #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] pub enum Joystick { Neutral, Left, Right, } impl From<Joystick> for String { fn from(other: Joystick) -> String { match other { Joystick::Neutral => String::from("0"), Joystick::Left => String::from("-1"), Joystick::Right => String::from("1"), } } } pub fn run_loop(mut prog: Prog) -> Result<i64, Error> { let mut input = VecDeque::new(); let mut output = VecDeque::new(); let mut score: i64 = 0; let mut tiles = Vec::<Tile>::new(); loop { let mut new_tiles = Vec::<Tile>::new(); prog.run(&mut input, &mut output)?; while let Some(x) = output.pop_front() { if let Some(y) = output.pop_front() { if let Some(id) = output.pop_front() { if x == "-1" && y == "0" { score = id.parse::<i64>()?; } else { new_tiles.push(Tile { pos: Pos { x: x.parse::<i64>()?, y: y.parse::<i64>()?, }, tile_id: Type::from_str(&id)?, }) } } else { panic!("unexpected program state"); } } else { panic!("unexpected program state"); } } let pos_to_replace = new_tiles.iter().map(|t| t.pos).collect::<Vec<Pos>>(); tiles = tiles .into_iter() .filter(|t| !pos_to_replace.contains(&t.pos)) .collect::<Vec<Tile>>(); tiles.append(&mut new_tiles); // display(tiles.clone()); match prog.state() { ProgState::Halt => break, ProgState::NotStarted => unreachable!(), ProgState::NeedInput => { let paddle = tiles .iter() .find(|&&t| t.tile_id == Type::HorizontalPaddle) .expect("paddle to exist"); let ball = tiles .iter() .find(|&&t| t.tile_id == Type::Ball) .expect("ball to exist"); if ball.pos.x == paddle.pos.x { input.push_back(String::from(Joystick::Neutral)); } else if ball.pos.x > paddle.pos.x { input.push_back(String::from(Joystick::Right)); } else if ball.pos.x < paddle.pos.x { input.push_back(String::from(Joystick::Left)); } } } } Ok(score) } pub fn display(mut tiles: Vec<Tile>) { let max_x = tiles.iter().map(|t| t.pos.x).max().unwrap(); let min_x = tiles.iter().map(|t| t.pos.x).min().unwrap(); let max_y = tiles.iter().map(|t| t.pos.y).max().unwrap(); let min_y = tiles.iter().map(|t| t.pos.y).min().unwrap(); tiles.sort_by(|a, b| { if a.pos.y > b.pos.y { Ordering::Less } else if a.pos.y < b.pos.y { Ordering::Greater } else { a.pos.x.cmp(&b.pos.x) } }); let mut iter = tiles.iter().peekable(); let rng = max_y - min_y; for y in 0..=rng { let y = max_y - y; for x in min_x..=max_x { if let Some(&next_tile) = iter.peek() { let pos = Pos { x, y }; if next_tile.pos == pos { print!( "{}", match next_tile.tile_id { Type::Empty => " ", Type::Wall => "|", Type::Block => "=", Type::HorizontalPaddle => "-", Type::Ball => "*", } ); iter.next(); } } else { print!(" "); } } println!(); } }
//! Types which represent various database backends use byteorder::ByteOrder; use crate::query_builder::bind_collector::BindCollector; use crate::query_builder::QueryBuilder; use crate::sql_types::{self, HasSqlType}; /// A database backend /// /// This trait represents the concept of a backend (e.g. "MySQL" vs "SQLite"). /// It is separate from a [`Connection`](crate::connection::Connection) /// to that backend. /// One backend may have multiple concrete connection implementations. /// /// Implementations of this trait should not assume details about how the /// connection is implemented. /// For example, the `Pg` backend does not assume that `libpq` is being used. /// Implementations of this trait can and should care about details of the wire /// protocol used to communicated with the database. pub trait Backend where Self: Sized + SqlDialect, Self: HasSqlType<sql_types::SmallInt>, Self: HasSqlType<sql_types::Integer>, Self: HasSqlType<sql_types::BigInt>, Self: HasSqlType<sql_types::Float>, Self: HasSqlType<sql_types::Double>, Self: HasSqlType<sql_types::VarChar>, Self: HasSqlType<sql_types::Text>, Self: HasSqlType<sql_types::Binary>, Self: HasSqlType<sql_types::Date>, Self: HasSqlType<sql_types::Time>, Self: HasSqlType<sql_types::Timestamp>, Self: for<'a> HasRawValue<'a>, { /// The concrete `QueryBuilder` implementation for this backend. type QueryBuilder: QueryBuilder<Self>; /// The concrete `BindCollector` implementation for this backend. /// /// Most backends should use [`RawBytesBindCollector`]. /// /// [`RawBytesBindCollector`]: crate::query_builder::bind_collector::RawBytesBindCollector type BindCollector: BindCollector<Self>; /// What byte order is used to transmit integers? /// /// This type is only used if `RawValue` is `[u8]`. type ByteOrder: ByteOrder; } /// The raw representation of a database value given to `FromSql`. /// /// This trait is separate from `Backend` to imitate `type RawValue<'a>`. It /// should only be referenced directly by implementors. Users of this type /// should instead use the [`RawValue`] helper type instead. pub trait HasRawValue<'a> { /// The actual type given to `FromSql`, with lifetimes applied. This type /// should not be used directly. Use the [`RawValue`] /// helper type instead. type RawValue; } /// A trait indicating that the provided raw value uses a binary representation internally // That's a false positive, `HasRawValue<'a>` is essentially // a reference wrapper #[allow(clippy::wrong_self_convention)] pub trait BinaryRawValue<'a>: HasRawValue<'a> { /// Get the underlying binary representation of the raw value fn as_bytes(value: Self::RawValue) -> &'a [u8]; } /// A helper type to get the raw representation of a database type given to /// `FromSql`. Equivalent to `<DB as Backend>::RawValue<'a>`. pub type RawValue<'a, DB> = <DB as HasRawValue<'a>>::RawValue; /// This trait provides various options to configure the /// generated SQL for a specific backend. /// /// Accessing anything from this trait is considered to be part of the /// public API. Implementing this trait is not considered to be part of /// diesels public API, as future versions of diesel may add additional /// associated constants here. /// /// Each associated type is used to configure the behaviour /// of one or more [`QueryFragment`](crate::query_builder::QueryFragment) /// implementations by providing /// a custom `QueryFragment<YourBackend, YourSpecialSyntaxType>` implementation /// to specialize on generic `QueryFragment<DB, DB::AssociatedType>` implementations. /// /// See the [`sql_dialect`] module for options provided by diesel out of the box. pub trait SqlDialect { /// Configures how this backends supports `RETURNING` clauses /// /// This allows backends to opt in `RETURNING` clause support and to /// provide a custom [`QueryFragment`](crate::query_builder::QueryFragment) /// implementation for [`ReturningClause`](crate::query_builder::ReturningClause) type ReturningClause; /// Configures how this backend supports `ON CONFLICT` clauses /// /// This allows backends to opt in `ON CONFLICT` clause support type OnConflictClause; /// Configures how this backend handles the bare `DEFAULT` keyword for /// inserting the default value in a `INSERT INTO` `VALUES` clause /// /// This allows backends to opt in support for `DEFAULT` value expressions /// for insert statements type InsertWithDefaultKeyword; /// Configures how this backend handles Batch insert statements /// /// This allows backends to provide a custom [`QueryFragment`](crate::query_builder::QueryFragment) /// implementation for [`BatchInsert`](crate::query_builder::BatchInsert) type BatchInsertSupport; /// Configures how this backend handles the `DEFAULT VALUES` clause for /// insert statements. /// /// This allows backends to provide a custom [`QueryFragment`](crate::query_builder::QueryFragment) /// implementation for [`DefaultValues`](crate::query_builder::DefaultValues) type DefaultValueClauseForInsert; /// Configures how this backend handles empty `FROM` clauses for select statements. /// /// This allows backends to provide a custom [`QueryFragment`](crate::query_builder::QueryFragment) /// implementation for [`NoFromClause`](crate::query_builder::NoFromClause) type EmptyFromClauseSyntax; /// Configures how this backend handles `EXISTS()` expressions. /// /// This allows backends to provide a custom [`QueryFragment`](crate::query_builder::QueryFragment) /// implementation for [`Exists`](crate::expression::exists::Exists) type ExistsSyntax; /// Configures how this backend handles `IN()` and `NOT IN()` expressions. /// /// This allows backends to provide custom [`QueryFragment`](crate::query_builder::QueryFragment) /// implementations for [`In`](crate::expression::array_comparison::In), /// [`NotIn`](crate::expression::array_comparison::NotIn) and /// [`Many`](crate::expression::array_comparison::Many) type ArrayComparision; } /// This module contains all options provided by diesel to configure the [`SqlDialect`] trait. pub mod sql_dialect { #[cfg(doc)] use super::SqlDialect; /// This module contains all diesel provided reusable options to /// configure [`SqlDialect::OnConflictClause`] pub mod on_conflict_clause { /// A marker trait indicating if a `ON CONFLICT` clause is supported or not /// /// If you use a custom type to specify specialized support for `ON CONFLICT` clauses /// implementing this trait opts into reusing diesels existing `ON CONFLICT` /// `QueryFragment` implementations pub trait SupportsOnConflictClause {} /// This marker type indicates that `ON CONFLICT` clauses are not supported for this backend #[derive(Debug, Copy, Clone)] pub struct DoesNotSupportOnConflictClause; } /// This module contains all reusable options to configure /// [`SqlDialect::ReturningClause`] pub mod returning_clause { /// A marker trait indicating if a `RETURNING` clause is supported or not /// /// If you use custom type to specify specialized support for `RETURNING` clauses /// implementing this trait opts in supporting `RETURNING` clause syntax pub trait SupportsReturningClause {} /// Indicates that a backend provides support for `RETURNING` clauses /// using the postgresql `RETURNING` syntax #[derive(Debug, Copy, Clone)] pub struct PgLikeReturningClause; /// Indicates that a backend does not support `RETURNING` clauses #[derive(Debug, Copy, Clone)] pub struct DoesNotSupportReturningClause; impl SupportsReturningClause for PgLikeReturningClause {} } /// This module contains all reusable options to configure /// [`SqlDialect::InsertWithDefaultKeyword`] pub mod default_keyword_for_insert { /// A marker trait indicating if a `DEFAULT` like expression /// is supported as part of `INSERT INTO` clauses to indicate /// that a default value should be inserted at a specific position /// /// If you use a custom type to specify specialized support for `DEFAULT` /// expressions implementing this trait opts in support for `DEFAULT` /// value expressions for inserts. Otherwise diesel will emulate this /// behaviour. pub trait SupportsDefaultKeyword {} /// Indicates that a backend support `DEFAULT` value expressions /// for `INSERT INTO` statements based on the ISO SQL standard #[derive(Debug, Copy, Clone)] pub struct IsoSqlDefaultKeyword; /// Indicates that a backend does not support `DEFAULT` value /// expressions0for `INSERT INTO` statements #[derive(Debug, Copy, Clone)] pub struct DoesNotSupportDefaultKeyword; impl SupportsDefaultKeyword for IsoSqlDefaultKeyword {} } /// This module contains all reusable options to configure /// [`SqlDialect::BatchInsertSupport`] pub mod batch_insert_support { /// A marker trait indicating if batch insert statements /// are supported for this backend or not pub trait SupportsBatchInsert {} /// Indicates that this backend does not support batch /// insert statements. /// In this case diesel will emulate batch insert support /// by inserting each row on it's own #[derive(Debug, Copy, Clone)] pub struct DoesNotSupportBatchInsert; /// Indicates that this backend supports postgres style /// batch insert statements to insert multiple rows using one /// insert statement #[derive(Debug, Copy, Clone)] pub struct PostgresLikeBatchInsertSupport; impl SupportsBatchInsert for PostgresLikeBatchInsertSupport {} } /// This module contains all reusable options to configure /// [`SqlDialect::DefaultValueClauseForInsert`] pub mod default_value_clause { /// Indicates that this backend uses the /// `DEFAULT VALUES` syntax to specify /// that a row consisting only of default /// values should be inserted #[derive(Debug, Clone, Copy)] pub struct AnsiDefaultValueClause; } /// This module contains all reusable options to configure /// [`SqlDialect::EmptyFromClauseSyntax`] pub mod from_clause_syntax { /// Indicates that this backend skips /// the `FROM` clause in `SELECT` statements /// if no table/view is queried #[derive(Debug, Copy, Clone)] pub struct AnsiSqlFromClauseSyntax; } /// This module contains all reusable options to configure /// [`SqlDialect::ExistsSyntax`] pub mod exists_syntax { /// Indicates that this backend /// treats `EXIST()` as function /// like expression #[derive(Debug, Copy, Clone)] pub struct AnsiSqlExistsSyntax; } /// This module contains all reusable options to configure /// [`SqlDialect::ArrayComparision`] pub mod array_comparision { /// Indicates that this backend requires a single bind /// per array element in `IN()` and `NOT IN()` expression #[derive(Debug, Copy, Clone)] pub struct AnsiSqlArrayComparison; } }
#![deny(warnings)] extern crate futures; extern crate hyper; extern crate tokio_core; extern crate pretty_env_logger; use std::env; use std::io::{self, Write}; use futures::Future; use futures::stream::Stream; use hyper::Client; fn main() { pretty_env_logger::init().unwrap(); let url = match env::args().nth(1) { Some(url) => url, None => { println!("Usage: client <url>"); return; } }; let url = hyper::Url::parse(&url).unwrap(); if url.scheme() != "http" { println!("This example only works with 'http' URLs."); return; } let mut core = tokio_core::reactor::Core::new().unwrap(); let handle = core.handle(); let client = Client::new(&handle); let work = client.get(url).and_then(|res| { println!("Response: {}", res.status()); println!("Headers: \n{}", res.headers()); res.body().for_each(|chunk| { io::stdout().write_all(&chunk).map_err(From::from) }) }).map(|_| { println!("\n\nDone."); }); core.run(work).unwrap(); }
pub mod tokenize; pub mod parse; pub mod generate; pub mod trans; use std::io; use std::io::Read; use std::fs::File; use std::env; use std::io::BufWriter; fn main() -> io::Result<()> { let mut args = env::args(); let _program = args.next().unwrap(); let in_filename = args.next().expect("Please specify input filename"); let out_filename = args.next().expect("Please specify output filename"); let mut in_file = File::open(in_filename).expect("Cannot open file"); let mut code = String::new(); in_file.read_to_string(&mut code)?; let tokens = tokenize::tokenize(&code).expect("Failde to tokenize"); println!("Tokens = {:?}", tokens); let ast = parse::parse(&tokens).expect("Failed to parse"); println!("AST = {:?}", ast); let prog = generate::generate(&ast).expect("Failed to generate program"); println!("Program = {:?}", prog); let mut out_file_buf = BufWriter::new(File::create(out_filename).expect("Cannot create file")); trans::trans(&prog, &mut out_file_buf); Ok(()) }
extern crate structopt; use std::error::Error; use std::path::PathBuf; use structopt::StructOpt; use crate::ecoz2_lib::lpc_signals; use crate::utl; mod libpar; mod lpc_rs; pub mod lpca_cepstrum_rs; pub mod lpca_r_rs; mod lpca_rs; #[derive(StructOpt, Debug)] pub struct LpcOpts { /// Prediction order #[structopt(short = "P", long, default_value = "36")] prediction_order: usize, /// Analysis window length in milliseconds #[structopt(short = "W", long, default_value = "45")] window_length_ms: usize, /// Window offset length in milliseconds #[structopt(short = "O", long, default_value = "15")] offset_length_ms: usize, /// Only process a class if it has at least this number of signals #[structopt(short = "m", long, default_value = "0")] minpc: usize, /// Put the generated predictors into two different training /// and test subsets (with the given approx ratio). /// DEPRECATED. #[structopt(short = "s", long, default_value = "0")] split: f32, /// Signal files to process. If directories are included, then /// all `.wav` under them will be used. /// If a `.csv` is given, then it's assumed to contain columns /// `tt,class,selection` to process desired signals according to /// `--signals-dir-template`, `--tt`, `--class`. /// TODO --class #[structopt(long, required = true, min_values = 1, parse(from_os_str))] signals: Vec<PathBuf>, #[structopt(long, default_value = "data/signals")] signals_dir_template: String, /// TRAIN or TEST #[structopt(long)] tt: Option<String>, #[structopt(long)] class: Option<String>, /// Min time in secs to report processing time per signal #[structopt(short = "X", default_value = "5")] mintrpt: f32, /// Use Rust "parallel" implementation #[structopt(long)] zrsp: bool, /// Use Rust implementation #[structopt(long)] zrs: bool, #[structopt(long)] verbose: bool, } pub fn main(opts: LpcOpts) { let res = main_lpc(opts); if let Err(err) = res { println!("{}", err); } } pub fn main_lpc(opts: LpcOpts) -> Result<(), Box<dyn Error>> { let LpcOpts { prediction_order, window_length_ms, offset_length_ms, minpc, split, signals, signals_dir_template, tt, class, mintrpt, zrsp, zrs, verbose, } = opts; let tt = tt.unwrap_or_else(|| "".to_string()); let sgn_filenames = utl::resolve_files3( &signals, tt.as_str(), &class, "".to_string(), signals_dir_template, ".wav", )?; // println!("sgn_filenames = {:?}", sgn_filenames); // return Ok(()).into(); if zrsp { main_lpc_par_rs( sgn_filenames, prediction_order, window_length_ms, offset_length_ms, ); } else if zrs { main_lpc_rs( sgn_filenames, prediction_order, window_length_ms, offset_length_ms, ); } else { lpc_signals( prediction_order, window_length_ms, offset_length_ms, minpc, split, sgn_filenames, mintrpt, verbose, ); } Ok(()) } fn main_lpc_rs( sgn_filenames: Vec<PathBuf>, prediction_order: usize, window_length_ms: usize, offset_length_ms: usize, ) { for sgn_filename in sgn_filenames { lpc_rs::lpc_rs( sgn_filename, None, prediction_order, window_length_ms, offset_length_ms, ); } } fn main_lpc_par_rs( sgn_filenames: Vec<PathBuf>, prediction_order: usize, window_length_ms: usize, offset_length_ms: usize, ) { for sgn_filename in sgn_filenames { libpar::lpc_par( sgn_filename, None, prediction_order, window_length_ms, offset_length_ms, ); } }
use async_std::prelude::*; use serde::Deserialize; const API_URL: &'static str = "https://api.codetabs.com/v1/loc?github="; #[derive(Deserialize, Debug)] // #[serde(rename_all = "camelCase")] struct LocItem { language: String, files: String, lines: String, blanks: String, comments: String, #[serde(rename = "linesOfCode")] lines_of_code: String, } type Loc = Vec<LocItem>; async fn get_statistics( repo: &str, ) -> Result<Loc, Box<dyn std::error::Error + Send + Sync + 'static>> { let uri = format!("{}{}", API_URL, repo); let data: Loc = surf::get(uri).recv_json().await?; Ok(data) } #[async_std::main] async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { if let Some(repo) = std::env::args().nth(1) { let data = get_statistics(&repo).await?; for i in data { println!("{:#?}", i); } } Ok(()) }
use handler::WebHandler; use routing::WebRouter; use iron::Handler; use iron::prelude::*; use mount::Mount; use router::Router; use staticfile::Static; use std::collections::HashMap; use std::path::Path; use std::thread; use std::thread::JoinHandle; pub struct WebServer { interface: String, port: u32, child_thread: Option<JoinHandle<()>>, web_root: String, router: WebRouter, } impl WebServer { pub fn new(interface: &str, port: u32, web_root: &str, router: WebRouter) -> Self { WebServer { interface: interface.to_string(), port: port, child_thread: None, web_root: web_root.to_string(), router: router, } } pub fn bind(&mut self) { let bind_string = self.get_bind_string(); let mount = self.init_mount(&self.web_root); let child_thread_handle = thread::spawn(move || { Iron::new(mount).http(&*bind_string).unwrap(); }); self.child_thread = Some(child_thread_handle); } fn get_bind_string(&self) -> String { format!("{}:{}", self.interface, self.port) } fn init_mount(&self, path: &str) -> Mount { let mut mount = Mount::new(); mount.mount("/", Static::new(Path::new(path))) .mount("/api", self.router.to_iron_router()); mount } }
use embedded_graphics::pixelcolor::PixelColor; // TODO: rename DefaultTheme to LightTheme and add DarkTheme pub mod default; // TODO: merge this into DefaultTheme. This would allow defining different color schemes for the same // color space. pub trait Theme: PixelColor { const TEXT_COLOR: Self; const BORDER_COLOR: Self; const BACKGROUND_COLOR: Self; }
use crate::game_event::GameEventType; use crate::room::Room; use crate::timer::{Timer, TimerType}; use crate::EventQueue; use crate::{Action, ActionHandled, State}; #[derive(Debug)] pub struct Cryocontrol { pub visited: bool, pub lever: bool, pub opened: bool, } impl Cryocontrol { pub fn new() -> Cryocontrol { Cryocontrol { visited: false, lever: false, opened: false, } } } impl Room for Cryocontrol { fn handle_action( &mut self, state: &mut State, event_queue: &mut EventQueue, action: &Action, ) -> ActionHandled { match action { Action::UseTerminal => { if let Some(enemy) = state.get_current_enemy(state.current_room) { event_queue.schedule_action(Action::Message( format!("The {:?} is blocking you from getting to the terminal.", enemy.get_enemy_type()), GameEventType::Failure )); return ActionHandled::Handled; } let time_to_reboot = 20_000; event_queue.schedule_action(Action::Message( format!("The AI's voice is slowly dying. \"Rebooting System in {} seconds... boot process, life support systems will be offline. All passengers, please enter cryosleep caskets immediately.", time_to_reboot / 1000), GameEventType::Success, )); event_queue.schedule_timer(Timer::new( TimerType::Reboot, "Reboot countdown", 0, time_to_reboot, Action::Rebooted, true, )); ActionHandled::Handled } Action::OpenCryoControl => { if !self.opened { self.opened = true; event_queue.schedule_action(Action::Message( String::from("You open the cryo control door."), GameEventType::Success, )); ActionHandled::Handled } else { event_queue.schedule_action(Action::Message( String::from("The cryo control door is already open."), GameEventType::Failure, )); ActionHandled::Handled } } _ => ActionHandled::NotHandled, } } fn is_opened(&self) -> bool { self.opened } fn open(&mut self) { self.opened = true } fn visit(&mut self) { self.visited = true; } fn is_visited(&self) -> bool { self.visited } }
#[derive(Debug)] pub struct TypeInteraction{ weaknesses: Vec<String>, strengths: Vec<String>, ineffectivities: Vec<String> } pub enum TypeFactor{ Weakness(String), Strength(String), Ineffective(String) } impl TypeInteraction{ pub fn new() -> TypeInteraction{ TypeInteraction{ strengths: Vec::new(), weaknesses: Vec::new(), ineffectivities: Vec::new() } } pub fn get_weaknesses(&self) -> Vec<String>{ self.weaknesses.clone() } pub fn get_strengths(&self) -> Vec<String> { self.strengths.clone() } pub fn get_ineffectivities(&self) -> Vec<String> { self.ineffectivities.clone() } pub fn add_type_factor(&mut self, factor: TypeFactor){ match factor { TypeFactor::Weakness(t) => self.weaknesses.push(t), TypeFactor::Strength(t) => self.strengths.push(t), TypeFactor::Ineffective(t) => self.ineffectivities.push(t) } } }
use crate::{Ops, Port, Range}; use std::str::FromStr; use std::{net::Ipv4Addr, net::TcpListener}; pub struct TcpPort; impl Ops for TcpPort { fn any(host: &str) -> Option<Port> { let r = Range::default(); (r.min..=r.max) .filter(|&p| TcpPort::is_port_available(host, p)) .nth(0) } fn in_range(host: &str, r: Range) -> Option<Port> { (r.min..=r.max) .filter(|&p| TcpPort::is_port_available(host, p)) .nth(0) } fn from_list(host: &str, v: Vec<Port>) -> Option<Port> { v.into_iter() .filter(|&p| TcpPort::is_port_available(host, p)) .nth(0) } fn except(host: &str, v: Vec<Port>) -> Option<Port> { let r = Range::default(); (r.min..=r.max) .filter(|&p| !v.contains(&p) && TcpPort::is_port_available(host, p)) .nth(0) } fn in_range_except(host: &str, r: Range, v: Vec<Port>) -> Option<Port> { (r.min..=r.max) .filter(|&p| !v.contains(&p) && TcpPort::is_port_available(host, p)) .nth(0) } fn is_port_available(host: &str, p: Port) -> bool { matches!( TcpListener::bind((Ipv4Addr::from_str(host).unwrap(), p)).is_ok(), true ) } }
use mysql::*; use mysql::prelude::*; use std::mem; #[derive(Debug, PartialEq, Eq)] struct Payment { customer_id: i32, amount: i32, account_name: Option<String>, } #[derive(Debug, PartialEq, Eq)] struct Rust{ id: i32, name: String, age: i32, } fn main(){ let url = "mysql://root:root@localhost:3306/rust"; let pool = Pool::new(url).unwrap(); let mut conn = pool.get_conn().unwrap(); // // Let's create a table for payments. // conn.query_drop( // r"CREATE TABLE payment ( // customer_id int not null, // amount int not null, // account_name text // )").unwrap(); // let payments = vec![ // Payment { customer_id: 1, amount: 2, account_name: None }, // Payment { customer_id: 3, amount: 4, account_name: Some("foo".into()) }, // Payment { customer_id: 5, amount: 6, account_name: None }, // Payment { customer_id: 7, amount: 8, account_name: None }, // Payment { customer_id: 9, amount: 10, account_name: Some("bar".into()) }, // ]; // // Now let's insert payments to the database // conn.exec_batch( // r"INSERT INTO payment (customer_id, amount, account_name) // VALUES (:customer_id, :amount, :account_name)", // payments.iter().map(|p| params! { // "customer_id" => p.customer_id, // "amount" => p.amount, // "account_name" => &p.account_name, // }) // ).unwrap(); // Let's select payments from database. Type inference should do the trick here. // let selected_payments = conn // .query_map( // "SELECT customer_id, amount, account_name from payment", // |(customer_id, amount, account_name)| { // Payment { customer_id, amount, account_name } // }, // ).unwrap(); let selected_payments = conn .query_map( "SELECT * FROM rust", |(id, name, age)| { Rust { id, name, age } }, ).unwrap(); println!("Len {}", mem::size_of_val(&selected_payments)-21); for i in 0..mem::size_of_val(&selected_payments) - 21{ println!("{:?}", selected_payments[i].name); } // println!("{:#?}", selected_payments); // Let's make sure, that `payments` equals to `selected_payments`. // Mysql gives no guaranties on order of returned rows // without `ORDER BY`, so assume we are lucky. //assert_eq!(_, selected_payments); println!("Yay!"); }
use coi::{container, Inject}; #[derive(Inject)] #[coi(provides Impl1<T> with Impl1::<T>::new())] struct Impl1<T>(T) where T: Default; impl<T> Impl1<T> where T: Default, { fn new() -> Self { Self(Default::default()) } } #[test] fn main() { let impl1_provider = Impl1Provider::<bool>::new(); let container = container! { impl1 => impl1_provider, }; let _bool_impl = container .resolve::<Impl1<bool>>("impl1") .expect("Should exist"); }
use std::time::Duration; use std; #[repr(C)] #[derive(Eq)] pub struct Time { ns : u64 } impl Clone for Time { fn clone(&self) -> Time { Time::new(self.ns) } } impl Copy for Time {} impl std::cmp::PartialEq for Time { fn eq(&self, other: &Time) -> bool { self.ns == other.ns } } impl std::cmp::PartialOrd for Time { fn partial_cmp(&self, other: &Time) -> Option<std::cmp::Ordering> { self.ns.partial_cmp(&other.ns) } } impl std::cmp::Ord for Time { fn cmp(&self, other: &Time) -> std::cmp::Ordering { self.ns.cmp(&other.ns) } } impl std::ops::Add<Duration> for Time { type Output = Time; fn add(self, duration: Duration) -> Time { let dur_ns = duration.as_secs() * 1000_000_000u64 + duration.subsec_nanos() as u64; return Time::new(self.ns + dur_ns) } } impl std::ops::Sub<Time> for Time { type Output = Duration; fn sub(self, other: Time) -> Duration { let res = self.ns - other.ns; return Duration::new(res / 1000_000_000u64 , (res % 1000_000_000u64) as u32); } } impl Time { fn new(ns : u64) -> Time { Time{ ns: ns } } pub fn min() -> Time { Time::new(0) } pub fn now() -> Time { now() } } #[cfg(not(target_os = "linux"))] fn now() -> Time { let option = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH); let duration = option.unwrap(); let ns = duration.as_secs() * 1_000_000_000 + (duration.subsec_nanos() as u64); Time::new(ns) } #[cfg(target_os = "linux")] fn now() -> Time { extern crate libc; let mut time = libc::timespec{tv_sec: 0, tv_nsec : 0 }; let mut ns = 0; unsafe { let res = libc::clock_gettime(libc::CLOCK_REALTIME, &mut time); if res == 0 { ns = time.tv_sec as u64 * 1_000_000_000 + time.tv_nsec as u64; } }; Time::new(ns) }
/// Defines a strongly typed array wrapper. #[macro_export] macro_rules! array_wrapper { ($name:ident, $t:ty, $doc:literal) => { /// $doc #[derive(Debug, Clone)] pub struct $name(::ndarray::Array1<$t>); impl From<::ndarray::Array1<$t>> for $name { fn from(array: ::ndarray::Array1<$t>) -> Self { Self(array) } } impl<'a> From<&'a $name> for ::ndarray::ArrayView1<'a, $t> { fn from(array: &'a $name) -> Self { array.0.view() } } impl ::std::iter::FromIterator<$t> for $name { fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = $t>, { Self(iter.into_iter().collect()) } } impl $name { /// Vector length. #[must_use] pub fn len(&self) -> usize { self.0.len() } /// Iterates the vector. pub fn iter(&self) -> impl Iterator<Item = &$t> { self.0.iter() } /// Returns the underlying vector. #[must_use] pub fn vec(&self) -> &::ndarray::Array1<$t> { &self.0 } /// Returns the underlying vector. pub fn vec_mut(&mut self) -> &mut ::ndarray::Array1<$t> { &mut self.0 } /// Iterates over filtered elements of the vector. /// Any `i`-th element will be present iff the `i`-th element of `mask` is `true`. pub fn filter<'a, I>(&'a self, mask: I) -> impl Iterator<Item = &'a $t> where I: IntoIterator<Item = &'a bool>, { self.0 .iter() .zip(mask.into_iter()) .filter(|(_, m)| **m) .map(|(f, _)| f) } } }; }
//! Information about the current compaction round use std::fmt::Display; use data_types::CompactionLevel; /// Information about the current compaction round (see driver.rs for /// more details about a round) #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum RoundInfo { /// compacting to target level TargetLevel { /// compaction level of target fles target_level: CompactionLevel, }, /// In many small files mode ManySmallFiles { /// start level of files in this round start_level: CompactionLevel, /// max number of files to group in each plan max_num_files_to_group: usize, /// max total size limit of files to group in each plan max_total_file_size_to_group: usize, }, /// This scenario is not 'leading edge', but we'll process it like it is. /// We'll start with the L0 files we must start with (the first by max_l0_created_at), /// and take as many as we can (up to max files | bytes), and compact them down as if /// that's the only L0s there are. This will be very much like if we got the chance /// to compact a while ago, when those were the only files in L0. /// Why would we do this: /// The diagnosis of various scenarios (vertical splitting, ManySmallFiles, etc) /// sometimes get into conflict with each other. When we're having trouble with /// an efficient "big picture" approach, this is a way to get some progress. /// Its sorta like pushing the "easy button". SimulatedLeadingEdge { // level: always Initial /// max number of files to group in each plan max_num_files_to_group: usize, /// max total size limit of files to group in each plan max_total_file_size_to_group: usize, }, } impl Display for RoundInfo { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::TargetLevel { target_level } => write!(f, "TargetLevel: {target_level}"), Self::ManySmallFiles { start_level, max_num_files_to_group, max_total_file_size_to_group, } => write!(f, "ManySmallFiles: {start_level}, {max_num_files_to_group}, {max_total_file_size_to_group}",), Self::SimulatedLeadingEdge { max_num_files_to_group, max_total_file_size_to_group, } => write!(f, "SimulatedLeadingEdge: {max_num_files_to_group}, {max_total_file_size_to_group}",), } } } impl RoundInfo { /// what levels should the files in this round be? pub fn target_level(&self) -> CompactionLevel { match self { Self::TargetLevel { target_level } => *target_level, // For many files, start level is the target level Self::ManySmallFiles { start_level, .. } => *start_level, Self::SimulatedLeadingEdge { .. } => CompactionLevel::FileNonOverlapped, } } /// Is this round in many small files mode? pub fn is_many_small_files(&self) -> bool { matches!(self, Self::ManySmallFiles { .. }) } /// Is this round in simulated leading edge mode? pub fn is_simulated_leading_edge(&self) -> bool { matches!(self, Self::SimulatedLeadingEdge { .. }) } /// return max_num_files_to_group, when available. pub fn max_num_files_to_group(&self) -> Option<usize> { match self { Self::TargetLevel { .. } => None, Self::ManySmallFiles { max_num_files_to_group, .. } => Some(*max_num_files_to_group), Self::SimulatedLeadingEdge { max_num_files_to_group, .. } => Some(*max_num_files_to_group), } } /// return max_total_file_size_to_group, when available. pub fn max_total_file_size_to_group(&self) -> Option<usize> { match self { Self::TargetLevel { .. } => None, Self::ManySmallFiles { max_total_file_size_to_group, .. } => Some(*max_total_file_size_to_group), Self::SimulatedLeadingEdge { max_total_file_size_to_group, .. } => Some(*max_total_file_size_to_group), } } }
#[no_mangle] pub fn SumSquares(n: usize) -> f64 { let mut total = 0f64; for x in 0..n { total = total + (x as f64 * x as f64); } total }
use std::io; use std::{env, process}; use crate::cli::SubCommand; use crate::workflow_config::Config; use rusty_pin::{PinBuilder, Pinboard, Tag}; pub mod config; mod delete; mod list; mod post; mod rename; mod search; mod update; mod upgrade; mod browser_info; use alfred_rs::updater::GithubReleaser; use alfred_rs::updater::Updater; pub(super) struct Runner<'api, 'pin> { pub config: Option<Config>, pub pinboard: Option<Pinboard<'api, 'pin>>, pub updater: Option<Updater<GithubReleaser>>, } impl<'api, 'pin> Runner<'api, 'pin> { fn write_output_items<'a, 'b, I, J>( &self, items: I, vars: Option<J>, ) -> Result<(), Box<dyn std::error::Error>> where I: IntoIterator<Item = alfred::Item<'a>>, J: IntoIterator<Item = (&'b str, &'b str)>, { debug!("Starting in write_output_items"); let mut output_items = items.into_iter().collect::<Vec<alfred::Item>>(); match self.get_upgrade_item() { Ok(Some(item)) => output_items.push(item), Ok(None) => {} Err(e) => error!("Error checking for workflow updates: {:?}", e), } let json_format = self.config.as_ref().unwrap().can_use_json(); // Get username from auth_token let idx = self .config .as_ref() .unwrap() .auth_token .find(':') .ok_or_else(|| "Bad Auth. Token!".to_string())?; let username = &self.config.as_ref().unwrap().auth_token.as_str()[..idx]; let mut variables = vec![("username", username)]; if let Some(items) = vars { items.into_iter().for_each(|(k, v)| { variables.push((k, v)); }); } crate::write_to_alfred(output_items, json_format, Some(variables)); Ok(()) } fn get_upgrade_item(&self) -> Result<Option<alfred::Item>, Box<dyn std::error::Error>> { debug!("Starting in get_upgrade_item"); self.updater .as_ref() .unwrap() .update_ready() .map(|update| { if update { info!("Update is available"); // Since an update is available `latest_version().unwrap()` will not fail let new_version = self .updater .as_ref() .unwrap() .latest_avail_version() .unwrap(); let old_version = self.updater.as_ref().unwrap().current_version(); Some( alfred::ItemBuilder::new( "New Version Is Available for Rusty Pin Workflow! 🎉", ) .subtitle(format!( "Click to download & upgrade {old_version} ⟶ {new_version}" )) .icon_path("auto_update.png") .variable("workflow_update_ready", "1") .arg("update") .into_item(), ) } else { info!("Update UNAVAILABLE: You have the latest version of workflow!"); None } }) .map_err(Into::into) } }
use super::{ModInt, Modulo}; use num::integer::Integer; use std::convert::From; impl From<ModInt<'_, i8>> for i8 { fn from(orig: ModInt<'_, i8>) -> Self { orig.number } } impl From<ModInt<'_, i16>> for i16 { fn from(orig: ModInt<'_, i16>) -> Self { orig.number } } impl From<ModInt<'_, i32>> for i32 { fn from(orig: ModInt<'_, i32>) -> Self { orig.number } } impl From<ModInt<'_, i64>> for i64 { fn from(orig: ModInt<'_, i64>) -> Self { orig.number } } impl From<ModInt<'_, i128>> for i128 { fn from(orig: ModInt<'_, i128>) -> Self { orig.number } } impl From<ModInt<'_, u8>> for u8 { fn from(orig: ModInt<'_, u8>) -> Self { orig.number } } impl From<ModInt<'_, u16>> for u16 { fn from(orig: ModInt<'_, u16>) -> Self { orig.number } } impl From<ModInt<'_, u32>> for u32 { fn from(orig: ModInt<'_, u32>) -> Self { orig.number } } impl From<ModInt<'_, u64>> for u64 { fn from(orig: ModInt<'_, u64>) -> Self { orig.number } } impl From<ModInt<'_, u128>> for u128 { fn from(orig: ModInt<'_, u128>) -> Self { orig.number } } impl From<ModInt<'_, usize>> for usize { fn from(orig: ModInt<'_, usize>) -> Self { orig.number } } use std::ops::{Add, Sub, Mul, Div, Rem}; impl<T> Modulo<T> where T: Integer + Copy { pub fn new(&self, number: T) -> ModInt<T> { ModInt{ number: ((number % self.modulo) + self.modulo) % self.modulo, modulo: &self.modulo, inv: &self.inv } } } impl<T> Add for ModInt<'_, T> where T: Add<Output=T> + Rem<Output=T> + Copy { type Output = Self; fn add(self, other: Self) -> Self { Self { number: (self.number + other.number + *self.modulo) % *self.modulo, modulo: self.modulo, inv: self.inv } } } impl<T> Sub for ModInt<'_, T> where T: Add<Output=T> + Sub<Output=T> + Rem<Output=T> + Copy { type Output = Self; fn sub(self, other: Self) -> Self { Self { number: (self.number + *self.modulo - other.number) % *self.modulo, modulo: self.modulo, inv: self.inv } } } impl<T> Mul for ModInt<'_, T> where T: Mul<Output=T> + Rem<Output=T> + Copy { type Output = Self; fn mul(self, other: Self) -> Self { Self { number: (self.number * other.number) % *self.modulo, modulo: self.modulo, inv: self.inv } } } impl Div for ModInt<'_, u32> { type Output = Self; fn div(self, other: Self) -> Self { let index = other.number as usize; if let Some(c) = self.inv[index] { Self { number: (self.number * c) % *self.modulo, modulo: self.modulo, inv: self.inv } }else{ panic!("no inverse element of {:?} on modulo {:?}", other.number, self.modulo) } } } impl<T> std::cmp::PartialEq for ModInt<'_, T> where T: PartialEq { fn eq(&self, other: &Self) -> bool { self.number == other.number && self.modulo == other.modulo } } impl<T> std::fmt::Debug for ModInt<'_, T> where T: std::fmt::Debug { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ModInt") .field("number", &self.number) .field("modulo", self.modulo) .field("modulo", self.inv) .finish() } }
use std::error::Error; use rustbox::{Color, RustBox}; use rustbox::Key; use rustbox::Event::*; use rustbox; pub fn read_into(start_x: usize, start_y: usize, rustbox: &RustBox, result: &mut String){ let mut position: usize=0; loop{ match rustbox.poll_event(false) { Ok(KeyEvent(key)) => { match key { Some(Key::Enter) => { break; } Some(Key::Backspace) => { if result.len()>0 { result.pop(); position-=1; rustbox.print_char(start_x+position, start_y, rustbox::RB_BOLD, Color::Default, Color::Default, ' '); rustbox.present(); } } Some(Key::Char(v)) => { result.push(v); rustbox.print_char(start_x+position, start_y, rustbox::RB_BOLD, Color::White, Color::Black, v); rustbox.present(); position+=1; } _ => { } } }, Err(e) => panic!("{}", e.description()), _ => { } } } }
use super::{greedy::GreedySolver, utils::best_valued_item_fit, Problem, Solution, SolverTrait}; #[derive(Debug, Clone)] pub struct ReduxSolver(); impl SolverTrait for ReduxSolver { fn construction(&self, problem: &Problem) -> Solution { let biggest_item_which_fit = best_valued_item_fit(&problem.items, problem.max_weight); let greedy = GreedySolver().construction(problem); if biggest_item_which_fit.0 > greedy.cost { Solution { id: problem.id, size: problem.size, cost: biggest_item_which_fit.0, items: Some( (0..problem.size) .map(|i| i == biggest_item_which_fit.1) .collect(), ), } } else { greedy } } }
use std::env; use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::path::Path; use std::string::String; fn main() { let args: Vec<String> = env::args().collect(); let path = Path::new(&args[1]); let display = path.display(); let file = match File::open(&path) { Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)), Ok(file) => file, }; // Printable ASCII range from 0x20 (32) to 0x7E (126) println!("------------------+-------------------------+-------------------------+------------------"); println!(" OFFSET | 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F | ASCII (7-bit) "); println!("------------------+-------------------------+-------------------------+------------------"); let mut line: u32 = 0; let mut i: usize = 0; let mut buf: [char; 16] = [' '; 16]; for byte in file.bytes() { if i % 16 == 0 { print!(" {:016X} | ", line); } let b = byte.unwrap() as char; let idx = i % 16; buf[idx] = b; line += 1; print!("{:02X} ", b as u8); i += 1; if i % 8 == 0 { print!("| "); } if i % 16 == 0 { for c in 0..16 { if buf[c] >= ' ' && buf[c] <= '~' { print!("{}", buf[c] as char); } else { print!("."); } } println!(""); } } // flush remaining bytes from last line while i % 16 != 0 { print!(" "); // 3 spaces (2 for byte and 1 for spacing) buf[i % 16] = ' '; i += 1; if i % 8 == 0 { print!("| "); } if i % 16 == 0 { for c in 0..16 { if buf[c] >= ' ' && buf[c] <= '~' { print!("{}", buf[c] as char); } else { print!("."); } } println!(""); } } }
// ignore-compare-mode-nll // revisions: base nll // [nll]compile-flags: -Zborrowck=mir trait Foo: 'static { } trait Bar<T>: Foo { } fn test1<T: ?Sized + Bar<S>, S>() { } fn test2<'a>() { // Here: the type `dyn Bar<&'a u32>` references `'a`, // and so it does not outlive `'static`. test1::<dyn Bar<&'a u32>, _>(); //[base]~^ ERROR the type `(dyn Bar<&'a u32> + 'static)` does not fulfill the required lifetime //[nll]~^^ ERROR lifetime may not live long enough } fn main() { }
use std::fmt::{self, Debug, Display, Formatter}; pub trait DebugDisplay: Debug + Display { fn to_string(&self, is_debug: bool) -> String { if is_debug { format!("{:?}", self) } else { format!("{}", self) } } fn fmt(&self, f: &mut Formatter, is_debug: bool) -> fmt::Result; } macro_rules! impl_debug_display_via_debugdisplay { ($type:ty) => { impl std::fmt::Debug for $type { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { DebugDisplay::fmt(self, f, true) } } impl std::fmt::Display for $type { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { DebugDisplay::fmt(self, f, false) } } }; } macro_rules! impl_eq_hash_ord_via_get { ($type:ty) => { impl Eq for $type {} impl PartialEq for $type { fn eq(&self, other: &Self) -> bool { self.get() == other.get() } } impl std::hash::Hash for $type { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.get().hash(state) } } impl Ord for $type { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.get().cmp(&other.get()) } } impl PartialOrd for $type { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } }; } pub(super) use {impl_debug_display_via_debugdisplay, impl_eq_hash_ord_via_get};
//! Persistent Storage use chrono::{NaiveTime, NaiveDateTime}; use diesel::*; use diesel::sql_query; use diesel::{Connection, OptionalExtension}; use ::r2d2::Pool; use r2d2_redis::RedisConnectionManager; use redis::{ToRedisArgs, FromRedisValue, RedisResult, RedisWrite, Commands}; use redis; use diesel::deserialize::QueryableByName; use diesel::sql_types as sqlty; pub struct Persistent(Pool<diesel::r2d2::ConnectionManager<MysqlConnection>>, Pool<RedisConnectionManager>); macro_rules! PreparedSql { ($sql: expr; $($arg: expr => $sqlty: ty),+) => { sql_query($sql) $(.bind::<$sqlty, _>($arg))+ } } #[derive(QueryableByName)] pub struct UserIotimes { #[sql_type = "sqlty::Integer"] pub github_id: i32, #[sql_type = "sqlty::Varchar"] pub slack_id: String, #[sql_type = "sqlty::Varchar"] pub github_login: String, #[sql_type = "sqlty::Time"] pub intime: NaiveTime, #[sql_type = "sqlty::Time"] pub outtime: NaiveTime } impl UserIotimes { pub fn fetch_all<C: Connection>(con: &C) -> Vec<Self> where Self: QueryableByName<C::Backend> { let select_cols = [ "usermap.github_id", "slack_id", "github_login", "coalesce(temporal_intime, default_intime) as intime", "coalesce(temporal_outtime, default_outtime) as outtime" ]; let datasource = "user_inout_time right join usermap on usermap.github_id = user_inout_time.github_id"; sql_query(format!("Select {} from {}", select_cols.join(","), datasource)).load(con).unwrap() } } #[derive(QueryableByName)] pub struct LinkedGitHubInfo { #[sql_type = "sqlty::Integer"] pub github_id: i32, #[sql_type = "sqlty::Varchar"] pub github_login: String } impl LinkedGitHubInfo { fn fetch1<C: Connection>(con: &C, slack_id: &str) -> Option<Self> where Self: QueryableByName<C::Backend> { PreparedSql!("Select github_id, github_login from usermap where slack_id=? limit 1"; slack_id => sqlty::Varchar) .get_result(con).optional().unwrap() } } #[derive(QueryableByName)] pub struct UserLastTimes { #[sql_type = "sqlty::Datetime"] pub itime: NaiveDateTime, #[sql_type = "sqlty::Datetime"] pub otime: NaiveDateTime } impl UserLastTimes { pub fn fetch1<C: Connection>(con: &C, github_id: i32) -> Option<Self> where Self: QueryableByName<C::Backend> { PreparedSql!("Select last_intime as itime, last_outtime as otime from user_inout_time where github_id=? limit 1"; github_id => sqlty::Integer) .get_result::<Self>(con).optional().unwrap() } } pub struct RemainingWork { pub issue_id: u32, pub progress: Option<(u32, u32)> } impl<'a> ToRedisArgs for &'a RemainingWork { fn write_redis_args<W: ?Sized + RedisWrite>(&self, out: &mut W) { if let Some((c, t)) = self.progress { format!("{}:{}:{}", self.issue_id, c, t).write_redis_args(out); } else { self.issue_id.write_redis_args(out); } } } impl FromRedisValue for RemainingWork { fn from_redis_value(v: &redis::Value) -> RedisResult<Self> { if let redis::Value::Status(ref s) = v { let mut values = s.split(":"); let issue_id = values.next().expect("Unable to get issue_id") .parse().expect("Unable to get issue_id as number"); if let Some(cstr) = values.next() { let c = cstr.parse().expect("Unable to get checked_count as number"); let t = values.next().expect("Missing total_checkbox_count") .parse().expect("Unable to get total_checkbox_count as number"); Ok(RemainingWork { issue_id, progress: Some((c, t)) }) } else { Ok(RemainingWork { issue_id, progress: None }) } } else { panic!("Invalid data type") } } } impl Persistent { pub fn new(database_url: &str, redis_url: &str) -> Self { let con = diesel::r2d2::ConnectionManager::new(database_url); let rcon = RedisConnectionManager::new(redis_url).unwrap(); let pool = Pool::builder().build(con).expect("PersistentDB Connection failed"); let rpool = Pool::builder().build(rcon).expect("Redis Connection failed"); Persistent(pool, rpool) } pub fn init_user(&self, github_id: i32, slack_id: &str, github_login: &str) { let con = self.0.get().unwrap(); con.transaction(|| -> diesel::result::QueryResult<()> { sql_query("Replace into usermap (github_id, slack_id, github_login) values (?, ?, ?)") .bind::<sqlty::Integer, _>(github_id) .bind::<sqlty::Varchar, _>(slack_id) .bind::<sqlty::Varchar, _>(github_login) .execute(&con)?; PreparedSql!("Replace into user_inout_time (github_id, last_intime, last_outtime) values (?, utc_time(), timestamp(utc_date()-1, '10:00:00'))"; github_id => sqlty::Integer) .execute(&con)?; sql_query("Replace into user_last_act_time (github_id, by_mention) values (?, null)") .bind::<sqlty::Integer, _>(github_id) .execute(&con)?; Ok(()) }).unwrap(); } pub fn forall_user_iotimes(&self) -> Vec<UserIotimes> { UserIotimes::fetch_all(&self.0.get().unwrap()) } /// Fetch a linked github user id and login name, by slack id. pub fn query_github_from_slack_id(&self, slack_id: &str) -> Option<(i32, String)> { LinkedGitHubInfo::fetch1(&self.0.get().unwrap(), slack_id).map(|l| (l.github_id, l.github_login)) } fn update_user_last_intime(&self, github_id: i32, last_intime: NaiveDateTime) { PreparedSql!("Update user_inout_time set last_intime=? where github_id=?"; last_intime => sqlty::Datetime, github_id => sqlty::Integer).execute(&self.0.get().unwrap()).unwrap(); } pub fn update_user_last_outtime(&self, github_id: i32, last_outtime: NaiveDateTime) { PreparedSql!("Update user_inout_time set last_outtime=? where github_id=?"; last_outtime => sqlty::Datetime, github_id => sqlty::Integer).execute(&self.0.get().unwrap()).unwrap(); } pub fn is_user_working(&self, github_id: i32) -> bool { UserLastTimes::fetch1(&self.0.get().unwrap(), github_id).map_or(false, |st| st.itime > st.otime) } pub fn user_setup_work(&self, github_id: i32, last_intime: NaiveDateTime, remaining_works: &[RemainingWork]) { self.update_user_last_intime(github_id, last_intime); let k = github_id.to_string(); let mut con = self.1.get().unwrap(); let _: () = redis::transaction(&mut *con, &[&k], |con, p| { for w in remaining_works { p.rpush(&k, w); } p.query(con) }).unwrap(); } pub fn user_moveout_works(&self, github_id: i32) -> Option<Vec<RemainingWork>> { self.1.get().unwrap().lrange(github_id.to_string(), 0, -1).unwrap() } }
//! Module providing an implementation of the [HtsGet] trait using a [Storage]. //! use crate::{ htsget::bam_search::BamSearch, htsget::{Format, HtsGet, HtsGetError, Query, Response, Result}, storage::Storage, }; /// Implementation of the [HtsGet] trait using a [Storage]. pub struct HtsGetFromStorage<S> { storage: S, } impl<S> HtsGet for HtsGetFromStorage<S> where S: Storage, { fn search(&self, query: Query) -> Result<Response> { match query.format { Some(Format::Bam) | None => BamSearch::new(&self.storage).search(query), Some(format) => Err(HtsGetError::unsupported_format(format)), } } } impl<S> HtsGetFromStorage<S> { pub fn new(storage: S) -> Self { Self { storage } } pub fn storage(&self) -> &S { &self.storage } } #[cfg(test)] mod tests { use crate::htsget::bam_search::tests::{expected_url, with_local_storage}; use crate::htsget::{Headers, Url}; use super::*; #[test] fn search_bam() { with_local_storage(|storage| { let htsget = HtsGetFromStorage::new(storage); let query = Query::new("htsnexus_test_NA12878").with_format(Format::Bam); let response = htsget.search(query); println!("{:#?}", response); let expected_response = Ok(Response::new( Format::Bam, vec![Url::new(expected_url(&htsget.storage())) .with_headers(Headers::default().with_header("Range", "bytes=4668-"))], )); assert_eq!(response, expected_response) }) } }
use std::collections::HashMap; use std::string::String; use serde::{Serialize, Deserialize}; #[derive(Debug, PartialEq, Clone)] pub struct Environment { pub conversions: Conversions, values: Vec<Result<Value, ()>>, vars: HashMap<String, Value>, } impl Environment { pub fn new(conversions: &Conversions) -> Environment { Environment { conversions: Environment::expand_conversions(conversions), values: Vec::new(), vars: HashMap::new(), } } pub fn add_entry(&mut self, val: Result<Value, ()>) { self.values.push(val); } fn conversion_ratio(&self, from: &Unit, to: &Unit) -> Result<f64, String> { self.conversions .0 .get(&(from.clone(), to.clone())) .map(|ratio| ratio.clone()) .ok_or(format!("Cannot convert from {:?} to {:?}", from, to)) } /// unit conversions e.g. 1km/h to 0.28m/s etc. pub fn convert_units(&self, value: &Value, new_units: &UnitSet) -> Value { let mut converted = value.clone(); match value { Value { num: _, units: UnitSet(units), } => { for (unit, val) in units.iter() { for (to_unit, _) in new_units.0.iter() { match self.conversion_ratio(unit, to_unit) { Err(_) => { // pass } Ok(ratio) => { converted.num *= ratio.powf(*val as f64); converted.units.0.remove(&unit); converted.units.0.insert(to_unit.clone(), val.clone()); } } } } } } converted } fn expand_conversions(basic_conversions: &Conversions) -> Conversions { let mut conversions = HashMap::new(); // Add a -> b, b -> a, a -> a and b -> b conversions for conversion in basic_conversions.clone().0 { match conversion { ((from, to), ratio) => { conversions.insert((from.clone(), to.clone()), ratio.clone()); conversions.insert((to.clone(), from.clone()), 1. / ratio); conversions.insert((from.clone(), from.clone()), 1.); conversions.insert((to.clone(), to.clone()), 1.); } } } // for all a -> b and b -> c, add a -> c, aka transitive conversions loop { // loop until no changes are made anymore let mut is_saturated = true; let mut new_conversions = HashMap::new(); for ((left_from, left_to), left_ratio) in &conversions { for ((right_from, right_to), right_ratio) in &conversions { let key = (left_from.clone(), right_to.clone()); if left_to == right_from && !conversions.contains_key(&key) { new_conversions.insert( key, left_ratio * right_ratio, ); is_saturated = false; } } } if is_saturated { break; } conversions.extend(new_conversions); } Conversions(conversions) } pub fn add(&self, left: Value, right: Value) -> Value { let converted_right = self.convert_units(&right, &left.units); Value { num: left.num + converted_right.num, units: left.units, } } pub fn sub(&self, left: Value, right: Value) -> Value { let converted_right = self.convert_units(&right, &left.units); Value { num: left.num - converted_right.num, units: left.units, } } pub fn mul(&self, left: Value, right: Value) -> Value { let converted_right = self.convert_units(&right, &left.units); let mut result_units = left.units.0.clone(); for (unit, num) in converted_right.units.0.iter() { let result_num = result_units.entry(unit.clone()).or_insert(0); *result_num += num; if *result_num == 0 { result_units.remove(unit); } } Value { num: left.num * converted_right.num, units: UnitSet(result_units), } } pub fn div(&self, left: Value, right: Value) -> Value { let inverted_units = right .units .0 .clone() .into_iter() .map(|(k, v)| (k, -v)) .collect(); let inverted_right = Value { num: 1.0 / right.num, units: UnitSet(inverted_units), }; self.mul(left, inverted_right) } /// Unit powers /// /// Example: /// ``` /// # use std::collections::HashMap; /// # use dedo_rust::*; /// # use dedo_rust::types::*; /// # use dedo_rust::defaults::*; /// # let env = ENVIRONMENT.clone(); /// let res = env.pow(Value::simple(12.0, "usd"), Value::unitless(4.0)); /// assert_eq!(res, Value::new(20736.0, units!("usd" to 4))); /// ``` pub fn pow(&self, left: Value, right: Value) -> Value { let pow = right.num.round(); let units = left .units .0 .into_iter() .map(|(k, v)| (k, v * (pow as i32))) .collect(); Value { num: left.num.powf(pow), units: UnitSet(units), } } pub fn ident(&self, ident: String) -> Result<Value, ()> { match (ident.as_ref(), self.vars.get(&ident)) { ("sum", _) => self.sum(), ("prod", _) => self.prod(), ("prev", _) => self.prev(), (_, Some(v)) => Ok(v.clone()), (units, _) => Ok(Value::simple(1.0, units)), } } pub fn sum(&self) -> Result<Value, ()> { let mut res: Result<Value, ()> = Err(()); for row in self.values.iter().rev() { match (row.clone(), res.clone()) { (Ok(lhs), Ok(rhs)) => { res = Ok(self.add(lhs, rhs)); } (Ok(lhs), Err(())) => { res = Ok(lhs.clone()); } _ => break, } } res } pub fn prod(&self) -> Result<Value, ()> { let mut res: Result<Value, ()> = Err(()); for row in self.values.iter().rev() { match (row.clone(), res.clone()) { (Ok(lhs), Ok(rhs)) => { res = Ok(self.mul(lhs, rhs)); } (Ok(lhs), Err(())) => { res = Ok(lhs.clone()); } _ => break, } } res } pub fn prev(&self) -> Result<Value, ()> { for row in self.values.iter().rev() { return row.clone(); } return Err(()); } pub fn assign<U: Into<String>>(&mut self, ident: U, value: Value) -> Result<Value, ()> { self.vars.insert(ident.into(), value.clone()); Ok(value.clone()) } pub fn convert(&self, value: Value, target: Value) -> Value { self.convert_units(&value, &target.units) } } /// Utility to help create a static environment. Basic syntax is /// environment!["some_unit" to "some_other_unit" is 123.456, ...] #[macro_export] macro_rules! environment { ($($from:literal to $to:literal is $num:literal),*) => { { let mut tmp_map: std::collections::HashMap<(Unit, Unit), f64> = std::collections::HashMap::new(); $( tmp_map.insert(($from.into(), $to.into()), $num as f64); )* Environment::new(&Conversions(tmp_map)) } } ; } #[derive(Clone, Debug, PartialEq)] pub struct Conversions(pub HashMap<(Unit, Unit), f64>); #[derive(Clone, Debug, Hash, Serialize, Deserialize)] pub struct Unit(pub String); impl From<&str> for Unit { fn from(name: &str) -> Self { Unit(name.into()) } } impl PartialEq for Unit { fn eq(&self, other: &Self) -> bool { self.0.to_lowercase() == other.0.to_lowercase() } } impl Eq for Unit {} #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct UnitSet(pub HashMap<Unit, i32>); impl From<Unit> for UnitSet { fn from(unit: Unit) -> UnitSet { let mut unit_map: HashMap<Unit, i32> = HashMap::new(); unit_map.insert(unit.into(), 1); UnitSet(unit_map) } } #[macro_export] macro_rules! units { ($($from:literal to $to:literal),*) => { { use std::collections::HashMap; let mut tmp_map: HashMap<Unit, i32> = HashMap::new(); $( tmp_map.insert($from.into(), $to); )* UnitSet(tmp_map) } } ; } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Value { num: f64, units: UnitSet, } impl Value { pub fn new<U: Into<UnitSet>>(num: f64, units: U) -> Value { Value { num, units: units.into(), } } pub fn simple<U: Into<String>>(num: f64, units: U) -> Value { let unit_str: String = units.into(); Value { num, units: UnitSet::from(Unit(unit_str)), } } /// A value with no units and the given number /// /// Example: /// ``` /// # use dedo_rust::types::*; /// let value = Value::unitless(14.1); /// ``` pub fn unitless(num: f64) -> Value { Value { num, units: UnitSet(HashMap::new()), } } /// The zero value /// /// Example: /// ``` /// # use dedo_rust::types::*; /// # use std::collections::HashMap; /// let value = Value::zero(); /// assert_eq!(value, Value::unitless(0.0)); /// ``` pub fn zero() -> Value { Self::unitless(0.0) } /// Negates a value /// /// Example: /// ``` /// # use dedo_rust::types::*; /// let value = Value::simple(123.0, "$").negate(); /// let other_value = Value::negate(Value::simple(123.0, "$")); /// # assert_eq!(value, Value::simple(-123.0, "$")); /// # assert_eq!(other_value, Value::simple(-123.0, "$")); /// ``` pub fn negate(self) -> Value { Value { num: -self.num, units: self.units, } } }
use super::BufMutExt; /// An MQTT packet #[derive(Clone, Debug, Eq, PartialEq)] pub enum Packet { /// Ref: 3.2 CONNACK – Acknowledge connection request ConnAck { session_present: bool, return_code: super::ConnectReturnCode, }, /// Ref: 3.1 CONNECT – Client requests a connection to a Server Connect { username: Option<String>, password: Option<String>, will: Option<Publication>, client_id: super::ClientId, keep_alive: std::time::Duration, }, Disconnect, /// Ref: 3.12 PINGREQ – PING request PingReq, /// Ref: 3.13 PINGRESP – PING response PingResp, /// Ref: 3.4 PUBACK – Publish acknowledgement PubAck { packet_identifier: super::PacketIdentifier, }, /// Ref: 3.7 PUBCOMP – Publish complete (QoS 2 publish received, part 3) PubComp { packet_identifier: super::PacketIdentifier, }, /// 3.3 PUBLISH – Publish message Publish { packet_identifier_dup_qos: PacketIdentifierDupQoS, retain: bool, topic_name: String, payload: Vec<u8>, }, /// Ref: 3.5 PUBREC – Publish received (QoS 2 publish received, part 1) PubRec { packet_identifier: super::PacketIdentifier, }, /// Ref: 3.6 PUBREL – Publish release (QoS 2 publish received, part 2) PubRel { packet_identifier: super::PacketIdentifier, }, /// Ref: 3.9 SUBACK – Subscribe acknowledgement SubAck { packet_identifier: super::PacketIdentifier, qos: Vec<SubAckQos>, }, /// Ref: 3.8 SUBSCRIBE - Subscribe to topics Subscribe { packet_identifier: super::PacketIdentifier, subscribe_to: Vec<SubscribeTo>, }, /// Ref: 3.11 UNSUBACK – Unsubscribe acknowledgement UnsubAck { packet_identifier: super::PacketIdentifier, }, /// Ref: 3.10 UNSUBSCRIBE – Unsubscribe from topics Unsubscribe { packet_identifier: super::PacketIdentifier, unsubscribe_from: Vec<String>, }, } impl Packet { /// The type of a [`Packet::ConnAck`] pub const CONNACK: u8 = 0x20; /// The type of a [`Packet::Connect`] pub const CONNECT: u8 = 0x10; /// The type of a [`Packet::Disconnect`] pub const DISCONNECT: u8 = 0xE0; /// The type of a [`Packet::PingReq`] pub const PINGREQ: u8 = 0xC0; /// The type of a [`Packet::PingResp`] pub const PINGRESP: u8 = 0xD0; /// The type of a [`Packet::PubAck`] pub const PUBACK: u8 = 0x40; /// The type of a [`Packet::PubComp`] pub const PUBCOMP: u8 = 0x70; /// The type of a [`Packet::Publish`] pub const PUBLISH: u8 = 0x30; /// The type of a [`Packet::PubRec`] pub const PUBREC: u8 = 0x50; /// The type of a [`Packet::PubRel`] pub const PUBREL: u8 = 0x60; /// The type of a [`Packet::SubAck`] pub const SUBACK: u8 = 0x90; /// The type of a [`Packet::Subscribe`] pub const SUBSCRIBE: u8 = 0x80; /// The type of a [`Packet::UnsubAck`] pub const UNSUBACK: u8 = 0xB0; /// The type of a [`Packet::Unsubscribe`] pub const UNSUBSCRIBE: u8 = 0xA0; } #[allow(clippy::doc_markdown)] /// A combination of the packet identifier, dup flag and QoS that only allows valid combinations of these three properties. /// Used in [`Packet::Publish`] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PacketIdentifierDupQoS { AtMostOnce, AtLeastOnce(super::PacketIdentifier, bool), ExactlyOnce(super::PacketIdentifier, bool), } /// A subscription request. #[derive(Clone, Debug, Eq, PartialEq)] pub struct SubscribeTo { pub topic_filter: String, pub qos: QoS, } /// The level of reliability for a publication /// /// Ref: 4.3 Quality of Service levels and protocol flows #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub enum QoS { AtMostOnce, AtLeastOnce, ExactlyOnce, } impl From<QoS> for u8 { fn from(qos: QoS) -> Self { match qos { QoS::AtMostOnce => 0x00, QoS::AtLeastOnce => 0x01, QoS::ExactlyOnce => 0x02, } } } #[allow(clippy::doc_markdown)] /// QoS returned in a SUBACK packet. Either one of the [`QoS`] values, or an error code. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum SubAckQos { Success(QoS), Failure, } impl From<SubAckQos> for u8 { fn from(qos: SubAckQos) -> Self { match qos { SubAckQos::Success(qos) => qos.into(), SubAckQos::Failure => 0x80, } } } /// A message that can be published to the server #[derive(Clone, Debug, Eq, PartialEq)] pub struct Publication { pub topic_name: String, pub qos: crate::proto::QoS, pub retain: bool, pub payload: Vec<u8>, } /// A tokio codec that encodes and decodes MQTT packets. /// /// Ref: 2 MQTT Control Packet format #[derive(Debug, Default)] pub struct PacketCodec { decoder_state: PacketDecoderState, } #[derive(Debug)] pub enum PacketDecoderState { Empty, HaveFirstByte { first_byte: u8, remaining_length: super::RemainingLengthCodec, }, HaveFixedHeader { first_byte: u8, remaining_length: usize, }, } impl Default for PacketDecoderState { fn default() -> Self { PacketDecoderState::Empty } } impl tokio::codec::Decoder for PacketCodec { type Item = Packet; type Error = super::DecodeError; fn decode(&mut self, src: &mut bytes::BytesMut) -> Result<Option<Self::Item>, Self::Error> { let (first_byte, mut src) = loop { match &mut self.decoder_state { PacketDecoderState::Empty => { let first_byte = match src.try_get_u8() { Ok(first_byte) => first_byte, Err(_) => return Ok(None), }; self.decoder_state = PacketDecoderState::HaveFirstByte { first_byte, remaining_length: Default::default(), }; } PacketDecoderState::HaveFirstByte { first_byte, remaining_length, } => match remaining_length.decode(src)? { Some(remaining_length) => { self.decoder_state = PacketDecoderState::HaveFixedHeader { first_byte: *first_byte, remaining_length, } } None => return Ok(None), }, PacketDecoderState::HaveFixedHeader { first_byte, remaining_length, } => { if src.len() < *remaining_length { return Ok(None); } let first_byte = *first_byte; let src = src.split_to(*remaining_length); self.decoder_state = PacketDecoderState::Empty; break (first_byte, src); } } }; match (first_byte & 0xF0, first_byte & 0x0F, src.len()) { (Packet::CONNACK, 0, 2) => { let flags = src.try_get_u8()?; let session_present = match flags { 0x00 => false, 0x01 => true, flags => return Err(super::DecodeError::UnrecognizedConnAckFlags(flags)), }; let return_code: super::ConnectReturnCode = src.try_get_u8()?.into(); Ok(Some(Packet::ConnAck { session_present, return_code, })) } (Packet::CONNECT, 0, _) => { let protocol_name = super::Utf8StringCodec::default() .decode(&mut src)? .ok_or(super::DecodeError::IncompletePacket)?; if protocol_name != "MQTT" { return Err(super::DecodeError::UnrecognizedProtocolName(protocol_name)); } let protocol_level = src.try_get_u8()?; if protocol_level != 0x04 { return Err(super::DecodeError::UnrecognizedProtocolLevel( protocol_level, )); } let connect_flags = src.try_get_u8()?; if connect_flags & 0x01 != 0 { return Err(super::DecodeError::ConnectReservedSet); } let keep_alive = std::time::Duration::from_secs(u64::from(src.try_get_u16_be()?)); let client_id = super::Utf8StringCodec::default() .decode(&mut src)? .ok_or(super::DecodeError::IncompletePacket)?; let client_id = if client_id == "" { super::ClientId::ServerGenerated } else if connect_flags & 0x02 == 0 { super::ClientId::IdWithExistingSession(client_id) } else { super::ClientId::IdWithCleanSession(client_id) }; let will = if connect_flags & 0x04 == 0 { None } else { let topic_name = super::Utf8StringCodec::default() .decode(&mut src)? .ok_or(super::DecodeError::IncompletePacket)?; let qos = match connect_flags & 0x18 { 0x00 => QoS::AtMostOnce, 0x08 => QoS::AtLeastOnce, 0x10 => QoS::ExactlyOnce, qos => return Err(super::DecodeError::UnrecognizedQoS(qos >> 3)), }; let retain = connect_flags & 0x20 != 0; let payload_len = usize::from(src.try_get_u16_be()?); if src.len() < payload_len { return Err(super::DecodeError::IncompletePacket); } let payload = (&*src.split_to(payload_len)).to_owned(); Some(Publication { topic_name, qos, retain, payload, }) }; let username = if connect_flags & 0x80 == 0 { None } else { Some( super::Utf8StringCodec::default() .decode(&mut src)? .ok_or(super::DecodeError::IncompletePacket)?, ) }; let password = if connect_flags & 0x40 == 0 { None } else { Some( super::Utf8StringCodec::default() .decode(&mut src)? .ok_or(super::DecodeError::IncompletePacket)?, ) }; Ok(Some(Packet::Connect { username, password, will, client_id, keep_alive, })) } (Packet::DISCONNECT, 0, 0) => Ok(Some(Packet::Disconnect)), (Packet::PINGREQ, 0, 0) => Ok(Some(Packet::PingReq)), (Packet::PINGRESP, 0, 0) => Ok(Some(Packet::PingResp)), (Packet::PUBACK, 0, 2) => { let packet_identifier = src.try_get_u16_be()?; let packet_identifier = match super::PacketIdentifier::new(packet_identifier) { Some(packet_identifier) => packet_identifier, None => return Err(super::DecodeError::ZeroPacketIdentifier), }; Ok(Some(Packet::PubAck { packet_identifier })) } (Packet::PUBCOMP, 0, 2) => { let packet_identifier = src.try_get_u16_be()?; let packet_identifier = match super::PacketIdentifier::new(packet_identifier) { Some(packet_identifier) => packet_identifier, None => return Err(super::DecodeError::ZeroPacketIdentifier), }; Ok(Some(Packet::PubComp { packet_identifier })) } (Packet::PUBLISH, flags, _) => { let dup = (flags & 0x08) != 0; let retain = (flags & 0x01) != 0; let topic_name = super::Utf8StringCodec::default() .decode(&mut src)? .ok_or(super::DecodeError::IncompletePacket)?; let packet_identifier_dup_qos = match (flags & 0x06) >> 1 { 0x00 if dup => return Err(super::DecodeError::PublishDupAtMostOnce), 0x00 => PacketIdentifierDupQoS::AtMostOnce, 0x01 => { let packet_identifier = src.try_get_u16_be()?; let packet_identifier = match super::PacketIdentifier::new(packet_identifier) { Some(packet_identifier) => packet_identifier, None => return Err(super::DecodeError::ZeroPacketIdentifier), }; PacketIdentifierDupQoS::AtLeastOnce(packet_identifier, dup) } 0x02 => { let packet_identifier = src.try_get_u16_be()?; let packet_identifier = match super::PacketIdentifier::new(packet_identifier) { Some(packet_identifier) => packet_identifier, None => return Err(super::DecodeError::ZeroPacketIdentifier), }; PacketIdentifierDupQoS::ExactlyOnce(packet_identifier, dup) } qos => return Err(super::DecodeError::UnrecognizedQoS(qos)), }; let mut payload = vec![0_u8; src.len()]; payload.copy_from_slice(&src.take()); Ok(Some(Packet::Publish { packet_identifier_dup_qos, retain, topic_name, payload, })) } (Packet::PUBREC, 0, 2) => { let packet_identifier = src.try_get_u16_be()?; let packet_identifier = match super::PacketIdentifier::new(packet_identifier) { Some(packet_identifier) => packet_identifier, None => return Err(super::DecodeError::ZeroPacketIdentifier), }; Ok(Some(Packet::PubRec { packet_identifier })) } (Packet::PUBREL, 2, 2) => { let packet_identifier = src.try_get_u16_be()?; let packet_identifier = match super::PacketIdentifier::new(packet_identifier) { Some(packet_identifier) => packet_identifier, None => return Err(super::DecodeError::ZeroPacketIdentifier), }; Ok(Some(Packet::PubRel { packet_identifier })) } (Packet::SUBACK, 0, remaining_length) => { let packet_identifier = src.try_get_u16_be()?; let packet_identifier = match super::PacketIdentifier::new(packet_identifier) { Some(packet_identifier) => packet_identifier, None => return Err(super::DecodeError::ZeroPacketIdentifier), }; let mut qos = vec![]; for _ in 2..remaining_length { qos.push(match src.try_get_u8()? { 0x00 => SubAckQos::Success(QoS::AtMostOnce), 0x01 => SubAckQos::Success(QoS::AtLeastOnce), 0x02 => SubAckQos::Success(QoS::ExactlyOnce), 0x80 => SubAckQos::Failure, qos => return Err(super::DecodeError::UnrecognizedQoS(qos)), }); } Ok(Some(Packet::SubAck { packet_identifier, qos, })) } (Packet::SUBSCRIBE, 2, _) => { let packet_identifier = src.try_get_u16_be()?; let packet_identifier = match super::PacketIdentifier::new(packet_identifier) { Some(packet_identifier) => packet_identifier, None => return Err(super::DecodeError::ZeroPacketIdentifier), }; let mut subscribe_to = vec![]; while !src.is_empty() { let topic_filter = super::Utf8StringCodec::default() .decode(&mut src)? .ok_or(super::DecodeError::IncompletePacket)?; let qos = match src.try_get_u8()? { 0x00 => QoS::AtMostOnce, 0x01 => QoS::AtLeastOnce, 0x02 => QoS::ExactlyOnce, qos => return Err(super::DecodeError::UnrecognizedQoS(qos)), }; subscribe_to.push(SubscribeTo { topic_filter, qos }); } if subscribe_to.is_empty() { return Err(super::DecodeError::NoTopics); } Ok(Some(Packet::Subscribe { packet_identifier, subscribe_to, })) } (Packet::UNSUBACK, 0, 2) => { let packet_identifier = src.try_get_u16_be()?; let packet_identifier = match super::PacketIdentifier::new(packet_identifier) { Some(packet_identifier) => packet_identifier, None => return Err(super::DecodeError::ZeroPacketIdentifier), }; Ok(Some(Packet::UnsubAck { packet_identifier })) } (Packet::UNSUBSCRIBE, 2, _) => { let packet_identifier = src.try_get_u16_be()?; let packet_identifier = match super::PacketIdentifier::new(packet_identifier) { Some(packet_identifier) => packet_identifier, None => return Err(super::DecodeError::ZeroPacketIdentifier), }; let mut unsubscribe_from = vec![]; while !src.is_empty() { unsubscribe_from.push( super::Utf8StringCodec::default() .decode(&mut src)? .ok_or(super::DecodeError::IncompletePacket)?, ); } if unsubscribe_from.is_empty() { return Err(super::DecodeError::NoTopics); } Ok(Some(Packet::Unsubscribe { packet_identifier, unsubscribe_from, })) } (packet_type, flags, remaining_length) => Err(super::DecodeError::UnrecognizedPacket { packet_type, flags, remaining_length, }), } } } impl tokio::codec::Encoder for PacketCodec { type Item = Packet; type Error = super::EncodeError; fn encode(&mut self, item: Self::Item, dst: &mut bytes::BytesMut) -> Result<(), Self::Error> { dst.reserve(std::mem::size_of::<u8>() + 4 * std::mem::size_of::<u8>()); match item { Packet::ConnAck { session_present, return_code, } => encode_packet(dst, Packet::CONNACK, |dst| { if session_present { dst.append_u8(0x01); } else { dst.append_u8(0x00); } dst.append_u8(return_code.into()); Ok(()) })?, Packet::Connect { username, password, will, client_id, keep_alive, } => encode_packet(dst, Packet::CONNECT, |dst| { super::Utf8StringCodec::default().encode("MQTT".to_string(), dst)?; dst.append_u8(0x04_u8); { let mut connect_flags = 0x00_u8; if username.is_some() { connect_flags |= 0x80; } if password.is_some() { connect_flags |= 0x40; } if let Some(will) = &will { if will.retain { connect_flags |= 0x20; } connect_flags |= match will.qos { QoS::AtMostOnce => 0x00, QoS::AtLeastOnce => 0x08, QoS::ExactlyOnce => 0x10, }; connect_flags |= 0x04; } match client_id { super::ClientId::ServerGenerated | super::ClientId::IdWithCleanSession(_) => connect_flags |= 0x02, super::ClientId::IdWithExistingSession(_) => (), } dst.append_u8(connect_flags); } { #[allow(clippy::cast_possible_truncation)] let keep_alive = match keep_alive { keep_alive if keep_alive.as_secs() <= u64::from(u16::max_value()) => { keep_alive.as_secs() as u16 } keep_alive => return Err(super::EncodeError::KeepAliveTooHigh(keep_alive)), }; dst.append_u16_be(keep_alive); } match client_id { super::ClientId::ServerGenerated => { super::Utf8StringCodec::default().encode("".to_string(), dst)? } super::ClientId::IdWithCleanSession(id) | super::ClientId::IdWithExistingSession(id) => { super::Utf8StringCodec::default().encode(id, dst)? } } if let Some(will) = will { super::Utf8StringCodec::default().encode(will.topic_name, dst)?; #[allow(clippy::cast_possible_truncation)] let will_len = match will.payload.len() { will_len if will_len <= u16::max_value() as usize => will_len as u16, will_len => return Err(super::EncodeError::WillTooLarge(will_len)), }; dst.append_u16_be(will_len); dst.extend_from_slice(&will.payload); } if let Some(username) = username { super::Utf8StringCodec::default().encode(username, dst)?; } if let Some(password) = password { super::Utf8StringCodec::default().encode(password, dst)?; } Ok(()) })?, Packet::Disconnect => encode_packet(dst, Packet::DISCONNECT, |_| Ok(()))?, Packet::PingReq => encode_packet(dst, Packet::PINGREQ, |_| Ok(()))?, Packet::PingResp => encode_packet(dst, Packet::PINGRESP, |_| Ok(()))?, Packet::PubAck { packet_identifier } => encode_packet(dst, Packet::PUBACK, |dst| { dst.append_packet_identifier(packet_identifier); Ok(()) })?, Packet::PubComp { packet_identifier } => encode_packet(dst, Packet::PUBCOMP, |dst| { dst.append_packet_identifier(packet_identifier); Ok(()) })?, Packet::Publish { packet_identifier_dup_qos, retain, topic_name, payload, } => { let mut packet_type = Packet::PUBLISH; packet_type |= match packet_identifier_dup_qos { PacketIdentifierDupQoS::AtMostOnce => 0x00, PacketIdentifierDupQoS::AtLeastOnce(_, true) => 0x0A, PacketIdentifierDupQoS::AtLeastOnce(_, false) => 0x02, PacketIdentifierDupQoS::ExactlyOnce(_, true) => 0x0C, PacketIdentifierDupQoS::ExactlyOnce(_, false) => 0x04, }; if retain { packet_type |= 0x01; } encode_packet(dst, packet_type, |dst| { super::Utf8StringCodec::default().encode(topic_name, dst)?; match packet_identifier_dup_qos { PacketIdentifierDupQoS::AtMostOnce => (), PacketIdentifierDupQoS::AtLeastOnce(packet_identifier, _) | PacketIdentifierDupQoS::ExactlyOnce(packet_identifier, _) => { dst.append_packet_identifier(packet_identifier) } } dst.extend_from_slice(&payload); Ok(()) })?; } Packet::PubRec { packet_identifier } => encode_packet(dst, Packet::PUBREC, |dst| { dst.append_packet_identifier(packet_identifier); Ok(()) })?, Packet::PubRel { packet_identifier } => { encode_packet(dst, Packet::PUBREL | 0x02, |dst| { dst.append_packet_identifier(packet_identifier); Ok(()) })? } Packet::SubAck { packet_identifier, qos, } => encode_packet(dst, Packet::SUBACK, |dst| { dst.append_packet_identifier(packet_identifier); for qos in qos { dst.append_u8(qos.into()); } Ok(()) })?, Packet::Subscribe { packet_identifier, subscribe_to, } => encode_packet(dst, Packet::SUBSCRIBE | 0x02, |dst| { dst.append_packet_identifier(packet_identifier); for SubscribeTo { topic_filter, qos } in subscribe_to { super::Utf8StringCodec::default().encode(topic_filter, dst)?; dst.append_u8(qos.into()); } Ok(()) })?, Packet::UnsubAck { packet_identifier } => { encode_packet(dst, Packet::UNSUBACK, |dst| { dst.append_packet_identifier(packet_identifier); Ok(()) })? } Packet::Unsubscribe { packet_identifier, unsubscribe_from, } => encode_packet(dst, Packet::UNSUBSCRIBE | 0x02, |dst| { dst.append_packet_identifier(packet_identifier); for unsubscribe_from in unsubscribe_from { super::Utf8StringCodec::default().encode(unsubscribe_from, dst)?; } Ok(()) })?, } Ok(()) } } fn encode_packet<F>( dst: &mut bytes::BytesMut, packet_type: u8, f: F, ) -> Result<(), super::EncodeError> where F: FnOnce(&mut bytes::BytesMut) -> Result<(), super::EncodeError>, { use tokio::codec::Encoder; let mut remaining_dst = bytes::BytesMut::new(); f(&mut remaining_dst)?; dst.append_u8(packet_type); super::RemainingLengthCodec::default().encode(remaining_dst.len(), dst)?; dst.extend_from_slice(&remaining_dst); Ok(()) }
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn serialize_operation_add_tags( input: &crate::input::AddTagsInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_add_tags_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_batch_prediction( input: &crate::input::CreateBatchPredictionInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_batch_prediction_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_data_source_from_rds( input: &crate::input::CreateDataSourceFromRdsInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_data_source_from_rds_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_data_source_from_redshift( input: &crate::input::CreateDataSourceFromRedshiftInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_data_source_from_redshift_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_data_source_from_s3( input: &crate::input::CreateDataSourceFromS3Input, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_data_source_from_s3_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_evaluation( input: &crate::input::CreateEvaluationInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_evaluation_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_ml_model( input: &crate::input::CreateMlModelInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_ml_model_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_realtime_endpoint( input: &crate::input::CreateRealtimeEndpointInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_realtime_endpoint_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_delete_batch_prediction( input: &crate::input::DeleteBatchPredictionInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_delete_batch_prediction_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_delete_data_source( input: &crate::input::DeleteDataSourceInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_delete_data_source_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_delete_evaluation( input: &crate::input::DeleteEvaluationInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_delete_evaluation_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_delete_ml_model( input: &crate::input::DeleteMlModelInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_delete_ml_model_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_delete_realtime_endpoint( input: &crate::input::DeleteRealtimeEndpointInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_delete_realtime_endpoint_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_delete_tags( input: &crate::input::DeleteTagsInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_delete_tags_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_describe_batch_predictions( input: &crate::input::DescribeBatchPredictionsInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_describe_batch_predictions_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_describe_data_sources( input: &crate::input::DescribeDataSourcesInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_describe_data_sources_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_describe_evaluations( input: &crate::input::DescribeEvaluationsInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_describe_evaluations_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_describe_ml_models( input: &crate::input::DescribeMlModelsInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_describe_ml_models_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_describe_tags( input: &crate::input::DescribeTagsInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_describe_tags_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_batch_prediction( input: &crate::input::GetBatchPredictionInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_batch_prediction_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_data_source( input: &crate::input::GetDataSourceInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_data_source_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_evaluation( input: &crate::input::GetEvaluationInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_evaluation_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_ml_model( input: &crate::input::GetMlModelInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_ml_model_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_predict( input: &crate::input::PredictInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_predict_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_update_batch_prediction( input: &crate::input::UpdateBatchPredictionInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_update_batch_prediction_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_update_data_source( input: &crate::input::UpdateDataSourceInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_update_data_source_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_update_evaluation( input: &crate::input::UpdateEvaluationInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_update_evaluation_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_update_ml_model( input: &crate::input::UpdateMlModelInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_update_ml_model_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) }
#![feature(specialization)] use dbgify::*; fn main() { #[dbgify] fn test(x: &mut Vec<String>) { let _y = 10; bp!(); x.push(" world".into()); } let mut x = vec!["hello".to_string()]; test(&mut x); }
/* * Author: Dave Eddy <dave@daveeddy.com> * Date: January 26, 2022 * License: MIT */ //! Generic service related structs and enums. use libc::pid_t; use std::fmt; use std::path::Path; use std::time; use anyhow::Result; use yansi::{Color, Style}; use crate::runit::{RunitService, RunitServiceState}; use crate::utils; /// Possible states for a service. pub enum ServiceState { Run, Down, Finish, Unknown, } impl ServiceState { /// Get a suitable `yansi::Style` for the state. pub fn get_style(&self) -> Style { let style = Style::default(); let color = match self { ServiceState::Run => Color::Green, ServiceState::Down => Color::Red, ServiceState::Finish => Color::Yellow, ServiceState::Unknown => Color::Yellow, }; style.fg(color) } /// Get a suitable char for the state (as a `String`). pub fn get_char(&self) -> String { let s = match self { ServiceState::Run => "✔", ServiceState::Down => "X", ServiceState::Finish => "X", ServiceState::Unknown => "?", }; s.to_string() } } impl fmt::Display for ServiceState { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let s = match self { ServiceState::Run => "run", ServiceState::Down => "down", ServiceState::Finish => "finish", ServiceState::Unknown => "n/a", }; s.fmt(f) } } /** * A struct suitable for describing an abstract service. * * This struct itself doesn't do much - it just stores information about a * service and knows how to format it to look pretty. */ pub struct Service { name: String, state: ServiceState, enabled: bool, command: Option<String>, pid: Option<pid_t>, start_time: Result<time::SystemTime>, pstree: Option<Result<String>>, } impl Service { /// Create a new service from a `RunitService`. pub fn from_runit_service( service: &RunitService, want_pstree: bool, proc_path: &Path, pstree_prog: &str, ) -> (Self, Vec<String>) { let mut messages: Vec<String> = vec![]; let name = service.name.to_string(); let enabled = service.enabled(); let pid = service.get_pid(); let state = service.get_state(); let start_time = service.get_start_time(); let mut command = None; if let Ok(p) = pid { match utils::cmd_from_pid(p, proc_path) { Ok(cmd) => { command = Some(cmd); } Err(err) => { messages.push(format!( "{:?}: failed to get command for pid {}: {:?}", service.path, p, err )); } }; } let pid = match pid { Ok(pid) => Some(pid), Err(ref err) => { messages.push(format!( "{:?}: failed to get pid: {}", service.path, err )); None } }; // optionally get pstree. None if the user wants it, Some if the user // wants it regardless of execution success. let pstree = if want_pstree { pid.map(|pid| get_pstree(pid, pstree_prog)) } else { None }; let state = match state { RunitServiceState::Run => ServiceState::Run, RunitServiceState::Down => ServiceState::Down, RunitServiceState::Finish => ServiceState::Finish, RunitServiceState::Unknown => ServiceState::Unknown, }; let svc = Self { name, state, enabled, command, pid, start_time, pstree }; (svc, messages) } /// Format the service name as a string. fn format_name(&self) -> (String, Style) { (self.name.to_string(), Style::default()) } /// Format the service char as a string. fn format_status_char(&self) -> (String, Style) { (self.state.get_char(), self.state.get_style()) } /// Format the service state as a string. fn format_state(&self) -> (String, Style) { (self.state.to_string(), self.state.get_style()) } /// Format the service enabled status as a string. fn format_enabled(&self) -> (String, Style) { let style = match self.enabled { true => Style::default().fg(Color::Green), false => Style::default().fg(Color::Red), }; let s = self.enabled.to_string(); (s, style) } /// Format the service pid as a string. fn format_pid(&self) -> (String, Style) { let style = Style::default().fg(Color::Magenta); let s = match self.pid { Some(pid) => pid.to_string(), None => String::from("---"), }; (s, style) } /// Format the service command a string. fn format_command(&self) -> (String, Style) { let style = Style::default().fg(Color::Green); let s = match &self.command { Some(cmd) => cmd.clone(), None => String::from("---"), }; (s, style) } /// Format the service time as a string. fn format_time(&self) -> (String, Style) { let style = Style::default(); let time = match &self.start_time { Ok(time) => time, Err(err) => return (err.to_string(), style.fg(Color::Red)), }; let t = match time.elapsed() { Ok(t) => t, Err(err) => return (err.to_string(), style.fg(Color::Red)), }; let s = utils::relative_duration(&t); let style = match t.as_secs() { t if t < 5 => style.fg(Color::Red), t if t < 30 => style.fg(Color::Yellow), _ => style.dimmed(), }; (s, style) } /// Format the service `pstree` output as a string. pub fn format_pstree(&self) -> (String, Style) { let style = Style::default(); let tree = match &self.pstree { Some(tree) => tree, None => return ("".into(), style), }; let (tree_s, style) = match tree { Ok(stdout) => (stdout.trim().into(), style.dimmed()), Err(err) => { (format!("pstree call failed: {}", err), style.fg(Color::Red)) } }; (format!("\n{}\n", tree_s), style) } } impl fmt::Display for Service { /// Format the service as a string suitable for output by `vsv`. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let base = utils::format_status_line( self.format_status_char(), self.format_name(), self.format_state(), self.format_enabled(), self.format_pid(), self.format_command(), self.format_time(), ); base.fmt(f) } } /// Get the `pstree` for a given pid. fn get_pstree(pid: pid_t, pstree_prog: &str) -> Result<String> { let cmd = pstree_prog.to_string(); let args = ["-ac".to_string(), pid.to_string()]; utils::run_program_get_output(&cmd, &args) }
use libc::*; use core_foundation_sys::array::*; use core_foundation_sys::base::*; use core_foundation_sys::data::*; use core_foundation_sys::string::*; pub type CFHostRef = *const c_void; extern { pub fn CFHostGetTypeID() -> CFTypeID; pub fn CFHostCreateWithName(allocator: CFAllocatorRef, hostname: CFStringRef) -> CFHostRef; pub fn CFHostCreateWithAddress(allocator: CFAllocatorRef, addr: CFDataRef) -> CFHostRef; } #[allow(non_camel_case_types)] #[repr(C)] pub enum CFHostInfoType { kCFHostAddresses = 0, kCFHostNames = 1, kCFHostReachability = 2 } extern { pub fn CFHostCancelInfoResolution(host: CFHostRef, info: CFHostInfoType); pub fn CFHostGetAddressing(host: CFHostRef, resolved: *mut bool) -> CFArrayRef; pub fn CFHostGetNames(host: CFHostRef, resolved: *mut bool) -> CFArrayRef; pub fn CFHostGetReachability(host: CFHostRef, resolved: *mut bool) -> CFArrayRef; } extern { //pub fn CFHostStartInfoResolution(host: CFHostRef, info: CFHostInfoType, *error: *mut CFStreamError) -> bool; }
use std::{borrow::Cow, fmt}; use serde::{de::DeserializeOwned, Serialize}; use crate::parser::{ParseError, ScalarToken}; pub use juniper_codegen::ScalarValue; /// The result of converting a string into a scalar value pub type ParseScalarResult<S = DefaultScalarValue> = Result<S, ParseError>; /// A trait used to convert a `ScalarToken` into a certain scalar value type pub trait ParseScalarValue<S = DefaultScalarValue> { /// See the trait documentation fn from_str(value: ScalarToken<'_>) -> ParseScalarResult<S>; } /// A trait marking a type that could be used as internal representation of /// scalar values in juniper /// /// The main objective of this abstraction is to allow other libraries to /// replace the default representation with something that better fits their /// needs. /// There is a custom derive (`#[derive(`[`ScalarValue`]`)]`) available that /// implements most of the required traits automatically for a enum representing /// a scalar value. However, [`Serialize`] and [`Deserialize`] implementations /// are expected to be provided. /// /// # Implementing a new scalar value representation /// The preferred way to define a new scalar value representation is /// defining a enum containing a variant for each type that needs to be /// represented at the lowest level. /// The following example introduces an new variant that is able to store 64 bit /// integers. /// /// ```rust /// # use std::fmt; /// # /// # use serde::{de, Deserialize, Deserializer, Serialize}; /// # use juniper::ScalarValue; /// # /// #[derive(Clone, Debug, PartialEq, ScalarValue, Serialize)] /// #[serde(untagged)] /// enum MyScalarValue { /// #[value(as_float, as_int)] /// Int(i32), /// Long(i64), /// #[value(as_float)] /// Float(f64), /// #[value(as_str, as_string, into_string)] /// String(String), /// #[value(as_bool)] /// Boolean(bool), /// } /// /// impl<'de> Deserialize<'de> for MyScalarValue { /// fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> { /// struct Visitor; /// /// impl<'de> de::Visitor<'de> for Visitor { /// type Value = MyScalarValue; /// /// fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { /// f.write_str("a valid input value") /// } /// /// fn visit_bool<E: de::Error>(self, b: bool) -> Result<Self::Value, E> { /// Ok(MyScalarValue::Boolean(b)) /// } /// /// fn visit_i32<E: de::Error>(self, n: i32) -> Result<Self::Value, E> { /// Ok(MyScalarValue::Int(n)) /// } /// /// fn visit_i64<E: de::Error>(self, n: i64) -> Result<Self::Value, E> { /// if n <= i64::from(i32::MAX) { /// self.visit_i32(n.try_into().unwrap()) /// } else { /// Ok(MyScalarValue::Long(n)) /// } /// } /// /// fn visit_u32<E: de::Error>(self, n: u32) -> Result<Self::Value, E> { /// if n <= i32::MAX as u32 { /// self.visit_i32(n.try_into().unwrap()) /// } else { /// self.visit_u64(n.into()) /// } /// } /// /// fn visit_u64<E: de::Error>(self, n: u64) -> Result<Self::Value, E> { /// if n <= i64::MAX as u64 { /// self.visit_i64(n.try_into().unwrap()) /// } else { /// // Browser's `JSON.stringify()` serialize all numbers /// // having no fractional part as integers (no decimal /// // point), so we must parse large integers as floating /// // point, otherwise we would error on transferring large /// // floating point numbers. /// Ok(MyScalarValue::Float(n as f64)) /// } /// } /// /// fn visit_f64<E: de::Error>(self, f: f64) -> Result<Self::Value, E> { /// Ok(MyScalarValue::Float(f)) /// } /// /// fn visit_str<E: de::Error>(self, s: &str) -> Result<Self::Value, E> { /// self.visit_string(s.into()) /// } /// /// fn visit_string<E: de::Error>(self, s: String) -> Result<Self::Value, E> { /// Ok(MyScalarValue::String(s)) /// } /// } /// /// de.deserialize_any(Visitor) /// } /// } /// ``` /// /// [`Deserialize`]: trait@serde::Deserialize /// [`Serialize`]: trait@serde::Serialize pub trait ScalarValue: fmt::Debug + fmt::Display + PartialEq + Clone + DeserializeOwned + Serialize + From<String> + From<bool> + From<i32> + From<f64> + 'static { /// Checks whether this [`ScalarValue`] contains the value of the given /// type. /// /// ``` /// # use juniper::{ScalarValue, DefaultScalarValue}; /// # /// let value = DefaultScalarValue::Int(42); /// /// assert_eq!(value.is_type::<i32>(), true); /// assert_eq!(value.is_type::<f64>(), false); /// ``` #[must_use] fn is_type<'a, T>(&'a self) -> bool where T: 'a, Option<&'a T>: From<&'a Self>, { <Option<&'a T>>::from(self).is_some() } /// Represents this [`ScalarValue`] as an integer value. /// /// This function is used for implementing [`GraphQLValue`] for [`i32`] for /// all possible [`ScalarValue`]s. Implementations should convert all the /// supported integer types with 32 bit or less to an integer, if requested. /// /// [`GraphQLValue`]: crate::GraphQLValue #[must_use] fn as_int(&self) -> Option<i32>; /// Represents this [`ScalarValue`] as a [`String`] value. /// /// This function is used for implementing [`GraphQLValue`] for [`String`] /// for all possible [`ScalarValue`]s. /// /// [`GraphQLValue`]: crate::GraphQLValue #[must_use] fn as_string(&self) -> Option<String>; /// Converts this [`ScalarValue`] into a [`String`] value. /// /// Same as [`ScalarValue::as_string()`], but takes ownership, so allows to /// omit redundant cloning. #[must_use] fn into_string(self) -> Option<String>; /// Represents this [`ScalarValue`] as a [`str`] value. /// /// This function is used for implementing [`GraphQLValue`] for [`str`] for /// all possible [`ScalarValue`]s. /// /// [`GraphQLValue`]: crate::GraphQLValue #[must_use] fn as_str(&self) -> Option<&str>; /// Represents this [`ScalarValue`] as a float value. /// /// This function is used for implementing [`GraphQLValue`] for [`f64`] for /// all possible [`ScalarValue`]s. Implementations should convert all /// supported integer types with 64 bit or less and all floating point /// values with 64 bit or less to a float, if requested. /// /// [`GraphQLValue`]: crate::GraphQLValue #[must_use] fn as_float(&self) -> Option<f64>; /// Represents this [`ScalarValue`] as a boolean value /// /// This function is used for implementing [`GraphQLValue`] for [`bool`] for /// all possible [`ScalarValue`]s. /// /// [`GraphQLValue`]: crate::GraphQLValue fn as_bool(&self) -> Option<bool>; /// Converts this [`ScalarValue`] into another one. fn into_another<S: ScalarValue>(self) -> S { if let Some(i) = self.as_int() { S::from(i) } else if let Some(f) = self.as_float() { S::from(f) } else if let Some(b) = self.as_bool() { S::from(b) } else if let Some(s) = self.into_string() { S::from(s) } else { unreachable!("`ScalarValue` must represent at least one of the GraphQL spec types") } } } /// The default [`ScalarValue`] representation in [`juniper`]. /// /// These types closely follow the [GraphQL specification][0]. /// /// [0]: https://spec.graphql.org/October2021 #[derive(Clone, Debug, PartialEq, ScalarValue, Serialize)] #[serde(untagged)] pub enum DefaultScalarValue { /// [`Int` scalar][0] as a signed 32‐bit numeric non‐fractional value. /// /// [0]: https://spec.graphql.org/October2021#sec-Int #[value(as_float, as_int)] Int(i32), /// [`Float` scalar][0] as a signed double‐precision fractional values as /// specified by [IEEE 754]. /// /// [0]: https://spec.graphql.org/October2021#sec-Float /// [IEEE 754]: https://en.wikipedia.org/wiki/IEEE_floating_point #[value(as_float)] Float(f64), /// [`String` scalar][0] as a textual data, represented as UTF‐8 character /// sequences. /// /// [0]: https://spec.graphql.org/October2021#sec-String #[value(as_str, as_string, into_string)] String(String), /// [`Boolean` scalar][0] as a `true` or `false` value. /// /// [0]: https://spec.graphql.org/October2021#sec-Boolean #[value(as_bool)] Boolean(bool), } impl<'a> From<&'a str> for DefaultScalarValue { fn from(s: &'a str) -> Self { Self::String(s.into()) } } impl<'a> From<Cow<'a, str>> for DefaultScalarValue { fn from(s: Cow<'a, str>) -> Self { Self::String(s.into()) } }
// Copyright 2018 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. // only-x86_64 #![allow(dead_code, non_upper_case_globals)] #![feature(asm)] #[repr(C)] pub struct D32x4(f32,f32,f32,f32); impl D32x4 { fn add(&self, vec: Self) -> Self { unsafe { let ret: Self; asm!(" movaps $1, %xmm1 movaps $2, %xmm2 addps %xmm1, %xmm2 movaps $xmm1, $0 " : "=r"(ret) : "1"(self), "2"(vec) : "xmm1", "xmm2" ); ret } } } fn main() { }
use clap::Clap; use day03_01::{Slope, Square, Topology}; use std::fs::read_to_string; #[derive(Clap)] struct Opts { input: String, } fn main() -> Result<(), std::io::Error> { let opts: Opts = Opts::parse(); let input = read_to_string(opts.input)?; let squares = parse(&input).unwrap(); let topology = Topology { squares: &squares, height: squares.len(), width: squares.first().unwrap().len(), }; let num_trees = topology .iter(&Slope { horizontal: 3, vertical: 1, }) .filter(|square| square.is_tree()) .count(); println!("{}", num_trees); Ok(()) } fn parse(input: &str) -> Option<Vec<Vec<Square>>> { input .lines() .map(|l| { l.chars() .map(|c| match c { '.' => Some(Square::Empty), '#' => Some(Square::Tree), _ => None, }) .collect() }) .collect() }
use super::common_type::*; #[derive(Clone, Debug, PartialEq)] pub enum AccessFlagKind { PUBLIC, PRIVATE, PROTECTED, STATIC, FINAL, SYNCHRONIZED, BRIDGE, VARARGS, NATIVE, ABSTRACT, STRICT, SYNTHETIC, } #[derive(Clone, Debug, PartialEq)] pub struct AccessFlags(Vec<AccessFlagKind>); impl From<u2> for AccessFlags { fn from(n: u2) -> Self { use AccessFlagKind::*; let mut v = vec![]; let mut n = n; macro_rules! push { ($value: expr, $kind: ident) => { if n >= $value { v.push($kind); n -= $value; } }; } push!(0x1000, SYNTHETIC); push!(0x0800, STRICT); push!(0x0400, ABSTRACT); push!(0x0100, NATIVE); push!(0x0080, VARARGS); push!(0x0040, BRIDGE); push!(0x0020, SYNCHRONIZED); push!(0x0010, FINAL); push!(0x0008, STATIC); push!(0x0004, PROTECTED); push!(0x0002, PRIVATE); push!(0x0001, PUBLIC); Self(v) } }
pub fn get_addresses_in_from_header(from_header: &str) -> std::vec::Vec<String> { lazy_static::lazy_static! { static ref REGEX : regex::Regex = regex::Regex::new("(?:[^<@\\s]*@[^\\s>,]*)|(?:\"[^\"@]*\"@[^\\s>,]*)").unwrap(); } REGEX .find_iter(from_header) .map(|elem| elem.as_str().to_string()) .collect() } #[cfg(test)] mod tests { #[test] fn parse_mails() { assert_eq!( super::get_addresses_in_from_header( "foo@bar, Frank Rotzelpü <frank@göckel.com>, Murkel <\"my murkel\"@localhost" ), std::vec!("foo@bar", "frank@göckel.com", "\"my murkel\"@localhost") ); } }
#[cfg(test)] mod tests { use crate::{Point, Message, Color}; #[test] fn it_works() { assert_eq!(2 + 2, 4); } #[test] fn syntax() { // matching literals let x = 1; match x { 1 => println!("one"), 2 => println!("two"), _ => println!("others"), } // matching named variables let x = Some(5); match x { Some(y) => println!("y = {:?}", y), _ => println!("others"), } // multiple pattern let x = 1; match x { 1 | 2 => println!("one or two"), _ => println!("others"), } // matching ranges of values let x = 5; match x { 1..=5 => println!("one through five"), _ => println!("others"), } } #[test] fn destruct() { // destructuring structs let p = Point { x: 0, y: 7 }; let Point { x: a, y: b } = p; // a and b are variables let Point { x, y } = p; // x and y are variables match p { // destruct with literal values Point { x, y: 0 } => println!("y is zero"), Point { x: 0, y } => println!("x is zero"), Point { x, y } => println!("others") } // destructuring enums // mentioned before, like Option<T>, Result<T, E> // destructuring nested structs and enums let msg = Message::ChangeColor(Color::Hsv(0, 160, 255)); match msg { Message::ChangeColor(Color::Rgb(r, g, b)) => println!("rgb"); Message::ChangeColor(Color::Hsv(g, s, v)) => println!("hsv"), _ => println!("others"), } // destructuring structs and tuples let ((feet, inches), Point { x, y }) = ((3, 10), Point { x: 3, y: -10 }); } #[test] fn ignore() { // ignoring an entire value with _ fn foo(_: i32, y: i32) {} // ignoring parts of a value with a nested _ let numbers = (2, 4, 8, 16, 32); match numbers { (first, _, third, _, fifth) => println!("numbers"), } // ignoring an unused variable by starting its name with _ let _x = 5; // no compile warning even though _x is not used anywhere // ignoring remaining parts of a value with .. let numbers = (2, 4, 8, 16, 32); match numbers { (first, .., last) => println!("first and last"), } } #[test] fn guard() { let num = Some(4); match num { Some(x) if x < 5 => println!("x < 5"), Some(x) => println!("other x"), _ => println!("others"), } } #[test] fn at() { enum Msg { Hello { id: i32 }, } let msg = Msg::Hello { id: 5 }; match msg { Msg::Hello { id: id_var @ 3..=7, } => println!("id: {}", id_var), Msg::Hello { id: 10..=12 } => println!("10 to 12"), Msg::Hello { id } => println!("other"), } } } struct Point { x: i32, y: i32, } struct Point3D { x: i32, y: i32, z: i32, } enum Color { Rgb(i32, i32, i32), Hsv(i32, i32, i32), } enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(Color), }