text
stringlengths
8
4.13M
#[cfg(test)] mod tests { use counter::Counter; use rand::Rng; #[test] fn test_composite_add_sub() { let mut counts = Counter::<_>::init( "able babble table babble rabble table able fable scrabble".split_whitespace(), ); // add or subtract an iterable of the same type counts += "cain and abel fable table cable".split_whitespace(); // or add or subtract from another Counter of the same type let other_counts = Counter::init("scrabble cabbie fable babble".split_whitespace()); let _diff = counts - other_counts; } #[test] fn test_most_common() { let counter = Counter::init("abbccc".chars()); let by_common = counter.most_common(); let expected = vec![('c', 3), ('b', 2), ('a', 1)]; assert!(by_common == expected); } #[test] fn test_most_common_tiebreaker() { let counter = Counter::init("eaddbbccc".chars()); let by_common = counter.most_common_tiebreaker(|&a, &b| a.cmp(&b)); let expected = vec![('c', 3), ('b', 2), ('d', 2), ('a', 1), ('e', 1)]; assert!(by_common == expected); } #[test] fn test_most_common_tiebreaker_reversed() { let counter = Counter::init("eaddbbccc".chars()); let by_common = counter.most_common_tiebreaker(|&a, &b| b.cmp(&a)); let expected = vec![('c', 3), ('d', 2), ('b', 2), ('e', 1), ('a', 1)]; assert!(by_common == expected); } // The main purpose of this test is to see that we can call `Counter::most_common_tiebreaker()` // with a closure that is `FnMut` but not `Fn`. #[test] fn test_most_common_tiebreaker_fn_mut() { let counter: Counter<_> = Counter::init("abracadabra".chars()); // Count how many times the tiebreaker closure is called. let mut num_ties = 0; let sorted = counter.most_common_tiebreaker(|a, b| { num_ties += 1; a.cmp(b) }); let expected = vec![('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]; assert_eq!(sorted, expected); // We should have called the tiebreaker twice: once to resolve the tie between `'b'` and // `'r'` and once to resolve the tie between `'c'` and `'d'`. assert_eq!(num_ties, 2); } #[test] fn test_most_common_ordered() { let counter = Counter::init("eaddbbccc".chars()); let by_common = counter.most_common_ordered(); let expected = vec![('c', 3), ('b', 2), ('d', 2), ('a', 1), ('e', 1)]; assert!(by_common == expected); } #[test] fn test_k_most_common_ordered() { let counter: Counter<_> = "abracadabra".chars().collect(); let all = counter.most_common_ordered(); for k in 0..=counter.len() { let topk = counter.k_most_common_ordered(k); assert_eq!(&topk, &all[..k]); } } /// This test is fundamentally the same as `test_k_most_common_ordered`, but it operates on /// a wider variety of data. In particular, it tests both longer, narrower, and wider /// distributions of data than the other test does. #[test] fn test_k_most_common_ordered_heavy() { let mut rng = rand::thread_rng(); for container_size in [5, 10, 25, 100, 256] { for max_value_factor in [0.25, 0.5, 1.0, 1.25, 2.0, 10.0, 100.0] { let max_value = ((container_size as f64) * max_value_factor) as u32; let mut values = vec![0; container_size]; for value in values.iter_mut() { *value = rng.gen_range(0..=max_value); } let counter: Counter<_> = values.into_iter().collect(); let all = counter.most_common_ordered(); for k in 0..=counter.len() { let topk = counter.k_most_common_ordered(k); assert_eq!(&topk, &all[..k]); } } } } #[test] fn test_total() { let counter = Counter::init("".chars()); let total: usize = counter.total(); assert_eq!(total, 0); let counter = Counter::init("eaddbbccc".chars()); let total: usize = counter.total(); assert_eq!(total, 9); } #[test] fn test_add() { let d = Counter::<_>::init("abbccc".chars()); let e = Counter::<_>::init("bccddd".chars()); let out = d + e; let expected = Counter::init("abbbcccccddd".chars()); assert!(out == expected); } #[test] fn test_sub() { let d = Counter::<_>::init("abbccc".chars()); let e = Counter::<_>::init("bccddd".chars()); let out = d - e; let expected = Counter::init("abc".chars()); assert!(out == expected); } #[test] fn test_intersection() { let d = Counter::<_>::init("abbccc".chars()); let e = Counter::<_>::init("bccddd".chars()); let out = d & e; let expected = Counter::init("bcc".chars()); assert!(out == expected); } #[test] fn test_union() { let d = Counter::<_>::init("abbccc".chars()); let e = Counter::<_>::init("bccddd".chars()); let out = d | e; let expected = Counter::init("abbcccddd".chars()); assert!(out == expected); } #[test] fn test_delete_key_from_backing_map() { let mut counter = Counter::<_>::init("aa-bb-cc".chars()); counter.remove(&'-'); assert!(counter == Counter::init("aabbcc".chars())); } #[test] fn test_superset_non_usize_count() { let mut a: Counter<_, i8> = "abbcccc".chars().collect(); let mut b: Counter<_, i8> = "abb".chars().collect(); assert!(a.is_superset(&b)); // Negative values are possible, a is no longer a superset a[&'e'] = -1; assert!(!a.is_superset(&b)); // Adjust b to make a a superset again b[&'e'] = -2; assert!(a.is_superset(&b)); } #[test] fn test_subset_non_usize_count() { let mut a: Counter<_, i8> = "abb".chars().collect(); let mut b: Counter<_, i8> = "abbcccc".chars().collect(); assert!(a.is_subset(&b)); // Negative values are possible; a is no longer a subset b[&'e'] = -1; assert!(!a.is_subset(&b)); // Adjust a to make it a subset again a[&'e'] = -2; assert!(a.is_subset(&b)); } }
fn main() { proconio::input!{mut a:u64,b:u64,mut c:u64,d:u64}; let x = (c+b-1)/b; let y = (a+d-1)/d; println!("{}", if x<=y{"Yes"}else{"No"}) }
use std::{mem::size_of, rc::Rc}; use ash::vk; use gpu_allocator::{vulkan::Allocation, MemoryLocation}; use super::allocator::Allocator; const DEFAULT_STAGING_BUFFER_SIZE: u64 = 16 * 1024 * 1024; struct StagingBuffer { buffer: vk::Buffer, alloc: Allocation, mapping: *mut u8, pos: u64, size: u64, last_used_frame: u64, } /// This struct automatically manages a pool of staging buffers that can be used to upload data to GPU-only buffers and images. /// /// # Notes /// This struct has to be cleaned up manually by calling [`destroy()`](Uploader::destroy()). pub struct Uploader { device: Rc<ash::Device>, allocator: Rc<Allocator>, staging_buffers: Vec<StagingBuffer>, frame_counter: u64, max_frames_ahead: u64, command_pool: vk::CommandPool, command_buffers: Vec<vk::CommandBuffer>, fences: Vec<vk::Fence>, } impl Uploader { /// Creates a new [`Uploader`]. pub fn new( device: Rc<ash::Device>, allocator: Rc<Allocator>, max_frames_ahead: u64, queue_family: u32, ) -> Uploader { let pool_info = vk::CommandPoolCreateInfo::builder() .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER) .queue_family_index(queue_family) .build(); let command_pool = unsafe { device.create_command_pool(&pool_info, None) }.unwrap(); let alloc_info = vk::CommandBufferAllocateInfo::builder() .command_buffer_count(max_frames_ahead as u32) .command_pool(command_pool) .level(vk::CommandBufferLevel::PRIMARY) .build(); let command_buffers = unsafe { device.allocate_command_buffers(&alloc_info) }.unwrap(); let fence_info = vk::FenceCreateInfo::builder() .flags(vk::FenceCreateFlags::SIGNALED) .build(); let mut fences = Vec::with_capacity(max_frames_ahead as usize); for _ in 0..max_frames_ahead as usize { fences.push(unsafe { device.create_fence(&fence_info, None) }.unwrap()); } let res = Uploader { device, allocator, staging_buffers: Vec::new(), frame_counter: 0, max_frames_ahead, command_pool, command_buffers, fences, }; let command_buffer = res.command_buffers[0]; let begin_info = vk::CommandBufferBeginInfo::builder() .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT) .build(); unsafe { res.device .begin_command_buffer(command_buffer, &begin_info) .unwrap(); res.device.reset_fences(&[res.fences[0]]).unwrap(); } res } /// Destroys a [`Uploader`]. /// /// The object *must not* be used after calling this method. pub fn destroy(&mut self) { for fence in &self.fences { unsafe { self.device.destroy_fence(*fence, None); } } for buf in &self.staging_buffers { self.allocator.destroy_buffer(buf.buffer, buf.alloc.clone()); } unsafe { self.device.destroy_command_pool(self.command_pool, None); } } fn find_staging_buffer(&mut self, size: u64) -> usize { for (i, sb) in self.staging_buffers.iter_mut().enumerate() { // staging buffer was not used in any frame that might still be in flight, reset pos if self.frame_counter - sb.last_used_frame >= self.max_frames_ahead { sb.pos = 0; } if sb.size - sb.pos >= size { return i; } } // no staging buffer with enough capacity found, create a new one let new_size = (size + DEFAULT_STAGING_BUFFER_SIZE - 1) / DEFAULT_STAGING_BUFFER_SIZE * DEFAULT_STAGING_BUFFER_SIZE; log::trace!("Creating new staging buffer with size {}", new_size); let (buffer, alloc) = self .allocator .create_buffer( new_size, vk::BufferUsageFlags::TRANSFER_SRC, MemoryLocation::CpuToGpu, ) .unwrap(); let mapping = alloc.mapped_ptr().unwrap().as_ptr() as *mut u8; self.staging_buffers.push(StagingBuffer { buffer, alloc, mapping, pos: 0, size: new_size, last_used_frame: self.frame_counter, }); self.staging_buffers.len() - 1 } /// Enqueues a buffer upload command. /// /// The data upload will happend before any other vulkan commands are executed this frame. pub fn enqueue_buffer_upload<T>( &mut self, dest_buffer: vk::Buffer, dst_offset: u64, data: &[T], ) { let size = size_of::<T>() as u64 * data.len() as u64; let staging_buffer_index = self.find_staging_buffer(size); let staging_buffer = &mut self.staging_buffers[staging_buffer_index]; let command_buffer = self.command_buffers[(self.frame_counter % self.max_frames_ahead) as usize]; unsafe { staging_buffer .mapping .offset(staging_buffer.pos as isize) .copy_from_nonoverlapping(data.as_ptr() as *const u8, size as usize); let regions = [vk::BufferCopy { src_offset: staging_buffer.pos, dst_offset, size, }]; self.device.cmd_copy_buffer( command_buffer, staging_buffer.buffer, dest_buffer, &regions, ); } staging_buffer.pos += size; staging_buffer.last_used_frame = self.frame_counter; } /// Enqueues an image upload command. /// /// The image upload will happend before any other vulkan commands are executed this frame. /// /// Any previous contents of the image will be discarded. After upload, /// the image will be transitioned to the given `layout`. pub fn enqueue_image_upload( &mut self, dst_image: vk::Image, layout: vk::ImageLayout, width: u32, height: u32, pixels: &[u8], ) { let size = width as u64 * height as u64 * 4; let staging_buffer_index = self.find_staging_buffer(size); let staging_buffer = &mut self.staging_buffers[staging_buffer_index]; let command_buffer = self.command_buffers[(self.frame_counter % self.max_frames_ahead) as usize]; unsafe { staging_buffer .mapping .offset(staging_buffer.pos as isize) .copy_from_nonoverlapping(pixels.as_ptr() as *const u8, size as usize); let transition = vk::ImageMemoryBarrier::builder() .src_access_mask(vk::AccessFlags::empty()) .dst_access_mask(vk::AccessFlags::TRANSFER_WRITE) .old_layout(vk::ImageLayout::UNDEFINED) .new_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL) .src_queue_family_index(0) .dst_queue_family_index(0) .image(dst_image) .subresource_range(vk::ImageSubresourceRange { aspect_mask: vk::ImageAspectFlags::COLOR, base_mip_level: 0, level_count: 1, base_array_layer: 0, layer_count: 1, }) .build(); self.device.cmd_pipeline_barrier( command_buffer, vk::PipelineStageFlags::TOP_OF_PIPE, vk::PipelineStageFlags::TRANSFER, vk::DependencyFlags::BY_REGION, &[], &[], &[transition], ); let regions = [vk::BufferImageCopy::builder() .buffer_offset(staging_buffer.pos) .buffer_row_length(0) .buffer_image_height(0) .image_subresource(vk::ImageSubresourceLayers { aspect_mask: vk::ImageAspectFlags::COLOR, mip_level: 0, base_array_layer: 0, layer_count: 1, }) .image_offset(vk::Offset3D { x: 0, y: 0, z: 0 }) .image_extent(vk::Extent3D { width, height, depth: 1, }) .build()]; self.device.cmd_copy_buffer_to_image( command_buffer, staging_buffer.buffer, dst_image, vk::ImageLayout::TRANSFER_DST_OPTIMAL, &regions, ); let transition = vk::ImageMemoryBarrier::builder() .src_access_mask(vk::AccessFlags::TRANSFER_WRITE) .dst_access_mask(vk::AccessFlags::empty()) .old_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL) .new_layout(layout) .src_queue_family_index(0) .dst_queue_family_index(0) .image(dst_image) .subresource_range(vk::ImageSubresourceRange { aspect_mask: vk::ImageAspectFlags::COLOR, base_mip_level: 0, level_count: 1, base_array_layer: 0, layer_count: 1, }) .build(); self.device.cmd_pipeline_barrier( command_buffer, vk::PipelineStageFlags::TRANSFER, vk::PipelineStageFlags::TOP_OF_PIPE, vk::DependencyFlags::BY_REGION, &[], &[], &[transition], ); } staging_buffer.pos += size; staging_buffer.last_used_frame = self.frame_counter; } /// Submits all upload commands for the current frame. /// /// This method should be called once per frame before any rendering takes place. pub fn submit_uploads(&mut self, queue: vk::Queue) { let command_buffer = self.command_buffers[(self.frame_counter % self.max_frames_ahead) as usize]; unsafe { let mem_barrier = vk::MemoryBarrier::builder() .src_access_mask(vk::AccessFlags::TRANSFER_WRITE) .dst_access_mask(vk::AccessFlags::empty()) .build(); self.device.cmd_pipeline_barrier( command_buffer, vk::PipelineStageFlags::TRANSFER, vk::PipelineStageFlags::TOP_OF_PIPE, vk::DependencyFlags::BY_REGION, &[mem_barrier], &[], &[], ); self.device.end_command_buffer(command_buffer).unwrap(); } let command_buffers = [command_buffer]; let submit_info = vk::SubmitInfo::builder() .command_buffers(&command_buffers) .build(); unsafe { self.device .queue_submit( queue, &[submit_info], self.fences[(self.frame_counter % self.max_frames_ahead) as usize], ) .unwrap(); } self.frame_counter += 1; let command_buffer = self.command_buffers[(self.frame_counter % self.max_frames_ahead) as usize]; let fence = self.fences[(self.frame_counter % self.max_frames_ahead) as usize]; unsafe { self.device .wait_for_fences(&[fence], true, u64::MAX) .unwrap(); self.device.reset_fences(&[fence]).unwrap(); } let begin_info = vk::CommandBufferBeginInfo::builder() .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT) .build(); unsafe { self.device .begin_command_buffer(command_buffer, &begin_info) .unwrap(); } // delete staging buffers after not being used for 10 frames self.staging_buffers.retain(|b| { if self.frame_counter - b.last_used_frame >= 10 { self.allocator.destroy_buffer(b.buffer, b.alloc.clone()); log::trace!( "Deleting staging buffer of size {}, offset={}, last used {} frames ago", b.size, b.pos, self.frame_counter - b.last_used_frame ); false } else { true } }); } }
use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use super::types; use super::types::MalType::{List, Symbol, Vector}; use super::types::{new_list, MalResult, MalValue}; pub struct EnvData { data: HashMap<String, MalValue>, outer: Option<Env>, } /// Main Trait to interact with a Make A Lisp Environment. pub trait Environment: Clone + Sized { /// Create a new environment with an optional outer. fn new(outer: Option<&Self>) -> Self; /// Create a new inner environment, i.e. with the current environment as its outer. fn new_inner(&self) -> Self; /// Return the root outer of this environment (can be itself if no outer). /// /// TODO: find way to return reference without "reference to temporary value" error fn root(&self) -> Self; /// Try to found, if it exists, the value with the associated key (must be a /// Symbol) in the current environment and, if applicable, in its outer(s). fn get_env_value(&self, key: &MalValue) -> MalResult; /// Associate the given key (must be a Symbol) with the given MAL value in the /// current environment. fn set_env_value(&mut self, key: MalValue, val: MalValue) -> &mut Self; } /// Handler for an 'EnvData' instance. pub type Env = Rc<RefCell<EnvData>>; impl Environment for Env { fn new(outer: Option<&Self>) -> Self { Rc::new(RefCell::new(EnvData { data: HashMap::new(), outer: outer.cloned(), })) } fn new_inner(&self) -> Self { self::new(Some(self.clone())) } fn root(&self) -> Self { match self.borrow().outer { Some(ref outer) => outer.root(), None => self.clone(), } } fn get_env_value(&self, key: &MalValue) -> MalResult { match **key { Symbol(ref symbol) => match find(self, key) { Some(env) => Ok(env.borrow().data.get(symbol).unwrap().clone()), None => types::err_string(format!("env: cannot find {}", symbol)), }, _ => types::err_str("env: cannot get with a non-symbol key"), } } fn set_env_value(&mut self, key: MalValue, val: MalValue) -> &mut Self { match *key { Symbol(ref symbol) => { self.borrow_mut().data.insert(symbol.clone(), val); } _ => warn!("env: cannot set with a non-symbol key"), } self } } /// Create a new 'Env' instance with the (optional) outer environment. pub fn new(outer: Option<Env>) -> Env { Rc::new(RefCell::new(EnvData { data: HashMap::new(), outer, })) } /// Return the root environment of the given 'Env'. pub fn root(env: &Env) -> Env { match env.borrow().outer { Some(ref outer) => root(outer), None => env.clone(), } } /// Return the given environment if it contains the given key (must be a Symbol) /// or, if any, the first outer environment containing it. pub fn find(env: &Env, key: &MalValue) -> Option<Env> { match **key { Symbol(ref symbol) => { let env_data = env.borrow(); if env_data.data.contains_key(symbol) { Some(env.clone()) } else { match env_data.outer { Some(ref outer_env) => find(outer_env, key), None => None, } } } _ => None, } } /// Bind the given lists on a key/value basis and return the new environment, /// with the given environment as its outer. /// The binding will be variadic if a '&' symbol is encountered in the bindings /// list ; in this case the next symbol in the bindings list is bound to the /// rest of the exprs. pub fn bind(outer: &Env, binds: MalValue, exprs: MalValue) -> Result<Env, String> { let mut env = new(Some(outer.clone())); let mut variadic_pos: Option<usize> = None; match *binds { List(ref binds_seq) | Vector(ref binds_seq) => match *exprs { List(ref exprs_seq) | Vector(ref exprs_seq) => { for (i, bind) in binds_seq.iter().enumerate() { match **bind { Symbol(ref bind_key) => { if *bind_key == "&" { variadic_pos = Some(i); break; } else if i >= exprs_seq.len() { return Err("not enough parameters for binding".into()); } env.set_env_value(bind.clone(), exprs_seq[i].clone()); } _ => return Err("non-symbol bind".into()), } } if let Some(i) = variadic_pos { if i >= binds_seq.len() { return Err( concat!("missing a symbol after '&'", " for variadic binding").into(), ); } let vbind = &binds_seq[i + 1]; match **vbind { Symbol(_) => { env.set_env_value(vbind.clone(), new_list(exprs_seq[i..].to_vec())); } _ => return Err("non-symbol variadic binding".into()), } } Ok(env) } _ => Err("env: exprs must be a list/vector".into()), }, _ => Err("env: binds must be a list/vector".into()), } }
use std::env; fn main() { let args = env::args(); for (k, v) in args.enumerate() { println!("args[{}] = {}", k, v); } }
use std::io::{stdin}; fn main() { let mut buf = String::new(); stdin().read_line(&mut buf).unwrap(); let value = buf.trim().parse::<i32>().unwrap(); let result = match value { x if x % 4 == 0 && x % 100 != 0 => 1, x if x % 4 == 0 && x % 400 == 0 => 1, _ => 0, }; println!("{}", result); }
//! Clint use riscv::{csr, interrupt}; use e310x::CLINT; pub struct Clint<'a>(pub &'a CLINT); impl<'a> Clone for Clint<'a> { fn clone(&self) -> Self { *self } } impl<'a> Copy for Clint<'a> { } impl<'a> Clint<'a> { /// Read mtime register. pub fn get_mtime(&self) -> ::aonclk::Ticks<u64> { loop { let hi = self.0.mtimeh.read().bits(); let lo = self.0.mtime.read().bits(); if hi == self.0.mtimeh.read().bits() { return ::aonclk::Ticks(((hi as u64) << 32) | lo as u64); } } } /// Write mtime register. pub fn set_mtime(&self, time: ::aonclk::Ticks<u64>) { unsafe { self.0.mtimeh.write(|w| w.bits(time.into_hi())); self.0.mtime.write(|w| w.bits(time.into())); } } /// Read mtimecmp register. pub fn get_mtimecmp(&self) -> ::aonclk::Ticks<u64> { let hi = self.0.mtimecmph.read().bits() as u64; let lo = self.0.mtimecmp.read().bits() as u64; ::aonclk::Ticks(hi << 32 | lo) } /// Write mtimecmp register. pub fn set_mtimecmp(&self, time: ::aonclk::Ticks<u64>) { unsafe { self.0.mtimecmph.write(|w| w.bits(time.into_hi())); self.0.mtimecmp.write(|w| w.bits(time.into())); } } /// Read mcycle register. pub fn get_mcycle(&self) -> ::coreclk::Ticks<u64> { loop { let hi = csr::mcycleh.read().bits(); let lo = csr::mcycle.read().bits(); if hi == csr::mcycleh.read().bits() { return ::coreclk::Ticks(((hi as u64) << 32) | lo as u64); } } } /// Write mcycle register. pub fn set_mcycle(&self, cycle: ::coreclk::Ticks<u64>) { csr::mcycleh.write(|w| w.bits(cycle.into_hi())); csr::mcycle.write(|w| w.bits(cycle.into())); } /// Read minstret register. pub fn get_minstret(&self) -> u64 { loop { let hi = csr::minstreth.read().bits(); let lo = csr::minstret.read().bits(); if hi == csr::minstreth.read().bits() { return ((hi as u64) << 32) | lo as u64; } } } /// Write minstret register. pub fn set_minstret(&self, instret: u64) { csr::minstreth.write(|w| w.bits((instret >> 32) as u32)); csr::minstret.write(|w| w.bits(instret as u32)); } /// Enable Machine-Timer interrupt. pub fn enable_mtimer(&self) { csr::mie.set(|w| w.mtimer()); } /// Disable Machine-Timer interrupt. pub fn disable_mtimer(&self) { csr::mie.clear(|w| w.mtimer()); } /// Check if the Machine-Timer is interrupt pending. pub fn is_mtimer_pending(&self) -> bool { csr::mip.read().mtimer() } /// Measure the coreclk frequency by counting the number of aonclk ticks. pub fn measure_coreclk(&self, min_ticks: ::aonclk::Ticks<u64>) -> u32 { interrupt::free(|_| { let clint = self.0; // Don't start measuring until we see an mtime tick while clint.mtime.read().bits() == clint.mtime.read().bits() {} let start_cycle = self.get_mcycle(); let start_time = self.get_mtime(); // Wait for min_ticks to pass while start_time + min_ticks > self.get_mtime() {} let end_cycle = self.get_mcycle(); let end_time = self.get_mtime(); let delta_cycle: u32 = (end_cycle - start_cycle).into(); let delta_time: u32 = (end_time - start_time).into(); (delta_cycle / delta_time) * 32768 + ((delta_cycle % delta_time) * 32768) / delta_time }) } } impl<'a> ::hal::Timer for Clint<'a> { type Time = ::aonclk::Ticks<u64>; fn get_timeout(&self) -> ::aonclk::Ticks<u64> { self.get_mtimecmp() } fn pause(&self) { self.disable_mtimer(); } fn restart(&self) { self.set_mtime(::aonclk::Ticks(0)); self.enable_mtimer(); } fn resume(&self) { unimplemented!(); } fn set_timeout<T>(&self, timeout: T) where T: Into<::aonclk::Ticks<u64>>, { self.disable_mtimer(); self.set_mtimecmp(timeout.into()); self.set_mtime(::aonclk::Ticks(0)); self.enable_mtimer(); } fn wait(&self) -> ::nb::Result<(), !> { if self.is_mtimer_pending() { Ok(()) } else { Err(::nb::Error::WouldBlock) } } }
#[doc = "Reader of register HWCFGR1"] pub type R = crate::R<u32, super::HWCFGR1>; #[doc = "Writer for register HWCFGR1"] pub type W = crate::W<u32, super::HWCFGR1>; #[doc = "Register HWCFGR1 `reset()`'s with value 0x3110_0000"] impl crate::ResetValue for super::HWCFGR1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x3110_0000 } } #[doc = "Reader of field `CFG1`"] pub type CFG1_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CFG1`"] pub struct CFG1_W<'a> { w: &'a mut W, } impl<'a> CFG1_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 & !0x0f) | ((value as u32) & 0x0f); self.w } } #[doc = "Reader of field `CFG2`"] pub type CFG2_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CFG2`"] pub struct CFG2_W<'a> { w: &'a mut W, } impl<'a> CFG2_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 & !(0x0f << 4)) | (((value as u32) & 0x0f) << 4); self.w } } #[doc = "Reader of field `CFG3`"] pub type CFG3_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CFG3`"] pub struct CFG3_W<'a> { w: &'a mut W, } impl<'a> CFG3_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 & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "Reader of field `CFG4`"] pub type CFG4_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CFG4`"] pub struct CFG4_W<'a> { w: &'a mut W, } impl<'a> CFG4_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 & !(0x0f << 12)) | (((value as u32) & 0x0f) << 12); self.w } } #[doc = "Reader of field `CFG5`"] pub type CFG5_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CFG5`"] pub struct CFG5_W<'a> { w: &'a mut W, } impl<'a> CFG5_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 & !(0x0f << 16)) | (((value as u32) & 0x0f) << 16); self.w } } #[doc = "Reader of field `CFG6`"] pub type CFG6_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CFG6`"] pub struct CFG6_W<'a> { w: &'a mut W, } impl<'a> CFG6_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 & !(0x0f << 20)) | (((value as u32) & 0x0f) << 20); self.w } } #[doc = "Reader of field `CFG7`"] pub type CFG7_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CFG7`"] pub struct CFG7_W<'a> { w: &'a mut W, } impl<'a> CFG7_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 & !(0x0f << 24)) | (((value as u32) & 0x0f) << 24); self.w } } #[doc = "Reader of field `CFG8`"] pub type CFG8_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CFG8`"] pub struct CFG8_W<'a> { w: &'a mut W, } impl<'a> CFG8_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 & !(0x0f << 28)) | (((value as u32) & 0x0f) << 28); self.w } } impl R { #[doc = "Bits 0:3 - LUART hardware configuration 1"] #[inline(always)] pub fn cfg1(&self) -> CFG1_R { CFG1_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:7 - LUART hardware configuration 2"] #[inline(always)] pub fn cfg2(&self) -> CFG2_R { CFG2_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 8:11 - LUART hardware configuration 1"] #[inline(always)] pub fn cfg3(&self) -> CFG3_R { CFG3_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 12:15 - LUART hardware configuration 2"] #[inline(always)] pub fn cfg4(&self) -> CFG4_R { CFG4_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bits 16:19 - LUART hardware configuration 2"] #[inline(always)] pub fn cfg5(&self) -> CFG5_R { CFG5_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bits 20:23 - LUART hardware configuration 2"] #[inline(always)] pub fn cfg6(&self) -> CFG6_R { CFG6_R::new(((self.bits >> 20) & 0x0f) as u8) } #[doc = "Bits 24:27 - LUART hardware configuration 2"] #[inline(always)] pub fn cfg7(&self) -> CFG7_R { CFG7_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bits 28:31 - LUART hardware configuration 2"] #[inline(always)] pub fn cfg8(&self) -> CFG8_R { CFG8_R::new(((self.bits >> 28) & 0x0f) as u8) } } impl W { #[doc = "Bits 0:3 - LUART hardware configuration 1"] #[inline(always)] pub fn cfg1(&mut self) -> CFG1_W { CFG1_W { w: self } } #[doc = "Bits 4:7 - LUART hardware configuration 2"] #[inline(always)] pub fn cfg2(&mut self) -> CFG2_W { CFG2_W { w: self } } #[doc = "Bits 8:11 - LUART hardware configuration 1"] #[inline(always)] pub fn cfg3(&mut self) -> CFG3_W { CFG3_W { w: self } } #[doc = "Bits 12:15 - LUART hardware configuration 2"] #[inline(always)] pub fn cfg4(&mut self) -> CFG4_W { CFG4_W { w: self } } #[doc = "Bits 16:19 - LUART hardware configuration 2"] #[inline(always)] pub fn cfg5(&mut self) -> CFG5_W { CFG5_W { w: self } } #[doc = "Bits 20:23 - LUART hardware configuration 2"] #[inline(always)] pub fn cfg6(&mut self) -> CFG6_W { CFG6_W { w: self } } #[doc = "Bits 24:27 - LUART hardware configuration 2"] #[inline(always)] pub fn cfg7(&mut self) -> CFG7_W { CFG7_W { w: self } } #[doc = "Bits 28:31 - LUART hardware configuration 2"] #[inline(always)] pub fn cfg8(&mut self) -> CFG8_W { CFG8_W { w: self } } }
use std::rc::Rc; #[derive(Debug)] struct FileName { name: Rc<String>, ext: Rc<String>, } fn ref_counter() { let name = Rc::new(String::from("main")); let ext = Rc::new(String::from("rs")); for _ in 0..3 { println!("{:?}", FileName { name: name.clone(), ext: ext.clone(), }); } } fn main() { ref_counter(); }
#[derive(Debug, PartialEq)] pub enum ElmCode<'a> { Comment, Declaration, Ignore, Function(Function<'a>), Type(Type<'a>), } #[derive(Debug, PartialEq)] pub enum ElmModule<'a> { All, List(Vec<TypeOrFunction<'a>>), } type Name<'a> = &'a str; type Definition<'a> = &'a str; type TypeSignature = Vec<String>; #[derive(Debug, PartialEq)] pub enum TypeOrFunction<'a> { Type(Type<'a>), Function(Function<'a>), } #[derive(Debug, PartialEq)] pub struct Type<'a> { pub name: Name<'a>, pub definition: Option<Definition<'a>>, } #[derive(Debug, PartialEq)] pub struct Function<'a> { pub name: Name<'a>, pub type_signature: Option<TypeSignature>, }
pub struct Solution; impl Solution { pub fn count_smaller(nums: Vec<i32>) -> Vec<i32> { Solver::new(nums).solve() } } struct Solver { nums: Vec<i32>, count: Vec<i32>, index: Vec<usize>, dummy: Vec<usize>, } impl Solver { fn new(nums: Vec<i32>) -> Self { let n = nums.len(); Self { nums: nums, count: vec![0; n], index: (0..n).collect(), dummy: vec![0; n], } } fn solve(mut self) -> Vec<i32> { self.rec(0, self.nums.len()); self.count } fn rec(&mut self, a: usize, b: usize) { if b - a < 2 { return; } let c = (a + b) / 2; self.rec(a, c); self.rec(c, b); let mut i = a; let mut j = c; let mut k = a; let mut count = 0; while i < c && j < b { if self.nums[self.index[i]] <= self.nums[self.index[j]] { self.count[self.index[i]] += count; self.dummy[k] = self.index[i]; i += 1; k += 1; } else { count += 1; self.dummy[k] = self.index[j]; j += 1; k += 1; } } while i < c { self.count[self.index[i]] += count; self.dummy[k] = self.index[i]; i += 1; k += 1; } for i in a..k { self.index[i] = self.dummy[i]; } } } #[test] fn test0315() { fn case(nums: Vec<i32>, want: Vec<i32>) { let got = Solution::count_smaller(nums); assert_eq!(got, want); } case(vec![5, 2, 6, 1], vec![2, 1, 1, 0]); case(vec![5, 2, 6, 1, 3, 3, 3], vec![5, 1, 4, 0, 0, 0, 0]); case(vec![1, 0, 2], vec![1, 0, 0]); }
use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Client, Request, Response, Server}; use hyper_tls::HttpsConnector; use std::net::SocketAddr; use std::sync::Arc; const STRIPPED: [&str; 6] = [ "content-length", "transfer-encoding", "accept-encoding", "content-encoding", "host", "connection", ]; #[derive(Debug)] enum ReverseProxyError { Hyper(hyper::Error), HyperHttp(hyper::http::Error), } impl From<hyper::Error> for ReverseProxyError { fn from(e: hyper::Error) -> Self { ReverseProxyError::Hyper(e) } } impl From<hyper::http::Error> for ReverseProxyError { fn from(e: hyper::http::Error) -> Self { ReverseProxyError::HyperHttp(e) } } impl std::fmt::Display for ReverseProxyError { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(fmt, "{:?}", self) } } impl std::error::Error for ReverseProxyError {} struct ReverseProxy { scheme: String, host: String, client: Client<HttpsConnector<hyper::client::HttpConnector>>, } impl ReverseProxy { async fn handle(&self, mut req: Request<Body>) -> Result<Response<Body>, ReverseProxyError> { let h = req.headers_mut(); for key in &STRIPPED { h.remove(*key); } let mut builder = hyper::Uri::builder() .scheme(&*self.scheme) .authority(&*self.host); if let Some(pq) = req.uri().path_and_query() { builder = builder.path_and_query(pq.clone()); } *req.uri_mut() = builder.build()?; log::debug!("request == {:?}", req); let response = self.client.request(req).await?; log::debug!("response == {:?}", response); Ok(response) } } #[tokio::main] async fn main() { env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); let https = HttpsConnector::new(); let client = Client::builder().build(https); let rp = Arc::new(ReverseProxy { client, scheme: "https".to_owned(), host: "www.fpcomplete.com".to_owned(), }); let make_svc = make_service_fn(move |_conn| { let rp = Arc::clone(&rp); async { Ok::<_, ReverseProxyError>(service_fn(move |req| { let rp = Arc::clone(&rp); async move { rp.handle(req).await } })) } }); let server = Server::bind(&addr).serve(make_svc); log::info!("Server started, bound on {}", addr); if let Err(e) = server.await { log::error!("server error: {}", e); std::process::abort(); } }
use crate::actors_manager::ActorProxyReport; use crate::envelope::{Envelope, Letter}; use crate::system::AddressBook; use crate::{Actor, Assistant, Handle}; use async_std::{ sync::{channel, Receiver, Sender}, task::spawn, }; use std::fmt::Debug; #[derive(Debug)] enum ActorProxyCommand<A: Actor> { Dispatch(Box<dyn Envelope<Actor = A>>), End, } #[derive(Debug)] pub(crate) struct ActorProxy<A: Actor> { sender: Sender<ActorProxyCommand<A>>, assistant: Assistant, } impl<A: Actor> ActorProxy<A> { pub fn new( address_book: AddressBook, id: A::Id, report_sender: Sender<ActorProxyReport<A>>, ) -> ActorProxy<A> { let (sender, receiver): (Sender<ActorProxyCommand<A>>, Receiver<ActorProxyCommand<A>>) = channel(5); let assistant = Assistant::new(address_book); actor_loop( id, sender.clone(), receiver, assistant.clone(), report_sender, ); ActorProxy { sender, assistant } } pub fn send<M: 'static>(&self, message: M) where A: Handle<M>, M: Send + Debug, { let message = Letter::<A, M>::new(message); let sender = self.sender.clone(); // TODO: Handle the channel disconnection properly spawn(async move { sender .send(ActorProxyCommand::Dispatch(Box::new(message))) .await; }); } pub async fn end(&self) { self.sender.send(ActorProxyCommand::End).await; } } fn actor_loop<A: Actor>( id: A::Id, sender: Sender<ActorProxyCommand<A>>, receiver: Receiver<ActorProxyCommand<A>>, assistant: Assistant, report_sender: Sender<ActorProxyReport<A>>, ) { spawn(async move { let mut actor = A::activate(id.clone()).await; spawn(async move { while let Some(command) = receiver.recv().await { match command { ActorProxyCommand::Dispatch(mut envelope) => { envelope.dispatch(&mut actor, assistant.clone()).await } ActorProxyCommand::End => { // We may find cases where we can have several End command in a row. In that case, // we want to consume all the end command together until we find nothing or a not-end command match recv_until_not_end_command(receiver.clone()).await { None => { actor.deactivate().await; report_sender.send(ActorProxyReport::ActorStopped(id)).await; break; } Some(ActorProxyCommand::Dispatch(mut envelope)) => { // If there are any message left, we postpone the shutdown. sender.send(ActorProxyCommand::End).await; envelope.dispatch(&mut actor, assistant.clone()).await } _ => unreachable!(), } } } } }); }); } async fn recv_until_not_end_command<A: Actor>( receiver: Receiver<ActorProxyCommand<A>>, ) -> Option<ActorProxyCommand<A>> { if receiver.is_empty() { return None; } while let Some(command) = receiver.recv().await { match command { ActorProxyCommand::Dispatch(_) => return Some(command), ActorProxyCommand::End => { if receiver.is_empty() { return None; } else { continue; } } } } None }
use ::errors::*; use ::ir::{Type, TypeVariant, TypeData, TypeContainer, FieldPropertyReference}; use ::ir::variant::{Variant, SimpleScalarVariant, ContainerVariant, ContainerField, ContainerFieldType, ArrayVariant, UnionVariant}; use super::*; use super::utils::*; pub fn find_field_index(variant: &ContainerVariant, property: &FieldPropertyReference) -> usize { let property_field_ident = { let rc = property.reference_node.clone().unwrap().upgrade().unwrap(); let rc_inner = rc.borrow(); rc_inner.data.ident.unwrap() }; let (idx, _) = variant.fields .iter().enumerate() .find(|&(_, f)| { let rc = f.child.clone().upgrade().unwrap(); let rc_inner = rc.borrow(); rc_inner.data.ident.unwrap() == property_field_ident }) .unwrap(); idx } pub fn build_var_accessor(variant: &ContainerVariant, data: &TypeData, block: &mut Vec<Operation>, field_num: usize) -> Result<()> { let field: &ContainerField = &variant.fields[field_num]; let field_input_var = input_for_type(field.child.upgrade().unwrap()); build_var_accessor_inner(variant, data, block, field_num, &field_input_var) } fn build_var_accessor_inner(variant: &ContainerVariant, data: &TypeData, block: &mut Vec<Operation>, field_num: usize, chain_var: &str) -> Result<()> { let field: &ContainerField = &variant.fields[field_num]; match field.field_type { ContainerFieldType::Normal => { if variant.virt { block.push(Operation::Assign { name: chain_var.to_owned().into(), value: Expr::Var(input_for(data).into()), }); Ok(()) } else { block.push(Operation::Assign { name: chain_var.to_owned().into(), value: Expr::ContainerField { value: Box::new(Expr::Var(input_for(data).into())), field: field.name.clone(), }, }); Ok(()) } } ContainerFieldType::Virtual { ref property } => { let ref_node_rc = property.reference_node.clone().unwrap() .upgrade().unwrap(); let ref_node = ref_node_rc.borrow(); if property.reference.up == 0 { let next_index = find_field_index(variant, property); build_var_accessor_inner( variant, data, block, next_index, chain_var)?; } else { block.push(Operation::Assign { name: chain_var.to_owned().into(), value: Expr::Var(input_for(&ref_node.data).into()), }); }; let property_variant = match property.property.as_ref() { "length" => MapOperation::ArrayLength, "tag" => { match ref_node.variant { Variant::Union(ref union) => { let cases = union.cases.iter().map(|case| { let block = Block(vec![ Operation::Assign { name: chain_var.to_owned().into(), value: Expr::Literal(Literal::Number( case.match_val_str.clone())) } ]); UnionTagCase { variant_name: case.case_name.clone(), variant_var: None, block: block, } }).collect(); MapOperation::UnionTagToExpr(cases) }, // TODO: This NEEDS to be validated earlier. // The way it's done right now is a hack. _ => unreachable!(), } }, _ => unimplemented!(), }; block.push(Operation::MapValue { input: chain_var.to_owned().into(), output: chain_var.to_owned().into(), operation: property_variant, }); Ok(()) } _ => unimplemented!(), } }
// material.rs // // Copyright (c) 2019, Univerisity of Minnesota // // Author: Bridger Herman (herma582@umn.edu) //! Data container for material information use std::str::FromStr; use glam::{Vec3, Vec4}; use wasm_bindgen::prelude::*; use crate::texture::TextureId; #[wasm_bindgen] #[derive(Debug, Clone, Copy)] pub struct Material { pub shader_id: usize, pub color: Vec4, pub specular: Vec4, texture_id: Option<TextureId>, } #[wasm_bindgen] impl Material { #[wasm_bindgen(constructor)] pub fn new( shader_id: usize, color: Vec4, specular: Option<Vec4>, texture_id: Option<TextureId>, ) -> Self { let specular = specular.unwrap_or(Vec4::new( color.x(), color.y(), color.z(), 100.0, )); Self { shader_id, color, specular, texture_id, } } /// Partial implementation of wavefront obj mtl parsing (diffuse + specular /// + diffuse texture only) pub fn from_mtl_str(mtl_text: &str) -> Self { let lines: Vec<_> = mtl_text .lines() .filter(|&line| !line.starts_with('#') && !line.is_empty()) .map(|line| { if let Some(index) = line.find('#') { &line[..index] } else { line } }) .collect(); let mut returned = Material::default(); for line in lines { let lowercase = line.to_lowercase(); let tokens: Vec<_> = lowercase.split_whitespace().collect(); match tokens[0] { "kd" => { // Diffuse color let float_tokens = parse_slice(&tokens[1..]); returned.color = Vec3::new( float_tokens[0], float_tokens[1], float_tokens[2], ) .extend(1.0); } "ks" => { // Specular color let float_tokens = parse_slice(&tokens[1..]); returned.specular = Vec3::new( float_tokens[0], float_tokens[1], float_tokens[2], ) .extend(1.0); } "ns" => { // Specular highlight exponent let float_tokens = parse_slice(&tokens[1..]); returned.specular.set_w(float_tokens[0]); } _ => (), } } returned } #[wasm_bindgen(getter)] pub fn texture_id(&self) -> Option<TextureId> { self.texture_id } #[wasm_bindgen(setter)] pub fn set_texture_id(&mut self, texture_id: Option<TextureId>) { self.texture_id = texture_id; } } impl Default for Material { fn default() -> Self { Self { shader_id: 0, color: Vec4::unit_w(), specular: Vec4::unit_w(), texture_id: None, } } } pub fn parse_slice<T: FromStr + Default>(str_slice: &[&str]) -> Vec<T> { str_slice .iter() .map(|&s| s.parse::<T>().unwrap_or_default()) .collect() }
#![allow(missing_docs)] #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] pub enum Key { Key1, Key2, Key3, Key4, Key5, Key6, Key7, Key8, Key9, Key0, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Escape, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24, Snapshot, Scroll, Pause, Insert, Home, Delete, End, PageDown, PageUp, Left, Up, Right, Down, Back, Return, Space, Compose, Caret, Numlock, Numpad0, Numpad1, Numpad2, Numpad3, Numpad4, Numpad5, Numpad6, Numpad7, Numpad8, Numpad9, AbntC1, AbntC2, Add, Apostrophe, Apps, At, Ax, Backslash, Calculator, Capital, Colon, Comma, Convert, Decimal, Divide, Equals, Grave, Kana, Kanji, LAlt, LBracket, LControl, LShift, LWin, Mail, MediaSelect, MediaStop, Minus, Multiply, Mute, MyComputer, NavigateForward, NavigateBackward, NextTrack, NoConvert, NumpadComma, NumpadEnter, NumpadEquals, OEM102, Period, PlayPause, Power, PrevTrack, RAlt, RBracket, RControl, RShift, RWin, Semicolon, Slash, Sleep, Stop, Subtract, Sysrq, Tab, Underline, Unlabeled, VolumeDown, VolumeUp, Wake, WebBack, WebFavorites, WebForward, WebHome, WebRefresh, WebSearch, WebStop, Yen, } pub(crate) const KEY_LIST: &[Key] = &[Key::Key1, Key::Key2, Key::Key3, Key::Key4, Key::Key5, Key::Key6, Key::Key7, Key::Key8, Key::Key9, Key::Key0, Key::A, Key::B, Key::C, Key::D, Key::E, Key::F, Key::G, Key::H, Key::I, Key::J, Key::K, Key::L, Key::M, Key::N, Key::O, Key::P, Key::Q, Key::R, Key::S, Key::T, Key::U, Key::V, Key::W, Key::X, Key::Y, Key::Z, Key::Escape, Key::F1, Key::F2, Key::F3, Key::F4, Key::F5, Key::F6, Key::F7, Key::F8, Key::F9, Key::F10, Key::F11, Key::F12, Key::F13, Key::F14, Key::F15, Key::F16, Key::F17, Key::F18, Key::F19, Key::F20, Key::F21, Key::F22, Key::F23, Key::F24, Key::Snapshot, Key::Scroll, Key::Pause, Key::Insert, Key::Home, Key::Delete, Key::End, Key::PageDown, Key::PageUp, Key::Left, Key::Up, Key::Right, Key::Down, Key::Back, Key::Return, Key::Space, Key::Compose, Key::Caret, Key::Numlock, Key::Numpad0, Key::Numpad1, Key::Numpad2, Key::Numpad3, Key::Numpad4, Key::Numpad5, Key::Numpad6, Key::Numpad7, Key::Numpad8, Key::Numpad9, Key::AbntC1, Key::AbntC2, Key::Add, Key::Apostrophe, Key::Apps, Key::At, Key::Ax, Key::Backslash, Key::Calculator, Key::Capital, Key::Colon, Key::Comma, Key::Convert, Key::Decimal, Key::Divide, Key::Equals, Key::Grave, Key::Kana, Key::Kanji, Key::LAlt, Key::LBracket, Key::LControl, Key::LShift, Key::LWin, Key::Mail, Key::MediaSelect, Key::MediaStop, Key::Minus, Key::Multiply, Key::Mute, Key::MyComputer, Key::NavigateForward, Key::NavigateBackward, Key::NextTrack, Key::NoConvert, Key::NumpadComma, Key::NumpadEnter, Key::NumpadEquals, Key::OEM102, Key::Period, Key::PlayPause, Key::Power, Key::PrevTrack, Key::RAlt, Key::RBracket, Key::RControl, Key::RShift, Key::RWin, Key::Semicolon, Key::Slash, Key::Sleep, Key::Stop, Key::Subtract, Key::Sysrq, Key::Tab, Key::Underline, Key::Unlabeled, Key::VolumeDown, Key::VolumeUp, Key::Wake, Key::WebBack, Key::WebFavorites, Key::WebForward, Key::WebHome, Key::WebRefresh, Key::WebSearch, Key::WebStop, Key::Yen]; #[cfg(test)] mod tests { use super::*; #[test] fn check_key_list() { for i in 0..KEY_LIST.len() { assert_eq!(i as u32, KEY_LIST[i] as u32); } } #[test] fn key_constants_match() { assert_eq!(Key::Key1 as u32, glutin::VirtualKeyCode::Key1 as u32); assert_eq!(Key::Key2 as u32, glutin::VirtualKeyCode::Key2 as u32); assert_eq!(Key::Key3 as u32, glutin::VirtualKeyCode::Key3 as u32); assert_eq!(Key::Key4 as u32, glutin::VirtualKeyCode::Key4 as u32); assert_eq!(Key::Key5 as u32, glutin::VirtualKeyCode::Key5 as u32); assert_eq!(Key::Key6 as u32, glutin::VirtualKeyCode::Key6 as u32); assert_eq!(Key::Key7 as u32, glutin::VirtualKeyCode::Key7 as u32); assert_eq!(Key::Key8 as u32, glutin::VirtualKeyCode::Key8 as u32); assert_eq!(Key::Key9 as u32, glutin::VirtualKeyCode::Key9 as u32); assert_eq!(Key::Key0 as u32, glutin::VirtualKeyCode::Key0 as u32); assert_eq!(Key::A as u32, glutin::VirtualKeyCode::A as u32); assert_eq!(Key::B as u32, glutin::VirtualKeyCode::B as u32); assert_eq!(Key::C as u32, glutin::VirtualKeyCode::C as u32); assert_eq!(Key::D as u32, glutin::VirtualKeyCode::D as u32); assert_eq!(Key::E as u32, glutin::VirtualKeyCode::E as u32); assert_eq!(Key::F as u32, glutin::VirtualKeyCode::F as u32); assert_eq!(Key::G as u32, glutin::VirtualKeyCode::G as u32); assert_eq!(Key::H as u32, glutin::VirtualKeyCode::H as u32); assert_eq!(Key::I as u32, glutin::VirtualKeyCode::I as u32); assert_eq!(Key::J as u32, glutin::VirtualKeyCode::J as u32); assert_eq!(Key::K as u32, glutin::VirtualKeyCode::K as u32); assert_eq!(Key::L as u32, glutin::VirtualKeyCode::L as u32); assert_eq!(Key::M as u32, glutin::VirtualKeyCode::M as u32); assert_eq!(Key::N as u32, glutin::VirtualKeyCode::N as u32); assert_eq!(Key::O as u32, glutin::VirtualKeyCode::O as u32); assert_eq!(Key::P as u32, glutin::VirtualKeyCode::P as u32); assert_eq!(Key::Q as u32, glutin::VirtualKeyCode::Q as u32); assert_eq!(Key::R as u32, glutin::VirtualKeyCode::R as u32); assert_eq!(Key::S as u32, glutin::VirtualKeyCode::S as u32); assert_eq!(Key::T as u32, glutin::VirtualKeyCode::T as u32); assert_eq!(Key::U as u32, glutin::VirtualKeyCode::U as u32); assert_eq!(Key::V as u32, glutin::VirtualKeyCode::V as u32); assert_eq!(Key::W as u32, glutin::VirtualKeyCode::W as u32); assert_eq!(Key::X as u32, glutin::VirtualKeyCode::X as u32); assert_eq!(Key::Y as u32, glutin::VirtualKeyCode::Y as u32); assert_eq!(Key::Z as u32, glutin::VirtualKeyCode::Z as u32); assert_eq!(Key::Escape as u32, glutin::VirtualKeyCode::Escape as u32); assert_eq!(Key::F1 as u32, glutin::VirtualKeyCode::F1 as u32); assert_eq!(Key::F2 as u32, glutin::VirtualKeyCode::F2 as u32); assert_eq!(Key::F3 as u32, glutin::VirtualKeyCode::F3 as u32); assert_eq!(Key::F4 as u32, glutin::VirtualKeyCode::F4 as u32); assert_eq!(Key::F5 as u32, glutin::VirtualKeyCode::F5 as u32); assert_eq!(Key::F6 as u32, glutin::VirtualKeyCode::F6 as u32); assert_eq!(Key::F7 as u32, glutin::VirtualKeyCode::F7 as u32); assert_eq!(Key::F8 as u32, glutin::VirtualKeyCode::F8 as u32); assert_eq!(Key::F9 as u32, glutin::VirtualKeyCode::F9 as u32); assert_eq!(Key::F10 as u32, glutin::VirtualKeyCode::F10 as u32); assert_eq!(Key::F11 as u32, glutin::VirtualKeyCode::F11 as u32); assert_eq!(Key::F12 as u32, glutin::VirtualKeyCode::F12 as u32); assert_eq!(Key::F13 as u32, glutin::VirtualKeyCode::F13 as u32); assert_eq!(Key::F14 as u32, glutin::VirtualKeyCode::F14 as u32); assert_eq!(Key::F15 as u32, glutin::VirtualKeyCode::F15 as u32); assert_eq!(Key::F16 as u32, glutin::VirtualKeyCode::F16 as u32); assert_eq!(Key::F17 as u32, glutin::VirtualKeyCode::F17 as u32); assert_eq!(Key::F18 as u32, glutin::VirtualKeyCode::F18 as u32); assert_eq!(Key::F19 as u32, glutin::VirtualKeyCode::F19 as u32); assert_eq!(Key::F20 as u32, glutin::VirtualKeyCode::F20 as u32); assert_eq!(Key::F21 as u32, glutin::VirtualKeyCode::F21 as u32); assert_eq!(Key::F22 as u32, glutin::VirtualKeyCode::F22 as u32); assert_eq!(Key::F23 as u32, glutin::VirtualKeyCode::F23 as u32); assert_eq!(Key::F24 as u32, glutin::VirtualKeyCode::F24 as u32); assert_eq!(Key::Snapshot as u32, glutin::VirtualKeyCode::Snapshot as u32); assert_eq!(Key::Scroll as u32, glutin::VirtualKeyCode::Scroll as u32); assert_eq!(Key::Pause as u32, glutin::VirtualKeyCode::Pause as u32); assert_eq!(Key::Insert as u32, glutin::VirtualKeyCode::Insert as u32); assert_eq!(Key::Home as u32, glutin::VirtualKeyCode::Home as u32); assert_eq!(Key::Delete as u32, glutin::VirtualKeyCode::Delete as u32); assert_eq!(Key::End as u32, glutin::VirtualKeyCode::End as u32); assert_eq!(Key::PageDown as u32, glutin::VirtualKeyCode::PageDown as u32); assert_eq!(Key::PageUp as u32, glutin::VirtualKeyCode::PageUp as u32); assert_eq!(Key::Left as u32, glutin::VirtualKeyCode::Left as u32); assert_eq!(Key::Up as u32, glutin::VirtualKeyCode::Up as u32); assert_eq!(Key::Right as u32, glutin::VirtualKeyCode::Right as u32); assert_eq!(Key::Down as u32, glutin::VirtualKeyCode::Down as u32); assert_eq!(Key::Back as u32, glutin::VirtualKeyCode::Back as u32); assert_eq!(Key::Return as u32, glutin::VirtualKeyCode::Return as u32); assert_eq!(Key::Space as u32, glutin::VirtualKeyCode::Space as u32); assert_eq!(Key::Compose as u32, glutin::VirtualKeyCode::Compose as u32); assert_eq!(Key::Caret as u32, glutin::VirtualKeyCode::Caret as u32); assert_eq!(Key::Numlock as u32, glutin::VirtualKeyCode::Numlock as u32); assert_eq!(Key::Numpad0 as u32, glutin::VirtualKeyCode::Numpad0 as u32); assert_eq!(Key::Numpad1 as u32, glutin::VirtualKeyCode::Numpad1 as u32); assert_eq!(Key::Numpad2 as u32, glutin::VirtualKeyCode::Numpad2 as u32); assert_eq!(Key::Numpad3 as u32, glutin::VirtualKeyCode::Numpad3 as u32); assert_eq!(Key::Numpad4 as u32, glutin::VirtualKeyCode::Numpad4 as u32); assert_eq!(Key::Numpad5 as u32, glutin::VirtualKeyCode::Numpad5 as u32); assert_eq!(Key::Numpad6 as u32, glutin::VirtualKeyCode::Numpad6 as u32); assert_eq!(Key::Numpad7 as u32, glutin::VirtualKeyCode::Numpad7 as u32); assert_eq!(Key::Numpad8 as u32, glutin::VirtualKeyCode::Numpad8 as u32); assert_eq!(Key::Numpad9 as u32, glutin::VirtualKeyCode::Numpad9 as u32); assert_eq!(Key::AbntC1 as u32, glutin::VirtualKeyCode::AbntC1 as u32); assert_eq!(Key::AbntC2 as u32, glutin::VirtualKeyCode::AbntC2 as u32); assert_eq!(Key::Add as u32, glutin::VirtualKeyCode::Add as u32); assert_eq!(Key::Apostrophe as u32, glutin::VirtualKeyCode::Apostrophe as u32); assert_eq!(Key::Apps as u32, glutin::VirtualKeyCode::Apps as u32); assert_eq!(Key::At as u32, glutin::VirtualKeyCode::At as u32); assert_eq!(Key::Ax as u32, glutin::VirtualKeyCode::Ax as u32); assert_eq!(Key::Backslash as u32, glutin::VirtualKeyCode::Backslash as u32); assert_eq!(Key::Calculator as u32, glutin::VirtualKeyCode::Calculator as u32); assert_eq!(Key::Capital as u32, glutin::VirtualKeyCode::Capital as u32); assert_eq!(Key::Colon as u32, glutin::VirtualKeyCode::Colon as u32); assert_eq!(Key::Comma as u32, glutin::VirtualKeyCode::Comma as u32); assert_eq!(Key::Convert as u32, glutin::VirtualKeyCode::Convert as u32); assert_eq!(Key::Decimal as u32, glutin::VirtualKeyCode::Decimal as u32); assert_eq!(Key::Divide as u32, glutin::VirtualKeyCode::Divide as u32); assert_eq!(Key::Equals as u32, glutin::VirtualKeyCode::Equals as u32); assert_eq!(Key::Grave as u32, glutin::VirtualKeyCode::Grave as u32); assert_eq!(Key::Kana as u32, glutin::VirtualKeyCode::Kana as u32); assert_eq!(Key::Kanji as u32, glutin::VirtualKeyCode::Kanji as u32); assert_eq!(Key::LAlt as u32, glutin::VirtualKeyCode::LAlt as u32); assert_eq!(Key::LBracket as u32, glutin::VirtualKeyCode::LBracket as u32); assert_eq!(Key::LControl as u32, glutin::VirtualKeyCode::LControl as u32); assert_eq!(Key::LShift as u32, glutin::VirtualKeyCode::LShift as u32); assert_eq!(Key::LWin as u32, glutin::VirtualKeyCode::LWin as u32); assert_eq!(Key::Mail as u32, glutin::VirtualKeyCode::Mail as u32); assert_eq!(Key::MediaSelect as u32, glutin::VirtualKeyCode::MediaSelect as u32); assert_eq!(Key::MediaStop as u32, glutin::VirtualKeyCode::MediaStop as u32); assert_eq!(Key::Minus as u32, glutin::VirtualKeyCode::Minus as u32); assert_eq!(Key::Multiply as u32, glutin::VirtualKeyCode::Multiply as u32); assert_eq!(Key::Mute as u32, glutin::VirtualKeyCode::Mute as u32); assert_eq!(Key::MyComputer as u32, glutin::VirtualKeyCode::MyComputer as u32); assert_eq!(Key::NavigateForward as u32, glutin::VirtualKeyCode::NavigateForward as u32); assert_eq!(Key::NavigateBackward as u32, glutin::VirtualKeyCode::NavigateBackward as u32); assert_eq!(Key::NextTrack as u32, glutin::VirtualKeyCode::NextTrack as u32); assert_eq!(Key::NoConvert as u32, glutin::VirtualKeyCode::NoConvert as u32); assert_eq!(Key::NumpadComma as u32, glutin::VirtualKeyCode::NumpadComma as u32); assert_eq!(Key::NumpadEnter as u32, glutin::VirtualKeyCode::NumpadEnter as u32); assert_eq!(Key::NumpadEquals as u32, glutin::VirtualKeyCode::NumpadEquals as u32); assert_eq!(Key::OEM102 as u32, glutin::VirtualKeyCode::OEM102 as u32); assert_eq!(Key::Period as u32, glutin::VirtualKeyCode::Period as u32); assert_eq!(Key::PlayPause as u32, glutin::VirtualKeyCode::PlayPause as u32); assert_eq!(Key::Power as u32, glutin::VirtualKeyCode::Power as u32); assert_eq!(Key::PrevTrack as u32, glutin::VirtualKeyCode::PrevTrack as u32); assert_eq!(Key::RAlt as u32, glutin::VirtualKeyCode::RAlt as u32); assert_eq!(Key::RBracket as u32, glutin::VirtualKeyCode::RBracket as u32); assert_eq!(Key::RControl as u32, glutin::VirtualKeyCode::RControl as u32); assert_eq!(Key::RShift as u32, glutin::VirtualKeyCode::RShift as u32); assert_eq!(Key::RWin as u32, glutin::VirtualKeyCode::RWin as u32); assert_eq!(Key::Semicolon as u32, glutin::VirtualKeyCode::Semicolon as u32); assert_eq!(Key::Slash as u32, glutin::VirtualKeyCode::Slash as u32); assert_eq!(Key::Sleep as u32, glutin::VirtualKeyCode::Sleep as u32); assert_eq!(Key::Stop as u32, glutin::VirtualKeyCode::Stop as u32); assert_eq!(Key::Subtract as u32, glutin::VirtualKeyCode::Subtract as u32); assert_eq!(Key::Sysrq as u32, glutin::VirtualKeyCode::Sysrq as u32); assert_eq!(Key::Tab as u32, glutin::VirtualKeyCode::Tab as u32); assert_eq!(Key::Underline as u32, glutin::VirtualKeyCode::Underline as u32); assert_eq!(Key::Unlabeled as u32, glutin::VirtualKeyCode::Unlabeled as u32); assert_eq!(Key::VolumeDown as u32, glutin::VirtualKeyCode::VolumeDown as u32); assert_eq!(Key::VolumeUp as u32, glutin::VirtualKeyCode::VolumeUp as u32); assert_eq!(Key::Wake as u32, glutin::VirtualKeyCode::Wake as u32); assert_eq!(Key::WebBack as u32, glutin::VirtualKeyCode::WebBack as u32); assert_eq!(Key::WebFavorites as u32, glutin::VirtualKeyCode::WebFavorites as u32); assert_eq!(Key::WebForward as u32, glutin::VirtualKeyCode::WebForward as u32); assert_eq!(Key::WebHome as u32, glutin::VirtualKeyCode::WebHome as u32); assert_eq!(Key::WebRefresh as u32, glutin::VirtualKeyCode::WebRefresh as u32); assert_eq!(Key::WebSearch as u32, glutin::VirtualKeyCode::WebSearch as u32); assert_eq!(Key::WebStop as u32, glutin::VirtualKeyCode::WebStop as u32); assert_eq!(Key::Yen as u32, glutin::VirtualKeyCode::Yen as u32); } }
use std::str::FromStr; struct Length { length: usize }; use std::iter::FromIterator; impl<A> FromIterator<A> for Length { fn from_iter<S>(src: S) -> Self where S: IntoIterator<Item = A>, { let mut length: usize = 0; for _ in src { length += 1; } Length{length} } } #[derive(Clone)] struct Password(String); #[derive(Clone)] struct Rule { low: usize, high: usize, key: char, } #[derive(Clone)] struct InputLine { rule: Rule, password: Password, } impl InputLine { fn old_validate(&self) -> bool { let Length{length} = self .password .0 .chars() .filter(|c| *c == self.rule.key) .collect(); self.rule.low <= length && length <= self.rule.high } fn new_validate(&self) -> bool { let chars: Vec<char> = self.password.0.chars().collect(); (chars[self.rule.low - 1] == self.rule.key) ^ (chars[self.rule.high - 1] == self.rule.key) } } impl FromStr for InputLine { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let (rule, password) = match &s.split(": ").collect::<Vec<_>>()[..] { [rule, password] => Ok((*rule, String::from(*password))), _ => Err(Error::from(format!( "Unable to locate rule and password in {}", s ))), }?; let (bounds, key) = match &rule.split(" ").collect::<Vec<_>>()[..] { [bounds, key] if key.len() == 1 => Ok((*bounds, key.chars().nth(0).unwrap())), _ => Err(Error::from(format!( "Unable to locate bounds and key in {}", rule ))), }?; let (&low, &high) = match &(bounds .split("-") .map(|s| s.parse().map_err(Error::from)) .collect::<Result<Vec<usize>, Error>>()?)[..] { [low, high] => Ok((low, high)), _ => Err(format!("Incorrect number of bounds in {}", bounds)), }?; Ok(InputLine { rule: Rule { low, high, key }, password: Password(password), }) } } use std::path::PathBuf; use structopt::StructOpt; #[derive(StructOpt)] #[structopt( name = "solve", about = "solve the puzzles from the Advent of Code 2020, day 2" )] struct Opt { /// path to input file; should contain rule/password lines input: PathBuf, } use std::error; type Error = Box<dyn error::Error>; use std::fs::File; use std::io::{BufRead, BufReader}; fn main() -> Result<(), Error> { let opts = Opt::from_args(); let file = File::open(opts.input.clone())?; let input = BufReader::new(file) .lines() .map(|read| read?.parse().map_err(Error::from)) .collect::<Result<Vec<InputLine>, Error>>()?; println!("passwords in {:?} satisfying old rules", opts.input); println!( "{}", input .iter() .cloned() .filter(InputLine::old_validate) .collect::<Length>() .0 ); println!("passwords in {:?} satisfying new rules", opts.input); println!( "{}", input .iter() .cloned() .filter(InputLine::new_validate) .collect::<Length>() .0 ); Ok(()) }
use crate::utils; fn read_problem_data() -> Vec<String> { let path = "data/day18.txt"; let mut result = Vec::new(); if let Ok(lines) = utils::read_lines(path) { for line in lines { if let Ok(s) = line { result.push(s); } } } result } fn tokenize(expression: &String) -> Vec<String> { let mut tokens = Vec::new(); for token in expression.split(" ") { match token { "+" => tokens.push(String::from("+")), "*" => tokens.push(String::from("*")), _ => { if token.starts_with("(") { let mut t = token; while t.starts_with("(") { tokens.push(String::from("(")); t = t.strip_prefix("(").unwrap(); } tokens.push(String::from(t)); } else if token.ends_with(")") { let mut t = token; let mut num = 0; while t.ends_with(")") { t = t.strip_suffix(")").unwrap(); num += 1; } tokens.push(String::from(t)); for _ in 0..num { tokens.push(String::from(")")); } } else { tokens.push(String::from(token)); } } } } tokens } fn compute(lhs: &Option<usize>, rhs: usize, op: &Option<String>) -> Option<usize> { if let Some(lhs) = lhs { if let Some(op) = op { if op == "+" { return Some(lhs + rhs); } return Some(lhs * rhs); } } return Some(rhs); } fn solve(expression: &String) -> usize { let mut lhs = None; let mut op = None; let mut stack = Vec::new(); for token in tokenize(expression) { match token.as_str() { "+" | "*" => op = Some(token), "(" => { stack.push((lhs, op)); lhs = None; op = None; } ")" => { let (l, o) = stack.pop().unwrap(); lhs = compute(&l, lhs.unwrap(), &o); } _ => { lhs = compute(&lhs, token.parse::<usize>().unwrap(), &op); } } } lhs.unwrap() } fn multiply(values: &Vec<Option<usize>>) -> usize { let mut result = 1; for v in values { if let Some(v) = v { result *= v; } } result } fn solve2(expression: &String) -> usize { let mut lhs = None; let mut op = None; let mut stack = Vec::new(); let mut mul = Vec::new(); for token in tokenize(expression) { match token.as_str() { "+" => op = Some(token), "*" => { mul.push(lhs); lhs = None; } "(" => { stack.push((lhs, op, mul)); lhs = None; op = None; mul = Vec::new(); } ")" => { mul.push(lhs); let (l, o, m) = stack.pop().unwrap(); lhs = compute(&l, multiply(&mul), &o); mul = m; } _ => { lhs = compute(&lhs, token.parse::<usize>().unwrap(), &op); } } } mul.push(lhs); multiply(&mul) } #[allow(dead_code)] pub fn problem1() { println!("running problem 18.1:"); let mut total = 0; for expression in read_problem_data() { total += solve(&expression); } println!("Total: {}", total); } #[allow(dead_code)] pub fn problem2() { println!("running problem 18.2:"); let mut total = 0; for expression in read_problem_data() { total += solve2(&expression); } println!("Total: {}", total); } #[cfg(test)] mod tests { use super::*; #[test] fn test_solver() { assert_eq!(solve(&String::from("1 + 2 * 3 + 4 * 5 + 6")), 71); assert_eq!(solve(&String::from("1 + (2 * 3) + (4 * (5 + 6))")), 51); assert_eq!(solve(&String::from("2 * 3 + (4 * 5)")), 26); assert_eq!(solve(&String::from("5 + (8 * 3 + 9 + 3 * 4 * 3)")), 437); assert_eq!( solve(&String::from("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))")), 12240 ); assert_eq!( solve(&String::from( "((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2" )), 13632 ); } #[test] fn test_solver2() { assert_eq!(solve2(&String::from("1 + 2 * 3 + 4 * 5 + 6")), 231); assert_eq!(solve2(&String::from("1 + (2 * 3) + (4 * (5 + 6))")), 51); assert_eq!(solve2(&String::from("2 * 3 + (4 * 5)")), 46); assert_eq!(solve2(&String::from("5 + (8 * 3 + 9 + 3 * 4 * 3)")), 1445); assert_eq!( solve2(&String::from("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))")), 669060 ); assert_eq!( solve2(&String::from( "((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2" )), 23340 ); } }
use std::ops::{Mul, MulAssign}; use std::str::FromStr; use serde::Deserialize; use tiny_fail::Fail; #[derive(Debug, Clone, Copy, PartialEq, Deserialize)] pub struct Coords { pub x: f32, pub y: f32, pub z: f32, } impl Coords { pub const fn new(x: f32, y: f32, z: f32) -> Coords { Coords { x, y, z } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum Plane { XY, XZ, YX, YZ, ZX, ZY, } impl Plane { pub fn to_2d(self, coords: Coords) -> (f32, f32) { match self { Plane::XY => (coords.x, -coords.y), Plane::XZ => (coords.x, -coords.z), Plane::YX => (coords.y, -coords.x), Plane::YZ => (coords.y, -coords.z), Plane::ZX => (coords.z, -coords.x), Plane::ZY => (coords.z, -coords.y), } } } impl FromStr for Plane { type Err = Fail; fn from_str(name: &str) -> Result<Plane, Fail> { match name { "xy" => Ok(Plane::XY), "xz" => Ok(Plane::XZ), "yx" => Ok(Plane::YX), "yz" => Ok(Plane::YZ), "zx" => Ok(Plane::ZX), "zy" => Ok(Plane::ZY), name => Err(Fail::new(format!("invalud plane name '{}'", name))), } } } // |-- --| |-- --| |-- --| // | x' | | a[0][0] a[0][1] a[0][2] | | x | // | y' | = | a[1][0] a[1][1] a[1][2] | | y | // | z' | | a[2][0] a[2][1] a[2][2] | | z | // |-- --| |-- --| |-- --| #[derive(Debug, Clone, Copy, PartialEq, Deserialize)] pub struct Mat3D([[f32; 3]; 3]); impl Mat3D { pub fn one() -> Mat3D { Mat3D([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) } pub fn join(self, rhs: Mat3D) -> Mat3D { let mut y = [[0f32; 3]; 3]; for i in 0..3 { for j in 0..3 { y[i][j] = self.0[i][0] * rhs.0[0][i] + self.0[i][1] * rhs.0[1][i] + self.0[i][2] * rhs.0[2][i]; } } Mat3D(y) } pub fn transform(self, c: Coords) -> Coords { Coords { x: self.0[0][0] * c.x + self.0[0][1] * c.y + self.0[0][2] * c.z, y: self.0[1][0] * c.x + self.0[1][1] * c.y + self.0[1][2] * c.z, z: self.0[2][0] * c.x + self.0[2][1] * c.y + self.0[2][2] * c.z, } } } impl Default for Mat3D { fn default() -> Mat3D { Mat3D::one() } } impl From<[[f32; 3]; 3]> for Mat3D { fn from(m: [[f32; 3]; 3]) -> Mat3D { Mat3D(m) } } impl Mul for Mat3D { type Output = Mat3D; fn mul(self, rhs: Mat3D) -> Mat3D { self.join(rhs) } } impl Mul<Coords> for Mat3D { type Output = Coords; fn mul(self, rhs: Coords) -> Coords { self.transform(rhs) } } impl MulAssign for Mat3D { fn mul_assign(&mut self, rhs: Mat3D) { *self = (*self) * rhs; } }
use super::mocks::*; use super::{db_path, pause}; use crate::adapters::twitter::{ReceivedMessageContext, TwitterId}; use crate::connector::{AckResponse, EventType, JudgementRequest, Message}; use crate::primitives::{unix_time, Account, AccountType, NetAccount}; use crate::{test_run, Database}; use std::sync::Arc; use tokio::runtime::Runtime; #[test] fn twitter_init_message() { let mut rt = Runtime::new().unwrap(); rt.block_on(async { let db = Database::new(&db_path()).unwrap(); let manager = Arc::new(EventManager::new()); let (writer, twitter_child) = manager.child(); let my_screen_name = Account::from("@registrar"); let index_book = vec![ (Account::from("@registrar"), TwitterId::from(111u64)), (Account::from("@alice"), TwitterId::from(222u64)), ]; let twitter_transport = TwitterMocker::new(twitter_child, my_screen_name.clone(), index_book); let handlers = test_run( Arc::clone(&manager), db, Default::default(), DummyTransport::new(), twitter_transport, DummyTransport::new(), ) .await .unwrap(); let injector = handlers.reader.injector(); // Generate events. let msg = serde_json::to_string(&Message { event: EventType::NewJudgementRequest, data: serde_json::to_value(&JudgementRequest { address: NetAccount::alice(), accounts: [(AccountType::Twitter, Some(Account::from("@alice")))] .iter() .cloned() .collect(), }) .unwrap(), }) .unwrap(); // Send new judgement request. injector.send_message(msg.clone()).await; pause().await; let sender_watermark = unix_time(); writer .send_message(ReceivedMessageContext { sender: TwitterId::from(222u64), message: String::from("Hello, World!"), created: sender_watermark, }) .await; pause().await; // Verify events. let events = manager.events().await; assert!(events.contains(&Event::Connector(ConnectorEvent::Writer { message: Message { event: EventType::DisplayNamesRequest, data: serde_json::to_value(Option::<()>::None).unwrap(), } }))); assert!(events.contains(&Event::Connector(ConnectorEvent::Writer { message: Message { event: EventType::PendingJudgementsRequests, data: serde_json::to_value(Option::<()>::None).unwrap(), } }))); assert!( events.contains(&Event::Twitter(TwitterEvent::LookupTwitterId { twitter_ids: None, accounts: Some(vec![my_screen_name.clone(),]), lookups: vec![(my_screen_name, TwitterId::from(111u64)),], })) ); assert!( events.contains(&Event::Twitter(TwitterEvent::RequestMessages { exclude: TwitterId::from(111u64), watermark: 0, messages: vec![ReceivedMessageContext { sender: TwitterId::from(222u64), message: String::from("Hello, World!"), created: sender_watermark, }] })) ); assert!(events.contains(&Event::Connector(ConnectorEvent::Reader { message: msg }))); assert!(events.contains(&Event::Connector(ConnectorEvent::Writer { message: Message { event: EventType::Ack, data: serde_json::to_value(&AckResponse { result: String::from("Message acknowledged"), }) .unwrap() } }))); assert_eq!( events[6], Event::Twitter(TwitterEvent::LookupTwitterId { twitter_ids: Some(vec![TwitterId::from(222u64),]), accounts: None, lookups: vec![(Account::from("@alice"), TwitterId::from(222u64)),], }) ); match &events[7] { Event::Twitter(e) => match e { TwitterEvent::SendMessage { id, message } => { assert_eq!(id, &TwitterId::from(222u64)); match message { VerifierMessageBlank::InitMessageWithContext => {} _ => panic!(), } } _ => panic!(), }, _ => panic!(), } }); }
/// This file contains the CPU logic. /// Used http://nesdev.com/6502_cpu.txt as a reference. /// /// The NMOS 65xx processors have 256 bytes of stack memory ranging from $0100 to $01FF. use log::info; use std::convert::From; use crate::opcode::{self, *}; const MEMORY_SIZE_MAX: usize = 0xffff + 1; pub type AddressSpace = [u8; MEMORY_SIZE_MAX]; /// State of the CPU. /// /// For simplicity, we store the bank fixed to the CPU for now. As we build to a more advanced /// structure we will move this outside of the CPU (e.g. bank switching). /// /// TODO: Make these structs with certain operations available on them. pub struct Cpu { /// Program counter. /// /// Low 8-bit is PCL, higher 8-bit is PCH. pub program_counter: u16, /// Stack. pub stack: Stack, /// Processor Status. /// /// Contains flags to denote the process status. pub status: ProcessorStatus, /// Accumulator. pub a: u8, /// Index register X. pub x: u8, /// Index register Y. pub y: u8, /// Memory. /// /// Limited to NROM thus only has 64 kibibytes. pub memory: AddressSpace, pub cycles: u64, } impl Cpu { const FIRST_16_KB_OF_ROM: usize = 0x8000; const LAST_16_KB_OF_ROM: usize = 0xC000; /// Create a new CPU from a NesFile. /// /// TODO: This is a little leaky, the CPU shouldn't know about the NES File Format but instead a /// third-party service should know about both the NES File Format and the CPU to initialize the /// state of the CPU and let it run. pub fn new(nes_file: crate::ines::NesFile) -> Self { // Power up state derived from http://wiki.nesdev.com/w/index.php/CPU_power_up_state. let mut cpu = Cpu { // Hard coded to start at ROM. program_counter: 0xc000, stack: Stack::new(), status: ProcessorStatus::new(), a: 0, x: 0, y: 0, memory: [0; MEMORY_SIZE_MAX], cycles: 7, }; cpu.memory[Cpu::FIRST_16_KB_OF_ROM..Cpu::LAST_16_KB_OF_ROM] .copy_from_slice(&nes_file.prg_rom); cpu.memory[Cpu::LAST_16_KB_OF_ROM..].copy_from_slice(&nes_file.prg_rom); cpu } /// Start running! pub fn run(&mut self) { loop { let operation = opcode::next(self); info!( "{:X} {} \tA:{:02X} X:{:02X} Y:{:02X} P:{:02X} SP: {:02X} CYC: {}", self.program_counter, &operation.dump(self), self.a, self.x, self.y, u8::from(self.status.clone()), self.stack.as_stack_offset(), self.cycles ); operation.execute(self); } } } /// A 8 bit register that has the processor state. /// TODO: Expand this. #[derive(Clone)] pub struct ProcessorStatus { /// Carry (C) Flag pub carry: bool, /// Zero (Z) Flag pub zero: bool, /// Interrupt Disable (I) Flag pub interrupt_disable: bool, /// Overflow Flag pub overflow: bool, /// Bit 4, not used by CPU. pub b_flag: bool, /// Negative flag. pub negative: bool, /// Decimal flag. Should not ever be used in nes. pub decimal: bool, } impl ProcessorStatus { pub const CARRY_MASK: u8 = 0b0000_0001; pub const ZERO_MASK: u8 = 0b0000_0010; pub const INTERRUPT_DISABLE_MASK: u8 = 0b0000_0100; pub const DECIMAL_MASK: u8 = 0b0000_1000; pub const B_FLAG_MASK: u8 = 0b0010_0000; pub const OVERFLOW_MASK: u8 = 0b0100_0000; pub const NEGATIVE_MASK: u8 = 0b1000_0000; fn new() -> Self { ProcessorStatus { carry: false, zero: false, b_flag: false, interrupt_disable: true, overflow: false, negative: false, decimal: false, } } pub fn update_load(&mut self, value: u8) { self.zero = value == 0; self.negative = value & ProcessorStatus::NEGATIVE_MASK == ProcessorStatus::NEGATIVE_MASK; } pub fn update_bit(&mut self, value: u8) { self.update_load(value); self.overflow = value & ProcessorStatus::OVERFLOW_MASK == ProcessorStatus::OVERFLOW_MASK; } } impl From<ProcessorStatus> for u8 { fn from(src: ProcessorStatus) -> u8 { // Upper bit of b flag (bit 5 of status) is always 1. let b_flag_upper = 1u8; (src.carry as u8) | (src.zero as u8) << 1 | (src.interrupt_disable as u8) << 2 | (src.decimal as u8) << 3 | (src.b_flag as u8) << 4 | b_flag_upper << 5 | (src.overflow as u8) << 6 | (src.negative as u8) << 7 } } impl From<u8> for ProcessorStatus { fn from(src: u8) -> ProcessorStatus { ProcessorStatus { carry: src & ProcessorStatus::CARRY_MASK == ProcessorStatus::CARRY_MASK, zero: src & ProcessorStatus::ZERO_MASK == ProcessorStatus::ZERO_MASK, interrupt_disable: src & ProcessorStatus::INTERRUPT_DISABLE_MASK == ProcessorStatus::INTERRUPT_DISABLE_MASK, decimal: src & ProcessorStatus::DECIMAL_MASK == ProcessorStatus::DECIMAL_MASK, b_flag: src & ProcessorStatus::B_FLAG_MASK == ProcessorStatus::B_FLAG_MASK, overflow: src & ProcessorStatus::OVERFLOW_MASK == ProcessorStatus::OVERFLOW_MASK, negative: src & ProcessorStatus::NEGATIVE_MASK == ProcessorStatus::NEGATIVE_MASK, } } } /// Stack starts at 0x1000. pub struct Stack { // Address of the next free element in the stack (absolute address). stack_pointer: usize, } impl Stack { fn new() -> Self { Stack { stack_pointer: 0x1000 + 0xFD, } } /// Returns the expected value in cpu register which is an offset to $1000. fn as_stack_offset(&self) -> u8 { (self.stack_pointer - 0x1000) as u8 } pub fn push_addr(&mut self, memory: &mut AddressSpace, addr: u16) { let (pcl, pch) = addr_to_bytes(addr); memory[self.stack_pointer] = pch; memory[self.stack_pointer - 1] = pcl; self.stack_pointer -= 2; } pub fn push(&mut self, memory: &mut AddressSpace, value: u8) { memory[self.stack_pointer] = value; self.stack_pointer -= 1; } pub fn pop(&mut self, memory: &mut AddressSpace) -> u8 { let value = memory[self.stack_pointer + 1]; self.stack_pointer += 1; value } pub fn pop_addr(&mut self, memory: &mut AddressSpace) -> (u8, u8) { let pcl = memory[self.stack_pointer + 1]; let pch = memory[self.stack_pointer + 2]; self.stack_pointer += 2; (pcl, pch) } } #[cfg(test)] mod tests { use super::*; use crate::ines; use anyhow::Result; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; const LOG_FILENAME: &str = "test/nestest.log"; const WORKING_UP_TO_LINE: u32 = 73; #[test] fn test_until_fail() -> Result<()> { let nes_file = ines::NesFile::new("test/nestest.nes".to_string())?; let mut cpu = Cpu::new(nes_file); let f = File::open(LOG_FILENAME)?; let f = BufReader::new(f); let mut counter = 1u32; for line in f.lines() { let line = line.unwrap(); let operation = opcode::next(&cpu); let operation_output = format!("{:04X} {}", cpu.program_counter, operation.dump(&cpu)); if !line.contains(&operation_output) { println!("Expected output: {}", line); println!("Received output: {}", operation_output); panic!("Mismatch in operation state at {}.", counter); } let cpu_state_output = format!( "A:{:02X} X:{:02X} Y:{:02X} P:{:02X} SP:{:02X}", cpu.a, cpu.x, cpu.y, u8::from(cpu.status.clone()), cpu.stack.as_stack_offset(), ); let cyc = format!("CYC:{}", cpu.cycles); if !line.contains(&cpu_state_output) || !line.contains(&cyc) { println!("Expected output: {}", line); println!("Received output: {} __ {}", cpu_state_output, cyc); panic!("Mismatch in cpu state at {}.", counter); } operation.execute(&mut cpu); counter += 1; // Don't test further than this line. if counter == WORKING_UP_TO_LINE { break; } } Ok(()) } }
#![no_main] #![feature(start)] extern crate olin; use log::{error, info, warn}; use olin::entrypoint; entrypoint!(); fn main() -> Result<(), std::io::Error> { let string = "hi"; error!("{}", string); warn!("{}", string); info!("{}", string); Ok(()) }
/*------------------------------- args.rs 起動引数を取得して、 場合に応じたオプションをつける * print_usage() : ヘルプ表示用の関数 * print_version(): version表示用の関数 * impl Args * new() : 外部から呼び出す関数。内部でargs_check()を呼ぶ。 * args_check() : env::args()の値を見て、適切なモードを指定する * set_to_env_var(): デバッグモードかどうかを、環境変数に指定する * struct Args * flag_debug : debug modeかどうかを判定する変数 -------------------------------*/ use std::{self, env}; const USAGE: &'static str = " \ Description: dodge rock game USAGE: dodge_rock (-h | --help) dodge_rock (-v | --version) dodge_rock (-d | --debug) Options: -h --help Show this screen. -v --version Show version. -d --debug Run game with debug mode."; // build時にCargo.tomlから名前とバージョンを組み込ませる const OWN_NAME: &'static str = env!("CARGO_PKG_NAME"); const OWN_VERSION: &'static str = env!("CARGO_PKG_VERSION"); /// USAGEメッセージを表示。内部用。 fn print_usage() { println!("{}", USAGE); } /// versionを表示。内部用。 fn print_version() { println!("{} v{}", OWN_NAME, OWN_VERSION); } #[derive(Debug, Default)] pub struct Args { pub flag_debug: bool, } impl Args { /// 起動引数の読み込みと分析 pub fn new() { // Args struct用の各種変数初期化 let mut args:Args = Default::default(); // 引数なしの場合は早期終了、エラー回避。 if env::args().len() == 1 { // Do nothing } else { args.args_check(); } args.set_to_env_var(); } /// 内部用。env::args()を見て、適切な引数が使われていたら作動する。 fn args_check(&mut self) { // 起動引数を取得 let env_args: Vec<String> = env::args().skip(1).collect(); let first_arg = env_args[0].as_str(); match first_arg { "-h" | "--help" => { print_usage(); std::process::exit(0); } "-v" | "--version" => { print_version(); std::process::exit(0); } "-d" | "--debug" => { self.flag_debug = true; } _ => (), } // match end } /// ゲームの起動引数に応じて、起動モードを環境変数に指定 fn set_to_env_var(&self) { let game_activate_mode = "GAME_ACTIVATE_MODE"; if self.flag_debug { let debug = "DEBUG_MODE"; env::set_var(game_activate_mode, debug); } else { let normal = "NORMAL_MODE"; env::set_var(game_activate_mode, normal); } } }
use std::collections::HashMap; use std::str::FromStr; #[derive(Debug, PartialEq)] pub struct ParseError; #[derive(Debug, PartialEq)] pub struct PositionSpec { pos_a : (i64, i64), pos_b : (i64, i64), } impl FromStr for PositionSpec { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { let result: Vec<&str> = s.split(" -> ").collect(); let pos_a = PositionSpec::get_pos(&result[0]); let pos_b = PositionSpec::get_pos(&result[1]); Ok(Self { pos_a, pos_b}) } } impl PositionSpec { fn get_pos(result: &str) -> (i64, i64) { let mut pos_a = result.split(","); let pos_a_x: i64 = pos_a.next().unwrap().parse().unwrap(); let pos_a_y: i64 = pos_a.next().unwrap().parse().unwrap(); (pos_a_x, pos_a_y) } } pub fn part_1(input : &Vec<PositionSpec>) -> usize { let visisted_postions = get_visited_locations(input, false); visisted_postions.iter().filter( | (_key, value)| **value >= 2 as u64).count() } pub fn part_2(input : &Vec<PositionSpec>) -> usize { let visisted_postions = get_visited_locations(input, true); visisted_postions.iter().filter( | (_key, value)| **value >= 2 as u64).count() } fn get_visited_locations(input: &Vec<PositionSpec>, allow_diagonal : bool) -> HashMap<(i64, i64), u64> { let mut visisted_postions: HashMap<(i64, i64), u64> = HashMap::new(); for spec in input { let (range, x_step, y_step) = get_stepsize_and_range(spec); if allow_diagonal || x_step == 0 || y_step == 0 { let (mut x, mut y) = spec.pos_a; let count = visisted_postions.entry((x, y)).or_insert(0); *count += 1; for _ in 0..range.abs() { x += x_step; y += y_step; let count = visisted_postions.entry((x, y)).or_insert(0); *count += 1; } } } visisted_postions } fn get_stepsize_and_range(spec: &PositionSpec) -> (i64, i64, i64) { let (x1, y1) = spec.pos_a; let (x2, y2) = spec.pos_b; let dx = x2 - x1; let dy = y2 - y1; let range = { if dx.abs() > dy.abs() { dx } else { dy } }; let x_step = { if dx != 0 { dx / dx.abs() } else { 0 } }; let y_step = { if dy != 0 { dy / dy.abs() } else { 0 } }; (range, x_step, y_step) } #[cfg(test)] mod tests { use crate::day5::{part_1, part_2}; use crate::day5::PositionSpec; use crate::reader::{parse_lines_to_vec}; #[test] fn test_example() { let input : Vec<PositionSpec>= parse_lines_to_vec("./resources/inputs/day5-example.txt").unwrap(); assert_eq!(5, part_1(&input)); assert_eq!(12, part_2(&input)); } #[test] fn test_input() { let input : Vec<PositionSpec>= parse_lines_to_vec("./resources/inputs/day5-input.txt").unwrap(); assert_eq!(6225, part_1(&input)); assert_eq!(22116, part_2(&input)); } }
use std::{collections::HashMap, hash::Hash}; use chrono::{DateTime, Local}; use egui::{ emath::align, util::History, Color32, FontData, FontDefinitions, FontFamily, TextFormat, }; use env_logger::fmt::Color; use rfd; use serde_json; use zhouyi::show_text_divinate; use egui_extras::{Size,StripBuilder}; /// We derive Deserialize/Serialize so we can persist app state on shutdown. #[derive(serde::Deserialize, serde::Serialize)] #[serde(default)]// if we add new fields, give them default values when deserializing old state pub struct TemplateApp { // settings, meta-information divination_type: String, is_dark_theme: bool, // contents of the zhouyi gua_name: String, gua: String, duan: String, xang: String, xang_up: String, xang_bottom: String, subgua_up: String, subgua_bottom: String, yaos: Vec<String>, yaos_xang: Vec<String>, // contents of user inputs. inps: String, is_visual: bool, historys: Vec<( HashMap<String, String>, Vec<String>, Vec<String>, String, // inps String, // time String, //place String, // analysis Vec<(String, String)>, // comments with (text, time) )>, place: String, analyse: String, comments: Vec<(String, String)>, temp_comment: String, pop_open:bool, current_point:usize, is_open_import:bool, is_open_export:bool, hm:HashMap<String,String>, // Example stuff: label: String, // this how you opt-out of serialization of a member #[serde(skip)] value: f32, } impl Default for TemplateApp { fn default() -> Self { Self { // Example stuff: label: "Hello World!".to_owned(), value: 2.7, divination_type:"dayanshi".to_owned(), is_dark_theme:false, gua_name: "乾".to_owned(), gua: "乾,元亨,利貞。".to_owned(), duan:"《彖》曰:大哉乾元,萬物資始,乃統天。雲行雨施,品物流形,大明終始,六位時成,時乘六龍以御天。乾道變化,各正性命,保合大和,乃利貞。".to_owned(), xang:"《象》曰:天行健,君子以自強不息。".to_owned(), xang_up:"天".to_owned(), xang_bottom:"天".to_owned(), subgua_up:"乾".to_owned(), subgua_bottom:"乾".to_owned(), yaos:vec![ "初九:潛龍勿用。".to_owned(), "九二:見龍再田,利見大人。".to_owned(), "九三:君子終日乾乾,夕惕若,厲,無咎。".to_owned(), "九四:或躍在淵,無咎。".to_owned(), "九五:飛龍在天,利見大人。".to_owned(), "上九:亢龍有悔。".to_owned(), "用九:見群龍無首,吉。".to_owned() ], yaos_xang:vec!["《象》曰:潛龍勿用,陽在下也。".to_owned(), "《象》曰:見龍在田,德施普也。".to_owned(), "《象》曰:終日乾乾,反復道也。".to_owned(), "《象》曰:或躍在淵,進無咎也。".to_owned(), "《象》曰:飛龍在天,大人造也。".to_owned(), "《象》曰:亢龍有悔,盈不可久也。".to_owned(), "《象》曰:用九,天德不可為首也。".to_owned()], inps:"明天的我会快乐么".to_owned(), is_visual:false, historys:vec![], place:"无关".to_owned(), analyse:"".to_owned(), comments:vec![], temp_comment:"".to_owned(), pop_open:false, current_point:0, is_open_import:false, is_open_export:false, hm:HashMap::new(), } } } impl TemplateApp { /// Called once before the first frame. pub fn new(cc: &eframe::CreationContext<'_>) -> Self { // This is also where you can customize the look and feel of egui using // `cc.egui_ctx.set_visuals` and `cc.egui_ctx.set_fonts`. cc.egui_ctx.set_visuals(egui::Visuals::light()); // load CJK fonts. let mut fonts = FontDefinitions::default(); fonts.font_data.insert( "wenquan".to_owned(), FontData::from_static(include_bytes!("../data/wenquan.ttf")), ); // set priority fonts .families .get_mut(&FontFamily::Proportional) .unwrap() .insert(0, "wenquan".to_owned()); fonts .families .get_mut(&FontFamily::Monospace) .unwrap() .push("wenquan".to_owned()); cc.egui_ctx.set_fonts(fonts); // Load previous app state (if any). // Note that you must enable the `persistence` feature for this to work. if let Some(storage) = cc.storage { return eframe::get_value(storage, eframe::APP_KEY).unwrap_or_default(); } Default::default() } } impl eframe::App for TemplateApp { /// Called by the frame work to save state before shutdown. fn save(&mut self, storage: &mut dyn eframe::Storage) { eframe::set_value(storage, eframe::APP_KEY, self); } /// Called each time the UI needs repainting, which may be many times per second. /// Put your widgets into a `SidePanel`, `TopPanel`, `CentralPanel`, `Window` or `Area`. fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { let Self { label, value, divination_type, is_dark_theme, gua_name, gua, duan, xang, xang_up, xang_bottom, subgua_up, subgua_bottom, yaos, yaos_xang, inps, is_visual, historys, place, analyse, comments, temp_comment, pop_open, current_point, is_open_import, is_open_export, hm, } = self; let now = Local::now().format("%F-%T").to_string(); // let mut place: String = "无关".to_owned(); // let mut analyse=String::from(""); // let mut comments:Vec<(String,String)>=vec![]; if true { egui::CentralPanel::default().show(ctx, |ui| { let mut color_blue: Color32; if *is_dark_theme { ctx.set_visuals(egui::Visuals::dark()); color_blue = Color32::from_rgb(255, 255, 1); } else { ctx.set_visuals(egui::Visuals::light()); color_blue = Color32::from_rgb(33, 24, 68); } let (default_color, strong_color) = if ui.visuals().dark_mode { (Color32::LIGHT_GRAY, Color32::WHITE) } else { (Color32::DARK_GRAY, Color32::BLACK) }; ui.horizontal(|ui| { ui.label("主题"); ui.radio_value(is_dark_theme, false, "☀️亮色").clicked(); ui.radio_value(is_dark_theme, true, "🌙暗色").clicked(); }); // if ui.button("Change Theme").clicked() { // *is_dark_theme = !*is_dark_theme; // } ui.text_edit_multiline(inps); let mut track_divination = false; ui.horizontal(|ui| { ui.label("卜法"); track_divination |= ui .radio_value(divination_type, "dayanshi".to_owned(), "大衍筮法") .clicked(); track_divination |= ui .radio_value(divination_type, "coin".to_owned(), "铜钱爻") .clicked(); }); let mut track_lang = true; let mut lang = "zh".to_owned(); ui.horizontal(|ui| { ui.label("语言"); track_lang |= ui.radio_value(&mut lang, "zh".to_owned(), "中文").clicked(); track_lang |= ui .radio_value(&mut lang, "en".to_owned(), "English") .clicked(); }); ui.horizontal(|ui| { ui.label("占卜时刻"); let label = egui::widgets::Label::new(now.clone()); ui.add(label); ui.ctx().request_repaint(); }); ui.horizontal(|ui| { ui.label("占卜地点"); ui.horizontal(|ui|{ ui.set_width(230.0); ui.add(egui::TextEdit::singleline(place)); }); }); let divinate_b = egui::Button::new("卜筮之"); if ui.add(divinate_b).clicked() { *is_visual = true; // obtain the results of Gua let res = show_text_divinate(divination_type, inps); // at current results to history *hm = res .0 .iter() .map(|(k, v)| (String::from(*k), v.clone())) .collect(); // update the divination results *gua_name = res.0.get("name").unwrap().to_string(); *gua = res.0.get("gua").unwrap().to_string(); *duan = res.0.get("duan").unwrap().to_string(); *xang = res.0.get("xang").unwrap().to_string(); *xang_up = res.0.get("xang_top").unwrap().to_string(); *xang_bottom = res.0.get("xang_bottom").unwrap().to_string(); *subgua_up = res.0.get("gua_top").unwrap().to_string(); *subgua_bottom = res.0.get("gua_bottom").unwrap().to_string(); *yaos = res.1; *yaos_xang = res.2; } ui.separator(); // add the export and import button. ui.horizontal(|ui| { ui.label("卜筮记录管理: "); #[cfg(not(target_arch = "wasm32"))] if ui.button("导出").clicked() { if let Some(path) = rfd::FileDialog::new().save_file() { let res = serde_json::to_string(historys).unwrap(); std::fs::write(path, res); } } #[cfg(not(target_arch = "wasm32"))] if ui.button("导入").clicked() { if let Some(path) = rfd::FileDialog::new().pick_file() { let content = std::fs::read_to_string(path).unwrap(); *historys = serde_json::from_str(&content).unwrap(); } } if ui.button("文本方式导入").clicked() { *is_open_import=true; } if ui.button("导出为可复制的文本").clicked() { *is_open_export=true; } if ui.button("清空").clicked() { *historys = vec![]; *comments = vec![]; *place = "".to_owned(); *analyse = "".to_owned(); *temp_comment = "".to_owned(); *pop_open = false; *current_point = 0; *is_open_import = false; *is_open_export = false; *is_visual=false; } }); ui.separator(); ui.heading("往-卜"); let scroll = egui::ScrollArea::vertical() .max_height(400.0) .auto_shrink([false; 2]) .show(ui, |ui| { ui.vertical(|ui| { let mut newhis = historys.clone(); newhis.reverse(); let mut i_x:u8=0; for x in newhis { let mut t_job = egui::text::LayoutJob::default(); t_job.append( &(x.0.get("name").unwrap().clone() + " "), 0.0, TextFormat { color: strong_color, ..Default::default() }, ); t_job.append( &x.4.clone(), 0.0, TextFormat { color: default_color, background: Color32::from_rgb(239, 83, 80), ..Default::default() }, ); t_job.append( " ", 0.0, TextFormat { color: strong_color, ..Default::default() }, ); t_job.append( &x.5.clone(), 0.0, TextFormat { color: default_color, background: Color32::from_rgb(124, 179, 66), ..Default::default() }, ); ui.collapsing(t_job, |ui| { // question ui.horizontal(|ui| { ui.label("求卜: "); ui.colored_label(color_blue.clone(), x.3.clone()); }); ui.separator(); ui.horizontal(|ui| { ui.label("得卦"); ui.label(x.0.get("name").unwrap().clone()) .on_hover_cursor(egui::CursorIcon::Help) .on_hover_ui(|ui| { ui.heading(x.0.get("name").unwrap().clone()); ui.label(x.0.get("gua").unwrap().clone()); ui.colored_label( Color32::from_rgb(128, 140, 255), x.0.get("duan").unwrap().clone(), ); ui.colored_label( Color32::from_rgb(128, 128, 12), x.0.get("xang").unwrap().clone(), ); ui.separator(); for i_yao in 0..yaos.len() { ui.colored_label( Color32::from_rgb(3, 111, 4), x.1.clone().get(i_yao).unwrap(), ); ui.colored_label( Color32::from_rgb(111, 12, 4), x.2.clone().get(i_yao).unwrap(), ); ui.set_min_height(300.0); } }); }); ui.separator(); // analysis ui.horizontal(|ui| { ui.label("分析: "); ui.colored_label(color_blue.clone(), x.6.clone()); }); ui.separator(); // comments ui.collapsing("批注/应验", |ui| { egui::ScrollArea::vertical().max_height(100.) .min_scrolled_width(200.0).show( ui, |ui| { if ui.button("记录之").clicked() { *pop_open=true; *current_point=(*historys).len()-1-(i_x as usize); } ui.vertical(|ui| { let mut xx = x.7.clone(); xx.reverse(); for com in xx { ui.collapsing(com.1, |ui| { ui.label(com.0); }); } }); }, ); }) }); // // if gua_head.clicked(){ // // *is_visual=true; // // } // ui.label((x.3).clone()); // ui.label(x.4.clone()); // ui.label(x.5.clone()); i_x+=1 } }); }); egui::Window::new("通过文本导入").default_width(300.0) .open(is_open_import) .show(ctx,|ui|{ let mut read_text:String="".to_owned(); ui.text_edit_multiline(&mut read_text); if ui.button("毕").clicked(){ *historys = serde_json::from_str(&read_text).unwrap(); } }); egui::Window::new("导出为文本").default_width(300.0) .open(is_open_export) .show(ctx,|ui|{ let scroll = egui::ScrollArea::vertical() .max_height(400.0) .auto_shrink([false;2]) .show(ui, |ui| { let res = serde_json::to_string(historys).unwrap(); ui.vertical(|ui|{ let mut is_copyed=false; if ui.button("复制之").clicked(){ is_copyed=true; use clipboard::{ClipboardContext,ClipboardProvider}; let mut ctx:ClipboardContext = ClipboardProvider::new().unwrap(); let res = serde_json::to_string(historys).unwrap(); // ctx.set_contents(res).unwrap(); ui.output_mut(|o| o.copied_text = res.to_string()); } // ui.label(res); code_view_ui(ui,&res); }) }); }); // pop a new window to add the comments. egui::Window::new("记录之") .default_width(320.0) .open(pop_open) .show(ctx, |ui| { ui.horizontal(|ui| { ui.code("求卜:"); ui.label((historys.get(*current_point as usize).unwrap()).3.clone()); }); ui.separator(); let temp_map=historys.get(*current_point as usize) .unwrap().0.clone(); ui.heading(temp_map.get("name").unwrap().clone()); ui.label(temp_map.get("gua").unwrap().clone()).on_hover_text( temp_map.get("duan").unwrap().clone() + &temp_map.get("xang").unwrap().clone(), ); ui.separator(); let temp_yaos=historys.get(*current_point).unwrap().1.clone(); let temp_yxs=historys.get(*current_point).unwrap().2.clone(); for i_yao in 0..temp_yaos.len() { ui.colored_label( Color32::from_rgb(3, 111, 4), temp_yaos.get(i_yao).unwrap(), ) .on_hover_text( temp_yxs.get(i_yao).unwrap(), ); ui.set_min_height(200.0); } ui.separator(); ui.vertical(|ui| { ui.heading("解语"); ui.colored_label(color_blue.clone(),historys.get(*current_point).unwrap() .6.clone()); }); ui.separator(); ui.vertical(|ui| { let mut xx = (*(historys.get(*current_point as usize).unwrap())).7.clone(); xx.reverse(); for com in xx { ui.collapsing(com.1, |ui| { ui.label(com.0); }); } }); ui.separator(); ui.horizontal(|ui| { ui.text_edit_singleline( temp_comment, ); if ui.button("添加").clicked() { (*historys)[*current_point as usize].7.push(( temp_comment.clone(), now.clone(), )); } }); }); // ui.heading("eframe template"); // ui.hyperlink("https://github.com/emilk/eframe_template"); // ui.add(egui::github_link_file!( // "https://github.com/emilk/eframe_template/blob/master/", // "Source code." // )); // egui::warn_if_debug_build(ui); }); } egui::Window::new("结果") .default_width(340.0) .open(is_visual) .show(ctx, |ui| { ui.horizontal(|ui| { ui.code("求卜:"); ui.label(inps.clone()); }); ui.separator(); ui.heading(gua_name); ui.label(gua.clone()); ui.colored_label(Color32::from_rgb(128, 140, 255), duan); ui.colored_label(Color32::from_rgb(128, 128, 12), xang); ui.separator(); for i_yao in 0..yaos.len() { ui.colored_label(Color32::from_rgb(3, 111, 4), yaos.get(i_yao).unwrap()); ui.colored_label(Color32::from_rgb(111, 12, 4), yaos_xang.get(i_yao).unwrap()); ui.set_min_height(300.0); } ui.separator(); ui.vertical(|ui| { ui.heading("解易"); ui.label(" 1. 以卦意察之\n 2. 以诸爻审之\n 3. 写下预言"); ui.label("回车确认"); // ui.label("例:\n 1. ") let response=ui.add(egui::TextEdit::multiline(analyse)); if response.lost_focus(){ (*historys).push(( hm.clone(), yaos.clone(), yaos_xang.clone(), inps.clone(), String::from(now.clone()), place.clone(), analyse.clone(), comments.clone(), )); } }); // if ui.button("回返之").clicked() { // *is_visual = false; // } }); if false { egui::Window::new("Window").show(ctx, |ui| { ui.label("Windows can be moved by dragging them."); ui.label("They are automatically sized based on contents."); ui.label("You can turn on resizing and scrolling if you like."); ui.label("You would normally choose either panels OR windows."); }); } } } use egui::text::LayoutJob; /// View some code with syntax highlighting and selection. pub fn code_view_ui(ui: &mut egui::Ui, mut code: &str) { ui.add( egui::TextEdit::multiline(&mut code) .font(egui::TextStyle::Monospace) // for cursor height .code_editor() .desired_rows(1) .lock_focus(true), ); }
fn main() { let input = std::fs::read_to_string("input.txt").unwrap(); let lines: Vec<&str> = input.split("\n").collect(); let drawings: Vec<u32> = to_ints(lines[0], ","); // create list of boards for part 1 & part 2 let size = 5; let mut boards1: Vec<Board> = Vec::new(); let mut boards2: Vec<Board> = Vec::new(); let mut values: Vec<Vec<u32>> = Vec::new(); for i in 2..lines.len() { if lines[i].len() == 0 { continue; } values.push(to_ints(lines[i], " ")); if values.len() == size { boards1.push(Board::new(values.clone())); boards2.push(Board::new(values)); values = Vec::new(); } } println!("part 1={}", part1(boards1, &drawings)); println!("part 2={}", part2(boards2, &drawings)); } fn part1(mut boards: Vec<Board>, drawings: &Vec<u32>) -> u32 { for d in drawings { for b in &mut boards { b.mark(*d); if b.done() { return d * b.score(); } } } panic!("no solution") } fn part2(mut boards: Vec<Board>, drawings: &Vec<u32>) -> u32 { let mut current: Vec<&mut Board> = Vec::new(); for b in &mut boards { current.push(b); } for d in drawings { let mut next: Vec<&mut Board> = Vec::new(); let count = current.len(); for c in current { c.mark(*d); if !c.done() { next.push(c); } else { if count == 1 { return d * c.score(); } } } current = next; } panic!("no solution") } struct Board { values: Vec<Vec<u32>>, seen: Vec<Vec<bool>>, } impl Board { fn new(values: Vec<Vec<u32>>) -> Self { let seen: Vec<Vec<bool>> = vec![vec![false; values.len()]; values.len()]; Self { values: values, seen: seen, } } // slow but fine fn mark(&mut self, target: u32) { for (i, row) in self.values.iter().enumerate() { for (j, v) in row.iter().enumerate() { if target == *v { self.seen[i][j] = true; } } } } // slow but fine fn done(&self) -> bool { for i in 0..self.seen.len() { let mut all = true; for j in 0..self.seen[0].len() { if !self.seen[i][j] { all = false; break; } } if all { return true; } } for j in 0..self.seen[0].len() { let mut all = true; for i in 0..self.seen.len() { if !self.seen[i][j] { all = false; break; } } if all { return true; } } false } fn score(&self) -> u32 { let mut ret: u32 = 0; for i in 0..self.seen.len() { for j in 0..self.seen[0].len() { if !self.seen[i][j] { ret += self.values[i][j]; } } } ret } } // do i need all of the collect / iters ? fn to_ints(s: &str, d: &str) -> Vec<u32> { clean(s.trim()) .as_str() .split(d) .collect::<Vec<&str>>() .iter() .map(|v| v.parse::<u32>().unwrap()) .collect() } // remove depulicate spaces // write manually so i can learn rust syntax fn clean(s: &str) -> String { let mut ret = String::new(); let mut prev: Option<char> = None; for (_, c) in s.chars().enumerate() { if prev == None { if c != ' ' { ret = ret + &c.to_string(); } } else { if c != ' ' { ret = ret + &c.to_string(); } else { if prev != Some(' ') { ret = ret + &c.to_string(); } } } prev = Some(c); } ret }
#[macro_use] extern crate derive_builder; #[derive(Clone, Debug)] struct Resolution { width: u32, height: u32, } impl Default for Resolution { fn default() -> Resolution { Resolution { width: 1920, height: 1080, } } } #[derive(Debug, Default, Builder)] #[builder(field(private), setter(into))] struct GameConfig { #[builder(default)] resolution: Resolution, save_dir: Option<String>, #[builder(default)] autosave: bool, fov: f32, render_distance: u32, } fn main() { println!("24 Days of Rust vol. 2 - derive_builder"); let conf = GameConfigBuilder::default() .save_dir("saves".to_string()) .fov(70.0) .render_distance(1000u32) .build() .unwrap(); println!("{:?}", conf); }
#![allow(unused_unsafe)] use libc; use raw_window_handle::*; use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; use winapi::_core::ptr; use winapi::shared::minwindef::{BOOL, FALSE, TRUE, UINT}; use winapi::shared::windef::HWND; #[allow(non_snake_case)] #[inline] pub fn BOOL(flag: bool) -> BOOL { match flag { false => FALSE, true => TRUE, } } #[inline] pub fn slice_to_ptr<T>(s: &[T]) -> (UINT, *const T) { let len = s.len() as UINT; let p: *const T = match len { 0 => ptr::null(), _ => &s[0], }; (len, p) } #[inline] pub fn opt_to_ptr<T>(src: Option<&T>) -> *const T { match src { Some(a) => a, None => ptr::null(), } } #[inline] pub unsafe fn opt_to_ptr_mut<T>(src: Option<&T>) -> *mut T { opt_to_ptr(src) as *mut _ } #[inline] pub fn to_utf16_chars<'a, S: Into<&'a str>>(s: S) -> Vec<u16> { let s = s.into(); println!("to_utf16_chars({})", s); let v = OsStr::new(s) .encode_wide() .chain(Some(0).into_iter()) .collect::<Vec<_>>(); println!(" --> {:?}", v); v } #[inline] pub fn to_utf8_chars<'a, S: Into<&'a str>>(s: S) -> Vec<u8> { let s = s.into(); println!("to_utf8_chars({})", s); let mut v = s.as_bytes().to_vec(); v.push(0); println!(" --> {:?}", v); v } #[inline] pub unsafe fn memcpy(dst: *mut u8, src: *const u8, size: usize) -> *mut u8 { let dst = dst as *mut libc::c_void; let src = src as *const libc::c_void; libc::memcpy(dst, src, size) as *mut u8 } #[inline] pub unsafe fn HWND(handle: RawWindowHandle) -> HWND { match handle { RawWindowHandle::Windows(h) => h.hwnd as HWND, _ => ptr::null_mut() as HWND, } }
use embedded_graphics::{ mono_font::{ascii::FONT_6X10, MonoFont}, pixelcolor::BinaryColor, }; use crate::themes::default::toggle_button::{ ButtonStateColors, ToggleButtonStyle as ToggleButtonStyleTrait, }; pub struct ToggleButtonInactive; pub struct ToggleButtonIdle; pub struct ToggleButtonHovered; pub struct ToggleButtonPressed; impl ButtonStateColors<BinaryColor> for ToggleButtonInactive { const LABEL_COLOR: BinaryColor = BinaryColor::On; const BORDER_COLOR: BinaryColor = BinaryColor::Off; const BACKGROUND_COLOR: BinaryColor = BinaryColor::Off; } impl ButtonStateColors<BinaryColor> for ToggleButtonIdle { const LABEL_COLOR: BinaryColor = BinaryColor::On; const BORDER_COLOR: BinaryColor = BinaryColor::On; const BACKGROUND_COLOR: BinaryColor = BinaryColor::Off; } impl ButtonStateColors<BinaryColor> for ToggleButtonHovered { const LABEL_COLOR: BinaryColor = BinaryColor::On; const BORDER_COLOR: BinaryColor = BinaryColor::Off; const BACKGROUND_COLOR: BinaryColor = BinaryColor::Off; } impl ButtonStateColors<BinaryColor> for ToggleButtonPressed { const LABEL_COLOR: BinaryColor = BinaryColor::Off; const BORDER_COLOR: BinaryColor = BinaryColor::Off; const BACKGROUND_COLOR: BinaryColor = BinaryColor::On; } pub struct ToggleButtonInactiveChecked; pub struct ToggleButtonIdleChecked; pub struct ToggleButtonHoveredChecked; pub struct ToggleButtonPressedChecked; impl ButtonStateColors<BinaryColor> for ToggleButtonInactiveChecked { const LABEL_COLOR: BinaryColor = BinaryColor::On; const BORDER_COLOR: BinaryColor = BinaryColor::Off; const BACKGROUND_COLOR: BinaryColor = BinaryColor::Off; } impl ButtonStateColors<BinaryColor> for ToggleButtonIdleChecked { const LABEL_COLOR: BinaryColor = BinaryColor::Off; const BORDER_COLOR: BinaryColor = BinaryColor::Off; const BACKGROUND_COLOR: BinaryColor = BinaryColor::On; } impl ButtonStateColors<BinaryColor> for ToggleButtonHoveredChecked { const LABEL_COLOR: BinaryColor = BinaryColor::On; const BORDER_COLOR: BinaryColor = BinaryColor::On; const BACKGROUND_COLOR: BinaryColor = BinaryColor::Off; } impl ButtonStateColors<BinaryColor> for ToggleButtonPressedChecked { const LABEL_COLOR: BinaryColor = BinaryColor::On; const BORDER_COLOR: BinaryColor = BinaryColor::Off; const BACKGROUND_COLOR: BinaryColor = BinaryColor::Off; } pub struct ToggleButtonStyle; impl ToggleButtonStyleTrait<BinaryColor> for ToggleButtonStyle { type Inactive = ToggleButtonInactive; type Idle = ToggleButtonIdle; type Hovered = ToggleButtonHovered; type Pressed = ToggleButtonPressed; type InactiveChecked = ToggleButtonInactiveChecked; type IdleChecked = ToggleButtonIdleChecked; type HoveredChecked = ToggleButtonHoveredChecked; type PressedChecked = ToggleButtonPressedChecked; const FONT: MonoFont<'static> = FONT_6X10; }
// This file is part of NAME. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/NAME/master/COPYRIGHT. No part of NAME, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © YEAR The developers of NAME. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/NAME/master/COPYRIGHT. #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![deny(absolute_paths_not_starting_with_crate)] #![deny(invalid_html_tags)] #![deny(macro_use_extern_crate)] #![deny(missing_crate_level_docs)] #![deny(missing_docs)] #![deny(pointer_structural_match)] #![deny(unaligned_references)] #![deny(unconditional_recursion)] #![deny(unreachable_patterns)] #![deny(unused_import_braces)] #![deny(unused_must_use)] #![deny(unused_qualifications)] #![deny(unused_results)] #![warn(unreachable_pub)] #![warn(unused_lifetimes)] #![warn(unused_crate_dependencies)] //! #NAME //! //! This is a rust library.
#[cfg(all(not(target_arch = "wasm32"), test))] mod test; use std::convert::TryInto; use std::sync::Arc; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::Term; use crate::erlang::start_timer; use crate::runtime::timer::Format; use crate::timer; #[native_implemented::function(erlang:send_after/4)] pub fn result( arc_process: Arc<Process>, time: Term, destination: Term, message: Term, options: Term, ) -> exception::Result<Term> { let timer_start_options: timer::start::Options = options.try_into()?; start_timer( time, destination, Format::Message, message, timer_start_options, arc_process, ) .map_err(From::from) }
use std::ops::Neg; use std::collections::HashSet; fn part1(data : &str) -> i32 { data.lines().fold(0, |acc, line| { acc + parse_line(line) }) } fn parse_line(s : &str) -> i32 { let out = s.get(0..1).and_then(|sign| { s.get(1..).and_then(|rest| { rest.parse::<i32>().ok().map(|i| { if sign == "+" { i } else { i.neg() } }) }) }); match out { | Some(x) => x, | None => panic!("couldn't parse {}", s) } } fn part2(data : &str) -> (i32, i32) { let mut acc = 0; let mut i = 0; let mut seen : HashSet<i32> = HashSet::new(); seen.insert(acc); let mut lines = data.lines().map(parse_line).cycle(); loop { i += 1; acc += lines.next().expect("no lines left!"); if seen.contains(&acc) { break (acc, i) } seen.insert(acc); } } fn main() { let fname = "data/01.txt"; let fdata = std::fs::read_to_string(fname) .expect(&format!("couldn't read {}", fname)); println!("result p1: {}", part1(&fdata)); let (r, i) = part2(&fdata); println!("result p2: {} (after {} lines)", r, i); }
use std::sync::Arc; use self::{ changed_files_filter::ChangedFilesFilter, commit::CommitToScheduler, compaction_job_done_sink::CompactionJobDoneSink, compaction_job_stream::CompactionJobStream, df_plan_exec::DataFusionPlanExec, df_planner::DataFusionPlanner, divide_initial::DivideInitial, file_classifier::FileClassifier, ir_planner::IRPlanner, parquet_files_sink::ParquetFilesSink, partition_files_source::PartitionFilesSource, partition_filter::PartitionFilter, partition_info_source::PartitionInfoSource, post_classification_partition_filter::PostClassificationPartitionFilter, round_info_source::RoundInfoSource, round_split::RoundSplit, scratchpad::ScratchpadGen, }; pub mod changed_files_filter; pub(crate) mod commit; pub mod compaction_job_done_sink; pub mod compaction_job_stream; pub mod compaction_jobs_source; pub mod df_plan_exec; pub mod df_planner; pub mod divide_initial; pub mod file_classifier; pub mod file_filter; pub mod files_split; pub mod hardcoded; pub mod ir_planner; pub mod namespaces_source; pub mod parquet_file_sink; pub mod parquet_files_sink; pub mod partition_files_source; pub mod partition_filter; pub mod partition_info_source; pub mod partition_source; pub mod post_classification_partition_filter; pub mod report; pub mod round_info_source; pub mod round_split; pub mod scratchpad; pub mod split_or_compact; pub mod tables_source; pub mod timeout; /// Pluggable system to determine compactor behavior. Please see /// [Crate Level Documentation](crate) for more details on the /// design. #[derive(Debug, Clone)] pub struct Components { /// Source of partitions for the compactor to compact pub compaction_job_stream: Arc<dyn CompactionJobStream>, /// Source of information about a partition neededed for compaction pub partition_info_source: Arc<dyn PartitionInfoSource>, /// Source of files in a partition for compaction pub partition_files_source: Arc<dyn PartitionFilesSource>, /// Determines what type of compaction round the compactor will be doing pub round_info_source: Arc<dyn RoundInfoSource>, /// stop condition for completing a partition compaction pub partition_filter: Arc<dyn PartitionFilter>, /// condition to avoid running out of resources during compaction pub post_classification_partition_filter: Arc<dyn PostClassificationPartitionFilter>, /// Records "compaction job is done" status for given partition. pub compaction_job_done_sink: Arc<dyn CompactionJobDoneSink>, /// Commits changes (i.e. deletion and creation). pub commit: Arc<CommitToScheduler>, /// Creates `PlanIR` that describes what files should be compacted and updated pub ir_planner: Arc<dyn IRPlanner>, /// Creates an Execution plan for a `PlanIR` pub df_planner: Arc<dyn DataFusionPlanner>, /// Executes a DataFusion plan to multiple output streams. pub df_plan_exec: Arc<dyn DataFusionPlanExec>, /// Writes the streams created by [`DataFusionPlanExec`] to the object store. pub parquet_files_sink: Arc<dyn ParquetFilesSink>, /// Split files into two buckets "now" and "later". pub round_split: Arc<dyn RoundSplit>, /// Divide files in a partition into "branches" pub divide_initial: Arc<dyn DivideInitial>, /// Create intermediate temporary storage pub scratchpad_gen: Arc<dyn ScratchpadGen>, /// Classify files for each compaction branch. pub file_classifier: Arc<dyn FileClassifier>, /// Check for other processes modifying files. pub changed_files_filter: Arc<dyn ChangedFilesFilter>, }
//! File holding the OneOrMany type and associated tests //! //! Author: [Boris](mailto:boris@humanenginuity.com) //! Version: 1.0 //! //! ## Release notes //! - v1.0 : creation // ======================================================================= // LIBRARY IMPORTS // ======================================================================= use std::clone::Clone; use std::ops::{ Index, IndexMut }; use serde::{ Serialize, Serializer }; use traits::Pushable; // ======================================================================= // STRUCT & TRAIT DEFINITION // ======================================================================= /// Type to encapsulate 'one or many' values #[derive(Debug, PartialEq)] pub enum OneOrMany<T> { One(T), Many(Vec<T>), } // ======================================================================= // STRUCT & TRAIT IMPLEMENTATION // ======================================================================= impl<T> OneOrMany<T> { /// Return a reference to value (if is OneOrMany::One) or the first value of the vector (if is OneOrMany::Many) pub fn value<'v>(&'v self) -> Option<&'v T> { match *self { OneOrMany::One(ref val) => Some(val), OneOrMany::Many(ref vect) => vect.get(0), } } /// Return a mutable value (if is OneOrMany::One) or the first value of the vector (if is OneOrMany::Many) pub fn value_mut<'v>(&'v mut self) -> Option<&'v mut T> { match *self { OneOrMany::One(ref mut val) => Some(val), OneOrMany::Many(ref mut vect) => vect.get_mut(0), } } /// If the Value is `One` value, returns the associated value. Returns None otherwise. pub fn as_one(&self) -> Option<&T> { match *self { OneOrMany::One(ref o) => Some(o), _ => None, } } /// If the Value is `Many` value, returns the associated vector. Returns None otherwise. pub fn as_many(&self) -> Option<&Vec<T>> { match *self { OneOrMany::Many(ref vect) => Some(&*vect), _ => None, } } /// If the Value is `Many` value, returns the associated vector. Returns None otherwise. pub fn as_many_mut(&mut self) -> Option<&mut Vec<T>> { match *self { OneOrMany::Many(ref mut vect) => Some(vect), _ => None, } } /// Consume `self` and return the value (if is OneOrMany::One) or the first value of the vector (if is OneOrMany::Many) pub fn into_value(self) -> Option<T> { match self { OneOrMany::One(val) => Some(val), OneOrMany::Many(mut vect) => { if vect.len() > 0 { Some(vect.remove(0)) } else { None } } } } /// Consume `self` and return a vector containing all the values from `self` (if OneOrMany::Many) or one value (if OneOrMany::One) pub fn into_values(self) -> Vec<T> { match self { OneOrMany::One(val) => vec![val], OneOrMany::Many(vect) => vect, } } /// Returns `true` if `self` is OneOrMany::One pub fn is_one(&self) -> bool { match *self { OneOrMany::One(_) => true, _ => false, } } /// Returns `true` if `self` is OneOrMany::Many pub fn is_many(&self) -> bool { match *self { OneOrMany::Many(_) => true, _ => false, } } } /// Allow to push a new value into a mutable reference of OneOrMany /// /// - If `self` was OneOrMany::One => converts it to OneOrMany::Many and appends the new value /// - If `self` was OneOrMany::Many => appends the new value impl<T> Pushable<T> for OneOrMany<T> where T: Clone { fn push(&mut self, new_value: T) -> &mut Self { let mut vect : Vec<T> = Vec::new(); if self.is_one() { vect.push(self.value().unwrap().clone()); } else { vect.append(self.as_many_mut().unwrap()); } vect.push(new_value); ::std::mem::replace(self, OneOrMany::Many(vect)); self } } /// Access an element of this type. Panics if the index is out of bounds impl<T> Index<usize> for OneOrMany<T> { type Output = T; fn index(&self, index: usize) -> &T { match *self { OneOrMany::One(ref val) => { if index != 0 { panic!("index out of bounds: only 'One' value but the index is {}", index); } val }, OneOrMany::Many(ref vect) => &vect[index], } } } /// Access an element of this type in a mutable context. Panics if the index is out of bounds impl<T> IndexMut<usize> for OneOrMany<T> { fn index_mut(&mut self, index: usize) -> &mut T { match *self { OneOrMany::One(ref mut val) => { if index != 0 { panic!("index out of bounds: only 'One' value but the index is {}", index); } val }, OneOrMany::Many(ref mut vect) => &mut vect[index], } } } /// Implement IntoIterator for OneOrMany impl<T> IntoIterator for OneOrMany<T> { type Item = T; type IntoIter = ::std::vec::IntoIter<T>; fn into_iter(self) -> Self::IntoIter { self.into_values().into_iter() } } impl<T> Serialize for OneOrMany<T> where T: Serialize { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { match *self { OneOrMany::One(ref val) => serializer.serialize_newtype_variant("OneOrMany", 0, "One", val), OneOrMany::Many(ref vec) => serializer.serialize_newtype_variant("OneOrMany", 1, "Many", vec), } } } /// Allow to compare a Vector with an instance from OneOrMany impl <T: PartialEq<U>, U> PartialEq<Vec<U>> for OneOrMany<T> { fn eq(&self, other: &Vec<U>) -> bool { match *self { OneOrMany::One(ref val) => other.len() == 1 && *val == other[0], OneOrMany::Many(ref vect) => { let mut index = 0; while index < vect.len() { if self[index] != other[index] { return false; }; index += 1; } true } } } } impl <T: PartialEq<U>, U> PartialEq<::std::vec::IntoIter<U>> for OneOrMany<T> { fn eq(&self, other: &::std::vec::IntoIter<U>) -> bool { let other_slice = other.as_slice(); match *self { OneOrMany::One(ref val) => other_slice.len() == 1 && *val == other_slice[0], OneOrMany::Many(ref vect) => { let mut index = 0; while index < vect.len() { if self[index] != other_slice[index] { return false; }; index += 1; } true } } } } impl <'a, T> PartialEq<OneOrMany<T>> for Vec<&'a str> where T: PartialEq<&'a str> { fn eq(&self, other: &OneOrMany<T>) -> bool { match *other { OneOrMany::One(ref val) => self.len() == 1 && val == &self[0], OneOrMany::Many(ref vect) => vect == self } } } macro_rules! __impl_partial_eq { (Vec < $($args:ty),* $(,)* >) => { impl <T> PartialEq<OneOrMany<T>> for Vec<$($args),*> where Vec<T>: PartialEq<Vec<$($args),*>>, T: PartialEq<$($args),*> { fn eq(&self, other: &OneOrMany<T>) -> bool { match *other { OneOrMany::One(ref val) => self.len() == 1 && *val == self[0], OneOrMany::Many(ref vect) => vect == self } } } } } __impl_partial_eq!(Vec<i8>); __impl_partial_eq!(Vec<i16>); __impl_partial_eq!(Vec<i32>); __impl_partial_eq!(Vec<i64>); __impl_partial_eq!(Vec<u8>); __impl_partial_eq!(Vec<u16>); __impl_partial_eq!(Vec<u32>); __impl_partial_eq!(Vec<u64>); __impl_partial_eq!(Vec<isize>); __impl_partial_eq!(Vec<usize>); __impl_partial_eq!(Vec<f32>); __impl_partial_eq!(Vec<f64>); __impl_partial_eq!(Vec<String>); // ======================================================================= // UNIT TESTS // ======================================================================= #[cfg(test)] mod tests { #![allow(non_snake_case)] use super::OneOrMany; use traits::Pushable; #[test] fn OneOrMany_test_one() { let x = OneOrMany::One(17); assert_eq!(x.is_one(), true); assert_eq!(x.is_many(), false); assert_eq!(x.value().unwrap(), &17); assert_eq!(x[0], 17); assert_eq!(x.into_value().unwrap(), 17); let mut x = OneOrMany::One(18); assert_eq!(x.value_mut().unwrap(), &18); assert_eq!(x.into_value().unwrap(), 18); } #[test] fn OneOrMany_test_one_mut() { let mut x = OneOrMany::One(17); if let Some(y) = x.value_mut() { *y = 18; } assert_eq!(x.value().unwrap(), &18); x[0] = 19; assert_eq!(x.value().unwrap(), &19); } #[test] fn OneOrMany_test_many() { let x = OneOrMany::Many(vec![1, 2, 3]); assert_eq!(x.is_one(), false); assert_eq!(x.is_many(), true); assert_eq!(x.value().unwrap(), &1); assert_eq!(x[0], 1); assert_eq!(x[1], 2); assert_eq!(x[2], 3); assert_eq!(x.into_value().unwrap(), 1); let mut x = OneOrMany::Many(vec![11, 22, 33]); assert_eq!(x.value_mut().unwrap(), &11); assert_eq!(x.into_value().unwrap(), 11); } #[test] fn OneOrMany_test_many_mut() { let mut x = OneOrMany::Many(vec![1, 2, 3]); if let Some(y) = x.value_mut() { *y = 18; } assert_eq!(x.value().unwrap(), &18); assert_eq!(x.into_values(), vec![18, 2, 3]); let mut x = OneOrMany::Many(vec![1, 2, 3]); x[0] = 19; x[1] = 20; x[2] = 21; assert_eq!(x.into_values(), vec![19, 20, 21]); } #[test] #[should_panic(expected = "index out of bounds: only 'One' value but the index is")] fn OneOrMany_test_one_index_oob() { let x = OneOrMany::One(17); x[1]; } #[test] #[should_panic(expected = "index out of bounds: the len is 3 but the index is")] fn OneOrMany_test_many_index_oob() { let x = OneOrMany::Many(vec![1, 2, 3]); x[4]; } #[test] fn OneOrMany_test_one_into_iter() { let mut x = OneOrMany::One(17).into_iter(); assert_eq!(x.next(), Some(17)); assert_eq!(x.next(), None); } #[test] fn OneOrMany_test_many_into_iter() { let mut x = OneOrMany::Many(vec![1, 2, 3]).into_iter(); assert_eq!(x.next(), Some(1)); assert_eq!(x.next(), Some(2)); assert_eq!(x.next(), Some(3)); assert_eq!(x.next(), None); } #[test] fn OneOrMany_test_eq() { let ox = OneOrMany::One(17); let oy = OneOrMany::One(18); let mx = OneOrMany::Many(vec![1, 2, 3]); let my = OneOrMany::Many(vec![11, 22, 33]); assert_eq!(ox == ox, true); assert_eq!(mx == mx, true); assert_eq!(ox == oy, false); assert_eq!(oy == ox, false); assert_eq!(ox == mx, false); assert_eq!(mx == ox, false); assert_eq!(ox == my, false); assert_eq!(my == ox, false); } #[test] fn OneOrMany_test_eq_vect() { let x = OneOrMany::One(17); assert_eq!(x, vec![17]); assert_eq!(vec![17], x); let x = OneOrMany::Many(vec![1, 2, 3]); assert_eq!(x, vec![1, 2, 3]); assert_eq!(vec![1, 2, 3], x); assert_eq!(OneOrMany::One("test String".to_string()), vec!["test String".to_string()]); assert_eq!(vec!["test String".to_string()], OneOrMany::One("test String".to_string())); assert_eq!(OneOrMany::One("test String".to_string()), vec!["test String"]); assert_eq!(vec!["test String"], OneOrMany::One("test String".to_string())); assert_eq!(OneOrMany::One("test &str"), vec!["test &str"]); assert_eq!(vec!["test &str"], OneOrMany::One("test &str")); } #[test] fn OneOrMany_test_pushable() { let mut x = OneOrMany::One(17); x.push(18); assert_eq!(x, OneOrMany::Many(vec![17, 18])); let mut x = OneOrMany::Many(vec!["a", "b"]); x.push("c").push("d"); assert_eq!(x, OneOrMany::Many(vec!["a", "b", "c", "d"])); } }
use hashbrown::HashSet; use utils::VectorN; // #[test] pub fn run() { let input = read_input(include_str!("input/day17.txt")); println!("{}", exercise_1(&input, 160)); // let input = read_input_hack(include_str!("input/day17.txt")); println!("{}", exercise_2(&input, 160)); } type Vector = VectorN<4>; fn read_input(input: &str) -> HashSet<Vector> { input .lines() .enumerate() .flat_map(|(y, line)| { line.chars().enumerate().filter_map(move |(x, c)| { if c == '#' { Some(Vector { value: [x as isize, y as isize, 0, 0], }) } else { None } }) }) .collect() } fn exercise_1(input: &HashSet<Vector>, iterations: usize) -> usize { let offsets: Vec<Vector> = (-1..=1) .flat_map(|x| { (-1..=1).flat_map(move |y| { (-1..=1).map(move |z| Vector { value: [x, y, z, 0], }) }) }) .filter(|x| x.value != [0, 0, 0, 0]) .collect::<Vec<_>>(); exercise_a(input, iterations, offsets) } fn exercise_2(input: &HashSet<Vector>, iterations: usize) -> usize { let offsets: Vec<Vector> = (-1..=1) .flat_map(|x| { (-1..=1).flat_map(move |y| { (-1..=1).flat_map(move |z| { (-1..=1).map(move |w| Vector { value: [x, y, z, w], }) }) }) }) .filter(|x| x.value != [0, 0, 0, 0]) .collect::<Vec<_>>(); exercise_a(input, iterations, offsets) } fn exercise_b<const N: usize>(input: &HashSet<VectorN<N>>, iterations: usize) -> usize { let mut old_set = input.clone(); for _ in 0..iterations { let cands = candidates(&old_set, &offsets); old_set = cands .into_iter() .filter(|v| { let count = offsets .iter() .filter_map(|w| old_set.get(&(w.clone() + v.clone()))) .count(); match (old_set.contains(v), count) { (true, 2) => true, (true, 3) => true, (false, 3) => true, _ => false, } }) .collect(); } old_set.len() } fn exercise_a(input: &HashSet<Vector>, iterations: usize, offsets: Vec<Vector>) -> usize { let mut old_set = input.clone(); for _ in 0..iterations { let cands = candidates(&old_set, &offsets); old_set = cands .into_iter() .filter(|v| { let count = offsets .iter() .filter_map(|w| old_set.get(&(w.clone() + v.clone()))) .count(); match (old_set.contains(v), count) { (true, 2) => true, (true, 3) => true, (false, 3) => true, _ => false, } }) .collect(); } old_set.len() } fn candidates<const N: usize>( input: &HashSet<VectorN<N>>, offsets: &Vec<VectorN<N>>, ) -> HashSet<VectorN<N>> { input .iter() .flat_map(|v| offsets.iter().map(move |w| v.clone() + w.clone())) .collect() } #[cfg(test)] mod tests { use super::*; use crate::test::Bencher; #[test] fn d17ex1() { let input = read_input(include_str!("input/day17test.txt")); assert_eq!(112, exercise_1(&input, 6)) } #[test] fn d17ex2() { let input = read_input(include_str!("input/day17test.txt")); assert_eq!(848, exercise_2(&input, 6)); } #[bench] fn d17_bench_ex1(b: &mut Bencher) { let input = read_input(include_str!("input/day17.txt")); b.iter(|| exercise_1(&input, 6)); } #[bench] fn d17_bench_ex2(b: &mut Bencher) { let input = read_input(include_str!("input/day17.txt")); b.iter(|| exercise_2(&input, 6)); } }
fn main() { let mut fred = Person { first_name: "Fred".to_string(), last_name: "Sanford".to_string(), birth_year: 1908, }; fred.set_age(109); println!("{}", fred); print_name(&fred); let fido = Dog {name: "Fido".to_string()}; print_name(&fido); let snoopy = Dog {name: "Snoopy".to_string()}; let dog; { let spike = Dog {name: "Spike".to_string()}; dog = return_first(&snoopy, &spike); } print_name(dog); } fn print_name(nameable: &HasName) { println!("{}", nameable.get_name()); } fn return_first<'a, 'b>(obj1: &'a HasName, obj2: &'b HasName) -> &'a HasName { obj1 } trait HasName { fn get_name(&self) -> String; } struct Person { first_name: String, last_name: String, birth_year: i16, } impl Person { fn get_age(&self) -> i16 { 2017 - self.birth_year } fn set_age(&mut self, age: i16) { self.birth_year = 2017 - age; } } impl std::fmt::Display for Person { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{} {}, age {}", self.first_name, self.last_name, self.get_age()) } } impl HasName for Person { fn get_name(&self) -> String { format!("{} {}", self.first_name, self.last_name) } } struct Dog { name: String } impl HasName for Dog { fn get_name(&self) -> String { format!("{}", self.name) } }
mod ckb; use structopt::StructOpt; #[derive(StructOpt)] #[structopt( name = "nodebridge", about = "Bridge between the mining pool and the blockchain node", rename_all = "snake_case" )] enum Opt { #[structopt(name = "ckb", about = "Node bridge for CKB network")] Ckb { /// RPC address in <host>:<port> format #[structopt(long)] rpc_addr: String, /// RPC interval in milliseconds #[structopt(long, default_value = "3000")] rpc_interval: u64, #[structopt(long)] /// Kafka brokers in comma separated <host>:<port> format kafka_brokers: String, /// Job topic name #[structopt(long)] job_topic: String, /// Solved share topic name #[structopt(long)] solved_share_topic: String, /// Database URL in mysql://<username>:<password>@<host>:<port>/<table> format #[structopt(long)] db_url: String, }, } fn main() { env_logger::init(); let opt = Opt::from_args(); match opt { Opt::Ckb { rpc_addr, rpc_interval, kafka_brokers, job_topic, solved_share_topic, db_url, } => ckb::run( rpc_addr, rpc_interval, kafka_brokers, job_topic, solved_share_topic, db_url, ), } }
use ggez::{ Context, GameResult, nalgebra::Point2 }; use ggez::graphics; /// A menu with equally-sized, vertically-stacked menu items. pub struct Menu<T> { bounds: graphics::Rect, items: Vec<MenuItem<T>>, item_width: f32, item_height: f32, } struct MenuItem<T> { ident: T, bounds: graphics::Rect, text: graphics::Text, } impl<T> Menu<T> { pub fn new(position: Point2<f32>, item_width: f32, item_height: f32) -> Menu<T> { Menu { items: Vec::new(), bounds: graphics::Rect::new(position.x, position.y, item_width, 0.0), item_width, item_height, } } /// Add an item to the end (i.e. bottom) of the menu. pub fn add(&mut self, ident: T, label: &str) { let x = self.bounds.x; let y = self.bounds.y + self.item_height * self.items.len() as f32; self.bounds.h += self.item_height; self.items.push(MenuItem { ident, bounds: graphics::Rect::new(x, y, self.item_width, self.item_height), text: graphics::Text::new(label) }) } // pub fn get(&self, ident: &T) -> Option<MenuItem<T>> {} /// Evaluate whether the given point falls within the bounds of /// a menu item, returning the item's identifier. pub fn select(&self, p: Point2<f32>) -> Option<&T> { if !self.bounds.contains(p) { return None } self.items.iter() .find(|item| item.bounds.contains(p)) .map(|item| &item.ident) } pub fn draw(&self, ctx: &mut Context) -> GameResult<()> { let mut mesh = graphics::MeshBuilder::new(); for item in &self.items { mesh.rectangle(graphics::DrawMode::stroke(2.0), item.bounds, graphics::WHITE); let text_w = item.text.width(ctx) as f32; let text_h = item.text.height(ctx) as f32; let pos = Point2::new( item.bounds.x + (item.bounds.w - text_w) / 2., item.bounds.y + (item.bounds.h - text_h) / 2.); graphics::queue_text(ctx, &item.text, pos, Some(graphics::WHITE)); } let param = graphics::DrawParam::default(); if let Ok(menu) = mesh.build(ctx) { graphics::draw(ctx, &menu, param)?; } graphics::draw_queued_text(ctx, param, None, graphics::FilterMode::Linear)?; 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 serde_derive::{Deserialize, Serialize}; /// Enums and structs for wlan client status. /// These definitions come from fuchsia.wlan.policy/client_provider.fidl /// #[derive(Serialize, Deserialize, Debug)] pub enum WlanClientState { ConnectionsDisabled = 1, ConnectionsEnabled = 2, } #[derive(Serialize, Deserialize, Debug)] pub enum ConnectionState { Failed = 1, Disconnected = 2, Connecting = 3, Connected = 4, } #[derive(Serialize, Deserialize, Debug)] pub enum SecurityType { None = 1, Wep = 2, Wpa = 3, Wpa2 = 4, Wpa3 = 5, } #[derive(Serialize, Deserialize, Debug)] pub enum DisconnectStatus { TimedOut = 1, CredentialsFailed = 2, ConnectionStopped = 3, ConnectionFailed = 4, } #[derive(Serialize, Deserialize, Debug)] pub struct NetworkIdentifier { /// Network name, often used by users to choose between networks in the UI. pub ssid: Vec<u8>, /// Protection type (or not) for the network. pub type_: SecurityType, } #[derive(Serialize, Deserialize, Debug)] pub struct NetworkState { /// Network id for the current connection (or attempt). pub id: Option<NetworkIdentifier>, /// Current state for the connection. pub state: Option<ConnectionState>, /// Extra information for debugging or Settings display pub status: Option<DisconnectStatus>, } #[derive(Serialize, Deserialize, Debug)] pub struct ClientStateSummary { /// State indicating whether wlan will attempt to connect to networks or not. pub state: Option<WlanClientState>, /// Active connections, connection attempts or failed connections. pub networks: Option<Vec<NetworkState>>, }
// Copyright 2017 Dasein Phaos aka. Luxko // // 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. //! describes what kind of resources are to be bound to the pipeline. use device::Device; use smallvec::SmallVec; use comptr::ComPtr; use winapi::{ID3D12RootSignature, ID3DBlob}; use error::WinError; use super::sampler::StaticSamplerDesc; /// a root signature #[derive(Clone, Debug)] pub struct RootSig { pub(crate) ptr: ComPtr<ID3D12RootSignature>, } /// a serialized root signature description blob #[derive(Clone, Debug)] pub struct RootSigDescBlob { pub(crate) ptr: ComPtr<ID3DBlob>, } /// builder for a root signature #[derive(Clone, Debug, Default)] pub struct RootSigBuilder { pub root_params: SmallVec<[RootParam; 8]>, pub static_samplers: SmallVec<[StaticSamplerDesc; 8]>, pub flags: RootSigFlags, } impl RootSigBuilder { /// construct a new builder pub fn new() -> Self { Default::default() } /// build a root signature with description in this builder using `device` pub fn build(&self, device: &mut Device, node_mask: u32) -> Result<RootSig, WinError> { let blob = self.serialize()?; device.create_root_sig(node_mask, &blob) } /// serialize the description into a blob pub fn serialize(&self) -> Result<RootSigDescBlob, WinError> { let mut root_params: SmallVec<[_; 8]> = Default::default(); for root_param in self.root_params.iter() { root_params.push(root_param.into()); } let desc = ::winapi::D3D12_ROOT_SIGNATURE_DESC{ NumParameters: root_params.len() as u32, pParameters: root_params.as_ptr(), NumStaticSamplers: self.static_samplers.len() as u32, pStaticSamplers: self.static_samplers.as_ptr() as *const _, Flags: self.flags.into() }; unsafe { let mut ptr = ::std::mem::uninitialized(); let hr = ::d3d12::D3D12SerializeRootSignature( &desc, ::winapi::D3D_ROOT_SIGNATURE_VERSION_1, // TODO: support more signature versions? &mut ptr, ::std::ptr::null_mut() // TODO: support error blob? ); WinError::from_hresult_or_ok(hr, || RootSigDescBlob{ ptr: ComPtr::new(ptr) }) } } } /// describes a root parameter #[derive(Clone, Debug)] pub struct RootParam { /// shader visibility pub visibility: ShaderVisibility, pub param_type: RootParamType, } impl<'a> From<&'a RootParam> for ::winapi::D3D12_ROOT_PARAMETER { fn from(param: &'a RootParam) -> Self { let (t, d) = match param.param_type { RootParamType::DescriptorTable{ ref descriptor_ranges } => ( ::winapi::D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, ::winapi::D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: descriptor_ranges.len() as u32, pDescriptorRanges: descriptor_ranges.as_ptr() as *const _, } ), RootParamType::Constant{ shader_register, register_space, num_32bit_values, } => ( ::winapi::D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, ParamTypeHelper::new(shader_register, register_space, num_32bit_values).into() ), RootParamType::Cbv{ shader_register, register_space, } => ( ::winapi::D3D12_ROOT_PARAMETER_TYPE_CBV, ParamTypeHelper::new(shader_register, register_space, 0).into() ), RootParamType::Srv{ shader_register, register_space, } => ( ::winapi::D3D12_ROOT_PARAMETER_TYPE_SRV, ParamTypeHelper::new(shader_register, register_space, 0).into() ), RootParamType::Uav{ shader_register, register_space, } => ( ::winapi::D3D12_ROOT_PARAMETER_TYPE_UAV, ParamTypeHelper::new(shader_register, register_space, 0).into() ), }; ::winapi::D3D12_ROOT_PARAMETER{ ParameterType: t, u: d, ShaderVisibility: unsafe{::std::mem::transmute(param.visibility)} } } } /// specifies a type of root parameter #[derive(Clone, Debug)] pub enum RootParamType { /// a collection of descriptor ranges, appearing in sequence in a descriptor heap DescriptorTable{ /// an array of descriptor ranges descriptor_ranges: SmallVec<[DescriptorRange; 4]>, }, /// cbv descriptor inlined in the signature Cbv{ /// the shader register shader_register: u32, /// the register space register_space: u32, }, /// srv descriptor inlined in the signature Srv{ /// the shader register shader_register: u32, /// the register space register_space: u32, }, /// uav descriptor inlined in the signature Uav{ /// the shader register shader_register: u32, /// the register space register_space: u32, }, /// constants inlined in the signature that appear in shaders as one constant buffer Constant{ /// shader register of this constant shader_register: u32, /// register space of this constant register_space: u32, /// number of 32bit values in this constant slot num_32bit_values: u32, }, } #[repr(C)] struct ParamTypeHelper { shader_register: u32, register_space: u32, num_32bit_values: u32, _pad: u32, } impl ParamTypeHelper { #[inline] fn new(shader_register: u32, register_space: u32, num_32bit_values: u32) -> Self { ParamTypeHelper{shader_register, register_space, num_32bit_values, _pad: 0} } } impl From<ParamTypeHelper> for ::winapi::D3D12_ROOT_DESCRIPTOR_TABLE { fn from(helper: ParamTypeHelper) -> Self { unsafe {::std::mem::transmute(helper)} } } /// descriptor range #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct DescriptorRange { pub range_type: DescriptorRangeType, pub num_descriptors: u32, pub base_shader_register: u32, pub register_space: u32, pub offset_from_table_start: u32, } bitflags!{ /// type of a descriptor range #[repr(C)] pub struct DescriptorRangeType: u32 { const SRV = 0; const UAV = DescriptorRangeType::SRV.bits + 1; const CBV = DescriptorRangeType::UAV.bits + 1; const SAMPLER = DescriptorRangeType::CBV.bits + 1; } } bitflags!{ /// specifies which shader can access content of a given root parameter #[repr(C)] pub struct ShaderVisibility: u32 { const ALL = 0; const VERTEX = 1; const HULL = 2; const DOMAIN = 3; const GEOMETRY = 4; const PIXEL = 5; } } impl Default for ShaderVisibility { #[inline] fn default() -> ShaderVisibility { ShaderVisibility::ALL } } bitflags!{ /// misc flags for a root signature #[repr(C)] pub struct RootSigFlags: u32 { const NONE = 0; const ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT = 0x1; const DENY_VERTEX_SHADER_ROOT_ACCESS = 0x2; const DENY_HULL_SHADER_ROOT_ACCESS = 0x4; const DENY_DOMAIN_SHADER_ROOT_ACCESS = 0x8; const DENY_GEOMETRY_SHADER_ROOT_ACCESS = 0x10; const DENY_PIXEL_SHADER_ROOT_ACCESS = 0x20; const ALLOW_STREAM_OUTPUT = 0x40; } } impl Default for RootSigFlags { #[inline] fn default() -> Self { RootSigFlags::ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT } } impl From<RootSigFlags> for ::winapi::D3D12_ROOT_SIGNATURE_FLAGS { #[inline] fn from(flags: RootSigFlags) -> Self { unsafe{ ::std::mem::transmute(flags)} } }
use game; use game_item; use hero; use low_level; use map; use monster; use texts; pub fn HeroShot(app: &mut ::cursive::Cursive, direction: map::Direction) { use map::Direction::*; let curhero = get_mut_ref_curhero!(); if let Some(item) = curhero.Slots[hero::slotHands] { if item.IType != game_item::TGameItemType::ItemRangedWeapon { low_level::ShowInfo(app, texts::STR_NONE_RANGED_WEAPONS.to_string()); return; } } else { low_level::ShowInfo(app, texts::STR_NONE_WEAPONS.to_string()); return; } if curhero.Slots[hero::slotHands].unwrap().Ints[game_item::intRangedAmmo] == Some(0) { low_level::ShowInfo(app, texts::STR_NONE_AMMO.to_string()); return; } let mut old_item = curhero.Slots[hero::slotHands].unwrap(); let n = old_item.Ints[game_item::intRangedAmmo]; old_item.Ints[game_item::intRangedAmmo] = Some(n.unwrap() - 1); curhero.Slots[hero::slotHands] = if n.unwrap() > 0 { Some(old_item) } else { None }; if !hero::SkillTest(app, curhero, hero::skillRangedWeapon) { low_level::ShowInfo(app, texts::STR_BAD_RANGED_ATTACK.to_string()); return; } let mut n = curhero.Slots[hero::slotHands].unwrap().Ints[game_item::intRangedRange].unwrap(); let d = game::RollDice(3, 6); if d <= curhero.Chars[hero::chrDEX] { n += n / 3; } let (mut x, mut y) = (curhero.x, curhero.y); while n >= 1 { match direction { Up => { y += 1; } Down => { y -= 1; } Left => { x -= 1; } Right => { x += 1; } } if !map::FreeTile(&get_ref_curmap!().Cells[x][y].Tile) { return; } let m = monster::IsMonsterOnTile(x, y); if m.is_some() { let mut dam = game::RollDice( curhero.Slots[hero::slotHands].unwrap().Ints[game_item::intRangedDices].unwrap(), curhero.Slots[hero::slotHands].unwrap().Ints[game_item::intRangedDiceNum].unwrap()); let d = game::RollDice(3, 6); if d <= curhero.Chars[hero::chrSTR] { dam += dam / 3; } HeroAttackFin(app, curhero, m.unwrap(), dam); monster::MonstersStep(app); // Don't change an order of operations! hero::SetHeroVisible(unsafe { hero::CUR_HERO }); game::ShowGame(app); return; } n -= 1; } } fn HeroAttackFin(app: &mut ::cursive::Cursive, h: &mut hero::THero, m: usize, dam: usize) { // let mut mnstr = unsafe { monster::MONSTERS[m] }; // let skin = game::RollDice(mnstr.Dd1, mnstr.Dd2); // if skin >= dam { // low_level::ShowInfo(app, texts::STR_BIG_SKIN.to_string()); // return; // } // mnstr.HP -= dam - skin; // low_level::ShowInfo(app, texts::STR_ATTACK.to_string() + &(dam-skin).to_string()); // // if mnstr.HP <= 0 { // low_level::ShowInfo(app, mnstr.Name.to_string() + texts::STR_MON_KILL); // hero::IncXP(app, h, mnstr.XP); // } let skin = unsafe { game::RollDice(monster::MONSTERS[m].Dd1, monster::MONSTERS[m].Dd2) }; if skin > dam { low_level::ShowInfo(app, texts::STR_BIG_SKIN.to_string()); return; } unsafe { if monster::MONSTERS[m].HP >= (dam - skin) { monster::MONSTERS[m].HP -= dam - skin; } else { monster::MONSTERS[m].HP = 0; } }; low_level::ShowInfo(app, format!("{}{}", texts::STR_ATTACK, dam - skin)); unsafe { if monster::MONSTERS[m].HP == 0 { low_level::ShowInfo( app, format!("{}{}", monster::MONSTERS[m].Name, texts::STR_MON_KILL), ); // Don't change an order of operations! hero::SetHeroVisible(hero::CUR_HERO); game::ShowGame(app); } hero::IncXP(app, h, monster::MONSTERS[m].XP); } } pub fn HeroAttack(app: &mut ::cursive::Cursive, h: &mut hero::THero, m: usize) { let w = hero::GetHeroWeapon(h); if w.is_none() { low_level::ShowInfo(app, texts::STR_NONE_WEAPONS.to_string()); return; } if !hero::SkillTest(app, h, hero::skillHandWeapon) { low_level::ShowInfo(app, texts::STR_BAD_ATTACK.to_string()); return; } let mut dam = WeaponDamage(h.Slots[w.unwrap()].unwrap()); let d = game::RollDice(3, 6); if d <= h.Chars[hero::chrSTR] { dam += dam / 2; // If the hero is strong, then the damage from his impact will be increased by one and a half times. } HeroAttackFin(app, h, m, dam); } fn WeaponDamage(itm: game_item::TGameItem) -> usize { if map::random(0, 100) + 1_usize > itm.Ints[game_item::intAttackHit].unwrap() as usize { return 0; } game::RollDice( itm.Ints[game_item::intAttack_d1].unwrap(), itm.Ints[game_item::intAttack_d2].unwrap(), ) } pub fn MonstersAttack(app: &mut ::cursive::Cursive) { let curhero = get_mut_ref_curhero!(); for i in 0..monster::MaxMonsters { if unsafe { monster::MONSTERS[i].HP > 0 && CanAttack(i, hero::CUR_HERO) } { MonsterAttack(app, i, curhero); } } low_level::ShowHeroInfo(app, unsafe { hero::CUR_HERO }); } fn CanAttack(MonsterNum: usize, HeroNum: usize) -> bool { unsafe { Distance( (hero::HEROES[HeroNum].x, hero::HEROES[HeroNum].y), ( monster::MONSTERS[MonsterNum].x, monster::MONSTERS[MonsterNum].y, ), ) == 1 } } pub fn Distance(hero_xy: (usize, usize), monster_xy: (usize, usize)) -> usize { use std::cmp::{min, max}; max(hero_xy.0, monster_xy.0) - min(hero_xy.0, monster_xy.0) + max(hero_xy.1, monster_xy.1) - min(hero_xy.1, monster_xy.1) } fn MonsterAttack(app: &mut ::cursive::Cursive, MonsterNum: usize, h: &mut hero::THero) { if hero::SkillTest(app, h, hero::skillDefence) { unsafe { low_level::ShowInfo( app, format!( "{}{}", monster::MONSTERS[MonsterNum].Name, texts::STR_MON_STOP ), ); } return; } let dam = unsafe { game::RollDice( monster::MONSTERS[MonsterNum].Ad1, monster::MONSTERS[MonsterNum].Ad2, ) }; let def = hero::GetHeroDefence(h); if dam <= def { unsafe { low_level::ShowInfo( app, format!( "{}{}", monster::MONSTERS[MonsterNum].Name, texts::STR_MON_DEF ), ); } return; } unsafe { low_level::ShowInfo( app, format!( "{}{} {} points!", monster::MONSTERS[MonsterNum].Name, texts::STR_MON_ATTACK, dam - def ), ); } hero::DecHP(app, h, dam - def); }
use crate::function::LoxFunction; use crate::class::{LoxObject, LoxClass}; use crate::state::State; use crate::value::{Value, ValueError, LoxTrait, LoxArray}; use parser::types::{Expression, ExpressionType, FunctionHeader, ProgramError, SourceCodeLocation, Statement, StatementType, TokenType, Type}; use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; use std::convert::{TryInto, TryFrom}; use std::iter::FromIterator; use std::ops::{Add, Div, Mul, Sub}; use std::rc::Rc; use std::path::Path; use std::fs::File; use std::io::Read; use parser::lexer::Lexer; use parser::parser::Parser; pub type EvaluationResult<'a> = Result<Value<'a>, ProgramError<'a>>; fn operation<'a, R, T: TryFrom<Value<'a>, Error=ValueError>>(l: Value<'a>, r: Value<'a>, op: fn(T, T) -> R) -> Result<R, ValueError> { let l_number = l.try_into()?; let r_number = r.try_into()?; Ok(op(l_number, r_number)) } fn f32_math_operation<'a>(l: Value<'a>, r: Value<'a>, op: fn(f32, f32) -> f32) -> Result<Value<'a>, ValueError> { Ok(Value::Float { value: operation(l, r, op)?, }) } fn i64_math_operation<'a>(l: Value<'a>, r: Value<'a>, op: fn(i64, i64) -> i64) -> Result<Value<'a>, ValueError> { Ok(Value::Integer { value: operation(l, r, op)?, }) } fn math_operation<'a>(l: Value<'a>, r: Value<'a>, i64_op: fn(i64, i64) -> i64, f32_op: fn(f32, f32) -> f32) -> Result<Value<'a>, ValueError> { match (&l, &r) { (Value::Float { .. }, Value::Float { .. }) => f32_math_operation(l, r, f32_op), (Value::Float { .. }, Value::Integer { value }) => f32_math_operation(l, Value::Float { value: *value as _ }, f32_op), (Value::Integer { value }, Value::Float { .. }) => f32_math_operation(Value::Float { value: *value as _ }, r, f32_op), (Value::Integer { .. }, Value::Integer { .. }) => i64_math_operation(l, r, i64_op), _ => Err(ValueError::ExpectingNumber), } } fn comparison_operation<'a>(l: Value<'a>, r: Value<'a>, op: fn(f32, f32) -> bool) -> Result<Value<'a>, ValueError> { Ok(Value::Boolean { value: operation(l, r, op)?, }) } fn statements_to_hash_set<'a>(statements: &[&Statement<'a>]) -> HashSet<FunctionHeader<'a>> { let mut map = HashSet::new(); for s in statements { if let StatementType::FunctionDeclaration { name, arguments, .. } = &s.statement_type { map.insert(FunctionHeader { name, arity: arguments.len(), }); } else { panic!("Unexpected statement"); } } map } fn check_trait_methods<'a>( impl_methods: &[&Statement<'a>], trait_methods: &[FunctionHeader], location: &SourceCodeLocation<'a>, ) -> Result<(), Vec<ProgramError<'a>>> { let trait_methods_hash = HashSet::from_iter(trait_methods.iter().cloned()); let impl_methods_hash = statements_to_hash_set(impl_methods); let missed_methods = trait_methods_hash.difference(&impl_methods_hash); let extra_methods = impl_methods_hash.difference(&trait_methods_hash); let mut errors = vec![]; for missed_method in missed_methods { errors.push(ProgramError { location: location.clone(), message: format!( "Missing method {} of arity {}, in trait implementation", missed_method.name, missed_method.arity ), }); } for extra_method in extra_methods { errors.push(ProgramError { location: location.clone(), message: format!( "Method {} of arity {} is not in trait declaration", extra_method.name, extra_method.arity ), }); } if errors.is_empty() { Ok(()) } else { Err(errors) } } fn is_trait(trait_name: &str, obj: &LoxObject) -> bool { if obj.traits.contains(trait_name) { true } else { if let Some(superclass) = &obj.superclass { is_trait(trait_name, superclass) } else { false } } } fn is_class<'a>(lox_class: &LoxClass<'a>, obj: &LoxObject<'a>) -> bool { if lox_class.name == obj.class_name { true } else { if let Some(superclass) = &obj.superclass { is_class(lox_class, superclass) } else { false } } } pub struct Interpreter<'a> { pub blacklist: RefCell<Vec<&'a str>>, pub locals: HashMap<usize, usize>, modules: Cell<HashMap<&'a str, Vec<Box<Statement<'a>>>>>, module_contents: Cell<HashMap<&'a str, String>>, module_interpreters: Cell<HashMap<&'a str, Box<Interpreter<'a>>>>, paths: &'a [String], pub state: RefCell<State<'a>>, } impl<'a> Interpreter<'a> { pub fn new(paths: &'a [String], file: &'a str,) -> Interpreter<'a> { Interpreter { blacklist: RefCell::new(vec![file]), locals: HashMap::default(), modules: Cell::new(HashMap::default()), module_contents: Cell::new(HashMap::default()), module_interpreters: Cell::new(HashMap::default()), state: RefCell::new(State::default()), paths, } } pub fn run(&'a self, content: &'a [Statement<'a>]) -> Result<(), ProgramError<'a>> { for s in content { self.evaluate(s)?; } Ok(()) } pub fn evaluate_expression(&'a self, expression: &'a Expression<'a>) -> EvaluationResult<'a> { match &expression.expression_type { ExpressionType::IsType { value, checked_type } => { let value = self.evaluate_expression(value)?; self.is_value_type(&value, checked_type, &expression.location) } ExpressionType::ModuleLiteral { module, field, } => { let value = self.look_up_variable(expression.id(), module) .ok_or_else(|| { expression.create_program_error(&format!("Module `{}` not found!", module)) })?; if let Value::Module(module) = value { self.get_module_interpreter(module).evaluate_expression(field) } else { Err(expression.create_program_error(&format!("Variable `{}` is not a module", module))) } } ExpressionType::ArrayElementSet { array, index, value, } => self.array_element_expression_set(array, index, value), ExpressionType::ArrayElement { array, index } => { self.array_element_expression(array, index) } ExpressionType::RepeatedElementArray { element, length } => { let element = self.evaluate_expression(element)?; let length = self.evaluate_expression(length)?; if let Value::Integer { value: length } = length { let elements = vec![Box::new(element); length as _]; Ok(Value::Array(Rc::new(RefCell::new(LoxArray { elements, capacity: length as _, })))) } else { Err(expression.create_program_error("Array length should be an integer")) } } ExpressionType::Array { elements } => { let elements = elements .iter() .try_fold(vec![], |mut elements, e| { let e = self.evaluate_expression(e)?; elements.push(Box::new(e)); Ok(elements) })?; Ok(Value::Array(Rc::new(RefCell::new(LoxArray { capacity: elements.len(), elements, }))), ) } ExpressionType::Set { callee, property, value, } => self.set_property(callee, property, value), ExpressionType::Get { callee, property } => { self.get_property(callee, property) } ExpressionType::ExpressionLiteral { value } => Ok(value.into()), ExpressionType::VariableLiteral { identifier } => self.look_up_variable(expression.id(), identifier) .ok_or_else(|| { expression.create_program_error(&format!("Variable `{}` not found!", identifier)) }), ExpressionType::Grouping { expression } => self.evaluate_expression(expression), ExpressionType::UpliftFunctionVariables(_) => return Ok(Value::Nil), ExpressionType::UpliftClassVariables(_) => return Ok(Value::Nil), ExpressionType::Unary { operand, operator: TokenType::Minus, } => { let v = self.evaluate_expression(operand)?; if v.is_number() { Ok(-v) } else { Err(expression.create_program_error("Can only negate numbers")) } } ExpressionType::Unary { operand, operator: TokenType::Bang, } => self.evaluate_expression(operand).map(|v| !v), ExpressionType::Unary { .. } => { Err(expression.create_program_error("Invalid unary operator")) } ExpressionType::Binary { left, right, operator: TokenType::Plus, } => self.add_expressions(left, right, &expression.location), ExpressionType::Binary { left, right, operator: TokenType::Minus, } => self.value_math_operation(left, right, &expression.location, i64::sub, f32::sub), ExpressionType::Binary { left, right, operator: TokenType::Slash, } => self.div_expressions(left, right, &expression.location), ExpressionType::Binary { left, right, operator: TokenType::Star, } => self.value_math_operation(left, right, &expression.location, i64::mul, f32::mul), ExpressionType::Binary { left, right, operator: TokenType::Greater, } => self.value_comparison_operation( left, right, &expression.location, |f1, f2| f32::gt(&f1, &f2), ), ExpressionType::Binary { left, right, operator: TokenType::GreaterEqual, } => self.value_comparison_operation( left, right, &expression.location, |f1, f2| f32::ge(&f1, &f2), ), ExpressionType::Binary { left, right, operator: TokenType::Less, } => self.value_comparison_operation( left, right, &expression.location, |f1, f2| f32::lt(&f1, &f2), ), ExpressionType::Binary { left, right, operator: TokenType::LessEqual, } => self.value_comparison_operation( left, right, &expression.location, |f1, f2| f32::le(&f1, &f2), ), ExpressionType::Binary { left, right, operator: TokenType::EqualEqual, } => self.eq_expressions(left, right), ExpressionType::Binary { left, right, operator: TokenType::BangEqual, } => self.eq_expressions(left, right).map(|v| !v), ExpressionType::Binary { left, right, operator: TokenType::And, } => self.boolean_expression( left, right, |left_value, right_value| { if left_value.is_truthy() { right_value } else { left_value } }, ), ExpressionType::Binary { left, right, operator: TokenType::Or, } => self.boolean_expression( left, right, |left_value, right_value| { if left_value.is_truthy() { left_value } else { right_value } }, ), ExpressionType::Binary { .. } => { Err(expression.create_program_error("Invalid binary operator")) } ExpressionType::Conditional { condition, then_branch, else_branch, } => self.conditional_expression(condition, then_branch, else_branch), ExpressionType::VariableAssignment { expression: value, identifier, } => self.variable_assignment( identifier, expression.id(), value, &expression.location, ), ExpressionType::Call { callee, arguments } => { self.call_expression(callee, arguments) } ExpressionType::AnonymousFunction { arguments, body } => { let f = Value::Function(Rc::new(LoxFunction { arguments: arguments.to_vec(), body: body.iter().collect(), environments: self.state.borrow().get_environments(), location: expression.location.clone(), })); Ok(f) } } } pub(crate) fn evaluate( &'a self, statement: &'a Statement<'a>, ) -> EvaluationResult<'a> { match &statement.statement_type { StatementType::EOF => {}, StatementType::Module { name, statements } => { unsafe { self.modules.as_ptr().as_mut() }.unwrap().insert(*name, statements.clone()); self.process_module(name)?; }, StatementType::Import { name, } => { let statements = self.resolve_import(name, &statement.location)? .into_iter() .map(Box::new) .collect(); unsafe { self.modules.as_ptr().as_mut() }.unwrap().insert(*name, statements); self.process_module(name)?; } StatementType::If { condition, then, otherwise, } => { let cond_value = self.evaluate_expression(condition)?; if cond_value.is_truthy() { self.evaluate(then)?; } else if let Some(o) = otherwise { self.evaluate(o)?; } } StatementType::Expression { expression } => { self.evaluate_expression(expression)?; }, StatementType::Block { body } => { self.state.borrow_mut().push(); for st in body { self.evaluate(st)?; if self.state.borrow().broke_loop { break; } } self.state.borrow_mut().pop(); } StatementType::VariableDeclaration { expression, name } => { let v = if let Some(e) = expression { self.evaluate_expression(e)? } else { Value::Uninitialized }; self.state.borrow_mut().insert_top(name, v); } StatementType::PrintStatement { expression } => { let v = self.evaluate_expression(expression)?; println!("{}", v); } StatementType::TraitDeclaration { name, methods, static_methods, setters, getters, } => { self.state.borrow_mut().insert_top( name, Value::Trait(Rc::new(LoxTrait { name, methods: methods.clone(), static_methods: static_methods.clone(), setters: setters.clone(), getters: getters.clone(), })), ); } StatementType::TraitImplementation { class_name, getters, methods, setters, static_methods, trait_name, } => { if let Value::Class(class) = self.evaluate_expression(class_name)? { if let Value::Trait(t) = self.evaluate_expression(trait_name)? { if class.implements(t.name) { return Err(statement.create_program_error( format!("{} already implements {}", class.name, t.name).as_str(), )); } else { class.append_trait(t.name); } let methods = &methods.iter().map(|s| s.as_ref()).collect::<Vec<&_>>(); let static_methods = &static_methods .iter() .map(|s| s.as_ref()) .collect::<Vec<&_>>(); let getters = &getters.iter().map(|s| s.as_ref()).collect::<Vec<&_>>(); let setters = &setters.iter().map(|s| s.as_ref()).collect::<Vec<&_>>(); let envs = self.state.borrow().get_environments(); check_trait_methods(methods, &t.methods, &statement.location) .map_err(|ee| ee[0].clone())?; class.append_methods(methods, envs.clone()); check_trait_methods(static_methods, &t.static_methods, &statement.location) .map_err(|ee| ee[0].clone())?; class.append_static_methods(static_methods, envs.clone()); check_trait_methods(getters, &t.getters, &statement.location) .map_err(|ee| ee[0].clone())?; class.append_getters(getters, envs.clone()); check_trait_methods(setters, &t.setters, &statement.location) .map_err(|ee| ee[0].clone())?; class.append_setters(setters, envs.clone()); } else { return Err(class_name .create_program_error("You can implement traits only on classes")); } } else { return Err( class_name.create_program_error("You can implement traits only on classes") ); } } StatementType::ClassDeclaration { getters, properties, name, methods, setters, static_methods, superclass, } => { let superclass = if let Some(e) = superclass { let superclass = self.evaluate_expression(e)?; if let Value::Class(c) = superclass { Some(c) } else { return Err(statement.create_program_error("Superclass must be a class")); } } else { None }; let environments = self.state.borrow().get_environments(); self.state.borrow_mut().insert_top( name.to_owned(), Value::Class(Rc::new(LoxClass::new( name.to_owned(), &static_methods .iter() .map(|s| s.as_ref()) .collect::<Vec<&Statement>>(), &methods .iter() .map(|s| s.as_ref()) .collect::<Vec<&Statement>>(), &getters .iter() .map(|s| s.as_ref()) .collect::<Vec<&Statement>>(), &setters .iter() .map(|s| s.as_ref()) .collect::<Vec<&Statement>>(), superclass, environments, ))), ); } StatementType::FunctionDeclaration { name, arguments, body, .. } => { let environments = self.state.borrow().get_environments(); self.state.borrow_mut().insert( name, Value::Function(Rc::new(LoxFunction { arguments: arguments.clone(), body: body.into_iter().map(AsRef::as_ref).collect(), location: statement.location.clone(), environments, })), ); } StatementType::Return { value } if self.state.borrow().in_function => match value { None => {}, Some(e) => { let v = self.evaluate_expression(e)?; self.state.borrow_mut().add_return_value(v); } }, StatementType::Return { .. } => return Err(statement.create_program_error("Return outside function")), StatementType::While { condition, action } => { self.state.borrow_mut().loop_count += 1; while { let v = self.evaluate_expression(condition)?; self.state.borrow().loop_count > 0 && v.is_truthy() } { self.evaluate(action)?; if self.state.borrow().broke_loop { break; } } self.state.borrow_mut().loop_count -= 1; self.state.borrow_mut().broke_loop = false; } StatementType::Break if self.state.borrow().loop_count > 0 => { self.state.borrow_mut().broke_loop = true; } StatementType::Break => return Err(statement.create_program_error("Break outside loop")), }; Ok(Value::Nil) } fn get_module_content(&'a self, name: &'a str) -> &'a str { unsafe { self.module_contents.as_ptr().as_ref() }.unwrap().get(name).unwrap() } fn get_module_statements( &'a self, name: &'a str, ) -> &'a [Box<Statement<'a>>] { unsafe { self.modules.as_ptr().as_ref() }.unwrap().get(name).unwrap() } fn get_module_interpreter( &'a self, name: &'a str, ) -> &'a Box<Interpreter<'a>> { unsafe { self.module_interpreters.as_ptr().as_ref() }.unwrap().get(name).unwrap() } fn open_import( &'a self, name: &'a str, location: &SourceCodeLocation<'a>, ) -> Result<String, ProgramError<'a>> { for path in self.paths { let path = Path::new(path).join(format!("{}.sa", name)); if path.exists() { let mut buffer = String::new(); File::open(path).unwrap().read_to_string(&mut buffer).unwrap(); return Ok(buffer); } } Err(ProgramError { location: location.clone(), message: format!("Can't find file {}.sa", name), }) } fn resolve_import( &'a self, name: &'a str, location: &SourceCodeLocation<'a>, ) -> Result<Vec<Statement<'a>>, ProgramError<'a>> { if self.blacklist.borrow().contains(&name) { return Err(ProgramError { message: format!("Circular import of {}", name), location: location.clone(), }); } let content = self.open_import(name, location)?; unsafe { self.module_contents.as_ptr().as_mut() }.unwrap() .insert(name, content); let mut lexer = Lexer::new(self.get_module_content(name), name); lexer.parse() .and_then(|tt| { let parser = Parser::new(tt.into_iter().peekable()); parser.parse().map(|t| t.0) }) .map_err(|ee| ee[0].clone()) } fn process_module<'b>( &'a self, name: &'a str, ) -> Result<(), ProgramError<'a>> { let statements = self.get_module_statements(name); let mut interpreter = Interpreter::new(&self.paths, name); interpreter.locals = self.locals.clone(); interpreter.blacklist.borrow_mut().extend(&*self.blacklist.borrow()); unsafe { self.module_interpreters.as_ptr().as_mut() }.unwrap().insert(name, Box::new(interpreter)); for statement in statements { self.get_module_interpreter(name) .evaluate(statement)?; } self.state.borrow_mut().insert_top(name, Value::Module(name)); Ok(()) } fn variable_assignment( &'a self, name: &'a str, id: usize, expression: &'a Expression<'a>, location: &SourceCodeLocation<'a>, ) -> EvaluationResult<'a> { match self.locals.get(&id) { Some(env) => { let value = self.evaluate_expression(expression)?; self.state.borrow_mut().assign_at(*env, name, &value); Ok(value) } None => Err(ProgramError { location: location.clone(), message: format!("Variable `{}` not found!", name), }), } } fn call_expression( &'a self, callee: &'a Expression<'a>, arguments: &'a [Box<Expression<'a>>], ) -> EvaluationResult<'a> { let function_value = self.evaluate_expression(callee)?; match function_value { Value::Class(c) => { let instance = LoxObject::new(c); let mut values = vec![]; for e in arguments { let value = self.evaluate_expression(e)?; values.push(value); } instance.init(&values, &self, &callee.location)?; Ok(Value::Object(instance)) } Value::Function(f) if f.arguments.len() != arguments.len() => Err(callee .create_program_error( format!( "Wrong number of arguments! Expected: {} Got: {}", f.arguments.len(), arguments.len() ) .as_str(), )), Value::Method(f, _) if f.arguments.len() != arguments.len() + 1 => Err(callee .create_program_error( format!( "Wrong number of arguments in method! Expected: {} Got: {}", f.arguments.len(), arguments.len() ) .as_str(), )), Value::Method(f, this) => { let mut values = vec![Value::Object(this)]; for e in arguments { let value = self.evaluate_expression(e)?; values.push(value); } f.eval(&values, &self) } Value::Function(f) => { let mut values = vec![]; for e in arguments { let value = self.evaluate_expression(e)?; values.push(value); } f.eval(&values, &self) } _ => Err(callee.create_program_error("Only functions or classes can be called!")), } } fn conditional_expression( &'a self, condition: &'a Expression<'a>, then_branch: &'a Expression<'a>, else_branch: &'a Expression<'a>, ) -> EvaluationResult<'a> { let condition = self.evaluate_expression(condition)?; self.evaluate_expression( if condition.is_truthy() { then_branch } else { else_branch } ) } fn boolean_expression( &'a self, left: &'a Expression<'a>, right: &'a Expression<'a>, op: fn(Value<'a>, Value<'a>) -> Value<'a>, ) -> EvaluationResult<'a> { let left_value = self.evaluate_expression(left)?; let right_value = self.evaluate_expression(right)?; Ok(op(left_value, right_value)) } fn value_comparison_operation( &'a self, left: &'a Expression<'a>, right: &'a Expression<'a>, location: &SourceCodeLocation<'a>, op: fn(f32, f32) -> bool, ) -> EvaluationResult<'a> { let left_value = self.evaluate_expression(left)?; let right_value = self.evaluate_expression(right)?; comparison_operation(left_value, right_value, op) .map_err(|e| e.into_program_error(location)) } fn eq_expressions( &'a self, left: &'a Expression<'a>, right: &'a Expression<'a>, ) -> EvaluationResult<'a> { let left_value = self.evaluate_expression(left)?; let right_value = self.evaluate_expression(right)?; Ok(Value::Boolean { value: left_value == right_value, }) } fn value_math_operation( &'a self, left: &'a Expression<'a>, right: &'a Expression<'a>, location: &SourceCodeLocation<'a>, i64_op: fn(i64, i64) -> i64, f32_op: fn(f32, f32) -> f32, ) -> EvaluationResult<'a> { let left_value = self.evaluate_expression(left)?; let right_value = self.evaluate_expression(right)?; math_operation(left_value, right_value, i64_op, f32_op) .map_err(|e| e.into_program_error(location)) } fn div_expressions( &'a self, left: &'a Expression<'a>, right: &'a Expression<'a>, location: &SourceCodeLocation<'a>, ) -> EvaluationResult<'a> { let left_value = self.evaluate_expression(left)?; let right_value = self.evaluate_expression(right)?; match right_value { Value::Float { value } if value == 0f32 => { Err(right.create_program_error("Division by zero!")) } Value::Integer { value } if value == 0 => { Err(right.create_program_error("Division by zero!")) } _ => Ok(()), }?; math_operation(left_value, right_value, i64::div, f32::div) .map_err(|e| e.into_program_error(&location)) } fn add_expressions( &'a self, left: &'a Expression<'a>, right: &'a Expression<'a>, location: &SourceCodeLocation<'a>, ) -> EvaluationResult<'a> { let left_value = self.evaluate_expression(left)?; if left_value.is_number() { let right_value = self.evaluate_expression(right)?; math_operation(left_value, right_value, i64::add, f32::add) .map_err(|e| e.into_program_error(location)) } else { let left_string: String = left_value .try_into() .map_err(|e: ValueError| e.into_program_error(location))?; let right_value = self.evaluate_expression(right)?; let right_string: String = right_value .try_into() .map_err(|e: ValueError| e.into_program_error(location))?; Ok(Value::String { value: format!("{}{}", left_string, right_string), }) } } fn get_property( &'a self, callee: &'a Expression<'a>, property: &'a str, ) -> EvaluationResult<'a> { let object = self.evaluate_expression(callee)?; match object { Value::Object(instance) => { if let Some(v) = instance.get(property) { Ok(v) } else { if let Some(v) = instance.get_getter(property) { v.eval(&[Value::Object(instance)], &self) } else { Err(callee .create_program_error(format!("Undefined property {}.", property).as_str())) } } } Value::Class(c) => { if let Some(v) = c.static_instance.get(property) { Ok(v) } else { Err(callee .create_program_error(format!("Undefined property {}.", property).as_str())) } } _ => Err(callee.create_program_error("Only instances have properties")), } } fn set_property( &'a self, callee: &'a Expression<'a>, property: &'a str, value: &'a Expression<'a>, ) -> EvaluationResult<'a> { let object = self.evaluate_expression(callee)?; if let Value::Object(instance) = object { let value = self.evaluate_expression(value)?; if let Some(f) = instance.get_setter(property) { f.eval(&[Value::Object(instance), value], &self) } else { instance.set(property, value.clone()); Ok(value) } } else { Err(callee.create_program_error("Only instances have properties")) } } fn array_element_expression_set( &'a self, array: &'a Expression<'a>, index: &'a Expression<'a>, value: &'a Expression<'a>, ) -> EvaluationResult<'a> { self.array_element_operation( array, index, |array, index_value| { let value = self.evaluate_expression(value)?; array.borrow_mut().elements[index_value] = Box::new(value.clone()); Ok(value) } ) } fn array_element_expression( &'a self, array: &'a Expression<'a>, index: &'a Expression<'a>, ) -> EvaluationResult<'a> { self.array_element_operation( array, index, |array, index_value| { Ok(*array.borrow().elements[index_value].clone()) } ) } fn array_element_operation<I: Fn(Rc<RefCell<LoxArray<'a>>>, usize) -> EvaluationResult<'a>>( &'a self, array: &'a Expression<'a>, index: &'a Expression<'a>, op: I, ) -> EvaluationResult<'a> { let array_value = self.evaluate_expression(array)?; if let Value::Array(a) = array_value { let index_value = self.evaluate_expression(index)?; let index_value: i64 = i64::try_from(index_value).map_err(|e: ValueError| index.create_program_error( e.to_string().as_str(), ))?; if (index_value as usize) < a.borrow().capacity { op(a, index_value as usize) } else { Err(index.create_program_error( format!( "You can't access element {} in an array of {} elements", index_value, a.borrow().capacity ) .as_str(), )) } } else { Err(array.create_program_error("You can only index arrays")) } } fn look_up_variable( &'a self, expression_id: usize, name: &str, ) -> Option<Value<'a>> { if let Some(env) = self.locals.get(&expression_id) { self.state.borrow().get_at(name, *env) } else { self.state.borrow().get_global(name) } } fn is_value_type( &'a self, value: &Value<'a>, checked_type: &'a Type<'a>, location: &SourceCodeLocation<'a>, ) -> EvaluationResult<'a> { match (value, checked_type) { (Value::Nil, Type::Nil) => Ok(Value::Boolean { value: true }), (Value::Nil, _) => Ok(Value::Boolean { value: false }), (Value::Boolean { .. }, Type::Boolean) => Ok(Value::Boolean { value: true }), (Value::Boolean { .. }, _) => Ok(Value::Boolean { value: false }), (Value::Integer { .. }, Type::Integer) => Ok(Value::Boolean { value: true }), (Value::Integer { .. }, _) => Ok(Value::Boolean { value: false }), (Value::Float { .. }, Type::Float) => Ok(Value::Boolean { value: true }), (Value::Float { .. }, _) => Ok(Value::Boolean { value: false }), (Value::Module { .. }, Type::Module) => Ok(Value::Boolean { value: true }), (Value::Module { .. }, _) => Ok(Value::Boolean { value: false }), (Value::String { .. }, Type::String) => Ok(Value::Boolean { value: true }), (Value::String { .. }, _) => Ok(Value::Boolean { value: false }), (Value::Array { .. }, Type::Array) => Ok(Value::Boolean { value: true }), (Value::Array { .. }, _) => Ok(Value::Boolean { value: false }), (Value::Function(_), Type::Function) => Ok(Value::Boolean { value: true }), (Value::Function(_), _) => Ok(Value::Boolean { value: false }), (Value::Trait { .. }, Type::Trait) => Ok(Value::Boolean { value: true }), (Value::Trait { .. }, _) => Ok(Value::Boolean { value: false }), (Value::Class(_), Type::Class) => Ok(Value::Boolean { value: true }), (Value::Class(_), _) => Ok(Value::Boolean { value: false }), (Value::Object(obj), Type::UserDefined(c)) => { let v = self.evaluate_expression(c)?; match v { Value::Class(lox_class) => { Ok(Value::Boolean { value: is_class(&lox_class, obj) }) } Value::Trait(t) => { Ok(Value::Boolean { value: is_trait(&t.name, obj) }) } _ => Err(ProgramError { location: c.location.clone(), message: "Objects can only be either an implementation of a class or an object".to_owned(), }) } }, (Value::Object(_), _) => Ok(Value::Boolean { value: false }), _ => Err(ProgramError { location: location.clone(), message: "Invalid value to check for type".to_owned(), }) } } } #[cfg(test)] mod common_test { use parser::types::{ExpressionType, SourceCodeLocation, Expression, ExpressionFactory, Statement, StatementType, StatementFactory,}; pub fn create_expression<'a>( expression_type: ExpressionType<'a>, location: SourceCodeLocation<'a>, ) -> Expression<'a> { let mut factory = ExpressionFactory::new(); factory.new_expression(expression_type, location) } pub fn create_statement<'a>( statement_type: StatementType<'a>, location: SourceCodeLocation<'a>, ) -> Statement<'a> { let mut factory = StatementFactory::new(); factory.new_statement(location, statement_type) } pub fn get_variable<'a>(s: &'a str, location: &SourceCodeLocation<'a>) -> Expression<'a> { create_expression( ExpressionType::VariableLiteral { identifier: s, }, location.clone(), ) } } #[cfg(test)] mod test_statement { use crate::state::State; use crate::value::Value; use ahash::{AHashMap as HashMap}; use parser::types::{ Expression, ExpressionType, Literal, ProgramError, SourceCodeLocation, Statement, StatementType, TokenType, }; use super::common_test::{create_expression, get_variable}; use crate::interpreter::Interpreter; use std::cell::RefCell; use crate::interpreter::common_test::create_statement; #[test] fn test_if_statement() { let location = SourceCodeLocation { line: 1, file: "", }; let mut locals = HashMap::default(); locals.insert(0, 0); let mut interpreter = Interpreter::new(&[], ""); interpreter.locals = locals; let statement = create_statement( StatementType::If { condition: create_expression_number(1.0, &location), then: Box::new(create_variable_assignment_statement( "identifier", 1.0, &location, )), otherwise: Some(Box::new(create_variable_assignment_statement( "identifier", 0.0, &location, ))), }, location, ); let mut state = State::default(); state.insert("identifier", Value::Float { value: 2.0 }); interpreter.state = RefCell::new(state); interpreter.evaluate(&statement).unwrap(); assert_eq!(interpreter.state.borrow().find("identifier"), Some(Value::Float { value: 1.0 })); } #[test] fn test_if_statement_else() { let location = SourceCodeLocation { line: 1, file: "", }; let mut locals = HashMap::default(); locals.insert(0, 0); let mut interpreter = Interpreter::new(&[], ""); interpreter.locals = locals; let statement = create_statement( StatementType::If { condition: create_expression_number(0.0, &location), then: Box::new(create_variable_assignment_statement( "identifier", 1.0, &location, )), otherwise: Some(Box::new(create_variable_assignment_statement( "identifier", 0.0, &location, ))), }, location, ); let mut state = State::default(); state.insert("identifier", Value::Float { value: 2.0 }); interpreter.state = RefCell::new(state); interpreter.evaluate(&statement).unwrap(); assert_eq!(interpreter.state.borrow().find("identifier"), Some(Value::Float { value: 0.0 })); } #[test] fn test_expression_statement() { let location = SourceCodeLocation { line: 1, file: "", }; let mut locals = HashMap::default(); locals.insert(0, 0); let mut interpreter = Interpreter::new(&[], ""); interpreter.locals = locals; let statement = create_variable_assignment_statement("identifier", 0.0, &location); let mut state = State::default(); state.insert("identifier", Value::Float { value: 2.0 }); interpreter.state = RefCell::new(state); interpreter.evaluate(&statement).unwrap(); assert_eq!(interpreter.state.borrow().find("identifier"), Some(Value::Float { value: 0.0 })); } #[test] fn test_block_statement() { let location = SourceCodeLocation { line: 1, file: "", }; let mut locals = HashMap::default(); locals.insert(0, 0); let mut interpreter = Interpreter::new(&[], ""); interpreter.locals = locals; let statement = create_statement( StatementType::Block { body: vec![ Box::new(create_variable_assignment_statement( "identifier", 0.0, &location, )), Box::new(create_variable_assignment_statement( "identifier1", 1.0, &location, )), Box::new(create_variable_assignment_statement( "identifier2", 2.0, &location, )), ], }, location, ); let mut state = State::default(); state.insert("identifier", Value::Float { value: 2.0 }); state.insert("identifier1", Value::Float { value: 2.0 }); state.insert("identifier2", Value::Float { value: 0.0 }); interpreter.state = RefCell::new(state); interpreter.evaluate(&statement).unwrap(); assert_eq!(interpreter.state.borrow().find("identifier"), Some(Value::Float { value: 0.0 })); assert_eq!(interpreter.state.borrow().find("identifier1"), Some(Value::Float { value: 1.0 })); assert_eq!(interpreter.state.borrow().find("identifier2"), Some(Value::Float { value: 2.0 })); } #[test] fn test_variable_declaration() { let location = SourceCodeLocation { line: 1, file: "", }; let mut interpreter = Interpreter::new(&[], ""); let statement = create_statement( StatementType::VariableDeclaration { expression: Some(create_expression_number(1.0, &location)), name: "identifier", }, location, ); let state = State::default(); interpreter.state = RefCell::new(state); interpreter.evaluate(&statement).unwrap(); assert_eq!(interpreter.state.borrow().find("identifier"), Some(Value::Float { value: 1.0 })); } #[test] fn test_function_declaration() { let location = SourceCodeLocation { line: 1, file: "", }; let mut interpreter = Interpreter::new(&[], ""); let statement = create_statement( StatementType::FunctionDeclaration { name: "function", arguments: vec![], body: vec![Box::new(create_statement( StatementType::EOF, location.clone(), ))], context_variables: vec![], }, location.clone(), ); let state = State::default(); interpreter.state = RefCell::new(state); interpreter.evaluate(&statement).unwrap(); let value = interpreter.state.borrow().find("function").unwrap(); match value { Value::Function(lf ) => { assert_eq!(lf.arguments, Vec::<String>::new()); assert_eq!( lf.body, vec![&create_statement( StatementType::EOF, location.clone(), )] ); assert_eq!(lf.location, location); } _ => panic!("Wrong type! Should be Function!"), } } #[test] fn test_return_in_function() { let location = SourceCodeLocation { line: 1, file: "", }; let statement = create_statement( StatementType::Return { value: Some(create_expression_number(1.0, &location)), }, location, ); let mut interpreter = Interpreter::new(&[], ""); let mut state = State::default(); state.in_function = true; interpreter.state = RefCell::new(state); interpreter.evaluate(&statement).unwrap(); assert_eq!(interpreter.state.borrow().return_value, Some(Box::new(Value::Float { value: 1.0 }))); } #[test] fn test_return_outside_function() { let location = SourceCodeLocation { line: 1, file: "", }; let mut interpreter = Interpreter::new(&[], ""); let statement = create_statement( StatementType::Return { value: Some(create_expression_number(1.0, &location)), }, location.clone(), ); let state = State::default(); interpreter.state = RefCell::new(state); let r = interpreter.evaluate(&statement); assert_eq!( r, Err(ProgramError { message: "Return outside function".to_owned(), location, }) ); } #[test] fn test_break_in_function() { let location = SourceCodeLocation { line: 1, file: "", }; let statement = create_statement( StatementType::Break, location, ); let mut interpreter = Interpreter::new(&[], ""); let mut state = State::default(); state.loop_count = 1; interpreter.state = RefCell::new(state); interpreter.evaluate(&statement).unwrap(); assert!(interpreter.state.borrow().broke_loop); assert_eq!(interpreter.state.borrow().loop_count, 1); } #[test] fn test_break_outside_function() { let location = SourceCodeLocation { line: 1, file: "", }; let statement = create_statement( StatementType::Break, location.clone(), ); let interpreter = Interpreter::new(&[], ""); let r = interpreter.evaluate(&statement); assert_eq!( r, Err(ProgramError { message: "Break outside loop".to_owned(), location, }) ); } #[test] fn test_while_loop() { let location = SourceCodeLocation { line: 1, file: "", }; let identifier_expression = get_variable("identifier", &location); let mut locals = HashMap::default(); locals.insert(0, 0); let mut interpreter = Interpreter::new(&[], ""); interpreter.locals = locals; let statement = create_statement( StatementType::While { condition: create_expression( ExpressionType::Binary { operator: TokenType::Less, left: Box::new(identifier_expression.clone()), right: Box::new(create_expression_number(10f32, &location)), }, location.clone(), ), action: Box::new(create_statement( StatementType::Expression { expression: create_expression( ExpressionType::VariableAssignment { identifier: "identifier", expression: Box::new(create_expression( ExpressionType::Binary { operator: TokenType::Plus, left: Box::new(identifier_expression.clone()), right: Box::new(create_expression_number(1.0, &location)), }, location.clone(), )), }, location.clone(), ), }, location.clone(), )), }, location, ); let mut state = State::default(); state.insert("identifier", Value::Float { value: 0.0 }); interpreter.state = RefCell::new(state); interpreter.evaluate(&statement).unwrap(); assert_eq!(interpreter.state.borrow().find("identifier"), Some(Value::Float { value: 10.0 })); } fn create_variable_assignment_statement<'a>( id: &'a str, value: f32, location: &SourceCodeLocation<'a>, ) -> Statement<'a> { create_statement( StatementType::Expression { expression: create_expression( ExpressionType::VariableAssignment { identifier: id, expression: Box::new(create_expression_number(value, location)), }, location.clone(), ), }, location.clone(), ) } fn create_expression_number<'a>(value: f32, location: &SourceCodeLocation<'a>) -> Expression<'a> { create_expression( ExpressionType::ExpressionLiteral { value: Literal::Float(value), }, location.clone(), ) } } #[cfg(test)] mod test_expression { use ahash::{AHashMap as HashMap}; use crate::function::LoxFunction; use crate::interpreter::Interpreter; use crate::state::State; use crate::value::Value; use parser::types::{ DataKeyword, Expression, ExpressionType, Literal, SourceCodeLocation, Statement, StatementType, TokenType, }; use super::common_test::{create_expression, get_variable}; use std::rc::Rc; use std::cell::RefCell; use crate::interpreter::common_test::create_statement; #[test] fn test_expression_literal() { let location = SourceCodeLocation { line: 1, file: "", }; let interpreter = Interpreter::new(&[], ""); let e = get_number(1.0, &location); let got = interpreter.evaluate_expression(&e).unwrap(); assert_eq!(got, Value::Float { value: 1.0 }); } #[test] fn test_variable_literal() { let location = SourceCodeLocation { line: 1, file: "", }; let expression = get_variable("variable", &location); let mut state = State::default(); let mut interpreter = Interpreter::new(&[], ""); state.insert("variable", Value::Float { value: 1.0 }); interpreter.state = RefCell::new(state); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Float { value: 1.0 }); } #[test] fn test_group_expression() { let location = SourceCodeLocation { line: 1, file: "", }; let expression = create_expression( ExpressionType::Grouping { expression: Box::new(get_number(1.0, &location)), }, location, ); let state = State::default(); let mut interpreter = Interpreter::new(&[], ""); interpreter.state = RefCell::new(state); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Float { value: 1.0 }); } #[test] fn test_minus_operator() { let location = SourceCodeLocation { line: 1, file: "", }; let expression = create_expression( ExpressionType::Unary { operator: TokenType::Minus, operand: Box::new(get_number(1.0, &location)), }, location, ); let interpreter = Interpreter::new(&[], ""); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Float { value: -1.0 }); } #[test] fn test_bang_operator() { let location = SourceCodeLocation { line: 1, file: "", }; let expression = create_expression( ExpressionType::Unary { operator: TokenType::Bang, operand: Box::new(get_number(1.0, &location)), }, location, ); let interpreter = Interpreter::new(&[], ""); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Boolean { value: false }); } #[test] fn test_sum() { let location = SourceCodeLocation { line: 1, file: "", }; let interpreter = Interpreter::new(&[], ""); let expression = create_expression( ExpressionType::Binary { operator: TokenType::Plus, left: Box::new(get_number(1.0, &location)), right: Box::new(get_number(1.0, &location)), }, location, ); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Float { value: 2.0 }); } #[test] fn test_sum_strings() { let location = SourceCodeLocation { line: 1, file: "", }; let expression = create_expression( ExpressionType::Binary { operator: TokenType::Plus, left: Box::new(get_string("1", &location)), right: Box::new(get_string("2", &location)), }, location, ); let interpreter = Interpreter::new(&[], ""); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!( got, Value::String { value: "12".to_string() } ); } #[test] fn test_sub() { let location = SourceCodeLocation { line: 1, file: "", }; let expression = create_expression( ExpressionType::Binary { operator: TokenType::Minus, left: Box::new(get_number(1.0, &location)), right: Box::new(get_number(1.0, &location)), }, location, ); let interpreter = Interpreter::new(&[], ""); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Float { value: 0.0 }); } #[test] fn test_mult() { let location = SourceCodeLocation { line: 1, file: "", }; let interpreter = Interpreter::new(&[], ""); let expression = create_expression( ExpressionType::Binary { operator: TokenType::Star, left: Box::new(get_number(2.0, &location)), right: Box::new(get_number(1.0, &location)), }, location, ); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Float { value: 2.0 }); } #[test] fn test_div() { let location = SourceCodeLocation { line: 1, file: "", }; let interpreter = Interpreter::new(&[], ""); let expression = create_expression( ExpressionType::Binary { operator: TokenType::Slash, left: Box::new(get_number(2.0, &location)), right: Box::new(get_number(2.0, &location)), }, location, ); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Float { value: 1.0 }); } #[test] fn test_greater() { let location = SourceCodeLocation { line: 1, file: "", }; let interpreter = Interpreter::new(&[], ""); let expression = create_expression( ExpressionType::Binary { operator: TokenType::Greater, left: Box::new(get_number(3.0, &location)), right: Box::new(get_number(2.0, &location)), }, location, ); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Boolean { value: true }); } #[test] fn test_greater_equal() { let location = SourceCodeLocation { line: 1, file: "", }; let interpreter = Interpreter::new(&[], ""); let expression = create_expression( ExpressionType::Binary { operator: TokenType::GreaterEqual, left: Box::new(get_number(3.0, &location)), right: Box::new(get_number(3.0, &location)), }, location, ); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Boolean { value: true }); } #[test] fn test_greater_equal_with_greater() { let location = SourceCodeLocation { line: 1, file: "", }; let interpreter = Interpreter::new(&[], ""); let expression = create_expression( ExpressionType::Binary { operator: TokenType::GreaterEqual, left: Box::new(get_number(3.0, &location)), right: Box::new(get_number(2.0, &location)), }, location, ); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Boolean { value: true }); } #[test] fn test_less() { let location = SourceCodeLocation { line: 1, file: "", }; let interpreter = Interpreter::new(&[], ""); let expression = create_expression( ExpressionType::Binary { operator: TokenType::Less, left: Box::new(get_number(1.0, &location)), right: Box::new(get_number(2.0, &location)), }, location, ); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Boolean { value: true }); } #[test] fn test_less_equal() { let location = SourceCodeLocation { line: 1, file: "", }; let interpreter = Interpreter::new(&[], ""); let expression = create_expression( ExpressionType::Binary { operator: TokenType::LessEqual, left: Box::new(get_number(3.0, &location)), right: Box::new(get_number(3.0, &location)), }, location, ); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Boolean { value: true }); } #[test] fn test_less_equal_with_less() { let location = SourceCodeLocation { line: 1, file: "", }; let interpreter = Interpreter::new(&[], ""); let expression = create_expression( ExpressionType::Binary { operator: TokenType::LessEqual, left: Box::new(get_number(1.0, &location)), right: Box::new(get_number(2.0, &location)), }, location, ); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Boolean { value: true }); } #[test] fn test_equal() { let location = SourceCodeLocation { line: 1, file: "", }; let interpreter = Interpreter::new(&[], ""); let expression = create_expression( ExpressionType::Binary { operator: TokenType::EqualEqual, left: Box::new(get_number(2.0, &location)), right: Box::new(get_number(2.0, &location)), }, location, ); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Boolean { value: true }); } #[test] fn test_different() { let location = SourceCodeLocation { line: 1, file: "", }; let interpreter = Interpreter::new(&[], ""); let expression = create_expression( ExpressionType::Binary { operator: TokenType::BangEqual, left: Box::new(get_number(2.0, &location)), right: Box::new(get_number(1.0, &location)), }, location, ); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Boolean { value: true }); } #[test] fn test_and() { let location = SourceCodeLocation { line: 1, file: "", }; let interpreter = Interpreter::new(&[], ""); let expression = create_expression( ExpressionType::Binary { operator: TokenType::And, left: Box::new(get_boolean(true, &location)), right: Box::new(get_boolean(true, &location)), }, location, ); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Boolean { value: true }); } #[test] fn test_or() { let location = SourceCodeLocation { line: 1, file: "", }; let interpreter = Interpreter::new(&[], ""); let expression = create_expression( ExpressionType::Binary { operator: TokenType::Or, left: Box::new(get_boolean(true, &location)), right: Box::new(get_boolean(false, &location)), }, location, ); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Boolean { value: true }); } #[test] fn test_conditional() { let location = SourceCodeLocation { line: 1, file: "", }; let interpreter = Interpreter::new(&[], ""); let expression = create_expression( ExpressionType::Conditional { condition: Box::new(get_boolean(true, &location)), then_branch: Box::new(get_number(1.0, &location)), else_branch: Box::new(get_number(2.0, &location)), }, location, ); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Float { value: 1.0 }); } #[test] fn test_conditional_else_branch() { let location = SourceCodeLocation { line: 1, file: "", }; let interpreter = Interpreter::new(&[], ""); let expression = create_expression( ExpressionType::Conditional { condition: Box::new(get_boolean(false, &location)), then_branch: Box::new(get_number(1.0, &location)), else_branch: Box::new(get_number(2.0, &location)), }, location, ); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Float { value: 2.0 }); } #[test] fn test_variable_assignment() { let location = SourceCodeLocation { line: 1, file: "", }; let mut locals = HashMap::default(); locals.insert(0, 0); let mut interpreter = Interpreter::new(&[], ""); interpreter.locals = locals; let expression = create_expression( ExpressionType::VariableAssignment { identifier: "identifier", expression: Box::new(get_number(1.0, &location)), }, location, ); let mut state = State::default(); state.insert("identifier", Value::Float { value: 0.0 }); interpreter.state = RefCell::new(state); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Float { value: 1.0 }); } #[test] fn test_function_call() { let location = SourceCodeLocation { line: 1, file: "", }; let expression = create_expression( ExpressionType::Call { callee: Box::new(get_variable("function", &location)), arguments: vec![], }, location.clone(), ); let mut state = State::default(); let mut interpreter = Interpreter::new(&[], ""); let s = create_statement( StatementType::VariableDeclaration { expression: Some(get_number(1.0, &location)), name: "identifier", }, location.clone(), ); state.insert("identifier", Value::Float { value: 0.0 }); state.insert( "function", Value::Function(Rc::new(LoxFunction { arguments: vec![], environments: state.get_environments(), body: vec![&s], location, })), ); interpreter.state = RefCell::new(state); let got = interpreter.evaluate_expression(&expression).unwrap(); assert_eq!(got, Value::Nil); } fn get_string<'a>(s: &'a str, location: &SourceCodeLocation<'a>) -> Expression<'a> { create_expression( ExpressionType::ExpressionLiteral { value: Literal::QuotedString(s), }, location.clone(), ) } fn get_number<'a>(n: f32, location: &SourceCodeLocation<'a>) -> Expression<'a> { create_expression( ExpressionType::ExpressionLiteral { value: Literal::Float(n), }, location.clone(), ) } fn get_boolean<'a>(n: bool, location: &SourceCodeLocation<'a>) -> Expression<'a> { let keyword = if n { DataKeyword::True } else { DataKeyword::False }; create_expression( ExpressionType::ExpressionLiteral { value: Literal::Keyword(keyword), }, location.clone(), ) } }
#![deny(warnings)] pub mod led;
//! Account module types. use std::collections::BTreeMap; use num_traits::identities::Zero; use crate::types::{address::Address, token}; /// Transfer call. #[derive(Clone, Debug, cbor::Encode, cbor::Decode)] pub struct Transfer { pub to: Address, pub amount: token::BaseUnits, } /// Account metadata. #[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)] pub struct Account { #[cbor(optional)] #[cbor(default)] #[cbor(skip_serializing_if = "Zero::is_zero")] pub nonce: u64, } /// Arguments for the Nonce query. #[derive(Clone, Debug, cbor::Encode, cbor::Decode)] pub struct NonceQuery { pub address: Address, } /// Arguments for the Addresses query. #[derive(Clone, Debug, cbor::Encode, cbor::Decode)] pub struct AddressesQuery { pub denomination: token::Denomination, } /// Arguments for the Balances query. #[derive(Clone, Debug, cbor::Encode, cbor::Decode)] pub struct BalancesQuery { pub address: Address, } /// Balances in an account. #[derive(Clone, Debug, cbor::Encode, cbor::Decode)] pub struct AccountBalances { pub balances: BTreeMap<token::Denomination, u128>, }
use blake2::Blake2s as b2s; use digest::Digest; use super::PRF; use crate::CryptoError; #[derive(Clone)] pub struct Blake2s; impl PRF for Blake2s { type Input = [u8; 32]; type Output = [u8; 32]; type Seed = [u8; 32]; fn evaluate(seed: &Self::Seed, input: &Self::Input) -> Result<Self::Output, CryptoError> { let eval_time = start_timer!(|| "Blake2s::Eval"); let mut h = b2s::new(); h.input(seed.as_ref()); h.input(input.as_ref()); let mut result = [0u8; 32]; result.copy_from_slice(&h.result()); end_timer!(eval_time); Ok(result) } }
#[macro_export] macro_rules! debug { ($format: literal, $( $args:expr ), * ) => { if crate::CONFIG.debug { println!($format, $( $args ), *); } } }
use std::{ future::Future, marker::PhantomData, ops::{Deref, DerefMut}, pin::Pin, task::{Context, Poll}, time::Duration, }; pub use map::Map; use pin_project_lite::pin_project; pub use then::Then; pub use timeout::Timeout; use crate::actor::Actor; mod either; mod map; pub mod result; mod then; mod timeout; /// Trait for types which are a placeholder of a value that may become /// available at some later point in time. /// /// [`ActorFuture`] is very similar to a regular [`Future`], only with subsequent combinator closures accepting the actor and its context, in addition to the result. /// /// [`ActorFuture`] allows for use cases where future processing requires access to the actor or its context. /// /// Here is an example of a handler on a single actor, deferring work to another actor, and /// then updating the initiating actor's state: /// /// ```no_run /// use actix::prelude::*; /// /// // The response type returned by the actor future /// type OriginalActorResponse = (); /// // The error type returned by the actor future /// type MessageError = (); /// // This is the needed result for the DeferredWork message /// // It's a result that combine both Response and Error from the future response. /// type DeferredWorkResult = Result<OriginalActorResponse, MessageError>; /// # /// # struct ActorState {} /// # /// # impl ActorState { /// # fn update_from(&mut self, _result: ()) {} /// # } /// # /// # struct OtherActor {} /// # /// # impl Actor for OtherActor { /// # type Context = Context<Self>; /// # } /// # /// # impl Handler<OtherMessage> for OtherActor { /// # type Result = (); /// # /// # fn handle(&mut self, _msg: OtherMessage, _ctx: &mut Context<Self>) -> Self::Result { /// # } /// # } /// # /// # struct OriginalActor{ /// # other_actor: Addr<OtherActor>, /// # inner_state: ActorState /// # } /// # /// # impl Actor for OriginalActor{ /// # type Context = Context<Self>; /// # } /// # /// # #[derive(Message)] /// # #[rtype(result = "Result<(), MessageError>")] /// # struct DeferredWork{} /// # /// # #[derive(Message)] /// # #[rtype(result = "()")] /// # struct OtherMessage{} /// /// impl Handler<DeferredWork> for OriginalActor { /// // Notice the `Response` is an `ActorFuture`-ized version of `Self::Message::Result`. /// type Result = ResponseActFuture<Self, DeferredWorkResult>; /// /// fn handle(&mut self, _msg: DeferredWork, _ctx: &mut Context<Self>) -> Self::Result { /// // this creates a `Future` representing the `.send` and subsequent `Result` from /// // `other_actor` /// let send_to_other = self.other_actor /// .send(OtherMessage {}); /// /// // Wrap that `Future` so subsequent chained handlers can access /// // the `actor` (`self` in the synchronous code) as well as the context. /// let send_to_other = actix::fut::wrap_future::<_, Self>(send_to_other); /// /// // once the wrapped future resolves, update this actor's state /// let update_self = send_to_other.map(|result, actor, _ctx| { /// // Actor's state updated here /// match result { /// Ok(v) => { /// actor.inner_state.update_from(v); /// Ok(()) /// }, /// // Failed to send message to other_actor /// Err(_e) => Err(()), /// } /// }); /// /// // return the wrapped future /// Box::pin(update_self) /// } /// } /// /// ``` /// /// See also [`into_actor`](trait.WrapFuture.html#tymethod.into_actor), which provides future conversion using trait pub trait ActorFuture<A: Actor> { /// The type of value that this future will resolved with if it is /// successful. type Output; fn poll( self: Pin<&mut Self>, srv: &mut A, ctx: &mut A::Context, task: &mut Context<'_>, ) -> Poll<Self::Output>; } pub trait ActorFutureExt<A: Actor>: ActorFuture<A> { /// Map this future's result to a different type, returning a new future of /// the resulting type. fn map<F, U>(self, f: F) -> Map<Self, F> where F: FnOnce(Self::Output, &mut A, &mut A::Context) -> U, Self: Sized, { Map::new(self, f) } /// Chain on a computation for when a future finished, passing the result of /// the future to the provided closure `f`. fn then<F, Fut>(self, f: F) -> Then<Self, Fut, F> where F: FnOnce(Self::Output, &mut A, &mut A::Context) -> Fut, Fut: ActorFuture<A>, Self: Sized, { then::new(self, f) } /// Add timeout to futures chain. /// /// `Err(())` returned as a timeout error. fn timeout(self, timeout: Duration) -> Timeout<Self> where Self: Sized, { Timeout::new(self, timeout) } /// Wrap the future in a Box, pinning it. /// /// A shortcut for wrapping in [`Box::pin`]. fn boxed_local(self) -> LocalBoxActorFuture<A, Self::Output> where Self: Sized + 'static, { Box::pin(self) } } impl<F, A> ActorFutureExt<A> for F where F: ActorFuture<A>, A: Actor, { } /// Type alias for a pinned box [`ActorFuture`] trait object. pub type LocalBoxActorFuture<A, I> = Pin<Box<dyn ActorFuture<A, Output = I>>>; impl<F, A> ActorFuture<A> for Box<F> where F: ActorFuture<A> + Unpin + ?Sized, A: Actor, { type Output = F::Output; fn poll( mut self: Pin<&mut Self>, srv: &mut A, ctx: &mut A::Context, task: &mut Context<'_>, ) -> Poll<Self::Output> { Pin::new(&mut **self.as_mut()).poll(srv, ctx, task) } } impl<P, A> ActorFuture<A> for Pin<P> where P: Unpin + DerefMut, <P as Deref>::Target: ActorFuture<A>, A: Actor, { type Output = <<P as Deref>::Target as ActorFuture<A>>::Output; fn poll( self: Pin<&mut Self>, srv: &mut A, ctx: &mut A::Context, task: &mut Context<'_>, ) -> Poll<Self::Output> { Pin::get_mut(self).as_mut().poll(srv, ctx, task) } } /// Helper trait that allows conversion of normal future into [`ActorFuture`] pub trait WrapFuture<A> where A: Actor, { /// The future that this type can be converted into. type Future: ActorFuture<A>; #[deprecated(since = "0.11.0", note = "Please use WrapFuture::into_actor")] #[doc(hidden)] fn actfuture(self) -> Self::Future; /// Convert normal future to a [`ActorFuture`] fn into_actor(self, a: &A) -> Self::Future; } impl<F: Future, A: Actor> WrapFuture<A> for F { type Future = FutureWrap<F, A>; #[doc(hidden)] fn actfuture(self) -> Self::Future { wrap_future(self) } fn into_actor(self, _: &A) -> Self::Future { wrap_future(self) } } pin_project! { pub struct FutureWrap<F, A> where F: Future, A: Actor, { #[pin] fut: F, _act: PhantomData<A> } } /// Converts normal future into [`ActorFuture`], allowing its processing to /// use the actor's state. /// /// See the documentation for [`ActorFuture`] for a practical example involving both /// [`wrap_future`] and [`ActorFuture`] pub fn wrap_future<F, A>(f: F) -> FutureWrap<F, A> where F: Future, A: Actor, { FutureWrap { fut: f, _act: PhantomData, } } impl<F, A> ActorFuture<A> for FutureWrap<F, A> where F: Future, A: Actor, { type Output = F::Output; fn poll( self: Pin<&mut Self>, _: &mut A, _: &mut A::Context, task: &mut Context<'_>, ) -> Poll<Self::Output> { self.project().fut.poll(task) } }
use juniper::{GraphQLInputObject, GraphQLObject}; // if you need to pass this struct as parameter // in GraphQL mutations it needs to derive GraphQLInputObject #[derive(GraphQLObject, Debug, Clone)] #[graphql(description = "Todo List. Represents group of todo items with same goal.")] pub struct TodoList { pub id: i32, pub title: String, } #[derive(GraphQLInputObject, Debug)] #[graphql(description = "New todo list to be created.")] pub struct NewTodoList { pub title: String, } #[derive(GraphQLInputObject, Debug)] #[graphql(description = "Todo list to be updated.")] pub struct UpdateTodoList { pub id: i32, pub title: String, } #[derive(GraphQLObject, Debug, Clone)] #[graphql(description = "Todo Item. Represents single todo item belonging to specific todo list.")] pub struct TodoItem { pub id: i32, pub list_id: i32, pub title: String, pub checked: bool, } #[derive(GraphQLInputObject, Debug)] #[graphql(description = "New todo item to be created in specific todo list.")] pub struct NewTodoItem { pub list_id: i32, pub title: String, pub checked: bool, }
//***************************************************************************** // // The following are defines for the Univeral Serial Bus register offsets. // //***************************************************************************** pub const O_FADDR: uint = 0x00000000; // USB Device Functional Address pub const O_POWER: uint = 0x00000001; // USB Power pub const O_TXIS: uint = 0x00000002; // USB Transmit Interrupt Status pub const O_RXIS: uint = 0x00000004; // USB Receive Interrupt Status pub const O_TXIE: uint = 0x00000006; // USB Transmit Interrupt Enable pub const O_RXIE: uint = 0x00000008; // USB Receive Interrupt Enable pub const O_IS: uint = 0x0000000A; // USB General Interrupt Status pub const O_IE: uint = 0x0000000B; // USB Interrupt Enable pub const O_FRAME: uint = 0x0000000C; // USB Frame Value pub const O_EPIDX: uint = 0x0000000E; // USB Endpoint Index pub const O_TEST: uint = 0x0000000F; // USB Test Mode pub const O_FIFO0: uint = 0x00000020; // USB FIFO Endpoint 0 pub const O_FIFO1: uint = 0x00000024; // USB FIFO Endpoint 1 pub const O_FIFO2: uint = 0x00000028; // USB FIFO Endpoint 2 pub const O_FIFO3: uint = 0x0000002C; // USB FIFO Endpoint 3 pub const O_FIFO4: uint = 0x00000030; // USB FIFO Endpoint 4 pub const O_FIFO5: uint = 0x00000034; // USB FIFO Endpoint 5 pub const O_FIFO6: uint = 0x00000038; // USB FIFO Endpoint 6 pub const O_FIFO7: uint = 0x0000003C; // USB FIFO Endpoint 7 pub const O_DEVCTL: uint = 0x00000060; // USB Device Control pub const O_CCONF: uint = 0x00000061; // USB Common Configuration pub const O_TXFIFOSZ: uint = 0x00000062; // USB Transmit Dynamic FIFO Sizing pub const O_RXFIFOSZ: uint = 0x00000063; // USB Receive Dynamic FIFO Sizing pub const O_TXFIFOADD: uint = 0x00000064; // USB Transmit FIFO Start Address pub const O_RXFIFOADD: uint = 0x00000066; // USB Receive FIFO Start Address pub const O_ULPIVBUSCTL: uint = 0x00000070; // USB ULPI VBUS Control pub const O_ULPIREGDATA: uint = 0x00000074; // USB ULPI Register Data pub const O_ULPIREGADDR: uint = 0x00000075; // USB ULPI Register Address pub const O_ULPIREGCTL: uint = 0x00000076; // USB ULPI Register Control pub const O_EPINFO: uint = 0x00000078; // USB Endpoint Information pub const O_RAMINFO: uint = 0x00000079; // USB RAM Information pub const O_CONTIM: uint = 0x0000007A; // USB Connect Timing pub const O_VPLEN: uint = 0x0000007B; // USB OTG VBUS Pulse Timing pub const O_HSEOF: uint = 0x0000007C; // USB High-Speed Last Transaction // to End of Frame Timing pub const O_FSEOF: uint = 0x0000007D; // USB Full-Speed Last Transaction // to End of Frame Timing pub const O_LSEOF: uint = 0x0000007E; // USB Low-Speed Last Transaction // to End of Frame Timing pub const O_TXFUNCADDR0: uint = 0x00000080; // USB Transmit Functional Address // Endpoint 0 pub const O_TXHUBADDR0: uint = 0x00000082; // USB Transmit Hub Address // Endpoint 0 pub const O_TXHUBPORT0: uint = 0x00000083; // USB Transmit Hub Port Endpoint 0 pub const O_TXFUNCADDR1: uint = 0x00000088; // USB Transmit Functional Address // Endpoint 1 pub const O_TXHUBADDR1: uint = 0x0000008A; // USB Transmit Hub Address // Endpoint 1 pub const O_TXHUBPORT1: uint = 0x0000008B; // USB Transmit Hub Port Endpoint 1 pub const O_RXFUNCADDR1: uint = 0x0000008C; // USB Receive Functional Address // Endpoint 1 pub const O_RXHUBADDR1: uint = 0x0000008E; // USB Receive Hub Address Endpoint // 1 pub const O_RXHUBPORT1: uint = 0x0000008F; // USB Receive Hub Port Endpoint 1 pub const O_TXFUNCADDR2: uint = 0x00000090; // USB Transmit Functional Address // Endpoint 2 pub const O_TXHUBADDR2: uint = 0x00000092; // USB Transmit Hub Address // Endpoint 2 pub const O_TXHUBPORT2: uint = 0x00000093; // USB Transmit Hub Port Endpoint 2 pub const O_RXFUNCADDR2: uint = 0x00000094; // USB Receive Functional Address // Endpoint 2 pub const O_RXHUBADDR2: uint = 0x00000096; // USB Receive Hub Address Endpoint // 2 pub const O_RXHUBPORT2: uint = 0x00000097; // USB Receive Hub Port Endpoint 2 pub const O_TXFUNCADDR3: uint = 0x00000098; // USB Transmit Functional Address // Endpoint 3 pub const O_TXHUBADDR3: uint = 0x0000009A; // USB Transmit Hub Address // Endpoint 3 pub const O_TXHUBPORT3: uint = 0x0000009B; // USB Transmit Hub Port Endpoint 3 pub const O_RXFUNCADDR3: uint = 0x0000009C; // USB Receive Functional Address // Endpoint 3 pub const O_RXHUBADDR3: uint = 0x0000009E; // USB Receive Hub Address Endpoint // 3 pub const O_RXHUBPORT3: uint = 0x0000009F; // USB Receive Hub Port Endpoint 3 pub const O_TXFUNCADDR4: uint = 0x000000A0; // USB Transmit Functional Address // Endpoint 4 pub const O_TXHUBADDR4: uint = 0x000000A2; // USB Transmit Hub Address // Endpoint 4 pub const O_TXHUBPORT4: uint = 0x000000A3; // USB Transmit Hub Port Endpoint 4 pub const O_RXFUNCADDR4: uint = 0x000000A4; // USB Receive Functional Address // Endpoint 4 pub const O_RXHUBADDR4: uint = 0x000000A6; // USB Receive Hub Address Endpoint // 4 pub const O_RXHUBPORT4: uint = 0x000000A7; // USB Receive Hub Port Endpoint 4 pub const O_TXFUNCADDR5: uint = 0x000000A8; // USB Transmit Functional Address // Endpoint 5 pub const O_TXHUBADDR5: uint = 0x000000AA; // USB Transmit Hub Address // Endpoint 5 pub const O_TXHUBPORT5: uint = 0x000000AB; // USB Transmit Hub Port Endpoint 5 pub const O_RXFUNCADDR5: uint = 0x000000AC; // USB Receive Functional Address // Endpoint 5 pub const O_RXHUBADDR5: uint = 0x000000AE; // USB Receive Hub Address Endpoint // 5 pub const O_RXHUBPORT5: uint = 0x000000AF; // USB Receive Hub Port Endpoint 5 pub const O_TXFUNCADDR6: uint = 0x000000B0; // USB Transmit Functional Address // Endpoint 6 pub const O_TXHUBADDR6: uint = 0x000000B2; // USB Transmit Hub Address // Endpoint 6 pub const O_TXHUBPORT6: uint = 0x000000B3; // USB Transmit Hub Port Endpoint 6 pub const O_RXFUNCADDR6: uint = 0x000000B4; // USB Receive Functional Address // Endpoint 6 pub const O_RXHUBADDR6: uint = 0x000000B6; // USB Receive Hub Address Endpoint // 6 pub const O_RXHUBPORT6: uint = 0x000000B7; // USB Receive Hub Port Endpoint 6 pub const O_TXFUNCADDR7: uint = 0x000000B8; // USB Transmit Functional Address // Endpoint 7 pub const O_TXHUBADDR7: uint = 0x000000BA; // USB Transmit Hub Address // Endpoint 7 pub const O_TXHUBPORT7: uint = 0x000000BB; // USB Transmit Hub Port Endpoint 7 pub const O_RXFUNCADDR7: uint = 0x000000BC; // USB Receive Functional Address // Endpoint 7 pub const O_RXHUBADDR7: uint = 0x000000BE; // USB Receive Hub Address Endpoint // 7 pub const O_RXHUBPORT7: uint = 0x000000BF; // USB Receive Hub Port Endpoint 7 pub const O_CSRL0: uint = 0x00000102; // USB Control and Status Endpoint // 0 Low pub const O_CSRH0: uint = 0x00000103; // USB Control and Status Endpoint // 0 High pub const O_COUNT0: uint = 0x00000108; // USB Receive Byte Count Endpoint // 0 pub const O_TYPE0: uint = 0x0000010A; // USB Type Endpoint 0 pub const O_NAKLMT: uint = 0x0000010B; // USB NAK Limit pub const O_TXMAXP1: uint = 0x00000110; // USB Maximum Transmit Data // Endpoint 1 pub const O_TXCSRL1: uint = 0x00000112; // USB Transmit Control and Status // Endpoint 1 Low pub const O_TXCSRH1: uint = 0x00000113; // USB Transmit Control and Status // Endpoint 1 High pub const O_RXMAXP1: uint = 0x00000114; // USB Maximum Receive Data // Endpoint 1 pub const O_RXCSRL1: uint = 0x00000116; // USB Receive Control and Status // Endpoint 1 Low pub const O_RXCSRH1: uint = 0x00000117; // USB Receive Control and Status // Endpoint 1 High pub const O_RXCOUNT1: uint = 0x00000118; // USB Receive Byte Count Endpoint // 1 pub const O_TXTYPE1: uint = 0x0000011A; // USB Host Transmit Configure Type // Endpoint 1 pub const O_TXINTERVAL1: uint = 0x0000011B; // USB Host Transmit Interval // Endpoint 1 pub const O_RXTYPE1: uint = 0x0000011C; // USB Host Configure Receive Type // Endpoint 1 pub const O_RXINTERVAL1: uint = 0x0000011D; // USB Host Receive Polling // Interval Endpoint 1 pub const O_TXMAXP2: uint = 0x00000120; // USB Maximum Transmit Data // Endpoint 2 pub const O_TXCSRL2: uint = 0x00000122; // USB Transmit Control and Status // Endpoint 2 Low pub const O_TXCSRH2: uint = 0x00000123; // USB Transmit Control and Status // Endpoint 2 High pub const O_RXMAXP2: uint = 0x00000124; // USB Maximum Receive Data // Endpoint 2 pub const O_RXCSRL2: uint = 0x00000126; // USB Receive Control and Status // Endpoint 2 Low pub const O_RXCSRH2: uint = 0x00000127; // USB Receive Control and Status // Endpoint 2 High pub const O_RXCOUNT2: uint = 0x00000128; // USB Receive Byte Count Endpoint // 2 pub const O_TXTYPE2: uint = 0x0000012A; // USB Host Transmit Configure Type // Endpoint 2 pub const O_TXINTERVAL2: uint = 0x0000012B; // USB Host Transmit Interval // Endpoint 2 pub const O_RXTYPE2: uint = 0x0000012C; // USB Host Configure Receive Type // Endpoint 2 pub const O_RXINTERVAL2: uint = 0x0000012D; // USB Host Receive Polling // Interval Endpoint 2 pub const O_TXMAXP3: uint = 0x00000130; // USB Maximum Transmit Data // Endpoint 3 pub const O_TXCSRL3: uint = 0x00000132; // USB Transmit Control and Status // Endpoint 3 Low pub const O_TXCSRH3: uint = 0x00000133; // USB Transmit Control and Status // Endpoint 3 High pub const O_RXMAXP3: uint = 0x00000134; // USB Maximum Receive Data // Endpoint 3 pub const O_RXCSRL3: uint = 0x00000136; // USB Receive Control and Status // Endpoint 3 Low pub const O_RXCSRH3: uint = 0x00000137; // USB Receive Control and Status // Endpoint 3 High pub const O_RXCOUNT3: uint = 0x00000138; // USB Receive Byte Count Endpoint // 3 pub const O_TXTYPE3: uint = 0x0000013A; // USB Host Transmit Configure Type // Endpoint 3 pub const O_TXINTERVAL3: uint = 0x0000013B; // USB Host Transmit Interval // Endpoint 3 pub const O_RXTYPE3: uint = 0x0000013C; // USB Host Configure Receive Type // Endpoint 3 pub const O_RXINTERVAL3: uint = 0x0000013D; // USB Host Receive Polling // Interval Endpoint 3 pub const O_TXMAXP4: uint = 0x00000140; // USB Maximum Transmit Data // Endpoint 4 pub const O_TXCSRL4: uint = 0x00000142; // USB Transmit Control and Status // Endpoint 4 Low pub const O_TXCSRH4: uint = 0x00000143; // USB Transmit Control and Status // Endpoint 4 High pub const O_RXMAXP4: uint = 0x00000144; // USB Maximum Receive Data // Endpoint 4 pub const O_RXCSRL4: uint = 0x00000146; // USB Receive Control and Status // Endpoint 4 Low pub const O_RXCSRH4: uint = 0x00000147; // USB Receive Control and Status // Endpoint 4 High pub const O_RXCOUNT4: uint = 0x00000148; // USB Receive Byte Count Endpoint // 4 pub const O_TXTYPE4: uint = 0x0000014A; // USB Host Transmit Configure Type // Endpoint 4 pub const O_TXINTERVAL4: uint = 0x0000014B; // USB Host Transmit Interval // Endpoint 4 pub const O_RXTYPE4: uint = 0x0000014C; // USB Host Configure Receive Type // Endpoint 4 pub const O_RXINTERVAL4: uint = 0x0000014D; // USB Host Receive Polling // Interval Endpoint 4 pub const O_TXMAXP5: uint = 0x00000150; // USB Maximum Transmit Data // Endpoint 5 pub const O_TXCSRL5: uint = 0x00000152; // USB Transmit Control and Status // Endpoint 5 Low pub const O_TXCSRH5: uint = 0x00000153; // USB Transmit Control and Status // Endpoint 5 High pub const O_RXMAXP5: uint = 0x00000154; // USB Maximum Receive Data // Endpoint 5 pub const O_RXCSRL5: uint = 0x00000156; // USB Receive Control and Status // Endpoint 5 Low pub const O_RXCSRH5: uint = 0x00000157; // USB Receive Control and Status // Endpoint 5 High pub const O_RXCOUNT5: uint = 0x00000158; // USB Receive Byte Count Endpoint // 5 pub const O_TXTYPE5: uint = 0x0000015A; // USB Host Transmit Configure Type // Endpoint 5 pub const O_TXINTERVAL5: uint = 0x0000015B; // USB Host Transmit Interval // Endpoint 5 pub const O_RXTYPE5: uint = 0x0000015C; // USB Host Configure Receive Type // Endpoint 5 pub const O_RXINTERVAL5: uint = 0x0000015D; // USB Host Receive Polling // Interval Endpoint 5 pub const O_TXMAXP6: uint = 0x00000160; // USB Maximum Transmit Data // Endpoint 6 pub const O_TXCSRL6: uint = 0x00000162; // USB Transmit Control and Status // Endpoint 6 Low pub const O_TXCSRH6: uint = 0x00000163; // USB Transmit Control and Status // Endpoint 6 High pub const O_RXMAXP6: uint = 0x00000164; // USB Maximum Receive Data // Endpoint 6 pub const O_RXCSRL6: uint = 0x00000166; // USB Receive Control and Status // Endpoint 6 Low pub const O_RXCSRH6: uint = 0x00000167; // USB Receive Control and Status // Endpoint 6 High pub const O_RXCOUNT6: uint = 0x00000168; // USB Receive Byte Count Endpoint // 6 pub const O_TXTYPE6: uint = 0x0000016A; // USB Host Transmit Configure Type // Endpoint 6 pub const O_TXINTERVAL6: uint = 0x0000016B; // USB Host Transmit Interval // Endpoint 6 pub const O_RXTYPE6: uint = 0x0000016C; // USB Host Configure Receive Type // Endpoint 6 pub const O_RXINTERVAL6: uint = 0x0000016D; // USB Host Receive Polling // Interval Endpoint 6 pub const O_TXMAXP7: uint = 0x00000170; // USB Maximum Transmit Data // Endpoint 7 pub const O_TXCSRL7: uint = 0x00000172; // USB Transmit Control and Status // Endpoint 7 Low pub const O_TXCSRH7: uint = 0x00000173; // USB Transmit Control and Status // Endpoint 7 High pub const O_RXMAXP7: uint = 0x00000174; // USB Maximum Receive Data // Endpoint 7 pub const O_RXCSRL7: uint = 0x00000176; // USB Receive Control and Status // Endpoint 7 Low pub const O_RXCSRH7: uint = 0x00000177; // USB Receive Control and Status // Endpoint 7 High pub const O_RXCOUNT7: uint = 0x00000178; // USB Receive Byte Count Endpoint // 7 pub const O_TXTYPE7: uint = 0x0000017A; // USB Host Transmit Configure Type // Endpoint 7 pub const O_TXINTERVAL7: uint = 0x0000017B; // USB Host Transmit Interval // Endpoint 7 pub const O_RXTYPE7: uint = 0x0000017C; // USB Host Configure Receive Type // Endpoint 7 pub const O_RXINTERVAL7: uint = 0x0000017D; // USB Host Receive Polling // Interval Endpoint 7 pub const O_DMAINTR: uint = 0x00000200; // USB DMA Interrupt pub const O_DMACTL0: uint = 0x00000204; // USB DMA Control 0 pub const O_DMAADDR0: uint = 0x00000208; // USB DMA Address 0 pub const O_DMACOUNT0: uint = 0x0000020C; // USB DMA Count 0 pub const O_DMACTL1: uint = 0x00000214; // USB DMA Control 1 pub const O_DMAADDR1: uint = 0x00000218; // USB DMA Address 1 pub const O_DMACOUNT1: uint = 0x0000021C; // USB DMA Count 1 pub const O_DMACTL2: uint = 0x00000224; // USB DMA Control 2 pub const O_DMAADDR2: uint = 0x00000228; // USB DMA Address 2 pub const O_DMACOUNT2: uint = 0x0000022C; // USB DMA Count 2 pub const O_DMACTL3: uint = 0x00000234; // USB DMA Control 3 pub const O_DMAADDR3: uint = 0x00000238; // USB DMA Address 3 pub const O_DMACOUNT3: uint = 0x0000023C; // USB DMA Count 3 pub const O_DMACTL4: uint = 0x00000244; // USB DMA Control 4 pub const O_DMAADDR4: uint = 0x00000248; // USB DMA Address 4 pub const O_DMACOUNT4: uint = 0x0000024C; // USB DMA Count 4 pub const O_DMACTL5: uint = 0x00000254; // USB DMA Control 5 pub const O_DMAADDR5: uint = 0x00000258; // USB DMA Address 5 pub const O_DMACOUNT5: uint = 0x0000025C; // USB DMA Count 5 pub const O_DMACTL6: uint = 0x00000264; // USB DMA Control 6 pub const O_DMAADDR6: uint = 0x00000268; // USB DMA Address 6 pub const O_DMACOUNT6: uint = 0x0000026C; // USB DMA Count 6 pub const O_DMACTL7: uint = 0x00000274; // USB DMA Control 7 pub const O_DMAADDR7: uint = 0x00000278; // USB DMA Address 7 pub const O_DMACOUNT7: uint = 0x0000027C; // USB DMA Count 7 pub const O_RQPKTCOUNT1: uint = 0x00000304; // USB Request Packet Count in // Block Transfer Endpoint 1 pub const O_RQPKTCOUNT2: uint = 0x00000308; // USB Request Packet Count in // Block Transfer Endpoint 2 pub const O_RQPKTCOUNT3: uint = 0x0000030C; // USB Request Packet Count in // Block Transfer Endpoint 3 pub const O_RQPKTCOUNT4: uint = 0x00000310; // USB Request Packet Count in // Block Transfer Endpoint 4 pub const O_RQPKTCOUNT5: uint = 0x00000314; // USB Request Packet Count in // Block Transfer Endpoint 5 pub const O_RQPKTCOUNT6: uint = 0x00000318; // USB Request Packet Count in // Block Transfer Endpoint 6 pub const O_RQPKTCOUNT7: uint = 0x0000031C; // USB Request Packet Count in // Block Transfer Endpoint 7 pub const O_RXDPKTBUFDIS: uint = 0x00000340; // USB Receive Double Packet Buffer // Disable pub const O_TXDPKTBUFDIS: uint = 0x00000342; // USB Transmit Double Packet // Buffer Disable pub const O_CTO: uint = 0x00000344; // USB Chirp Timeout pub const O_HHSRTN: uint = 0x00000346; // USB High Speed to UTM Operating // Delay pub const O_HSBT: uint = 0x00000348; // USB High Speed Time-out Adder pub const O_LPMATTR: uint = 0x00000360; // USB LPM Attributes pub const O_LPMCNTRL: uint = 0x00000362; // USB LPM Control pub const O_LPMIM: uint = 0x00000363; // USB LPM Interrupt Mask pub const O_LPMRIS: uint = 0x00000364; // USB LPM Raw Interrupt Status pub const O_LPMFADDR: uint = 0x00000365; // USB LPM Function Address pub const O_EPC: uint = 0x00000400; // USB External Power Control pub const O_EPCRIS: uint = 0x00000404; // USB External Power Control Raw // Interrupt Status pub const O_EPCIM: uint = 0x00000408; // USB External Power Control // Interrupt Mask pub const O_EPCISC: uint = 0x0000040C; // USB External Power Control // Interrupt Status and Clear pub const O_DRRIS: uint = 0x00000410; // USB Device RESUME Raw Interrupt // Status pub const O_DRIM: uint = 0x00000414; // USB Device RESUME Interrupt Mask pub const O_DRISC: uint = 0x00000418; // USB Device RESUME Interrupt // Status and Clear pub const O_GPCS: uint = 0x0000041C; // USB General-Purpose Control and // Status pub const O_VDC: uint = 0x00000430; // USB VBUS Droop Control pub const O_VDCRIS: uint = 0x00000434; // USB VBUS Droop Control Raw // Interrupt Status pub const O_VDCIM: uint = 0x00000438; // USB VBUS Droop Control Interrupt // Mask pub const O_VDCISC: uint = 0x0000043C; // USB VBUS Droop Control Interrupt // Status and Clear pub const O_IDVRIS: uint = 0x00000444; // USB ID Valid Detect Raw // Interrupt Status pub const O_IDVIM: uint = 0x00000448; // USB ID Valid Detect Interrupt // Mask pub const O_IDVISC: uint = 0x0000044C; // USB ID Valid Detect Interrupt // Status and Clear pub const O_DMASEL: uint = 0x00000450; // USB DMA Select pub const O_PP: uint = 0x00000FC0; // USB Peripheral Properties pub const O_PC: uint = 0x00000FC4; // USB Peripheral Configuration pub const O_CC: uint = 0x00000FC8; // USB Clock Configuration //***************************************************************************** // // The following are defines for the bit fields in the USB_O_FADDR register. // //***************************************************************************** pub const FADDR_M: u32 = 0x0000007F; // Function Address pub const FADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_POWER register. // //***************************************************************************** pub const POWER_ISOUP: u32 = 0x00000080; // Isochronous Update pub const POWER_SOFTCONN: u32 = 0x00000040; // Soft Connect/Disconnect pub const POWER_HSENAB: u32 = 0x00000020; // High Speed Enable pub const POWER_HSMODE: u32 = 0x00000010; // High Speed Enable pub const POWER_RESET: u32 = 0x00000008; // RESET Signaling pub const POWER_RESUME: u32 = 0x00000004; // RESUME Signaling pub const POWER_SUSPEND: u32 = 0x00000002; // SUSPEND Mode pub const POWER_PWRDNPHY: u32 = 0x00000001; // Power Down PHY //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXIS register. // //***************************************************************************** pub const TXIS_EP7: u32 = 0x00000080; // TX Endpoint 7 Interrupt pub const TXIS_EP6: u32 = 0x00000040; // TX Endpoint 6 Interrupt pub const TXIS_EP5: u32 = 0x00000020; // TX Endpoint 5 Interrupt pub const TXIS_EP4: u32 = 0x00000010; // TX Endpoint 4 Interrupt pub const TXIS_EP3: u32 = 0x00000008; // TX Endpoint 3 Interrupt pub const TXIS_EP2: u32 = 0x00000004; // TX Endpoint 2 Interrupt pub const TXIS_EP1: u32 = 0x00000002; // TX Endpoint 1 Interrupt pub const TXIS_EP0: u32 = 0x00000001; // TX and RX Endpoint 0 Interrupt //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXIS register. // //***************************************************************************** pub const RXIS_EP7: u32 = 0x00000080; // RX Endpoint 7 Interrupt pub const RXIS_EP6: u32 = 0x00000040; // RX Endpoint 6 Interrupt pub const RXIS_EP5: u32 = 0x00000020; // RX Endpoint 5 Interrupt pub const RXIS_EP4: u32 = 0x00000010; // RX Endpoint 4 Interrupt pub const RXIS_EP3: u32 = 0x00000008; // RX Endpoint 3 Interrupt pub const RXIS_EP2: u32 = 0x00000004; // RX Endpoint 2 Interrupt pub const RXIS_EP1: u32 = 0x00000002; // RX Endpoint 1 Interrupt //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXIE register. // //***************************************************************************** pub const TXIE_EP7: u32 = 0x00000080; // TX Endpoint 7 Interrupt Enable pub const TXIE_EP6: u32 = 0x00000040; // TX Endpoint 6 Interrupt Enable pub const TXIE_EP5: u32 = 0x00000020; // TX Endpoint 5 Interrupt Enable pub const TXIE_EP4: u32 = 0x00000010; // TX Endpoint 4 Interrupt Enable pub const TXIE_EP3: u32 = 0x00000008; // TX Endpoint 3 Interrupt Enable pub const TXIE_EP2: u32 = 0x00000004; // TX Endpoint 2 Interrupt Enable pub const TXIE_EP1: u32 = 0x00000002; // TX Endpoint 1 Interrupt Enable pub const TXIE_EP0: u32 = 0x00000001; // TX and RX Endpoint 0 Interrupt // Enable //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXIE register. // //***************************************************************************** pub const RXIE_EP7: u32 = 0x00000080; // RX Endpoint 7 Interrupt Enable pub const RXIE_EP6: u32 = 0x00000040; // RX Endpoint 6 Interrupt Enable pub const RXIE_EP5: u32 = 0x00000020; // RX Endpoint 5 Interrupt Enable pub const RXIE_EP4: u32 = 0x00000010; // RX Endpoint 4 Interrupt Enable pub const RXIE_EP3: u32 = 0x00000008; // RX Endpoint 3 Interrupt Enable pub const RXIE_EP2: u32 = 0x00000004; // RX Endpoint 2 Interrupt Enable pub const RXIE_EP1: u32 = 0x00000002; // RX Endpoint 1 Interrupt Enable //***************************************************************************** // // The following are defines for the bit fields in the USB_O_IS register. // //***************************************************************************** pub const IS_VBUSERR: u32 = 0x00000080; // VBUS Error (OTG only) pub const IS_SESREQ: u32 = 0x00000040; // SESSION REQUEST (OTG only) pub const IS_DISCON: u32 = 0x00000020; // Session Disconnect (OTG only) pub const IS_CONN: u32 = 0x00000010; // Session Connect pub const IS_SOF: u32 = 0x00000008; // Start of Frame pub const IS_BABBLE: u32 = 0x00000004; // Babble Detected pub const IS_RESET: u32 = 0x00000004; // RESET Signaling Detected pub const IS_RESUME: u32 = 0x00000002; // RESUME Signaling Detected pub const IS_SUSPEND: u32 = 0x00000001; // SUSPEND Signaling Detected //***************************************************************************** // // The following are defines for the bit fields in the USB_O_IE register. // //***************************************************************************** pub const IE_VBUSERR: u32 = 0x00000080; // Enable VBUS Error Interrupt (OTG // only) pub const IE_SESREQ: u32 = 0x00000040; // Enable Session Request (OTG // only) pub const IE_DISCON: u32 = 0x00000020; // Enable Disconnect Interrupt pub const IE_CONN: u32 = 0x00000010; // Enable Connect Interrupt pub const IE_SOF: u32 = 0x00000008; // Enable Start-of-Frame Interrupt pub const IE_BABBLE: u32 = 0x00000004; // Enable Babble Interrupt pub const IE_RESET: u32 = 0x00000004; // Enable RESET Interrupt pub const IE_RESUME: u32 = 0x00000002; // Enable RESUME Interrupt pub const IE_SUSPND: u32 = 0x00000001; // Enable SUSPEND Interrupt //***************************************************************************** // // The following are defines for the bit fields in the USB_O_FRAME register. // //***************************************************************************** pub const FRAME_M: u32 = 0x000007FF; // Frame Number pub const FRAME_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_EPIDX register. // //***************************************************************************** pub const EPIDX_EPIDX_M: u32 = 0x0000000F; // Endpoint Index pub const EPIDX_EPIDX_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TEST register. // //***************************************************************************** pub const TEST_FORCEH: u32 = 0x00000080; // Force Host Mode pub const TEST_FIFOACC: u32 = 0x00000040; // FIFO Access pub const TEST_FORCEFS: u32 = 0x00000020; // Force Full-Speed Mode pub const TEST_FORCEHS: u32 = 0x00000010; // Force High-Speed Mode pub const TEST_TESTPKT: u32 = 0x00000008; // Test Packet Mode Enable pub const TEST_TESTK: u32 = 0x00000004; // Test_K Mode Enable pub const TEST_TESTJ: u32 = 0x00000002; // Test_J Mode Enable pub const TEST_TESTSE0NAK: u32 = 0x00000001; // Test_SE0_NAK Test Mode Enable //***************************************************************************** // // The following are defines for the bit fields in the USB_O_FIFO0 register. // //***************************************************************************** pub const FIFO0_EPDATA_M: u32 = 0xFFFFFFFF; // Endpoint Data pub const FIFO0_EPDATA_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_FIFO1 register. // //***************************************************************************** pub const FIFO1_EPDATA_M: u32 = 0xFFFFFFFF; // Endpoint Data pub const FIFO1_EPDATA_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_FIFO2 register. // //***************************************************************************** pub const FIFO2_EPDATA_M: u32 = 0xFFFFFFFF; // Endpoint Data pub const FIFO2_EPDATA_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_FIFO3 register. // //***************************************************************************** pub const FIFO3_EPDATA_M: u32 = 0xFFFFFFFF; // Endpoint Data pub const FIFO3_EPDATA_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_FIFO4 register. // //***************************************************************************** pub const FIFO4_EPDATA_M: u32 = 0xFFFFFFFF; // Endpoint Data pub const FIFO4_EPDATA_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_FIFO5 register. // //***************************************************************************** pub const FIFO5_EPDATA_M: u32 = 0xFFFFFFFF; // Endpoint Data pub const FIFO5_EPDATA_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_FIFO6 register. // //***************************************************************************** pub const FIFO6_EPDATA_M: u32 = 0xFFFFFFFF; // Endpoint Data pub const FIFO6_EPDATA_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_FIFO7 register. // //***************************************************************************** pub const FIFO7_EPDATA_M: u32 = 0xFFFFFFFF; // Endpoint Data pub const FIFO7_EPDATA_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DEVCTL register. // //***************************************************************************** pub const DEVCTL_DEV: u32 = 0x00000080; // Device Mode (OTG only) pub const DEVCTL_FSDEV: u32 = 0x00000040; // Full-Speed Device Detected pub const DEVCTL_LSDEV: u32 = 0x00000020; // Low-Speed Device Detected pub const DEVCTL_VBUS_M: u32 = 0x00000018; // VBUS Level (OTG only) pub const DEVCTL_VBUS_NONE: u32 = 0x00000000; // Below SessionEnd pub const DEVCTL_VBUS_SEND: u32 = 0x00000008; // Above SessionEnd, below AValid pub const DEVCTL_VBUS_AVALID: u32 = 0x00000010; // Above AValid, below VBUSValid pub const DEVCTL_VBUS_VALID: u32 = 0x00000018; // Above VBUSValid pub const DEVCTL_HOST: u32 = 0x00000004; // Host Mode pub const DEVCTL_HOSTREQ: u32 = 0x00000002; // Host Request (OTG only) pub const DEVCTL_SESSION: u32 = 0x00000001; // Session Start/End (OTG only) //***************************************************************************** // // The following are defines for the bit fields in the USB_O_CCONF register. // //***************************************************************************** pub const CCONF_TXEDMA: u32 = 0x00000002; // TX Early DMA Enable pub const CCONF_RXEDMA: u32 = 0x00000001; // TX Early DMA Enable //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXFIFOSZ register. // //***************************************************************************** pub const TXFIFOSZ_DPB: u32 = 0x00000010; // Double Packet Buffer Support pub const TXFIFOSZ_SIZE_M: u32 = 0x0000000F; // Max Packet Size pub const TXFIFOSZ_SIZE_8: u32 = 0x00000000; // 8 pub const TXFIFOSZ_SIZE_16: u32 = 0x00000001; // 16 pub const TXFIFOSZ_SIZE_32: u32 = 0x00000002; // 32 pub const TXFIFOSZ_SIZE_64: u32 = 0x00000003; // 64 pub const TXFIFOSZ_SIZE_128: u32 = 0x00000004; // 128 pub const TXFIFOSZ_SIZE_256: u32 = 0x00000005; // 256 pub const TXFIFOSZ_SIZE_512: u32 = 0x00000006; // 512 pub const TXFIFOSZ_SIZE_1024: u32 = 0x00000007; // 1024 pub const TXFIFOSZ_SIZE_2048: u32 = 0x00000008; // 2048 //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXFIFOSZ register. // //***************************************************************************** pub const RXFIFOSZ_DPB: u32 = 0x00000010; // Double Packet Buffer Support pub const RXFIFOSZ_SIZE_M: u32 = 0x0000000F; // Max Packet Size pub const RXFIFOSZ_SIZE_8: u32 = 0x00000000; // 8 pub const RXFIFOSZ_SIZE_16: u32 = 0x00000001; // 16 pub const RXFIFOSZ_SIZE_32: u32 = 0x00000002; // 32 pub const RXFIFOSZ_SIZE_64: u32 = 0x00000003; // 64 pub const RXFIFOSZ_SIZE_128: u32 = 0x00000004; // 128 pub const RXFIFOSZ_SIZE_256: u32 = 0x00000005; // 256 pub const RXFIFOSZ_SIZE_512: u32 = 0x00000006; // 512 pub const RXFIFOSZ_SIZE_1024: u32 = 0x00000007; // 1024 pub const RXFIFOSZ_SIZE_2048: u32 = 0x00000008; // 2048 //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXFIFOADD // register. // //***************************************************************************** pub const TXFIFOADD_ADDR_M: u32 = 0x000001FF; // Transmit/Receive Start Address pub const TXFIFOADD_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXFIFOADD // register. // //***************************************************************************** pub const RXFIFOADD_ADDR_M: u32 = 0x000001FF; // Transmit/Receive Start Address pub const RXFIFOADD_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_ULPIVBUSCTL // register. // //***************************************************************************** pub const ULPIVBUSCTL_USEEXTVBUSIND: u32 = 0x00000002; // Use External VBUS Indicator pub const ULPIVBUSCTL_USEEXTVBUS: u32 = 0x00000001; // Use External VBUS //***************************************************************************** // // The following are defines for the bit fields in the USB_O_ULPIREGDATA // register. // //***************************************************************************** pub const ULPIREGDATA_REGDATA_M: u32 = 0x000000FF; // Register Data pub const ULPIREGDATA_REGDATA_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_ULPIREGADDR // register. // //***************************************************************************** pub const ULPIREGADDR_ADDR_M: u32 = 0x000000FF; // Register Address pub const ULPIREGADDR_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_ULPIREGCTL // register. // //***************************************************************************** pub const ULPIREGCTL_RDWR: u32 = 0x00000004; // Read/Write Control pub const ULPIREGCTL_REGCMPLT: u32 = 0x00000002; // Register Access Complete pub const ULPIREGCTL_REGACC: u32 = 0x00000001; // Initiate Register Access //***************************************************************************** // // The following are defines for the bit fields in the USB_O_EPINFO register. // //***************************************************************************** pub const EPINFO_RXEP_M: u32 = 0x000000F0; // RX Endpoints pub const EPINFO_TXEP_M: u32 = 0x0000000F; // TX Endpoints pub const EPINFO_RXEP_S: uint = 4; pub const EPINFO_TXEP_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RAMINFO register. // //***************************************************************************** pub const RAMINFO_DMACHAN_M: u32 = 0x000000F0; // DMA Channels pub const RAMINFO_RAMBITS_M: u32 = 0x0000000F; // RAM Address Bus Width pub const RAMINFO_DMACHAN_S: uint = 4; pub const RAMINFO_RAMBITS_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_CONTIM register. // //***************************************************************************** pub const CONTIM_WTCON_M: u32 = 0x000000F0; // Connect Wait pub const CONTIM_WTID_M: u32 = 0x0000000F; // Wait ID pub const CONTIM_WTCON_S: uint = 4; pub const CONTIM_WTID_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_VPLEN register. // //***************************************************************************** pub const VPLEN_VPLEN_M: u32 = 0x000000FF; // VBUS Pulse Length pub const VPLEN_VPLEN_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_HSEOF register. // //***************************************************************************** pub const HSEOF_HSEOFG_M: u32 = 0x000000FF; // HIgh-Speed End-of-Frame Gap pub const HSEOF_HSEOFG_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_FSEOF register. // //***************************************************************************** pub const FSEOF_FSEOFG_M: u32 = 0x000000FF; // Full-Speed End-of-Frame Gap pub const FSEOF_FSEOFG_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_LSEOF register. // //***************************************************************************** pub const LSEOF_LSEOFG_M: u32 = 0x000000FF; // Low-Speed End-of-Frame Gap pub const LSEOF_LSEOFG_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXFUNCADDR0 // register. // //***************************************************************************** pub const TXFUNCADDR0_ADDR_M: u32 = 0x0000007F; // Device Address pub const TXFUNCADDR0_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXHUBADDR0 // register. // //***************************************************************************** pub const TXHUBADDR0_ADDR_M: u32 = 0x0000007F; // Hub Address pub const TXHUBADDR0_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXHUBPORT0 // register. // //***************************************************************************** pub const TXHUBPORT0_PORT_M: u32 = 0x0000007F; // Hub Port pub const TXHUBPORT0_PORT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXFUNCADDR1 // register. // //***************************************************************************** pub const TXFUNCADDR1_ADDR_M: u32 = 0x0000007F; // Device Address pub const TXFUNCADDR1_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXHUBADDR1 // register. // //***************************************************************************** pub const TXHUBADDR1_ADDR_M: u32 = 0x0000007F; // Hub Address pub const TXHUBADDR1_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXHUBPORT1 // register. // //***************************************************************************** pub const TXHUBPORT1_PORT_M: u32 = 0x0000007F; // Hub Port pub const TXHUBPORT1_PORT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXFUNCADDR1 // register. // //***************************************************************************** pub const RXFUNCADDR1_ADDR_M: u32 = 0x0000007F; // Device Address pub const RXFUNCADDR1_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXHUBADDR1 // register. // //***************************************************************************** pub const RXHUBADDR1_ADDR_M: u32 = 0x0000007F; // Hub Address pub const RXHUBADDR1_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXHUBPORT1 // register. // //***************************************************************************** pub const RXHUBPORT1_PORT_M: u32 = 0x0000007F; // Hub Port pub const RXHUBPORT1_PORT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXFUNCADDR2 // register. // //***************************************************************************** pub const TXFUNCADDR2_ADDR_M: u32 = 0x0000007F; // Device Address pub const TXFUNCADDR2_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXHUBADDR2 // register. // //***************************************************************************** pub const TXHUBADDR2_ADDR_M: u32 = 0x0000007F; // Hub Address pub const TXHUBADDR2_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXHUBPORT2 // register. // //***************************************************************************** pub const TXHUBPORT2_PORT_M: u32 = 0x0000007F; // Hub Port pub const TXHUBPORT2_PORT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXFUNCADDR2 // register. // //***************************************************************************** pub const RXFUNCADDR2_ADDR_M: u32 = 0x0000007F; // Device Address pub const RXFUNCADDR2_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXHUBADDR2 // register. // //***************************************************************************** pub const RXHUBADDR2_ADDR_M: u32 = 0x0000007F; // Hub Address pub const RXHUBADDR2_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXHUBPORT2 // register. // //***************************************************************************** pub const RXHUBPORT2_PORT_M: u32 = 0x0000007F; // Hub Port pub const RXHUBPORT2_PORT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXFUNCADDR3 // register. // //***************************************************************************** pub const TXFUNCADDR3_ADDR_M: u32 = 0x0000007F; // Device Address pub const TXFUNCADDR3_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXHUBADDR3 // register. // //***************************************************************************** pub const TXHUBADDR3_ADDR_M: u32 = 0x0000007F; // Hub Address pub const TXHUBADDR3_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXHUBPORT3 // register. // //***************************************************************************** pub const TXHUBPORT3_PORT_M: u32 = 0x0000007F; // Hub Port pub const TXHUBPORT3_PORT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXFUNCADDR3 // register. // //***************************************************************************** pub const RXFUNCADDR3_ADDR_M: u32 = 0x0000007F; // Device Address pub const RXFUNCADDR3_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXHUBADDR3 // register. // //***************************************************************************** pub const RXHUBADDR3_ADDR_M: u32 = 0x0000007F; // Hub Address pub const RXHUBADDR3_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXHUBPORT3 // register. // //***************************************************************************** pub const RXHUBPORT3_PORT_M: u32 = 0x0000007F; // Hub Port pub const RXHUBPORT3_PORT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXFUNCADDR4 // register. // //***************************************************************************** pub const TXFUNCADDR4_ADDR_M: u32 = 0x0000007F; // Device Address pub const TXFUNCADDR4_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXHUBADDR4 // register. // //***************************************************************************** pub const TXHUBADDR4_ADDR_M: u32 = 0x0000007F; // Hub Address pub const TXHUBADDR4_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXHUBPORT4 // register. // //***************************************************************************** pub const TXHUBPORT4_PORT_M: u32 = 0x0000007F; // Hub Port pub const TXHUBPORT4_PORT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXFUNCADDR4 // register. // //***************************************************************************** pub const RXFUNCADDR4_ADDR_M: u32 = 0x0000007F; // Device Address pub const RXFUNCADDR4_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXHUBADDR4 // register. // //***************************************************************************** pub const RXHUBADDR4_ADDR_M: u32 = 0x0000007F; // Hub Address pub const RXHUBADDR4_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXHUBPORT4 // register. // //***************************************************************************** pub const RXHUBPORT4_PORT_M: u32 = 0x0000007F; // Hub Port pub const RXHUBPORT4_PORT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXFUNCADDR5 // register. // //***************************************************************************** pub const TXFUNCADDR5_ADDR_M: u32 = 0x0000007F; // Device Address pub const TXFUNCADDR5_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXHUBADDR5 // register. // //***************************************************************************** pub const TXHUBADDR5_ADDR_M: u32 = 0x0000007F; // Hub Address pub const TXHUBADDR5_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXHUBPORT5 // register. // //***************************************************************************** pub const TXHUBPORT5_PORT_M: u32 = 0x0000007F; // Hub Port pub const TXHUBPORT5_PORT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXFUNCADDR5 // register. // //***************************************************************************** pub const RXFUNCADDR5_ADDR_M: u32 = 0x0000007F; // Device Address pub const RXFUNCADDR5_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXHUBADDR5 // register. // //***************************************************************************** pub const RXHUBADDR5_ADDR_M: u32 = 0x0000007F; // Hub Address pub const RXHUBADDR5_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXHUBPORT5 // register. // //***************************************************************************** pub const RXHUBPORT5_PORT_M: u32 = 0x0000007F; // Hub Port pub const RXHUBPORT5_PORT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXFUNCADDR6 // register. // //***************************************************************************** pub const TXFUNCADDR6_ADDR_M: u32 = 0x0000007F; // Device Address pub const TXFUNCADDR6_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXHUBADDR6 // register. // //***************************************************************************** pub const TXHUBADDR6_ADDR_M: u32 = 0x0000007F; // Hub Address pub const TXHUBADDR6_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXHUBPORT6 // register. // //***************************************************************************** pub const TXHUBPORT6_PORT_M: u32 = 0x0000007F; // Hub Port pub const TXHUBPORT6_PORT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXFUNCADDR6 // register. // //***************************************************************************** pub const RXFUNCADDR6_ADDR_M: u32 = 0x0000007F; // Device Address pub const RXFUNCADDR6_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXHUBADDR6 // register. // //***************************************************************************** pub const RXHUBADDR6_ADDR_M: u32 = 0x0000007F; // Hub Address pub const RXHUBADDR6_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXHUBPORT6 // register. // //***************************************************************************** pub const RXHUBPORT6_PORT_M: u32 = 0x0000007F; // Hub Port pub const RXHUBPORT6_PORT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXFUNCADDR7 // register. // //***************************************************************************** pub const TXFUNCADDR7_ADDR_M: u32 = 0x0000007F; // Device Address pub const TXFUNCADDR7_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXHUBADDR7 // register. // //***************************************************************************** pub const TXHUBADDR7_ADDR_M: u32 = 0x0000007F; // Hub Address pub const TXHUBADDR7_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXHUBPORT7 // register. // //***************************************************************************** pub const TXHUBPORT7_PORT_M: u32 = 0x0000007F; // Hub Port pub const TXHUBPORT7_PORT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXFUNCADDR7 // register. // //***************************************************************************** pub const RXFUNCADDR7_ADDR_M: u32 = 0x0000007F; // Device Address pub const RXFUNCADDR7_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXHUBADDR7 // register. // //***************************************************************************** pub const RXHUBADDR7_ADDR_M: u32 = 0x0000007F; // Hub Address pub const RXHUBADDR7_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXHUBPORT7 // register. // //***************************************************************************** pub const RXHUBPORT7_PORT_M: u32 = 0x0000007F; // Hub Port pub const RXHUBPORT7_PORT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_CSRL0 register. // //***************************************************************************** pub const CSRL0_NAKTO: u32 = 0x00000080; // NAK Timeout pub const CSRL0_SETENDC: u32 = 0x00000080; // Setup End Clear pub const CSRL0_STATUS: u32 = 0x00000040; // STATUS Packet pub const CSRL0_RXRDYC: u32 = 0x00000040; // RXRDY Clear pub const CSRL0_REQPKT: u32 = 0x00000020; // Request Packet pub const CSRL0_STALL: u32 = 0x00000020; // Send Stall pub const CSRL0_SETEND: u32 = 0x00000010; // Setup End pub const CSRL0_ERROR: u32 = 0x00000010; // Error pub const CSRL0_DATAEND: u32 = 0x00000008; // Data End pub const CSRL0_SETUP: u32 = 0x00000008; // Setup Packet pub const CSRL0_STALLED: u32 = 0x00000004; // Endpoint Stalled pub const CSRL0_TXRDY: u32 = 0x00000002; // Transmit Packet Ready pub const CSRL0_RXRDY: u32 = 0x00000001; // Receive Packet Ready //***************************************************************************** // // The following are defines for the bit fields in the USB_O_CSRH0 register. // //***************************************************************************** pub const CSRH0_DISPING: u32 = 0x00000008; // PING Disable pub const CSRH0_DTWE: u32 = 0x00000004; // Data Toggle Write Enable pub const CSRH0_DT: u32 = 0x00000002; // Data Toggle pub const CSRH0_FLUSH: u32 = 0x00000001; // Flush FIFO //***************************************************************************** // // The following are defines for the bit fields in the USB_O_COUNT0 register. // //***************************************************************************** pub const COUNT0_COUNT_M: u32 = 0x0000007F; // FIFO Count pub const COUNT0_COUNT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TYPE0 register. // //***************************************************************************** pub const TYPE0_SPEED_M: u32 = 0x000000C0; // Operating Speed pub const TYPE0_SPEED_HIGH: u32 = 0x00000040; // High pub const TYPE0_SPEED_FULL: u32 = 0x00000080; // Full pub const TYPE0_SPEED_LOW: u32 = 0x000000C0; // Low //***************************************************************************** // // The following are defines for the bit fields in the USB_O_NAKLMT register. // //***************************************************************************** pub const NAKLMT_NAKLMT_M: u32 = 0x0000001F; // EP0 NAK Limit pub const NAKLMT_NAKLMT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXMAXP1 register. // //***************************************************************************** pub const TXMAXP1_MAXLOAD_M: u32 = 0x000007FF; // Maximum Payload pub const TXMAXP1_MAXLOAD_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXCSRL1 register. // //***************************************************************************** pub const TXCSRL1_NAKTO: u32 = 0x00000080; // NAK Timeout pub const TXCSRL1_CLRDT: u32 = 0x00000040; // Clear Data Toggle pub const TXCSRL1_STALLED: u32 = 0x00000020; // Endpoint Stalled pub const TXCSRL1_STALL: u32 = 0x00000010; // Send STALL pub const TXCSRL1_SETUP: u32 = 0x00000010; // Setup Packet pub const TXCSRL1_FLUSH: u32 = 0x00000008; // Flush FIFO pub const TXCSRL1_ERROR: u32 = 0x00000004; // Error pub const TXCSRL1_UNDRN: u32 = 0x00000004; // Underrun pub const TXCSRL1_FIFONE: u32 = 0x00000002; // FIFO Not Empty pub const TXCSRL1_TXRDY: u32 = 0x00000001; // Transmit Packet Ready //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXCSRH1 register. // //***************************************************************************** pub const TXCSRH1_AUTOSET: u32 = 0x00000080; // Auto Set pub const TXCSRH1_ISO: u32 = 0x00000040; // Isochronous Transfers pub const TXCSRH1_MODE: u32 = 0x00000020; // Mode pub const TXCSRH1_DMAEN: u32 = 0x00000010; // DMA Request Enable pub const TXCSRH1_FDT: u32 = 0x00000008; // Force Data Toggle pub const TXCSRH1_DMAMOD: u32 = 0x00000004; // DMA Request Mode pub const TXCSRH1_DTWE: u32 = 0x00000002; // Data Toggle Write Enable pub const TXCSRH1_DT: u32 = 0x00000001; // Data Toggle //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXMAXP1 register. // //***************************************************************************** pub const RXMAXP1_MAXLOAD_M: u32 = 0x000007FF; // Maximum Payload pub const RXMAXP1_MAXLOAD_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCSRL1 register. // //***************************************************************************** pub const RXCSRL1_CLRDT: u32 = 0x00000080; // Clear Data Toggle pub const RXCSRL1_STALLED: u32 = 0x00000040; // Endpoint Stalled pub const RXCSRL1_STALL: u32 = 0x00000020; // Send STALL pub const RXCSRL1_REQPKT: u32 = 0x00000020; // Request Packet pub const RXCSRL1_FLUSH: u32 = 0x00000010; // Flush FIFO pub const RXCSRL1_DATAERR: u32 = 0x00000008; // Data Error pub const RXCSRL1_NAKTO: u32 = 0x00000008; // NAK Timeout pub const RXCSRL1_OVER: u32 = 0x00000004; // Overrun pub const RXCSRL1_ERROR: u32 = 0x00000004; // Error pub const RXCSRL1_FULL: u32 = 0x00000002; // FIFO Full pub const RXCSRL1_RXRDY: u32 = 0x00000001; // Receive Packet Ready //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCSRH1 register. // //***************************************************************************** pub const RXCSRH1_AUTOCL: u32 = 0x00000080; // Auto Clear pub const RXCSRH1_AUTORQ: u32 = 0x00000040; // Auto Request pub const RXCSRH1_ISO: u32 = 0x00000040; // Isochronous Transfers pub const RXCSRH1_DMAEN: u32 = 0x00000020; // DMA Request Enable pub const RXCSRH1_DISNYET: u32 = 0x00000010; // Disable NYET pub const RXCSRH1_PIDERR: u32 = 0x00000010; // PID Error pub const RXCSRH1_DMAMOD: u32 = 0x00000008; // DMA Request Mode pub const RXCSRH1_DTWE: u32 = 0x00000004; // Data Toggle Write Enable pub const RXCSRH1_DT: u32 = 0x00000002; // Data Toggle pub const RXCSRH1_INCOMPRX: u32 = 0x00000001; // Incomplete RX Transmission // Status //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCOUNT1 register. // //***************************************************************************** pub const RXCOUNT1_COUNT_M: u32 = 0x00001FFF; // Receive Packet Count pub const RXCOUNT1_COUNT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXTYPE1 register. // //***************************************************************************** pub const TXTYPE1_SPEED_M: u32 = 0x000000C0; // Operating Speed pub const TXTYPE1_SPEED_DFLT: u32 = 0x00000000; // Default pub const TXTYPE1_SPEED_HIGH: u32 = 0x00000040; // High pub const TXTYPE1_SPEED_FULL: u32 = 0x00000080; // Full pub const TXTYPE1_SPEED_LOW: u32 = 0x000000C0; // Low pub const TXTYPE1_PROTO_M: u32 = 0x00000030; // Protocol pub const TXTYPE1_PROTO_CTRL: u32 = 0x00000000; // Control pub const TXTYPE1_PROTO_ISOC: u32 = 0x00000010; // Isochronous pub const TXTYPE1_PROTO_BULK: u32 = 0x00000020; // Bulk pub const TXTYPE1_PROTO_INT: u32 = 0x00000030; // Interrupt pub const TXTYPE1_TEP_M: u32 = 0x0000000F; // Target Endpoint Number pub const TXTYPE1_TEP_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXINTERVAL1 // register. // //***************************************************************************** pub const TXINTERVAL1_NAKLMT_M: u32 = 0x000000FF; // NAK Limit pub const TXINTERVAL1_TXPOLL_M: u32 = 0x000000FF; // TX Polling pub const TXINTERVAL1_TXPOLL_S: uint = 0; pub const TXINTERVAL1_NAKLMT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXTYPE1 register. // //***************************************************************************** pub const RXTYPE1_SPEED_M: u32 = 0x000000C0; // Operating Speed pub const RXTYPE1_SPEED_DFLT: u32 = 0x00000000; // Default pub const RXTYPE1_SPEED_HIGH: u32 = 0x00000040; // High pub const RXTYPE1_SPEED_FULL: u32 = 0x00000080; // Full pub const RXTYPE1_SPEED_LOW: u32 = 0x000000C0; // Low pub const RXTYPE1_PROTO_M: u32 = 0x00000030; // Protocol pub const RXTYPE1_PROTO_CTRL: u32 = 0x00000000; // Control pub const RXTYPE1_PROTO_ISOC: u32 = 0x00000010; // Isochronous pub const RXTYPE1_PROTO_BULK: u32 = 0x00000020; // Bulk pub const RXTYPE1_PROTO_INT: u32 = 0x00000030; // Interrupt pub const RXTYPE1_TEP_M: u32 = 0x0000000F; // Target Endpoint Number pub const RXTYPE1_TEP_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXINTERVAL1 // register. // //***************************************************************************** pub const RXINTERVAL1_TXPOLL_M: u32 = 0x000000FF; // RX Polling pub const RXINTERVAL1_NAKLMT_M: u32 = 0x000000FF; // NAK Limit pub const RXINTERVAL1_TXPOLL_S: uint = 0; pub const RXINTERVAL1_NAKLMT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXMAXP2 register. // //***************************************************************************** pub const TXMAXP2_MAXLOAD_M: u32 = 0x000007FF; // Maximum Payload pub const TXMAXP2_MAXLOAD_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXCSRL2 register. // //***************************************************************************** pub const TXCSRL2_NAKTO: u32 = 0x00000080; // NAK Timeout pub const TXCSRL2_CLRDT: u32 = 0x00000040; // Clear Data Toggle pub const TXCSRL2_STALLED: u32 = 0x00000020; // Endpoint Stalled pub const TXCSRL2_SETUP: u32 = 0x00000010; // Setup Packet pub const TXCSRL2_STALL: u32 = 0x00000010; // Send STALL pub const TXCSRL2_FLUSH: u32 = 0x00000008; // Flush FIFO pub const TXCSRL2_ERROR: u32 = 0x00000004; // Error pub const TXCSRL2_UNDRN: u32 = 0x00000004; // Underrun pub const TXCSRL2_FIFONE: u32 = 0x00000002; // FIFO Not Empty pub const TXCSRL2_TXRDY: u32 = 0x00000001; // Transmit Packet Ready //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXCSRH2 register. // //***************************************************************************** pub const TXCSRH2_AUTOSET: u32 = 0x00000080; // Auto Set pub const TXCSRH2_ISO: u32 = 0x00000040; // Isochronous Transfers pub const TXCSRH2_MODE: u32 = 0x00000020; // Mode pub const TXCSRH2_DMAEN: u32 = 0x00000010; // DMA Request Enable pub const TXCSRH2_FDT: u32 = 0x00000008; // Force Data Toggle pub const TXCSRH2_DMAMOD: u32 = 0x00000004; // DMA Request Mode pub const TXCSRH2_DTWE: u32 = 0x00000002; // Data Toggle Write Enable pub const TXCSRH2_DT: u32 = 0x00000001; // Data Toggle //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXMAXP2 register. // //***************************************************************************** pub const RXMAXP2_MAXLOAD_M: u32 = 0x000007FF; // Maximum Payload pub const RXMAXP2_MAXLOAD_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCSRL2 register. // //***************************************************************************** pub const RXCSRL2_CLRDT: u32 = 0x00000080; // Clear Data Toggle pub const RXCSRL2_STALLED: u32 = 0x00000040; // Endpoint Stalled pub const RXCSRL2_REQPKT: u32 = 0x00000020; // Request Packet pub const RXCSRL2_STALL: u32 = 0x00000020; // Send STALL pub const RXCSRL2_FLUSH: u32 = 0x00000010; // Flush FIFO pub const RXCSRL2_DATAERR: u32 = 0x00000008; // Data Error pub const RXCSRL2_NAKTO: u32 = 0x00000008; // NAK Timeout pub const RXCSRL2_ERROR: u32 = 0x00000004; // Error pub const RXCSRL2_OVER: u32 = 0x00000004; // Overrun pub const RXCSRL2_FULL: u32 = 0x00000002; // FIFO Full pub const RXCSRL2_RXRDY: u32 = 0x00000001; // Receive Packet Ready //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCSRH2 register. // //***************************************************************************** pub const RXCSRH2_AUTOCL: u32 = 0x00000080; // Auto Clear pub const RXCSRH2_AUTORQ: u32 = 0x00000040; // Auto Request pub const RXCSRH2_ISO: u32 = 0x00000040; // Isochronous Transfers pub const RXCSRH2_DMAEN: u32 = 0x00000020; // DMA Request Enable pub const RXCSRH2_DISNYET: u32 = 0x00000010; // Disable NYET pub const RXCSRH2_PIDERR: u32 = 0x00000010; // PID Error pub const RXCSRH2_DMAMOD: u32 = 0x00000008; // DMA Request Mode pub const RXCSRH2_DTWE: u32 = 0x00000004; // Data Toggle Write Enable pub const RXCSRH2_DT: u32 = 0x00000002; // Data Toggle pub const RXCSRH2_INCOMPRX: u32 = 0x00000001; // Incomplete RX Transmission // Status //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCOUNT2 register. // //***************************************************************************** pub const RXCOUNT2_COUNT_M: u32 = 0x00001FFF; // Receive Packet Count pub const RXCOUNT2_COUNT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXTYPE2 register. // //***************************************************************************** pub const TXTYPE2_SPEED_M: u32 = 0x000000C0; // Operating Speed pub const TXTYPE2_SPEED_DFLT: u32 = 0x00000000; // Default pub const TXTYPE2_SPEED_HIGH: u32 = 0x00000040; // High pub const TXTYPE2_SPEED_FULL: u32 = 0x00000080; // Full pub const TXTYPE2_SPEED_LOW: u32 = 0x000000C0; // Low pub const TXTYPE2_PROTO_M: u32 = 0x00000030; // Protocol pub const TXTYPE2_PROTO_CTRL: u32 = 0x00000000; // Control pub const TXTYPE2_PROTO_ISOC: u32 = 0x00000010; // Isochronous pub const TXTYPE2_PROTO_BULK: u32 = 0x00000020; // Bulk pub const TXTYPE2_PROTO_INT: u32 = 0x00000030; // Interrupt pub const TXTYPE2_TEP_M: u32 = 0x0000000F; // Target Endpoint Number pub const TXTYPE2_TEP_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXINTERVAL2 // register. // //***************************************************************************** pub const TXINTERVAL2_TXPOLL_M: u32 = 0x000000FF; // TX Polling pub const TXINTERVAL2_NAKLMT_M: u32 = 0x000000FF; // NAK Limit pub const TXINTERVAL2_NAKLMT_S: uint = 0; pub const TXINTERVAL2_TXPOLL_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXTYPE2 register. // //***************************************************************************** pub const RXTYPE2_SPEED_M: u32 = 0x000000C0; // Operating Speed pub const RXTYPE2_SPEED_DFLT: u32 = 0x00000000; // Default pub const RXTYPE2_SPEED_HIGH: u32 = 0x00000040; // High pub const RXTYPE2_SPEED_FULL: u32 = 0x00000080; // Full pub const RXTYPE2_SPEED_LOW: u32 = 0x000000C0; // Low pub const RXTYPE2_PROTO_M: u32 = 0x00000030; // Protocol pub const RXTYPE2_PROTO_CTRL: u32 = 0x00000000; // Control pub const RXTYPE2_PROTO_ISOC: u32 = 0x00000010; // Isochronous pub const RXTYPE2_PROTO_BULK: u32 = 0x00000020; // Bulk pub const RXTYPE2_PROTO_INT: u32 = 0x00000030; // Interrupt pub const RXTYPE2_TEP_M: u32 = 0x0000000F; // Target Endpoint Number pub const RXTYPE2_TEP_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXINTERVAL2 // register. // //***************************************************************************** pub const RXINTERVAL2_TXPOLL_M: u32 = 0x000000FF; // RX Polling pub const RXINTERVAL2_NAKLMT_M: u32 = 0x000000FF; // NAK Limit pub const RXINTERVAL2_TXPOLL_S: uint = 0; pub const RXINTERVAL2_NAKLMT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXMAXP3 register. // //***************************************************************************** pub const TXMAXP3_MAXLOAD_M: u32 = 0x000007FF; // Maximum Payload pub const TXMAXP3_MAXLOAD_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXCSRL3 register. // //***************************************************************************** pub const TXCSRL3_NAKTO: u32 = 0x00000080; // NAK Timeout pub const TXCSRL3_CLRDT: u32 = 0x00000040; // Clear Data Toggle pub const TXCSRL3_STALLED: u32 = 0x00000020; // Endpoint Stalled pub const TXCSRL3_SETUP: u32 = 0x00000010; // Setup Packet pub const TXCSRL3_STALL: u32 = 0x00000010; // Send STALL pub const TXCSRL3_FLUSH: u32 = 0x00000008; // Flush FIFO pub const TXCSRL3_ERROR: u32 = 0x00000004; // Error pub const TXCSRL3_UNDRN: u32 = 0x00000004; // Underrun pub const TXCSRL3_FIFONE: u32 = 0x00000002; // FIFO Not Empty pub const TXCSRL3_TXRDY: u32 = 0x00000001; // Transmit Packet Ready //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXCSRH3 register. // //***************************************************************************** pub const TXCSRH3_AUTOSET: u32 = 0x00000080; // Auto Set pub const TXCSRH3_ISO: u32 = 0x00000040; // Isochronous Transfers pub const TXCSRH3_MODE: u32 = 0x00000020; // Mode pub const TXCSRH3_DMAEN: u32 = 0x00000010; // DMA Request Enable pub const TXCSRH3_FDT: u32 = 0x00000008; // Force Data Toggle pub const TXCSRH3_DMAMOD: u32 = 0x00000004; // DMA Request Mode pub const TXCSRH3_DTWE: u32 = 0x00000002; // Data Toggle Write Enable pub const TXCSRH3_DT: u32 = 0x00000001; // Data Toggle //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXMAXP3 register. // //***************************************************************************** pub const RXMAXP3_MAXLOAD_M: u32 = 0x000007FF; // Maximum Payload pub const RXMAXP3_MAXLOAD_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCSRL3 register. // //***************************************************************************** pub const RXCSRL3_CLRDT: u32 = 0x00000080; // Clear Data Toggle pub const RXCSRL3_STALLED: u32 = 0x00000040; // Endpoint Stalled pub const RXCSRL3_STALL: u32 = 0x00000020; // Send STALL pub const RXCSRL3_REQPKT: u32 = 0x00000020; // Request Packet pub const RXCSRL3_FLUSH: u32 = 0x00000010; // Flush FIFO pub const RXCSRL3_DATAERR: u32 = 0x00000008; // Data Error pub const RXCSRL3_NAKTO: u32 = 0x00000008; // NAK Timeout pub const RXCSRL3_ERROR: u32 = 0x00000004; // Error pub const RXCSRL3_OVER: u32 = 0x00000004; // Overrun pub const RXCSRL3_FULL: u32 = 0x00000002; // FIFO Full pub const RXCSRL3_RXRDY: u32 = 0x00000001; // Receive Packet Ready //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCSRH3 register. // //***************************************************************************** pub const RXCSRH3_AUTOCL: u32 = 0x00000080; // Auto Clear pub const RXCSRH3_AUTORQ: u32 = 0x00000040; // Auto Request pub const RXCSRH3_ISO: u32 = 0x00000040; // Isochronous Transfers pub const RXCSRH3_DMAEN: u32 = 0x00000020; // DMA Request Enable pub const RXCSRH3_DISNYET: u32 = 0x00000010; // Disable NYET pub const RXCSRH3_PIDERR: u32 = 0x00000010; // PID Error pub const RXCSRH3_DMAMOD: u32 = 0x00000008; // DMA Request Mode pub const RXCSRH3_DTWE: u32 = 0x00000004; // Data Toggle Write Enable pub const RXCSRH3_DT: u32 = 0x00000002; // Data Toggle pub const RXCSRH3_INCOMPRX: u32 = 0x00000001; // Incomplete RX Transmission // Status //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCOUNT3 register. // //***************************************************************************** pub const RXCOUNT3_COUNT_M: u32 = 0x00001FFF; // Receive Packet Count pub const RXCOUNT3_COUNT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXTYPE3 register. // //***************************************************************************** pub const TXTYPE3_SPEED_M: u32 = 0x000000C0; // Operating Speed pub const TXTYPE3_SPEED_DFLT: u32 = 0x00000000; // Default pub const TXTYPE3_SPEED_HIGH: u32 = 0x00000040; // High pub const TXTYPE3_SPEED_FULL: u32 = 0x00000080; // Full pub const TXTYPE3_SPEED_LOW: u32 = 0x000000C0; // Low pub const TXTYPE3_PROTO_M: u32 = 0x00000030; // Protocol pub const TXTYPE3_PROTO_CTRL: u32 = 0x00000000; // Control pub const TXTYPE3_PROTO_ISOC: u32 = 0x00000010; // Isochronous pub const TXTYPE3_PROTO_BULK: u32 = 0x00000020; // Bulk pub const TXTYPE3_PROTO_INT: u32 = 0x00000030; // Interrupt pub const TXTYPE3_TEP_M: u32 = 0x0000000F; // Target Endpoint Number pub const TXTYPE3_TEP_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXINTERVAL3 // register. // //***************************************************************************** pub const TXINTERVAL3_TXPOLL_M: u32 = 0x000000FF; // TX Polling pub const TXINTERVAL3_NAKLMT_M: u32 = 0x000000FF; // NAK Limit pub const TXINTERVAL3_TXPOLL_S: uint = 0; pub const TXINTERVAL3_NAKLMT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXTYPE3 register. // //***************************************************************************** pub const RXTYPE3_SPEED_M: u32 = 0x000000C0; // Operating Speed pub const RXTYPE3_SPEED_DFLT: u32 = 0x00000000; // Default pub const RXTYPE3_SPEED_HIGH: u32 = 0x00000040; // High pub const RXTYPE3_SPEED_FULL: u32 = 0x00000080; // Full pub const RXTYPE3_SPEED_LOW: u32 = 0x000000C0; // Low pub const RXTYPE3_PROTO_M: u32 = 0x00000030; // Protocol pub const RXTYPE3_PROTO_CTRL: u32 = 0x00000000; // Control pub const RXTYPE3_PROTO_ISOC: u32 = 0x00000010; // Isochronous pub const RXTYPE3_PROTO_BULK: u32 = 0x00000020; // Bulk pub const RXTYPE3_PROTO_INT: u32 = 0x00000030; // Interrupt pub const RXTYPE3_TEP_M: u32 = 0x0000000F; // Target Endpoint Number pub const RXTYPE3_TEP_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXINTERVAL3 // register. // //***************************************************************************** pub const RXINTERVAL3_TXPOLL_M: u32 = 0x000000FF; // RX Polling pub const RXINTERVAL3_NAKLMT_M: u32 = 0x000000FF; // NAK Limit pub const RXINTERVAL3_TXPOLL_S: uint = 0; pub const RXINTERVAL3_NAKLMT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXMAXP4 register. // //***************************************************************************** pub const TXMAXP4_MAXLOAD_M: u32 = 0x000007FF; // Maximum Payload pub const TXMAXP4_MAXLOAD_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXCSRL4 register. // //***************************************************************************** pub const TXCSRL4_NAKTO: u32 = 0x00000080; // NAK Timeout pub const TXCSRL4_CLRDT: u32 = 0x00000040; // Clear Data Toggle pub const TXCSRL4_STALLED: u32 = 0x00000020; // Endpoint Stalled pub const TXCSRL4_SETUP: u32 = 0x00000010; // Setup Packet pub const TXCSRL4_STALL: u32 = 0x00000010; // Send STALL pub const TXCSRL4_FLUSH: u32 = 0x00000008; // Flush FIFO pub const TXCSRL4_ERROR: u32 = 0x00000004; // Error pub const TXCSRL4_UNDRN: u32 = 0x00000004; // Underrun pub const TXCSRL4_FIFONE: u32 = 0x00000002; // FIFO Not Empty pub const TXCSRL4_TXRDY: u32 = 0x00000001; // Transmit Packet Ready //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXCSRH4 register. // //***************************************************************************** pub const TXCSRH4_AUTOSET: u32 = 0x00000080; // Auto Set pub const TXCSRH4_ISO: u32 = 0x00000040; // Isochronous Transfers pub const TXCSRH4_MODE: u32 = 0x00000020; // Mode pub const TXCSRH4_DMAEN: u32 = 0x00000010; // DMA Request Enable pub const TXCSRH4_FDT: u32 = 0x00000008; // Force Data Toggle pub const TXCSRH4_DMAMOD: u32 = 0x00000004; // DMA Request Mode pub const TXCSRH4_DTWE: u32 = 0x00000002; // Data Toggle Write Enable pub const TXCSRH4_DT: u32 = 0x00000001; // Data Toggle //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXMAXP4 register. // //***************************************************************************** pub const RXMAXP4_MAXLOAD_M: u32 = 0x000007FF; // Maximum Payload pub const RXMAXP4_MAXLOAD_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCSRL4 register. // //***************************************************************************** pub const RXCSRL4_CLRDT: u32 = 0x00000080; // Clear Data Toggle pub const RXCSRL4_STALLED: u32 = 0x00000040; // Endpoint Stalled pub const RXCSRL4_STALL: u32 = 0x00000020; // Send STALL pub const RXCSRL4_REQPKT: u32 = 0x00000020; // Request Packet pub const RXCSRL4_FLUSH: u32 = 0x00000010; // Flush FIFO pub const RXCSRL4_NAKTO: u32 = 0x00000008; // NAK Timeout pub const RXCSRL4_DATAERR: u32 = 0x00000008; // Data Error pub const RXCSRL4_OVER: u32 = 0x00000004; // Overrun pub const RXCSRL4_ERROR: u32 = 0x00000004; // Error pub const RXCSRL4_FULL: u32 = 0x00000002; // FIFO Full pub const RXCSRL4_RXRDY: u32 = 0x00000001; // Receive Packet Ready //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCSRH4 register. // //***************************************************************************** pub const RXCSRH4_AUTOCL: u32 = 0x00000080; // Auto Clear pub const RXCSRH4_AUTORQ: u32 = 0x00000040; // Auto Request pub const RXCSRH4_ISO: u32 = 0x00000040; // Isochronous Transfers pub const RXCSRH4_DMAEN: u32 = 0x00000020; // DMA Request Enable pub const RXCSRH4_DISNYET: u32 = 0x00000010; // Disable NYET pub const RXCSRH4_PIDERR: u32 = 0x00000010; // PID Error pub const RXCSRH4_DMAMOD: u32 = 0x00000008; // DMA Request Mode pub const RXCSRH4_DTWE: u32 = 0x00000004; // Data Toggle Write Enable pub const RXCSRH4_DT: u32 = 0x00000002; // Data Toggle pub const RXCSRH4_INCOMPRX: u32 = 0x00000001; // Incomplete RX Transmission // Status //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCOUNT4 register. // //***************************************************************************** pub const RXCOUNT4_COUNT_M: u32 = 0x00001FFF; // Receive Packet Count pub const RXCOUNT4_COUNT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXTYPE4 register. // //***************************************************************************** pub const TXTYPE4_SPEED_M: u32 = 0x000000C0; // Operating Speed pub const TXTYPE4_SPEED_DFLT: u32 = 0x00000000; // Default pub const TXTYPE4_SPEED_HIGH: u32 = 0x00000040; // High pub const TXTYPE4_SPEED_FULL: u32 = 0x00000080; // Full pub const TXTYPE4_SPEED_LOW: u32 = 0x000000C0; // Low pub const TXTYPE4_PROTO_M: u32 = 0x00000030; // Protocol pub const TXTYPE4_PROTO_CTRL: u32 = 0x00000000; // Control pub const TXTYPE4_PROTO_ISOC: u32 = 0x00000010; // Isochronous pub const TXTYPE4_PROTO_BULK: u32 = 0x00000020; // Bulk pub const TXTYPE4_PROTO_INT: u32 = 0x00000030; // Interrupt pub const TXTYPE4_TEP_M: u32 = 0x0000000F; // Target Endpoint Number pub const TXTYPE4_TEP_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXINTERVAL4 // register. // //***************************************************************************** pub const TXINTERVAL4_TXPOLL_M: u32 = 0x000000FF; // TX Polling pub const TXINTERVAL4_NAKLMT_M: u32 = 0x000000FF; // NAK Limit pub const TXINTERVAL4_NAKLMT_S: uint = 0; pub const TXINTERVAL4_TXPOLL_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXTYPE4 register. // //***************************************************************************** pub const RXTYPE4_SPEED_M: u32 = 0x000000C0; // Operating Speed pub const RXTYPE4_SPEED_DFLT: u32 = 0x00000000; // Default pub const RXTYPE4_SPEED_HIGH: u32 = 0x00000040; // High pub const RXTYPE4_SPEED_FULL: u32 = 0x00000080; // Full pub const RXTYPE4_SPEED_LOW: u32 = 0x000000C0; // Low pub const RXTYPE4_PROTO_M: u32 = 0x00000030; // Protocol pub const RXTYPE4_PROTO_CTRL: u32 = 0x00000000; // Control pub const RXTYPE4_PROTO_ISOC: u32 = 0x00000010; // Isochronous pub const RXTYPE4_PROTO_BULK: u32 = 0x00000020; // Bulk pub const RXTYPE4_PROTO_INT: u32 = 0x00000030; // Interrupt pub const RXTYPE4_TEP_M: u32 = 0x0000000F; // Target Endpoint Number pub const RXTYPE4_TEP_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXINTERVAL4 // register. // //***************************************************************************** pub const RXINTERVAL4_TXPOLL_M: u32 = 0x000000FF; // RX Polling pub const RXINTERVAL4_NAKLMT_M: u32 = 0x000000FF; // NAK Limit pub const RXINTERVAL4_NAKLMT_S: uint = 0; pub const RXINTERVAL4_TXPOLL_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXMAXP5 register. // //***************************************************************************** pub const TXMAXP5_MAXLOAD_M: u32 = 0x000007FF; // Maximum Payload pub const TXMAXP5_MAXLOAD_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXCSRL5 register. // //***************************************************************************** pub const TXCSRL5_NAKTO: u32 = 0x00000080; // NAK Timeout pub const TXCSRL5_CLRDT: u32 = 0x00000040; // Clear Data Toggle pub const TXCSRL5_STALLED: u32 = 0x00000020; // Endpoint Stalled pub const TXCSRL5_SETUP: u32 = 0x00000010; // Setup Packet pub const TXCSRL5_STALL: u32 = 0x00000010; // Send STALL pub const TXCSRL5_FLUSH: u32 = 0x00000008; // Flush FIFO pub const TXCSRL5_ERROR: u32 = 0x00000004; // Error pub const TXCSRL5_UNDRN: u32 = 0x00000004; // Underrun pub const TXCSRL5_FIFONE: u32 = 0x00000002; // FIFO Not Empty pub const TXCSRL5_TXRDY: u32 = 0x00000001; // Transmit Packet Ready //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXCSRH5 register. // //***************************************************************************** pub const TXCSRH5_AUTOSET: u32 = 0x00000080; // Auto Set pub const TXCSRH5_ISO: u32 = 0x00000040; // Isochronous Transfers pub const TXCSRH5_MODE: u32 = 0x00000020; // Mode pub const TXCSRH5_DMAEN: u32 = 0x00000010; // DMA Request Enable pub const TXCSRH5_FDT: u32 = 0x00000008; // Force Data Toggle pub const TXCSRH5_DMAMOD: u32 = 0x00000004; // DMA Request Mode pub const TXCSRH5_DTWE: u32 = 0x00000002; // Data Toggle Write Enable pub const TXCSRH5_DT: u32 = 0x00000001; // Data Toggle //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXMAXP5 register. // //***************************************************************************** pub const RXMAXP5_MAXLOAD_M: u32 = 0x000007FF; // Maximum Payload pub const RXMAXP5_MAXLOAD_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCSRL5 register. // //***************************************************************************** pub const RXCSRL5_CLRDT: u32 = 0x00000080; // Clear Data Toggle pub const RXCSRL5_STALLED: u32 = 0x00000040; // Endpoint Stalled pub const RXCSRL5_STALL: u32 = 0x00000020; // Send STALL pub const RXCSRL5_REQPKT: u32 = 0x00000020; // Request Packet pub const RXCSRL5_FLUSH: u32 = 0x00000010; // Flush FIFO pub const RXCSRL5_NAKTO: u32 = 0x00000008; // NAK Timeout pub const RXCSRL5_DATAERR: u32 = 0x00000008; // Data Error pub const RXCSRL5_ERROR: u32 = 0x00000004; // Error pub const RXCSRL5_OVER: u32 = 0x00000004; // Overrun pub const RXCSRL5_FULL: u32 = 0x00000002; // FIFO Full pub const RXCSRL5_RXRDY: u32 = 0x00000001; // Receive Packet Ready //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCSRH5 register. // //***************************************************************************** pub const RXCSRH5_AUTOCL: u32 = 0x00000080; // Auto Clear pub const RXCSRH5_AUTORQ: u32 = 0x00000040; // Auto Request pub const RXCSRH5_ISO: u32 = 0x00000040; // Isochronous Transfers pub const RXCSRH5_DMAEN: u32 = 0x00000020; // DMA Request Enable pub const RXCSRH5_DISNYET: u32 = 0x00000010; // Disable NYET pub const RXCSRH5_PIDERR: u32 = 0x00000010; // PID Error pub const RXCSRH5_DMAMOD: u32 = 0x00000008; // DMA Request Mode pub const RXCSRH5_DTWE: u32 = 0x00000004; // Data Toggle Write Enable pub const RXCSRH5_DT: u32 = 0x00000002; // Data Toggle pub const RXCSRH5_INCOMPRX: u32 = 0x00000001; // Incomplete RX Transmission // Status //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCOUNT5 register. // //***************************************************************************** pub const RXCOUNT5_COUNT_M: u32 = 0x00001FFF; // Receive Packet Count pub const RXCOUNT5_COUNT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXTYPE5 register. // //***************************************************************************** pub const TXTYPE5_SPEED_M: u32 = 0x000000C0; // Operating Speed pub const TXTYPE5_SPEED_DFLT: u32 = 0x00000000; // Default pub const TXTYPE5_SPEED_HIGH: u32 = 0x00000040; // High pub const TXTYPE5_SPEED_FULL: u32 = 0x00000080; // Full pub const TXTYPE5_SPEED_LOW: u32 = 0x000000C0; // Low pub const TXTYPE5_PROTO_M: u32 = 0x00000030; // Protocol pub const TXTYPE5_PROTO_CTRL: u32 = 0x00000000; // Control pub const TXTYPE5_PROTO_ISOC: u32 = 0x00000010; // Isochronous pub const TXTYPE5_PROTO_BULK: u32 = 0x00000020; // Bulk pub const TXTYPE5_PROTO_INT: u32 = 0x00000030; // Interrupt pub const TXTYPE5_TEP_M: u32 = 0x0000000F; // Target Endpoint Number pub const TXTYPE5_TEP_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXINTERVAL5 // register. // //***************************************************************************** pub const TXINTERVAL5_TXPOLL_M: u32 = 0x000000FF; // TX Polling pub const TXINTERVAL5_NAKLMT_M: u32 = 0x000000FF; // NAK Limit pub const TXINTERVAL5_NAKLMT_S: uint = 0; pub const TXINTERVAL5_TXPOLL_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXTYPE5 register. // //***************************************************************************** pub const RXTYPE5_SPEED_M: u32 = 0x000000C0; // Operating Speed pub const RXTYPE5_SPEED_DFLT: u32 = 0x00000000; // Default pub const RXTYPE5_SPEED_HIGH: u32 = 0x00000040; // High pub const RXTYPE5_SPEED_FULL: u32 = 0x00000080; // Full pub const RXTYPE5_SPEED_LOW: u32 = 0x000000C0; // Low pub const RXTYPE5_PROTO_M: u32 = 0x00000030; // Protocol pub const RXTYPE5_PROTO_CTRL: u32 = 0x00000000; // Control pub const RXTYPE5_PROTO_ISOC: u32 = 0x00000010; // Isochronous pub const RXTYPE5_PROTO_BULK: u32 = 0x00000020; // Bulk pub const RXTYPE5_PROTO_INT: u32 = 0x00000030; // Interrupt pub const RXTYPE5_TEP_M: u32 = 0x0000000F; // Target Endpoint Number pub const RXTYPE5_TEP_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXINTERVAL5 // register. // //***************************************************************************** pub const RXINTERVAL5_TXPOLL_M: u32 = 0x000000FF; // RX Polling pub const RXINTERVAL5_NAKLMT_M: u32 = 0x000000FF; // NAK Limit pub const RXINTERVAL5_TXPOLL_S: uint = 0; pub const RXINTERVAL5_NAKLMT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXMAXP6 register. // //***************************************************************************** pub const TXMAXP6_MAXLOAD_M: u32 = 0x000007FF; // Maximum Payload pub const TXMAXP6_MAXLOAD_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXCSRL6 register. // //***************************************************************************** pub const TXCSRL6_NAKTO: u32 = 0x00000080; // NAK Timeout pub const TXCSRL6_CLRDT: u32 = 0x00000040; // Clear Data Toggle pub const TXCSRL6_STALLED: u32 = 0x00000020; // Endpoint Stalled pub const TXCSRL6_STALL: u32 = 0x00000010; // Send STALL pub const TXCSRL6_SETUP: u32 = 0x00000010; // Setup Packet pub const TXCSRL6_FLUSH: u32 = 0x00000008; // Flush FIFO pub const TXCSRL6_ERROR: u32 = 0x00000004; // Error pub const TXCSRL6_UNDRN: u32 = 0x00000004; // Underrun pub const TXCSRL6_FIFONE: u32 = 0x00000002; // FIFO Not Empty pub const TXCSRL6_TXRDY: u32 = 0x00000001; // Transmit Packet Ready //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXCSRH6 register. // //***************************************************************************** pub const TXCSRH6_AUTOSET: u32 = 0x00000080; // Auto Set pub const TXCSRH6_ISO: u32 = 0x00000040; // Isochronous Transfers pub const TXCSRH6_MODE: u32 = 0x00000020; // Mode pub const TXCSRH6_DMAEN: u32 = 0x00000010; // DMA Request Enable pub const TXCSRH6_FDT: u32 = 0x00000008; // Force Data Toggle pub const TXCSRH6_DMAMOD: u32 = 0x00000004; // DMA Request Mode pub const TXCSRH6_DTWE: u32 = 0x00000002; // Data Toggle Write Enable pub const TXCSRH6_DT: u32 = 0x00000001; // Data Toggle //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXMAXP6 register. // //***************************************************************************** pub const RXMAXP6_MAXLOAD_M: u32 = 0x000007FF; // Maximum Payload pub const RXMAXP6_MAXLOAD_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCSRL6 register. // //***************************************************************************** pub const RXCSRL6_CLRDT: u32 = 0x00000080; // Clear Data Toggle pub const RXCSRL6_STALLED: u32 = 0x00000040; // Endpoint Stalled pub const RXCSRL6_REQPKT: u32 = 0x00000020; // Request Packet pub const RXCSRL6_STALL: u32 = 0x00000020; // Send STALL pub const RXCSRL6_FLUSH: u32 = 0x00000010; // Flush FIFO pub const RXCSRL6_NAKTO: u32 = 0x00000008; // NAK Timeout pub const RXCSRL6_DATAERR: u32 = 0x00000008; // Data Error pub const RXCSRL6_ERROR: u32 = 0x00000004; // Error pub const RXCSRL6_OVER: u32 = 0x00000004; // Overrun pub const RXCSRL6_FULL: u32 = 0x00000002; // FIFO Full pub const RXCSRL6_RXRDY: u32 = 0x00000001; // Receive Packet Ready //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCSRH6 register. // //***************************************************************************** pub const RXCSRH6_AUTOCL: u32 = 0x00000080; // Auto Clear pub const RXCSRH6_AUTORQ: u32 = 0x00000040; // Auto Request pub const RXCSRH6_ISO: u32 = 0x00000040; // Isochronous Transfers pub const RXCSRH6_DMAEN: u32 = 0x00000020; // DMA Request Enable pub const RXCSRH6_DISNYET: u32 = 0x00000010; // Disable NYET pub const RXCSRH6_PIDERR: u32 = 0x00000010; // PID Error pub const RXCSRH6_DMAMOD: u32 = 0x00000008; // DMA Request Mode pub const RXCSRH6_DTWE: u32 = 0x00000004; // Data Toggle Write Enable pub const RXCSRH6_DT: u32 = 0x00000002; // Data Toggle pub const RXCSRH6_INCOMPRX: u32 = 0x00000001; // Incomplete RX Transmission // Status //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCOUNT6 register. // //***************************************************************************** pub const RXCOUNT6_COUNT_M: u32 = 0x00001FFF; // Receive Packet Count pub const RXCOUNT6_COUNT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXTYPE6 register. // //***************************************************************************** pub const TXTYPE6_SPEED_M: u32 = 0x000000C0; // Operating Speed pub const TXTYPE6_SPEED_DFLT: u32 = 0x00000000; // Default pub const TXTYPE6_SPEED_HIGH: u32 = 0x00000040; // High pub const TXTYPE6_SPEED_FULL: u32 = 0x00000080; // Full pub const TXTYPE6_SPEED_LOW: u32 = 0x000000C0; // Low pub const TXTYPE6_PROTO_M: u32 = 0x00000030; // Protocol pub const TXTYPE6_PROTO_CTRL: u32 = 0x00000000; // Control pub const TXTYPE6_PROTO_ISOC: u32 = 0x00000010; // Isochronous pub const TXTYPE6_PROTO_BULK: u32 = 0x00000020; // Bulk pub const TXTYPE6_PROTO_INT: u32 = 0x00000030; // Interrupt pub const TXTYPE6_TEP_M: u32 = 0x0000000F; // Target Endpoint Number pub const TXTYPE6_TEP_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXINTERVAL6 // register. // //***************************************************************************** pub const TXINTERVAL6_TXPOLL_M: u32 = 0x000000FF; // TX Polling pub const TXINTERVAL6_NAKLMT_M: u32 = 0x000000FF; // NAK Limit pub const TXINTERVAL6_TXPOLL_S: uint = 0; pub const TXINTERVAL6_NAKLMT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXTYPE6 register. // //***************************************************************************** pub const RXTYPE6_SPEED_M: u32 = 0x000000C0; // Operating Speed pub const RXTYPE6_SPEED_DFLT: u32 = 0x00000000; // Default pub const RXTYPE6_SPEED_HIGH: u32 = 0x00000040; // High pub const RXTYPE6_SPEED_FULL: u32 = 0x00000080; // Full pub const RXTYPE6_SPEED_LOW: u32 = 0x000000C0; // Low pub const RXTYPE6_PROTO_M: u32 = 0x00000030; // Protocol pub const RXTYPE6_PROTO_CTRL: u32 = 0x00000000; // Control pub const RXTYPE6_PROTO_ISOC: u32 = 0x00000010; // Isochronous pub const RXTYPE6_PROTO_BULK: u32 = 0x00000020; // Bulk pub const RXTYPE6_PROTO_INT: u32 = 0x00000030; // Interrupt pub const RXTYPE6_TEP_M: u32 = 0x0000000F; // Target Endpoint Number pub const RXTYPE6_TEP_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXINTERVAL6 // register. // //***************************************************************************** pub const RXINTERVAL6_TXPOLL_M: u32 = 0x000000FF; // RX Polling pub const RXINTERVAL6_NAKLMT_M: u32 = 0x000000FF; // NAK Limit pub const RXINTERVAL6_NAKLMT_S: uint = 0; pub const RXINTERVAL6_TXPOLL_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXMAXP7 register. // //***************************************************************************** pub const TXMAXP7_MAXLOAD_M: u32 = 0x000007FF; // Maximum Payload pub const TXMAXP7_MAXLOAD_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXCSRL7 register. // //***************************************************************************** pub const TXCSRL7_NAKTO: u32 = 0x00000080; // NAK Timeout pub const TXCSRL7_CLRDT: u32 = 0x00000040; // Clear Data Toggle pub const TXCSRL7_STALLED: u32 = 0x00000020; // Endpoint Stalled pub const TXCSRL7_STALL: u32 = 0x00000010; // Send STALL pub const TXCSRL7_SETUP: u32 = 0x00000010; // Setup Packet pub const TXCSRL7_FLUSH: u32 = 0x00000008; // Flush FIFO pub const TXCSRL7_ERROR: u32 = 0x00000004; // Error pub const TXCSRL7_UNDRN: u32 = 0x00000004; // Underrun pub const TXCSRL7_FIFONE: u32 = 0x00000002; // FIFO Not Empty pub const TXCSRL7_TXRDY: u32 = 0x00000001; // Transmit Packet Ready //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXCSRH7 register. // //***************************************************************************** pub const TXCSRH7_AUTOSET: u32 = 0x00000080; // Auto Set pub const TXCSRH7_ISO: u32 = 0x00000040; // Isochronous Transfers pub const TXCSRH7_MODE: u32 = 0x00000020; // Mode pub const TXCSRH7_DMAEN: u32 = 0x00000010; // DMA Request Enable pub const TXCSRH7_FDT: u32 = 0x00000008; // Force Data Toggle pub const TXCSRH7_DMAMOD: u32 = 0x00000004; // DMA Request Mode pub const TXCSRH7_DTWE: u32 = 0x00000002; // Data Toggle Write Enable pub const TXCSRH7_DT: u32 = 0x00000001; // Data Toggle //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXMAXP7 register. // //***************************************************************************** pub const RXMAXP7_MAXLOAD_M: u32 = 0x000007FF; // Maximum Payload pub const RXMAXP7_MAXLOAD_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCSRL7 register. // //***************************************************************************** pub const RXCSRL7_CLRDT: u32 = 0x00000080; // Clear Data Toggle pub const RXCSRL7_STALLED: u32 = 0x00000040; // Endpoint Stalled pub const RXCSRL7_REQPKT: u32 = 0x00000020; // Request Packet pub const RXCSRL7_STALL: u32 = 0x00000020; // Send STALL pub const RXCSRL7_FLUSH: u32 = 0x00000010; // Flush FIFO pub const RXCSRL7_DATAERR: u32 = 0x00000008; // Data Error pub const RXCSRL7_NAKTO: u32 = 0x00000008; // NAK Timeout pub const RXCSRL7_ERROR: u32 = 0x00000004; // Error pub const RXCSRL7_OVER: u32 = 0x00000004; // Overrun pub const RXCSRL7_FULL: u32 = 0x00000002; // FIFO Full pub const RXCSRL7_RXRDY: u32 = 0x00000001; // Receive Packet Ready //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCSRH7 register. // //***************************************************************************** pub const RXCSRH7_AUTOCL: u32 = 0x00000080; // Auto Clear pub const RXCSRH7_ISO: u32 = 0x00000040; // Isochronous Transfers pub const RXCSRH7_AUTORQ: u32 = 0x00000040; // Auto Request pub const RXCSRH7_DMAEN: u32 = 0x00000020; // DMA Request Enable pub const RXCSRH7_PIDERR: u32 = 0x00000010; // PID Error pub const RXCSRH7_DISNYET: u32 = 0x00000010; // Disable NYET pub const RXCSRH7_DMAMOD: u32 = 0x00000008; // DMA Request Mode pub const RXCSRH7_DTWE: u32 = 0x00000004; // Data Toggle Write Enable pub const RXCSRH7_DT: u32 = 0x00000002; // Data Toggle pub const RXCSRH7_INCOMPRX: u32 = 0x00000001; // Incomplete RX Transmission // Status //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXCOUNT7 register. // //***************************************************************************** pub const RXCOUNT7_COUNT_M: u32 = 0x00001FFF; // Receive Packet Count pub const RXCOUNT7_COUNT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXTYPE7 register. // //***************************************************************************** pub const TXTYPE7_SPEED_M: u32 = 0x000000C0; // Operating Speed pub const TXTYPE7_SPEED_DFLT: u32 = 0x00000000; // Default pub const TXTYPE7_SPEED_HIGH: u32 = 0x00000040; // High pub const TXTYPE7_SPEED_FULL: u32 = 0x00000080; // Full pub const TXTYPE7_SPEED_LOW: u32 = 0x000000C0; // Low pub const TXTYPE7_PROTO_M: u32 = 0x00000030; // Protocol pub const TXTYPE7_PROTO_CTRL: u32 = 0x00000000; // Control pub const TXTYPE7_PROTO_ISOC: u32 = 0x00000010; // Isochronous pub const TXTYPE7_PROTO_BULK: u32 = 0x00000020; // Bulk pub const TXTYPE7_PROTO_INT: u32 = 0x00000030; // Interrupt pub const TXTYPE7_TEP_M: u32 = 0x0000000F; // Target Endpoint Number pub const TXTYPE7_TEP_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXINTERVAL7 // register. // //***************************************************************************** pub const TXINTERVAL7_TXPOLL_M: u32 = 0x000000FF; // TX Polling pub const TXINTERVAL7_NAKLMT_M: u32 = 0x000000FF; // NAK Limit pub const TXINTERVAL7_NAKLMT_S: uint = 0; pub const TXINTERVAL7_TXPOLL_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXTYPE7 register. // //***************************************************************************** pub const RXTYPE7_SPEED_M: u32 = 0x000000C0; // Operating Speed pub const RXTYPE7_SPEED_DFLT: u32 = 0x00000000; // Default pub const RXTYPE7_SPEED_HIGH: u32 = 0x00000040; // High pub const RXTYPE7_SPEED_FULL: u32 = 0x00000080; // Full pub const RXTYPE7_SPEED_LOW: u32 = 0x000000C0; // Low pub const RXTYPE7_PROTO_M: u32 = 0x00000030; // Protocol pub const RXTYPE7_PROTO_CTRL: u32 = 0x00000000; // Control pub const RXTYPE7_PROTO_ISOC: u32 = 0x00000010; // Isochronous pub const RXTYPE7_PROTO_BULK: u32 = 0x00000020; // Bulk pub const RXTYPE7_PROTO_INT: u32 = 0x00000030; // Interrupt pub const RXTYPE7_TEP_M: u32 = 0x0000000F; // Target Endpoint Number pub const RXTYPE7_TEP_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXINTERVAL7 // register. // //***************************************************************************** pub const RXINTERVAL7_TXPOLL_M: u32 = 0x000000FF; // RX Polling pub const RXINTERVAL7_NAKLMT_M: u32 = 0x000000FF; // NAK Limit pub const RXINTERVAL7_NAKLMT_S: uint = 0; pub const RXINTERVAL7_TXPOLL_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMAINTR register. // //***************************************************************************** pub const DMAINTR_CH7: u32 = 0x00000080; // Channel 7 DMA Interrupt pub const DMAINTR_CH6: u32 = 0x00000040; // Channel 6 DMA Interrupt pub const DMAINTR_CH5: u32 = 0x00000020; // Channel 5 DMA Interrupt pub const DMAINTR_CH4: u32 = 0x00000010; // Channel 4 DMA Interrupt pub const DMAINTR_CH3: u32 = 0x00000008; // Channel 3 DMA Interrupt pub const DMAINTR_CH2: u32 = 0x00000004; // Channel 2 DMA Interrupt pub const DMAINTR_CH1: u32 = 0x00000002; // Channel 1 DMA Interrupt pub const DMAINTR_CH0: u32 = 0x00000001; // Channel 0 DMA Interrupt //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMACTL0 register. // //***************************************************************************** pub const DMACTL0_BRSTM_M: u32 = 0x00000600; // Burst Mode pub const DMACTL0_BRSTM_ANY: u32 = 0x00000000; // Bursts of unspecified length pub const DMACTL0_BRSTM_INC4: u32 = 0x00000200; // INCR4 or unspecified length pub const DMACTL0_BRSTM_INC8: u32 = 0x00000400; // INCR8, INCR4 or unspecified // length pub const DMACTL0_BRSTM_INC16: u32 = 0x00000600; // INCR16, INCR8, INCR4 or // unspecified length pub const DMACTL0_ERR: u32 = 0x00000100; // Bus Error Bit pub const DMACTL0_EP_M: u32 = 0x000000F0; // Endpoint number pub const DMACTL0_IE: u32 = 0x00000008; // DMA Interrupt Enable pub const DMACTL0_MODE: u32 = 0x00000004; // DMA Transfer Mode pub const DMACTL0_DIR: u32 = 0x00000002; // DMA Direction pub const DMACTL0_ENABLE: u32 = 0x00000001; // DMA Transfer Enable pub const DMACTL0_EP_S: uint = 4; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMAADDR0 register. // //***************************************************************************** pub const DMAADDR0_ADDR_M: u32 = 0xFFFFFFFC; // DMA Address pub const DMAADDR0_ADDR_S: uint = 2; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMACOUNT0 // register. // //***************************************************************************** pub const DMACOUNT0_COUNT_M: u32 = 0xFFFFFFFC; // DMA Count pub const DMACOUNT0_COUNT_S: uint = 2; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMACTL1 register. // //***************************************************************************** pub const DMACTL1_BRSTM_M: u32 = 0x00000600; // Burst Mode pub const DMACTL1_BRSTM_ANY: u32 = 0x00000000; // Bursts of unspecified length pub const DMACTL1_BRSTM_INC4: u32 = 0x00000200; // INCR4 or unspecified length pub const DMACTL1_BRSTM_INC8: u32 = 0x00000400; // INCR8, INCR4 or unspecified // length pub const DMACTL1_BRSTM_INC16: u32 = 0x00000600; // INCR16, INCR8, INCR4 or // unspecified length pub const DMACTL1_ERR: u32 = 0x00000100; // Bus Error Bit pub const DMACTL1_EP_M: u32 = 0x000000F0; // Endpoint number pub const DMACTL1_IE: u32 = 0x00000008; // DMA Interrupt Enable pub const DMACTL1_MODE: u32 = 0x00000004; // DMA Transfer Mode pub const DMACTL1_DIR: u32 = 0x00000002; // DMA Direction pub const DMACTL1_ENABLE: u32 = 0x00000001; // DMA Transfer Enable pub const DMACTL1_EP_S: uint = 4; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMAADDR1 register. // //***************************************************************************** pub const DMAADDR1_ADDR_M: u32 = 0xFFFFFFFC; // DMA Address pub const DMAADDR1_ADDR_S: uint = 2; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMACOUNT1 // register. // //***************************************************************************** pub const DMACOUNT1_COUNT_M: u32 = 0xFFFFFFFC; // DMA Count pub const DMACOUNT1_COUNT_S: uint = 2; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMACTL2 register. // //***************************************************************************** pub const DMACTL2_BRSTM_M: u32 = 0x00000600; // Burst Mode pub const DMACTL2_BRSTM_ANY: u32 = 0x00000000; // Bursts of unspecified length pub const DMACTL2_BRSTM_INC4: u32 = 0x00000200; // INCR4 or unspecified length pub const DMACTL2_BRSTM_INC8: u32 = 0x00000400; // INCR8, INCR4 or unspecified // length pub const DMACTL2_BRSTM_INC16: u32 = 0x00000600; // INCR16, INCR8, INCR4 or // unspecified length pub const DMACTL2_ERR: u32 = 0x00000100; // Bus Error Bit pub const DMACTL2_EP_M: u32 = 0x000000F0; // Endpoint number pub const DMACTL2_IE: u32 = 0x00000008; // DMA Interrupt Enable pub const DMACTL2_MODE: u32 = 0x00000004; // DMA Transfer Mode pub const DMACTL2_DIR: u32 = 0x00000002; // DMA Direction pub const DMACTL2_ENABLE: u32 = 0x00000001; // DMA Transfer Enable pub const DMACTL2_EP_S: uint = 4; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMAADDR2 register. // //***************************************************************************** pub const DMAADDR2_ADDR_M: u32 = 0xFFFFFFFC; // DMA Address pub const DMAADDR2_ADDR_S: uint = 2; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMACOUNT2 // register. // //***************************************************************************** pub const DMACOUNT2_COUNT_M: u32 = 0xFFFFFFFC; // DMA Count pub const DMACOUNT2_COUNT_S: uint = 2; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMACTL3 register. // //***************************************************************************** pub const DMACTL3_BRSTM_M: u32 = 0x00000600; // Burst Mode pub const DMACTL3_BRSTM_ANY: u32 = 0x00000000; // Bursts of unspecified length pub const DMACTL3_BRSTM_INC4: u32 = 0x00000200; // INCR4 or unspecified length pub const DMACTL3_BRSTM_INC8: u32 = 0x00000400; // INCR8, INCR4 or unspecified // length pub const DMACTL3_BRSTM_INC16: u32 = 0x00000600; // INCR16, INCR8, INCR4 or // unspecified length pub const DMACTL3_ERR: u32 = 0x00000100; // Bus Error Bit pub const DMACTL3_EP_M: u32 = 0x000000F0; // Endpoint number pub const DMACTL3_IE: u32 = 0x00000008; // DMA Interrupt Enable pub const DMACTL3_MODE: u32 = 0x00000004; // DMA Transfer Mode pub const DMACTL3_DIR: u32 = 0x00000002; // DMA Direction pub const DMACTL3_ENABLE: u32 = 0x00000001; // DMA Transfer Enable pub const DMACTL3_EP_S: uint = 4; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMAADDR3 register. // //***************************************************************************** pub const DMAADDR3_ADDR_M: u32 = 0xFFFFFFFC; // DMA Address pub const DMAADDR3_ADDR_S: uint = 2; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMACOUNT3 // register. // //***************************************************************************** pub const DMACOUNT3_COUNT_M: u32 = 0xFFFFFFFC; // DMA Count pub const DMACOUNT3_COUNT_S: uint = 2; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMACTL4 register. // //***************************************************************************** pub const DMACTL4_BRSTM_M: u32 = 0x00000600; // Burst Mode pub const DMACTL4_BRSTM_ANY: u32 = 0x00000000; // Bursts of unspecified length pub const DMACTL4_BRSTM_INC4: u32 = 0x00000200; // INCR4 or unspecified length pub const DMACTL4_BRSTM_INC8: u32 = 0x00000400; // INCR8, INCR4 or unspecified // length pub const DMACTL4_BRSTM_INC16: u32 = 0x00000600; // INCR16, INCR8, INCR4 or // unspecified length pub const DMACTL4_ERR: u32 = 0x00000100; // Bus Error Bit pub const DMACTL4_EP_M: u32 = 0x000000F0; // Endpoint number pub const DMACTL4_IE: u32 = 0x00000008; // DMA Interrupt Enable pub const DMACTL4_MODE: u32 = 0x00000004; // DMA Transfer Mode pub const DMACTL4_DIR: u32 = 0x00000002; // DMA Direction pub const DMACTL4_ENABLE: u32 = 0x00000001; // DMA Transfer Enable pub const DMACTL4_EP_S: uint = 4; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMAADDR4 register. // //***************************************************************************** pub const DMAADDR4_ADDR_M: u32 = 0xFFFFFFFC; // DMA Address pub const DMAADDR4_ADDR_S: uint = 2; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMACOUNT4 // register. // //***************************************************************************** pub const DMACOUNT4_COUNT_M: u32 = 0xFFFFFFFC; // DMA Count pub const DMACOUNT4_COUNT_S: uint = 2; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMACTL5 register. // //***************************************************************************** pub const DMACTL5_BRSTM_M: u32 = 0x00000600; // Burst Mode pub const DMACTL5_BRSTM_ANY: u32 = 0x00000000; // Bursts of unspecified length pub const DMACTL5_BRSTM_INC4: u32 = 0x00000200; // INCR4 or unspecified length pub const DMACTL5_BRSTM_INC8: u32 = 0x00000400; // INCR8, INCR4 or unspecified // length pub const DMACTL5_BRSTM_INC16: u32 = 0x00000600; // INCR16, INCR8, INCR4 or // unspecified length pub const DMACTL5_ERR: u32 = 0x00000100; // Bus Error Bit pub const DMACTL5_EP_M: u32 = 0x000000F0; // Endpoint number pub const DMACTL5_IE: u32 = 0x00000008; // DMA Interrupt Enable pub const DMACTL5_MODE: u32 = 0x00000004; // DMA Transfer Mode pub const DMACTL5_DIR: u32 = 0x00000002; // DMA Direction pub const DMACTL5_ENABLE: u32 = 0x00000001; // DMA Transfer Enable pub const DMACTL5_EP_S: uint = 4; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMAADDR5 register. // //***************************************************************************** pub const DMAADDR5_ADDR_M: u32 = 0xFFFFFFFC; // DMA Address pub const DMAADDR5_ADDR_S: uint = 2; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMACOUNT5 // register. // //***************************************************************************** pub const DMACOUNT5_COUNT_M: u32 = 0xFFFFFFFC; // DMA Count pub const DMACOUNT5_COUNT_S: uint = 2; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMACTL6 register. // //***************************************************************************** pub const DMACTL6_BRSTM_M: u32 = 0x00000600; // Burst Mode pub const DMACTL6_BRSTM_ANY: u32 = 0x00000000; // Bursts of unspecified length pub const DMACTL6_BRSTM_INC4: u32 = 0x00000200; // INCR4 or unspecified length pub const DMACTL6_BRSTM_INC8: u32 = 0x00000400; // INCR8, INCR4 or unspecified // length pub const DMACTL6_BRSTM_INC16: u32 = 0x00000600; // INCR16, INCR8, INCR4 or // unspecified length pub const DMACTL6_ERR: u32 = 0x00000100; // Bus Error Bit pub const DMACTL6_EP_M: u32 = 0x000000F0; // Endpoint number pub const DMACTL6_IE: u32 = 0x00000008; // DMA Interrupt Enable pub const DMACTL6_MODE: u32 = 0x00000004; // DMA Transfer Mode pub const DMACTL6_DIR: u32 = 0x00000002; // DMA Direction pub const DMACTL6_ENABLE: u32 = 0x00000001; // DMA Transfer Enable pub const DMACTL6_EP_S: uint = 4; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMAADDR6 register. // //***************************************************************************** pub const DMAADDR6_ADDR_M: u32 = 0xFFFFFFFC; // DMA Address pub const DMAADDR6_ADDR_S: uint = 2; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMACOUNT6 // register. // //***************************************************************************** pub const DMACOUNT6_COUNT_M: u32 = 0xFFFFFFFC; // DMA Count pub const DMACOUNT6_COUNT_S: uint = 2; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMACTL7 register. // //***************************************************************************** pub const DMACTL7_BRSTM_M: u32 = 0x00000600; // Burst Mode pub const DMACTL7_BRSTM_ANY: u32 = 0x00000000; // Bursts of unspecified length pub const DMACTL7_BRSTM_INC4: u32 = 0x00000200; // INCR4 or unspecified length pub const DMACTL7_BRSTM_INC8: u32 = 0x00000400; // INCR8, INCR4 or unspecified // length pub const DMACTL7_BRSTM_INC16: u32 = 0x00000600; // INCR16, INCR8, INCR4 or // unspecified length pub const DMACTL7_ERR: u32 = 0x00000100; // Bus Error Bit pub const DMACTL7_EP_M: u32 = 0x000000F0; // Endpoint number pub const DMACTL7_IE: u32 = 0x00000008; // DMA Interrupt Enable pub const DMACTL7_MODE: u32 = 0x00000004; // DMA Transfer Mode pub const DMACTL7_DIR: u32 = 0x00000002; // DMA Direction pub const DMACTL7_ENABLE: u32 = 0x00000001; // DMA Transfer Enable pub const DMACTL7_EP_S: uint = 4; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMAADDR7 register. // //***************************************************************************** pub const DMAADDR7_ADDR_M: u32 = 0xFFFFFFFC; // DMA Address pub const DMAADDR7_ADDR_S: uint = 2; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMACOUNT7 // register. // //***************************************************************************** pub const DMACOUNT7_COUNT_M: u32 = 0xFFFFFFFC; // DMA Count pub const DMACOUNT7_COUNT_S: uint = 2; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RQPKTCOUNT1 // register. // //***************************************************************************** pub const RQPKTCOUNT1_M: u32 = 0x0000FFFF; // Block Transfer Packet Count pub const RQPKTCOUNT1_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RQPKTCOUNT2 // register. // //***************************************************************************** pub const RQPKTCOUNT2_M: u32 = 0x0000FFFF; // Block Transfer Packet Count pub const RQPKTCOUNT2_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RQPKTCOUNT3 // register. // //***************************************************************************** pub const RQPKTCOUNT3_M: u32 = 0x0000FFFF; // Block Transfer Packet Count pub const RQPKTCOUNT3_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RQPKTCOUNT4 // register. // //***************************************************************************** pub const RQPKTCOUNT4_COUNT_M: u32 = 0x0000FFFF; // Block Transfer Packet Count pub const RQPKTCOUNT4_COUNT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RQPKTCOUNT5 // register. // //***************************************************************************** pub const RQPKTCOUNT5_COUNT_M: u32 = 0x0000FFFF; // Block Transfer Packet Count pub const RQPKTCOUNT5_COUNT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RQPKTCOUNT6 // register. // //***************************************************************************** pub const RQPKTCOUNT6_COUNT_M: u32 = 0x0000FFFF; // Block Transfer Packet Count pub const RQPKTCOUNT6_COUNT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RQPKTCOUNT7 // register. // //***************************************************************************** pub const RQPKTCOUNT7_COUNT_M: u32 = 0x0000FFFF; // Block Transfer Packet Count pub const RQPKTCOUNT7_COUNT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_RXDPKTBUFDIS // register. // //***************************************************************************** pub const RXDPKTBUFDIS_EP7: u32 = 0x00000080; // EP7 RX Double-Packet Buffer // Disable pub const RXDPKTBUFDIS_EP6: u32 = 0x00000040; // EP6 RX Double-Packet Buffer // Disable pub const RXDPKTBUFDIS_EP5: u32 = 0x00000020; // EP5 RX Double-Packet Buffer // Disable pub const RXDPKTBUFDIS_EP4: u32 = 0x00000010; // EP4 RX Double-Packet Buffer // Disable pub const RXDPKTBUFDIS_EP3: u32 = 0x00000008; // EP3 RX Double-Packet Buffer // Disable pub const RXDPKTBUFDIS_EP2: u32 = 0x00000004; // EP2 RX Double-Packet Buffer // Disable pub const RXDPKTBUFDIS_EP1: u32 = 0x00000002; // EP1 RX Double-Packet Buffer // Disable //***************************************************************************** // // The following are defines for the bit fields in the USB_O_TXDPKTBUFDIS // register. // //***************************************************************************** pub const TXDPKTBUFDIS_EP7: u32 = 0x00000080; // EP7 TX Double-Packet Buffer // Disable pub const TXDPKTBUFDIS_EP6: u32 = 0x00000040; // EP6 TX Double-Packet Buffer // Disable pub const TXDPKTBUFDIS_EP5: u32 = 0x00000020; // EP5 TX Double-Packet Buffer // Disable pub const TXDPKTBUFDIS_EP4: u32 = 0x00000010; // EP4 TX Double-Packet Buffer // Disable pub const TXDPKTBUFDIS_EP3: u32 = 0x00000008; // EP3 TX Double-Packet Buffer // Disable pub const TXDPKTBUFDIS_EP2: u32 = 0x00000004; // EP2 TX Double-Packet Buffer // Disable pub const TXDPKTBUFDIS_EP1: u32 = 0x00000002; // EP1 TX Double-Packet Buffer // Disable //***************************************************************************** // // The following are defines for the bit fields in the USB_O_CTO register. // //***************************************************************************** pub const CTO_CCTV_M: u32 = 0x0000FFFF; // Configurable Chirp Timeout Value pub const CTO_CCTV_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_HHSRTN register. // //***************************************************************************** pub const HHSRTN_HHSRTN_M: u32 = 0x0000FFFF; // HIgh Speed to UTM Operating // Delay pub const HHSRTN_HHSRTN_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_HSBT register. // //***************************************************************************** pub const HSBT_HSBT_M: u32 = 0x0000000F; // High Speed Timeout Adder pub const HSBT_HSBT_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_LPMATTR register. // //***************************************************************************** pub const LPMATTR_ENDPT_M: u32 = 0x0000F000; // Endpoint pub const LPMATTR_RMTWAK: u32 = 0x00000100; // Remote Wake pub const LPMATTR_HIRD_M: u32 = 0x000000F0; // Host Initiated Resume Duration pub const LPMATTR_LS_M: u32 = 0x0000000F; // Link State pub const LPMATTR_LS_L1: u32 = 0x00000001; // Sleep State (L1) pub const LPMATTR_ENDPT_S: uint = 12; pub const LPMATTR_HIRD_S: uint = 4; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_LPMCNTRL register. // //***************************************************************************** pub const LPMCNTRL_NAK: u32 = 0x00000010; // LPM NAK pub const LPMCNTRL_EN_M: u32 = 0x0000000C; // LPM Enable pub const LPMCNTRL_EN_NONE: u32 = 0x00000000; // LPM and Extended transactions // are not supported. In this case, // the USB does not respond to LPM // transactions and LPM // transactions cause a timeout pub const LPMCNTRL_EN_EXT: u32 = 0x00000004; // LPM is not supported but // extended transactions are // supported. In this case, the USB // does respond to an LPM // transaction with a STALL pub const LPMCNTRL_EN_LPMEXT: u32 = 0x0000000C; // The USB supports LPM extended // transactions. In this case, the // USB responds with a NYET or an // ACK as determined by the value // of TXLPM and other conditions pub const LPMCNTRL_RES: u32 = 0x00000002; // LPM Resume pub const LPMCNTRL_TXLPM: u32 = 0x00000001; // Transmit LPM Transaction Enable //***************************************************************************** // // The following are defines for the bit fields in the USB_O_LPMIM register. // //***************************************************************************** pub const LPMIM_ERR: u32 = 0x00000020; // LPM Error Interrupt Mask pub const LPMIM_RES: u32 = 0x00000010; // LPM Resume Interrupt Mask pub const LPMIM_NC: u32 = 0x00000008; // LPM NC Interrupt Mask pub const LPMIM_ACK: u32 = 0x00000004; // LPM ACK Interrupt Mask pub const LPMIM_NY: u32 = 0x00000002; // LPM NY Interrupt Mask pub const LPMIM_STALL: u32 = 0x00000001; // LPM STALL Interrupt Mask //***************************************************************************** // // The following are defines for the bit fields in the USB_O_LPMRIS register. // //***************************************************************************** pub const LPMRIS_ERR: u32 = 0x00000020; // LPM Interrupt Status pub const LPMRIS_RES: u32 = 0x00000010; // LPM Resume Interrupt Status pub const LPMRIS_NC: u32 = 0x00000008; // LPM NC Interrupt Status pub const LPMRIS_ACK: u32 = 0x00000004; // LPM ACK Interrupt Status pub const LPMRIS_NY: u32 = 0x00000002; // LPM NY Interrupt Status pub const LPMRIS_LPMST: u32 = 0x00000001; // LPM STALL Interrupt Status //***************************************************************************** // // The following are defines for the bit fields in the USB_O_LPMFADDR register. // //***************************************************************************** pub const LPMFADDR_ADDR_M: u32 = 0x0000007F; // LPM Function Address pub const LPMFADDR_ADDR_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_EPC register. // //***************************************************************************** pub const EPC_PFLTACT_M: u32 = 0x00000300; // Power Fault Action pub const EPC_PFLTACT_UNCHG: u32 = 0x00000000; // Unchanged pub const EPC_PFLTACT_TRIS: u32 = 0x00000100; // Tristate pub const EPC_PFLTACT_LOW: u32 = 0x00000200; // Low pub const EPC_PFLTACT_HIGH: u32 = 0x00000300; // High pub const EPC_PFLTAEN: u32 = 0x00000040; // Power Fault Action Enable pub const EPC_PFLTSEN_HIGH: u32 = 0x00000020; // Power Fault Sense pub const EPC_PFLTEN: u32 = 0x00000010; // Power Fault Input Enable pub const EPC_EPENDE: u32 = 0x00000004; // EPEN Drive Enable pub const EPC_EPEN_M: u32 = 0x00000003; // External Power Supply Enable // Configuration pub const EPC_EPEN_LOW: u32 = 0x00000000; // Power Enable Active Low pub const EPC_EPEN_HIGH: u32 = 0x00000001; // Power Enable Active High pub const EPC_EPEN_VBLOW: u32 = 0x00000002; // Power Enable High if VBUS Low // (OTG only) pub const EPC_EPEN_VBHIGH: u32 = 0x00000003; // Power Enable High if VBUS High // (OTG only) //***************************************************************************** // // The following are defines for the bit fields in the USB_O_EPCRIS register. // //***************************************************************************** pub const EPCRIS_PF: u32 = 0x00000001; // USB Power Fault Interrupt Status //***************************************************************************** // // The following are defines for the bit fields in the USB_O_EPCIM register. // //***************************************************************************** pub const EPCIM_PF: u32 = 0x00000001; // USB Power Fault Interrupt Mask //***************************************************************************** // // The following are defines for the bit fields in the USB_O_EPCISC register. // //***************************************************************************** pub const EPCISC_PF: u32 = 0x00000001; // USB Power Fault Interrupt Status // and Clear //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DRRIS register. // //***************************************************************************** pub const DRRIS_RESUME: u32 = 0x00000001; // RESUME Interrupt Status //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DRIM register. // //***************************************************************************** pub const DRIM_RESUME: u32 = 0x00000001; // RESUME Interrupt Mask //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DRISC register. // //***************************************************************************** pub const DRISC_RESUME: u32 = 0x00000001; // RESUME Interrupt Status and // Clear //***************************************************************************** // // The following are defines for the bit fields in the USB_O_GPCS register. // //***************************************************************************** pub const GPCS_DEVMOD_M: u32 = 0x00000007; // Device Mode pub const GPCS_DEVMOD_OTG: u32 = 0x00000000; // Use USB0VBUS and USB0ID pin pub const GPCS_DEVMOD_HOST: u32 = 0x00000002; // Force USB0VBUS and USB0ID low pub const GPCS_DEVMOD_DEV: u32 = 0x00000003; // Force USB0VBUS and USB0ID high pub const GPCS_DEVMOD_HOSTVBUS: u32 = 0x00000004; // Use USB0VBUS and force USB0ID // low pub const GPCS_DEVMOD_DEVVBUS: u32 = 0x00000005; // Use USB0VBUS and force USB0ID // high pub const GPCS_DEVMODOTG: u32 = 0x00000002; // Enable Device Mode pub const GPCS_DEVMOD: u32 = 0x00000001; // Device Mode //***************************************************************************** // // The following are defines for the bit fields in the USB_O_VDC register. // //***************************************************************************** pub const VDC_VBDEN: u32 = 0x00000001; // VBUS Droop Enable //***************************************************************************** // // The following are defines for the bit fields in the USB_O_VDCRIS register. // //***************************************************************************** pub const VDCRIS_VD: u32 = 0x00000001; // VBUS Droop Raw Interrupt Status //***************************************************************************** // // The following are defines for the bit fields in the USB_O_VDCIM register. // //***************************************************************************** pub const VDCIM_VD: u32 = 0x00000001; // VBUS Droop Interrupt Mask //***************************************************************************** // // The following are defines for the bit fields in the USB_O_VDCISC register. // //***************************************************************************** pub const VDCISC_VD: u32 = 0x00000001; // VBUS Droop Interrupt Status and // Clear //***************************************************************************** // // The following are defines for the bit fields in the USB_O_IDVRIS register. // //***************************************************************************** pub const IDVRIS_ID: u32 = 0x00000001; // ID Valid Detect Raw Interrupt // Status //***************************************************************************** // // The following are defines for the bit fields in the USB_O_IDVIM register. // //***************************************************************************** pub const IDVIM_ID: u32 = 0x00000001; // ID Valid Detect Interrupt Mask //***************************************************************************** // // The following are defines for the bit fields in the USB_O_IDVISC register. // //***************************************************************************** pub const IDVISC_ID: u32 = 0x00000001; // ID Valid Detect Interrupt Status // and Clear //***************************************************************************** // // The following are defines for the bit fields in the USB_O_DMASEL register. // //***************************************************************************** pub const DMASEL_DMACTX_M: u32 = 0x00F00000; // DMA C TX Select pub const DMASEL_DMACRX_M: u32 = 0x000F0000; // DMA C RX Select pub const DMASEL_DMABTX_M: u32 = 0x0000F000; // DMA B TX Select pub const DMASEL_DMABRX_M: u32 = 0x00000F00; // DMA B RX Select pub const DMASEL_DMAATX_M: u32 = 0x000000F0; // DMA A TX Select pub const DMASEL_DMAARX_M: u32 = 0x0000000F; // DMA A RX Select pub const DMASEL_DMACTX_S: uint = 20; pub const DMASEL_DMACRX_S: uint = 16; pub const DMASEL_DMABTX_S: uint = 12; pub const DMASEL_DMABRX_S: uint = 8; pub const DMASEL_DMAATX_S: uint = 4; pub const DMASEL_DMAARX_S: uint = 0; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_PP register. // //***************************************************************************** pub const PP_ECNT_M: u32 = 0x0000FF00; // Endpoint Count pub const PP_USB_M: u32 = 0x000000C0; // USB Capability pub const PP_USB_DEVICE: u32 = 0x00000040; // DEVICE pub const PP_USB_HOSTDEVICE: u32 = 0x00000080; // HOST pub const PP_USB_OTG: u32 = 0x000000C0; // OTG pub const PP_ULPI: u32 = 0x00000020; // ULPI Present pub const PP_PHY: u32 = 0x00000010; // PHY Present pub const PP_TYPE_M: u32 = 0x0000000F; // Controller Type pub const PP_TYPE_0: u32 = 0x00000000; // The first-generation USB // controller pub const PP_TYPE_1: u32 = 0x00000001; // Second-generation USB // controller.The controller // implemented in post Icestorm // devices that use the 3.0 version // of the Mentor controller pub const PP_ECNT_S: uint = 8; //***************************************************************************** // // The following are defines for the bit fields in the USB_O_PC register. // //***************************************************************************** pub const PC_ULPIEN: u32 = 0x00010000; // ULPI Enable //***************************************************************************** // // The following are defines for the bit fields in the USB_O_CC register. // //***************************************************************************** pub const CC_CLKEN: u32 = 0x00000200; // USB Clock Enable pub const CC_CSD: u32 = 0x00000100; // Clock Source/Direction pub const CC_CLKDIV_M: u32 = 0x0000000F; // PLL Clock Divisor pub const CC_CLKDIV_S: uint = 0;
{{#each arguments~}} {{#if ../arg_names}}{{lookup ../arg_names @index}}{{else}}{{this.[0]}}{{/if}}, {{~/each}}
use std::env; use std::fs::File; use std::io::{self, BufRead, BufReader}; fn main() -> Result<(), io::Error> { let args: Vec<String> = env::args().collect(); let reader = BufReader::new(File::open(&args[1]).expect("File::open failed")); let list = reader .lines() .map(|x| { x.expect("reader.lines failed") .parse::<i64>() .expect("parse failed") }) .collect::<Vec<i64>>(); let mut sum_hit = 0; for i in 25..list.len() { let preamble = &list[i - 25..i]; if !find_sum(preamble, list[i]) { sum_hit = list[i]; break; } } if &args[2] == "1" { println!("{}", sum_hit); } else if &args[2] == "2" { let series = find_continuous_sum(&list, sum_hit); if let Some(mut series) = series { series.sort(); println!("{}", series[0] + series[series.len() - 1]) } } Ok(()) } fn find_sum(list: &[i64], n: i64) -> bool { for i in 0..list.len() - 1 { for j in i + 1..list.len() { if list[i] + list[j] == n { return true; } } } return false; } fn find_continuous_sum(list: &[i64], target: i64) -> Option<Vec<i64>> { let mut series = Vec::<i64>::new(); for i in 0..list.len() - 1 { let mut sum = list[i]; series.push(list[i]); for j in i + 1..list.len() { if sum + list[j] > target { break; } sum += list[j]; series.push(list[j]); } if sum == target { return Some(series); } series.clear(); } return None; } #[cfg(test)] mod tests { use super::*; #[test] fn test_stuff() { let list = vec![1, 2, 3]; assert_eq!(find_sum(&list, 3), true); assert_eq!(find_sum(&list, 5), true); assert_eq!(find_sum(&list, 4), true); assert_eq!(find_sum(&list, 6), false); } }
use super::PyMethod; use crate::{ builtins::{pystr::AsPyStr, PyBaseExceptionRef, PyList, PyStrInterned}, function::IntoFuncArgs, identifier, object::{AsObject, PyObject, PyObjectRef, PyResult}, vm::VirtualMachine, }; /// PyObject support impl VirtualMachine { #[track_caller] #[cold] fn _py_panic_failed(&self, exc: PyBaseExceptionRef, msg: &str) -> ! { #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))] { let show_backtrace = std::env::var_os("RUST_BACKTRACE").map_or(cfg!(target_os = "wasi"), |v| &v != "0"); let after = if show_backtrace { self.print_exception(exc); "exception backtrace above" } else { "run with RUST_BACKTRACE=1 to see Python backtrace" }; panic!("{msg}; {after}") } #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] { use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console)] fn error(s: &str); } let mut s = String::new(); self.write_exception(&mut s, &exc).unwrap(); error(&s); panic!("{}; exception backtrace above", msg) } } #[track_caller] pub fn unwrap_pyresult<T>(&self, result: PyResult<T>) -> T { match result { Ok(x) => x, Err(exc) => { self._py_panic_failed(exc, "called `vm.unwrap_pyresult()` on an `Err` value") } } } #[track_caller] pub fn expect_pyresult<T>(&self, result: PyResult<T>, msg: &str) -> T { match result { Ok(x) => x, Err(exc) => self._py_panic_failed(exc, msg), } } /// Test whether a python object is `None`. pub fn is_none(&self, obj: &PyObject) -> bool { obj.is(&self.ctx.none) } pub fn option_if_none(&self, obj: PyObjectRef) -> Option<PyObjectRef> { if self.is_none(&obj) { None } else { Some(obj) } } pub fn unwrap_or_none(&self, obj: Option<PyObjectRef>) -> PyObjectRef { obj.unwrap_or_else(|| self.ctx.none()) } pub fn call_get_descriptor_specific( &self, descr: &PyObject, obj: Option<PyObjectRef>, cls: Option<PyObjectRef>, ) -> Option<PyResult> { let descr_get = descr .class() .mro_find_map(|cls| cls.slots.descr_get.load())?; Some(descr_get(descr.to_owned(), obj, cls, self)) } pub fn call_get_descriptor(&self, descr: &PyObject, obj: PyObjectRef) -> Option<PyResult> { let cls = obj.class().to_owned().into(); self.call_get_descriptor_specific(descr, Some(obj), Some(cls)) } pub fn call_if_get_descriptor(&self, attr: &PyObject, obj: PyObjectRef) -> PyResult { self.call_get_descriptor(attr, obj) .unwrap_or_else(|| Ok(attr.to_owned())) } #[inline] pub fn call_method<T>(&self, obj: &PyObject, method_name: &str, args: T) -> PyResult where T: IntoFuncArgs, { flame_guard!(format!("call_method({:?})", method_name)); let dynamic_name; let name = match self.ctx.interned_str(method_name) { Some(name) => name.as_pystr(&self.ctx), None => { dynamic_name = self.ctx.new_str(method_name); &dynamic_name } }; PyMethod::get(obj.to_owned(), name, self)?.invoke(args, self) } pub fn dir(&self, obj: Option<PyObjectRef>) -> PyResult<PyList> { let seq = match obj { Some(obj) => self .get_special_method(&obj, identifier!(self, __dir__))? .ok_or_else(|| self.new_type_error("object does not provide __dir__".to_owned()))? .invoke((), self)?, None => self.call_method( self.current_locals()?.as_object(), identifier!(self, keys).as_str(), (), )?, }; let items: Vec<_> = seq.try_to_value(self)?; let lst = PyList::from(items); lst.sort(Default::default(), self)?; Ok(lst) } #[inline] pub(crate) fn get_special_method( &self, obj: &PyObject, method: &'static PyStrInterned, ) -> PyResult<Option<PyMethod>> { PyMethod::get_special::<false>(obj, method, self) } /// NOT PUBLIC API #[doc(hidden)] pub fn call_special_method( &self, obj: &PyObject, method: &'static PyStrInterned, args: impl IntoFuncArgs, ) -> PyResult { self.get_special_method(obj, method)? .ok_or_else(|| self.new_attribute_error(method.as_str().to_owned()))? .invoke(args, self) } #[deprecated(note = "in favor of `obj.call(args, vm)`")] pub fn invoke(&self, obj: &impl AsObject, args: impl IntoFuncArgs) -> PyResult { obj.as_object().call(args, self) } }
use chip::rom::getfun; //***************************************************************************** // // The following are values that can be passed to the // SysCtlPeripheralPresent(), SysCtlPeripheralEnable(), // SysCtlPeripheralDisable(), and SysCtlPeripheralReset() APIs as the // ui32Peripheral parameter. The peripherals in the fourth group (upper nibble // is 3) can only be used with the SysCtlPeripheralPresent() API. // //***************************************************************************** pub const PERIPH_ADC0: u32 = 0xf0003800; // ADC 0 pub const PERIPH_ADC1: u32 = 0xf0003801; // ADC 1 pub const PERIPH_CAN0: u32 = 0xf0003400; // CAN 0 pub const PERIPH_CAN1: u32 = 0xf0003401; // CAN 1 pub const PERIPH_COMP0: u32 = 0xf0003c00; // Analog Comparator Module 0 pub const PERIPH_EMAC0: u32 = 0xf0009c00; // Ethernet MAC0 pub const PERIPH_EPHY0: u32 = 0xf0003000; // Ethernet PHY0 pub const PERIPH_EPI0: u32 = 0xf0001000; // EPI0 pub const PERIPH_GPIOA: u32 = 0xf0000800; // GPIO A pub const PERIPH_GPIOB: u32 = 0xf0000801; // GPIO B pub const PERIPH_GPIOC: u32 = 0xf0000802; // GPIO C pub const PERIPH_GPIOD: u32 = 0xf0000803; // GPIO D pub const PERIPH_GPIOE: u32 = 0xf0000804; // GPIO E pub const PERIPH_GPIOF: u32 = 0xf0000805; // GPIO F pub const PERIPH_GPIOG: u32 = 0xf0000806; // GPIO G pub const PERIPH_GPIOH: u32 = 0xf0000807; // GPIO H pub const PERIPH_GPIOJ: u32 = 0xf0000808; // GPIO J pub const PERIPH_HIBERNATE: u32 = 0xf0001400; // Hibernation module pub const PERIPH_CCM0: u32 = 0xf0007400; // CCM 0 pub const PERIPH_EEPROM0: u32 = 0xf0005800; // EEPROM 0 pub const PERIPH_FAN0: u32 = 0xf0005400; // FAN 0 pub const PERIPH_FAN1: u32 = 0xf0005401; // FAN 1 pub const PERIPH_GPIOK: u32 = 0xf0000809; // GPIO K pub const PERIPH_GPIOL: u32 = 0xf000080a; // GPIO L pub const PERIPH_GPIOM: u32 = 0xf000080b; // GPIO M pub const PERIPH_GPION: u32 = 0xf000080c; // GPIO N pub const PERIPH_GPIOP: u32 = 0xf000080d; // GPIO P pub const PERIPH_GPIOQ: u32 = 0xf000080e; // GPIO Q pub const PERIPH_GPIOR: u32 = 0xf000080f; // GPIO R pub const PERIPH_GPIOS: u32 = 0xf0000810; // GPIO S pub const PERIPH_GPIOT: u32 = 0xf0000811; // GPIO T pub const PERIPH_I2C0: u32 = 0xf0002000; // I2C 0 pub const PERIPH_I2C1: u32 = 0xf0002001; // I2C 1 pub const PERIPH_I2C2: u32 = 0xf0002002; // I2C 2 pub const PERIPH_I2C3: u32 = 0xf0002003; // I2C 3 pub const PERIPH_I2C4: u32 = 0xf0002004; // I2C 4 pub const PERIPH_I2C5: u32 = 0xf0002005; // I2C 5 pub const PERIPH_I2C6: u32 = 0xf0002006; // I2C 6 pub const PERIPH_I2C7: u32 = 0xf0002007; // I2C 7 pub const PERIPH_I2C8: u32 = 0xf0002008; // I2C 8 pub const PERIPH_I2C9: u32 = 0xf0002009; // I2C 9 pub const PERIPH_LCD0: u32 = 0xf0009000; // LCD 0 pub const PERIPH_ONEWIRE0: u32 = 0xf0009800; // One Wire 0 pub const PERIPH_PWM0: u32 = 0xf0004000; // PWM 0 pub const PERIPH_PWM1: u32 = 0xf0004001; // PWM 1 pub const PERIPH_QEI0: u32 = 0xf0004400; // QEI 0 pub const PERIPH_QEI1: u32 = 0xf0004401; // QEI 1 pub const PERIPH_SSI0: u32 = 0xf0001c00; // SSI 0 pub const PERIPH_SSI1: u32 = 0xf0001c01; // SSI 1 pub const PERIPH_SSI2: u32 = 0xf0001c02; // SSI 2 pub const PERIPH_SSI3: u32 = 0xf0001c03; // SSI 3 pub const PERIPH_TIMER0: u32 = 0xf0000400; // Timer 0 pub const PERIPH_TIMER1: u32 = 0xf0000401; // Timer 1 pub const PERIPH_TIMER2: u32 = 0xf0000402; // Timer 2 pub const PERIPH_TIMER3: u32 = 0xf0000403; // Timer 3 pub const PERIPH_TIMER4: u32 = 0xf0000404; // Timer 4 pub const PERIPH_TIMER5: u32 = 0xf0000405; // Timer 5 pub const PERIPH_TIMER6: u32 = 0xf0000406; // Timer 6 pub const PERIPH_TIMER7: u32 = 0xf0000407; // Timer 7 pub const PERIPH_UART0: u32 = 0xf0001800; // UART 0 pub const PERIPH_UART1: u32 = 0xf0001801; // UART 1 pub const PERIPH_UART2: u32 = 0xf0001802; // UART 2 pub const PERIPH_UART3: u32 = 0xf0001803; // UART 3 pub const PERIPH_UART4: u32 = 0xf0001804; // UART 4 pub const PERIPH_UART5: u32 = 0xf0001805; // UART 5 pub const PERIPH_UART6: u32 = 0xf0001806; // UART 6 pub const PERIPH_UART7: u32 = 0xf0001807; // UART 7 pub const PERIPH_UDMA: u32 = 0xf0000c00; // uDMA pub const PERIPH_USB0: u32 = 0xf0002800; // USB 0 pub const PERIPH_WDOG0: u32 = 0xf0000000; // Watchdog 0 pub const PERIPH_WDOG1: u32 = 0xf0000001; // Watchdog 1 pub const PERIPH_WTIMER0: u32 = 0xf0005c00; // Wide Timer 0 pub const PERIPH_WTIMER1: u32 = 0xf0005c01; // Wide Timer 1 pub const PERIPH_WTIMER2: u32 = 0xf0005c02; // Wide Timer 2 pub const PERIPH_WTIMER3: u32 = 0xf0005c03; // Wide Timer 3 pub const PERIPH_WTIMER4: u32 = 0xf0005c04; // Wide Timer 4 pub const PERIPH_WTIMER5: u32 = 0xf0005c05; // Wide Timer 5 //***************************************************************************** // // The following are values that can be passed to the SysCtlLDOSleepSet() and // SysCtlLDODeepSleepSet() APIs as the ui32Voltage value, or returned by the // SysCtlLDOSleepGet() and SysCtlLDODeepSleepGet() APIs. // //***************************************************************************** pub const LDO_0_90V: u32 = 0x80000012; // LDO output of 0.90V pub const LDO_0_95V: u32 = 0x80000013; // LDO output of 0.95V pub const LDO_1_00V: u32 = 0x80000014; // LDO output of 1.00V pub const LDO_1_05V: u32 = 0x80000015; // LDO output of 1.05V pub const LDO_1_10V: u32 = 0x80000016; // LDO output of 1.10V pub const LDO_1_15V: u32 = 0x80000017; // LDO output of 1.15V pub const LDO_1_20V: u32 = 0x80000018; // LDO output of 1.20V //***************************************************************************** // // The following are values that can be passed to the SysCtlIntEnable(), // SysCtlIntDisable(), and SysCtlIntClear() APIs, or returned in the bit mask // by the SysCtlIntStatus() API. // //***************************************************************************** pub const INT_BOR0: u32 = 0x00000800; // VDD under BOR0 pub const INT_VDDA_OK: u32 = 0x00000400; // VDDA Power OK pub const INT_MOSC_PUP: u32 = 0x00000100; // MOSC power-up interrupt pub const INT_USBPLL_LOCK: u32 = 0x00000080; // USB PLL lock interrupt pub const INT_PLL_LOCK: u32 = 0x00000040; // PLL lock interrupt pub const INT_MOSC_FAIL: u32 = 0x00000008; // Main oscillator failure int pub const INT_BOR1: u32 = 0x00000002; // VDD under BOR1 pub const INT_BOR: u32 = 0x00000002; // Brown out interrupt //***************************************************************************** // // The following are values that can be passed to the SysCtlResetCauseClear() // API or returned by the SysCtlResetCauseGet() API. // //***************************************************************************** pub const CAUSE_HSRVREQ: u32 = 0x00001000; // Hardware System Service Request pub const CAUSE_HIB: u32 = 0x00000040; // Hibernate reset pub const CAUSE_WDOG1: u32 = 0x00000020; // Watchdog 1 reset pub const CAUSE_SW: u32 = 0x00000010; // Software reset pub const CAUSE_WDOG0: u32 = 0x00000008; // Watchdog 0 reset pub const CAUSE_BOR: u32 = 0x00000004; // Brown-out reset pub const CAUSE_POR: u32 = 0x00000002; // Power on reset pub const CAUSE_EXT: u32 = 0x00000001; // External reset //***************************************************************************** // // The following are values that can be passed to the SysCtlBrownOutConfigSet() // API as the ui32Config parameter. // //***************************************************************************** pub const BOR_RESET: u32 = 0x00000002; // Reset instead of interrupting pub const BOR_RESAMPLE: u32 = 0x00000001; // Resample BOR before asserting //***************************************************************************** // // The following are values that can be passed to the SysCtlPWMClockSet() API // as the ui32Config parameter, and can be returned by the SysCtlPWMClockGet() // API. // //***************************************************************************** pub const PWMDIV_1: u32 = 0x00000000; // PWM clock is processor clock /1 pub const PWMDIV_2: u32 = 0x00100000; // PWM clock is processor clock /2 pub const PWMDIV_4: u32 = 0x00120000; // PWM clock is processor clock /4 pub const PWMDIV_8: u32 = 0x00140000; // PWM clock is processor clock /8 pub const PWMDIV_16: u32 = 0x00160000; // PWM clock is processor clock /16 pub const PWMDIV_32: u32 = 0x00180000; // PWM clock is processor clock /32 pub const PWMDIV_64: u32 = 0x001A0000; // PWM clock is processor clock /64 //***************************************************************************** // // The following are values that can be passed to the SysCtlClockSet() API as // the ui32Config parameter. // //***************************************************************************** pub const SYSDIV_1: u32 = 0x07800000; // Processor clock is osc/pll /1 pub const SYSDIV_2: u32 = 0x00C00000; // Processor clock is osc/pll /2 pub const SYSDIV_3: u32 = 0x01400000; // Processor clock is osc/pll /3 pub const SYSDIV_4: u32 = 0x01C00000; // Processor clock is osc/pll /4 pub const SYSDIV_5: u32 = 0x02400000; // Processor clock is osc/pll /5 pub const SYSDIV_6: u32 = 0x02C00000; // Processor clock is osc/pll /6 pub const SYSDIV_7: u32 = 0x03400000; // Processor clock is osc/pll /7 pub const SYSDIV_8: u32 = 0x03C00000; // Processor clock is osc/pll /8 pub const SYSDIV_9: u32 = 0x04400000; // Processor clock is osc/pll /9 pub const SYSDIV_10: u32 = 0x04C00000; // Processor clock is osc/pll /10 pub const SYSDIV_11: u32 = 0x05400000; // Processor clock is osc/pll /11 pub const SYSDIV_12: u32 = 0x05C00000; // Processor clock is osc/pll /12 pub const SYSDIV_13: u32 = 0x06400000; // Processor clock is osc/pll /13 pub const SYSDIV_14: u32 = 0x06C00000; // Processor clock is osc/pll /14 pub const SYSDIV_15: u32 = 0x07400000; // Processor clock is osc/pll /15 pub const SYSDIV_16: u32 = 0x07C00000; // Processor clock is osc/pll /16 pub const SYSDIV_17: u32 = 0x88400000; // Processor clock is osc/pll /17 pub const SYSDIV_18: u32 = 0x88C00000; // Processor clock is osc/pll /18 pub const SYSDIV_19: u32 = 0x89400000; // Processor clock is osc/pll /19 pub const SYSDIV_20: u32 = 0x89C00000; // Processor clock is osc/pll /20 pub const SYSDIV_21: u32 = 0x8A400000; // Processor clock is osc/pll /21 pub const SYSDIV_22: u32 = 0x8AC00000; // Processor clock is osc/pll /22 pub const SYSDIV_23: u32 = 0x8B400000; // Processor clock is osc/pll /23 pub const SYSDIV_24: u32 = 0x8BC00000; // Processor clock is osc/pll /24 pub const SYSDIV_25: u32 = 0x8C400000; // Processor clock is osc/pll /25 pub const SYSDIV_26: u32 = 0x8CC00000; // Processor clock is osc/pll /26 pub const SYSDIV_27: u32 = 0x8D400000; // Processor clock is osc/pll /27 pub const SYSDIV_28: u32 = 0x8DC00000; // Processor clock is osc/pll /28 pub const SYSDIV_29: u32 = 0x8E400000; // Processor clock is osc/pll /29 pub const SYSDIV_30: u32 = 0x8EC00000; // Processor clock is osc/pll /30 pub const SYSDIV_31: u32 = 0x8F400000; // Processor clock is osc/pll /31 pub const SYSDIV_32: u32 = 0x8FC00000; // Processor clock is osc/pll /32 pub const SYSDIV_33: u32 = 0x90400000; // Processor clock is osc/pll /33 pub const SYSDIV_34: u32 = 0x90C00000; // Processor clock is osc/pll /34 pub const SYSDIV_35: u32 = 0x91400000; // Processor clock is osc/pll /35 pub const SYSDIV_36: u32 = 0x91C00000; // Processor clock is osc/pll /36 pub const SYSDIV_37: u32 = 0x92400000; // Processor clock is osc/pll /37 pub const SYSDIV_38: u32 = 0x92C00000; // Processor clock is osc/pll /38 pub const SYSDIV_39: u32 = 0x93400000; // Processor clock is osc/pll /39 pub const SYSDIV_40: u32 = 0x93C00000; // Processor clock is osc/pll /40 pub const SYSDIV_41: u32 = 0x94400000; // Processor clock is osc/pll /41 pub const SYSDIV_42: u32 = 0x94C00000; // Processor clock is osc/pll /42 pub const SYSDIV_43: u32 = 0x95400000; // Processor clock is osc/pll /43 pub const SYSDIV_44: u32 = 0x95C00000; // Processor clock is osc/pll /44 pub const SYSDIV_45: u32 = 0x96400000; // Processor clock is osc/pll /45 pub const SYSDIV_46: u32 = 0x96C00000; // Processor clock is osc/pll /46 pub const SYSDIV_47: u32 = 0x97400000; // Processor clock is osc/pll /47 pub const SYSDIV_48: u32 = 0x97C00000; // Processor clock is osc/pll /48 pub const SYSDIV_49: u32 = 0x98400000; // Processor clock is osc/pll /49 pub const SYSDIV_50: u32 = 0x98C00000; // Processor clock is osc/pll /50 pub const SYSDIV_51: u32 = 0x99400000; // Processor clock is osc/pll /51 pub const SYSDIV_52: u32 = 0x99C00000; // Processor clock is osc/pll /52 pub const SYSDIV_53: u32 = 0x9A400000; // Processor clock is osc/pll /53 pub const SYSDIV_54: u32 = 0x9AC00000; // Processor clock is osc/pll /54 pub const SYSDIV_55: u32 = 0x9B400000; // Processor clock is osc/pll /55 pub const SYSDIV_56: u32 = 0x9BC00000; // Processor clock is osc/pll /56 pub const SYSDIV_57: u32 = 0x9C400000; // Processor clock is osc/pll /57 pub const SYSDIV_58: u32 = 0x9CC00000; // Processor clock is osc/pll /58 pub const SYSDIV_59: u32 = 0x9D400000; // Processor clock is osc/pll /59 pub const SYSDIV_60: u32 = 0x9DC00000; // Processor clock is osc/pll /60 pub const SYSDIV_61: u32 = 0x9E400000; // Processor clock is osc/pll /61 pub const SYSDIV_62: u32 = 0x9EC00000; // Processor clock is osc/pll /62 pub const SYSDIV_63: u32 = 0x9F400000; // Processor clock is osc/pll /63 pub const SYSDIV_64: u32 = 0x9FC00000; // Processor clock is osc/pll /64 pub const SYSDIV_2_5: u32 = 0xC1000000; // Processor clock is pll / 2.5 pub const SYSDIV_3_5: u32 = 0xC1800000; // Processor clock is pll / 3.5 pub const SYSDIV_4_5: u32 = 0xC2000000; // Processor clock is pll / 4.5 pub const SYSDIV_5_5: u32 = 0xC2800000; // Processor clock is pll / 5.5 pub const SYSDIV_6_5: u32 = 0xC3000000; // Processor clock is pll / 6.5 pub const SYSDIV_7_5: u32 = 0xC3800000; // Processor clock is pll / 7.5 pub const SYSDIV_8_5: u32 = 0xC4000000; // Processor clock is pll / 8.5 pub const SYSDIV_9_5: u32 = 0xC4800000; // Processor clock is pll / 9.5 pub const SYSDIV_10_5: u32 = 0xC5000000; // Processor clock is pll / 10.5 pub const SYSDIV_11_5: u32 = 0xC5800000; // Processor clock is pll / 11.5 pub const SYSDIV_12_5: u32 = 0xC6000000; // Processor clock is pll / 12.5 pub const SYSDIV_13_5: u32 = 0xC6800000; // Processor clock is pll / 13.5 pub const SYSDIV_14_5: u32 = 0xC7000000; // Processor clock is pll / 14.5 pub const SYSDIV_15_5: u32 = 0xC7800000; // Processor clock is pll / 15.5 pub const SYSDIV_16_5: u32 = 0xC8000000; // Processor clock is pll / 16.5 pub const SYSDIV_17_5: u32 = 0xC8800000; // Processor clock is pll / 17.5 pub const SYSDIV_18_5: u32 = 0xC9000000; // Processor clock is pll / 18.5 pub const SYSDIV_19_5: u32 = 0xC9800000; // Processor clock is pll / 19.5 pub const SYSDIV_20_5: u32 = 0xCA000000; // Processor clock is pll / 20.5 pub const SYSDIV_21_5: u32 = 0xCA800000; // Processor clock is pll / 21.5 pub const SYSDIV_22_5: u32 = 0xCB000000; // Processor clock is pll / 22.5 pub const SYSDIV_23_5: u32 = 0xCB800000; // Processor clock is pll / 23.5 pub const SYSDIV_24_5: u32 = 0xCC000000; // Processor clock is pll / 24.5 pub const SYSDIV_25_5: u32 = 0xCC800000; // Processor clock is pll / 25.5 pub const SYSDIV_26_5: u32 = 0xCD000000; // Processor clock is pll / 26.5 pub const SYSDIV_27_5: u32 = 0xCD800000; // Processor clock is pll / 27.5 pub const SYSDIV_28_5: u32 = 0xCE000000; // Processor clock is pll / 28.5 pub const SYSDIV_29_5: u32 = 0xCE800000; // Processor clock is pll / 29.5 pub const SYSDIV_30_5: u32 = 0xCF000000; // Processor clock is pll / 30.5 pub const SYSDIV_31_5: u32 = 0xCF800000; // Processor clock is pll / 31.5 pub const SYSDIV_32_5: u32 = 0xD0000000; // Processor clock is pll / 32.5 pub const SYSDIV_33_5: u32 = 0xD0800000; // Processor clock is pll / 33.5 pub const SYSDIV_34_5: u32 = 0xD1000000; // Processor clock is pll / 34.5 pub const SYSDIV_35_5: u32 = 0xD1800000; // Processor clock is pll / 35.5 pub const SYSDIV_36_5: u32 = 0xD2000000; // Processor clock is pll / 36.5 pub const SYSDIV_37_5: u32 = 0xD2800000; // Processor clock is pll / 37.5 pub const SYSDIV_38_5: u32 = 0xD3000000; // Processor clock is pll / 38.5 pub const SYSDIV_39_5: u32 = 0xD3800000; // Processor clock is pll / 39.5 pub const SYSDIV_40_5: u32 = 0xD4000000; // Processor clock is pll / 40.5 pub const SYSDIV_41_5: u32 = 0xD4800000; // Processor clock is pll / 41.5 pub const SYSDIV_42_5: u32 = 0xD5000000; // Processor clock is pll / 42.5 pub const SYSDIV_43_5: u32 = 0xD5800000; // Processor clock is pll / 43.5 pub const SYSDIV_44_5: u32 = 0xD6000000; // Processor clock is pll / 44.5 pub const SYSDIV_45_5: u32 = 0xD6800000; // Processor clock is pll / 45.5 pub const SYSDIV_46_5: u32 = 0xD7000000; // Processor clock is pll / 46.5 pub const SYSDIV_47_5: u32 = 0xD7800000; // Processor clock is pll / 47.5 pub const SYSDIV_48_5: u32 = 0xD8000000; // Processor clock is pll / 48.5 pub const SYSDIV_49_5: u32 = 0xD8800000; // Processor clock is pll / 49.5 pub const SYSDIV_50_5: u32 = 0xD9000000; // Processor clock is pll / 50.5 pub const SYSDIV_51_5: u32 = 0xD9800000; // Processor clock is pll / 51.5 pub const SYSDIV_52_5: u32 = 0xDA000000; // Processor clock is pll / 52.5 pub const SYSDIV_53_5: u32 = 0xDA800000; // Processor clock is pll / 53.5 pub const SYSDIV_54_5: u32 = 0xDB000000; // Processor clock is pll / 54.5 pub const SYSDIV_55_5: u32 = 0xDB800000; // Processor clock is pll / 55.5 pub const SYSDIV_56_5: u32 = 0xDC000000; // Processor clock is pll / 56.5 pub const SYSDIV_57_5: u32 = 0xDC800000; // Processor clock is pll / 57.5 pub const SYSDIV_58_5: u32 = 0xDD000000; // Processor clock is pll / 58.5 pub const SYSDIV_59_5: u32 = 0xDD800000; // Processor clock is pll / 59.5 pub const SYSDIV_60_5: u32 = 0xDE000000; // Processor clock is pll / 60.5 pub const SYSDIV_61_5: u32 = 0xDE800000; // Processor clock is pll / 61.5 pub const SYSDIV_62_5: u32 = 0xDF000000; // Processor clock is pll / 62.5 pub const SYSDIV_63_5: u32 = 0xDF800000; // Processor clock is pll / 63.5 pub const CFG_VCO_480: u32 = 0xF1000000; // VCO is 480 MHz pub const CFG_VCO_320: u32 = 0xF0000000; // VCO is 320 MHz pub const USE_PLL: u32 = 0x00000000; // System clock is the PLL clock pub const USE_OSC: u32 = 0x00003800; // System clock is the osc clock pub const XTAL_1MHZ: u32 = 0x00000000; // External crystal is 1MHz pub const XTAL_1_84MHZ: u32 = 0x00000040; // External crystal is 1.8432MHz pub const XTAL_2MHZ: u32 = 0x00000080; // External crystal is 2MHz pub const XTAL_2_45MHZ: u32 = 0x000000C0; // External crystal is 2.4576MHz pub const XTAL_3_57MHZ: u32 = 0x00000100; // External crystal is 3.579545MHz pub const XTAL_3_68MHZ: u32 = 0x00000140; // External crystal is 3.6864MHz pub const XTAL_4MHZ: u32 = 0x00000180; // External crystal is 4MHz pub const XTAL_4_09MHZ: u32 = 0x000001C0; // External crystal is 4.096MHz pub const XTAL_4_91MHZ: u32 = 0x00000200; // External crystal is 4.9152MHz pub const XTAL_5MHZ: u32 = 0x00000240; // External crystal is 5MHz pub const XTAL_5_12MHZ: u32 = 0x00000280; // External crystal is 5.12MHz pub const XTAL_6MHZ: u32 = 0x000002C0; // External crystal is 6MHz pub const XTAL_6_14MHZ: u32 = 0x00000300; // External crystal is 6.144MHz pub const XTAL_7_37MHZ: u32 = 0x00000340; // External crystal is 7.3728MHz pub const XTAL_8MHZ: u32 = 0x00000380; // External crystal is 8MHz pub const XTAL_8_19MHZ: u32 = 0x000003C0; // External crystal is 8.192MHz pub const XTAL_10MHZ: u32 = 0x00000400; // External crystal is 10 MHz pub const XTAL_12MHZ: u32 = 0x00000440; // External crystal is 12 MHz pub const XTAL_12_2MHZ: u32 = 0x00000480; // External crystal is 12.288 MHz pub const XTAL_13_5MHZ: u32 = 0x000004C0; // External crystal is 13.56 MHz pub const XTAL_14_3MHZ: u32 = 0x00000500; // External crystal is 14.31818 MHz pub const XTAL_16MHZ: u32 = 0x00000540; // External crystal is 16 MHz pub const XTAL_16_3MHZ: u32 = 0x00000580; // External crystal is 16.384 MHz pub const XTAL_18MHZ: u32 = 0x000005C0; // External crystal is 18.0 MHz pub const XTAL_20MHZ: u32 = 0x00000600; // External crystal is 20.0 MHz pub const XTAL_24MHZ: u32 = 0x00000640; // External crystal is 24.0 MHz pub const XTAL_25MHZ: u32 = 0x00000680; // External crystal is 25.0 MHz pub const OSC_MAIN: u32 = 0x00000000; // Osc source is main osc pub const OSC_INT: u32 = 0x00000010; // Osc source is int. osc pub const OSC_INT4: u32 = 0x00000020; // Osc source is int. osc /4 pub const OSC_INT30: u32 = 0x00000030; // Osc source is int. 30 KHz pub const OSC_EXT32: u32 = 0x80000038; // Osc source is ext. 32 KHz pub const INT_OSC_DIS: u32 = 0x00000002; // Disable internal oscillator pub const MAIN_OSC_DIS: u32 = 0x00000001; // Disable main oscillator //***************************************************************************** // // The following are values that can be passed to the SysCtlDeepSleepClockSet() // API as the ui32Config parameter. // //***************************************************************************** pub const DSLP_DIV_1: u32 = 0x00000000; // Deep-sleep clock is osc /1 pub const DSLP_DIV_2: u32 = 0x00800000; // Deep-sleep clock is osc /2 pub const DSLP_DIV_3: u32 = 0x01000000; // Deep-sleep clock is osc /3 pub const DSLP_DIV_4: u32 = 0x01800000; // Deep-sleep clock is osc /4 pub const DSLP_DIV_5: u32 = 0x02000000; // Deep-sleep clock is osc /5 pub const DSLP_DIV_6: u32 = 0x02800000; // Deep-sleep clock is osc /6 pub const DSLP_DIV_7: u32 = 0x03000000; // Deep-sleep clock is osc /7 pub const DSLP_DIV_8: u32 = 0x03800000; // Deep-sleep clock is osc /8 pub const DSLP_DIV_9: u32 = 0x04000000; // Deep-sleep clock is osc /9 pub const DSLP_DIV_10: u32 = 0x04800000; // Deep-sleep clock is osc /10 pub const DSLP_DIV_11: u32 = 0x05000000; // Deep-sleep clock is osc /11 pub const DSLP_DIV_12: u32 = 0x05800000; // Deep-sleep clock is osc /12 pub const DSLP_DIV_13: u32 = 0x06000000; // Deep-sleep clock is osc /13 pub const DSLP_DIV_14: u32 = 0x06800000; // Deep-sleep clock is osc /14 pub const DSLP_DIV_15: u32 = 0x07000000; // Deep-sleep clock is osc /15 pub const DSLP_DIV_16: u32 = 0x07800000; // Deep-sleep clock is osc /16 pub const DSLP_DIV_17: u32 = 0x08000000; // Deep-sleep clock is osc /17 pub const DSLP_DIV_18: u32 = 0x08800000; // Deep-sleep clock is osc /18 pub const DSLP_DIV_19: u32 = 0x09000000; // Deep-sleep clock is osc /19 pub const DSLP_DIV_20: u32 = 0x09800000; // Deep-sleep clock is osc /20 pub const DSLP_DIV_21: u32 = 0x0A000000; // Deep-sleep clock is osc /21 pub const DSLP_DIV_22: u32 = 0x0A800000; // Deep-sleep clock is osc /22 pub const DSLP_DIV_23: u32 = 0x0B000000; // Deep-sleep clock is osc /23 pub const DSLP_DIV_24: u32 = 0x0B800000; // Deep-sleep clock is osc /24 pub const DSLP_DIV_25: u32 = 0x0C000000; // Deep-sleep clock is osc /25 pub const DSLP_DIV_26: u32 = 0x0C800000; // Deep-sleep clock is osc /26 pub const DSLP_DIV_27: u32 = 0x0D000000; // Deep-sleep clock is osc /27 pub const DSLP_DIV_28: u32 = 0x0D800000; // Deep-sleep clock is osc /28 pub const DSLP_DIV_29: u32 = 0x0E000000; // Deep-sleep clock is osc /29 pub const DSLP_DIV_30: u32 = 0x0E800000; // Deep-sleep clock is osc /30 pub const DSLP_DIV_31: u32 = 0x0F000000; // Deep-sleep clock is osc /31 pub const DSLP_DIV_32: u32 = 0x0F800000; // Deep-sleep clock is osc /32 pub const DSLP_DIV_33: u32 = 0x10000000; // Deep-sleep clock is osc /33 pub const DSLP_DIV_34: u32 = 0x10800000; // Deep-sleep clock is osc /34 pub const DSLP_DIV_35: u32 = 0x11000000; // Deep-sleep clock is osc /35 pub const DSLP_DIV_36: u32 = 0x11800000; // Deep-sleep clock is osc /36 pub const DSLP_DIV_37: u32 = 0x12000000; // Deep-sleep clock is osc /37 pub const DSLP_DIV_38: u32 = 0x12800000; // Deep-sleep clock is osc /38 pub const DSLP_DIV_39: u32 = 0x13000000; // Deep-sleep clock is osc /39 pub const DSLP_DIV_40: u32 = 0x13800000; // Deep-sleep clock is osc /40 pub const DSLP_DIV_41: u32 = 0x14000000; // Deep-sleep clock is osc /41 pub const DSLP_DIV_42: u32 = 0x14800000; // Deep-sleep clock is osc /42 pub const DSLP_DIV_43: u32 = 0x15000000; // Deep-sleep clock is osc /43 pub const DSLP_DIV_44: u32 = 0x15800000; // Deep-sleep clock is osc /44 pub const DSLP_DIV_45: u32 = 0x16000000; // Deep-sleep clock is osc /45 pub const DSLP_DIV_46: u32 = 0x16800000; // Deep-sleep clock is osc /46 pub const DSLP_DIV_47: u32 = 0x17000000; // Deep-sleep clock is osc /47 pub const DSLP_DIV_48: u32 = 0x17800000; // Deep-sleep clock is osc /48 pub const DSLP_DIV_49: u32 = 0x18000000; // Deep-sleep clock is osc /49 pub const DSLP_DIV_50: u32 = 0x18800000; // Deep-sleep clock is osc /50 pub const DSLP_DIV_51: u32 = 0x19000000; // Deep-sleep clock is osc /51 pub const DSLP_DIV_52: u32 = 0x19800000; // Deep-sleep clock is osc /52 pub const DSLP_DIV_53: u32 = 0x1A000000; // Deep-sleep clock is osc /53 pub const DSLP_DIV_54: u32 = 0x1A800000; // Deep-sleep clock is osc /54 pub const DSLP_DIV_55: u32 = 0x1B000000; // Deep-sleep clock is osc /55 pub const DSLP_DIV_56: u32 = 0x1B800000; // Deep-sleep clock is osc /56 pub const DSLP_DIV_57: u32 = 0x1C000000; // Deep-sleep clock is osc /57 pub const DSLP_DIV_58: u32 = 0x1C800000; // Deep-sleep clock is osc /58 pub const DSLP_DIV_59: u32 = 0x1D000000; // Deep-sleep clock is osc /59 pub const DSLP_DIV_60: u32 = 0x1D800000; // Deep-sleep clock is osc /60 pub const DSLP_DIV_61: u32 = 0x1E000000; // Deep-sleep clock is osc /61 pub const DSLP_DIV_62: u32 = 0x1E800000; // Deep-sleep clock is osc /62 pub const DSLP_DIV_63: u32 = 0x1F000000; // Deep-sleep clock is osc /63 pub const DSLP_DIV_64: u32 = 0x1F800000; // Deep-sleep clock is osc /64 pub const DSLP_OSC_MAIN: u32 = 0x00000000; // Osc source is main osc pub const DSLP_OSC_INT: u32 = 0x00000010; // Osc source is int. osc pub const DSLP_OSC_INT30: u32 = 0x00000030; // Osc source is int. 30 KHz pub const DSLP_OSC_EXT32: u32 = 0x00000070; // Osc source is ext. 32 KHz pub const DSLP_PIOSC_PD: u32 = 0x00000002; // Power down PIOSC in deep-sleep pub const DSLP_MOSC_PD: u32 = 0x40000000; // Power down MOSC in deep-sleep //***************************************************************************** // // The following are values that can be passed to the SysCtlPIOSCCalibrate() // API as the ui32Type parameter. // //***************************************************************************** pub const PIOSC_CAL_AUTO: u32 = 0x00000200; // Automatic calibration pub const PIOSC_CAL_FACT: u32 = 0x00000100; // Factory calibration pub const PIOSC_CAL_USER: u32 = 0x80000100; // User-supplied calibration //***************************************************************************** // // The following are values that can be passed to the SysCtlMOSCConfigSet() API // as the ui32Config parameter. // //***************************************************************************** pub const MOSC_VALIDATE: u32 = 0x00000001; // Enable MOSC validation pub const MOSC_INTERRUPT: u32 = 0x00000002; // Generate interrupt on MOSC fail pub const MOSC_NO_XTAL: u32 = 0x00000004; // No crystal is attached to MOSC pub const MOSC_PWR_DIS: u32 = 0x00000008; // Power down the MOSC. pub const MOSC_LOWFREQ: u32 = 0x00000000; // MOSC is less than 10MHz pub const MOSC_HIGHFREQ: u32 = 0x00000010; // MOSC is greater than 10MHz pub const MOSC_SESRC: u32 = 0x00000020; // Singled ended oscillator source. //***************************************************************************** // // The following are values that can be passed to the SysCtlSleepPowerSet() and // SysCtlDeepSleepPowerSet() APIs as the ui32Config parameter. // //***************************************************************************** pub const LDO_SLEEP: u32 = 0x00000200; // LDO in sleep mode // (Deep Sleep Only) pub const TEMP_LOW_POWER: u32 = 0x00000100; // Temp sensor in low power mode // (Deep Sleep Only) pub const FLASH_NORMAL: u32 = 0x00000000; // Flash in normal mode pub const FLASH_LOW_POWER: u32 = 0x00000020; // Flash in low power mode pub const SRAM_NORMAL: u32 = 0x00000000; // SRAM in normal mode pub const SRAM_STANDBY: u32 = 0x00000001; // SRAM in standby mode pub const SRAM_LOW_POWER: u32 = 0x00000003; // SRAM in low power mode //***************************************************************************** // // Defines for the SysCtlResetBehaviorSet() and SysCtlResetBehaviorGet() APIs. // //***************************************************************************** pub const ONRST_WDOG0_POR: u32 = 0x00000030; pub const ONRST_WDOG0_SYS: u32 = 0x00000020; pub const ONRST_WDOG1_POR: u32 = 0x000000C0; pub const ONRST_WDOG1_SYS: u32 = 0x00000080; pub const ONRST_BOR_POR: u32 = 0x0000000C; pub const ONRST_BOR_SYS: u32 = 0x00000008; pub const ONRST_EXT_POR: u32 = 0x00000003; pub const ONRST_EXT_SYS: u32 = 0x00000002; //***************************************************************************** // // Values used with the SysCtlVoltageEventConfig() API. // //***************************************************************************** pub const VEVENT_VDDABO_NONE: u32 = 0x00000000; pub const VEVENT_VDDABO_INT: u32 = 0x00000100; pub const VEVENT_VDDABO_NMI: u32 = 0x00000200; pub const VEVENT_VDDABO_RST: u32 = 0x00000300; pub const VEVENT_VDDBO_NONE: u32 = 0x00000000; pub const VEVENT_VDDBO_INT: u32 = 0x00000001; pub const VEVENT_VDDBO_NMI: u32 = 0x00000002; pub const VEVENT_VDDBO_RST: u32 = 0x00000003; //***************************************************************************** // // Values used with the SysCtlVoltageEventStatus() and // SysCtlVoltageEventClear() APIs. // //***************************************************************************** pub const VESTAT_VDDBOR: u32 = 0x00000040; pub const VESTAT_VDDABOR: u32 = 0x00000010; //***************************************************************************** // // Values used with the SysCtlNMIStatus() API. // //***************************************************************************** pub const NMI_MOSCFAIL: u32 = 0x00010000; pub const NMI_TAMPER: u32 = 0x00000200; pub const NMI_WDT1: u32 = 0x00000020; pub const NMI_WDT0: u32 = 0x00000008; pub const NMI_POWER: u32 = 0x00000004; pub const NMI_EXTERNAL: u32 = 0x00000001; //***************************************************************************** // // The defines for the SysCtlClockOutConfig() API. // //***************************************************************************** pub const CLKOUT_EN: u32 = 0x80000000; pub const CLKOUT_DIS: u32 = 0x00000000; pub const CLKOUT_SYSCLK: u32 = 0x00000000; pub const CLKOUT_PIOSC: u32 = 0x00010000; pub const CLKOUT_MOSC: u32 = 0x00020000; //***************************************************************************** // // The following defines are used with the SysCtlAltClkConfig() function. // //***************************************************************************** pub const ALTCLK_PIOSC: u32 = 0x00000000; pub const ALTCLK_RTCOSC: u32 = 0x00000003; pub const ALTCLK_LFIOSC: u32 = 0x00000004; pub fn ClockGet() -> u32 { unsafe { let func = getfun(13, 24) as *const extern "C" fn() -> u32; (*func)() }} pub fn ClockSet(config: u32) { unsafe { let func = getfun(13, 23) as *const extern "C" fn(u32); (*func)(config) }} pub fn DeepSleep() { unsafe { let func = getfun(13, 20) as *const extern "C" fn(); (*func)() }} pub fn DeepSleepClockSet(config: u32) { unsafe { let func = getfun(13, 46) as *const extern "C" fn(u32); (*func)(config) }} pub fn Delay(count: u32) { unsafe { let func = getfun(13, 34) as *const extern "C" fn(u32); (*func)(count) }} pub fn FlashSizeGet() -> u32 { unsafe { let func = getfun(13, 2) as *const extern "C" fn() -> u32; (*func)() }} pub fn IntClear(ints: u32) { unsafe { let func = getfun(13, 15) as *const extern "C" fn(u32); (*func)(ints) }} pub fn IntDisable(ints: u32) { unsafe { let func = getfun(13, 14) as *const extern "C" fn(u32); (*func)(ints) }} pub fn IntEnable(ints: u32) { unsafe { let func = getfun(13, 13) as *const extern "C" fn(u32); (*func)(ints) }} pub fn IntStatus(masked: bool) -> u32 { unsafe { let func = getfun(13, 16) as *const extern "C" fn(u8) -> u32; (*func)(masked as u8) }} pub fn MOSCConigSet(config: u32) { unsafe { let func = getfun(13, 44) as *const extern "C" fn(u32); (*func)(config) }} pub fn PeripheralClockGating(enable: bool) { unsafe { let func = getfun(13, 12) as *const extern "C" fn(u8); (*func)(enable as u8) }} pub fn PeripheralDeepSleepDisable(peripheral: u32) { unsafe { let func = getfun(13, 11) as *const extern "C" fn(u32); (*func)(peripheral) }} pub fn PeripheralDeepSleepEnable(peripheral: u32) { unsafe { let func = getfun(13, 10) as *const extern "C" fn(u32); (*func)(peripheral) }} pub fn PeripheralDisable(peripheral: u32) { unsafe { let func = getfun(13, 7) as *const extern "C" fn(u32); (*func)(peripheral) }} pub fn PeripheralEnable(peripheral: u32) { unsafe { let func = getfun(13, 6) as *const extern "C" fn(u32); (*func)(peripheral) }} pub fn PeripheralPowerOff(peripheral: u32) { unsafe { let func = getfun(13, 37) as *const extern "C" fn(u32); (*func)(peripheral) }} pub fn PeripheralPowerOn(peripheral: u32) { unsafe { let func = getfun(13, 36) as *const extern "C" fn(u32); (*func)(peripheral) }} pub fn PeripheralPresent(peripheral: u32) -> bool { unsafe { let func = getfun(13, 4) as *const extern "C" fn(u32) -> u8; (*func)(peripheral) != 0 }} pub fn PeripheralReady(peripheral: u32) -> bool { unsafe { let func = getfun(13, 35) as *const extern "C" fn(u32) -> u8; (*func)(peripheral) != 0 }} pub fn PeripheralReset(peripheral: u32) { unsafe { let func = getfun(13, 5) as *const extern "C" fn(u32); (*func)(peripheral) }} pub fn PeripheralSleepDisable(peripheral: u32) { unsafe { let func = getfun(13, 9) as *const extern "C" fn(u32); (*func)(peripheral) }} pub fn PeripheralSleepEnable(peripheral: u32) { unsafe { let func = getfun(13, 8) as *const extern "C" fn(u32); (*func)(peripheral) }} pub fn PIOSCCalibrate(typ: u32) -> u32 { unsafe { let func = getfun(13, 45) as *const extern "C" fn(u32) -> u32; (*func)(typ) }} pub fn PWMClockGet() -> u32 { unsafe { let func = getfun(13, 26) as *const extern "C" fn() -> u32; (*func)() }} pub fn PWMClockSet(config: u32) { unsafe { let func = getfun(13, 25) as *const extern "C" fn(u32); (*func)(config) }} pub fn Reset() { unsafe { let func = getfun(13, 19) as *const extern "C" fn(); (*func)() }} pub fn ResetCauseClear(causes: u32) { unsafe { let func = getfun(13, 22) as *const extern "C" fn(u32); (*func)(causes) }} pub fn ResetCauseGet() -> u32 { unsafe { let func = getfun(13, 21) as *const extern "C" fn() -> u32; (*func)() }} pub fn SRAMSizeGet() -> u32 { unsafe { let func = getfun(13, 1) as *const extern "C" fn() -> u32; (*func)() }} pub fn USBPLLDisable() { unsafe { let func = getfun(13, 32) as *const extern "C" fn(); (*func)() }} pub fn USBPLLEnable() { unsafe { let func = getfun(13, 31) as *const extern "C" fn(); (*func)() }}
/// Builds a static hashmap macro_rules! map( { $($key:expr => $value:expr),+ } => { { let mut m = ::std::collections::HashMap::new(); $( m.insert($key, $value); )+ m } }; ); /// Converts a rust variable type to the NodeValueType that could hold it macro_rules! node_value_of { ($val:ident: TriggerSignal) => {NodeValue::Trigger($val)}; ($val:literal: TriggerSignal) => {NodeValue::Trigger($val)}; ($val:ident: bool) => {NodeValue::Toggle($val)}; ($val:literal: bool) => {NodeValue::Toggle($val)}; ($val:ident: i64) => {NodeValue::Count($val)}; ($val:literal: i64) => {NodeValue::Count($val)}; ($val:ident: u32) => {NodeValue::ConstrainedMagnitude($val)}; ($val:literal: u32) => {NodeValue::ConstrainedMagnitude($val)}; ($val:ident: f64) => {NodeValue::UnconstrainedMagnitude($val)}; ($val:literal: f64) => {NodeValue::UnconstrainedMagnitude($val)}; ($val:ident: NodeColor) => {NodeValue::Color($val)}; ($val:literal: NodeColor) => {NodeValue::Color($val)}; ($val:ident: Box<String>) => {NodeValue::Text($val)}; ($val:literal: Box<String>) => {NodeValue::Text($val)}; } /// Converts a rust variable type to the NodeValueType that could hold it macro_rules! node_value_type_of { (TriggerSignal) => {NodeValueType::Trigger}; (bool) => {NodeValueType::Toggle}; (i64) => {NodeValueType::Count}; (u32) => {NodeValueType::ConstrainedMagnitude}; (f64) => {NodeValueType::UnconstrainedMagnitude}; (NodeColor) => {NodeValueType::Color}; (Box<String>) => {NodeValueType::Text}; } /// Converts an arg to a NodeValueInput macro_rules! node_input_def_from_arg { ($name:ident: $type:ident) => { NodeInputDef { desc: NodeDefBasicDescription { name: stringify!($name).to_string(), description: concat!("Automatic description of input ", stringify!($name)).to_string(), }, allowed_types: vec![node_value_type_of!($type)], required: true, } }; } /// Makes a list of NodeValueInputs based on function args. macro_rules! node_input_def_from_args { ($($name:ident: $type:ident),*) => {vec![ $(node_input_def_from_arg!($name: $type)),* ]}; } /// Converts an arg to a NodeValueInput macro_rules! node_output_def_from_type { ($type:ident) => { NodeOutputDef { desc: NodeDefBasicDescription { name: "Generic output".to_string(), description: "Generic output description".to_string() }, output_type: node_value_type_of!($type), } }; } /// Makes a list of NodeValueInputs based on function args. macro_rules! node_output_def_from_tuple { ($($type:ident),+) => {vec![ $(node_output_def_from_type!($type)),+ ]}; } /// Wraps a given function body with unwrapping code for NodeValue inputs macro_rules! wrap_node_function { (@body {$body:block} $ivar:ident $name_1:ident: $type_1:ident $idx:expr) => { if let node_value_of!($name_1: $type_1) = $ivar[$idx] { $body } else { panic!(concat!("Invalid type for NodeValue input ", stringify!($name_1))); } }; (@body {$body:block} $ivar:ident $name_1:ident: $type_1:ident, $($name:ident: $type:ident),+ $idx:expr) => { if let node_value_of!($name_1: $type_1) = $ivar[$idx] { wrap_node_function!(@body {$body} $ivar $($name: $type),+ $idx + 1usize) } else { panic!(concat!("Invalid type for NodeValue input ", stringify!($name_1))); } }; (fn $fname:ident($($name:ident: $type:ident),+) -> $o:ty $body:block) => { fn $fname(inputs: Vec<&NodeValue>) -> $o { wrap_node_function!(@body {$body} inputs $($name: $type),+ 0) } }; (|$($name:ident: $type:ident),+| $body:block) => { |inputs: Vec<&NodeValue>| { wrap_node_function!(@body {$body} inputs $($name: $type),+ 0) } }; (fn $fname:ident( ) -> $o:ty $body:block) => { fn $fname(_inputs: Vec<&NodeValue>) -> $o { $body } }; (| | $body:block) => { |_inputs: Vec<&NodeValue>| { $body } }; } /// Builds a NodeDef with a function runner from a lambda function. macro_rules! node_def_from_fn { (|$($name:ident: $type:ident),*| -> ($($o:ident),+) $body:block) => { NodeDef { desc: NodeDefBasicDescription { name: "Test Node".to_string(), description: "Test Description".to_string(), }, inputs: node_input_def_from_args!($($name: $type),*), outputs: node_output_def_from_tuple!($($o),+), runner: NodeDefRunner::Function(wrap_node_function!(|$($name: $type),*| $body)) } }; (|| -> ($($o:ident),+) $body:block) => { node_def_from_fn!(| | -> ($($o),+) $body); }; (fn $fname:ident($($name:ident: $type:ident),*) -> ($($o:ident),+) $body:block) => { NodeDef { desc: NodeDefBasicDescription { name: stringify!($fname).to_string(), description: concat!("Automatic description of node ", stringify!($fname)).to_string(), }, inputs: node_input_def_from_args!($($name: $type),+), outputs: node_output_def_from_tuple!($($o),+), runner: NodeDefRunner::Function(wrap_node_function!(|$($name: $type),+| $body)) } }; } /// Instantiates a node with an Id, a def, and inputs. macro_rules! make_node { (@input Wire{$nodeid:literal, $output:literal}) => { NodeInput::Wire(NodeOutputRef { from_node_id: $nodeid, node_output_index: $output }) }; (@input $type:ident{$val:literal}) => { NodeInput::Const(node_value_of!($val: $type)) }; ($id:literal: $def:ident[$($type:ident{$($arg:literal),+}),*]) => { Node { id: $id, def_name: stringify!($def).to_string(), inputs: vec![ $(make_node!(@input $type{$($arg),+})),* ] } }; } /// Instantiates one or more nodes with Ids, defs, and inputs. macro_rules! make_nodes { ($($id:literal: $def:ident[$($type:ident{$($arg:literal),+}),*]),+) => { vec![ $(make_node!($id: $def[$($type{$($arg),+}),*])),+ ] }; }
#[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::SCGCI2C { #[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 SYSCTL_SCGCI2C_S0R { bits: bool, } impl SYSCTL_SCGCI2C_S0R { #[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 _SYSCTL_SCGCI2C_S0W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_SCGCI2C_S0W<'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 SYSCTL_SCGCI2C_S1R { bits: bool, } impl SYSCTL_SCGCI2C_S1R { #[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 _SYSCTL_SCGCI2C_S1W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_SCGCI2C_S1W<'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 SYSCTL_SCGCI2C_S2R { bits: bool, } impl SYSCTL_SCGCI2C_S2R { #[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 _SYSCTL_SCGCI2C_S2W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_SCGCI2C_S2W<'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 SYSCTL_SCGCI2C_S3R { bits: bool, } impl SYSCTL_SCGCI2C_S3R { #[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 _SYSCTL_SCGCI2C_S3W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_SCGCI2C_S3W<'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 SYSCTL_SCGCI2C_S4R { bits: bool, } impl SYSCTL_SCGCI2C_S4R { #[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 _SYSCTL_SCGCI2C_S4W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_SCGCI2C_S4W<'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 } } #[doc = r"Value of the field"] pub struct SYSCTL_SCGCI2C_S5R { bits: bool, } impl SYSCTL_SCGCI2C_S5R { #[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 _SYSCTL_SCGCI2C_S5W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_SCGCI2C_S5W<'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 << 5); self.w.bits |= ((value as u32) & 1) << 5; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_SCGCI2C_S6R { bits: bool, } impl SYSCTL_SCGCI2C_S6R { #[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 _SYSCTL_SCGCI2C_S6W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_SCGCI2C_S6W<'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 << 6); self.w.bits |= ((value as u32) & 1) << 6; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_SCGCI2C_S7R { bits: bool, } impl SYSCTL_SCGCI2C_S7R { #[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 _SYSCTL_SCGCI2C_S7W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_SCGCI2C_S7W<'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 << 7); self.w.bits |= ((value as u32) & 1) << 7; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_SCGCI2C_S8R { bits: bool, } impl SYSCTL_SCGCI2C_S8R { #[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 _SYSCTL_SCGCI2C_S8W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_SCGCI2C_S8W<'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 << 8); self.w.bits |= ((value as u32) & 1) << 8; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_SCGCI2C_S9R { bits: bool, } impl SYSCTL_SCGCI2C_S9R { #[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 _SYSCTL_SCGCI2C_S9W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_SCGCI2C_S9W<'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 << 9); self.w.bits |= ((value as u32) & 1) << 9; 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 - I2C Module 0 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s0(&self) -> SYSCTL_SCGCI2C_S0R { let bits = ((self.bits >> 0) & 1) != 0; SYSCTL_SCGCI2C_S0R { bits } } #[doc = "Bit 1 - I2C Module 1 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s1(&self) -> SYSCTL_SCGCI2C_S1R { let bits = ((self.bits >> 1) & 1) != 0; SYSCTL_SCGCI2C_S1R { bits } } #[doc = "Bit 2 - I2C Module 2 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s2(&self) -> SYSCTL_SCGCI2C_S2R { let bits = ((self.bits >> 2) & 1) != 0; SYSCTL_SCGCI2C_S2R { bits } } #[doc = "Bit 3 - I2C Module 3 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s3(&self) -> SYSCTL_SCGCI2C_S3R { let bits = ((self.bits >> 3) & 1) != 0; SYSCTL_SCGCI2C_S3R { bits } } #[doc = "Bit 4 - I2C Module 4 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s4(&self) -> SYSCTL_SCGCI2C_S4R { let bits = ((self.bits >> 4) & 1) != 0; SYSCTL_SCGCI2C_S4R { bits } } #[doc = "Bit 5 - I2C Module 5 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s5(&self) -> SYSCTL_SCGCI2C_S5R { let bits = ((self.bits >> 5) & 1) != 0; SYSCTL_SCGCI2C_S5R { bits } } #[doc = "Bit 6 - I2C Module 6 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s6(&self) -> SYSCTL_SCGCI2C_S6R { let bits = ((self.bits >> 6) & 1) != 0; SYSCTL_SCGCI2C_S6R { bits } } #[doc = "Bit 7 - I2C Module 7 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s7(&self) -> SYSCTL_SCGCI2C_S7R { let bits = ((self.bits >> 7) & 1) != 0; SYSCTL_SCGCI2C_S7R { bits } } #[doc = "Bit 8 - I2C Module 8 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s8(&self) -> SYSCTL_SCGCI2C_S8R { let bits = ((self.bits >> 8) & 1) != 0; SYSCTL_SCGCI2C_S8R { bits } } #[doc = "Bit 9 - I2C Module 9 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s9(&self) -> SYSCTL_SCGCI2C_S9R { let bits = ((self.bits >> 9) & 1) != 0; SYSCTL_SCGCI2C_S9R { 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 - I2C Module 0 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s0(&mut self) -> _SYSCTL_SCGCI2C_S0W { _SYSCTL_SCGCI2C_S0W { w: self } } #[doc = "Bit 1 - I2C Module 1 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s1(&mut self) -> _SYSCTL_SCGCI2C_S1W { _SYSCTL_SCGCI2C_S1W { w: self } } #[doc = "Bit 2 - I2C Module 2 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s2(&mut self) -> _SYSCTL_SCGCI2C_S2W { _SYSCTL_SCGCI2C_S2W { w: self } } #[doc = "Bit 3 - I2C Module 3 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s3(&mut self) -> _SYSCTL_SCGCI2C_S3W { _SYSCTL_SCGCI2C_S3W { w: self } } #[doc = "Bit 4 - I2C Module 4 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s4(&mut self) -> _SYSCTL_SCGCI2C_S4W { _SYSCTL_SCGCI2C_S4W { w: self } } #[doc = "Bit 5 - I2C Module 5 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s5(&mut self) -> _SYSCTL_SCGCI2C_S5W { _SYSCTL_SCGCI2C_S5W { w: self } } #[doc = "Bit 6 - I2C Module 6 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s6(&mut self) -> _SYSCTL_SCGCI2C_S6W { _SYSCTL_SCGCI2C_S6W { w: self } } #[doc = "Bit 7 - I2C Module 7 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s7(&mut self) -> _SYSCTL_SCGCI2C_S7W { _SYSCTL_SCGCI2C_S7W { w: self } } #[doc = "Bit 8 - I2C Module 8 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s8(&mut self) -> _SYSCTL_SCGCI2C_S8W { _SYSCTL_SCGCI2C_S8W { w: self } } #[doc = "Bit 9 - I2C Module 9 Sleep Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_scgci2c_s9(&mut self) -> _SYSCTL_SCGCI2C_S9W { _SYSCTL_SCGCI2C_S9W { w: self } } }
use chrono::NaiveDateTime; use crate::schema::ciclos_letivos; #[derive(Serialize, Deserialize, Queryable)] pub struct CicloLetivos { pub id: i32, pub ano: Option<i32>, pub semestre: Option<i32>, pub nivel_ensino_id: Option<i32>, pub created_at: NaiveDateTime, pub updated_at: NaiveDateTime, } #[derive(Deserialize, Insertable)] #[table_name = "ciclos_letivos"] pub struct InsertableCicloLetivo { pub ano: Option<i32>, pub semestre: Option<i32>, pub nivel_ensino_id: Option<i32>, } #[derive(Serialize, Deserialize, Queryable, AsChangeset)] #[table_name = "ciclos_letivos"] pub struct UpdatableCicloLetivo { pub ano: Option<i32>, pub semestre: Option<i32>, pub nivel_ensino_id: Option<i32>, } /* ciclos_letivos (id) { id -> Integer, ano -> Nullable<Integer>, semestre -> Nullable<Integer>, nivel_ensino_id -> Nullable<Integer>, created_at -> Datetime, updated_at -> Datetime, } */
mod flag; pub mod node; pub mod node_chain; pub mod tree;
use super::calibration::Calibration; use super::capture::Capture; use super::error::{k4a_result, k4a_wait_result, Error, WaitError}; use super::frame::Frame; use super::tracker_configuration::TrackerConfiguration; pub struct Tracker { tracker_handle: libk4a_sys::k4abt_tracker_t, } impl Tracker { pub fn create( calibration: &Calibration, tracker_configuration: TrackerConfiguration, ) -> Result<Self, Error> { let mut tracker_handle = std::ptr::null_mut(); let result = unsafe { libk4a_sys::k4abt_tracker_create( calibration, tracker_configuration, &mut tracker_handle, ) }; k4a_result(result)?; Ok(Tracker { tracker_handle }) } pub fn enqueue_capture(&self, capture: Capture, timeout: i32) -> Result<(), WaitError> { let wait_result = unsafe { libk4a_sys::k4abt_tracker_enqueue_capture(self.tracker_handle, *capture, timeout) }; k4a_wait_result(wait_result)?; Ok(()) } pub fn k4abt_tracker_pop_result(&self, timeout: i32) -> Result<Frame, WaitError> { let mut frame_handle = std::ptr::null_mut(); let wait_result = unsafe { libk4a_sys::k4abt_tracker_pop_result(self.tracker_handle, &mut frame_handle, timeout) }; k4a_wait_result(wait_result)?; Ok(unsafe { Frame::from_handle(frame_handle) }) } } impl Drop for Tracker { fn drop(&mut self) { let tracker_handle = self.tracker_handle; if tracker_handle.is_null() { return; } unsafe { libk4a_sys::k4abt_tracker_shutdown(tracker_handle); libk4a_sys::k4abt_tracker_destroy(tracker_handle); } self.tracker_handle = std::ptr::null_mut(); } }
use std::io::{ErrorKind, Read}; use structopt::StructOpt; use crate::advents::AdventYear; #[macro_use] mod helper; mod advent_2020; mod advent_adapters; mod advents; #[derive(StructOpt, Debug)] struct Cli { year: Option<u16>, advent: Option<u8>, } impl Cli { pub fn from_user(advent_years: &[AdventYear]) -> Self { let mut options: Self = Self::from_args(); let dialoguer_theme = &dialoguer::theme::ColorfulTheme::default(); if options.year.is_none() { let years: Vec<_> = advent_years.iter().map(|y| y.get_year()).collect(); options.year = dialoguer::Select::with_theme(dialoguer_theme) .items(&years) .interact_opt() .unwrap() .map(|i| years[i]); } if let (Some(year), None) = (options.year, options.advent) { if let Some(advent_year) = advent_years.iter().find(|y| y.get_year() == year) { let advents: Vec<_> = advent_year .iter() .filter_map(|a| if a.skip() { None } else { Some(a.get_index()) }) .collect(); options.advent = dialoguer::Select::with_theme(dialoguer_theme) .items(&advents) .interact_opt() .unwrap() .map(|i| advents[i]); }; } options } } fn main() { let advent_years = vec![advent_2020::get_advent_year()]; let options: Cli = Cli::from_user(&advent_years); match options.year { Some(year) => { match advent_years .into_iter() .find(|advent_year| advent_year.get_year() == year) { None => println!("No solution registered for given year {}", year), Some(target_year) => run_advent_year(&options, target_year), }; } None => { advent_years .into_iter() .for_each(move |y| run_advent_year(&options, y)); } } } fn run_advent_year(options: &Cli, y: advents::AdventYear) { let year = y.get_year(); println!("Running year {}", year); let mut advents = y.into_advents(); if advents.len() == 0 { return eprintln!("No adventures registered for year {}!", year); } advents.sort_by_key(|advent| advent.get_index()); if let Some(advent) = options.advent { let index = advents .binary_search_by_key(&advent, |advent| advent.get_index()) .expect("Advent index not found"); let target_advent = advents.swap_remove(index); run_advent(year, target_advent); } else { advents .into_iter() .for_each(|advent| run_advent(year, advent)); } } fn run_advent(year: u16, advent: Box<dyn advents::Advent>) { if advent.skip() { return println!("Skipping advent {}...", advent.get_index()); } println!("Running advent day {}...", advent.get_index()); let mut inputs = advent.get_input_names(); let path_prefix = ["data", &year.to_string(), &advent.get_index().to_string()] .iter() .collect::<std::path::PathBuf>(); std::fs::create_dir_all(&path_prefix).expect("could not create missing input data folder"); for file in inputs.iter_mut() { let path = path_prefix.join(&file); file.clear(); std::fs::File::open(&path) .and_then(|mut f| f.read_to_string(file)) .and(Ok(())) .or_else(|err| { if err.kind() == ErrorKind::NotFound { std::fs::File::create(&path).and(Ok(())) } else { Err(err) } }) .expect("could not read input file"); } advent.process_input(inputs); println!("\n"); }
//! https://github.com/lumen/otp/tree/lumen/lib/megaco/src #[path = "megaco/app.rs"] mod app; #[path = "megaco/binary.rs"] mod binary; #[path = "megaco/engine.rs"] mod engine; #[path = "megaco/flex.rs"] mod flex; #[path = "megaco/tcp.rs"] mod tcp; #[path = "megaco/text.rs"] mod text; #[path = "megaco/udp.rs"] mod udp; use super::*; fn relative_directory_path() -> PathBuf { super::relative_directory_path().join("megaco/src") }
use crate::board::Board; use crate::icons::octocat::OctoCat; use crate::icons::rust::Rust; use crate::icons::yewstack::Yew; use crate::utils::calculate_winner; use yew::prelude::*; #[derive(Copy, Clone)] struct History { squares: [&'static str; 9], } pub struct Game { link: ComponentLink<Self>, history: Vec<History>, step_number: usize, x_is_next: bool, } pub enum Msg { HandleClick(usize), JumpTo(usize), } impl Game { fn handle_click(&mut self, i: usize) { let history_len = &self.history[0..(self.step_number + 1)].len(); let squares = &self.history[history_len - 1].squares; if calculate_winner(*squares) != "" || squares[i] != "" { return; } let mut squares_new = *squares; squares_new[i] = if self.x_is_next { "X" } else { "O" }; self.history.push(History { squares: squares_new, }); self.step_number = *history_len; self.x_is_next = !self.x_is_next; } fn jump_to(&mut self, step: usize) { self.history.truncate(step + 1); self.step_number = step; self.x_is_next = (step % 2) == 0; } fn display_moves(&self, (index, _): (usize, &History)) -> Html { let desc = if index == 0 { format!("Go to game start") } else { format!("Go to move #{}", index) }; html! { <li key={index}> <button onclick={self.link.callback(move |_| Msg::JumpTo(index))}>{desc}</button> </li> } } } impl Component for Game { type Message = Msg; type Properties = (); fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self { Self { link, history: vec![History { squares: [""; 9] }], step_number: 0, x_is_next: true, } } fn update(&mut self, msg: Self::Message) -> bool { match msg { Msg::HandleClick(i) => { self.handle_click(i); } Msg::JumpTo(i) => { self.jump_to(i); } } true } fn change(&mut self, _props: Self::Properties) -> bool { false } fn view(&self) -> Html { let history = &self.history; let current: &History = &history[self.step_number]; let winner = calculate_winner(current.squares); let status = if winner != "" { format!("Winner: {}", winner) } else { format!("Next player: {}", if self.x_is_next { "X" } else { "O" }) }; html! { <> <div class="head"> <a href="https://github.com/yuchanns/rustbyexample/tree/main/crates/yew-tic-tac-toe" target="_blank" class="head-icon-link"> <OctoCat /> </a> <a href="https://github.com/yewstack/yew" target="_blank" class="head-icon-link"> <Yew /> </a> <a href="https://github.com/rust-lang/rust" target="_blank" class="head-icon-link"> <Rust /> </a> </div> <div class="game"> <div class="game-board"> <Board squares={current.squares} onclick={self.link.callback(|i: usize| Msg::HandleClick(i))} /> </div> <div class="game-info"> <div>{status}</div> <ol>{for history.iter().enumerate().map(|e| self.display_moves(e))}</ol> </div> </div> </> } } }
// 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. mod integration_tests; use failure::{format_err, Error, ResultExt}; use fidl::endpoints::DiscoverableService; use fidl_fuchsia_net::{IpAddress, Subnet}; use fidl_fuchsia_net_icmp::ProviderMarker; use fidl_fuchsia_net_stack::{ ForwardingDestination, ForwardingEntry, InterfaceAddress, PhysicalStatus, StackMarker, }; use fidl_fuchsia_net_stack_ext::FidlReturn; use fidl_fuchsia_netemul_environment::{ EnvironmentOptions, LaunchService, LoggerOptions, ManagedEnvironmentMarker, ManagedEnvironmentProxy, VirtualDevice, }; use fidl_fuchsia_netemul_network::{ DeviceProxy_Marker, EndpointBacking, EndpointConfig, EndpointManagerMarker, EndpointManagerProxy, EndpointProxy, NetworkConfig, NetworkContextMarker, NetworkManagerMarker, NetworkProxy, }; use fidl_fuchsia_netemul_sandbox::{SandboxMarker, SandboxProxy}; use fidl_fuchsia_sys::{ ComponentControllerEvent, ComponentControllerMarker, LaunchInfo, LauncherMarker, TerminationReason, }; use fuchsia_component::client::connect_to_service; use fuchsia_component::fuchsia_single_component_package_url; use fuchsia_zircon as zx; use futures::StreamExt; use std::vec::Vec; const NETSTACK_URL: &'static str = fuchsia_single_component_package_url!("netstack3"); const PING_URL: &'static str = fuchsia_single_component_package_url!("ping3"); fn create_netstack_env( sandbox: &SandboxProxy, name: String, device: fidl::endpoints::ClientEnd<DeviceProxy_Marker>, ) -> Result<ManagedEnvironmentProxy, Error> { let (env, env_server_end) = fidl::endpoints::create_proxy::<ManagedEnvironmentMarker>()?; let services = vec![ LaunchService { name: StackMarker::SERVICE_NAME.to_string(), url: NETSTACK_URL.to_string(), arguments: None, }, LaunchService { name: ProviderMarker::SERVICE_NAME.to_string(), url: NETSTACK_URL.to_string(), arguments: None, }, ]; let devices = vec![VirtualDevice { path: "eth001".to_string(), device }]; sandbox .create_environment( env_server_end, EnvironmentOptions { name: Some(name), services: Some(services), devices: Some(devices), inherit_parent_launch_services: None, logger_options: Some(LoggerOptions { enabled: Some(true), klogs_enabled: None, filter_options: None, syslog_output: Some(true), }), }, ) .context("Failed to create environment")?; Ok(env) } pub struct TestSetup { sandbox: SandboxProxy, network: NetworkProxy, endpoint_manager: EndpointManagerProxy, endpoints: Vec<EndpointProxy>, subnet_addr: IpAddress, subnet_prefix: u8, } impl TestSetup { pub async fn new(subnet_addr: IpAddress, subnet_prefix: u8) -> Result<Self, Error> { let sandbox = connect_to_service::<SandboxMarker>().context("Failed to connect to sandbox")?; let (netctx, netctx_server_end) = fidl::endpoints::create_proxy::<NetworkContextMarker>()?; sandbox.get_network_context(netctx_server_end).context("Failed to get network context")?; let (network_manager, network_manager_server_end) = fidl::endpoints::create_proxy::<NetworkManagerMarker>()?; netctx .get_network_manager(network_manager_server_end) .context("Failed to get network manager")?; let config = NetworkConfig { latency: None, packet_loss: None, reorder: None }; let (status, network) = network_manager .create_network("test", config) .await .context("Failed to create network")?; assert_eq!(status, zx::sys::ZX_OK); let network = network.unwrap().into_proxy()?; let (endpoint_manager, endpoint_manager_server_end) = fidl::endpoints::create_proxy::<EndpointManagerMarker>()?; netctx .get_endpoint_manager(endpoint_manager_server_end) .context("Failed to get endpoint manager")?; Ok(Self { sandbox, network, endpoint_manager, endpoints: Vec::new(), subnet_addr, subnet_prefix, }) } async fn add_env( &mut self, name: &str, addr: IpAddress, ) -> Result<ManagedEnvironmentProxy, Error> { let mut config = EndpointConfig { mtu: 1500, mac: None, backing: EndpointBacking::Ethertap }; let (status, endpoint) = self .endpoint_manager .create_endpoint(name, &mut config) .await .context("Failed to create endpoint")?; assert_eq!(status, zx::sys::ZX_OK); let endpoint = endpoint.unwrap().into_proxy()?; endpoint.set_link_up(true).await.context("Failed to set link up")?; let status = self.network.attach_endpoint(name).await.context("Failed to attach endpoint")?; assert_eq!(status, zx::sys::ZX_OK); // Create device let (device, device_server_end) = fidl::endpoints::create_endpoints::<DeviceProxy_Marker>()?; endpoint.get_proxy_(device_server_end)?; // Create environment let env = create_netstack_env(&self.sandbox, name.to_string(), device) .context("Failed to create environment")?; // Add the ethernet interface let (stack, stack_server_end) = fidl::endpoints::create_proxy::<StackMarker>()?; env.connect_to_service("fuchsia.net.stack.Stack", stack_server_end.into_channel()) .context("Can't connect to fuchsia.net.stack")?; let eth = endpoint.get_ethernet_device().await.context("Failed to get ethernet device")?; let interface_id = stack .add_ethernet_interface("fake_topo_path", eth) .await .squash_result() .map_err(|e| format_err!("Failed to get ethernet interface: {:?}", e))?; // Wait for interface to become online // // TODO(fxb/38311): Replace this loop with an event loop waiting for fuchsia.net.stack's // Stack.OnInterfaceStatusChange to return an ONLINE InterfaceStatusChange. loop { let info = stack .get_interface_info(interface_id) .await .squash_result() .map_err(|e| format_err!("Failed to get interface info: {:?}", e))?; if info.properties.physical_status == PhysicalStatus::Up { break; } eprintln!("Interface not ready, waiting 10ms..."); zx::Duration::from_millis(100).sleep(); } // Assign IP address and add routes stack .add_interface_address( interface_id, &mut InterfaceAddress { ip_address: addr, prefix_len: self.subnet_prefix }, ) .await .squash_result() .map_err(|e| format_err!("Failed to add interface address: {:?}", e))?; stack .add_forwarding_entry(&mut ForwardingEntry { subnet: Subnet { addr: self.subnet_addr, prefix_len: self.subnet_prefix }, destination: ForwardingDestination::DeviceId(interface_id), }) .await .map_err(|e| format_err!("{}", e))? .map_err(|e| format_err!("Failed to add forwarding entry: {:?}", e))?; self.endpoints.push(endpoint); Ok(env) } } async fn assert_ping(env: &ManagedEnvironmentProxy, args: &str, expected_return_code: i64) { let (launcher, launcher_server_end) = fidl::endpoints::create_proxy::<LauncherMarker>().unwrap(); env.get_launcher(launcher_server_end).context("Failed to get launcher").unwrap(); let (controller, controller_server_end) = fidl::endpoints::create_proxy::<ComponentControllerMarker>().unwrap(); let mut ping_launch = LaunchInfo { url: PING_URL.to_string(), arguments: Some(args.split(" ").map(String::from).collect()), out: None, err: None, directory_request: None, flat_namespace: None, additional_services: None, }; launcher .create_component(&mut ping_launch, Some(controller_server_end)) .context("Failed to create component") .unwrap(); let mut event_stream = controller.take_event_stream(); while let Some(evt) = event_stream.next().await { match evt.unwrap() { ComponentControllerEvent::OnTerminated { return_code, termination_reason } => { assert_eq!(termination_reason, TerminationReason::Exited); assert!( return_code == expected_return_code, format!( "Expected return code {}, but got {} instead", expected_return_code, return_code ) ); } _ => {} } } }
use std::fmt::Debug; pub trait Convex<K>: Ord + Copy + Debug where K: PartialOrd, { fn get_angle(a: &Self, b: &Self) -> K; fn get_turn(a: &Self, b: &Self, c: &Self) -> Turn; } #[derive(PartialEq, PartialOrd)] pub enum Turn { Clockwise, CounterClockwise, } // Convex hull // Take array points. Output array of points that make the convex hull. // Find the lowest left most point // Calculate angle between it and every point // Sort the list from smallest to highest and turn into sorted_stack // Create vector called stack add first two vals from sorted values // Foreach point in sorted value check that first two top most vals and point // form counter clockwise (ccw) angle // If clockwise remove top value from stack and repeat. // If ccw add point to stack and move on to next point. // Once all points checked return stack vector pub fn convex_hull<T, K>(source: &[T]) -> Vec<T> where T: Convex<K>, K: PartialOrd, { if source.len() <= 3 { return source.to_vec(); } let min = source.iter().min().unwrap(); let sorted = sort_by_angle(source, min); let mut stack = vec![sorted[0], sorted[1]]; for p in sorted.iter().skip(2) { while stack.len() > 1 && Turn::Clockwise == Convex::get_turn(&stack[stack.len() - 2], &stack[stack.len() - 1], p) { stack.pop(); } stack.push(*p); } stack } fn sort_by_angle<T, K>(source: &[T], corner: &T) -> Vec<T> where T: Convex<K>, K: PartialOrd, { let mut angles: Vec<MinScored<K, T>> = source .iter() .map(|p| { let angle = Convex::get_angle(corner, p); return MinScored { key: angle, value: *p, }; }) .collect(); //Sort values by angle to corner. angles.sort_by(|a, b| a.key.partial_cmp(&b.key).unwrap()); return angles.iter().map(|ms| ms.value).collect(); } #[derive(Copy, Clone, Debug)] pub struct MinScored<K, T> where T: Convex<K>, K: PartialOrd, { pub key: K, pub value: T, }
use super::CompilePass; use super::Result; use ::{Type, TypeContainer}; use std::rc::{Rc, Weak}; use std::cell::RefCell; pub struct AssignParentPass; impl CompilePass for AssignParentPass { fn run(typ: &mut TypeContainer) -> Result<()> { do_run(typ, None) } } fn do_run(typ: &mut TypeContainer, parent: Option<Weak<RefCell<Type>>>) -> Result<()> { let mut inner = typ.borrow_mut(); inner.data.parent = parent; for mut child in &mut inner.data.children { do_run(&mut child, Some(Rc::downgrade(typ)))?; } Ok(()) }
use yew::{prelude::*, Children}; #[derive(Properties, Clone, PartialEq)] pub struct Props { pub title: String, #[prop_or_default] pub children: Children, } pub struct FormContainer { props: Props, } impl Component for FormContainer { type Message = (); type Properties = Props; fn create(props: Self::Properties, _link: ComponentLink<Self>) -> Self { Self { props: props } } fn update(&mut self, _msg: Self::Message) -> ShouldRender { false } fn change(&mut self, _props: Self::Properties) -> ShouldRender { false } fn view(&self) -> Html { html! { <div class="flex flex-col border-2 border-purple-600 py-12 px-8 rounded-md bg-purple-400"> <h1 class="font-semibold mb-2 text-xl"> { &self.props.title } </h1> { for self.props.children.iter() } </div> } } }
use std::ops::{Deref, DerefMut}; use libc::c_int; use curses; use {Error, Result, Window}; pub struct Panel<'a> { ptr: *mut curses::PANEL, window: Window<'a>, } impl<'a> Panel<'a> { #[inline] pub unsafe fn wrap<'b>(ptr: *mut curses::PANEL) -> Panel<'b> { Panel { ptr: ptr, window: Window::wrap(curses::panel_window(ptr)) } } #[inline] pub unsafe fn as_ptr(&self) -> *const curses::PANEL { self.ptr as *const _ } #[inline] pub unsafe fn as_mut_ptr(&mut self) -> *mut curses::PANEL { self.ptr } } impl<'a> Panel<'a> { #[inline] pub fn show(&mut self) -> Result<&mut Self> { unsafe { try!(Error::check(curses::show_panel(self.as_mut_ptr()))); } Ok(self) } #[inline] pub fn hide(&mut self) -> Result<&mut Self> { unsafe { try!(Error::check(curses::hide_panel(self.as_mut_ptr()))); } Ok(self) } #[inline] pub fn is_visible(&self) -> bool { unsafe { curses::panel_hidden(self.as_ptr()) == 0 } } #[inline] pub fn top(&mut self) -> Result<&mut Self> { unsafe { try!(Error::check(curses::top_panel(self.as_mut_ptr()))); } Ok(self) } #[inline] pub fn bottom(&mut self) -> Result<&mut Self> { unsafe { try!(Error::check(curses::bottom_panel(self.as_mut_ptr()))); } Ok(self) } #[inline] pub fn position(&mut self, x: u32, y: u32) -> Result<&mut Self> { unsafe { try!(Error::check(curses::move_panel(self.as_mut_ptr(), y as c_int, x as c_int))); } Ok(self) } } impl<'a> Deref for Panel<'a> { type Target = Window<'a>; fn deref(&self) -> &Self::Target { &self.window } } impl<'a> DerefMut for Panel<'a> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.window } }
use std::fmt; use num; use approx; use super::traits::ColorChannel; use super::scalar::{PosNormalChannelScalar, NormalChannelScalar}; use channel::ChannelCast; use channel::cast::ChannelFormatCast; use ::color; pub struct PosNormalChannelTag; pub struct NormalChannelTag; #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct PosNormalBoundedChannel<T>(pub T); #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct NormalBoundedChannel<T>(pub T); macro_rules! impl_bounded_channel_type { ($name:ident, $scalar_type:ident, $tag:ident) => { impl<T> ColorChannel for $name<T> where T: $scalar_type { type Format = T; type Scalar = T; type Tag = $tag; fn min_bound() -> T { T::min_bound() } fn max_bound() -> T { T::max_bound() } fn value(&self) -> T { self.0.clone() } impl_channel_clamp!($name, T); fn scalar(&self) -> T { self.0.clone() } fn from_scalar(value: T) -> Self { $name(value) } fn new(value: T) -> Self { $name(value) } } impl<T> color::Invert for $name<T> where T: $scalar_type { fn invert(self) -> Self { $name((Self::max_bound() + Self::min_bound()) - self.0) } } impl<T> color::Bounded for $name<T> where T: $scalar_type { fn normalize(self) -> Self { $name(self.0.normalize()) } fn is_normalized(&self) -> bool { self.0.is_normalized() } } impl<T> color::Lerp for $name<T> where T: $scalar_type + color::Lerp { type Position = <T as color::Lerp>::Position; fn lerp(&self, right: &Self, pos: Self::Position) -> Self { $name(self.0.lerp(&right.0, pos)) } } impl<T> ChannelCast for $name<T> where T: $scalar_type { fn channel_cast<To>(self) -> To where Self::Format: ChannelFormatCast<To::Format>, To: ColorChannel<Tag = Self::Tag> { To::new(self.scalar_cast()) } fn scalar_cast<To>(self) -> To where Self::Format: ChannelFormatCast<To>, { let max = <f64 as $scalar_type>::max_bound(); let min = <f64 as $scalar_type>::min_bound(); self.0.cast_with_rescale(min, max) } } impl<T> Default for $name<T> where T: $scalar_type + num::Zero { fn default() -> Self { $name(T::zero()) } } impl<T> fmt::Display for $name<T> where T: $scalar_type + fmt::Display { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } impl<T> approx::ApproxEq for $name<T> where T: $scalar_type + approx::ApproxEq { type Epsilon = T::Epsilon; fn default_epsilon() -> Self::Epsilon { T::default_epsilon() } fn default_max_relative() -> Self::Epsilon { T::default_max_relative() } fn default_max_ulps() -> u32 { T::default_max_ulps() } fn relative_eq(&self, other: &Self, epsilon: Self::Epsilon, max_relative: Self::Epsilon) -> bool { self.0.relative_eq(&other.0, epsilon, max_relative) } fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool { self.0.ulps_eq(&other.0, epsilon, max_ulps) } } }; } impl_bounded_channel_type!(PosNormalBoundedChannel, PosNormalChannelScalar, PosNormalChannelTag); impl_bounded_channel_type!(NormalBoundedChannel, NormalChannelScalar, NormalChannelTag);
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qstyleditemdelegate.h // dst-file: /src/widgets/qstyleditemdelegate.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use super::qabstractitemdelegate::*; // 773 use std::ops::Deref; use super::qstyleoption::*; // 773 use super::super::core::qabstractitemmodel::*; // 771 use super::super::core::qsize::*; // 771 use super::qwidget::*; // 773 use super::qitemeditorfactory::*; // 773 use super::super::gui::qpainter::*; // 771 use super::super::core::qobject::*; // 771 use super::super::core::qvariant::*; // 771 use super::super::core::qlocale::*; // 771 use super::super::core::qstring::*; // 771 use super::super::core::qobjectdefs::*; // 771 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QStyledItemDelegate_Class_Size() -> c_int; // proto: QSize QStyledItemDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index); fn C_ZNK19QStyledItemDelegate8sizeHintERK20QStyleOptionViewItemRK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void; // proto: QWidget * QStyledItemDelegate::createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index); fn C_ZNK19QStyledItemDelegate12createEditorEP7QWidgetRK20QStyleOptionViewItemRK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void) -> *mut c_void; // proto: void QStyledItemDelegate::~QStyledItemDelegate(); fn C_ZN19QStyledItemDelegateD2Ev(qthis: u64 /* *mut c_void*/); // proto: void QStyledItemDelegate::updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index); fn C_ZNK19QStyledItemDelegate20updateEditorGeometryEP7QWidgetRK20QStyleOptionViewItemRK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void); // proto: void QStyledItemDelegate::setEditorData(QWidget * editor, const QModelIndex & index); fn C_ZNK19QStyledItemDelegate13setEditorDataEP7QWidgetRK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void); // proto: void QStyledItemDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index); fn C_ZNK19QStyledItemDelegate12setModelDataEP7QWidgetP18QAbstractItemModelRK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void); // proto: void QStyledItemDelegate::setItemEditorFactory(QItemEditorFactory * factory); fn C_ZN19QStyledItemDelegate20setItemEditorFactoryEP18QItemEditorFactory(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QStyledItemDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index); fn C_ZNK19QStyledItemDelegate5paintEP8QPainterRK20QStyleOptionViewItemRK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void); // proto: QItemEditorFactory * QStyledItemDelegate::itemEditorFactory(); fn C_ZNK19QStyledItemDelegate17itemEditorFactoryEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QStyledItemDelegate::QStyledItemDelegate(QObject * parent); fn C_ZN19QStyledItemDelegateC2EP7QObject(arg0: *mut c_void) -> u64; // proto: QString QStyledItemDelegate::displayText(const QVariant & value, const QLocale & locale); fn C_ZNK19QStyledItemDelegate11displayTextERK8QVariantRK7QLocale(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void; // proto: const QMetaObject * QStyledItemDelegate::metaObject(); fn C_ZNK19QStyledItemDelegate10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; } // <= ext block end // body block begin => // class sizeof(QStyledItemDelegate)=1 #[derive(Default)] pub struct QStyledItemDelegate { qbase: QAbstractItemDelegate, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QStyledItemDelegate { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QStyledItemDelegate { return QStyledItemDelegate{qbase: QAbstractItemDelegate::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QStyledItemDelegate { type Target = QAbstractItemDelegate; fn deref(&self) -> &QAbstractItemDelegate { return & self.qbase; } } impl AsRef<QAbstractItemDelegate> for QStyledItemDelegate { fn as_ref(& self) -> & QAbstractItemDelegate { return & self.qbase; } } // proto: QSize QStyledItemDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index); impl /*struct*/ QStyledItemDelegate { pub fn sizeHint<RetType, T: QStyledItemDelegate_sizeHint<RetType>>(& self, overload_args: T) -> RetType { return overload_args.sizeHint(self); // return 1; } } pub trait QStyledItemDelegate_sizeHint<RetType> { fn sizeHint(self , rsthis: & QStyledItemDelegate) -> RetType; } // proto: QSize QStyledItemDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index); impl<'a> /*trait*/ QStyledItemDelegate_sizeHint<QSize> for (&'a QStyleOptionViewItem, &'a QModelIndex) { fn sizeHint(self , rsthis: & QStyledItemDelegate) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK19QStyledItemDelegate8sizeHintERK20QStyleOptionViewItemRK11QModelIndex()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK19QStyledItemDelegate8sizeHintERK20QStyleOptionViewItemRK11QModelIndex(rsthis.qclsinst, arg0, arg1)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QWidget * QStyledItemDelegate::createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index); impl /*struct*/ QStyledItemDelegate { pub fn createEditor<RetType, T: QStyledItemDelegate_createEditor<RetType>>(& self, overload_args: T) -> RetType { return overload_args.createEditor(self); // return 1; } } pub trait QStyledItemDelegate_createEditor<RetType> { fn createEditor(self , rsthis: & QStyledItemDelegate) -> RetType; } // proto: QWidget * QStyledItemDelegate::createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index); impl<'a> /*trait*/ QStyledItemDelegate_createEditor<QWidget> for (&'a QWidget, &'a QStyleOptionViewItem, &'a QModelIndex) { fn createEditor(self , rsthis: & QStyledItemDelegate) -> QWidget { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK19QStyledItemDelegate12createEditorEP7QWidgetRK20QStyleOptionViewItemRK11QModelIndex()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK19QStyledItemDelegate12createEditorEP7QWidgetRK20QStyleOptionViewItemRK11QModelIndex(rsthis.qclsinst, arg0, arg1, arg2)}; let mut ret1 = QWidget::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QStyledItemDelegate::~QStyledItemDelegate(); impl /*struct*/ QStyledItemDelegate { pub fn free<RetType, T: QStyledItemDelegate_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QStyledItemDelegate_free<RetType> { fn free(self , rsthis: & QStyledItemDelegate) -> RetType; } // proto: void QStyledItemDelegate::~QStyledItemDelegate(); impl<'a> /*trait*/ QStyledItemDelegate_free<()> for () { fn free(self , rsthis: & QStyledItemDelegate) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN19QStyledItemDelegateD2Ev()}; unsafe {C_ZN19QStyledItemDelegateD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: void QStyledItemDelegate::updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index); impl /*struct*/ QStyledItemDelegate { pub fn updateEditorGeometry<RetType, T: QStyledItemDelegate_updateEditorGeometry<RetType>>(& self, overload_args: T) -> RetType { return overload_args.updateEditorGeometry(self); // return 1; } } pub trait QStyledItemDelegate_updateEditorGeometry<RetType> { fn updateEditorGeometry(self , rsthis: & QStyledItemDelegate) -> RetType; } // proto: void QStyledItemDelegate::updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index); impl<'a> /*trait*/ QStyledItemDelegate_updateEditorGeometry<()> for (&'a QWidget, &'a QStyleOptionViewItem, &'a QModelIndex) { fn updateEditorGeometry(self , rsthis: & QStyledItemDelegate) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK19QStyledItemDelegate20updateEditorGeometryEP7QWidgetRK20QStyleOptionViewItemRK11QModelIndex()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.qclsinst as *mut c_void; unsafe {C_ZNK19QStyledItemDelegate20updateEditorGeometryEP7QWidgetRK20QStyleOptionViewItemRK11QModelIndex(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: void QStyledItemDelegate::setEditorData(QWidget * editor, const QModelIndex & index); impl /*struct*/ QStyledItemDelegate { pub fn setEditorData<RetType, T: QStyledItemDelegate_setEditorData<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setEditorData(self); // return 1; } } pub trait QStyledItemDelegate_setEditorData<RetType> { fn setEditorData(self , rsthis: & QStyledItemDelegate) -> RetType; } // proto: void QStyledItemDelegate::setEditorData(QWidget * editor, const QModelIndex & index); impl<'a> /*trait*/ QStyledItemDelegate_setEditorData<()> for (&'a QWidget, &'a QModelIndex) { fn setEditorData(self , rsthis: & QStyledItemDelegate) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK19QStyledItemDelegate13setEditorDataEP7QWidgetRK11QModelIndex()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; unsafe {C_ZNK19QStyledItemDelegate13setEditorDataEP7QWidgetRK11QModelIndex(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QStyledItemDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index); impl /*struct*/ QStyledItemDelegate { pub fn setModelData<RetType, T: QStyledItemDelegate_setModelData<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setModelData(self); // return 1; } } pub trait QStyledItemDelegate_setModelData<RetType> { fn setModelData(self , rsthis: & QStyledItemDelegate) -> RetType; } // proto: void QStyledItemDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index); impl<'a> /*trait*/ QStyledItemDelegate_setModelData<()> for (&'a QWidget, &'a QAbstractItemModel, &'a QModelIndex) { fn setModelData(self , rsthis: & QStyledItemDelegate) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK19QStyledItemDelegate12setModelDataEP7QWidgetP18QAbstractItemModelRK11QModelIndex()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.qclsinst as *mut c_void; unsafe {C_ZNK19QStyledItemDelegate12setModelDataEP7QWidgetP18QAbstractItemModelRK11QModelIndex(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: void QStyledItemDelegate::setItemEditorFactory(QItemEditorFactory * factory); impl /*struct*/ QStyledItemDelegate { pub fn setItemEditorFactory<RetType, T: QStyledItemDelegate_setItemEditorFactory<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setItemEditorFactory(self); // return 1; } } pub trait QStyledItemDelegate_setItemEditorFactory<RetType> { fn setItemEditorFactory(self , rsthis: & QStyledItemDelegate) -> RetType; } // proto: void QStyledItemDelegate::setItemEditorFactory(QItemEditorFactory * factory); impl<'a> /*trait*/ QStyledItemDelegate_setItemEditorFactory<()> for (&'a QItemEditorFactory) { fn setItemEditorFactory(self , rsthis: & QStyledItemDelegate) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN19QStyledItemDelegate20setItemEditorFactoryEP18QItemEditorFactory()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN19QStyledItemDelegate20setItemEditorFactoryEP18QItemEditorFactory(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QStyledItemDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index); impl /*struct*/ QStyledItemDelegate { pub fn paint<RetType, T: QStyledItemDelegate_paint<RetType>>(& self, overload_args: T) -> RetType { return overload_args.paint(self); // return 1; } } pub trait QStyledItemDelegate_paint<RetType> { fn paint(self , rsthis: & QStyledItemDelegate) -> RetType; } // proto: void QStyledItemDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index); impl<'a> /*trait*/ QStyledItemDelegate_paint<()> for (&'a QPainter, &'a QStyleOptionViewItem, &'a QModelIndex) { fn paint(self , rsthis: & QStyledItemDelegate) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK19QStyledItemDelegate5paintEP8QPainterRK20QStyleOptionViewItemRK11QModelIndex()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.qclsinst as *mut c_void; unsafe {C_ZNK19QStyledItemDelegate5paintEP8QPainterRK20QStyleOptionViewItemRK11QModelIndex(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: QItemEditorFactory * QStyledItemDelegate::itemEditorFactory(); impl /*struct*/ QStyledItemDelegate { pub fn itemEditorFactory<RetType, T: QStyledItemDelegate_itemEditorFactory<RetType>>(& self, overload_args: T) -> RetType { return overload_args.itemEditorFactory(self); // return 1; } } pub trait QStyledItemDelegate_itemEditorFactory<RetType> { fn itemEditorFactory(self , rsthis: & QStyledItemDelegate) -> RetType; } // proto: QItemEditorFactory * QStyledItemDelegate::itemEditorFactory(); impl<'a> /*trait*/ QStyledItemDelegate_itemEditorFactory<QItemEditorFactory> for () { fn itemEditorFactory(self , rsthis: & QStyledItemDelegate) -> QItemEditorFactory { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK19QStyledItemDelegate17itemEditorFactoryEv()}; let mut ret = unsafe {C_ZNK19QStyledItemDelegate17itemEditorFactoryEv(rsthis.qclsinst)}; let mut ret1 = QItemEditorFactory::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QStyledItemDelegate::QStyledItemDelegate(QObject * parent); impl /*struct*/ QStyledItemDelegate { pub fn new<T: QStyledItemDelegate_new>(value: T) -> QStyledItemDelegate { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QStyledItemDelegate_new { fn new(self) -> QStyledItemDelegate; } // proto: void QStyledItemDelegate::QStyledItemDelegate(QObject * parent); impl<'a> /*trait*/ QStyledItemDelegate_new for (Option<&'a QObject>) { fn new(self) -> QStyledItemDelegate { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN19QStyledItemDelegateC2EP7QObject()}; let ctysz: c_int = unsafe{QStyledItemDelegate_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void; let qthis: u64 = unsafe {C_ZN19QStyledItemDelegateC2EP7QObject(arg0)}; let rsthis = QStyledItemDelegate{qbase: QAbstractItemDelegate::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QString QStyledItemDelegate::displayText(const QVariant & value, const QLocale & locale); impl /*struct*/ QStyledItemDelegate { pub fn displayText<RetType, T: QStyledItemDelegate_displayText<RetType>>(& self, overload_args: T) -> RetType { return overload_args.displayText(self); // return 1; } } pub trait QStyledItemDelegate_displayText<RetType> { fn displayText(self , rsthis: & QStyledItemDelegate) -> RetType; } // proto: QString QStyledItemDelegate::displayText(const QVariant & value, const QLocale & locale); impl<'a> /*trait*/ QStyledItemDelegate_displayText<QString> for (&'a QVariant, &'a QLocale) { fn displayText(self , rsthis: & QStyledItemDelegate) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK19QStyledItemDelegate11displayTextERK8QVariantRK7QLocale()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK19QStyledItemDelegate11displayTextERK8QVariantRK7QLocale(rsthis.qclsinst, arg0, arg1)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: const QMetaObject * QStyledItemDelegate::metaObject(); impl /*struct*/ QStyledItemDelegate { pub fn metaObject<RetType, T: QStyledItemDelegate_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QStyledItemDelegate_metaObject<RetType> { fn metaObject(self , rsthis: & QStyledItemDelegate) -> RetType; } // proto: const QMetaObject * QStyledItemDelegate::metaObject(); impl<'a> /*trait*/ QStyledItemDelegate_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QStyledItemDelegate) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK19QStyledItemDelegate10metaObjectEv()}; let mut ret = unsafe {C_ZNK19QStyledItemDelegate10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // <= body block end
pub mod compiler; pub mod descriptor_pb;
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct IOcrEngine(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IOcrEngine { type Vtable = IOcrEngine_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5a14bc41_5b76_3140_b680_8825562683ac); } #[repr(C)] #[doc(hidden)] pub struct IOcrEngine_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 = "Graphics_Imaging"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bitmap: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Graphics_Imaging")))] usize, #[cfg(feature = "Globalization")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Globalization"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IOcrEngineStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IOcrEngineStatics { type Vtable = IOcrEngineStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5bffa85a_3384_3540_9940_699120d428a8); } #[repr(C)] #[doc(hidden)] pub struct IOcrEngineStatics_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 u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation_Collections", feature = "Globalization"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation_Collections", feature = "Globalization")))] usize, #[cfg(feature = "Globalization")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, language: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, #[cfg(not(feature = "Globalization"))] usize, #[cfg(feature = "Globalization")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, language: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Globalization"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IOcrLine(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IOcrLine { type Vtable = IOcrLine_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0043a16f_e31f_3a24_899c_d444bd088124); } #[repr(C)] #[doc(hidden)] pub struct IOcrLine_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, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IOcrResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IOcrResult { type Vtable = IOcrResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9bd235b2_175b_3d6a_92e2_388c206e2f63); } #[repr(C)] #[doc(hidden)] pub struct IOcrResult_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, #[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, 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 IOcrWord(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IOcrWord { type Vtable = IOcrWord_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3c2a477a_5cd9_3525_ba2a_23d1e0a68a1d); } #[repr(C)] #[doc(hidden)] pub struct IOcrWord_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 super::super::Foundation::Rect) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct OcrEngine(pub ::windows::core::IInspectable); impl OcrEngine { #[cfg(all(feature = "Foundation", feature = "Graphics_Imaging"))] pub fn RecognizeAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Graphics::Imaging::SoftwareBitmap>>(&self, bitmap: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<OcrResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), bitmap.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<OcrResult>>(result__) } } #[cfg(feature = "Globalization")] pub fn RecognizerLanguage(&self) -> ::windows::core::Result<super::super::Globalization::Language> { 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::Globalization::Language>(result__) } } pub fn MaxImageDimension() -> ::windows::core::Result<u32> { Self::IOcrEngineStatics(|this| unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) }) } #[cfg(all(feature = "Foundation_Collections", feature = "Globalization"))] pub fn AvailableRecognizerLanguages() -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<super::super::Globalization::Language>> { Self::IOcrEngineStatics(|this| 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::Collections::IVectorView<super::super::Globalization::Language>>(result__) }) } #[cfg(feature = "Globalization")] pub fn IsLanguageSupported<'a, Param0: ::windows::core::IntoParam<'a, super::super::Globalization::Language>>(language: Param0) -> ::windows::core::Result<bool> { Self::IOcrEngineStatics(|this| unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), language.into_param().abi(), &mut result__).from_abi::<bool>(result__) }) } #[cfg(feature = "Globalization")] pub fn TryCreateFromLanguage<'a, Param0: ::windows::core::IntoParam<'a, super::super::Globalization::Language>>(language: Param0) -> ::windows::core::Result<OcrEngine> { Self::IOcrEngineStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), language.into_param().abi(), &mut result__).from_abi::<OcrEngine>(result__) }) } pub fn TryCreateFromUserProfileLanguages() -> ::windows::core::Result<OcrEngine> { Self::IOcrEngineStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<OcrEngine>(result__) }) } pub fn IOcrEngineStatics<R, F: FnOnce(&IOcrEngineStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<OcrEngine, IOcrEngineStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for OcrEngine { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Ocr.OcrEngine;{5a14bc41-5b76-3140-b680-8825562683ac})"); } unsafe impl ::windows::core::Interface for OcrEngine { type Vtable = IOcrEngine_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5a14bc41_5b76_3140_b680_8825562683ac); } impl ::windows::core::RuntimeName for OcrEngine { const NAME: &'static str = "Windows.Media.Ocr.OcrEngine"; } impl ::core::convert::From<OcrEngine> for ::windows::core::IUnknown { fn from(value: OcrEngine) -> Self { value.0 .0 } } impl ::core::convert::From<&OcrEngine> for ::windows::core::IUnknown { fn from(value: &OcrEngine) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for OcrEngine { 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 OcrEngine { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<OcrEngine> for ::windows::core::IInspectable { fn from(value: OcrEngine) -> Self { value.0 } } impl ::core::convert::From<&OcrEngine> for ::windows::core::IInspectable { fn from(value: &OcrEngine) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for OcrEngine { 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 OcrEngine { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for OcrEngine {} unsafe impl ::core::marker::Sync for OcrEngine {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct OcrLine(pub ::windows::core::IInspectable); impl OcrLine { #[cfg(feature = "Foundation_Collections")] pub fn Words(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<OcrWord>> { 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::Collections::IVectorView<OcrWord>>(result__) } } pub fn Text(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } } unsafe impl ::windows::core::RuntimeType for OcrLine { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Ocr.OcrLine;{0043a16f-e31f-3a24-899c-d444bd088124})"); } unsafe impl ::windows::core::Interface for OcrLine { type Vtable = IOcrLine_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0043a16f_e31f_3a24_899c_d444bd088124); } impl ::windows::core::RuntimeName for OcrLine { const NAME: &'static str = "Windows.Media.Ocr.OcrLine"; } impl ::core::convert::From<OcrLine> for ::windows::core::IUnknown { fn from(value: OcrLine) -> Self { value.0 .0 } } impl ::core::convert::From<&OcrLine> for ::windows::core::IUnknown { fn from(value: &OcrLine) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for OcrLine { 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 OcrLine { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<OcrLine> for ::windows::core::IInspectable { fn from(value: OcrLine) -> Self { value.0 } } impl ::core::convert::From<&OcrLine> for ::windows::core::IInspectable { fn from(value: &OcrLine) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for OcrLine { 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 OcrLine { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for OcrLine {} unsafe impl ::core::marker::Sync for OcrLine {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct OcrResult(pub ::windows::core::IInspectable); impl OcrResult { #[cfg(feature = "Foundation_Collections")] pub fn Lines(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<OcrLine>> { 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::Collections::IVectorView<OcrLine>>(result__) } } #[cfg(feature = "Foundation")] pub fn TextAngle(&self) -> ::windows::core::Result<super::super::Foundation::IReference<f64>> { 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::IReference<f64>>(result__) } } pub fn Text(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } } unsafe impl ::windows::core::RuntimeType for OcrResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Ocr.OcrResult;{9bd235b2-175b-3d6a-92e2-388c206e2f63})"); } unsafe impl ::windows::core::Interface for OcrResult { type Vtable = IOcrResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9bd235b2_175b_3d6a_92e2_388c206e2f63); } impl ::windows::core::RuntimeName for OcrResult { const NAME: &'static str = "Windows.Media.Ocr.OcrResult"; } impl ::core::convert::From<OcrResult> for ::windows::core::IUnknown { fn from(value: OcrResult) -> Self { value.0 .0 } } impl ::core::convert::From<&OcrResult> for ::windows::core::IUnknown { fn from(value: &OcrResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for OcrResult { 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 OcrResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<OcrResult> for ::windows::core::IInspectable { fn from(value: OcrResult) -> Self { value.0 } } impl ::core::convert::From<&OcrResult> for ::windows::core::IInspectable { fn from(value: &OcrResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for OcrResult { 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 OcrResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for OcrResult {} unsafe impl ::core::marker::Sync for OcrResult {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct OcrWord(pub ::windows::core::IInspectable); impl OcrWord { #[cfg(feature = "Foundation")] pub fn BoundingRect(&self) -> ::windows::core::Result<super::super::Foundation::Rect> { let this = self; unsafe { let mut result__: super::super::Foundation::Rect = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Rect>(result__) } } pub fn Text(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } } unsafe impl ::windows::core::RuntimeType for OcrWord { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Ocr.OcrWord;{3c2a477a-5cd9-3525-ba2a-23d1e0a68a1d})"); } unsafe impl ::windows::core::Interface for OcrWord { type Vtable = IOcrWord_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3c2a477a_5cd9_3525_ba2a_23d1e0a68a1d); } impl ::windows::core::RuntimeName for OcrWord { const NAME: &'static str = "Windows.Media.Ocr.OcrWord"; } impl ::core::convert::From<OcrWord> for ::windows::core::IUnknown { fn from(value: OcrWord) -> Self { value.0 .0 } } impl ::core::convert::From<&OcrWord> for ::windows::core::IUnknown { fn from(value: &OcrWord) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for OcrWord { 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 OcrWord { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<OcrWord> for ::windows::core::IInspectable { fn from(value: OcrWord) -> Self { value.0 } } impl ::core::convert::From<&OcrWord> for ::windows::core::IInspectable { fn from(value: &OcrWord) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for OcrWord { 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 OcrWord { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for OcrWord {} unsafe impl ::core::marker::Sync for OcrWord {}
fn divide(x: f64, y: f64) -> Result<f64, ()> { if y == 0.0 { Ok(0.0) }else { Ok(x/y) } } fn main() { let x = match divide(3.0, 1.0) { Ok(val) => val, Err(_) => 0.0, }; println!("nilai x: {}", x); }
use std::error::Error; use std::fmt::{self, Display}; use std::str::FromStr; #[derive(Debug)] pub struct Wallet { amount: f64, address: String, } #[derive(Debug)] pub struct ParseWalletFromString { error: String, } impl Display for ParseWalletFromString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.error) } } impl Into<f64> for Wallet { fn into(self) -> f64 { self.amount } } impl std::error::Error for ParseWalletFromString {} impl FromStr for Wallet { type Err = ParseWalletFromString; fn from_str(s: &str) -> Result<Self, Self::Err> { let split = s.split(";").collect::<Vec<_>>(); let mut parts_iter = split.iter(); if let Some(amount) = parts_iter.next() { if let Some(address) = parts_iter.next() { if let Ok(v) = amount.parse::<f64>() { return Ok(Wallet { amount: v, address: address.to_string(), }); } } } Err(ParseWalletFromString { error: "Could not parse".to_string(), }) } }
#[doc = "Reader of register APB2RSTR"] pub type R = crate::R<u32, super::APB2RSTR>; #[doc = "Writer for register APB2RSTR"] pub type W = crate::W<u32, super::APB2RSTR>; #[doc = "Register APB2RSTR `reset()`'s with value 0"] impl crate::ResetValue for super::APB2RSTR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Alternate function I/O reset\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum AFIORST_A { #[doc = "1: Reset the selected module"] RESET = 1, } impl From<AFIORST_A> for bool { #[inline(always)] fn from(variant: AFIORST_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `AFIORST`"] pub type AFIORST_R = crate::R<bool, AFIORST_A>; impl AFIORST_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<bool, AFIORST_A> { use crate::Variant::*; match self.bits { true => Val(AFIORST_A::RESET), i => Res(i), } } #[doc = "Checks if the value of the field is `RESET`"] #[inline(always)] pub fn is_reset(&self) -> bool { *self == AFIORST_A::RESET } } #[doc = "Write proxy for field `AFIORST`"] pub struct AFIORST_W<'a> { w: &'a mut W, } impl<'a> AFIORST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: AFIORST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(AFIORST_A::RESET) } #[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 = "IO port A reset"] pub type IOPARST_A = AFIORST_A; #[doc = "Reader of field `IOPARST`"] pub type IOPARST_R = crate::R<bool, AFIORST_A>; #[doc = "Write proxy for field `IOPARST`"] pub struct IOPARST_W<'a> { w: &'a mut W, } impl<'a> IOPARST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: IOPARST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(AFIORST_A::RESET) } #[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 = "IO port B reset"] pub type IOPBRST_A = AFIORST_A; #[doc = "Reader of field `IOPBRST`"] pub type IOPBRST_R = crate::R<bool, AFIORST_A>; #[doc = "Write proxy for field `IOPBRST`"] pub struct IOPBRST_W<'a> { w: &'a mut W, } impl<'a> IOPBRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: IOPBRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(AFIORST_A::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "IO port C reset"] pub type IOPCRST_A = AFIORST_A; #[doc = "Reader of field `IOPCRST`"] pub type IOPCRST_R = crate::R<bool, AFIORST_A>; #[doc = "Write proxy for field `IOPCRST`"] pub struct IOPCRST_W<'a> { w: &'a mut W, } impl<'a> IOPCRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: IOPCRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(AFIORST_A::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "IO port D reset"] pub type IOPDRST_A = AFIORST_A; #[doc = "Reader of field `IOPDRST`"] pub type IOPDRST_R = crate::R<bool, AFIORST_A>; #[doc = "Write proxy for field `IOPDRST`"] pub struct IOPDRST_W<'a> { w: &'a mut W, } impl<'a> IOPDRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: IOPDRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(AFIORST_A::RESET) } #[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 = "IO port E reset"] pub type IOPERST_A = AFIORST_A; #[doc = "Reader of field `IOPERST`"] pub type IOPERST_R = crate::R<bool, AFIORST_A>; #[doc = "Write proxy for field `IOPERST`"] pub struct IOPERST_W<'a> { w: &'a mut W, } impl<'a> IOPERST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: IOPERST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(AFIORST_A::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "IO port F reset"] pub type IOPFRST_A = AFIORST_A; #[doc = "Reader of field `IOPFRST`"] pub type IOPFRST_R = crate::R<bool, AFIORST_A>; #[doc = "Write proxy for field `IOPFRST`"] pub struct IOPFRST_W<'a> { w: &'a mut W, } impl<'a> IOPFRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: IOPFRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(AFIORST_A::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "IO port G reset"] pub type IOPGRST_A = AFIORST_A; #[doc = "Reader of field `IOPGRST`"] pub type IOPGRST_R = crate::R<bool, AFIORST_A>; #[doc = "Write proxy for field `IOPGRST`"] pub struct IOPGRST_W<'a> { w: &'a mut W, } impl<'a> IOPGRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: IOPGRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(AFIORST_A::RESET) } #[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 = "ADC 1 interface reset"] pub type ADC1RST_A = AFIORST_A; #[doc = "Reader of field `ADC1RST`"] pub type ADC1RST_R = crate::R<bool, AFIORST_A>; #[doc = "Write proxy for field `ADC1RST`"] pub struct ADC1RST_W<'a> { w: &'a mut W, } impl<'a> ADC1RST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ADC1RST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(AFIORST_A::RESET) } #[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 = "TIM1 timer reset"] pub type TIM1RST_A = AFIORST_A; #[doc = "Reader of field `TIM1RST`"] pub type TIM1RST_R = crate::R<bool, AFIORST_A>; #[doc = "Write proxy for field `TIM1RST`"] pub struct TIM1RST_W<'a> { w: &'a mut W, } impl<'a> TIM1RST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIM1RST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(AFIORST_A::RESET) } #[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 = "SPI 1 reset"] pub type SPI1RST_A = AFIORST_A; #[doc = "Reader of field `SPI1RST`"] pub type SPI1RST_R = crate::R<bool, AFIORST_A>; #[doc = "Write proxy for field `SPI1RST`"] pub struct SPI1RST_W<'a> { w: &'a mut W, } impl<'a> SPI1RST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SPI1RST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(AFIORST_A::RESET) } #[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 = "USART1 reset"] pub type USART1RST_A = AFIORST_A; #[doc = "Reader of field `USART1RST`"] pub type USART1RST_R = crate::R<bool, AFIORST_A>; #[doc = "Write proxy for field `USART1RST`"] pub struct USART1RST_W<'a> { w: &'a mut W, } impl<'a> USART1RST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USART1RST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(AFIORST_A::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "TIM15 timer reset"] pub type TIM15RST_A = AFIORST_A; #[doc = "Reader of field `TIM15RST`"] pub type TIM15RST_R = crate::R<bool, AFIORST_A>; #[doc = "Write proxy for field `TIM15RST`"] pub struct TIM15RST_W<'a> { w: &'a mut W, } impl<'a> TIM15RST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIM15RST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(AFIORST_A::RESET) } #[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 = "TIM16 timer reset"] pub type TIM16RST_A = AFIORST_A; #[doc = "Reader of field `TIM16RST`"] pub type TIM16RST_R = crate::R<bool, AFIORST_A>; #[doc = "Write proxy for field `TIM16RST`"] pub struct TIM16RST_W<'a> { w: &'a mut W, } impl<'a> TIM16RST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIM16RST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(AFIORST_A::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "TIM17 timer reset"] pub type TIM17RST_A = AFIORST_A; #[doc = "Reader of field `TIM17RST`"] pub type TIM17RST_R = crate::R<bool, AFIORST_A>; #[doc = "Write proxy for field `TIM17RST`"] pub struct TIM17RST_W<'a> { w: &'a mut W, } impl<'a> TIM17RST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIM17RST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(AFIORST_A::RESET) } #[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 } } impl R { #[doc = "Bit 0 - Alternate function I/O reset"] #[inline(always)] pub fn afiorst(&self) -> AFIORST_R { AFIORST_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 2 - IO port A reset"] #[inline(always)] pub fn ioparst(&self) -> IOPARST_R { IOPARST_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - IO port B reset"] #[inline(always)] pub fn iopbrst(&self) -> IOPBRST_R { IOPBRST_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - IO port C reset"] #[inline(always)] pub fn iopcrst(&self) -> IOPCRST_R { IOPCRST_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - IO port D reset"] #[inline(always)] pub fn iopdrst(&self) -> IOPDRST_R { IOPDRST_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - IO port E reset"] #[inline(always)] pub fn ioperst(&self) -> IOPERST_R { IOPERST_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - IO port F reset"] #[inline(always)] pub fn iopfrst(&self) -> IOPFRST_R { IOPFRST_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - IO port G reset"] #[inline(always)] pub fn iopgrst(&self) -> IOPGRST_R { IOPGRST_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - ADC 1 interface reset"] #[inline(always)] pub fn adc1rst(&self) -> ADC1RST_R { ADC1RST_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 11 - TIM1 timer reset"] #[inline(always)] pub fn tim1rst(&self) -> TIM1RST_R { TIM1RST_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - SPI 1 reset"] #[inline(always)] pub fn spi1rst(&self) -> SPI1RST_R { SPI1RST_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 14 - USART1 reset"] #[inline(always)] pub fn usart1rst(&self) -> USART1RST_R { USART1RST_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 16 - TIM15 timer reset"] #[inline(always)] pub fn tim15rst(&self) -> TIM15RST_R { TIM15RST_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - TIM16 timer reset"] #[inline(always)] pub fn tim16rst(&self) -> TIM16RST_R { TIM16RST_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - TIM17 timer reset"] #[inline(always)] pub fn tim17rst(&self) -> TIM17RST_R { TIM17RST_R::new(((self.bits >> 18) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Alternate function I/O reset"] #[inline(always)] pub fn afiorst(&mut self) -> AFIORST_W { AFIORST_W { w: self } } #[doc = "Bit 2 - IO port A reset"] #[inline(always)] pub fn ioparst(&mut self) -> IOPARST_W { IOPARST_W { w: self } } #[doc = "Bit 3 - IO port B reset"] #[inline(always)] pub fn iopbrst(&mut self) -> IOPBRST_W { IOPBRST_W { w: self } } #[doc = "Bit 4 - IO port C reset"] #[inline(always)] pub fn iopcrst(&mut self) -> IOPCRST_W { IOPCRST_W { w: self } } #[doc = "Bit 5 - IO port D reset"] #[inline(always)] pub fn iopdrst(&mut self) -> IOPDRST_W { IOPDRST_W { w: self } } #[doc = "Bit 6 - IO port E reset"] #[inline(always)] pub fn ioperst(&mut self) -> IOPERST_W { IOPERST_W { w: self } } #[doc = "Bit 7 - IO port F reset"] #[inline(always)] pub fn iopfrst(&mut self) -> IOPFRST_W { IOPFRST_W { w: self } } #[doc = "Bit 8 - IO port G reset"] #[inline(always)] pub fn iopgrst(&mut self) -> IOPGRST_W { IOPGRST_W { w: self } } #[doc = "Bit 9 - ADC 1 interface reset"] #[inline(always)] pub fn adc1rst(&mut self) -> ADC1RST_W { ADC1RST_W { w: self } } #[doc = "Bit 11 - TIM1 timer reset"] #[inline(always)] pub fn tim1rst(&mut self) -> TIM1RST_W { TIM1RST_W { w: self } } #[doc = "Bit 12 - SPI 1 reset"] #[inline(always)] pub fn spi1rst(&mut self) -> SPI1RST_W { SPI1RST_W { w: self } } #[doc = "Bit 14 - USART1 reset"] #[inline(always)] pub fn usart1rst(&mut self) -> USART1RST_W { USART1RST_W { w: self } } #[doc = "Bit 16 - TIM15 timer reset"] #[inline(always)] pub fn tim15rst(&mut self) -> TIM15RST_W { TIM15RST_W { w: self } } #[doc = "Bit 17 - TIM16 timer reset"] #[inline(always)] pub fn tim16rst(&mut self) -> TIM16RST_W { TIM16RST_W { w: self } } #[doc = "Bit 18 - TIM17 timer reset"] #[inline(always)] pub fn tim17rst(&mut self) -> TIM17RST_W { TIM17RST_W { w: self } } }
//! Shared configuration and tests for accepting ingester addresses as arguments. use http::uri::{InvalidUri, InvalidUriParts, Uri}; use snafu::Snafu; use std::{fmt::Display, str::FromStr}; /// An address to an ingester's gRPC API. Create by using `IngesterAddress::from_str`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct IngesterAddress { uri: Uri, } /// Why a specified ingester address might be invalid #[allow(missing_docs)] #[derive(Snafu, Debug)] pub enum Error { #[snafu(context(false))] Invalid { source: InvalidUri }, #[snafu(display("Port is required; no port found in `{value}`"))] MissingPort { value: String }, #[snafu(context(false))] InvalidParts { source: InvalidUriParts }, } impl FromStr for IngesterAddress { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let uri = Uri::from_str(s)?; if uri.port().is_none() { return MissingPortSnafu { value: s }.fail(); } let uri = if uri.scheme().is_none() { Uri::from_str(&format!("http://{s}"))? } else { uri }; Ok(Self { uri }) } } impl Display for IngesterAddress { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.uri) } } #[cfg(test)] mod tests { use super::*; use clap::{error::ErrorKind, Parser}; use std::env; use test_helpers::{assert_contains, assert_error}; /// Applications such as the router MUST have valid ingester addresses. #[derive(Debug, Clone, clap::Parser)] struct RouterConfig { #[clap( long = "ingester-addresses", env = "TEST_INFLUXDB_IOX_INGESTER_ADDRESSES", required = true, num_args=1.., value_delimiter = ',' )] pub ingester_addresses: Vec<IngesterAddress>, } #[test] fn error_if_not_specified_when_required() { assert_error!( RouterConfig::try_parse_from(["my_binary"]), ref e if e.kind() == ErrorKind::MissingRequiredArgument ); } /// Applications such as the querier might not have any ingester addresses, but if they have /// any, they should be valid. #[derive(Debug, Clone, clap::Parser)] struct QuerierConfig { #[clap( long = "ingester-addresses", env = "TEST_INFLUXDB_IOX_INGESTER_ADDRESSES", required = false, num_args=0.., value_delimiter = ',' )] pub ingester_addresses: Vec<IngesterAddress>, } #[test] fn empty_if_not_specified_when_optional() { assert!(QuerierConfig::try_parse_from(["my_binary"]) .unwrap() .ingester_addresses .is_empty()); } fn both_types_valid(args: &[&'static str], expected: &[&'static str]) { let router = RouterConfig::try_parse_from(args).unwrap(); let actual: Vec<_> = router .ingester_addresses .iter() .map(ToString::to_string) .collect(); assert_eq!(actual, expected); let querier = QuerierConfig::try_parse_from(args).unwrap(); let actual: Vec<_> = querier .ingester_addresses .iter() .map(ToString::to_string) .collect(); assert_eq!(actual, expected); } fn both_types_error(args: &[&'static str], expected_error_message: &'static str) { assert_contains!( RouterConfig::try_parse_from(args).unwrap_err().to_string(), expected_error_message ); assert_contains!( QuerierConfig::try_parse_from(args).unwrap_err().to_string(), expected_error_message ); } #[test] fn accepts_one() { let args = [ "my_binary", "--ingester-addresses", "http://example.com:1234", ]; let expected = ["http://example.com:1234/"]; both_types_valid(&args, &expected); } #[test] fn accepts_two() { let args = [ "my_binary", "--ingester-addresses", "http://example.com:1234,http://example.com:5678", ]; let expected = ["http://example.com:1234/", "http://example.com:5678/"]; both_types_valid(&args, &expected); } #[test] fn rejects_any_invalid_uri() { let args = [ "my_binary", "--ingester-addresses", "http://example.com:1234,", // note the trailing comma; empty URIs are invalid ]; let expected = "error: invalid value '' for '--ingester-addresses"; both_types_error(&args, expected); } #[test] fn rejects_uri_without_port() { let args = [ "my_binary", "--ingester-addresses", "example.com,http://example.com:1234", ]; let expected = "Port is required; no port found in `example.com`"; both_types_error(&args, expected); } #[test] fn no_scheme_assumes_http() { let args = [ "my_binary", "--ingester-addresses", "http://example.com:1234,somescheme://0.0.0.0:1000,127.0.0.1:8080", ]; let expected = [ "http://example.com:1234/", "somescheme://0.0.0.0:1000/", "http://127.0.0.1:8080/", ]; both_types_valid(&args, &expected); } #[test] fn specifying_flag_multiple_times_works() { let args = [ "my_binary", "--ingester-addresses", "http://example.com:1234", "--ingester-addresses", "somescheme://0.0.0.0:1000", "--ingester-addresses", "127.0.0.1:8080", ]; let expected = [ "http://example.com:1234/", "somescheme://0.0.0.0:1000/", "http://127.0.0.1:8080/", ]; both_types_valid(&args, &expected); } #[test] fn specifying_flag_multiple_times_and_using_commas_works() { let args = [ "my_binary", "--ingester-addresses", "http://example.com:1234", "--ingester-addresses", "somescheme://0.0.0.0:1000,127.0.0.1:8080", ]; let expected = [ "http://example.com:1234/", "somescheme://0.0.0.0:1000/", "http://127.0.0.1:8080/", ]; both_types_valid(&args, &expected); } /// Use an environment variable name not shared with any other config to avoid conflicts when /// setting the var in tests. /// Applications such as the router MUST have valid ingester addresses. #[derive(Debug, Clone, clap::Parser)] struct EnvRouterConfig { #[clap( long = "ingester-addresses", env = "NO_CONFLICT_ROUTER_TEST_INFLUXDB_IOX_INGESTER_ADDRESSES", required = true, num_args=1.., value_delimiter = ',' )] pub ingester_addresses: Vec<IngesterAddress>, } #[test] fn required_and_specified_via_environment_variable() { env::set_var( "NO_CONFLICT_ROUTER_TEST_INFLUXDB_IOX_INGESTER_ADDRESSES", "http://example.com:1234,somescheme://0.0.0.0:1000,127.0.0.1:8080", ); let args = ["my_binary"]; let expected = [ "http://example.com:1234/", "somescheme://0.0.0.0:1000/", "http://127.0.0.1:8080/", ]; let router = EnvRouterConfig::try_parse_from(args).unwrap(); let actual: Vec<_> = router .ingester_addresses .iter() .map(ToString::to_string) .collect(); assert_eq!(actual, expected); } /// Use an environment variable name not shared with any other config to avoid conflicts when /// setting the var in tests. /// Applications such as the querier might not have any ingester addresses, but if they have /// any, they should be valid. #[derive(Debug, Clone, clap::Parser)] struct EnvQuerierConfig { #[clap( long = "ingester-addresses", env = "NO_CONFLICT_QUERIER_TEST_INFLUXDB_IOX_INGESTER_ADDRESSES", required = false, num_args=0.., value_delimiter = ',' )] pub ingester_addresses: Vec<IngesterAddress>, } #[test] fn optional_and_specified_via_environment_variable() { env::set_var( "NO_CONFLICT_QUERIER_TEST_INFLUXDB_IOX_INGESTER_ADDRESSES", "http://example.com:1234,somescheme://0.0.0.0:1000,127.0.0.1:8080", ); let args = ["my_binary"]; let expected = [ "http://example.com:1234/", "somescheme://0.0.0.0:1000/", "http://127.0.0.1:8080/", ]; let querier = EnvQuerierConfig::try_parse_from(args).unwrap(); let actual: Vec<_> = querier .ingester_addresses .iter() .map(ToString::to_string) .collect(); assert_eq!(actual, expected); } }
use super::*; use js_sys::{Reflect, Symbol}; use wasm_bindgen::JsCast; use web_sys::WebSocket; use liblumen_alloc::erts::fragment::HeapFragment; use liblumen_web::web_socket; #[wasm_bindgen_test] async fn with_valid_url_returns_ok_tuple() { start_once(); let (url, url_non_null_heap_fragment) = HeapFragment::new_binary_from_str("wss://echo.websocket.org").unwrap(); let options: Options = Default::default(); // ```elixir // web_socket_tuple = Lumen.Web.WebSocket.new(url) // Lumen.Web.Wait.with_return(web_socket_tuple) // ``` let promise = r#async::apply_3::promise( web_socket::module(), web_socket::new_1::function(), vec![url], options, ) .unwrap(); std::mem::drop(url_non_null_heap_fragment); let resolved = JsFuture::from(promise).await.unwrap(); assert!(js_sys::Array::is_array(&resolved)); let resolved_array: js_sys::Array = resolved.dyn_into().unwrap(); assert_eq!(resolved_array.length(), 2); let ok: JsValue = Symbol::for_("ok").into(); assert_eq!(Reflect::get(&resolved_array, &0.into()).unwrap(), ok); assert!(Reflect::get(&resolved_array, &1.into()) .unwrap() .has_type::<WebSocket>()); } #[wasm_bindgen_test] async fn without_valid_url_returns_error_tuple() { start_once(); let (url, url_non_null_heap_fragment) = HeapFragment::new_binary_from_str("invalid_url").unwrap(); let options: Options = Default::default(); // ```elixir // web_socket_tuple = Lumen.Web.WebSocket.new(url) // Lumen.Web.Wait.with_return(web_socket_tuple) // ``` let promise = r#async::apply_3::promise( web_socket::module(), web_socket::new_1::function(), vec![url], options, ) .unwrap(); std::mem::drop(url_non_null_heap_fragment); let resolved = JsFuture::from(promise).await.unwrap(); assert!(js_sys::Array::is_array(&resolved)); let resolved_array: js_sys::Array = resolved.dyn_into().unwrap(); assert_eq!(resolved_array.length(), 2); let error: JsValue = Symbol::for_("error").into(); assert_eq!(Reflect::get(&resolved_array, &0.into()).unwrap(), error); let reason = Reflect::get(&resolved_array, &1.into()).unwrap(); let reason_array: js_sys::Array = reason.dyn_into().unwrap(); assert_eq!(reason_array.length(), 2); let tag: JsValue = Symbol::for_("syntax").into(); assert_eq!(Reflect::get(&reason_array, &0.into()).unwrap(), tag); assert!(Reflect::get(&reason_array, &1.into()).unwrap().is_string()); }
//给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。 // // update(i, val) 函数可以通过将下标为 i 的数值更新为 val,从而对数列进行修改。 // // 示例: // // Given nums = [1, 3, 5] // //sumRange(0, 2) -> 9 //update(1, 2) //sumRange(0, 2) -> 8 // // // 说明: // // // 数组仅可以在 update 函数下进行修改。 // 你可以假设 update 函数与 sumRange 函数的调用次数是均匀分布的。 // // Related Topics 树状数组 线段树 //leetcode submit region begin(Prohibit modification and deletion) struct NumArray { datas: Vec<i32>, } /// /// 解题思路,先够着一个完全二叉树,二叉树最底层,也就是叶节点存放原数据 /// 二叉树父节点等于两个子节点的和,依次向上填满二叉树 /// 空间上用长度是 2^(向上取整(log2(len))) * 2 /// /// /// 改变一个子节点的数据的时候,依次向上更新父节点,直到根节点 时间复杂度O(lgN) /// /// 范围内求和的时候,利用父节点数据求和, 时间复杂度可将为 O(lgN) /// /// /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl NumArray { fn new(nums: Vec<i32>) -> Self { let mut i = 0; while 2_i32.pow(i) < nums.len() as i32 { i += 1; } let len = 2_i32.pow(i) as usize; let mut datas = vec![0; len * 2]; for (idx, val) in nums.into_iter().enumerate() { datas[len + idx] = val; } for i in (1..len).rev() { datas[i] = datas[2 * i] + datas[2 * i + 1]; } let num_arr = NumArray { datas }; return num_arr; } fn update(&mut self, i: i32, val: i32) { let i = i as usize; let mut index = self.datas.len() / 2 + i; self.datas[index] = val; while index != 1 { index = index / 2; self.datas[index] = self.datas[2 * index] + self.datas[2 * index + 1]; } } fn sum_range(&self, i: i32, j: i32) -> i32 { /// /// 完全二叉树当前层的长度 /// datas 完全二叉树 /// fn sum_range(datas: &Vec<i32>, idx: usize, len: usize) -> i32 { if idx == 0 { return datas[len]; } return if idx % 2 == 1 { sum_range(datas, idx / 2, len / 2) } else { sum_range(datas, idx - 1, len) + datas[len + idx] }; } let i = i as usize; let j = j as usize; let mut len = self.datas.len() / 2; let mut ii = len + i; return sum_range(&self.datas, j, len) - sum_range(&self.datas, i, len) + self.datas[ii]; } } /** * Your NumArray object will be instantiated and called as such: * let obj = NumArray::new(nums); * obj.update(i, val); * let ret_2: i32 = obj.sum_range(i, j); */ fn main() { let mut nums = NumArray::new(vec![1, 2, 4, 5, 99, 8, 3]); print_tree(&nums.datas); nums.update(1, 1000); print_tree(&nums.datas); nums.update(3, 1000); print_tree(&nums.datas); println!("{:?}", nums.sum_range(0, 1)); println!("{:?}", nums.sum_range(0, 2)); println!("{:?}", nums.sum_range(1, 3)); println!("{:?}", nums.sum_range(1, 4)); } fn print_tree(nums: &Vec<i32>) { let mut l = 1; for i in 1..nums.len() { if i as i32 == 2_i32.pow(l) - 1 { println!("{}", nums[i]); l += 1; } else { print!("{} ", nums[i]) } } println!(); println!(); }
use crate::{ conditions::{Condition, ConditionConfig}, event::{Event, Value}, topology::config::{ TestCondition, TestDefinition, TestInput, TestInputValue, TransformContext, }, transforms::Transform, }; use indexmap::IndexMap; use std::collections::HashMap; //------------------------------------------------------------------------------ pub struct UnitTestCheck { extract_from: String, conditions: Vec<Box<dyn Condition>>, } pub struct UnitTestTransform { transform: Box<dyn Transform>, next: Vec<String>, } pub struct UnitTest { pub name: String, inputs: Vec<(Vec<String>, Event)>, transforms: IndexMap<String, UnitTestTransform>, checks: Vec<UnitTestCheck>, no_outputs_from: Vec<String>, } //------------------------------------------------------------------------------ fn event_to_string(event: &Event) -> String { match event { Event::Log(log) => serde_json::to_string(&log).unwrap_or_else(|_| "{}".into()), Event::Metric(metric) => serde_json::to_string(&metric).unwrap_or_else(|_| "{}".into()), } } fn events_to_string(name: &str, events: &[Event]) -> String { if events.len() > 1 { format!( " {}s:\n {}", name, events .iter() .map(|e| event_to_string(e)) .collect::<Vec<_>>() .join("\n ") ) } else { events .first() .map(|e| format!(" {}: {}", name, event_to_string(e))) .unwrap_or(format!(" no {}", name)) } } fn walk( node: &str, mut inputs: Vec<Event>, transforms: &mut IndexMap<String, UnitTestTransform>, aggregated_results: &mut HashMap<String, (Vec<Event>, Vec<Event>)>, ) { let mut results = Vec::new(); let mut targets = Vec::new(); if let Some(target) = transforms.get_mut(node) { for input in inputs.clone() { target.transform.transform_into(&mut results, input); } targets = target.next.clone(); } for child in targets { walk(&child, results.clone(), transforms, aggregated_results); } if let Some((mut e_inputs, mut e_results)) = aggregated_results.remove(node) { inputs.append(&mut e_inputs); results.append(&mut e_results); } aggregated_results.insert(node.into(), (inputs, results)); } impl UnitTest { // Executes each test and provides a tuple of inspections and error lists. pub fn run(&mut self) -> (Vec<String>, Vec<String>) { let mut errors = Vec::new(); let mut inspections = Vec::new(); let mut results = HashMap::new(); for input in &self.inputs { for target in &input.0 { walk( target, vec![input.1.clone()], &mut self.transforms, &mut results, ); } } for check in &self.checks { if let Some((inputs, outputs)) = results.get(&check.extract_from) { if check.conditions.is_empty() { inspections.push(format!( "check transform '{}' payloads (events encoded as JSON):\n{}\n{}", check.extract_from, events_to_string("input", inputs), events_to_string("output", outputs), )); continue; } let failed_conditions = check .conditions .iter() .enumerate() .flat_map(|(i, cond)| { let cond_errs = outputs .iter() .enumerate() .filter_map(|(j, e)| { cond.check_with_context(e).err().map(|err| { if outputs.len() > 1 { format!("condition[{}], payload[{}]: {}", i, j, err) } else { format!("condition[{}]: {}", i, err) } }) }) .collect::<Vec<_>>(); if cond_errs.len() < outputs.len() { // At least one output succeeded for this condition. Vec::new() } else { cond_errs } }) .collect::<Vec<_>>(); if !failed_conditions.is_empty() { errors.push(format!( "check transform '{}' failed conditions:\n {}\npayloads (events encoded as JSON):\n{}\n{}", check.extract_from, failed_conditions.join("\n "), events_to_string("input", inputs), events_to_string("output", outputs), )); } if outputs.is_empty() { errors.push(format!( "check transform '{}' failed, no events received.", check.extract_from, )); } } else { errors.push(format!( "check transform '{}' failed: received zero resulting events.", check.extract_from, )); } } for tform in &self.no_outputs_from { if let Some((inputs, outputs)) = results.get(tform) { if !outputs.is_empty() { errors.push(format!( "check transform '{}' failed: expected no outputs.\npayloads (events encoded as JSON):\n{}\n{}", tform, events_to_string("input", inputs), events_to_string("output", outputs), )); } } } (inspections, errors) } } //------------------------------------------------------------------------------ fn links_to_a_leaf( target: &str, leaves: &IndexMap<String, ()>, link_checked: &mut IndexMap<String, bool>, transform_outputs: &IndexMap<String, IndexMap<String, ()>>, ) -> bool { if *link_checked.get(target).unwrap_or(&false) { return true; } let has_linked_children = if let Some(outputs) = transform_outputs.get(target) { outputs .iter() .filter(|(o, _)| links_to_a_leaf(o, leaves, link_checked, transform_outputs)) .count() > 0 } else { false }; let linked = leaves.contains_key(target) || has_linked_children; link_checked.insert(target.to_owned(), linked); linked } /// Reduces a collection of transforms into a set that only contains those that /// link between our root (test input) and a set of leaves (test outputs). fn reduce_transforms( roots: Vec<String>, leaves: &IndexMap<String, ()>, transform_outputs: &mut IndexMap<String, IndexMap<String, ()>>, ) { let mut link_checked: IndexMap<String, bool> = IndexMap::new(); if roots .iter() .map(|r| links_to_a_leaf(r, leaves, &mut link_checked, transform_outputs)) .collect::<Vec<_>>() // Ensure we map each element. .iter() .all(|b| !b) { transform_outputs.clear(); } transform_outputs.retain(|name, children| { let linked = roots.contains(name) || *link_checked.get(name).unwrap_or(&false); if linked { // Also remove all unlinked children. children.retain(|child_name, _| { roots.contains(child_name) || *link_checked.get(child_name).unwrap_or(&false) }) } linked }); } fn build_input( input: &TestInput, expansions: &IndexMap<String, Vec<String>>, ) -> Result<(Vec<String>, Event), String> { let target = if let Some(children) = expansions.get(&input.insert_at) { children.clone() } else { vec![input.insert_at.clone()] }; match input.type_str.as_ref() { "raw" => match input.value.as_ref() { Some(v) => Ok((target, Event::from(v.clone()))), None => Err("input type 'raw' requires the field 'value'".to_string()), }, "log" => { if let Some(log_fields) = &input.log_fields { let mut event = Event::from(""); for (path, value) in log_fields { let value: Value = match value { TestInputValue::String(s) => s.as_bytes().into(), TestInputValue::Boolean(b) => (*b).into(), TestInputValue::Integer(i) => (*i).into(), TestInputValue::Float(f) => (*f).into(), }; event.as_mut_log().insert(path.to_owned(), value); } Ok((target, event)) } else { Err("input type 'log' requires the field 'log_fields'".to_string()) } } "metric" => { if let Some(metric) = &input.metric { Ok((target, Event::Metric(metric.clone()))) } else { Err("input type 'metric' requires the field 'metric'".to_string()) } } _ => Err(format!( "unrecognized input type '{}', expected one of: 'raw', 'log' or 'metric'", input.type_str )), } } fn build_inputs( definition: &TestDefinition, expansions: &IndexMap<String, Vec<String>>, ) -> Result<Vec<(Vec<String>, Event)>, Vec<String>> { let mut inputs = Vec::new(); let mut errors = vec![]; if let Some(input_def) = &definition.input { match build_input(input_def, &expansions) { Ok(input_event) => inputs.push(input_event), Err(err) => errors.push(err), } } else if definition.inputs.is_empty() { errors.push("must specify at least one input.".to_owned()); } for input_def in &definition.inputs { match build_input(input_def, &expansions) { Ok(input_event) => inputs.push(input_event), Err(err) => errors.push(err), } } if errors.is_empty() { Ok(inputs) } else { Err(errors) } } fn build_unit_test( definition: &TestDefinition, expansions: &IndexMap<String, Vec<String>>, config: &super::Config, ) -> Result<UnitTest, Vec<String>> { let mut errors = vec![]; let inputs = match build_inputs(&definition, &expansions) { Ok(inputs) => inputs, Err(mut errs) => { errors.append(&mut errs); Vec::new() } }; // Maps transform names with their output targets (transforms that use it as // an input). let mut transform_outputs: IndexMap<String, IndexMap<String, ()>> = config .transforms .iter() .map(|(k, _)| (k.clone(), IndexMap::new())) .collect(); config.transforms.iter().for_each(|(k, t)| { t.inputs.iter().for_each(|i| { if let Some(outputs) = transform_outputs.get_mut(i) { outputs.insert(k.to_string(), ()); } }) }); for (i, (input_target, _)) in inputs.iter().enumerate() { for target in input_target { if !transform_outputs.contains_key(target) { errors.push(format!( "inputs[{}]: unable to locate target transform '{}'", i, target )); } } } if !errors.is_empty() { return Err(errors); } let mut leaves: IndexMap<String, ()> = IndexMap::new(); definition.outputs.iter().for_each(|o| { leaves.insert(o.extract_from.clone(), ()); }); definition.no_outputs_from.iter().for_each(|o| { leaves.insert(o.clone(), ()); }); // Reduce the configured transforms into just the ones connecting our test // target with output targets. reduce_transforms( inputs .iter() .map(|(names, _)| names) .flatten() .cloned() .collect::<Vec<_>>(), &leaves, &mut transform_outputs, ); // Build reduced transforms. let mut transforms: IndexMap<String, UnitTestTransform> = IndexMap::new(); for (name, transform_config) in &config.transforms { if let Some(outputs) = transform_outputs.remove(name) { match transform_config.inner.build(TransformContext::new_test()) { Ok(transform) => { transforms.insert( name.clone(), UnitTestTransform { transform, next: outputs.into_iter().map(|(k, _)| k).collect(), }, ); } Err(err) => { errors.push(format!("failed to build transform '{}': {}", name, err)); } } } } if !errors.is_empty() { return Err(errors); } definition.outputs.iter().for_each(|o| { if !transforms.contains_key(&o.extract_from) { let targets = inputs.iter().map(|(i, _)| i).flatten().collect::<Vec<_>>(); if targets.len() == 1 { errors.push(format!( "unable to complete topology between target transform '{}' and output target '{}'", targets.first().unwrap(), o.extract_from )); } else { errors.push(format!( "unable to complete topology between target transforms {:?} and output target '{}'", targets, o.extract_from )); } } }); // Build all output conditions. let checks = definition .outputs .iter() .map(|o| { let mut conditions: Vec<Box<dyn Condition>> = Vec::new(); for (index, cond_conf) in o .conditions .as_ref() .unwrap_or(&Vec::new()) .iter() .enumerate() { match cond_conf { TestCondition::Embedded(b) => match b.build() { Ok(c) => { conditions.push(c); } Err(e) => { errors.push(format!( "failed to create test condition '{}': {}", index, e, )); } }, TestCondition::NoTypeEmbedded(n) => match n.build() { Ok(c) => { conditions.push(c); } Err(e) => { errors.push(format!( "failed to create test condition '{}': {}", index, e, )); } }, TestCondition::String(_s) => { errors.push(format!( "failed to create test condition '{}': condition references are not yet supported", index )); } } } UnitTestCheck { extract_from: o.extract_from.clone(), conditions, } }) .collect(); if definition.outputs.is_empty() && definition.no_outputs_from.is_empty() { errors.push( "unit test must contain at least one of `outputs` or `no_outputs_from`.".to_owned(), ); } if !errors.is_empty() { Err(errors) } else { Ok(UnitTest { name: definition.name.clone(), inputs, transforms, checks, no_outputs_from: definition.no_outputs_from.clone(), }) } } pub fn build_unit_tests(config: &mut super::Config) -> Result<Vec<UnitTest>, Vec<String>> { let mut tests = vec![]; let mut errors = vec![]; let expansions = config.expand_macros()?; config .tests .iter() .for_each(|test| match build_unit_test(test, &expansions, config) { Ok(t) => tests.push(t), Err(errs) => { let mut test_err = errs.join("\n"); // Indent all line breaks test_err = test_err.replace("\n", "\n "); test_err.insert_str(0, &format!("Failed to build test '{}':\n ", test.name)); errors.push(test_err); } }); if errors.is_empty() { Ok(tests) } else { Err(errors) } } #[cfg(all( test, feature = "transforms-add_fields", feature = "transforms-swimlanes" ))] mod tests { use super::*; use crate::topology::config::Config; #[test] fn parse_no_input() { let mut config: Config = toml::from_str( r#" [transforms.bar] inputs = ["foo"] type = "add_fields" [transforms.bar.fields] my_string_field = "string value" [[tests]] name = "broken test" [tests.input] insert_at = "foo" value = "nah this doesnt matter" [[tests.outputs]] extract_from = "bar" [[tests.outputs.conditions]] type = "check_fields" "#, ) .unwrap(); let errs = build_unit_tests(&mut config).err().unwrap(); assert_eq!( errs, vec![r#"Failed to build test 'broken test': inputs[0]: unable to locate target transform 'foo'"# .to_owned(),] ); let mut config: Config = toml::from_str( r#" [transforms.bar] inputs = ["foo"] type = "add_fields" [transforms.bar.fields] my_string_field = "string value" [[tests]] name = "broken test" [[tests.inputs]] insert_at = "bar" value = "nah this doesnt matter" [[tests.inputs]] insert_at = "foo" value = "nah this doesnt matter" [[tests.outputs]] extract_from = "bar" [[tests.outputs.conditions]] type = "check_fields" "#, ) .unwrap(); let errs = build_unit_tests(&mut config).err().unwrap(); assert_eq!( errs, vec![r#"Failed to build test 'broken test': inputs[1]: unable to locate target transform 'foo'"# .to_owned(),] ); } #[test] fn parse_no_test_input() { let mut config: Config = toml::from_str( r#" [transforms.bar] inputs = ["foo"] type = "add_fields" [transforms.bar.fields] my_string_field = "string value" [[tests]] name = "broken test" [[tests.outputs]] extract_from = "bar" [[tests.outputs.conditions]] type = "check_fields" "#, ) .unwrap(); let errs = build_unit_tests(&mut config).err().unwrap(); assert_eq!( errs, vec![r#"Failed to build test 'broken test': must specify at least one input."# .to_owned(),] ); } #[test] fn parse_no_outputs() { let mut config: Config = toml::from_str( r#" [transforms.foo] inputs = ["ignored"] type = "add_fields" [transforms.foo.fields] my_string_field = "string value" [[tests]] name = "broken test" [tests.input] insert_at = "foo" value = "nah this doesnt matter" "#, ) .unwrap(); let errs = build_unit_tests(&mut config).err().unwrap(); assert_eq!( errs, vec![r#"Failed to build test 'broken test': unit test must contain at least one of `outputs` or `no_outputs_from`."# .to_owned(),] ); } #[test] fn parse_broken_topology() { let mut config: Config = toml::from_str( r#" [transforms.foo] inputs = ["something"] type = "add_fields" [transforms.foo.fields] foo_field = "string value" [transforms.nah] inputs = ["ignored"] type = "add_fields" [transforms.nah.fields] new_field = "string value" [transforms.baz] inputs = ["bar"] type = "add_fields" [transforms.baz.fields] baz_field = "string value" [transforms.quz] inputs = ["bar"] type = "add_fields" [transforms.quz.fields] quz_field = "string value" [[tests]] name = "broken test" [tests.input] insert_at = "foo" value = "nah this doesnt matter" [[tests.outputs]] extract_from = "baz" [[tests.outputs.conditions]] type = "check_fields" "message.equals" = "not this" [[tests.outputs]] extract_from = "quz" [[tests.outputs.conditions]] type = "check_fields" "message.equals" = "not this" [[tests]] name = "broken test 2" [tests.input] insert_at = "nope" value = "nah this doesnt matter" [[tests.outputs]] extract_from = "quz" [[tests.outputs.conditions]] type = "check_fields" "message.equals" = "not this" [[tests]] name = "broken test 3" [[tests.inputs]] insert_at = "foo" value = "nah this doesnt matter" [[tests.inputs]] insert_at = "nah" value = "nah this doesnt matter" [[tests.outputs]] extract_from = "baz" [[tests.outputs.conditions]] type = "check_fields" "message.equals" = "not this" [[tests.outputs]] extract_from = "quz" [[tests.outputs.conditions]] type = "check_fields" "message.equals" = "not this" "#, ) .unwrap(); let errs = build_unit_tests(&mut config).err().unwrap(); assert_eq!( errs, vec![ r#"Failed to build test 'broken test': unable to complete topology between target transform 'foo' and output target 'baz' unable to complete topology between target transform 'foo' and output target 'quz'"# .to_owned(), r#"Failed to build test 'broken test 2': inputs[0]: unable to locate target transform 'nope'"# .to_owned(), r#"Failed to build test 'broken test 3': unable to complete topology between target transforms ["foo", "nah"] and output target 'baz' unable to complete topology between target transforms ["foo", "nah"] and output target 'quz'"# .to_owned(), ] ); } #[test] fn parse_bad_input_event() { let mut config: Config = toml::from_str( r#" [transforms.foo] inputs = ["ignored"] type = "add_fields" [transforms.foo.fields] my_string_field = "string value" [[tests]] name = "broken test" [tests.input] insert_at = "foo" type = "nah" value = "nah this doesnt matter" [[tests.outputs]] extract_from = "foo" [[tests.outputs.conditions]] type = "check_fields" "#, ) .unwrap(); let errs = build_unit_tests(&mut config).err().unwrap(); assert_eq!( errs, vec![r#"Failed to build test 'broken test': unrecognized input type 'nah', expected one of: 'raw', 'log' or 'metric'"# .to_owned(),] ); } #[test] fn test_success_multi_inputs() { let mut config: Config = toml::from_str( r#" [transforms.foo] inputs = ["ignored"] type = "add_fields" [transforms.foo.fields] new_field = "string value" [transforms.foo_two] inputs = ["ignored"] type = "add_fields" [transforms.foo_two.fields] new_field_two = "second string value" [transforms.bar] inputs = ["foo", "foo_two"] type = "add_fields" [transforms.bar.fields] second_new_field = "also a string value" [transforms.baz] inputs = ["bar"] type = "add_fields" [transforms.baz.fields] third_new_field = "also also a string value" [[tests]] name = "successful test" [[tests.inputs]] insert_at = "foo" value = "nah this doesnt matter" [[tests.inputs]] insert_at = "foo_two" value = "nah this also doesnt matter" [[tests.outputs]] extract_from = "foo" [[tests.outputs.conditions]] type = "check_fields" "new_field.equals" = "string value" "message.equals" = "nah this doesnt matter" [[tests.outputs]] extract_from = "foo_two" [[tests.outputs.conditions]] type = "check_fields" "new_field_two.equals" = "second string value" "message.equals" = "nah this also doesnt matter" [[tests.outputs]] extract_from = "bar" [[tests.outputs.conditions]] type = "check_fields" "new_field.equals" = "string value" "second_new_field.equals" = "also a string value" "message.equals" = "nah this doesnt matter" [[tests.outputs.conditions]] type = "check_fields" "new_field_two.equals" = "second string value" "second_new_field.equals" = "also a string value" "message.equals" = "nah this also doesnt matter" [[tests.outputs]] extract_from = "baz" [[tests.outputs.conditions]] type = "check_fields" "new_field.equals" = "string value" "second_new_field.equals" = "also a string value" "third_new_field.equals" = "also also a string value" "message.equals" = "nah this doesnt matter" [[tests.outputs.conditions]] type = "check_fields" "new_field_two.equals" = "second string value" "second_new_field.equals" = "also a string value" "third_new_field.equals" = "also also a string value" "message.equals" = "nah this also doesnt matter" "#, ) .unwrap(); let mut tests = build_unit_tests(&mut config).unwrap(); assert_eq!(tests[0].run().1, Vec::<String>::new()); } #[test] fn test_success() { let mut config: Config = toml::from_str( r#" [transforms.foo] inputs = ["ignored"] type = "add_fields" [transforms.foo.fields] new_field = "string value" [transforms.bar] inputs = ["foo"] type = "add_fields" [transforms.bar.fields] second_new_field = "also a string value" [transforms.baz] inputs = ["bar"] type = "add_fields" [transforms.baz.fields] third_new_field = "also also a string value" [[tests]] name = "successful test" [tests.input] insert_at = "foo" value = "nah this doesnt matter" [[tests.outputs]] extract_from = "foo" [[tests.outputs.conditions]] type = "check_fields" "new_field.equals" = "string value" "message.equals" = "nah this doesnt matter" [[tests.outputs]] extract_from = "bar" [[tests.outputs.conditions]] type = "check_fields" "new_field.equals" = "string value" "second_new_field.equals" = "also a string value" "message.equals" = "nah this doesnt matter" [[tests.outputs]] extract_from = "baz" [[tests.outputs.conditions]] type = "check_fields" "new_field.equals" = "string value" "second_new_field.equals" = "also a string value" "third_new_field.equals" = "also also a string value" "message.equals" = "nah this doesnt matter" "#, ) .unwrap(); let mut tests = build_unit_tests(&mut config).unwrap(); assert_eq!(tests[0].run().1, Vec::<String>::new()); } #[test] fn test_swimlanes() { let mut config: Config = toml::from_str( r#" [transforms.foo] inputs = ["ignored"] type = "swimlanes" [transforms.foo.lanes.first] type = "check_fields" "message.eq" = "test swimlane 1" [transforms.foo.lanes.second] type = "check_fields" "message.eq" = "test swimlane 2" [transforms.bar] inputs = ["foo.first"] type = "add_fields" [transforms.bar.fields] new_field = "new field added" [[tests]] name = "successful swimlanes test 1" [tests.input] insert_at = "foo" value = "test swimlane 1" [[tests.outputs]] extract_from = "foo.first" [[tests.outputs.conditions]] type = "check_fields" "message.equals" = "test swimlane 1" [[tests.outputs]] extract_from = "bar" [[tests.outputs.conditions]] type = "check_fields" "message.equals" = "test swimlane 1" "new_field.equals" = "new field added" [[tests]] name = "successful swimlanes test 2" [tests.input] insert_at = "foo" value = "test swimlane 2" [[tests.outputs]] extract_from = "foo.second" [[tests.outputs.conditions]] type = "check_fields" "message.equals" = "test swimlane 2" "#, ) .unwrap(); let mut tests = build_unit_tests(&mut config).unwrap(); assert_eq!(tests[0].run().1, Vec::<String>::new()); } #[test] fn test_fail_no_outputs() { let mut config: Config = toml::from_str( r#" [transforms.foo] inputs = [ "TODO" ] type = "field_filter" field = "not_exist" value = "not_value" [[tests]] name = "check_no_outputs" [tests.input] insert_at = "foo" type = "raw" value = "test value" [[tests.outputs]] extract_from = "foo" [[tests.outputs.conditions]] type = "check_fields" "message.equals" = "test value" "#, ) .unwrap(); let mut tests = build_unit_tests(&mut config).unwrap(); assert_ne!(tests[0].run().1, Vec::<String>::new()); } #[test] fn test_fail_two_output_events() { let mut config: Config = toml::from_str( r#" [transforms.foo] inputs = [ "TODO" ] type = "add_fields" [transforms.foo.fields] foo = "new field 1" [transforms.bar] inputs = [ "foo" ] type = "add_fields" [transforms.bar.fields] bar = "new field 2" [transforms.baz] inputs = [ "foo" ] type = "add_fields" [transforms.baz.fields] baz = "new field 3" [transforms.boo] inputs = [ "bar", "baz" ] type = "add_fields" [transforms.boo.fields] boo = "new field 4" [[tests]] name = "check_multi_payloads" [tests.input] insert_at = "foo" type = "raw" value = "first" [[tests.outputs]] extract_from = "boo" [[tests.outputs.conditions]] type = "check_fields" "baz.equals" = "new field 3" [[tests.outputs.conditions]] type = "check_fields" "bar.equals" = "new field 2" [[tests]] name = "check_multi_payloads_bad" [tests.input] insert_at = "foo" type = "raw" value = "first" [[tests.outputs]] extract_from = "boo" [[tests.outputs.conditions]] type = "check_fields" "baz.equals" = "new field 3" "bar.equals" = "new field 2" "#, ) .unwrap(); let mut tests = build_unit_tests(&mut config).unwrap(); assert_eq!(tests[0].run().1, Vec::<String>::new()); assert_ne!(tests[1].run().1, Vec::<String>::new()); } #[test] fn test_no_outputs_from() { let mut config: Config = toml::from_str( r#" [transforms.foo] inputs = [ "ignored" ] type = "field_filter" field = "message" value = "foo" [[tests]] name = "check_no_outputs_from_succeeds" no_outputs_from = [ "foo" ] [tests.input] insert_at = "foo" type = "raw" value = "not foo at all" [[tests]] name = "check_no_outputs_from_fails" no_outputs_from = [ "foo" ] [tests.input] insert_at = "foo" type = "raw" value = "foo" "#, ) .unwrap(); let mut tests = build_unit_tests(&mut config).unwrap(); assert_eq!(tests[0].run().1, Vec::<String>::new()); assert_ne!(tests[1].run().1, Vec::<String>::new()); } #[test] fn test_no_outputs_from_chained() { let mut config: Config = toml::from_str( r#" [transforms.foo] inputs = [ "ignored" ] type = "field_filter" field = "message" value = "foo" [transforms.bar] inputs = [ "foo" ] type = "add_fields" [transforms.bar.fields] bar = "new field" [[tests]] name = "check_no_outputs_from_succeeds" no_outputs_from = [ "bar" ] [tests.input] insert_at = "foo" type = "raw" value = "not foo at all" [[tests]] name = "check_no_outputs_from_fails" no_outputs_from = [ "bar" ] [tests.input] insert_at = "foo" type = "raw" value = "foo" "#, ) .unwrap(); let mut tests = build_unit_tests(&mut config).unwrap(); assert_eq!(tests[0].run().1, Vec::<String>::new()); assert_ne!(tests[1].run().1, Vec::<String>::new()); } #[test] fn test_log_input() { let mut config: Config = toml::from_str( r#" [transforms.foo] inputs = ["ignored"] type = "add_fields" [transforms.foo.fields] new_field = "string value" [[tests]] name = "successful test with log event" [tests.input] insert_at = "foo" type = "log" [tests.input.log_fields] message = "this is the message" int_val = 5 bool_val = true [[tests.outputs]] extract_from = "foo" [[tests.outputs.conditions]] type = "check_fields" "new_field.equals" = "string value" "message.equals" = "this is the message" "bool_val.eq" = true "int_val.eq" = 5 "#, ) .unwrap(); let mut tests = build_unit_tests(&mut config).unwrap(); assert_eq!(tests[0].run().1, Vec::<String>::new()); } #[test] fn test_metric_input() { let mut config: Config = toml::from_str( r#" [transforms.foo] inputs = ["ignored"] type = "add_tags" [transforms.foo.tags] new_tag = "new value added" [[tests]] name = "successful test with metric event" [tests.input] insert_at = "foo" type = "metric" [tests.input.metric] kind = "incremental" name = "foometric" [tests.input.metric.tags] tagfoo = "valfoo" [tests.input.metric.counter] value = 100.0 [[tests.outputs]] extract_from = "foo" [[tests.outputs.conditions]] type = "check_fields" "tagfoo.equals" = "valfoo" "new_tag.eq" = "new value added" "#, ) .unwrap(); let mut tests = build_unit_tests(&mut config).unwrap(); assert_eq!(tests[0].run().1, Vec::<String>::new()); } #[test] fn test_success_over_gap() { let mut config: Config = toml::from_str( r#" [transforms.foo] inputs = ["ignored"] type = "add_fields" [transforms.foo.fields] new_field = "string value" [transforms.bar] inputs = ["foo"] type = "add_fields" [transforms.bar.fields] second_new_field = "also a string value" [transforms.baz] inputs = ["bar"] type = "add_fields" [transforms.baz.fields] third_new_field = "also also a string value" [[tests]] name = "successful test" [tests.input] insert_at = "foo" value = "nah this doesnt matter" [[tests.outputs]] extract_from = "baz" [[tests.outputs.conditions]] type = "check_fields" "new_field.equals" = "string value" "second_new_field.equals" = "also a string value" "third_new_field.equals" = "also also a string value" "message.equals" = "nah this doesnt matter" "#, ) .unwrap(); let mut tests = build_unit_tests(&mut config).unwrap(); assert_eq!(tests[0].run().1, Vec::<String>::new()); } #[test] fn test_success_tree() { let mut config: Config = toml::from_str( r#" [transforms.ignored] inputs = ["also_ignored"] type = "add_fields" [transforms.ignored.fields] not_field = "string value" [transforms.foo] inputs = ["ignored"] type = "add_fields" [transforms.foo.fields] new_field = "string value" [transforms.bar] inputs = ["foo"] type = "add_fields" [transforms.bar.fields] second_new_field = "also a string value" [transforms.baz] inputs = ["foo"] type = "add_fields" [transforms.baz.fields] second_new_field = "also also a string value" [[tests]] name = "successful test" [tests.input] insert_at = "foo" value = "nah this doesnt matter" [[tests.outputs]] extract_from = "bar" [[tests.outputs.conditions]] type = "check_fields" "new_field.equals" = "string value" "second_new_field.equals" = "also a string value" "message.equals" = "nah this doesnt matter" [[tests.outputs]] extract_from = "baz" [[tests.outputs.conditions]] type = "check_fields" "new_field.equals" = "string value" "second_new_field.equals" = "also also a string value" "message.equals" = "nah this doesnt matter" "#, ) .unwrap(); let mut tests = build_unit_tests(&mut config).unwrap(); assert_eq!(tests[0].run().1, Vec::<String>::new()); } #[test] fn test_fails() { let mut config: Config = toml::from_str( r#" [transforms.foo] inputs = ["ignored"] type = "remove_fields" fields = ["timestamp"] [transforms.bar] inputs = ["foo"] type = "add_fields" [transforms.bar.fields] second_new_field = "also a string value" [transforms.baz] inputs = ["bar"] type = "add_fields" [transforms.baz.fields] third_new_field = "also also a string value" [[tests]] name = "failing test" [tests.input] insert_at = "foo" value = "nah this doesnt matter" [[tests.outputs]] extract_from = "foo" [[tests.outputs.conditions]] type = "check_fields" "message.equals" = "nah this doesnt matter" [[tests.outputs]] extract_from = "bar" [[tests.outputs.conditions]] type = "check_fields" "message.equals" = "not this" [[tests.outputs.conditions]] type = "check_fields" "second_new_field.equals" = "and not this" [[tests]] name = "another failing test" [tests.input] insert_at = "foo" value = "also this doesnt matter" [[tests.outputs]] extract_from = "foo" [[tests.outputs.conditions]] type = "check_fields" "message.equals" = "also this doesnt matter" [[tests.outputs]] extract_from = "baz" [[tests.outputs.conditions]] type = "check_fields" "second_new_field.equals" = "nope not this" "third_new_field.equals" = "and not this" "message.equals" = "also this doesnt matter" "#, ) .unwrap(); let mut tests = build_unit_tests(&mut config).unwrap(); assert_ne!(tests[0].run().1, Vec::<String>::new()); assert_ne!(tests[1].run().1, Vec::<String>::new()); // TODO: The json representations are randomly ordered so these checks // don't always pass: /* assert_eq!( tests[0].run().1, vec![r#"check transform 'bar' failed conditions: condition[0]: predicates failed: [ message.equals: 'not this' ] condition[1]: predicates failed: [ second_new_field.equals: 'and not this' ] payloads (JSON encoded): input: {"message":"nah this doesnt matter"} output: {"message":"nah this doesnt matter","second_new_field":"also a string value"}"#.to_owned(), ]); assert_eq!( tests[1].run().1, vec![r#"check transform 'baz' failed conditions: condition[0]: predicates failed: [ second_new_field.equals: 'nope not this', third_new_field.equals: 'and not this' ] payloads (JSON encoded): input: {"second_new_field":"also a string value","message":"also this doesnt matter"} output: {"third_new_field":"also also a string value","second_new_field":"also a string value","message":"also this doesnt matter"}"#.to_owned(), ]); */ } }
use rand::random; use ray::Ray; use std::f64::consts::PI; use vec3::{cross, dot, unit_vector, Vec3}; pub fn random_in_unit_disk() -> Vec3 { let mut p = Vec3 { e: [1.0, 1.0, 1.0] }; while dot(&p, &p) >= 1.0 { p = Vec3 { e: [random::<f32>(), random::<f32>(), 0.0], } * 2.0 - Vec3 { e: [1.0, 1.0, 0.0] }; } p } pub struct Camera { origin: Vec3, lower_left_corner: Vec3, horizontal: Vec3, vertical: Vec3, u: Vec3, v: Vec3, lens_radius: f32, } impl Camera { pub fn new( look_from: Vec3, look_at: Vec3, v_up: Vec3, v_fov: f32, aspect: f32, aperture: f32, focus_dist: f32, ) -> Camera { let lens_radius = aperture / 2.0; let theta = v_fov * PI as f32 / 180.0; let half_height = (theta / 2.0).tan(); let half_width = aspect * half_height; let origin = look_from; let w = unit_vector(look_from - look_at); let u = unit_vector(cross(&v_up, &w)); let v = cross(&w, &u); let lower_left_corner = origin - (u * half_width * focus_dist) - (v * half_height * focus_dist) - w * focus_dist; let horizontal = u * half_width * focus_dist * 2.0; let vertical = v * half_height * focus_dist * 2.0; Camera { origin, lower_left_corner, horizontal, vertical, u, v, lens_radius, } } pub fn get_ray(&self, s: f32, t: f32) -> Ray { let rd = random_in_unit_disk() * self.lens_radius; let offset = self.u * rd.x() + self.v * rd.y(); Ray::new( self.origin + offset, self.lower_left_corner + self.horizontal * s + self.vertical * t - self.origin - offset, ) } }
//! Serial use crate::ccu::{Ccu, Clocks}; use crate::gpio::{ Alternate, AF0, AF1, AF2, PB0, PB1, PB2, PB3, PB8, PB9, PD0, PD1, PD2, PD3, PD4, PD5, }; use crate::hal::serial; use crate::pac::ccu::{BusClockGating3, BusSoftReset4}; use crate::pac::uart_common::{ DivisorLatchHigh, DivisorLatchLow, FifoControl, IntEnable, LineControl, LineStatus, NotConfigured, Receive, ReceiveHolding, Status, Transmit, TransmitHolding, }; use crate::pac::{uart0::UART0, uart1::UART1, uart2::UART2, uart3::UART3, uart4::UART4}; use core::convert::Infallible; use core::fmt; use core::marker::PhantomData; use embedded_time::rate::BitsPerSecond; use nb::block; #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum Error { /// RX buffer overrun Overrun, /// Parity check error Parity, /// Framing error Framing, /// Rx FIFO error Fifo, } /// Alias to `write!` that drops the result #[macro_export] macro_rules! console_write { ($dst:expr, $($arg:tt)*) => (write!($dst, $($arg)*).ok()) } /// Alias to `writeln!` that drops the result #[macro_export] macro_rules! console_writeln { ($dst:expr) => ( write!($dst, "\n").ok() ); ($dst:expr,) => ( writeln!($dst).ok() ); ($dst:expr, $($arg:tt)*) => ( writeln!($dst, $($arg)*).ok() ); } // TODO - these should be "closed" traits pub trait Pins<UART> {} pub trait PinTx<UART> {} pub trait PinRx<UART> {} pub trait PinRts<UART> {} pub trait PinCts<UART> {} impl<UART, TX, RX> Pins<UART> for (TX, RX) where TX: PinTx<UART>, RX: PinRx<UART>, { } impl<UART, TX, RX, RTS, CTS> Pins<UART> for (TX, RX, RTS, CTS) where TX: PinTx<UART>, RX: PinRx<UART>, RTS: PinRts<UART>, CTS: PinCts<UART>, { } impl<RxTx> PinTx<UART0<RxTx>> for PB8<Alternate<AF2>> {} impl<RxTx> PinRx<UART0<RxTx>> for PB9<Alternate<AF2>> {} // TODO UART1 pins impl<RxTx> PinTx<UART2<RxTx>> for PB0<Alternate<AF0>> {} impl<RxTx> PinRx<UART2<RxTx>> for PB1<Alternate<AF0>> {} impl<RxTx> PinRts<UART2<RxTx>> for PB2<Alternate<AF0>> {} impl<RxTx> PinCts<UART2<RxTx>> for PB3<Alternate<AF0>> {} // TODO - PH pins impl<RxTx> PinTx<UART3<RxTx>> for PD0<Alternate<AF1>> {} impl<RxTx> PinRx<UART3<RxTx>> for PD1<Alternate<AF1>> {} impl<RxTx> PinTx<UART4<RxTx>> for PD2<Alternate<AF1>> {} impl<RxTx> PinRx<UART4<RxTx>> for PD3<Alternate<AF1>> {} impl<RxTx> PinRts<UART4<RxTx>> for PD4<Alternate<AF1>> {} impl<RxTx> PinCts<UART4<RxTx>> for PD5<Alternate<AF1>> {} pub struct Serial<UART, PINS> { uart: UART, pins: PINS, } /// Serial receiver pub struct Rx<UART> { _uart: PhantomData<UART>, } /// Serial transmitter pub struct Tx<UART> { _uart: PhantomData<UART>, } macro_rules! hal { ($( $UARTX:ident: ($uartX:ident, $UartX:ident, $BCGr:ident, $BCGt:ident, $BSRr:ident, $BSRt:ident), )+) => { $( impl<PINS, RxTx> Serial<$UARTX<RxTx>, PINS> { pub fn $uartX( uart: $UARTX<RxTx>, pins: PINS, baud_rate: BitsPerSecond, clocks: Clocks, ccu: &mut Ccu, ) -> Self where PINS: Pins<$UARTX<RxTx>>, { ccu.$BCGr.enr().modify($BCGt::$UartX::Set); ccu.$BSRr.rstr().modify($BSRt::$UartX::Clear); ccu.$BSRr.rstr().modify($BSRt::$UartX::Set); let _ = ccu.$BSRr.rstr().is_set($BSRt::$UartX::Set); // Disable UART unsafe { (*$UARTX::<NotConfigured>::mut_ptr()) .lcr .modify(LineControl::DivisorLatchAccess::Set); (*$UARTX::<NotConfigured>::mut_ptr()) .dll .modify(DivisorLatchLow::Lsb::Clear); (*$UARTX::<NotConfigured>::mut_ptr()) .dlh .modify(DivisorLatchHigh::Msb::Clear); (*$UARTX::<NotConfigured>::mut_ptr()) .lcr .modify(LineControl::DivisorLatchAccess::Clear); } // Disable interrupts unsafe { (*$UARTX::<Transmit>::mut_ptr()) .ier .modify(IntEnable::Erbfi::Clear + IntEnable::Etbei::Clear + IntEnable::Elsi::Clear + IntEnable::Edssi::Clear + IntEnable::Ptime::Clear) }; // Disable FIFOs unsafe { (*$UARTX::<Transmit>::mut_ptr()) .fcr .modify(FifoControl::FifoEnable::Clear) }; // Clear MCR unsafe { (*$UARTX::<NotConfigured>::mut_ptr()).mcr.write(0) }; // Setup 8-N-1 unsafe { (*$UARTX::<NotConfigured>::mut_ptr()).lcr.modify( LineControl::DataLength::EightBits + LineControl::StopBits::One + LineControl::ParityEnable::Clear, ) }; // Enable and reset FIFOs unsafe { (*$UARTX::<Transmit>::mut_ptr()) .fcr .modify(FifoControl::FifoEnable::Set) }; // Setup baudrate, enable UART // // Baudrate = serial-clock / (16 * divisor) // => divisor = (serial-clock / 16) / baudrate // // Add half of the denominator to deal with rounding errors let divisor = (clocks.apb2().0 + (8 * baud_rate.0)) / (16 * baud_rate.0); let lsb = divisor & 0xFF; let msb = (divisor >> 8) & 0xFF; unsafe { (*$UARTX::<NotConfigured>::mut_ptr()) .lcr .modify(LineControl::DivisorLatchAccess::Set); (*$UARTX::<NotConfigured>::mut_ptr()) .dll .modify(DivisorLatchLow::Lsb::Field::new(lsb).unwrap()); (*$UARTX::<NotConfigured>::mut_ptr()) .dlh .modify(DivisorLatchHigh::Msb::Field::new(msb).unwrap()); (*$UARTX::<NotConfigured>::mut_ptr()) .lcr .modify(LineControl::DivisorLatchAccess::Clear); } Serial { uart, pins } } pub fn split(self) -> (Tx<$UARTX<RxTx>>, Rx<$UARTX<RxTx>>) { (Tx { _uart: PhantomData }, Rx { _uart: PhantomData }) } pub fn free(self) -> ($UARTX<RxTx>, PINS) { (self.uart, self.pins) } } impl<RxTx> serial::Read<u8> for Rx<$UARTX<RxTx>> { type Error = Error; fn read(&mut self) -> nb::Result<u8, Self::Error> { let uart = unsafe { &mut *$UARTX::<Receive>::mut_ptr() }; if uart.lsr.is_set(LineStatus::OverrunError::Set) { Err(nb::Error::Other(Error::Overrun)) } else if uart.lsr.is_set(LineStatus::ParityError::Set) { Err(nb::Error::Other(Error::Parity)) } else if uart.lsr.is_set(LineStatus::FramingError::Set) { Err(nb::Error::Other(Error::Framing)) } else if uart.lsr.is_set(LineStatus::RxFifoError::Set) { Err(nb::Error::Other(Error::Fifo)) } else if uart.sr.is_set(Status::RxFifoNotEmpty::Set) { Ok(uart .rhr .get_field(ReceiveHolding::Data::Read) .unwrap() .val() as u8) } else { Err(nb::Error::WouldBlock) } } } impl<RxTx> serial::Write<u8> for Tx<$UARTX<RxTx>> { // TODO - any real errors? // FIFOs should always be enabled type Error = Infallible; fn flush(&mut self) -> nb::Result<(), Self::Error> { let uart = unsafe { &mut *$UARTX::<Transmit>::mut_ptr() }; if uart.sr.is_set(Status::TxFifoEmpty::Set) { Ok(()) } else { Err(nb::Error::WouldBlock) } } fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> { let uart = unsafe { &mut *$UARTX::<Transmit>::mut_ptr() }; if uart.sr.is_set(Status::TxFifoNotFull::Set) { uart.thr .modify(TransmitHolding::Data::Field::new(byte as _).unwrap()); Ok(()) } else { Err(nb::Error::WouldBlock) } } } impl<RxTx> core::fmt::Write for Tx<$UARTX<RxTx>> { fn write_str(&mut self, s: &str) -> fmt::Result { use serial::Write; for b in s.bytes() { block!(self.write(b)).map_err(|_| fmt::Error)?; } Ok(()) } } )+ } } hal! { UART0: (uart0, Uart0, bcg3, BusClockGating3, bsr4, BusSoftReset4), UART1: (uart1, Uart1, bcg3, BusClockGating3, bsr4, BusSoftReset4), UART2: (uart2, Uart2, bcg3, BusClockGating3, bsr4, BusSoftReset4), UART3: (uart3, Uart3, bcg3, BusClockGating3, bsr4, BusSoftReset4), UART4: (uart4, Uart4, bcg3, BusClockGating3, bsr4, BusSoftReset4), }
use actix_web::{HttpRequest, HttpResponse, Result}; use actix_web::middleware::{Middleware, Response, Started}; use base64::decode; use http::{header, StatusCode}; use std::str; use std::str::FromStr; use api::error::APIError; use api::State; use api::state::UserStore; use user::User; #[derive(Debug)] pub struct BasicAuth; #[derive(Debug)] pub struct UrlAuth; pub struct AuthReq { key: String, secret: String, } impl FromStr for AuthReq { type Err = APIError; fn from_str(s: &str) -> Result<Self, Self::Err> { let decoded = decode(s).or(Err(APIError::FailedToParseAuth))?; let parts = str::from_utf8(&decoded[..]) .or(Err(APIError::FailedToParseAuth))? .split(":") .collect::<Vec<&str>>(); Ok(AuthReq { key: parts[0].to_string(), secret: parts[1].to_string(), }) } } fn find_user(auth: &AuthReq, store: &Box<UserStore>) -> Option<User> { store.get(&"users".to_string(), auth.key.as_str()).unwrap_or(None) } fn verifiy_auth(auth: &AuthReq, store: &Box<UserStore>) -> Option<User> { find_user(auth, store).and_then(|user| { if user.verify_secret(&auth.secret) { Some(user) } else { None } }) } fn handle_auth(auth: &AuthReq, req: &HttpRequest<State>) -> Started { if let Some(user) = verifiy_auth(auth, req.state().users()) { req.extensions_mut().insert(user); Started::Done } else { Started::Response(HttpResponse::new( StatusCode::UNAUTHORIZED )) } } impl Middleware<State> for BasicAuth { fn start(&self, req: &HttpRequest<State>) -> Result<Started> { // If the user was already authenticated by some other means, // use the already set user if req.extensions().get::<User>().is_some() { Ok(Started::Done) } else { let auth_test = req .headers() .get(header::AUTHORIZATION) .and_then(|auth| auth.to_str().ok()) .and_then(|auth| auth[6..].parse::<AuthReq>().ok()); if let Some(auth_req) = auth_test { Ok(handle_auth(&auth_req, req)) } else { println!("Denied access to due to missing credentials"); Ok(Started::Response(HttpResponse::new( StatusCode::UNAUTHORIZED ))) } } } fn response(&self, _: &HttpRequest<State>, resp: HttpResponse) -> Result<Response> { Ok(Response::Done(resp)) } } impl Middleware<State> for UrlAuth { fn start(&self, req: &HttpRequest<State>) -> Result<Started> { // If the user was already authenticated by some other means, // use the already set user if req.extensions().get::<User>().is_some() { Ok(Started::Done) } else { let auth_test = req.query().get("auth").and_then(|auth| auth.parse::<AuthReq>().ok()); if let Some(auth_req) = auth_test { Ok(handle_auth(&auth_req, req)) } else { Ok(Started::Done) } } } fn response(&self, _: &HttpRequest<State>, resp: HttpResponse) -> Result<Response> { Ok(Response::Done(resp)) } }
//============================================================================== // Notes //============================================================================== // mcu::adc.rs //============================================================================== // Crates and Mods //============================================================================== use core::cell::RefCell; use core::ops::DerefMut; use core::ptr; use cortex_m::interrupt::{free, Mutex}; use crate::config; use nrf52832_pac; use super::gpio; //============================================================================== // Enums, Structs, and Types //============================================================================== #[derive(Copy, Clone)] pub struct AdcLine { pub pin: u8, pub channel: u8, pub resolution: nrf52832_pac::saadc::resolution::VAL_A } //============================================================================== // Variables //============================================================================== static ADC_HANDLE: Mutex<RefCell<Option<nrf52832_pac::SAADC>>> = Mutex::new(RefCell::new(None)); const ADC_LINE: AdcLine = AdcLine { pin: config::BATTERY_ADC_PIN, channel: config::BATTERY_ADC_CHANNEL, resolution: nrf52832_pac::saadc::resolution::VAL_A::_12BIT }; //============================================================================== // Public Functions //============================================================================== pub fn init(adc: nrf52832_pac::SAADC){ configure(&adc); free(|cs| ADC_HANDLE.borrow(cs).replace(Some(adc))); } pub fn get_busy() -> bool { // Will always be a blocking call. Return false false } pub fn read_adc() -> u16 { free(|cs| { if let Some(ref mut adc) = ADC_HANDLE.borrow(cs).borrow_mut().deref_mut() { adc.ch[ADC_LINE.channel as usize].config.write(|w| w .resp().bypass() .resn().bypass() .gain().gain1_6() .refsel().internal() .tacq()._10us() .mode().se() .burst().disabled() ); for s in 0..config::ADC_RAM_BUFFER_LEN { // Define the result pointer and number of tranfers adc.result.ptr.write(|w| unsafe { w.bits(config::ADC_RAM_BUFFER + (s * 2) as u32)}); adc.result.maxcnt.write(|w| unsafe { w.maxcnt().bits(1) }); // Clear sampling flags adc.events_done.write(|w| unsafe { w.bits(0) }); // adc.events_resultdone.write(|w| unsafe { w.bits(0) }); // adc.events_end.write(|w| unsafe { w.bits(0) }); // Start the one-shot read // adc.tasks_start.write(|w| unsafe { w.bits(1) }); adc.tasks_sample.write(|w| unsafe { w.bits(1) }); // Wait for finish while adc.events_done.read().bits() == 0 {} } let mut sample: u32 = 0; for s in 0..config::ADC_RAM_BUFFER_LEN { let address: *const u16 = (config::ADC_RAM_BUFFER as u32 + (s as u32 * 2)) as *const u16; sample = sample + unsafe { *ptr::read(ptr::addr_of!(address)) as u32 }; } (sample / config::ADC_RAM_BUFFER_LEN as u32) as u16 } else { 0 } }) } //============================================================================== // Private Functions //============================================================================== fn configure(adc: &nrf52832_pac::SAADC) { adc.enable.write(|w| w.enable().disabled()); // Configure the pin gpio::pin_setup( ADC_LINE.pin, nrf52832_pac::p0::pin_cnf::DIR_A::INPUT, gpio::PinState::PinLow, nrf52832_pac::p0::pin_cnf::PULL_A::DISABLED ); // Clear all bits to be safe adc.intenclr.write(|w| unsafe { w.bits(0x3FFFFF) }); // Enable end event interrupt adc.intenset.write(|w| w.end().set()); // Enable the ADC when finished adc.enable.write(|w| w.enable().enabled()); } //============================================================================== // Interrupt Handler //============================================================================== //============================================================================== // Task Handler //==============================================================================
use yew::{html, Component, ComponentLink, Html, ShouldRender}; use crate::components::Header; use crate::components::Test; pub struct App; impl Component for App { type Message = (); type Properties = (); fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self { App {} } fn update(&mut self, _msg: Self::Message) -> ShouldRender { true } fn view(&self) -> Html { html! { <> <Header /> <section class="section"> <div class="container"> <Test /> </div> </section> </> } } }
extern crate actix_web; extern crate futures; extern crate juniper; use std::env; use std::io; use std::sync::Arc; use actix_web::{web, App, Error, HttpResponse, HttpServer}; use futures::future::Future; use juniper::http::graphiql::graphiql_source; use juniper::http::GraphQLRequest; mod graphql_schema; use crate::graphql_schema::{create_schema, Schema}; fn main() -> io::Result<()> { let schema = std::sync::Arc::new(create_schema()); let url = get_base_url(); HttpServer::new(move || { App::new() .data(schema.clone()) .service(web::resource("/graphql").route(web::post().to_async(graphql))) .service(web::resource("/graphiql").route(web::get().to(graphiql))) }) .bind(url)? .run() } fn graphql( st: web::Data<Arc<Schema>>, data: web::Json<GraphQLRequest>, ) -> impl Future<Item = HttpResponse, Error = Error> { web::block(move || { let res = data.execute(&st, &()); Ok::<_, serde_json::error::Error>(serde_json::to_string(&res)?) }) .map_err(Error::from) .and_then(|user| { Ok(HttpResponse::Ok() .content_type("application/json") .body(user)) }) } fn graphiql() -> HttpResponse { let html = graphiql_source("http://localhost:3003/graphql"); HttpResponse::Ok() .content_type("text/html; charset=utf-8") .body(html) } fn get_env_string<'a>(key: &'a str, default: &'a str) -> String { env::var(key).unwrap_or_else(|_error| default.to_owned()) } fn get_base_url() -> String { let host = get_env_string("HOST", "0.0.0.0"); let port = get_env_string("PORT", "3003"); host + ":" + port.as_str() }
//! Border thickness and color use crate::{ data::WidgetData, geometry::{measurement::MeasureSpec, BoundingBox, MeasuredSize, Position}, state::WidgetState, widgets::{ utils::{ decorator::WidgetDecorator, wrapper::{Wrapper, WrapperBindable}, }, Widget, }, }; pub trait BorderProperties { type Color; fn set_border_color(&mut self, color: Self::Color); fn get_border_width(&self) -> u32; } pub struct Border<W, P> where P: BorderProperties, { pub inner: W, pub border_properties: P, pub on_state_changed: fn(&mut Self, WidgetState), } impl<W, P> Border<W, P> where W: Widget, P: BorderProperties, { pub fn new(inner: W) -> Border<W, P> where P: Default, { Border { border_properties: P::default(), inner, on_state_changed: |_, _| (), } } } impl<W, P> WrapperBindable for Border<W, P> where W: Widget, P: BorderProperties, { } impl<W, P> Border<W, P> where P: BorderProperties, { pub fn border_color(mut self, color: P::Color) -> Self { self.set_border_color(color); self } pub fn set_border_color(&mut self, color: P::Color) { self.border_properties.set_border_color(color); } pub fn on_state_changed(mut self, callback: fn(&mut Self, WidgetState)) -> Self { self.on_state_changed = callback; self } } impl<W, P, D> Wrapper<Border<W, P>, D> where W: Widget, P: BorderProperties, D: WidgetData, { pub fn border_color(mut self, color: P::Color) -> Self { self.widget.set_border_color(color); self } pub fn on_state_changed(mut self, callback: fn(&mut Border<W, P>, WidgetState)) -> Self { // TODO this should be pulled up self.widget.on_state_changed = callback; self } } impl<W, P> WidgetDecorator for Border<W, P> where W: Widget, P: BorderProperties, { type Widget = W; fn widget(&self) -> &Self::Widget { &self.inner } fn widget_mut(&mut self) -> &mut Self::Widget { &mut self.inner } fn arrange(&mut self, position: Position) { let bw = self.border_properties.get_border_width(); self.inner.arrange(Position { x: position.x + bw as i32, y: position.y + bw as i32, }); } fn bounding_box(&self) -> BoundingBox { let bw = self.border_properties.get_border_width(); let bounds = self.inner.bounding_box(); BoundingBox { position: Position { x: bounds.position.x - bw as i32, y: bounds.position.y - bw as i32, }, size: MeasuredSize { width: bounds.size.width + 2 * bw, height: bounds.size.height + 2 * bw, }, } } fn measure(&mut self, measure_spec: MeasureSpec) { let bw = self.border_properties.get_border_width(); self.inner.measure(MeasureSpec { width: measure_spec.width.shrink(2 * bw), height: measure_spec.height.shrink(2 * bw), }); } fn fire_on_state_changed(&mut self, state: WidgetState) { (self.on_state_changed)(self, state); } }
use super::stat_expr_types::DataType; use std::collections::BTreeMap; use std::convert::From; use std::rc::Rc; use std::string::ToString; #[derive(Debug, PartialEq, Clone, Eq, Hash)] pub struct FunctionType<'a> { pub signature: (Vec<(&'a str, SyntaxType<'a>)>, SyntaxType<'a>), } impl<'a> FunctionType<'a> { pub fn new(signature: (Vec<(&'a str, SyntaxType<'a>)>, SyntaxType<'a>)) -> FunctionType<'a> { FunctionType { signature } } pub fn arg_names(&self) -> Vec<&'a str> { (self.signature).0.iter().map(|s| s.0).collect() } pub fn get_type_by_name(&self, name: &str) -> Option<&SyntaxType<'a>> { self.signature .0 .iter() .find_map(|s| if s.0 == name { Some(&s.1) } else { None }) } pub fn get_type(&self, index: usize) -> Option<&SyntaxType<'a>> { match self.signature.0.get(index) { Some(v) => Some(&v.1), None => None, } } } #[derive(Debug, PartialEq, Clone, Eq, Hash)] pub struct FunctionTypes<'a>(pub Vec<FunctionType<'a>>); #[derive(Debug, PartialEq, Clone, Eq, Hash)] pub enum SimpleSyntaxType { Int, Float, Bool, Na, String, Color, } impl<'a> From<DataType<'a>> for SimpleSyntaxType { fn from(data_type: DataType<'a>) -> Self { match data_type { DataType::Bool => SimpleSyntaxType::Bool, DataType::Int => SimpleSyntaxType::Int, DataType::Float => SimpleSyntaxType::Float, DataType::String => SimpleSyntaxType::String, DataType::Color => SimpleSyntaxType::Color, _ => SimpleSyntaxType::Na, } } } impl<'a> From<SyntaxType<'a>> for SimpleSyntaxType { fn from(syntax_type: SyntaxType<'a>) -> Self { match syntax_type { SyntaxType::Simple(simple_type) => simple_type, SyntaxType::Series(simple_type) => simple_type, _ => unreachable!(), } } } impl ToString for SimpleSyntaxType { fn to_string(&self) -> String { match self { SimpleSyntaxType::Int => String::from("int"), SimpleSyntaxType::Float => String::from("float"), SimpleSyntaxType::Bool => String::from("bool"), SimpleSyntaxType::Na => String::from("na"), SimpleSyntaxType::String => String::from("string"), SimpleSyntaxType::Color => String::from("color"), } } } #[derive(Debug, PartialEq, Clone, Eq, Hash)] pub enum SyntaxType<'a> { Void, Simple(SimpleSyntaxType), Series(SimpleSyntaxType), List(SimpleSyntaxType), // tuple list like [1, 2, 3] Tuple(Rc<Vec<SyntaxType<'a>>>), ObjectClass(&'a str), Val(Box<SyntaxType<'a>>), // evaluate value Object(Rc<BTreeMap<&'a str, SyntaxType<'a>>>), Function(Rc<FunctionTypes<'a>>), // function ObjectFunction(Rc<BTreeMap<&'a str, SyntaxType<'a>>>, Rc<FunctionTypes<'a>>), // object + function ValFunction(Box<SyntaxType<'a>>, Rc<FunctionTypes<'a>>), // value + function ValObjectFunction( Box<SyntaxType<'a>>, Rc<BTreeMap<&'a str, SyntaxType<'a>>>, Rc<FunctionTypes<'a>>, ), // value + object + function UserFunction(Rc<(Vec<&'a str>, SyntaxType<'a>)>), DynamicExpr(Box<SyntaxType<'a>>), // dynamic expression that can be invoked as function Any, } impl<'a> SyntaxType<'a> { // Get the value type from ValFunction type. pub fn get_v_for_vf(&self) -> &Self { match self { SyntaxType::Val(t) => &*t, SyntaxType::ValFunction(t, _) => &*t, SyntaxType::ValObjectFunction(t, _, _) => &*t, t => t, } } pub fn into_v_for_vf(self) -> Self { match self { SyntaxType::Val(t) => *t, SyntaxType::ValFunction(t, _) => *t, SyntaxType::ValObjectFunction(t, _, _) => *t, t => t, } } // Get the value type from DynamicExpr type. pub fn get_v_for_de(&self) -> &Self { match self { SyntaxType::DynamicExpr(t) => &*t, t => t, } } pub fn is_na(&self) -> bool { match self { SyntaxType::Simple(SimpleSyntaxType::Na) | SyntaxType::Series(SimpleSyntaxType::Na) => { true } _ => false, } } pub fn is_void(&self) -> bool { self == &SyntaxType::Void } pub fn is_int(&self) -> bool { match SyntaxType::get_v_for_vf(SyntaxType::get_v_for_vf(self)) { SyntaxType::Simple(SimpleSyntaxType::Int) | SyntaxType::Series(SimpleSyntaxType::Int) => true, _ => false, } } pub fn is_num(&self) -> bool { match SyntaxType::get_v_for_vf(SyntaxType::get_v_for_vf(self)) { SyntaxType::Simple(SimpleSyntaxType::Int) | SyntaxType::Series(SimpleSyntaxType::Int) | SyntaxType::Simple(SimpleSyntaxType::Float) | SyntaxType::Series(SimpleSyntaxType::Float) => true, _ => false, } } pub fn is_string(&self) -> bool { match SyntaxType::get_v_for_vf(SyntaxType::get_v_for_vf(self)) { SyntaxType::Simple(SimpleSyntaxType::String) | SyntaxType::Series(SimpleSyntaxType::String) => true, _ => false, } } pub fn int() -> SyntaxType<'a> { SyntaxType::Simple(SimpleSyntaxType::Int) } pub fn bool() -> SyntaxType<'a> { SyntaxType::Simple(SimpleSyntaxType::Bool) } pub fn float() -> SyntaxType<'a> { SyntaxType::Simple(SimpleSyntaxType::Float) } pub fn string() -> SyntaxType<'a> { SyntaxType::Simple(SimpleSyntaxType::String) } pub fn color() -> SyntaxType<'a> { SyntaxType::Simple(SimpleSyntaxType::Color) } pub fn int_series() -> SyntaxType<'a> { SyntaxType::Series(SimpleSyntaxType::Int) } pub fn float_series() -> SyntaxType<'a> { SyntaxType::Series(SimpleSyntaxType::Float) } pub fn bool_series() -> SyntaxType<'a> { SyntaxType::Series(SimpleSyntaxType::Bool) } pub fn color_series() -> SyntaxType<'a> { SyntaxType::Series(SimpleSyntaxType::Color) } pub fn string_series() -> SyntaxType<'a> { SyntaxType::Series(SimpleSyntaxType::String) } }
#[macro_use] extern crate inherit; pub mod expression; pub mod module; pub mod node; pub mod statement; use expression::{Expression, Identifier, Literal, PropertyKind}; use module::ModuleDeclaration; use node::{Node, NodeKind, SourceLocation}; use statement::{FunctionBody, Statement}; #[inherit(Node)] #[derive(Debug)] pub struct Program { pub source_type: SourceType, pub body: Vec<ProgramPart>, } #[derive(Debug)] pub enum SourceType { Script, Module, } #[derive(Debug)] pub enum ProgramPart { Directive(Directive), Statement(Statement), ModuleDecl(ModuleDeclaration), } #[derive(Debug)] pub struct Function { pub id: Option<Identifier>, pub params: Vec<Pattern>, pub body: FunctionBody, pub generator: bool, pub loc: SourceLocation, } #[derive(Debug)] pub struct Directive { pub expression: Literal, pub directive: String, pub loc: SourceLocation, } impl Node for Directive { fn loc(&self) -> SourceLocation { self.loc.clone() } fn kind(&self) -> NodeKind { NodeKind::ExpressionStatement } } #[derive(Debug)] pub struct AssignmentProperty { pub key: Expression, pub value: Pattern, pub kind: PropertyKind, pub method: bool, pub shorthand: bool, pub computed: bool, } #[derive(Debug)] pub enum Pattern { Ident(Identifier), Object(Object), Array(Array), RestElement(Box<RestElement>), Assignment(Box<Assignment>), } #[inherit(Pattern)] #[derive(Debug)] pub struct Object { pub properties: Vec<AssignmentProperty>, } #[inherit(Pattern)] #[derive(Debug)] pub struct Array { pub elements: Vec<Option<Pattern>>, } #[inherit(Node)] #[derive(Debug)] pub struct RestElement { pub argument: Pattern, } #[inherit(Pattern)] #[derive(Debug)] pub struct Assignment { pub left: Pattern, pub right: Expression, } impl Node for Pattern { fn loc(&self) -> SourceLocation { match self { Pattern::Ident(ref i) => i.loc(), Pattern::Object(ref o) => o.loc(), Pattern::Array(ref a) => a.loc(), Pattern::RestElement(ref r) => r.loc(), Pattern::Assignment(ref a) => a.loc(), } } fn kind(&self) -> NodeKind { match self { Pattern::Ident(ref i) => i.kind(), Pattern::Object(ref o) => o.kind(), Pattern::Array(ref a) => a.kind(), Pattern::RestElement(ref r) => r.kind(), Pattern::Assignment(ref a) => a.kind(), } } } #[derive(Debug)] pub struct Class { pub id: Option<Identifier>, pub super_class: Option<Expression>, pub body: ClassBody, pub loc: SourceLocation, } #[inherit(Node)] #[derive(Debug)] pub struct ClassBody { pub body: Vec<MethodDefinition>, } #[inherit(Node)] #[derive(Debug)] pub struct MethodDefinition { pub key: Expression, //TODO: FunctionExpression? pub value: Function, pub kind: MethodKind, pub computed: bool, pub _static: bool, } #[derive(Debug)] pub enum MethodKind { Constructor, Method, Get, Set, }
use std::rc::Rc; use std::str::FromStr; use crate::expr::Expr; use crate::lexer::Lexer; use crate::lexer::Lexem; use crate::field::Field; use crate::function::Function; use crate::operators::ArithmeticOp; use crate::operators::LogicalOp; use crate::operators::Op; use crate::query::OutputFormat; use crate::query::Query; use crate::query::Root; pub struct Parser { lexems: Vec<Lexem>, index: usize, } impl Parser { pub fn new() -> Parser { Parser { lexems: vec![], index: 0 } } pub fn parse(&mut self, query: &str) -> Result<Query, String> { let mut lexer = Lexer::new(query); while let Some(lexem) = lexer.next_lexem() { self.lexems.push(lexem); } let fields = self.parse_fields()?; let roots = self.parse_roots(); let expr = self.parse_where()?; let (ordering_fields, ordering_asc) = self.parse_order_by(&fields)?; let limit = self.parse_limit()?; let output_format = self.parse_output_format()?; Ok(Query { fields, roots, expr, ordering_fields, ordering_asc: Rc::new(ordering_asc), limit, output_format, }) } fn parse_fields(&mut self) -> Result<Vec<Expr>, String> { let mut fields = vec![]; loop { let lexem = self.get_lexem(); match lexem { Some(Lexem::Comma) => { // skip }, Some(Lexem::String(ref s)) | Some(Lexem::RawString(ref s)) | Some(Lexem::ArithmeticOperator(ref s)) => { if s.to_ascii_lowercase() != "select" { if s == "*" && fields.is_empty() { #[cfg(unix)] { fields.push(Expr::field(Field::Mode)); fields.push(Expr::field(Field::User)); fields.push(Expr::field(Field::Group)); } fields.push(Expr::field(Field::Size)); fields.push(Expr::field(Field::Path)); } else { self.drop_lexem(); if let Ok(Some(field)) = self.parse_expr() { fields.push(field); } } } }, _ => { self.drop_lexem(); break; } } } if fields.is_empty() { return Err(String::from("Error parsing fields, no selector found")) } Ok(fields) } fn parse_roots(&mut self) -> Vec<Root> { enum RootParsingMode { Unknown, From, Root, MinDepth, Depth, Options, Comma } let mut roots: Vec<Root> = Vec::new(); let mut mode = RootParsingMode::Unknown; let lexem = self.get_lexem(); match lexem { Some(ref lexem) => { match lexem { &Lexem::From => { mode = RootParsingMode::From; }, _ => { self.drop_lexem(); roots.push(Root::default()); } } }, None => { roots.push(Root::default()); } } if let RootParsingMode::From = mode { let mut path: String = String::from(""); let mut min_depth: u32 = 0; let mut depth: u32 = 0; let mut archives = false; let mut symlinks = false; let mut gitignore = false; let mut hgignore = false; loop { let lexem = self.get_lexem(); match lexem { Some(ref lexem) => { match lexem { Lexem::String(ref s) | Lexem::RawString(ref s) => { match mode { RootParsingMode::From | RootParsingMode::Comma => { path = s.to_string(); mode = RootParsingMode::Root; }, RootParsingMode::Root | RootParsingMode::Options => { let s = s.to_ascii_lowercase(); if s == "mindepth" { mode = RootParsingMode::MinDepth; } else if s == "maxdepth" || s == "depth" { mode = RootParsingMode::Depth; } else if s.starts_with("arc") { archives = true; mode = RootParsingMode::Options; } else if s.starts_with("sym") { symlinks = true; mode = RootParsingMode::Options; } else if s.starts_with("git") { gitignore = true; mode = RootParsingMode::Options; } else if s.starts_with("hg") { hgignore = true; mode = RootParsingMode::Options; } else { self.drop_lexem(); break; } }, RootParsingMode::MinDepth => { let d: Result<u32, _> = s.parse(); match d { Ok(d) => { min_depth = d; mode = RootParsingMode::Options; }, _ => { self.drop_lexem(); break; } } }, RootParsingMode::Depth => { let d: Result<u32, _> = s.parse(); match d { Ok(d) => { depth = d; mode = RootParsingMode::Options; }, _ => { self.drop_lexem(); break; } } }, _ => { } } }, Lexem::Comma => { if path.len() > 0 { roots.push(Root::new(path, min_depth, depth, archives, symlinks, gitignore, hgignore)); path = String::from(""); depth = 0; archives = false; symlinks = false; gitignore = false; hgignore = false; mode = RootParsingMode::Comma; } else { self.drop_lexem(); break; } }, _ => { if path.len() > 0 { roots.push(Root::new(path, min_depth, depth, archives, symlinks, gitignore, hgignore)); } self.drop_lexem(); break } } }, None => { if path.len() > 0 { roots.push(Root::new(path, min_depth, depth, archives, symlinks, gitignore, hgignore)); } break; } } } } roots } /* expr := and (OR and)* and := cond (AND cond)* cond := add_sub (OP add_sub)* add_sub := mul_div (PLUS mul_div)* | mul_div (MINUS mul_div)* mul_div := paren (MUL paren)* | paren (DIV paren)* paren := ( expr ) | func_scalar func_scalar := function paren | field | scalar */ fn parse_where(&mut self) -> Result<Option<Expr>, String> { match self.get_lexem() { Some(Lexem::Where) => { self.parse_expr() }, _ => { self.drop_lexem(); Ok(None) } } } fn parse_expr(&mut self) -> Result<Option<Expr>, String> { let left = self.parse_and()?; let mut right: Option<Expr> = None; loop { let lexem = self.get_lexem(); match lexem { Some(Lexem::Or) => { let expr = self.parse_and()?; right = match right { Some(right) => Some(Expr::logical_op(right, LogicalOp::Or, expr.clone().unwrap())), None => expr }; }, _ => { self.drop_lexem(); return match right { Some(right) => Ok(Some(Expr::logical_op(left.unwrap(), LogicalOp::Or, right))), None => Ok(left) } } } } } fn parse_and(&mut self) -> Result<Option<Expr>, String> { let left = self.parse_cond()?; let mut right: Option<Expr> = None; loop { let lexem = self.get_lexem(); match lexem { Some(Lexem::And) => { let expr = self.parse_cond()?; right = match right { Some(right) => Some(Expr::logical_op(right, LogicalOp::And, expr.clone().unwrap())), None => expr }; }, _ => { self.drop_lexem(); return match right { Some(right) => Ok(Some(Expr::logical_op(left.unwrap(), LogicalOp::And, right))), None => Ok(left) } } } } } fn parse_cond(&mut self) -> Result<Option<Expr>, String> { let left = self.parse_add_sub()?; let lexem = self.get_lexem(); match lexem { Some(Lexem::Operator(s)) => { let right = self.parse_add_sub()?; let op = Op::from(s); Ok(Some(Expr::op(left.unwrap(), op.unwrap(), right.unwrap()))) }, _ => { self.drop_lexem(); Ok(left) } } } fn parse_add_sub(&mut self) -> Result<Option<Expr>, String> { let left = self.parse_mul_div()?; let mut right: Option<Expr> = None; let mut op = None; loop { let lexem = self.get_lexem(); if let Some(Lexem::ArithmeticOperator(s)) = lexem { let new_op = ArithmeticOp::from(s); match new_op { Some(ArithmeticOp::Add) | Some(ArithmeticOp::Subtract) => { let expr = self.parse_mul_div()?; op = new_op.clone(); right = match right { Some(right) => Some(Expr::arithmetic_op(right, new_op.unwrap(), expr.clone().unwrap())), None => expr }; }, _ => { self.drop_lexem(); return match right { Some(right) => Ok(Some(Expr::arithmetic_op(left.unwrap(), op.unwrap(), right))), None => Ok(left) } } } } else { self.drop_lexem(); return match right { Some(right) => Ok(Some(Expr::arithmetic_op(left.unwrap(), op.unwrap(), right))), None => Ok(left) } } } } fn parse_mul_div(&mut self) -> Result<Option<Expr>, String> { let left = self.parse_paren()?; let mut right: Option<Expr> = None; let mut op = None; loop { let lexem = self.get_lexem(); if let Some(Lexem::ArithmeticOperator(s)) = lexem { let new_op = ArithmeticOp::from(s); match new_op { Some(ArithmeticOp::Multiply) | Some(ArithmeticOp::Divide) => { let expr = self.parse_paren()?; op = new_op.clone(); right = match right { Some(right) => Some(Expr::arithmetic_op(right, new_op.unwrap(), expr.clone().unwrap())), None => expr }; }, _ => { self.drop_lexem(); return match right { Some(right) => Ok(Some(Expr::arithmetic_op(left.unwrap(), op.unwrap(), right))), None => Ok(left) } } } } else { self.drop_lexem(); return match right { Some(right) => Ok(Some(Expr::arithmetic_op(left.unwrap(), op.unwrap(), right))), None => Ok(left) } } } } fn parse_paren(&mut self) -> Result<Option<Expr>, String> { if let Some(Lexem::Open) = self.get_lexem() { let result = self.parse_expr(); if let Some(Lexem::Close) = self.get_lexem() { result } else { Err("Unmatched parenthesis".to_string()) } } else { self.drop_lexem(); self.parse_func_scalar() } } fn parse_func_scalar(&mut self) -> Result<Option<Expr>, String> { let lexem = self.get_lexem(); match lexem { Some(Lexem::String(ref s)) | Some(Lexem::RawString(ref s)) => { if let Ok(field) = Field::from_str(s) { return Ok(Some(Expr::field(field))); } if let Ok(function) = Function::from_str(s) { match self.parse_function(function) { Ok(expr) => return Ok(Some(expr)), Err(err) => return Err(err) } } Ok(Some(Expr::value(s.to_string()))) } _ => { Err("Error parsing expression, expecting string".to_string()) } } } fn parse_function(&mut self, function: Function) -> Result<Expr, String> { let mut function_expr = Expr::function(function); if let Some(lexem) = self.get_lexem() { if lexem != Lexem::Open { return Err("Error in function expression".to_string()); } } if let Ok(Some(function_arg)) = self.parse_expr() { function_expr.left = Some(Box::from(function_arg)); } if let Some(lexem) = self.get_lexem() { if lexem != Lexem::Close { return Err("Error in function expression".to_string()); } } Ok(function_expr) } fn parse_order_by(&mut self, fields: &Vec<Expr>) -> Result<(Vec<Expr>, Vec<bool>), String> { let mut order_by_fields: Vec<Expr> = vec![]; let mut order_by_directions: Vec<bool> = vec![]; if let Some(Lexem::Order) = self.get_lexem() { if let Some(Lexem::By) = self.get_lexem() { loop { match self.get_lexem() { Some(Lexem::Comma) => {}, Some(Lexem::RawString(ref ordering_field)) => { let actual_field = match ordering_field.parse::<usize>() { Ok(idx) => fields[idx - 1].clone(), _ => Expr::field(Field::from_str(ordering_field)?), }; order_by_fields.push(actual_field.clone()); order_by_directions.push(true); }, Some(Lexem::DescendingOrder) => { let cnt = order_by_directions.len(); order_by_directions[cnt - 1] = false; }, _ => { self.drop_lexem(); break; }, } } } else { self.drop_lexem(); } } else { self.drop_lexem(); } Ok((order_by_fields, order_by_directions)) } fn parse_limit(&mut self) -> Result<u32, &str> { let lexem = self.get_lexem(); match lexem { Some(Lexem::Limit) => { let lexem = self.get_lexem(); match lexem { Some(Lexem::RawString(s)) | Some(Lexem::String(s)) => { if let Ok(limit) = s.parse() { return Ok(limit); } else { return Err("Error parsing limit"); } }, _ => { self.drop_lexem(); return Err("Error parsing limit, limit value not found"); } } }, _ => { self.drop_lexem(); } } Ok(0) } fn parse_output_format(&mut self) -> Result<OutputFormat, &str>{ let lexem = self.get_lexem(); match lexem { Some(Lexem::Into) => { let lexem = self.get_lexem(); match lexem { Some(Lexem::RawString(s)) | Some(Lexem::String(s)) => { return match OutputFormat::from(&s) { Some(output_format) => Ok(output_format), None => Err("Unknown output format") }; }, _ => { self.drop_lexem(); return Err("Error parsing output format"); } } }, _ => { self.drop_lexem(); } } Ok(OutputFormat::Tabs) } fn get_lexem(&mut self) -> Option<Lexem> { let lexem = self.lexems.get(self.index ); self.index += 1; match lexem { Some(lexem) => Some(lexem.clone()), None => None } } fn drop_lexem(&mut self) { self.index -= 1; } } #[cfg(test)] mod tests { use super::*; #[test] fn simple_query() { let query = "select name, path ,size , fsize from /"; let mut p = Parser::new(); let query = p.parse(&query).unwrap(); assert_eq!(query.fields, vec![Expr::field(Field::Name), Expr::field(Field::Path), Expr::field(Field::Size), Expr::field(Field::FormattedSize), ]); } #[test] fn query() { let query = "select name, path ,size , fsize from /test depth 2, /test2 archives,/test3 depth 3 archives , /test4 ,'/test5' gitignore , /test6 mindepth 3 where name != 123 AND ( size gt 456 or fsize lte 758) or name = 'xxx' order by 2, size desc limit 50"; let mut p = Parser::new(); let query = p.parse(&query).unwrap(); assert_eq!(query.fields, vec![Expr::field(Field::Name), Expr::field(Field::Path), Expr::field(Field::Size), Expr::field(Field::FormattedSize) ]); assert_eq!(query.roots, vec![ Root::new(String::from("/test"), 0, 2, false, false, false, false), Root::new(String::from("/test2"), 0, 0, true, false, false, false), Root::new(String::from("/test3"), 0, 3, true, false, false, false), Root::new(String::from("/test4"), 0, 0, false, false, false, false), Root::new(String::from("/test5"), 0, 0, false, false, true, false), Root::new(String::from("/test6"), 3, 0, false, false, false, false), ]); let expr = Expr::logical_op( Expr::logical_op( Expr::op(Expr::field(Field::Name), Op::Ne, Expr::value(String::from("123"))), LogicalOp::And, Expr::logical_op( Expr::op(Expr::field(Field::Size), Op::Gt, Expr::value(String::from("456"))), LogicalOp::Or, Expr::op(Expr::field(Field::FormattedSize), Op::Lte, Expr::value(String::from("758"))), ), ), LogicalOp::Or, Expr::op(Expr::field(Field::Name), Op::Eq, Expr::value(String::from("xxx"))) ); assert_eq!(query.expr, Some(expr)); assert_eq!(query.ordering_fields, vec![Expr::field(Field::Path), Expr::field(Field::Size)]); assert_eq!(query.ordering_asc, Rc::new(vec![true, false])); assert_eq!(query.limit, 50); } }
use crate::camera::Camera; use crate::mesh::{Mesh, Vertex}; use crate::shader::Shader; use crate::texture::Texture; use cgmath::prelude::*; use cgmath::{vec3, Matrix4, Quaternion, Vector2, Vector3}; use gltf::buffer::Data; use gltf::image::Source; use gltf::Mesh as GLTFMesh; use gltf::{scene::Node, Document, Scene}; use std::path::Path; pub struct Model { meshes: Vec<Mesh>, textures: Vec<Texture>, buffers: Vec<Data>, trans_meshes: Vec<Vector3<f32>>, rot_meshes: Vec<Quaternion<f32>>, scale_meshes: Vec<Vector3<f32>>, matrix_meshes: Vec<Matrix4<f32>>, path: String, } impl Model { pub fn from_gltf(file_path: &str) -> Self { let mut new_model = Model { meshes: Vec::new(), buffers: Vec::new(), rot_meshes: Vec::new(), scale_meshes: Vec::new(), trans_meshes: Vec::new(), textures: Vec::new(), matrix_meshes: Vec::new(), path: file_path.to_string(), }; new_model.load_data(file_path); new_model } fn load_data(&mut self, path: &str) { let (gltf, buffers, _) = gltf::import(path).expect("Couldnt read model"); self.buffers = buffers; self.load_textures(&gltf); let scenes: Vec<Scene> = gltf.scenes().collect(); for node in scenes[0].nodes() { self.load_node(node, Matrix4::identity()); } } fn load_mesh(&mut self, mesh: GLTFMesh) { let mut positions: Vec<Vector3<f32>> = Vec::new(); let mut normals: Vec<Vector3<f32>> = Vec::new(); let mut tex_uvs: Vec<Vector2<f32>> = Vec::new(); let mut indices: Vec<u32> = Vec::new(); for primitive in mesh.primitives() { let reader = primitive.reader(|buffer| Some(&self.buffers[buffer.index()])); if let Some(iter) = reader.read_positions() { for vertex_position in iter { positions.push(Vector3::from(vertex_position)); } } if let Some(iter) = reader.read_normals() { for vertex_normal in iter { normals.push(Vector3::from(vertex_normal)); } } if let Some(iter) = reader.read_tex_coords(0) { for vertex_uvs in iter.into_f32() { tex_uvs.push(Vector2::from(vertex_uvs)); } } indices = if let Some(indices) = reader.read_indices() { Some(indices.into_u32().map(|i| i as u32).collect()).unwrap() } else { Vec::new() }; } let mut vertices: Vec<Vertex> = Vec::new(); for (i, pos) in positions.iter().enumerate() { vertices.push(Vertex { position: *pos, normal: *normals.get(i).unwrap(), tex_uv: *tex_uvs.get(i).unwrap(), color: vec3(1.0, 1.0, 1.0), }) } self.meshes .push(Mesh::create(&vertices, &indices, &self.textures)); } fn load_node(&mut self, node: Node, matrix: Matrix4<f32>) { let transform = node.transform().decomposed(); let mat_4 = node.transform().matrix(); let node_matrix = Matrix4::from(mat_4); let trans = Matrix4::from_translation(Vector3::from(transform.0)); let rot = Matrix4::from(Quaternion::new( *transform.1.get(3).unwrap(), *transform.1.get(0).unwrap(), *transform.1.get(1).unwrap(), *transform.1.get(2).unwrap(), )); let scale = Vector3::from(transform.2); let sca = Matrix4::from_nonuniform_scale(scale.x, scale.y, scale.z); let mat_next: Matrix4<f32> = matrix * node_matrix * trans * rot * sca; if let Some(node_mesh) = node.mesh() { self.trans_meshes.push(Vector3::from(transform.0)); self.rot_meshes.push(Quaternion::new( *transform.1.get(3).unwrap(), *transform.1.get(0).unwrap(), *transform.1.get(1).unwrap(), *transform.1.get(2).unwrap(), )); self.scale_meshes.push(Vector3::from(transform.2)); self.matrix_meshes.push(mat_next); self.load_mesh(node_mesh); } for child in node.children() { self.load_node(child, mat_next); } } fn load_textures(&mut self, gltf: &Document) { let mut textures: Vec<Texture> = Vec::new(); let mut tex_unit = 0; gltf.images().for_each(|img| match img.source() { Source::Uri { uri, .. } => { let mut tex_type = ""; if uri.contains("baseColor") { tex_type = "diffuse"; } if uri.contains("metallicRoughness") { tex_type = "specular" } let tex_path = Path::join(Path::new(&self.path), Path::new("../")); println!("{:?}", tex_path); let texture = Texture::from_file( &(tex_path.as_os_str().to_str().unwrap().to_string() + uri), tex_type, tex_unit, false, ); textures.push(texture); tex_unit += 1; } _ => {} }); self.textures = textures; } pub fn draw(&mut self, shader: &Shader, camera: &Camera) { for (i, mesh) in self.meshes.iter().enumerate() { mesh.draw( shader, camera, *self.matrix_meshes.get(i).unwrap(), *self.trans_meshes.get(i).unwrap(), *self.rot_meshes.get(i).unwrap(), *self.scale_meshes.get(i).unwrap(), ); } } }
// 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 super::pseudo_directory_impl; use {indoc::indoc, proc_macro2::TokenStream, std::str::FromStr}; // rustfmt is aligning all the strings, making them even harder to read. TODO For some reason this // does not seem to work, and I need explicit `#[rustfmt::skip]` on every test. #[rustfmt::skip::macros(check_pseudo_directory_impl)] // Rustfmt is messing up indentation inside the `assert!` macro. #[rustfmt::skip] macro_rules! check_pseudo_directory_impl { ($input:expr, $expected:expr) => {{ let input = TokenStream::from_str($input).unwrap(); let output = pseudo_directory_impl(input); let expected = $expected; assert!( output.to_string() == expected, "Generated code does not match the expected one.\n\ Expected:\n\ {} Actual:\n\ {} ", expected, output ); }}; } #[test] #[rustfmt::skip] fn empty() { check_pseudo_directory_impl!( "", "{ \ let __dir = :: fuchsia_vfs_pseudo_fs_mt :: directory :: simple ( ) ; \ __dir \ }" ); } #[test] #[rustfmt::skip] fn one_entry() { check_pseudo_directory_impl!( indoc!( r#" "name" => read_only_static("content"), "# ), "{ \ let __dir = :: fuchsia_vfs_pseudo_fs_mt :: directory :: simple ( ) ; \ :: fuchsia_vfs_pseudo_fs_mt :: pseudo_directory :: unwrap_add_entry_span ( \ \"name\" , \"Span\" , \ __dir . clone ( ) . add_entry ( \"name\" , read_only_static ( \"content\" ) ) ) ; \ __dir \ }" ); } #[test] #[rustfmt::skip] fn two_entries() { check_pseudo_directory_impl!( indoc!( r#" "first" => read_only_static("A"), "second" => read_only_static("B"), "# ), "{ \ let __dir = :: fuchsia_vfs_pseudo_fs_mt :: directory :: simple ( ) ; \ :: fuchsia_vfs_pseudo_fs_mt :: pseudo_directory :: unwrap_add_entry_span ( \ \"first\" , \"Span\" , \ __dir . clone ( ) . add_entry ( \"first\" , read_only_static ( \"A\" ) ) ) ; \ :: fuchsia_vfs_pseudo_fs_mt :: pseudo_directory :: unwrap_add_entry_span ( \ \"second\" , \"Span\" , \ __dir . clone ( ) . add_entry ( \"second\" , read_only_static ( \"B\" ) ) ) ; \ __dir \ }" ); } #[test] #[rustfmt::skip] fn assign_to() { check_pseudo_directory_impl!( indoc!( r#" my_dir -> "first" => read_only_static("A"), "second" => read_only_static("B"), "# ), "{ \ my_dir = :: fuchsia_vfs_pseudo_fs_mt :: directory :: simple ( ) ; \ :: fuchsia_vfs_pseudo_fs_mt :: pseudo_directory :: unwrap_add_entry_span ( \ \"first\" , \"Span\" , \ my_dir . clone ( ) . add_entry ( \"first\" , read_only_static ( \"A\" ) ) ) ; \ :: fuchsia_vfs_pseudo_fs_mt :: pseudo_directory :: unwrap_add_entry_span ( \ \"second\" , \"Span\" , \ my_dir . clone ( ) . add_entry ( \"second\" , read_only_static ( \"B\" ) ) ) ; \ my_dir . clone ( ) \ }" ); } #[test] #[rustfmt::skip] fn entry_has_name_from_ref() { check_pseudo_directory_impl!( indoc!( r#" test_name => read_only_static("content"), "# ), "{ \ let __dir = :: fuchsia_vfs_pseudo_fs_mt :: directory :: simple ( ) ; \ :: fuchsia_vfs_pseudo_fs_mt :: pseudo_directory :: unwrap_add_entry_span ( \ test_name , \"Span\" , \ __dir . clone ( ) . add_entry ( test_name , read_only_static ( \"content\" ) ) ) ; \ __dir \ }" ); }
// coefficient trait trait Coef: Copy + std::ops::Add<Output = Self> + std::ops::Sub<Output = Self> + std::ops::Mul<Output = Self> + std::ops::Div<Output = Self> + std::ops::AddAssign + std::ops::SubAssign + std::ops::MulAssign + std::ops::DivAssign + std::default::Default + std::fmt::Display + std::fmt::Debug { } impl Coef for i64 {} impl Coef for u64 {} impl Coef for f64 {} #[derive(Eq, PartialEq, Clone)] struct Polynomial<T: Coef> { coef: Vec<T>, } // display, debug impl<T: Coef> std::fmt::Debug for Polynomial<T> { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let mut res = format!("{}", self.coef[0]); for i in 1..self.coef.len() { res = format!("{}+{}(x{})", res, self.coef[i], i); } write!(f, "{}", res) } } // constructor impl<T: Coef> Polynomial<T> { fn new() -> Self { Polynomial { coef: vec![T::default()], } } } impl<T: Coef> From<Vec<T>> for Polynomial<T> { fn from(a: Vec<T>) -> Self { Polynomial { coef: a.to_vec() } } } #[test] fn check_new_from() { let p = Polynomial::<i64>::new(); println!("{:?}", p); let v: Vec<i64> = vec![1, 2, 3, 4, 5]; let p = Polynomial::from(v); println!("{:?}", p); } // operations these borrow references impl<T: Coef> std::ops::Add<Polynomial<T>> for Polynomial<T> { type Output = Polynomial<T>; fn add(mut self, mut rhs: Polynomial<T>) -> Self::Output { if self.coef.len() < rhs.coef.len() { for i in 0..self.coef.len() { rhs.coef[i] += self.coef[i]; } rhs } else { for i in 0..rhs.coef.len() { self.coef[i] += rhs.coef[i]; } self } } } // component wise impl<T: Coef> std::ops::Sub<Polynomial<T>> for Polynomial<T> { type Output = Polynomial<T>; fn sub(self, rhs: Polynomial<T>) -> Self::Output { if self.coef.len() < rhs.coef.len() { for i in 0..self.coef.len() { self.coef[i] -= rhs.coef[i]; } self } else { for i in 0..rhs.coef.len() { self.coef[i] -= rhs.coef[i]; } self } } } // dot product // i*j x j * k impl<T: Coef> std::ops::Mul<Polynomial<T>> for Polynomial<T> where T: std::ops::Add<Output = T> + std::ops::Mul<Output = T> + std::fmt::Debug + From<i32> + Copy + Clone, { type Output = Polynomial<T>; fn mul(self, rhs: Polynomial<T>) -> Self::Output { Polynomial { coef: single_convolution(self.coef, b: rhs.coef) } } } #[test] fn check_ops() {} fn main() {}
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // 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 alloc::sync::Arc; use alloc::string::String; use alloc::string::ToString; use spin::Mutex; use alloc::vec::Vec; use super::super::super::super::qlib::common::*; use super::super::super::super::qlib::linux_def::*; use super::super::super::super::qlib::auth::*; use super::super::super::super::qlib::limits::*; use super::super::super::super::qlib::linux::time::*; use super::super::super::fsutil::file::readonly_file::*; use super::super::super::fsutil::inode::simple_file_inode::*; use super::super::super::super::task::*; use super::super::super::attr::*; use super::super::super::file::*; use super::super::super::flags::*; use super::super::super::dirent::*; use super::super::super::mount::*; use super::super::super::inode::*; use super::super::super::super::threadmgr::thread::*; use super::super::super::super::threadmgr::pid_namespace::*; use super::super::inode::*; pub fn NewStat(task: &Task, thread: &Thread, showSubtasks: bool, pidns: PIDNamespace, msrc: &Arc<Mutex<MountSource>>) -> Inode { let v = NewStatSimpleFileInode(task, thread, showSubtasks, pidns, &ROOT_OWNER, &FilePermissions::FromMode(FileMode(0o400)), FSMagic::PROC_SUPER_MAGIC); return NewProcInode(&Arc::new(v), msrc, InodeType::SpecialFile, Some(thread.clone())) } pub fn NewStatSimpleFileInode(task: &Task, thread: &Thread, showSubtasks: bool, pidns: PIDNamespace, owner: &FileOwner, perms: &FilePermissions, typ: u64) -> SimpleFileInode<StatData> { let io = StatData{t: thread.clone(), tgstats: showSubtasks, pidns: pidns}; return SimpleFileInode::New(task, owner, perms, typ, false, io) } pub struct StatData { pub t: Thread, // If tgstats is true, accumulate fault stats (not implemented) and CPU // time across all tasks in t's thread group. pub tgstats: bool, // pidns is the PID namespace associated with the proc filesystem that // includes the file using this statData. pub pidns: PIDNamespace } impl StatData { pub fn GenSnapshot(&self, _task: &Task,) -> Vec<u8> { let mut output : String = "".to_string(); output += &format!("{} ", self.pidns.IDOfTask(&self.t)); output += &format!("({}) ", self.t.Name()); output += &format!("{} ", self.t.lock().StateStatus().as_bytes()[0] as char); let ppid = match self.t.Parent() { None => 0, Some(parent) => self.pidns.IDOfThreadGroup(&parent.ThreadGroup()) }; output += &format!("{} ", ppid); output += &format!("{} ", self.pidns.IDOfProcessGroup(&self.t.ThreadGroup().ProcessGroup().unwrap())); output += &format!("{} ", self.pidns.IDOfSession(&self.t.ThreadGroup().Session().unwrap())); output += &format!("0 0 "/* tty_nr tpgid */); output += &format!("0 "/* flags */); output += &format!("0 0 0 0 "/* minflt cminflt majflt cmajflt */); let cputime = if self.tgstats { self.t.ThreadGroup().CPUStats() } else { self.t.CPUStats() }; output += &format!("{} {} ", ClockTFromDuration(cputime.UserTime), ClockTFromDuration(cputime.SysTime)); let cputime = self.t.ThreadGroup().JoinedChildCPUStats(); output += &format!("{} {} ", ClockTFromDuration(cputime.UserTime), ClockTFromDuration(cputime.SysTime)); output += &format!("{} {} ", self.t.Priority(), self.t.Niceness()); output += &format!("{} ", self.t.ThreadGroup().Count()); // itrealvalue. Since kernel 2.6.17, this field is no longer // maintained, and is hard coded as 0. output += &format!("{} ", 0); // Start time is relative to boot time, expressed in clock ticks. output += &format!("{} ", ClockTFromDuration(self.t.StartTime().Sub(self.t.Kernel().TimeKeeper().BootTime()))); let (vss, rss) = { let t = self.t.lock(); let mm = t.memoryMgr.clone(); let ml = mm.MappingLock(); let _ml = ml.read(); (mm.VirtualMemorySizeLocked(), mm.ResidentSetSizeLocked()) }; output += &format!("{} {} ", vss, rss/MemoryDef::PAGE_SIZE); // rsslim. output += &format!("{} ", self.t.ThreadGroup().Limits().Get(LimitType::Rss).Cur); output += &format!("0 0 0 0 0 "/* startcode endcode startstack kstkesp kstkeip */); output += &format!("0 0 0 0 0 "/* signal blocked sigignore sigcatch wchan */); output += &format!("0 0 "/* nswap cnswap */); let terminationSignal = if Some(self.t.clone()) == self.t.ThreadGroup().Leader() { self.t.ThreadGroup().TerminationSignal() } else { Signal(0) }; output += &format!("{} ", terminationSignal.0); output += &format!("0 0 0 "/* processor rt_priority policy */); output += &format!("0 0 0 "/* delayacct_blkio_ticks guest_time cguest_time */); output += &format!("0 0 0 0 0 0 0 " /* start_data end_data start_brk arg_start arg_end env_start env_end */); output += &format!("0\n"/* exit_code */); return output.as_bytes().to_vec(); } } impl SimpleFileTrait for StatData { fn GetFile(&self, task: &Task, _dir: &Inode, dirent: &Dirent, flags: FileFlags) -> Result<File> { let fops = NewSnapshotReadonlyFileOperations(self.GenSnapshot(task)); let file = File::New(dirent, &flags, fops); return Ok(file); } }
use super::VarResult; use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType}; use crate::helper::err_msgs::*; use crate::helper::str_replace; use crate::helper::{ move_element, pine_ref_to_bool, pine_ref_to_color, pine_ref_to_f64, pine_ref_to_i64, pine_ref_to_string, }; use crate::runtime::context::{downcast_ctx, Ctx}; use crate::runtime::{OutputData, OutputInfo, PlotBarInfo}; use crate::types::{ Bool, Callable, CallableFactory, CallableObject, DataType, Float, Int, ParamCollectCall, PineClass, PineFrom, PineRef, PineType, RefData, RuntimeErr, SecondType, Series, NA, }; use std::rc::Rc; fn pine_plot<'a>( context: &mut dyn Ctx<'a>, mut param: Vec<Option<PineRef<'a>>>, _func_type: FunctionType<'a>, ) -> Result<(), RuntimeErr> { move_tuplet!((open, high, low, close, title, color, editable, show_last, display) = param); if !downcast_ctx(context).check_is_output_info_ready() { let plot_info = PlotBarInfo { title: pine_ref_to_string(title), color: pine_ref_to_color(color), editable: pine_ref_to_bool(editable), show_last: pine_ref_to_i64(show_last), display: pine_ref_to_i64(display), }; downcast_ctx(context).push_output_info(OutputInfo::PlotBar(plot_info)); } match (open, high, low, close) { (Some(open_v), Some(high_v), Some(low_v), Some(close_v)) => { let mut open_items: RefData<Series<Float>> = Series::implicity_from(open_v).unwrap(); let mut high_items: RefData<Series<Float>> = Series::implicity_from(high_v).unwrap(); let mut low_items: RefData<Series<Float>> = Series::implicity_from(low_v).unwrap(); let mut close_items: RefData<Series<Float>> = Series::implicity_from(close_v).unwrap(); downcast_ctx(context).push_output_data(Some(OutputData::new(vec![ open_items.move_history(), high_items.move_history(), low_items.move_history(), close_items.move_history(), ]))); Ok(()) } (o, h, l, c) => { let mut missings: Vec<String> = vec![]; if o.is_none() { missings.push(String::from("open")); } if h.is_none() { missings.push(String::from("high")); } if l.is_none() { missings.push(String::from("low")); } if c.is_none() { missings.push(String::from("close")); } Err(RuntimeErr::MissingParameters(str_replace( REQUIRED_PARAMETERS, vec![missings.join(", ")], ))) } } } pub const VAR_NAME: &'static str = "plotbar"; pub fn declare_var<'a>() -> VarResult<'a> { let value = PineRef::new(CallableFactory::new(|| { Callable::new(None, Some(Box::new(ParamCollectCall::new(pine_plot)))) })); // plot(series, title, color, linewidth, style, trackprice, opacity, histbase, offset, join, editable, show_last) → plot let func_type = FunctionTypes(vec![FunctionType::new(( vec![ ("open", SyntaxType::Series(SimpleSyntaxType::Float)), ("high", SyntaxType::Series(SimpleSyntaxType::Float)), ("low", SyntaxType::Series(SimpleSyntaxType::Float)), ("close", SyntaxType::Series(SimpleSyntaxType::Float)), ("title", SyntaxType::string()), ("color", SyntaxType::color()), ("editable", SyntaxType::bool()), ("show_last", SyntaxType::int()), ("display", SyntaxType::int()), ], SyntaxType::Void, ))]); let syntax_type = SyntaxType::Function(Rc::new(func_type)); VarResult::new(value, syntax_type, VAR_NAME) } #[cfg(test)] mod tests { use super::*; use crate::runtime::{AnySeries, NoneCallback}; use crate::{LibInfo, PineParser, PineRunner}; #[test] fn plotbar_info_test() { use crate::runtime::OutputInfo; let lib_info = LibInfo::new( vec![declare_var()], vec![ ("close", SyntaxType::Series(SimpleSyntaxType::Float)), ("high", SyntaxType::Series(SimpleSyntaxType::Float)), ("low", SyntaxType::Series(SimpleSyntaxType::Float)), ("open", SyntaxType::Series(SimpleSyntaxType::Float)), ], ); let src = r"plotbar(open, high, low, close, title='Title', color=#ff0000, editable=true, show_last=100, display=1) "; let blk = PineParser::new(src, &lib_info).parse_blk().unwrap(); let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback()); runner .run( &vec![ ( "close", AnySeries::from_float_vec(vec![Some(1f64), Some(2f64)]), ), ( "open", AnySeries::from_float_vec(vec![Some(0f64), Some(10f64)]), ), ( "high", AnySeries::from_float_vec(vec![Some(1f64), Some(12f64)]), ), ( "low", AnySeries::from_float_vec(vec![Some(0f64), Some(1f64)]), ), ], None, ) .unwrap(); assert_eq!( runner.move_output_data(), vec![Some(OutputData::new(vec![ vec![Some(0f64), Some(10f64)], vec![Some(1f64), Some(12f64)], vec![Some(0f64), Some(1f64)], vec![Some(1f64), Some(2f64)], ])),] ); assert_eq!( runner.get_io_info().get_outputs(), &vec![OutputInfo::PlotBar(PlotBarInfo { title: Some(String::from("Title")), color: Some(String::from("#ff0000")), editable: Some(true), show_last: Some(100), display: Some(1) })] ); } }
// This file was generated by gir (https://github.com/gtk-rs/gir) // from ../gir-files // DO NOT EDIT use crate::AddressFamily; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::StaticType; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::wrapper! { #[doc(alias = "SoupAddress")] pub struct Address(Object<ffi::SoupAddress, ffi::SoupAddressClass>); match fn { type_ => || ffi::soup_address_get_type(), } } impl Address { #[doc(alias = "soup_address_new")] pub fn new(name: &str, port: u32) -> Address { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::soup_address_new(name.to_glib_none().0, port)) } } #[doc(alias = "soup_address_new_any")] pub fn new_any(family: AddressFamily, port: u32) -> Option<Address> { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::soup_address_new_any(family.into_glib(), port)) } } //#[doc(alias = "soup_address_new_from_sockaddr")] //#[doc(alias = "new_from_sockaddr")] //pub fn from_sockaddr(sa: /*Unimplemented*/Option<Fundamental: Pointer>, len: i32) -> Option<Address> { // unsafe { TODO: call ffi:soup_address_new_from_sockaddr() } //} } pub const NONE_ADDRESS: Option<&Address> = None; pub trait AddressExt: 'static { #[cfg(any(feature = "v2_32", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_32")))] #[doc(alias = "soup_address_get_gsockaddr")] #[doc(alias = "get_gsockaddr")] fn gsockaddr(&self) -> Option<gio::SocketAddress>; #[doc(alias = "soup_address_get_name")] #[doc(alias = "get_name")] fn name(&self) -> Option<glib::GString>; #[doc(alias = "soup_address_get_physical")] #[doc(alias = "get_physical")] fn physical(&self) -> Option<glib::GString>; #[doc(alias = "soup_address_get_port")] #[doc(alias = "get_port")] fn port(&self) -> u32; //#[doc(alias = "soup_address_get_sockaddr")] //#[doc(alias = "get_sockaddr")] //fn sockaddr(&self, len: i32) -> /*Unimplemented*/Option<Fundamental: Pointer>; #[doc(alias = "soup_address_is_resolved")] fn is_resolved(&self) -> bool; #[doc(alias = "soup_address_resolve_async")] fn resolve_async<P: IsA<gio::Cancellable>, Q: FnOnce(&Address, u32) + 'static>(&self, async_context: Option<&glib::MainContext>, cancellable: Option<&P>, callback: Q); #[doc(alias = "soup_address_resolve_sync")] fn resolve_sync<P: IsA<gio::Cancellable>>(&self, cancellable: Option<&P>) -> u32; fn family(&self) -> AddressFamily; fn protocol(&self) -> Option<glib::GString>; #[doc(alias = "physical")] fn connect_physical_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<Address>> AddressExt for O { #[cfg(any(feature = "v2_32", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_32")))] fn gsockaddr(&self) -> Option<gio::SocketAddress> { unsafe { from_glib_full(ffi::soup_address_get_gsockaddr(self.as_ref().to_glib_none().0)) } } fn name(&self) -> Option<glib::GString> { unsafe { from_glib_none(ffi::soup_address_get_name(self.as_ref().to_glib_none().0)) } } fn physical(&self) -> Option<glib::GString> { unsafe { from_glib_none(ffi::soup_address_get_physical(self.as_ref().to_glib_none().0)) } } fn port(&self) -> u32 { unsafe { ffi::soup_address_get_port(self.as_ref().to_glib_none().0) } } //fn sockaddr(&self, len: i32) -> /*Unimplemented*/Option<Fundamental: Pointer> { // unsafe { TODO: call ffi:soup_address_get_sockaddr() } //} fn is_resolved(&self) -> bool { unsafe { from_glib(ffi::soup_address_is_resolved(self.as_ref().to_glib_none().0)) } } fn resolve_async<P: IsA<gio::Cancellable>, Q: FnOnce(&Address, u32) + 'static>(&self, async_context: Option<&glib::MainContext>, cancellable: Option<&P>, callback: Q) { let callback_data: Box_<Q> = Box_::new(callback); unsafe extern "C" fn callback_func<P: IsA<gio::Cancellable>, Q: FnOnce(&Address, u32) + 'static>(addr: *mut ffi::SoupAddress, status: libc::c_uint, user_data: glib::ffi::gpointer) { let addr = from_glib_borrow(addr); let callback: Box_<Q> = Box_::from_raw(user_data as *mut _); (*callback)(&addr, status); } let callback = Some(callback_func::<P, Q> as _); let super_callback0: Box_<Q> = callback_data; unsafe { ffi::soup_address_resolve_async(self.as_ref().to_glib_none().0, async_context.to_glib_none().0, cancellable.map(|p| p.as_ref()).to_glib_none().0, callback, Box_::into_raw(super_callback0) as *mut _); } } fn resolve_sync<P: IsA<gio::Cancellable>>(&self, cancellable: Option<&P>) -> u32 { unsafe { ffi::soup_address_resolve_sync(self.as_ref().to_glib_none().0, cancellable.map(|p| p.as_ref()).to_glib_none().0) } } fn family(&self) -> AddressFamily { unsafe { let mut value = glib::Value::from_type(<AddressFamily as StaticType>::static_type()); glib::gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"family\0".as_ptr() as *const _, value.to_glib_none_mut().0); value.get().expect("Return Value for property `family` getter") } } fn protocol(&self) -> Option<glib::GString> { unsafe { let mut value = glib::Value::from_type(<glib::GString as StaticType>::static_type()); glib::gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"protocol\0".as_ptr() as *const _, value.to_glib_none_mut().0); value.get().expect("Return Value for property `protocol` getter") } } fn connect_physical_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_physical_trampoline<P: IsA<Address>, F: Fn(&P) + 'static>(this: *mut ffi::SoupAddress, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer) { let f: &F = &*(f as *const F); f(Address::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"notify::physical\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>(notify_physical_trampoline::<Self, F> as *const ())), Box_::into_raw(f)) } } } impl fmt::Display for Address { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("Address") } }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use common_exception::Result; use crate::plans::Plan; impl Plan { pub fn format_indent(&self) -> Result<String> { match self { Plan::Query { s_expr, metadata, .. } => s_expr.to_format_tree(metadata).format_pretty(), Plan::Explain { kind, plan } => { let result = plan.format_indent()?; Ok(format!("{:?}:\n{}", kind, result)) } Plan::ExplainAst { .. } => Ok("ExplainAst".to_string()), Plan::ExplainSyntax { .. } => Ok("ExplainSyntax".to_string()), Plan::ExplainAnalyze { .. } => Ok("ExplainAnalyze".to_string()), Plan::Copy(plan) => Ok(format!("{:?}", plan)), Plan::Call(plan) => Ok(format!("{:?}", plan)), // catalog Plan::ShowCreateCatalog(show_create_catalog) => { Ok(format!("{:?}", show_create_catalog)) } Plan::CreateCatalog(create_catalog) => Ok(format!("{:?}", create_catalog)), Plan::DropCatalog(drop_catalog) => Ok(format!("{:?}", drop_catalog)), // Databases Plan::ShowCreateDatabase(show_create_database) => { Ok(format!("{:?}", show_create_database)) } Plan::CreateDatabase(create_database) => Ok(format!("{:?}", create_database)), Plan::DropDatabase(drop_database) => Ok(format!("{:?}", drop_database)), Plan::UndropDatabase(undrop_database) => Ok(format!("{:?}", undrop_database)), Plan::RenameDatabase(rename_database) => Ok(format!("{:?}", rename_database)), // Tables Plan::ShowCreateTable(show_create_table) => Ok(format!("{:?}", show_create_table)), Plan::CreateTable(create_table) => Ok(format!("{:?}", create_table)), Plan::DropTable(drop_table) => Ok(format!("{:?}", drop_table)), Plan::UndropTable(undrop_table) => Ok(format!("{:?}", undrop_table)), Plan::DescribeTable(describe_table) => Ok(format!("{:?}", describe_table)), Plan::RenameTable(rename_table) => Ok(format!("{:?}", rename_table)), Plan::AddTableColumn(add_table_column) => Ok(format!("{:?}", add_table_column)), Plan::DropTableColumn(drop_table_column) => Ok(format!("{:?}", drop_table_column)), Plan::AlterTableClusterKey(alter_table_cluster_key) => { Ok(format!("{:?}", alter_table_cluster_key)) } Plan::DropTableClusterKey(drop_table_cluster_key) => { Ok(format!("{:?}", drop_table_cluster_key)) } Plan::ReclusterTable(recluster_table) => Ok(format!("{:?}", recluster_table)), Plan::TruncateTable(truncate_table) => Ok(format!("{:?}", truncate_table)), Plan::OptimizeTable(optimize_table) => Ok(format!("{:?}", optimize_table)), Plan::AnalyzeTable(analyze_table) => Ok(format!("{:?}", analyze_table)), Plan::ExistsTable(exists_table) => Ok(format!("{:?}", exists_table)), // Views Plan::CreateView(create_view) => Ok(format!("{:?}", create_view)), Plan::AlterView(alter_view) => Ok(format!("{:?}", alter_view)), Plan::DropView(drop_view) => Ok(format!("{:?}", drop_view)), // Insert Plan::Insert(insert) => Ok(format!("{:?}", insert)), Plan::Replace(replace) => Ok(format!("{:?}", replace)), Plan::Delete(delete) => Ok(format!("{:?}", delete)), Plan::Update(update) => Ok(format!("{:?}", update)), // Stages Plan::CreateStage(create_stage) => Ok(format!("{:?}", create_stage)), Plan::DropStage(s) => Ok(format!("{:?}", s)), Plan::RemoveStage(s) => Ok(format!("{:?}", s)), // FileFormat Plan::CreateFileFormat(create_file_format) => Ok(format!("{:?}", create_file_format)), Plan::DropFileFormat(drop_file_format) => Ok(format!("{:?}", drop_file_format)), Plan::ShowFileFormats(show_file_formats) => Ok(format!("{:?}", show_file_formats)), // Account Plan::GrantRole(grant_role) => Ok(format!("{:?}", grant_role)), Plan::GrantPriv(grant_priv) => Ok(format!("{:?}", grant_priv)), Plan::ShowGrants(show_grants) => Ok(format!("{:?}", show_grants)), Plan::RevokePriv(revoke_priv) => Ok(format!("{:?}", revoke_priv)), Plan::RevokeRole(revoke_role) => Ok(format!("{:?}", revoke_role)), Plan::CreateUser(create_user) => Ok(format!("{:?}", create_user)), Plan::DropUser(drop_user) => Ok(format!("{:?}", drop_user)), Plan::CreateUDF(create_user_udf) => Ok(format!("{:?}", create_user_udf)), Plan::AlterUDF(alter_user_udf) => Ok(format!("{alter_user_udf:?}")), Plan::DropUDF(drop_udf) => Ok(format!("{drop_udf:?}")), Plan::AlterUser(alter_user) => Ok(format!("{:?}", alter_user)), Plan::CreateRole(create_role) => Ok(format!("{:?}", create_role)), Plan::DropRole(drop_role) => Ok(format!("{:?}", drop_role)), Plan::Presign(presign) => Ok(format!("{:?}", presign)), Plan::SetVariable(p) => Ok(format!("{:?}", p)), Plan::UnSetVariable(p) => Ok(format!("{:?}", p)), Plan::SetRole(p) => Ok(format!("{:?}", p)), Plan::UseDatabase(p) => Ok(format!("{:?}", p)), Plan::Kill(p) => Ok(format!("{:?}", p)), Plan::CreateShare(p) => Ok(format!("{:?}", p)), Plan::DropShare(p) => Ok(format!("{:?}", p)), Plan::GrantShareObject(p) => Ok(format!("{:?}", p)), Plan::RevokeShareObject(p) => Ok(format!("{:?}", p)), Plan::AlterShareTenants(p) => Ok(format!("{:?}", p)), Plan::DescShare(p) => Ok(format!("{:?}", p)), Plan::ShowShares(p) => Ok(format!("{:?}", p)), Plan::ShowRoles(p) => Ok(format!("{:?}", p)), Plan::ShowObjectGrantPrivileges(p) => Ok(format!("{:?}", p)), Plan::ShowGrantTenantsOfShare(p) => Ok(format!("{:?}", p)), Plan::RevertTable(p) => Ok(format!("{:?}", p)), } } }
use crate::prelude::*; use std::os::raw::c_void; pub type PFN_vkAllocationFunction = extern "system" fn(*mut c_void, usize, usize, VkSystemAllocationScope) -> *mut c_void; pub type PFN_vkReallocationFunction = extern "system" fn( *mut c_void, *mut c_void, usize, usize, VkSystemAllocationScope, ) -> *mut c_void; pub type PFN_vkFreeFunction = extern "system" fn(*mut c_void, *mut c_void); pub type PFN_vkInternalAllocationNotification = extern "system" fn( *mut c_void, usize, VkInternalAllocationType, VkSystemAllocationScope, ) -> *mut c_void; pub type PFN_vkInternalFreeNotification = extern "system" fn( *mut c_void, usize, VkInternalAllocationType, VkSystemAllocationScope, ) -> *mut c_void; #[repr(C)] pub struct VkAllocationCallbacks { pub pUserData: *mut c_void, pub pfnAllocation: PFN_vkAllocationFunction, pub pfnReallocation: PFN_vkReallocationFunction, pub pfnFree: PFN_vkFreeFunction, pub pfnInternalAllocation: PFN_vkInternalAllocationNotification, pub pfnInternalFree: PFN_vkInternalFreeNotification, }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct IXboxLiveDeviceAddress(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXboxLiveDeviceAddress { type Vtable = IXboxLiveDeviceAddress_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf5bbd279_3c86_4b57_a31a_b9462408fd01); } #[repr(C)] #[doc(hidden)] pub struct IXboxLiveDeviceAddress_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, buffer_array_size: u32, buffer: *mut u8, byteswritten: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, otherdeviceaddress: ::windows::core::RawPtr, result__: *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 bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut XboxLiveNetworkAccessKind) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IXboxLiveDeviceAddressStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXboxLiveDeviceAddressStatics { type Vtable = IXboxLiveDeviceAddressStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5954a819_4a79_4931_827c_7f503e963263); } #[repr(C)] #[doc(hidden)] pub struct IXboxLiveDeviceAddressStatics_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, base64: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, buffer: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, buffer_array_size: u32, buffer: *const u8, 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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IXboxLiveEndpointPair(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXboxLiveEndpointPair { type Vtable = IXboxLiveEndpointPair_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1e9a839b_813e_44e0_b87f_c87a093475e4); } #[repr(C)] #[doc(hidden)] pub struct IXboxLiveEndpointPair_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, #[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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, socketAddress_array_size: u32, socketaddress: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, socketAddress_array_size: u32, socketaddress: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut XboxLiveEndpointPairState) -> ::windows::core::HRESULT, 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, 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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, 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, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IXboxLiveEndpointPairCreationResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXboxLiveEndpointPairCreationResult { type Vtable = IXboxLiveEndpointPairCreationResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd9a8bb95_2aab_4d1e_9794_33ecc0dcf0fe); } #[repr(C)] #[doc(hidden)] pub struct IXboxLiveEndpointPairCreationResult_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut XboxLiveEndpointPairCreationStatus) -> ::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, ); #[repr(transparent)] #[doc(hidden)] pub struct IXboxLiveEndpointPairStateChangedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXboxLiveEndpointPairStateChangedEventArgs { type Vtable = IXboxLiveEndpointPairStateChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x592e3b55_de08_44e7_ac3b_b9b9a169583a); } #[repr(C)] #[doc(hidden)] pub struct IXboxLiveEndpointPairStateChangedEventArgs_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 XboxLiveEndpointPairState) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut XboxLiveEndpointPairState) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IXboxLiveEndpointPairStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXboxLiveEndpointPairStatics { type Vtable = IXboxLiveEndpointPairStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x64316b30_217a_4243_8ee1_6729281d27db); } #[repr(C)] #[doc(hidden)] pub struct IXboxLiveEndpointPairStatics_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, localSocketAddress_array_size: u32, localsocketaddress: *const u8, remoteSocketAddress_array_size: u32, remotesocketaddress: *const u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, localhostname: ::windows::core::RawPtr, localport: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, remotehostname: ::windows::core::RawPtr, remoteport: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IXboxLiveEndpointPairTemplate(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXboxLiveEndpointPairTemplate { type Vtable = IXboxLiveEndpointPairTemplate_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6b286ecf_3457_40ce_b9a1_c0cfe0213ea7); } #[repr(C)] #[doc(hidden)] pub struct IXboxLiveEndpointPairTemplate_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, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceaddress: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceaddress: ::windows::core::RawPtr, behaviors: XboxLiveEndpointPairCreationBehaviors, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceaddress: ::windows::core::RawPtr, initiatorport: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, acceptorport: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceaddress: ::windows::core::RawPtr, initiatorport: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, acceptorport: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, behaviors: XboxLiveEndpointPairCreationBehaviors, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut XboxLiveSocketKind) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u16) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u16) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u16) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u16) -> ::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 IXboxLiveEndpointPairTemplateStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXboxLiveEndpointPairTemplateStatics { type Vtable = IXboxLiveEndpointPairTemplateStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1e13137b_737b_4a23_bc64_0870f75655ba); } #[repr(C)] #[doc(hidden)] pub struct IXboxLiveEndpointPairTemplateStatics_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, name: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::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 IXboxLiveInboundEndpointPairCreatedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXboxLiveInboundEndpointPairCreatedEventArgs { type Vtable = IXboxLiveInboundEndpointPairCreatedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdc183b62_22ba_48d2_80de_c23968bd198b); } #[repr(C)] #[doc(hidden)] pub struct IXboxLiveInboundEndpointPairCreatedEventArgs_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 IXboxLiveQualityOfServiceMeasurement(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXboxLiveQualityOfServiceMeasurement { type Vtable = IXboxLiveQualityOfServiceMeasurement_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4d682bce_a5d6_47e6_a236_cfde5fbdf2ed); } #[repr(C)] #[doc(hidden)] pub struct IXboxLiveQualityOfServiceMeasurement_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, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceaddress: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, metric: XboxLiveQualityOfServiceMetric, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceaddress: ::windows::core::RawPtr, metric: XboxLiveQualityOfServiceMetric, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceaddress: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::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, #[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 bool) -> ::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 u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::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, #[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 IXboxLiveQualityOfServiceMeasurementStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXboxLiveQualityOfServiceMeasurementStatics { type Vtable = IXboxLiveQualityOfServiceMeasurementStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6e352dca_23cf_440a_b077_5e30857a8234); } #[repr(C)] #[doc(hidden)] pub struct IXboxLiveQualityOfServiceMeasurementStatics_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, payload_array_size: u32, payload: *const u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u32) -> ::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, 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, value: bool) -> ::windows::core::HRESULT, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IXboxLiveQualityOfServiceMetricResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXboxLiveQualityOfServiceMetricResult { type Vtable = IXboxLiveQualityOfServiceMetricResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaeec53d1_3561_4782_b0cf_d3ae29d9fa87); } #[repr(C)] #[doc(hidden)] pub struct IXboxLiveQualityOfServiceMetricResult_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 XboxLiveQualityOfServiceMeasurementStatus) -> ::windows::core::HRESULT, 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, result__: *mut XboxLiveQualityOfServiceMetric) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IXboxLiveQualityOfServicePrivatePayloadResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXboxLiveQualityOfServicePrivatePayloadResult { type Vtable = IXboxLiveQualityOfServicePrivatePayloadResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5a6302ae_6f38_41c0_9fcc_ea6cb978cafc); } #[repr(C)] #[doc(hidden)] pub struct IXboxLiveQualityOfServicePrivatePayloadResult_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 XboxLiveQualityOfServiceMeasurementStatus) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct XboxLiveDeviceAddress(pub ::windows::core::IInspectable); impl XboxLiveDeviceAddress { #[cfg(feature = "Foundation")] pub fn SnapshotChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<XboxLiveDeviceAddress, ::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).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveSnapshotChanged<'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() } } pub fn GetSnapshotAsBase64(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn GetSnapshotAsBuffer(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn GetSnapshotAsBytes(&self, buffer: &mut [<u8 as ::windows::core::DefaultType>::DefaultType], byteswritten: &mut u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), buffer.len() as u32, ::core::mem::transmute_copy(&buffer), byteswritten).ok() } } pub fn Compare<'a, Param0: ::windows::core::IntoParam<'a, XboxLiveDeviceAddress>>(&self, otherdeviceaddress: Param0) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), otherdeviceaddress.into_param().abi(), &mut result__).from_abi::<i32>(result__) } } pub fn IsValid(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsLocal(&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__) } } pub fn NetworkAccessKind(&self) -> ::windows::core::Result<XboxLiveNetworkAccessKind> { let this = self; unsafe { let mut result__: XboxLiveNetworkAccessKind = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<XboxLiveNetworkAccessKind>(result__) } } pub fn CreateFromSnapshotBase64<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(base64: Param0) -> ::windows::core::Result<XboxLiveDeviceAddress> { Self::IXboxLiveDeviceAddressStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), base64.into_param().abi(), &mut result__).from_abi::<XboxLiveDeviceAddress>(result__) }) } #[cfg(feature = "Storage_Streams")] pub fn CreateFromSnapshotBuffer<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IBuffer>>(buffer: Param0) -> ::windows::core::Result<XboxLiveDeviceAddress> { Self::IXboxLiveDeviceAddressStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), buffer.into_param().abi(), &mut result__).from_abi::<XboxLiveDeviceAddress>(result__) }) } pub fn CreateFromSnapshotBytes(buffer: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<XboxLiveDeviceAddress> { Self::IXboxLiveDeviceAddressStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), buffer.len() as u32, ::core::mem::transmute(buffer.as_ptr()), &mut result__).from_abi::<XboxLiveDeviceAddress>(result__) }) } pub fn GetLocal() -> ::windows::core::Result<XboxLiveDeviceAddress> { Self::IXboxLiveDeviceAddressStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<XboxLiveDeviceAddress>(result__) }) } pub fn MaxSnapshotBytesSize() -> ::windows::core::Result<u32> { Self::IXboxLiveDeviceAddressStatics(|this| unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) }) } pub fn IXboxLiveDeviceAddressStatics<R, F: FnOnce(&IXboxLiveDeviceAddressStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<XboxLiveDeviceAddress, IXboxLiveDeviceAddressStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for XboxLiveDeviceAddress { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.XboxLive.XboxLiveDeviceAddress;{f5bbd279-3c86-4b57-a31a-b9462408fd01})"); } unsafe impl ::windows::core::Interface for XboxLiveDeviceAddress { type Vtable = IXboxLiveDeviceAddress_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf5bbd279_3c86_4b57_a31a_b9462408fd01); } impl ::windows::core::RuntimeName for XboxLiveDeviceAddress { const NAME: &'static str = "Windows.Networking.XboxLive.XboxLiveDeviceAddress"; } impl ::core::convert::From<XboxLiveDeviceAddress> for ::windows::core::IUnknown { fn from(value: XboxLiveDeviceAddress) -> Self { value.0 .0 } } impl ::core::convert::From<&XboxLiveDeviceAddress> for ::windows::core::IUnknown { fn from(value: &XboxLiveDeviceAddress) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for XboxLiveDeviceAddress { 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 XboxLiveDeviceAddress { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<XboxLiveDeviceAddress> for ::windows::core::IInspectable { fn from(value: XboxLiveDeviceAddress) -> Self { value.0 } } impl ::core::convert::From<&XboxLiveDeviceAddress> for ::windows::core::IInspectable { fn from(value: &XboxLiveDeviceAddress) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for XboxLiveDeviceAddress { 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 XboxLiveDeviceAddress { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for XboxLiveDeviceAddress {} unsafe impl ::core::marker::Sync for XboxLiveDeviceAddress {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct XboxLiveEndpointPair(pub ::windows::core::IInspectable); impl XboxLiveEndpointPair { #[cfg(feature = "Foundation")] pub fn StateChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<XboxLiveEndpointPair, XboxLiveEndpointPairStateChangedEventArgs>>>(&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 RemoveStateChanged<'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() } } #[cfg(feature = "Foundation")] pub fn DeleteAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; 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::<super::super::Foundation::IAsyncAction>(result__) } } pub fn GetRemoteSocketAddressBytes(&self, socketaddress: &mut [<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), socketaddress.len() as u32, ::core::mem::transmute_copy(&socketaddress)).ok() } } pub fn GetLocalSocketAddressBytes(&self, socketaddress: &mut [<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), socketaddress.len() as u32, ::core::mem::transmute_copy(&socketaddress)).ok() } } pub fn State(&self) -> ::windows::core::Result<XboxLiveEndpointPairState> { let this = self; unsafe { let mut result__: XboxLiveEndpointPairState = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<XboxLiveEndpointPairState>(result__) } } pub fn Template(&self) -> ::windows::core::Result<XboxLiveEndpointPairTemplate> { let this = self; 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::<XboxLiveEndpointPairTemplate>(result__) } } pub fn RemoteDeviceAddress(&self) -> ::windows::core::Result<XboxLiveDeviceAddress> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<XboxLiveDeviceAddress>(result__) } } pub fn RemoteHostName(&self) -> ::windows::core::Result<super::HostName> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::HostName>(result__) } } pub fn RemotePort(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn LocalHostName(&self) -> ::windows::core::Result<super::HostName> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::HostName>(result__) } } pub fn LocalPort(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn FindEndpointPairBySocketAddressBytes(localsocketaddress: &[<u8 as ::windows::core::DefaultType>::DefaultType], remotesocketaddress: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<XboxLiveEndpointPair> { Self::IXboxLiveEndpointPairStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), localsocketaddress.len() as u32, ::core::mem::transmute(localsocketaddress.as_ptr()), remotesocketaddress.len() as u32, ::core::mem::transmute(remotesocketaddress.as_ptr()), &mut result__).from_abi::<XboxLiveEndpointPair>(result__) }) } pub fn FindEndpointPairByHostNamesAndPorts<'a, Param0: ::windows::core::IntoParam<'a, super::HostName>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, super::HostName>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(localhostname: Param0, localport: Param1, remotehostname: Param2, remoteport: Param3) -> ::windows::core::Result<XboxLiveEndpointPair> { Self::IXboxLiveEndpointPairStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), localhostname.into_param().abi(), localport.into_param().abi(), remotehostname.into_param().abi(), remoteport.into_param().abi(), &mut result__).from_abi::<XboxLiveEndpointPair>(result__) }) } pub fn IXboxLiveEndpointPairStatics<R, F: FnOnce(&IXboxLiveEndpointPairStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<XboxLiveEndpointPair, IXboxLiveEndpointPairStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for XboxLiveEndpointPair { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.XboxLive.XboxLiveEndpointPair;{1e9a839b-813e-44e0-b87f-c87a093475e4})"); } unsafe impl ::windows::core::Interface for XboxLiveEndpointPair { type Vtable = IXboxLiveEndpointPair_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1e9a839b_813e_44e0_b87f_c87a093475e4); } impl ::windows::core::RuntimeName for XboxLiveEndpointPair { const NAME: &'static str = "Windows.Networking.XboxLive.XboxLiveEndpointPair"; } impl ::core::convert::From<XboxLiveEndpointPair> for ::windows::core::IUnknown { fn from(value: XboxLiveEndpointPair) -> Self { value.0 .0 } } impl ::core::convert::From<&XboxLiveEndpointPair> for ::windows::core::IUnknown { fn from(value: &XboxLiveEndpointPair) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for XboxLiveEndpointPair { 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 XboxLiveEndpointPair { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<XboxLiveEndpointPair> for ::windows::core::IInspectable { fn from(value: XboxLiveEndpointPair) -> Self { value.0 } } impl ::core::convert::From<&XboxLiveEndpointPair> for ::windows::core::IInspectable { fn from(value: &XboxLiveEndpointPair) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for XboxLiveEndpointPair { 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 XboxLiveEndpointPair { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for XboxLiveEndpointPair {} unsafe impl ::core::marker::Sync for XboxLiveEndpointPair {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct XboxLiveEndpointPairCreationBehaviors(pub u32); impl XboxLiveEndpointPairCreationBehaviors { pub const None: XboxLiveEndpointPairCreationBehaviors = XboxLiveEndpointPairCreationBehaviors(0u32); pub const ReevaluatePath: XboxLiveEndpointPairCreationBehaviors = XboxLiveEndpointPairCreationBehaviors(1u32); } impl ::core::convert::From<u32> for XboxLiveEndpointPairCreationBehaviors { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for XboxLiveEndpointPairCreationBehaviors { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for XboxLiveEndpointPairCreationBehaviors { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Networking.XboxLive.XboxLiveEndpointPairCreationBehaviors;u4)"); } impl ::windows::core::DefaultType for XboxLiveEndpointPairCreationBehaviors { type DefaultType = Self; } impl ::core::ops::BitOr for XboxLiveEndpointPairCreationBehaviors { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for XboxLiveEndpointPairCreationBehaviors { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for XboxLiveEndpointPairCreationBehaviors { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for XboxLiveEndpointPairCreationBehaviors { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for XboxLiveEndpointPairCreationBehaviors { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct XboxLiveEndpointPairCreationResult(pub ::windows::core::IInspectable); impl XboxLiveEndpointPairCreationResult { pub fn DeviceAddress(&self) -> ::windows::core::Result<XboxLiveDeviceAddress> { 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::<XboxLiveDeviceAddress>(result__) } } pub fn Status(&self) -> ::windows::core::Result<XboxLiveEndpointPairCreationStatus> { let this = self; unsafe { let mut result__: XboxLiveEndpointPairCreationStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<XboxLiveEndpointPairCreationStatus>(result__) } } pub fn IsExistingPathEvaluation(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn EndpointPair(&self) -> ::windows::core::Result<XboxLiveEndpointPair> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<XboxLiveEndpointPair>(result__) } } } unsafe impl ::windows::core::RuntimeType for XboxLiveEndpointPairCreationResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.XboxLive.XboxLiveEndpointPairCreationResult;{d9a8bb95-2aab-4d1e-9794-33ecc0dcf0fe})"); } unsafe impl ::windows::core::Interface for XboxLiveEndpointPairCreationResult { type Vtable = IXboxLiveEndpointPairCreationResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd9a8bb95_2aab_4d1e_9794_33ecc0dcf0fe); } impl ::windows::core::RuntimeName for XboxLiveEndpointPairCreationResult { const NAME: &'static str = "Windows.Networking.XboxLive.XboxLiveEndpointPairCreationResult"; } impl ::core::convert::From<XboxLiveEndpointPairCreationResult> for ::windows::core::IUnknown { fn from(value: XboxLiveEndpointPairCreationResult) -> Self { value.0 .0 } } impl ::core::convert::From<&XboxLiveEndpointPairCreationResult> for ::windows::core::IUnknown { fn from(value: &XboxLiveEndpointPairCreationResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for XboxLiveEndpointPairCreationResult { 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 XboxLiveEndpointPairCreationResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<XboxLiveEndpointPairCreationResult> for ::windows::core::IInspectable { fn from(value: XboxLiveEndpointPairCreationResult) -> Self { value.0 } } impl ::core::convert::From<&XboxLiveEndpointPairCreationResult> for ::windows::core::IInspectable { fn from(value: &XboxLiveEndpointPairCreationResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for XboxLiveEndpointPairCreationResult { 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 XboxLiveEndpointPairCreationResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for XboxLiveEndpointPairCreationResult {} unsafe impl ::core::marker::Sync for XboxLiveEndpointPairCreationResult {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct XboxLiveEndpointPairCreationStatus(pub i32); impl XboxLiveEndpointPairCreationStatus { pub const Succeeded: XboxLiveEndpointPairCreationStatus = XboxLiveEndpointPairCreationStatus(0i32); pub const NoLocalNetworks: XboxLiveEndpointPairCreationStatus = XboxLiveEndpointPairCreationStatus(1i32); pub const NoCompatibleNetworkPaths: XboxLiveEndpointPairCreationStatus = XboxLiveEndpointPairCreationStatus(2i32); pub const LocalSystemNotAuthorized: XboxLiveEndpointPairCreationStatus = XboxLiveEndpointPairCreationStatus(3i32); pub const Canceled: XboxLiveEndpointPairCreationStatus = XboxLiveEndpointPairCreationStatus(4i32); pub const TimedOut: XboxLiveEndpointPairCreationStatus = XboxLiveEndpointPairCreationStatus(5i32); pub const RemoteSystemNotAuthorized: XboxLiveEndpointPairCreationStatus = XboxLiveEndpointPairCreationStatus(6i32); pub const RefusedDueToConfiguration: XboxLiveEndpointPairCreationStatus = XboxLiveEndpointPairCreationStatus(7i32); pub const UnexpectedInternalError: XboxLiveEndpointPairCreationStatus = XboxLiveEndpointPairCreationStatus(8i32); } impl ::core::convert::From<i32> for XboxLiveEndpointPairCreationStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for XboxLiveEndpointPairCreationStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for XboxLiveEndpointPairCreationStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Networking.XboxLive.XboxLiveEndpointPairCreationStatus;i4)"); } impl ::windows::core::DefaultType for XboxLiveEndpointPairCreationStatus { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct XboxLiveEndpointPairState(pub i32); impl XboxLiveEndpointPairState { pub const Invalid: XboxLiveEndpointPairState = XboxLiveEndpointPairState(0i32); pub const CreatingOutbound: XboxLiveEndpointPairState = XboxLiveEndpointPairState(1i32); pub const CreatingInbound: XboxLiveEndpointPairState = XboxLiveEndpointPairState(2i32); pub const Ready: XboxLiveEndpointPairState = XboxLiveEndpointPairState(3i32); pub const DeletingLocally: XboxLiveEndpointPairState = XboxLiveEndpointPairState(4i32); pub const RemoteEndpointTerminating: XboxLiveEndpointPairState = XboxLiveEndpointPairState(5i32); pub const Deleted: XboxLiveEndpointPairState = XboxLiveEndpointPairState(6i32); } impl ::core::convert::From<i32> for XboxLiveEndpointPairState { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for XboxLiveEndpointPairState { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for XboxLiveEndpointPairState { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Networking.XboxLive.XboxLiveEndpointPairState;i4)"); } impl ::windows::core::DefaultType for XboxLiveEndpointPairState { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct XboxLiveEndpointPairStateChangedEventArgs(pub ::windows::core::IInspectable); impl XboxLiveEndpointPairStateChangedEventArgs { pub fn OldState(&self) -> ::windows::core::Result<XboxLiveEndpointPairState> { let this = self; unsafe { let mut result__: XboxLiveEndpointPairState = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<XboxLiveEndpointPairState>(result__) } } pub fn NewState(&self) -> ::windows::core::Result<XboxLiveEndpointPairState> { let this = self; unsafe { let mut result__: XboxLiveEndpointPairState = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<XboxLiveEndpointPairState>(result__) } } } unsafe impl ::windows::core::RuntimeType for XboxLiveEndpointPairStateChangedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.XboxLive.XboxLiveEndpointPairStateChangedEventArgs;{592e3b55-de08-44e7-ac3b-b9b9a169583a})"); } unsafe impl ::windows::core::Interface for XboxLiveEndpointPairStateChangedEventArgs { type Vtable = IXboxLiveEndpointPairStateChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x592e3b55_de08_44e7_ac3b_b9b9a169583a); } impl ::windows::core::RuntimeName for XboxLiveEndpointPairStateChangedEventArgs { const NAME: &'static str = "Windows.Networking.XboxLive.XboxLiveEndpointPairStateChangedEventArgs"; } impl ::core::convert::From<XboxLiveEndpointPairStateChangedEventArgs> for ::windows::core::IUnknown { fn from(value: XboxLiveEndpointPairStateChangedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&XboxLiveEndpointPairStateChangedEventArgs> for ::windows::core::IUnknown { fn from(value: &XboxLiveEndpointPairStateChangedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for XboxLiveEndpointPairStateChangedEventArgs { 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 XboxLiveEndpointPairStateChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<XboxLiveEndpointPairStateChangedEventArgs> for ::windows::core::IInspectable { fn from(value: XboxLiveEndpointPairStateChangedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&XboxLiveEndpointPairStateChangedEventArgs> for ::windows::core::IInspectable { fn from(value: &XboxLiveEndpointPairStateChangedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for XboxLiveEndpointPairStateChangedEventArgs { 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 XboxLiveEndpointPairStateChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for XboxLiveEndpointPairStateChangedEventArgs {} unsafe impl ::core::marker::Sync for XboxLiveEndpointPairStateChangedEventArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct XboxLiveEndpointPairTemplate(pub ::windows::core::IInspectable); impl XboxLiveEndpointPairTemplate { #[cfg(feature = "Foundation")] pub fn InboundEndpointPairCreated<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<XboxLiveEndpointPairTemplate, XboxLiveInboundEndpointPairCreatedEventArgs>>>(&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 RemoveInboundEndpointPairCreated<'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() } } #[cfg(feature = "Foundation")] pub fn CreateEndpointPairDefaultAsync<'a, Param0: ::windows::core::IntoParam<'a, XboxLiveDeviceAddress>>(&self, deviceaddress: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<XboxLiveEndpointPairCreationResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), deviceaddress.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<XboxLiveEndpointPairCreationResult>>(result__) } } #[cfg(feature = "Foundation")] pub fn CreateEndpointPairWithBehaviorsAsync<'a, Param0: ::windows::core::IntoParam<'a, XboxLiveDeviceAddress>>(&self, deviceaddress: Param0, behaviors: XboxLiveEndpointPairCreationBehaviors) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<XboxLiveEndpointPairCreationResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), deviceaddress.into_param().abi(), behaviors, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<XboxLiveEndpointPairCreationResult>>(result__) } } #[cfg(feature = "Foundation")] pub fn CreateEndpointPairForPortsDefaultAsync<'a, Param0: ::windows::core::IntoParam<'a, XboxLiveDeviceAddress>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, deviceaddress: Param0, initiatorport: Param1, acceptorport: Param2) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<XboxLiveEndpointPairCreationResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), deviceaddress.into_param().abi(), initiatorport.into_param().abi(), acceptorport.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<XboxLiveEndpointPairCreationResult>>(result__) } } #[cfg(feature = "Foundation")] pub fn CreateEndpointPairForPortsWithBehaviorsAsync<'a, Param0: ::windows::core::IntoParam<'a, XboxLiveDeviceAddress>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, deviceaddress: Param0, initiatorport: Param1, acceptorport: Param2, behaviors: XboxLiveEndpointPairCreationBehaviors) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<XboxLiveEndpointPairCreationResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), deviceaddress.into_param().abi(), initiatorport.into_param().abi(), acceptorport.into_param().abi(), behaviors, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<XboxLiveEndpointPairCreationResult>>(result__) } } pub fn Name(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SocketKind(&self) -> ::windows::core::Result<XboxLiveSocketKind> { let this = self; unsafe { let mut result__: XboxLiveSocketKind = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<XboxLiveSocketKind>(result__) } } pub fn InitiatorBoundPortRangeLower(&self) -> ::windows::core::Result<u16> { let this = self; unsafe { let mut result__: u16 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u16>(result__) } } pub fn InitiatorBoundPortRangeUpper(&self) -> ::windows::core::Result<u16> { let this = self; unsafe { let mut result__: u16 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u16>(result__) } } pub fn AcceptorBoundPortRangeLower(&self) -> ::windows::core::Result<u16> { let this = self; unsafe { let mut result__: u16 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u16>(result__) } } pub fn AcceptorBoundPortRangeUpper(&self) -> ::windows::core::Result<u16> { let this = self; unsafe { let mut result__: u16 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u16>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn EndpointPairs(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<XboxLiveEndpointPair>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<XboxLiveEndpointPair>>(result__) } } pub fn GetTemplateByName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(name: Param0) -> ::windows::core::Result<XboxLiveEndpointPairTemplate> { Self::IXboxLiveEndpointPairTemplateStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), name.into_param().abi(), &mut result__).from_abi::<XboxLiveEndpointPairTemplate>(result__) }) } #[cfg(feature = "Foundation_Collections")] pub fn Templates() -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<XboxLiveEndpointPairTemplate>> { Self::IXboxLiveEndpointPairTemplateStatics(|this| 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::Collections::IVectorView<XboxLiveEndpointPairTemplate>>(result__) }) } pub fn IXboxLiveEndpointPairTemplateStatics<R, F: FnOnce(&IXboxLiveEndpointPairTemplateStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<XboxLiveEndpointPairTemplate, IXboxLiveEndpointPairTemplateStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for XboxLiveEndpointPairTemplate { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.XboxLive.XboxLiveEndpointPairTemplate;{6b286ecf-3457-40ce-b9a1-c0cfe0213ea7})"); } unsafe impl ::windows::core::Interface for XboxLiveEndpointPairTemplate { type Vtable = IXboxLiveEndpointPairTemplate_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6b286ecf_3457_40ce_b9a1_c0cfe0213ea7); } impl ::windows::core::RuntimeName for XboxLiveEndpointPairTemplate { const NAME: &'static str = "Windows.Networking.XboxLive.XboxLiveEndpointPairTemplate"; } impl ::core::convert::From<XboxLiveEndpointPairTemplate> for ::windows::core::IUnknown { fn from(value: XboxLiveEndpointPairTemplate) -> Self { value.0 .0 } } impl ::core::convert::From<&XboxLiveEndpointPairTemplate> for ::windows::core::IUnknown { fn from(value: &XboxLiveEndpointPairTemplate) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for XboxLiveEndpointPairTemplate { 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 XboxLiveEndpointPairTemplate { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<XboxLiveEndpointPairTemplate> for ::windows::core::IInspectable { fn from(value: XboxLiveEndpointPairTemplate) -> Self { value.0 } } impl ::core::convert::From<&XboxLiveEndpointPairTemplate> for ::windows::core::IInspectable { fn from(value: &XboxLiveEndpointPairTemplate) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for XboxLiveEndpointPairTemplate { 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 XboxLiveEndpointPairTemplate { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for XboxLiveEndpointPairTemplate {} unsafe impl ::core::marker::Sync for XboxLiveEndpointPairTemplate {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct XboxLiveInboundEndpointPairCreatedEventArgs(pub ::windows::core::IInspectable); impl XboxLiveInboundEndpointPairCreatedEventArgs { pub fn EndpointPair(&self) -> ::windows::core::Result<XboxLiveEndpointPair> { 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::<XboxLiveEndpointPair>(result__) } } } unsafe impl ::windows::core::RuntimeType for XboxLiveInboundEndpointPairCreatedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.XboxLive.XboxLiveInboundEndpointPairCreatedEventArgs;{dc183b62-22ba-48d2-80de-c23968bd198b})"); } unsafe impl ::windows::core::Interface for XboxLiveInboundEndpointPairCreatedEventArgs { type Vtable = IXboxLiveInboundEndpointPairCreatedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdc183b62_22ba_48d2_80de_c23968bd198b); } impl ::windows::core::RuntimeName for XboxLiveInboundEndpointPairCreatedEventArgs { const NAME: &'static str = "Windows.Networking.XboxLive.XboxLiveInboundEndpointPairCreatedEventArgs"; } impl ::core::convert::From<XboxLiveInboundEndpointPairCreatedEventArgs> for ::windows::core::IUnknown { fn from(value: XboxLiveInboundEndpointPairCreatedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&XboxLiveInboundEndpointPairCreatedEventArgs> for ::windows::core::IUnknown { fn from(value: &XboxLiveInboundEndpointPairCreatedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for XboxLiveInboundEndpointPairCreatedEventArgs { 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 XboxLiveInboundEndpointPairCreatedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<XboxLiveInboundEndpointPairCreatedEventArgs> for ::windows::core::IInspectable { fn from(value: XboxLiveInboundEndpointPairCreatedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&XboxLiveInboundEndpointPairCreatedEventArgs> for ::windows::core::IInspectable { fn from(value: &XboxLiveInboundEndpointPairCreatedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for XboxLiveInboundEndpointPairCreatedEventArgs { 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 XboxLiveInboundEndpointPairCreatedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for XboxLiveInboundEndpointPairCreatedEventArgs {} unsafe impl ::core::marker::Sync for XboxLiveInboundEndpointPairCreatedEventArgs {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct XboxLiveNetworkAccessKind(pub i32); impl XboxLiveNetworkAccessKind { pub const Open: XboxLiveNetworkAccessKind = XboxLiveNetworkAccessKind(0i32); pub const Moderate: XboxLiveNetworkAccessKind = XboxLiveNetworkAccessKind(1i32); pub const Strict: XboxLiveNetworkAccessKind = XboxLiveNetworkAccessKind(2i32); } impl ::core::convert::From<i32> for XboxLiveNetworkAccessKind { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for XboxLiveNetworkAccessKind { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for XboxLiveNetworkAccessKind { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Networking.XboxLive.XboxLiveNetworkAccessKind;i4)"); } impl ::windows::core::DefaultType for XboxLiveNetworkAccessKind { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct XboxLiveQualityOfServiceMeasurement(pub ::windows::core::IInspectable); impl XboxLiveQualityOfServiceMeasurement { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<XboxLiveQualityOfServiceMeasurement, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation")] pub fn MeasureAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { 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::IAsyncAction>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn GetMetricResultsForDevice<'a, Param0: ::windows::core::IntoParam<'a, XboxLiveDeviceAddress>>(&self, deviceaddress: Param0) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<XboxLiveQualityOfServiceMetricResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), deviceaddress.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<XboxLiveQualityOfServiceMetricResult>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn GetMetricResultsForMetric(&self, metric: XboxLiveQualityOfServiceMetric) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<XboxLiveQualityOfServiceMetricResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), metric, &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<XboxLiveQualityOfServiceMetricResult>>(result__) } } pub fn GetMetricResult<'a, Param0: ::windows::core::IntoParam<'a, XboxLiveDeviceAddress>>(&self, deviceaddress: Param0, metric: XboxLiveQualityOfServiceMetric) -> ::windows::core::Result<XboxLiveQualityOfServiceMetricResult> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), deviceaddress.into_param().abi(), metric, &mut result__).from_abi::<XboxLiveQualityOfServiceMetricResult>(result__) } } pub fn GetPrivatePayloadResult<'a, Param0: ::windows::core::IntoParam<'a, XboxLiveDeviceAddress>>(&self, deviceaddress: Param0) -> ::windows::core::Result<XboxLiveQualityOfServicePrivatePayloadResult> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), deviceaddress.into_param().abi(), &mut result__).from_abi::<XboxLiveQualityOfServicePrivatePayloadResult>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Metrics(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<XboxLiveQualityOfServiceMetric>> { let this = self; 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::IVector<XboxLiveQualityOfServiceMetric>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn DeviceAddresses(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<XboxLiveDeviceAddress>> { let this = self; 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::<super::super::Foundation::Collections::IVector<XboxLiveDeviceAddress>>(result__) } } pub fn ShouldRequestPrivatePayloads(&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__) } } pub fn SetShouldRequestPrivatePayloads(&self, value: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), value).ok() } } pub fn TimeoutInMilliseconds(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn SetTimeoutInMilliseconds(&self, value: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), value).ok() } } pub fn NumberOfProbesToAttempt(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn SetNumberOfProbesToAttempt(&self, value: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), value).ok() } } pub fn NumberOfResultsPending(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn MetricResults(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<XboxLiveQualityOfServiceMetricResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<XboxLiveQualityOfServiceMetricResult>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn PrivatePayloadResults(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<XboxLiveQualityOfServicePrivatePayloadResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<XboxLiveQualityOfServicePrivatePayloadResult>>(result__) } } pub fn PublishPrivatePayloadBytes(payload: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { Self::IXboxLiveQualityOfServiceMeasurementStatics(|this| unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), payload.len() as u32, ::core::mem::transmute(payload.as_ptr())).ok() }) } pub fn ClearPrivatePayload() -> ::windows::core::Result<()> { Self::IXboxLiveQualityOfServiceMeasurementStatics(|this| unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this)).ok() }) } pub fn MaxSimultaneousProbeConnections() -> ::windows::core::Result<u32> { Self::IXboxLiveQualityOfServiceMeasurementStatics(|this| unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) }) } pub fn SetMaxSimultaneousProbeConnections(value: u32) -> ::windows::core::Result<()> { Self::IXboxLiveQualityOfServiceMeasurementStatics(|this| unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() }) } pub fn IsSystemOutboundBandwidthConstrained() -> ::windows::core::Result<bool> { Self::IXboxLiveQualityOfServiceMeasurementStatics(|this| 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__) }) } pub fn SetIsSystemOutboundBandwidthConstrained(value: bool) -> ::windows::core::Result<()> { Self::IXboxLiveQualityOfServiceMeasurementStatics(|this| unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() }) } pub fn IsSystemInboundBandwidthConstrained() -> ::windows::core::Result<bool> { Self::IXboxLiveQualityOfServiceMeasurementStatics(|this| unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) }) } pub fn SetIsSystemInboundBandwidthConstrained(value: bool) -> ::windows::core::Result<()> { Self::IXboxLiveQualityOfServiceMeasurementStatics(|this| unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value).ok() }) } #[cfg(feature = "Storage_Streams")] pub fn PublishedPrivatePayload() -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { Self::IXboxLiveQualityOfServiceMeasurementStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) }) } #[cfg(feature = "Storage_Streams")] pub fn SetPublishedPrivatePayload<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IBuffer>>(value: Param0) -> ::windows::core::Result<()> { Self::IXboxLiveQualityOfServiceMeasurementStatics(|this| unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }) } pub fn MaxPrivatePayloadSize() -> ::windows::core::Result<u32> { Self::IXboxLiveQualityOfServiceMeasurementStatics(|this| unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) }) } pub fn IXboxLiveQualityOfServiceMeasurementStatics<R, F: FnOnce(&IXboxLiveQualityOfServiceMeasurementStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<XboxLiveQualityOfServiceMeasurement, IXboxLiveQualityOfServiceMeasurementStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for XboxLiveQualityOfServiceMeasurement { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.XboxLive.XboxLiveQualityOfServiceMeasurement;{4d682bce-a5d6-47e6-a236-cfde5fbdf2ed})"); } unsafe impl ::windows::core::Interface for XboxLiveQualityOfServiceMeasurement { type Vtable = IXboxLiveQualityOfServiceMeasurement_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4d682bce_a5d6_47e6_a236_cfde5fbdf2ed); } impl ::windows::core::RuntimeName for XboxLiveQualityOfServiceMeasurement { const NAME: &'static str = "Windows.Networking.XboxLive.XboxLiveQualityOfServiceMeasurement"; } impl ::core::convert::From<XboxLiveQualityOfServiceMeasurement> for ::windows::core::IUnknown { fn from(value: XboxLiveQualityOfServiceMeasurement) -> Self { value.0 .0 } } impl ::core::convert::From<&XboxLiveQualityOfServiceMeasurement> for ::windows::core::IUnknown { fn from(value: &XboxLiveQualityOfServiceMeasurement) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for XboxLiveQualityOfServiceMeasurement { 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 XboxLiveQualityOfServiceMeasurement { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<XboxLiveQualityOfServiceMeasurement> for ::windows::core::IInspectable { fn from(value: XboxLiveQualityOfServiceMeasurement) -> Self { value.0 } } impl ::core::convert::From<&XboxLiveQualityOfServiceMeasurement> for ::windows::core::IInspectable { fn from(value: &XboxLiveQualityOfServiceMeasurement) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for XboxLiveQualityOfServiceMeasurement { 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 XboxLiveQualityOfServiceMeasurement { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for XboxLiveQualityOfServiceMeasurement {} unsafe impl ::core::marker::Sync for XboxLiveQualityOfServiceMeasurement {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct XboxLiveQualityOfServiceMeasurementStatus(pub i32); impl XboxLiveQualityOfServiceMeasurementStatus { pub const NotStarted: XboxLiveQualityOfServiceMeasurementStatus = XboxLiveQualityOfServiceMeasurementStatus(0i32); pub const InProgress: XboxLiveQualityOfServiceMeasurementStatus = XboxLiveQualityOfServiceMeasurementStatus(1i32); pub const InProgressWithProvisionalResults: XboxLiveQualityOfServiceMeasurementStatus = XboxLiveQualityOfServiceMeasurementStatus(2i32); pub const Succeeded: XboxLiveQualityOfServiceMeasurementStatus = XboxLiveQualityOfServiceMeasurementStatus(3i32); pub const NoLocalNetworks: XboxLiveQualityOfServiceMeasurementStatus = XboxLiveQualityOfServiceMeasurementStatus(4i32); pub const NoCompatibleNetworkPaths: XboxLiveQualityOfServiceMeasurementStatus = XboxLiveQualityOfServiceMeasurementStatus(5i32); pub const LocalSystemNotAuthorized: XboxLiveQualityOfServiceMeasurementStatus = XboxLiveQualityOfServiceMeasurementStatus(6i32); pub const Canceled: XboxLiveQualityOfServiceMeasurementStatus = XboxLiveQualityOfServiceMeasurementStatus(7i32); pub const TimedOut: XboxLiveQualityOfServiceMeasurementStatus = XboxLiveQualityOfServiceMeasurementStatus(8i32); pub const RemoteSystemNotAuthorized: XboxLiveQualityOfServiceMeasurementStatus = XboxLiveQualityOfServiceMeasurementStatus(9i32); pub const RefusedDueToConfiguration: XboxLiveQualityOfServiceMeasurementStatus = XboxLiveQualityOfServiceMeasurementStatus(10i32); pub const UnexpectedInternalError: XboxLiveQualityOfServiceMeasurementStatus = XboxLiveQualityOfServiceMeasurementStatus(11i32); } impl ::core::convert::From<i32> for XboxLiveQualityOfServiceMeasurementStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for XboxLiveQualityOfServiceMeasurementStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for XboxLiveQualityOfServiceMeasurementStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Networking.XboxLive.XboxLiveQualityOfServiceMeasurementStatus;i4)"); } impl ::windows::core::DefaultType for XboxLiveQualityOfServiceMeasurementStatus { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct XboxLiveQualityOfServiceMetric(pub i32); impl XboxLiveQualityOfServiceMetric { pub const AverageLatencyInMilliseconds: XboxLiveQualityOfServiceMetric = XboxLiveQualityOfServiceMetric(0i32); pub const MinLatencyInMilliseconds: XboxLiveQualityOfServiceMetric = XboxLiveQualityOfServiceMetric(1i32); pub const MaxLatencyInMilliseconds: XboxLiveQualityOfServiceMetric = XboxLiveQualityOfServiceMetric(2i32); pub const AverageOutboundBitsPerSecond: XboxLiveQualityOfServiceMetric = XboxLiveQualityOfServiceMetric(3i32); pub const MinOutboundBitsPerSecond: XboxLiveQualityOfServiceMetric = XboxLiveQualityOfServiceMetric(4i32); pub const MaxOutboundBitsPerSecond: XboxLiveQualityOfServiceMetric = XboxLiveQualityOfServiceMetric(5i32); pub const AverageInboundBitsPerSecond: XboxLiveQualityOfServiceMetric = XboxLiveQualityOfServiceMetric(6i32); pub const MinInboundBitsPerSecond: XboxLiveQualityOfServiceMetric = XboxLiveQualityOfServiceMetric(7i32); pub const MaxInboundBitsPerSecond: XboxLiveQualityOfServiceMetric = XboxLiveQualityOfServiceMetric(8i32); } impl ::core::convert::From<i32> for XboxLiveQualityOfServiceMetric { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for XboxLiveQualityOfServiceMetric { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for XboxLiveQualityOfServiceMetric { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Networking.XboxLive.XboxLiveQualityOfServiceMetric;i4)"); } impl ::windows::core::DefaultType for XboxLiveQualityOfServiceMetric { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct XboxLiveQualityOfServiceMetricResult(pub ::windows::core::IInspectable); impl XboxLiveQualityOfServiceMetricResult { pub fn Status(&self) -> ::windows::core::Result<XboxLiveQualityOfServiceMeasurementStatus> { let this = self; unsafe { let mut result__: XboxLiveQualityOfServiceMeasurementStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<XboxLiveQualityOfServiceMeasurementStatus>(result__) } } pub fn DeviceAddress(&self) -> ::windows::core::Result<XboxLiveDeviceAddress> { 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::<XboxLiveDeviceAddress>(result__) } } pub fn Metric(&self) -> ::windows::core::Result<XboxLiveQualityOfServiceMetric> { let this = self; unsafe { let mut result__: XboxLiveQualityOfServiceMetric = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<XboxLiveQualityOfServiceMetric>(result__) } } pub fn Value(&self) -> ::windows::core::Result<u64> { let this = self; unsafe { let mut result__: u64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__) } } } unsafe impl ::windows::core::RuntimeType for XboxLiveQualityOfServiceMetricResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.XboxLive.XboxLiveQualityOfServiceMetricResult;{aeec53d1-3561-4782-b0cf-d3ae29d9fa87})"); } unsafe impl ::windows::core::Interface for XboxLiveQualityOfServiceMetricResult { type Vtable = IXboxLiveQualityOfServiceMetricResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaeec53d1_3561_4782_b0cf_d3ae29d9fa87); } impl ::windows::core::RuntimeName for XboxLiveQualityOfServiceMetricResult { const NAME: &'static str = "Windows.Networking.XboxLive.XboxLiveQualityOfServiceMetricResult"; } impl ::core::convert::From<XboxLiveQualityOfServiceMetricResult> for ::windows::core::IUnknown { fn from(value: XboxLiveQualityOfServiceMetricResult) -> Self { value.0 .0 } } impl ::core::convert::From<&XboxLiveQualityOfServiceMetricResult> for ::windows::core::IUnknown { fn from(value: &XboxLiveQualityOfServiceMetricResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for XboxLiveQualityOfServiceMetricResult { 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 XboxLiveQualityOfServiceMetricResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<XboxLiveQualityOfServiceMetricResult> for ::windows::core::IInspectable { fn from(value: XboxLiveQualityOfServiceMetricResult) -> Self { value.0 } } impl ::core::convert::From<&XboxLiveQualityOfServiceMetricResult> for ::windows::core::IInspectable { fn from(value: &XboxLiveQualityOfServiceMetricResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for XboxLiveQualityOfServiceMetricResult { 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 XboxLiveQualityOfServiceMetricResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for XboxLiveQualityOfServiceMetricResult {} unsafe impl ::core::marker::Sync for XboxLiveQualityOfServiceMetricResult {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct XboxLiveQualityOfServicePrivatePayloadResult(pub ::windows::core::IInspectable); impl XboxLiveQualityOfServicePrivatePayloadResult { pub fn Status(&self) -> ::windows::core::Result<XboxLiveQualityOfServiceMeasurementStatus> { let this = self; unsafe { let mut result__: XboxLiveQualityOfServiceMeasurementStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<XboxLiveQualityOfServiceMeasurementStatus>(result__) } } pub fn DeviceAddress(&self) -> ::windows::core::Result<XboxLiveDeviceAddress> { 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::<XboxLiveDeviceAddress>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn Value(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = self; 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::<super::super::Storage::Streams::IBuffer>(result__) } } } unsafe impl ::windows::core::RuntimeType for XboxLiveQualityOfServicePrivatePayloadResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.XboxLive.XboxLiveQualityOfServicePrivatePayloadResult;{5a6302ae-6f38-41c0-9fcc-ea6cb978cafc})"); } unsafe impl ::windows::core::Interface for XboxLiveQualityOfServicePrivatePayloadResult { type Vtable = IXboxLiveQualityOfServicePrivatePayloadResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5a6302ae_6f38_41c0_9fcc_ea6cb978cafc); } impl ::windows::core::RuntimeName for XboxLiveQualityOfServicePrivatePayloadResult { const NAME: &'static str = "Windows.Networking.XboxLive.XboxLiveQualityOfServicePrivatePayloadResult"; } impl ::core::convert::From<XboxLiveQualityOfServicePrivatePayloadResult> for ::windows::core::IUnknown { fn from(value: XboxLiveQualityOfServicePrivatePayloadResult) -> Self { value.0 .0 } } impl ::core::convert::From<&XboxLiveQualityOfServicePrivatePayloadResult> for ::windows::core::IUnknown { fn from(value: &XboxLiveQualityOfServicePrivatePayloadResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for XboxLiveQualityOfServicePrivatePayloadResult { 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 XboxLiveQualityOfServicePrivatePayloadResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<XboxLiveQualityOfServicePrivatePayloadResult> for ::windows::core::IInspectable { fn from(value: XboxLiveQualityOfServicePrivatePayloadResult) -> Self { value.0 } } impl ::core::convert::From<&XboxLiveQualityOfServicePrivatePayloadResult> for ::windows::core::IInspectable { fn from(value: &XboxLiveQualityOfServicePrivatePayloadResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for XboxLiveQualityOfServicePrivatePayloadResult { 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 XboxLiveQualityOfServicePrivatePayloadResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for XboxLiveQualityOfServicePrivatePayloadResult {} unsafe impl ::core::marker::Sync for XboxLiveQualityOfServicePrivatePayloadResult {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct XboxLiveSocketKind(pub i32); impl XboxLiveSocketKind { pub const None: XboxLiveSocketKind = XboxLiveSocketKind(0i32); pub const Datagram: XboxLiveSocketKind = XboxLiveSocketKind(1i32); pub const Stream: XboxLiveSocketKind = XboxLiveSocketKind(2i32); } impl ::core::convert::From<i32> for XboxLiveSocketKind { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for XboxLiveSocketKind { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for XboxLiveSocketKind { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Networking.XboxLive.XboxLiveSocketKind;i4)"); } impl ::windows::core::DefaultType for XboxLiveSocketKind { type DefaultType = Self; }
// Copyright 2017 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. // ignore-emscripten FIXME(#45351) #![feature(repr_simd, platform_intrinsics)] #[repr(C)] #[repr(simd)] #[derive(Copy, Clone, Debug)] pub struct char3(pub i8, pub i8, pub i8); #[repr(C)] #[repr(simd)] #[derive(Copy, Clone, Debug)] pub struct short3(pub i16, pub i16, pub i16); extern "platform-intrinsic" { fn simd_cast<T, U>(x: T) -> U; } fn main() { let cast: short3 = unsafe { simd_cast(char3(10, -3, -9)) }; println!("{:?}", cast); }
use crate::error::{ErrorManager, Level}; use crate::span::Index; use crate::span::Span; #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub enum Keyword { And, Break, Do, Else, ElseIf, End, False, For, Function, Goto, If, In, Local, Nil, Not, Or, Repeat, Return, Then, True, Until, While, } impl Keyword { pub fn from_str(s: &str) -> Option<Self> { Some(match s { "and" => Keyword::And, "break" => Keyword::Break, "do" => Keyword::Do, "else" => Keyword::Else, "elseif" => Keyword::ElseIf, "end" => Keyword::End, "false" => Keyword::False, "for" => Keyword::For, "function" => Keyword::Function, "goto" => Keyword::Goto, "if" => Keyword::If, "in" => Keyword::In, "local" => Keyword::Local, "nil" => Keyword::Nil, "not" => Keyword::Not, "or" => Keyword::Or, "repeat" => Keyword::Repeat, "return" => Keyword::Return, "then" => Keyword::Then, "true" => Keyword::True, "until" => Keyword::Until, "while" => Keyword::While, _ => return None, }) } } #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub enum Token { Kw(Keyword), Plus, Minus, Star, Slash, Percent, Exp, Hash, BitAnd, Tilde, BitOr, LtLt, GtGt, ShashSlash, ColonColon, EqEq, TildeEq, LtEq, GtEq, Lt, Gt, Eq, OpenParen, CloseParen, OpenBrace, CloseBrace, OpenBracket, CloseBracket, Semicolon, Colon, Comma, Dot, DotDot, DotDotDot, Number, String(char), LongString(usize), Ident, Unknown(char), } #[macro_export] #[cfg_attr(rustfmt, rustfmt_skip)] macro_rules! tok { (and) => {Token::Kw(Keyword::And)}; (break) => {Token::Kw(Keyword::Break)}; (do) => {Token::Kw(Keyword::Do)}; (else) => {Token::Kw(Keyword::Else)}; (elseif) => {Token::Kw(Keyword::ElseIf)}; (end) => {Token::Kw(Keyword::End)}; (false) => {Token::Kw(Keyword::False)}; (for) => {Token::Kw(Keyword::For)}; (function) => {Token::Kw(Keyword::Function)}; (goto) => {Token::Kw(Keyword::Goto)}; (if) => {Token::Kw(Keyword::If)}; (in) => {Token::Kw(Keyword::In)}; (local) => {Token::Kw(Keyword::Local)}; (nil) => {Token::Kw(Keyword::Nil)}; (not) => {Token::Kw(Keyword::Not)}; (or) => {Token::Kw(Keyword::Or)}; (repeat) => {Token::Kw(Keyword::Repeat)}; (return) => {Token::Kw(Keyword::Return)}; (then) => {Token::Kw(Keyword::Then)}; (true) => {Token::Kw(Keyword::True)}; (until) => {Token::Kw(Keyword::Until)}; (while) => {Token::Kw(Keyword::While)}; (+) => {Token::Plus}; (-) => {Token::Minus}; (*) => {Token::Star}; (/) => {Token::Slash}; (%) => {Token::Percent}; (^) => {Token::Exp}; (#) => {Token::Hash}; (&) => {Token::BitAnd}; (~) => {Token::Tilde}; (|) => {Token::BitOr}; (<<) => {Token::LtLt}; (>>) => {Token::GtGt}; ("//") => {Token::ShashSlash}; (::) => {Token::ColonColon}; (==) => {Token::EqEq}; (~=) => {Token::TildeEq}; (<=) => {Token::LtEq}; (>=) => {Token::GtEq}; (<) => {Token::Lt}; (>) => {Token::Gt}; (=) => {Token::Eq}; ("(") => {Token::OpenParen}; (")") => {Token::CloseParen}; ("{") => {Token::OpenBrace}; ("}") => {Token::CloseBrace}; ("[") => {Token::OpenBracket}; ("]") => {Token::CloseBracket}; (;) => {Token::Semicolon}; (:) => {Token::Colon}; (,) => {Token::Comma}; (.) => {Token::Dot}; (..) => {Token::DotDot}; (...) => {Token::DotDotDot}; } #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub struct SpannedToken { pub ty: Token, pub span: Span, } #[derive(Debug, Eq, PartialEq, Hash)] pub struct Tokenizer<'src, 'ctx> { src: &'src str, idx: Index, errs: &'ctx mut ErrorManager, } impl<'a, 'b> Tokenizer<'a, 'b> { pub fn new(src: &'a str, errs: &'b mut ErrorManager) -> Self { Tokenizer { src, idx: Index::default(), errs, } } } impl Tokenizer<'_, '_> { /// Get the char at `n` chars offset from the current cursor. fn next(&self, n: usize) -> Option<char> { self.src[self.idx.byte..].chars().skip(n).next() } /// Advance the cursor by the size of `ch` and update like number and column number. fn consume_char(&mut self, ch: char) { self.idx = self.idx.advance_by(ch); } /// Bump the cursor `n` chars from the input. Panics if the end of the input is reached. fn consume(&mut self, n: usize) { for _ in 0..n { self.consume_char(self.next(0).expect("Tried consuming past the end of input")); } } fn make_token(&self, start: Index, ty: Token) -> SpannedToken { SpannedToken { ty, span: Span::new(start, self.idx), } } /// Consume characters until a non-whitespace char. fn scan_whitespace(&mut self) { while self.next(0).map(char::is_whitespace).unwrap_or(false) { self.consume(1); } } fn scan_while<F>(&mut self, mut func: F) -> usize where F: FnMut(char) -> bool, { let mut scanned = 0; while self.next(0).map(|ch| func(ch)).unwrap_or(false) { self.consume(1); scanned += 1; } scanned } fn scan_while_max<F>(&mut self, max: usize, mut func: F) -> usize where F: FnMut(char) -> bool, { let mut scanned = 0; while self.next(0).map(|ch| func(ch)).unwrap_or(false) && max > scanned { self.consume(1); scanned += 1; } scanned } // TODO: is this correct? this matches `0.` as a `Float` fn scan_number(&mut self, radix: u32) -> Token { self.scan_while(|ch| ch.is_digit(radix)); match self.next(0) { Some('.') => { self.consume(1); self.scan_while(|ch| ch.is_digit(radix)); Token::Number } _ => Token::Number, } } /// Consume one char if `ch` is the same as the input stream, returning true if so. /// Otherwise, don't do anything and return false. fn eat(&mut self, ch: char) -> bool { match self.next(0) { Some(c) if c == ch => { self.consume_char(c); true } _ => false, } } fn scan_unicode_delim(&mut self, delim: char, escape_start: Index) -> bool { match self.next(0) { Some(ch) if ch == delim => { self.consume(1); true } Some(ch) => { self.errs.span_error( Span::new(self.idx, self.idx.advance_by(ch)) .error_diagnostic() .with_message("malformed unicode escape sequence") .with_annotation( Level::Note, format!( "I was looking for a `{}`, but I found `{}` instead", delim, ch ), ), ); false } None => { self.errs.span_error( Span::new(escape_start, self.idx) .error_diagnostic() .with_message("malformed unicode escape sequence") .with_annotation(Level::Note, "The file unexpectedly ended while I was parsing a unicode escape sequence!"), ); false } } } fn scan_unicode_escape(&mut self, escape_start: Index) { if !self.scan_unicode_delim('{', escape_start) { return; } self.scan_while(|ch| ch.is_digit(16)); if !self.scan_unicode_delim('}', escape_start) { return; } } fn scan_hex_escape_digit(&mut self, escape_start: Index) -> bool { let digit_start = self.idx; match self.next(0) { // This is what we want, advance Some(ch) if ch.is_digit(16) => { self.consume(1); true } Some(ch) => { self.errs.span_error( Span::new(digit_start, self.idx.advance_by(ch)) .error_diagnostic() .with_message("malformed hex escape sequence") .with_annotation( Level::Note, format!( "I was looking for a hex digit, but I found `{}` instead", ch ), ) .with_annotation( Level::Note, "`\\x` has to be followed by exactly two hex digits", ), ); false } None => { self.errs.span_error( Span::new(escape_start, self.idx) .error_diagnostic() .with_message("unterminated hex escape sequence"), ); false } } } fn scan_hex_escape(&mut self, escape_start: Index) { // Consume two hex digits. for _ in 0..2 { if !self.scan_hex_escape_digit(escape_start) { return; } } } // NOTE: this assumes that the cursor is at a number. fn scan_dec_escape(&mut self) { debug_assert!(self.next(0).expect("dec escape missing digit").is_digit(10)); self.scan_while_max(3, |ch| ch.is_digit(10)); } fn scan_escape_sequence(&mut self, escape_start: Index) { match self.next(0) { Some(ch) => match ch { // Normal escape sequence, sonsume it and move on. 'a' | 'b' | 'f' | 'n' | 'r' | 't' | 'v' | '\\' | '"' | '\'' | '\r' | '\n' => { self.consume(1); } // Unicode escape, like `\u{CODEPOINT}` 'u' => { self.consume(1); self.scan_unicode_escape(escape_start); } // Hex escape, like `\xNN` 'x' => { // consume the `x` self.consume(1); self.scan_hex_escape(escape_start); } ch if ch.is_digit(10) => { self.scan_dec_escape(); } ch => self.errs.span_error( Span::new(escape_start, self.idx) .error_diagnostic() .with_message("unknown escape code") .with_annotation( Level::Note, format!("I was looking for an escape code, but I found `{}` which is not one", ch), ), ), }, None => self.errs.span_error( Span::new(escape_start, self.idx) .error_diagnostic() .with_message("unterminated escape sequence"), ), } } // TODO: escapes // Either scan a normal char, or if the cursor is on a `\`, scan past the end of the escape sequence. We do this so // that we can have strings like "\"", because otherwise the escaped `"` would be read and the string would terminate early. fn scan_string_char(&mut self) { match self.next(0) { Some('\\') => { let escape_start = self.idx; self.consume(1); self.scan_escape_sequence(escape_start); } Some(_) => { self.consume(1); } _ => {} } } fn scan_string(&mut self, quote_char: char) { let start = self.idx; // Eat the opening string char. This isn't really needed for how we call this, since we already know that the // we have the correct opening char, but this is just for completeness. if !self.eat(quote_char) { return; } loop { match self.next(0) { // If our cursor is over the same char we opened with, then we found the end of the string. Some(ch) if ch == quote_char => break, Some(_) => self.scan_string_char(), // If we get to the end of the file while scanning a string, then we have an unterminated string. None => { self.errs.span_error( Span::new(start, self.idx).error_diagnostic().with_message( match quote_char { '"' => "unterminated double quote string".into(), '\'' => "unterminated single quote string".into(), k => format!("unterminated `{}`-delimited string", k), }, ), ); return; } } } // Consume the string terminator. We know this is the same as the opening char because the only way we break // out of the loop is by matching the start char. self.consume(1); } fn scan_raw_string(&mut self) -> usize { debug_assert!(self.next(0) == Some('[')); let start = self.idx; self.consume(1); let level = self.scan_while(|ch| ch == '='); // The two brackets plus the number of `=`s let delim_len = level + 2; if !self.eat('[') { self.errs.span_error( Span::new(start, self.idx) .error_diagnostic() .with_message("malformed long string") .with_annotation( Level::Note, "I was looking for a `[`, but I did not find one", ), ); return delim_len; } loop { match self.next(0) { // We want to find a sequence like `]==]` with a matching number of `=` as the level. Some(']') => { // consume the first `]` self.consume(1); let found = self.scan_while(|ch| ch == '='); // If the number of `=`s matches, then try to consume a `]`, otherwise just ignore the whole thing and continue scanning the string. if found == level { // Correct formatting, exit the loop. if self.next(0) == Some(']') { self.consume(1); return delim_len; } } } // Other char, scan the char/escape Some(_) => self.scan_string_char(), None => { self.errs.span_error( Span::new(start, self.idx) .error_diagnostic() .with_message(format!("unterminated {}-level long string", level)), ); return delim_len; } } } } // -- line comment // --[[ block comment ]] // NOTE: block comments cannot nest :( fn scan_comment(&mut self) { let comment_start = self.idx; match (self.next(0), self.next(1)) { (Some('-'), Some('-')) => self.consume(2), _ => return, } match (self.next(0), self.next(1)) { // This is a block comment; scan until we find `]]`. Also, it doesn't seem like block comments nest... (Some('['), Some('[')) => { self.consume(2); loop { match self.next(0) { // If the next two chars are `]]` then consume them. Some(']') => match self.next(1) { Some(']') => { self.consume(2); break; } // Just consume the `-` we matched. _ => self.consume(1), }, // If we get to the end of the file and we're still looking for the end of a block comment, // then we have an unterminated block comment. Error and break out of the loop. None => { self.errs.span_error( Span::new(comment_start, self.idx) .error_diagnostic() .with_message("unterminated block comment"), ); break; } // Advance one for every other char. _ => self.consume(1), } } } // This is a line comment; scan to the end of the line. _ => { while self.next(0).map(|ch| ch != '\n').unwrap_or(false) { self.consume(1); } } } } // The main driver function; The tokenizer advances one token with each call, skipping whitespace and comments if it needs to. pub fn scan(&mut self) -> Option<SpannedToken> { // Scan leading whitespace away, so the cursor is at a char that is *not* whitespace. self.scan_whitespace(); let start_idx = self.idx; let ch = self.next(0)?; // Match an identifier or keyword. Idents look like `<id_start> <id_continue>*` if is_ident_start(ch) { while self.next(0).map(is_ident_continue).unwrap_or(false) { self.consume(1); } // Find the actual identifier text. If the ident is a keyword, emit the matching keyword token instead. let lexeme = &self.src[start_idx.byte..self.idx.byte]; return Some( self.make_token( start_idx, Keyword::from_str(lexeme) .map(Token::Kw) .unwrap_or(Token::Ident), ), ); } // Match a number. FIXME: this might be a little touchy... if ch.is_digit(10) { if self.next(1) == Some('x') { self.consume(2); let tt = self.scan_number(16); return Some(self.make_token(start_idx, tt)); } else { let tt = self.scan_number(10); return Some(self.make_token(start_idx, tt)); } } // Consume 1 char and return the specified token macro_rules! tok1 { ($tok:ident) => {{ self.consume(1); Token::$tok }}; } // Consume a char and pick the correct token depending on the next char. If the token is 2 chars long, consume // the second char too. macro_rules! tok2 { ($single:ident, [$($ch:tt = $tok:ident),+]) => {{ self.consume(1); match self.next(0) { $(Some($ch) => { self.consume(1); Token::$tok },)+ _ => Token::$single } }}; } let tok = match ch { '+' => tok1!(Plus), '*' => tok1!(Star), '%' => tok1!(Percent), '^' => tok1!(Exp), '#' => tok1!(Hash), '&' => tok1!(BitAnd), '|' => tok1!(BitOr), ';' => tok1!(Semicolon), ',' => tok1!(Comma), '(' => tok1!(OpenParen), ')' => tok1!(CloseParen), '{' => tok1!(OpenBrace), '}' => tok1!(CloseBrace), ']' => tok1!(CloseBracket), '~' => tok2!(Tilde, ['=' = TildeEq]), '/' => tok2!(Slash, ['/' = ShashSlash]), '=' => tok2!(Eq, ['=' = EqEq]), ':' => tok2!(Colon, [':' = ColonColon]), '<' => tok2!(Lt, ['<' = LtLt, '=' = LtEq]), '>' => tok2!(Gt, ['>' = GtGt, '=' = GtEq]), '[' => match self.next(1) { Some('[') | Some('=') => { let level = self.scan_raw_string(); Token::LongString(level) } _ => { self.consume(1); Token::OpenBracket } }, // Either match a `Minus` token or a comment. '-' => match self.next(1) { // If the char after the first is also a `-` then we have some sort of comment. // Basically, it consumes `<comment> <token>` but only returns `<token>`. Note that `<token>` can be a // comment itself, so it really consumes `<comment>* <token>`. Some('-') => { self.scan_comment(); return self.scan(); } _ => { self.consume(1); Token::Minus } }, '.' => { self.consume(1); match (self.next(0), self.next(1)) { (Some('.'), Some('.')) => { self.consume(2); Token::DotDotDot } (Some('.'), _) => { self.consume(1); Token::DotDot } _ => Token::Dot, } } // Scan each type of string. '"' => { self.scan_string('"'); Token::String('"') } '\'' => { self.scan_string('\''); Token::String('\'') } ch => { self.consume(1); self.errs.span_error( Span::new(start_idx, start_idx.advance_by(ch)) .error_diagnostic() .with_message("unknown token"), ); Token::Unknown(ch) } }; Some(self.make_token(start_idx, tok)) } } fn is_in_range(ch: char, lo: char, hi: char) -> bool { ch >= lo && ch <= hi } fn is_ident_start(ch: char) -> bool { // ch.is_xid_start() || ch == '_' is_in_range(ch, 'a', 'z') || is_in_range(ch, 'A', 'Z') || ch == '_' } fn is_ident_continue(ch: char) -> bool { // ch.is_xid_continue() is_in_range(ch, 'a', 'z') || is_in_range(ch, 'A', 'Z') || is_in_range(ch, '0', '9') || ch == '_' }
//! Wrapper the CUDA API. #![allow(dead_code)] mod array; mod counter; mod error; mod executor; mod jit_daemon; mod module; mod wrapper; pub use self::array::Array; pub use self::counter::{PerfCounter, PerfCounterSet}; pub use self::error::*; pub use self::executor::*; pub use self::jit_daemon::JITDaemon; pub use self::module::{Argument, Kernel, Module}; use self::jit_daemon::DaemonSpawner; #[cfg(test)] #[cfg(feature = "real_gpu")] mod tests { use super::array; use super::*; use utils::*; /// Tries to initialize a CUDA execution context. #[test] fn test_init() { let _ = Executor::init(); } /// Tries to obtain the name of the GPU. #[test] fn test_getname() { let executor = Executor::init(); executor.device_name(); } /// Tries to compile an empty PTX module. #[test] fn test_empty_module() { let executor = Executor::init(); let _ = executor.compile_ptx(".version 3.0\n.target sm_30\n.address_size 64\n", 1); } /// Tries to compile an empty PTX kernel and execute it. #[test] fn test_empty_kernel() { let executor = Executor::init(); let module = executor.compile_ptx( ".version 3.0\n.target sm_30\n.address_size 64\n .entry empty_fun() { ret; }", 1, ); let kernel = module.kernel("empty_fun"); let _ = kernel.execute(&[1, 1, 1], &[1, 1, 1], &[]); } /// Tries to allocate an array. #[test] fn test_array_allocation() { let executor = Executor::init(); let _: Array<f32> = executor.allocate_array(1024); } /// Allocates two identical arrays and ensures they are equal. #[test] fn test_array_copy() { let executor = Executor::init(); let src = executor.allocate_array::<f32>(1024); let dst = src.clone(); assert!(array::compare_f32(&src, &dst) < 1e-5); } /// Alocates a random array and copies using a PTX kernel. #[test] fn test_array_soft_copy() { let block_dim: u32 = 16; let executor = Executor::init(); let mut src = executor.allocate_array::<f32>(block_dim as usize); let dst = executor.allocate_array::<f32>(block_dim as usize); array::randomize_f32(&mut src); let module = executor.compile_ptx( ".version 3.0\n.target sm_30\n.address_size 64\n .entry copy( .param.u64.ptr.global .align 16 src, .param.u64.ptr.global .align 16 dst ) { .reg.u64 %rd<4>; .reg.u32 %r<1>; .reg.f32 %f; ld.param.u64 %rd0, [src]; ld.param.u64 %rd1, [dst]; mov.u32 %r0, %ctaid.x; mad.wide.u32 %rd2, %r0, 4, %rd0; mad.wide.u32 %rd3, %r0, 4, %rd1; ld.global.f32 %f, [%rd2]; st.global.f32 [%rd3], %f; ret; }", 1, ); let kernel = module.kernel("copy"); unwrap!(kernel.execute(&[block_dim, 1, 1], &[1, 1, 1], &[&src, &dst])); assert!(array::compare_f32(&src, &dst) < 1e-5); } }
//! Response body types. // TODO: support for streaming response bodies use prelude::*; /// Response body #[derive(Debug)] pub struct Body(pub(super) Vec<u8>); impl Body { /// Buffer the response body into a `Vec<u8>` and return it pub fn into_vec(self) -> Vec<u8> { self.0 } }