text
stringlengths
8
4.13M
use crate::io::BufMut; use crate::postgres::protocol::{StatementId, Write}; use byteorder::{ByteOrder, NetworkEndian}; pub enum Describe<'a> { Statement(StatementId), Portal(&'a str), } impl Write for Describe<'_> { fn write(&self, buf: &mut Vec<u8>) { buf.push(b'D'); let pos = buf.len(); buf.put_i32::<NetworkEndian>(0); // skip over len match self { Describe::Statement(id) => { buf.push(b'S'); id.write(buf); } Describe::Portal(name) => { buf.push(b'P'); buf.put_str_nul(name); } }; // Write-back the len to the beginning of this frame let len = buf.len() - pos; NetworkEndian::write_i32(&mut buf[pos..], len as i32); } } #[cfg(test)] mod test { use super::{Describe, Write}; use crate::postgres::protocol::StatementId; #[test] fn it_writes_describe_portal() { let mut buf = Vec::new(); let m = Describe::Portal("__rbatis_core_p_1"); m.write(&mut buf); assert_eq!(buf, b"D\0\0\0\x10P__rbatis_core_p_1\0"); } #[test] fn it_writes_describe_statement() { let mut buf = Vec::new(); let m = Describe::Statement(StatementId(1)); m.write(&mut buf); assert_eq!(buf, b"D\x00\x00\x00\x18S__rbatis_core_statement_1\x00"); } }
use std::io::{stdin}; fn factorial(n: i32) -> i32 { if n <= 1 { return 1; } else { return n * factorial(n - 1); } } fn main() { println!("Enter a number for factorial:"); let mut input = String::new(); stdin().read_line(&mut input) .ok() .expect("Couldn't read line"); let n = input.trim().parse::<i32>().ok().expect("Couldn't uwrap"); println!("factorial was {}", factorial(n)); }
use druid::{AppLauncher, WindowDesc}; use std::error::Error; mod controller; mod state; mod ui; mod widgets; fn main() -> Result<(), Box<dyn Error>> { let window = WindowDesc::new(ui::tracker) .title("Zeitig") .window_size((300.0, 400.0)); use state::backend::Backend; let mut backend = state::backend::Sqlite::new(state::paths::data_file())?; backend.setup()?; let content = backend.load_content()?; let history = backend.load_history(&content)?; backend.close()?; let state = state::AppState { content, history, setup: state::Setup::default(), active: None, }; AppLauncher::with_window(window) .use_simple_logger() .launch(state)?; Ok(()) }
/* * @lc app=leetcode.cn id=257 lang=rust * * [257] 二叉树的所有路径 * * https://leetcode-cn.com/problems/binary-tree-paths/description/ * * algorithms * Easy (60.96%) * Likes: 193 * Dislikes: 0 * Total Accepted: 22.8K * Total Submissions: 36.9K * Testcase Example: '[1,2,3,null,5]' * * 给定一个二叉树,返回所有从根节点到叶子节点的路径。 * * 说明: 叶子节点是指没有子节点的节点。 * * 示例: * * 输入: * * ⁠ 1 * ⁠/ \ * 2 3 * ⁠\ * ⁠ 5 * * 输出: ["1->2->5", "1->3"] * * 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3 * */ // @lc code=start // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn binary_tree_paths(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<String> { let mut container: Vec<String> = vec![]; if let Some(r) = root { Self::get_all_path(r, &mut vec![], &mut container) } else { container } } fn get_all_path( node: Rc<RefCell<TreeNode>>, path: &mut Vec<String>, list: &mut Vec<String>, ) -> Vec<String> { path.push(node.borrow().val.to_string()); match (node.borrow().left.clone(), node.borrow().right.clone()) { (Some(l), Some(r)) => Self::get_all_path( l, &mut path.clone(), &mut Self::get_all_path(r, &mut path.clone(), list), ), (Some(l), None) => Self::get_all_path(l, &mut path.clone(), list), (None, Some(r)) => Self::get_all_path(r, &mut path.clone(), list), _ => { list.push(path.join("->")); list.to_vec() } } } } // @lc code=end
use crate::{ error::CreationError, export::Export, import::IsExport, memory::dynamic::DYNAMIC_GUARD_SIZE, memory::static_::{SAFE_STATIC_GUARD_SIZE, SAFE_STATIC_HEAP_SIZE}, types::{MemoryDescriptor, ValueType}, units::Pages, vm, }; use std::{cell::RefCell, fmt, mem, ptr, rc::Rc, slice}; pub use self::dynamic::DynamicMemory; pub use self::static_::{SharedStaticMemory, StaticMemory}; mod dynamic; mod static_; pub struct Memory { desc: MemoryDescriptor, storage: Rc<RefCell<(MemoryStorage, Box<vm::LocalMemory>)>>, } impl Memory { /// Create a new `Memory` from a [`MemoryDescriptor`] /// /// [`MemoryDescriptor`]: struct.MemoryDescriptor.html /// /// Usage: /// /// ``` /// # use wasmer_runtime_core::types::MemoryDescriptor; /// # use wasmer_runtime_core::memory::Memory; /// # use wasmer_runtime_core::error::Result; /// # use wasmer_runtime_core::units::Pages; /// # fn create_memory() -> Result<()> { /// let descriptor = MemoryDescriptor { /// minimum: Pages(10), /// maximum: None, /// shared: false, /// }; /// /// let memory = Memory::new(descriptor)?; /// # Ok(()) /// # } /// ``` pub fn new(desc: MemoryDescriptor) -> Result<Self, CreationError> { let mut vm_local_memory = Box::new(vm::LocalMemory { base: ptr::null_mut(), bound: 0, memory: ptr::null_mut(), }); let memory_storage = match desc.memory_type() { MemoryType::Dynamic => { MemoryStorage::Dynamic(DynamicMemory::new(desc, &mut vm_local_memory)?) } MemoryType::Static => { MemoryStorage::Static(StaticMemory::new(desc, &mut vm_local_memory)?) } MemoryType::SharedStatic => unimplemented!("shared memories are not yet implemented"), }; Ok(Memory { desc, storage: Rc::new(RefCell::new((memory_storage, vm_local_memory))), }) } /// Return the [`MemoryDescriptor`] that this memory /// was created with. /// /// [`MemoryDescriptor`]: struct.MemoryDescriptor.html pub fn descriptor(&self) -> MemoryDescriptor { self.desc } /// Grow this memory by the specfied number of pages. pub fn grow(&mut self, delta: Pages) -> Option<Pages> { match &mut *self.storage.borrow_mut() { (MemoryStorage::Dynamic(ref mut dynamic_memory), ref mut local) => { dynamic_memory.grow(delta, local) } (MemoryStorage::Static(ref mut static_memory), ref mut local) => { static_memory.grow(delta, local) } (MemoryStorage::SharedStatic(_), _) => unimplemented!(), } } /// The size, in wasm pages, of this memory. pub fn size(&self) -> Pages { match &*self.storage.borrow() { (MemoryStorage::Dynamic(ref dynamic_memory), _) => dynamic_memory.size(), (MemoryStorage::Static(ref static_memory), _) => static_memory.size(), (MemoryStorage::SharedStatic(_), _) => unimplemented!(), } } pub fn read<T: ValueType>(&self, offset: u32) -> Result<T, ()> { let offset = offset as usize; let borrow_ref = self.storage.borrow(); let memory_storage = &borrow_ref.0; let mem_slice = match memory_storage { MemoryStorage::Dynamic(ref dynamic_memory) => dynamic_memory.as_slice(), MemoryStorage::Static(ref static_memory) => static_memory.as_slice(), MemoryStorage::SharedStatic(_) => panic!("cannot slice a shared memory"), }; if offset + mem::size_of::<T>() <= mem_slice.len() { T::from_le(&mem_slice[offset..]).map_err(|_| ()) } else { Err(()) } } pub fn write<T: ValueType>(&self, offset: u32, value: T) -> Result<(), ()> { let offset = offset as usize; let mut borrow_ref = self.storage.borrow_mut(); let memory_storage = &mut borrow_ref.0; let mem_slice = match memory_storage { MemoryStorage::Dynamic(ref mut dynamic_memory) => dynamic_memory.as_slice_mut(), MemoryStorage::Static(ref mut static_memory) => static_memory.as_slice_mut(), MemoryStorage::SharedStatic(_) => panic!("cannot slice a shared memory"), }; if offset + mem::size_of::<T>() <= mem_slice.len() { value.into_le(&mut mem_slice[offset..]); Ok(()) } else { Err(()) } } pub fn read_many<T: ValueType>(&self, offset: u32, count: usize) -> Result<Vec<T>, ()> { let offset = offset as usize; let borrow_ref = self.storage.borrow(); let memory_storage = &borrow_ref.0; let mem_slice = match memory_storage { MemoryStorage::Dynamic(ref dynamic_memory) => dynamic_memory.as_slice(), MemoryStorage::Static(ref static_memory) => static_memory.as_slice(), MemoryStorage::SharedStatic(_) => panic!("cannot slice a shared memory"), }; let bytes_size = count * mem::size_of::<T>(); if offset + bytes_size <= mem_slice.len() { let buffer = &mem_slice[offset..offset + bytes_size]; let value_type_buffer = unsafe { slice::from_raw_parts( buffer.as_ptr() as *const T, buffer.len() / mem::size_of::<T>(), ) }; Ok(value_type_buffer.to_vec()) } else { Err(()) } } pub fn write_many<T: ValueType>(&self, offset: u32, values: &[T]) -> Result<(), ()> { let offset = offset as usize; let mut borrow_ref = self.storage.borrow_mut(); let memory_storage = &mut borrow_ref.0; let mem_slice = match memory_storage { MemoryStorage::Dynamic(ref mut dynamic_memory) => dynamic_memory.as_slice_mut(), MemoryStorage::Static(ref mut static_memory) => static_memory.as_slice_mut(), MemoryStorage::SharedStatic(_) => panic!("cannot slice a shared memory"), }; let bytes_size = values.len() * mem::size_of::<T>(); if offset + bytes_size <= mem_slice.len() { let u8_buffer = unsafe { slice::from_raw_parts(values.as_ptr() as *const u8, bytes_size) }; mem_slice[offset..offset + bytes_size].copy_from_slice(u8_buffer); Ok(()) } else { Err(()) } } pub fn direct_access<T: ValueType, F, R>(&self, f: F) -> R where F: FnOnce(&[T]) -> R, { let borrow_ref = self.storage.borrow(); let memory_storage = &borrow_ref.0; let mem_slice = match memory_storage { MemoryStorage::Dynamic(ref dynamic_memory) => dynamic_memory.as_slice(), MemoryStorage::Static(ref static_memory) => static_memory.as_slice(), MemoryStorage::SharedStatic(_) => panic!("cannot slice a shared memory"), }; let t_buffer = unsafe { slice::from_raw_parts( mem_slice.as_ptr() as *const T, mem_slice.len() / mem::size_of::<T>(), ) }; f(t_buffer) } pub fn direct_access_mut<T: ValueType, F, R>(&self, f: F) -> R where F: FnOnce(&mut [T]) -> R, { let mut borrow_ref = self.storage.borrow_mut(); let memory_storage = &mut borrow_ref.0; let mem_slice = match memory_storage { MemoryStorage::Dynamic(ref mut dynamic_memory) => dynamic_memory.as_slice_mut(), MemoryStorage::Static(ref mut static_memory) => static_memory.as_slice_mut(), MemoryStorage::SharedStatic(_) => panic!("cannot slice a shared memory"), }; let t_buffer = unsafe { slice::from_raw_parts_mut( mem_slice.as_mut_ptr() as *mut T, mem_slice.len() / mem::size_of::<T>(), ) }; f(t_buffer) } pub(crate) fn vm_local_memory(&mut self) -> *mut vm::LocalMemory { &mut *self.storage.borrow_mut().1 } } impl IsExport for Memory { fn to_export(&mut self) -> Export { Export::Memory(self.clone()) } } impl Clone for Memory { fn clone(&self) -> Self { Self { desc: self.desc, storage: Rc::clone(&self.storage), } } } pub enum MemoryStorage { Dynamic(Box<DynamicMemory>), Static(Box<StaticMemory>), SharedStatic(Box<SharedStaticMemory>), } impl MemoryStorage { pub fn to_type(&self) -> MemoryType { match self { MemoryStorage::Dynamic(_) => MemoryType::Dynamic, MemoryStorage::Static(_) => MemoryType::Static, MemoryStorage::SharedStatic(_) => MemoryType::SharedStatic, } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MemoryType { Dynamic, Static, SharedStatic, } impl MemoryType { #[doc(hidden)] pub fn guard_size(self) -> u64 { match self { MemoryType::Dynamic => DYNAMIC_GUARD_SIZE as u64, MemoryType::Static => SAFE_STATIC_GUARD_SIZE as u64, MemoryType::SharedStatic => SAFE_STATIC_GUARD_SIZE as u64, } } #[doc(hidden)] pub fn bounds(self) -> Option<u64> { match self { MemoryType::Dynamic => None, MemoryType::Static => Some(SAFE_STATIC_HEAP_SIZE as u64), MemoryType::SharedStatic => Some(SAFE_STATIC_HEAP_SIZE as u64), } } } impl fmt::Debug for Memory { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Memory") .field("desc", &self.desc) .field("size", &self.size()) .finish() } }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::view::{ViewAssistantPtr, ViewController, ViewKey}; use failure::{bail, Error, ResultExt}; use fidl::endpoints::{RequestStream, ServiceMarker}; use fidl_fuchsia_ui_app as viewsv2; use fidl_fuchsia_ui_gfx as gfx; use fidl_fuchsia_ui_scenic::{ScenicMarker, ScenicProxy}; use fidl_fuchsia_ui_viewsv1::{ ViewManagerMarker, ViewManagerProxy, ViewProviderMarker, ViewProviderRequest::CreateView, ViewProviderRequestStream, }; use fuchsia_app::{self as component, client::connect_to_service, server::FdioServer}; use fuchsia_async as fasync; use fuchsia_scenic::SessionPtr; use fuchsia_zircon as zx; use futures::{TryFutureExt, TryStreamExt}; use std::{ any::Any, cell::RefCell, collections::BTreeMap, sync::atomic::{AtomicBool, Ordering}, }; /// Trait that a mod author must implement. Currently responsible for creating /// a view assistant when the Fuchsia view framework requests that the mod create /// a view. pub trait AppAssistant { /// This method is responsible for setting up the AppAssistant implementation. /// _It's not clear if this is going to so useful, as anything that isn't /// initialized in the creation of the structure implementing AppAssistant /// is going to have to be represented as an `Option`, which is awkward._ fn setup(&mut self) -> Result<(), Error>; /// Called when the Fuchsia view system requests that a view be created. fn create_view_assistant(&mut self, session: &SessionPtr) -> Result<ViewAssistantPtr, Error>; /// Return the list of names of services this app wants to provide fn outgoing_services_names(&self) -> Vec<&'static str> { Vec::new() } /// Handle a request to connect to a service provided by this app fn handle_service_connection_request( &mut self, _service_name: &str, _channel: fasync::Channel, ) -> Result<(), Error> { bail!("handle_service_connection_request not implemented") } } pub type AppAssistantPtr = Box<dyn AppAssistant>; /// Struct that implements module-wide responsibilties, currently limited /// to creating views on request. pub struct App { pub(crate) scenic: ScenicProxy, pub(crate) view_manager: ViewManagerProxy, view_controllers: BTreeMap<ViewKey, ViewController>, next_key: ViewKey, assistant: Option<AppAssistantPtr>, } /// Reference to the singleton app. _This type is likely to change in the future so /// using this type alias might make for easier forward migration._ type AppPtr = RefCell<App>; static DID_APP_INIT: AtomicBool = AtomicBool::new(false); thread_local! { /// Singleton reference to the running application static APP: AppPtr = { if DID_APP_INIT.fetch_or(true, Ordering::SeqCst) { panic!("App::with() may only be called on the first thread that calls App::run()"); } App::new().expect("Failed to create app") }; } impl App { fn new() -> Result<AppPtr, Error> { let scenic = connect_to_service::<ScenicMarker>()?; let view_manager = connect_to_service::<ViewManagerMarker>()?; Ok(RefCell::new(App { scenic, view_manager, view_controllers: BTreeMap::new(), next_key: 0, assistant: None, })) } /// Starts an application based on Carnelian. The `assistant` parameter will /// be used to create new views when asked to do so by the Fuchsia view system. pub fn run(assistant: Box<AppAssistant>) -> Result<(), Error> { let mut executor = fasync::Executor::new().context("Error creating executor")?; let fut = App::with(|app| { app.set_assistant(assistant); let fut = App::start_services(app); app.assistant.as_mut().unwrap().setup()?; fut })?; executor.run_singlethreaded(fut)?; Ok(()) } /// Function to get a mutable reference to the singleton app struct, useful /// in callbacks. pub fn with<F, R>(f: F) -> R where F: FnOnce(&mut App) -> R, { APP.with(|app| { let mut app_ref = app.borrow_mut(); f(&mut app_ref) }) } fn set_assistant(&mut self, assistant: AppAssistantPtr) { self.assistant = Some(assistant); } /// Function to get a mutable reference to a view controller for a particular /// view, by view key. It is a fatal error to pass a view key that doesn't /// have a corresponding view controller. pub fn with_view<F>(&mut self, key: ViewKey, f: F) where F: FnOnce(&mut ViewController), { if let Some(view) = self.view_controllers.get_mut(&key) { f(view) } else { panic!("Could not find view controller for {}", key); } } /// Send a message to a specific view controller. Messages not handled by the ViewController /// will be forwarded to the `ViewControllerAssistant`. pub fn send_message(&mut self, target: ViewKey, msg: &Any) { if let Some(view) = self.view_controllers.get_mut(&target) { view.send_message(msg); } } pub(crate) fn create_view_assistant( &mut self, session: &SessionPtr, ) -> Result<ViewAssistantPtr, Error> { Ok(self.assistant.as_mut().unwrap().create_view_assistant(session)?) } fn create_view(&mut self, view_token: gfx::ExportToken) -> Result<(), Error> { let view_controller = ViewController::new(self, view_token, self.next_key)?; self.view_controllers.insert(self.next_key, view_controller); self.next_key += 1; Ok(()) } fn spawn_view_provider_server(chan: fasync::Channel) { fasync::spawn_local( ViewProviderRequestStream::from_channel(chan) .try_for_each(move |req| { let CreateView { view_owner, .. } = req; let view_token = gfx::ExportToken { value: zx::EventPair::from(zx::Handle::from(view_owner.into_channel())), }; App::with(|app| { app.create_view(view_token) .unwrap_or_else(|e| eprintln!("create_view error: {:?}", e)); }); futures::future::ready(Ok(())) }) .unwrap_or_else(|e| eprintln!("error running view_provider server: {:?}", e)), ) } fn spawn_v2_view_provider_server(chan: fasync::Channel) { fasync::spawn_local( viewsv2::ViewProviderRequestStream::from_channel(chan) .try_for_each(move |req| { let viewsv2::ViewProviderRequest::CreateView { token, .. } = req; let view_token = gfx::ExportToken { value: token }; App::with(|app| { app.create_view(view_token) .unwrap_or_else(|e| eprintln!("create_view2 error: {:?}", e)); }); futures::future::ready(Ok(())) }) .unwrap_or_else(|e| eprintln!("error running V2 view_provider server: {:?}", e)), ) } fn pass_connection_to_assistant(channel: fasync::Channel, service_name: &'static str) { App::with(|app| { app.assistant .as_mut() .unwrap() .handle_service_connection_request(service_name, channel) .unwrap_or_else(|e| eprintln!("error running {} server: {:?}", service_name, e)); }); } fn start_services(app: &mut App) -> Result<FdioServer, Error> { let outgoing_services_names = app.assistant.as_ref().unwrap().outgoing_services_names(); let services_server = component::server::ServicesServer::new(); let mut services_server = services_server .add_service((ViewProviderMarker::NAME, move |channel| { Self::spawn_view_provider_server(channel); })) .add_service((viewsv2::ViewProviderMarker::NAME, move |channel| { Self::spawn_v2_view_provider_server(channel); })); for name in outgoing_services_names { services_server = services_server.add_service((name, move |channel| { Self::pass_connection_to_assistant(channel, name); })); } Ok(services_server.start()?) } }
#![no_std] #![no_main] use wio_terminal_probe_run; use wio_terminal as wio; use wio::entry; #[entry] fn main() -> ! { defmt::info!("Hello, world!"); wio_terminal_probe_run::exit() }
//! Types to combine multiple sensors and pools together //! //! If we have two tuples of compatible sensors and pools: //! * `s1` and `p1` //! * `s2` and `p2` //! //! Then we can combine them into a single sensor and pool as follows: //! ``` //! use fuzzcheck::sensors_and_pools::{AndSensor, AndPool, DifferentObservations}; //! use fuzzcheck::PoolExt; //! # use fuzzcheck::sensors_and_pools::{NoopSensor, UniqueValuesPool}; //! # let (s1, s2) = (NoopSensor, NoopSensor); //! # let (p1, p2) = (UniqueValuesPool::<u8>::new("a", 0), UniqueValuesPool::<bool>::new("b", 0)); //! let s = AndSensor(s1, s2); //! let p = p1.and(p2, Some(2.0), DifferentObservations); //! // 1.0 overrides the weight of `p2`, which influences how often the fuzzer will choose a test case //! // from that pool. By default, all pools have a weight of 1.0. Therefore, in this case, asssuming //! // `p1` has a weight of 1.0, then test cases will chosen from `p2` as often as `p1`. We can keep //! // `p2`s original weight using: //! # let (p1, p2) = (UniqueValuesPool::<u8>::new("a", 0), UniqueValuesPool::<bool>::new("b", 0)); //! let p = p1.and(p2, None, DifferentObservations); //! // Note that the weight of `p` is the weight of `p1` plus the weight of `p2`. //! ``` //! At every iteration of the fuzz test, both pools have a chance to provide a test case to mutate. //! After the test function is run, both sensors will collect data and feed them to their respective pool. //! //! It is also possible to use two pools processing the observations of a single sensor. This is done //! as follows: //! ``` //! use fuzzcheck::sensors_and_pools::{AndSensor, AndPool, SameObservations}; //! use fuzzcheck::PoolExt; //! # use fuzzcheck::sensors_and_pools::{NoopSensor, UniqueValuesPool}; //! # let s = NoopSensor; //! # let (p1, p2) = (UniqueValuesPool::<u8>::new("a", 0), UniqueValuesPool::<u8>::new("b", 0)); //! let p = p1.and(p2, Some(2.0), SameObservations); //! // if both `p1` and `p2` are compatible with the observations from sensor `s`, //! // then (s, p) is a valid combination of sensor and pool //! ``` use std::fmt::Display; use std::marker::PhantomData; use std::path::PathBuf; use crate::traits::{CompatibleWithObservations, CorpusDelta, Pool, SaveToStatsFolder, Sensor, SensorAndPool, Stats}; use crate::{CSVField, PoolStorageIndex, ToCSV}; /// Marker type used by [`AndPool`] to signal that all sub-pools are compatible with the same observations. pub struct SameObservations; /// Marker type used by [`AndPool`] to signal that each sub-pool works is compatible with different observations. pub struct DifferentObservations; /// A pool that combines two pools /// /// A convenient way to create an `AndPool` is to use [`p1.and(p2, ..)`](crate::PoolExt::and), but you /// are free to use [`AndPool::new`](AndPool::new) as well. /// /// If the two pools act on the same observations , then the `ObservationsMarker` generic type /// parameter should be [`SameObservations`]. However, if they act on different observations, /// then this type parameter should be [`DifferentObservations`]. This will influence what /// observations the `AndPool` is [compatible with](crate::CompatibleWithObservations). /// /// If both `P1` and `P2` are [`CompatibleWithObservations<O>`], then /// `AndPool<P1, P2, SameObservations>` will be `CompatibleWithObservations<O>` as well. /// /// If `P1` is [`CompatibleWithObservations<O1>`] and `P2` is [`CompatibleWithObservations<O2>`], then /// `AndPool<P1, P2, DifferentObservations>` will be `CompatibleWithObservations<(O1, O2)>`. /// /// When the `AndPool` is [asked to provide a test case](crate::Pool::get_random_index), it will /// choose between `p1` and `p2` randomly based on their weights, given by `self.p1_weight` and `self.p2_weight`, /// and based on how recently `p1` or `p2` made some progress. Pools that make progress will be prefered /// over pools that do not. pub struct AndPool<P1, P2, ObservationsMarker> where P1: Pool, P2: Pool, { pub p1: P1, pub p2: P2, pub p1_weight: f64, pub p2_weight: f64, p1_number_times_chosen_since_last_progress: usize, p2_number_times_chosen_since_last_progress: usize, rng: fastrand::Rng, _phantom: PhantomData<ObservationsMarker>, } impl<P1, P2, ObservationsMarker> AndPool<P1, P2, ObservationsMarker> where P1: Pool, P2: Pool, { #[no_coverage] pub fn new(p1: P1, p2: P2, p1_weight: f64, p2_weight: f64) -> Self { Self { p1, p2, p1_weight, p2_weight, p1_number_times_chosen_since_last_progress: 1, p2_number_times_chosen_since_last_progress: 1, rng: fastrand::Rng::new(), _phantom: PhantomData, } } } impl<P1, P2, ObservationsMarker> AndPool<P1, P2, ObservationsMarker> where P1: Pool, P2: Pool, { fn p1_weight(&self) -> f64 { self.p1_weight / self.p1_number_times_chosen_since_last_progress as f64 } fn p2_weight(&self) -> f64 { self.p2_weight / self.p2_number_times_chosen_since_last_progress as f64 } } impl<P1, P2, ObservationsMarker> Pool for AndPool<P1, P2, ObservationsMarker> where P1: Pool, P2: Pool, { type Stats = AndPoolStats<P1::Stats, P2::Stats>; #[no_coverage] fn stats(&self) -> Self::Stats { AndPoolStats(self.p1.stats(), self.p2.stats()) } #[no_coverage] fn get_random_index(&mut self) -> Option<PoolStorageIndex> { let choice = self.rng.f64() * self.weight(); if choice <= self.p1_weight() { if let Some(idx) = self.p1.get_random_index() { self.p1_number_times_chosen_since_last_progress += 1; Some(idx) } else { self.p2_number_times_chosen_since_last_progress += 1; self.p2.get_random_index() } } else if let Some(idx) = self.p2.get_random_index() { self.p2_number_times_chosen_since_last_progress += 1; Some(idx) } else { self.p1_number_times_chosen_since_last_progress += 1; self.p1.get_random_index() } } fn weight(&self) -> f64 { self.p1_weight() + self.p2_weight() } } impl<P1, P2, ObservationsMarker> SaveToStatsFolder for AndPool<P1, P2, ObservationsMarker> where P1: Pool, P2: Pool, { #[no_coverage] fn save_to_stats_folder(&self) -> Vec<(PathBuf, Vec<u8>)> { let mut x = self.p1.save_to_stats_folder(); x.extend(self.p2.save_to_stats_folder()); x } } /// A sensor that combines two sensors /// /// The [`observations`](crate::Sensor::Observations) from this sensor are the combination /// of the observations of both `S1` and `S2`. /// So `AndSensor<S1, S2>` implements `Sensor<Observations = (S1::Observations, S2::Observations)>`. /// /// To create a pool that is compatible with an `AndSensor`, use an [`AndPool`] with the [`DifferentObservations`] /// marker type. pub struct AndSensor<S1, S2>(pub S1, pub S2) where S1: Sensor, S2: Sensor; impl<S1, S2> Sensor for AndSensor<S1, S2> where S1: Sensor, S2: Sensor, { type Observations = (S1::Observations, S2::Observations); #[no_coverage] fn start_recording(&mut self) { self.0.start_recording(); self.1.start_recording(); } #[no_coverage] fn stop_recording(&mut self) { self.0.stop_recording(); self.1.stop_recording(); } #[no_coverage] fn get_observations(&mut self) -> Self::Observations { (self.0.get_observations(), self.1.get_observations()) } } impl<S1, S2> SaveToStatsFolder for AndSensor<S1, S2> where S1: Sensor, S2: Sensor, { #[no_coverage] fn save_to_stats_folder(&self) -> Vec<(PathBuf, Vec<u8>)> { let mut x = self.0.save_to_stats_folder(); x.extend(self.1.save_to_stats_folder()); x } } /// The statistics of an [AndPool] #[derive(Clone)] pub struct AndPoolStats<S1: Display, S2: Display>(pub S1, pub S2); impl<S1: Display, S2: Display> Display for AndPoolStats<S1, S2> { #[no_coverage] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{} {}", self.0, self.1) } } impl<S1: Display, S2: Display> Stats for AndPoolStats<S1, S2> where S1: Stats, S2: Stats, { } impl<O1, O2, P1, P2> CompatibleWithObservations<(O1, O2)> for AndPool<P1, P2, DifferentObservations> where P1: Pool, P2: Pool, P1: CompatibleWithObservations<O1>, P2: CompatibleWithObservations<O2>, { #[no_coverage] fn process(&mut self, input_id: PoolStorageIndex, observations: &(O1, O2), complexity: f64) -> Vec<CorpusDelta> { let AndPool { p1, p2, p1_number_times_chosen_since_last_progress, p2_number_times_chosen_since_last_progress, .. } = self; let deltas_1 = p1.process(input_id, &observations.0, complexity); if !deltas_1.is_empty() { *p1_number_times_chosen_since_last_progress = 1; } let deltas_2 = p2.process(input_id, &observations.1, complexity); if !deltas_2.is_empty() { *p2_number_times_chosen_since_last_progress = 1; } let mut deltas = deltas_1; deltas.extend(deltas_2); deltas } } impl<P1, P2, O> CompatibleWithObservations<O> for AndPool<P1, P2, SameObservations> where P1: CompatibleWithObservations<O>, P2: CompatibleWithObservations<O>, { #[no_coverage] fn process(&mut self, input_id: PoolStorageIndex, observations: &O, complexity: f64) -> Vec<CorpusDelta> { let AndPool { p1, p2, p1_number_times_chosen_since_last_progress, p2_number_times_chosen_since_last_progress, .. } = self; let deltas_1 = p1.process(input_id, observations, complexity); if !deltas_1.is_empty() { *p1_number_times_chosen_since_last_progress = 1; } let deltas_2 = p2.process(input_id, observations, complexity); if !deltas_2.is_empty() { *p2_number_times_chosen_since_last_progress = 1; } let mut deltas = deltas_1; deltas.extend(deltas_2); deltas } } impl<S1, S2> ToCSV for AndPoolStats<S1, S2> where S1: Display, S2: Display, S1: ToCSV, S2: ToCSV, { #[no_coverage] fn csv_headers(&self) -> Vec<CSVField> { let mut h = self.0.csv_headers(); h.extend(self.1.csv_headers()); h } #[no_coverage] fn to_csv_record(&self) -> Vec<CSVField> { let mut h = self.0.to_csv_record(); h.extend(self.1.to_csv_record()); h } } /// Combines two [`SensorAndPool`](crate::SensorAndPool) trait objects into one. /// /// You probably won't need to use this type directly because the /// [`SensorAndPool`](crate::SensorAndPool) trait is mainly used by fuzzcheck itself /// and not its users. Instead, it is more likely that you are working with types implementing /// [`Sensor`](crate::Sensor) and [`Pool`](crate::Pool). If that is the case, then you will /// want to look at [`AndSensor`] and [`AndPool`] (as well as the convenience method to /// create an `AndPool`: [`p1.and(p2, ..)`](crate::PoolExt::and)). pub struct AndSensorAndPool { sap1: Box<dyn SensorAndPool>, sap2: Box<dyn SensorAndPool>, sap1_weight: f64, sap2_weight: f64, sap1_number_times_chosen_since_last_progress: usize, sap2_number_times_chosen_since_last_progress: usize, rng: fastrand::Rng, } impl AndSensorAndPool { #[no_coverage] pub fn new(sap1: Box<dyn SensorAndPool>, sap2: Box<dyn SensorAndPool>, sap1_weight: f64, sap2_weight: f64) -> Self { Self { sap1, sap2, sap1_weight, sap2_weight, sap1_number_times_chosen_since_last_progress: 1, sap2_number_times_chosen_since_last_progress: 1, rng: fastrand::Rng::new(), } } } impl SaveToStatsFolder for AndSensorAndPool { #[no_coverage] fn save_to_stats_folder(&self) -> Vec<(PathBuf, Vec<u8>)> { let mut x = self.sap1.save_to_stats_folder(); x.extend(self.sap2.save_to_stats_folder()); x } } impl SensorAndPool for AndSensorAndPool { #[no_coverage] fn stats(&self) -> Box<dyn crate::traits::Stats> { Box::new(AndPoolStats(self.sap1.stats(), self.sap2.stats())) } #[no_coverage] fn start_recording(&mut self) { self.sap1.start_recording(); self.sap2.start_recording(); } #[no_coverage] fn stop_recording(&mut self) { self.sap1.stop_recording(); self.sap2.stop_recording(); } #[no_coverage] fn process(&mut self, input_id: PoolStorageIndex, cplx: f64) -> Vec<CorpusDelta> { let AndSensorAndPool { sap1, sap2, sap1_number_times_chosen_since_last_progress, sap2_number_times_chosen_since_last_progress, .. } = self; let deltas_1 = sap1.process(input_id, cplx); if !deltas_1.is_empty() { *sap1_number_times_chosen_since_last_progress = 1; } let deltas_2 = sap2.process(input_id, cplx); if !deltas_2.is_empty() { *sap2_number_times_chosen_since_last_progress = 1; } let mut deltas = deltas_1; deltas.extend(deltas_2); deltas } #[no_coverage] fn get_random_index(&mut self) -> Option<PoolStorageIndex> { let sum_weight = self.sap1_weight + self.sap2_weight; if self.rng.f64() <= sum_weight { if let Some(idx) = self.sap1.get_random_index() { self.sap1_number_times_chosen_since_last_progress += 1; Some(idx) } else { self.sap2_number_times_chosen_since_last_progress += 1; self.sap2.get_random_index() } } else if let Some(idx) = self.sap2.get_random_index() { self.sap2_number_times_chosen_since_last_progress += 1; Some(idx) } else { self.sap1_number_times_chosen_since_last_progress += 1; self.sap1.get_random_index() } } }
#![feature(test)] extern crate test; #[cfg(test)] mod tests { use test::Bencher; use P34; use P37; #[bench] pub fn bench_p34_totient(b: &mut Bencher) { b.iter(|| P34::totient(123456)); } #[bench] pub fn bench_p37_totient(b: &mut Bencher) { b.iter(|| P37::totient(123456)); } }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use common_catalog::table::Table; use common_catalog::table_context::TableContext; use common_exception::Result; use common_expression::types::BooleanType; use common_expression::types::StringType; use common_expression::utils::FromData; use common_expression::DataBlock; use common_expression::TableDataType; use common_expression::TableField; use common_expression::TableSchemaRefExt; use common_functions::aggregates::AggregateFunctionFactory; use common_functions::BUILTIN_FUNCTIONS; use common_meta_app::principal::UserDefinedFunction; use common_meta_app::schema::TableIdent; use common_meta_app::schema::TableInfo; use common_meta_app::schema::TableMeta; use common_users::UserApiProvider; use crate::table::AsyncOneBlockSystemTable; use crate::table::AsyncSystemTable; pub struct FunctionsTable { table_info: TableInfo, } #[async_trait::async_trait] impl AsyncSystemTable for FunctionsTable { const NAME: &'static str = "system.functions"; fn get_table_info(&self) -> &TableInfo { &self.table_info } async fn get_full_data(&self, ctx: Arc<dyn TableContext>) -> Result<DataBlock> { // TODO(andylokandy): add rewritable function names, e.g. database() let func_names = BUILTIN_FUNCTIONS.registered_names(); let aggregate_function_factory = AggregateFunctionFactory::instance(); let aggr_func_names = aggregate_function_factory.registered_names(); let udfs = FunctionsTable::get_udfs(ctx).await?; let names: Vec<&str> = func_names .iter() .chain(aggr_func_names.iter()) .chain(udfs.iter().map(|udf| &udf.name)) .map(|x| x.as_str()) .collect(); let builtin_func_len = func_names.len() + aggr_func_names.len(); let is_builtin = (0..names.len()) .map(|i| i < builtin_func_len) .collect::<Vec<bool>>(); let is_aggregate = (0..names.len()) .map(|i| i >= func_names.len() && i < builtin_func_len) .collect::<Vec<bool>>(); let definitions = (0..names.len()) .map(|i| { if i < builtin_func_len { "" } else { udfs.get(i - builtin_func_len) .map_or("", |udf| udf.definition.as_str()) } }) .collect::<Vec<&str>>(); let categorys = (0..names.len()) .map(|i| if i < builtin_func_len { "" } else { "UDF" }) .collect::<Vec<&str>>(); let descriptions = (0..names.len()) .map(|i| { if i < builtin_func_len { "" } else { udfs.get(i - builtin_func_len) .map_or("", |udf| udf.description.as_str()) } }) .collect::<Vec<&str>>(); let syntaxs = (0..names.len()) .map(|i| { if i < builtin_func_len { "" } else { udfs.get(i - builtin_func_len) .map_or("", |udf| udf.definition.as_str()) } }) .collect::<Vec<&str>>(); let examples = (0..names.len()).map(|_| "").collect::<Vec<&str>>(); Ok(DataBlock::new_from_columns(vec![ StringType::from_data(names), BooleanType::from_data(is_builtin), BooleanType::from_data(is_aggregate), StringType::from_data(definitions), StringType::from_data(categorys), StringType::from_data(descriptions), StringType::from_data(syntaxs), StringType::from_data(examples), ])) } } impl FunctionsTable { pub fn create(table_id: u64) -> Arc<dyn Table> { let schema = TableSchemaRefExt::create(vec![ TableField::new("name", TableDataType::String), TableField::new("is_builtin", TableDataType::Boolean), TableField::new("is_aggregate", TableDataType::Boolean), TableField::new("definition", TableDataType::String), TableField::new("category", TableDataType::String), TableField::new("description", TableDataType::String), TableField::new("syntax", TableDataType::String), TableField::new("example", TableDataType::String), ]); let table_info = TableInfo { desc: "'system'.'functions'".to_string(), name: "functions".to_string(), ident: TableIdent::new(table_id, 0), meta: TableMeta { schema, engine: "SystemFunctions".to_string(), ..Default::default() }, ..Default::default() }; AsyncOneBlockSystemTable::create(FunctionsTable { table_info }) } async fn get_udfs(ctx: Arc<dyn TableContext>) -> Result<Vec<UserDefinedFunction>> { let tenant = ctx.get_tenant(); UserApiProvider::instance().get_udfs(&tenant).await } }
use crate::prelude::*; use std::os::raw::c_void; use std::ptr; #[repr(C)] #[derive(Debug)] pub struct VkBufferMemoryBarrier { pub sType: VkStructureType, pub pNext: *const c_void, pub srcAccessMask: VkAccessFlagBits, pub dstAccessMask: VkAccessFlagBits, pub srcQueueFamilyIndex: u32, pub dstQueueFamilyIndex: u32, pub buffer: VkBuffer, pub offset: VkDeviceSize, pub size: VkDeviceSize, } impl VkBufferMemoryBarrier { pub fn new<S, T>( src_access_mask: S, dst_access_mask: T, src_queue_family_index: u32, dst_queue_family_index: u32, buffer: VkBuffer, offset: VkDeviceSize, size: VkDeviceSize, ) -> VkBufferMemoryBarrier where S: Into<VkAccessFlagBits>, T: Into<VkAccessFlagBits>, { VkBufferMemoryBarrier { sType: VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, pNext: ptr::null(), srcAccessMask: src_access_mask.into(), dstAccessMask: dst_access_mask.into(), srcQueueFamilyIndex: src_queue_family_index, dstQueueFamilyIndex: dst_queue_family_index, buffer, offset, size, } } }
use std::{io, process::ExitStatus}; use thiserror::Error; use tokio::process::{Child, Command}; #[derive(Debug, Error)] pub(crate) enum ForkError { #[error("Failed to fork child program: {0}")] FailedToFork(io::Error), #[cfg(unix)] #[error("Failed to register SIGTERM handler: {0}")] FailedToRegisterSignalHandler(io::Error), #[error("Child program failed: {0}")] IoError(#[from] io::Error), #[cfg(not(unix))] #[error("Child was killed")] Killed, } // From https://man.netbsd.org/sysexits.3 const EX_OSERR: i32 = 71; impl ForkError { pub(crate) fn suggested_exit_code(&self) -> i32 { match self { ForkError::FailedToFork(_) => EX_OSERR, #[cfg(unix)] ForkError::FailedToRegisterSignalHandler(_) => EX_OSERR, ForkError::IoError(err) => err.raw_os_error().unwrap_or(1), #[cfg(not(unix))] ForkError::Killed => 1, } } } struct TermSignal { #[cfg(unix)] signal: tokio::signal::unix::Signal, } #[cfg(unix)] impl TermSignal { fn new() -> Result<Self, ForkError> { use tokio::signal::unix::{signal, SignalKind}; let signal = signal(SignalKind::terminate()).map_err(ForkError::FailedToRegisterSignalHandler)?; Ok(Self { signal }) } async fn recv(&mut self) { self.signal.recv().await; } } #[cfg(not(unix))] impl TermSignal { #[allow(clippy::unnecessary_wraps)] fn new() -> Result<Self, ForkError> { Ok(Self {}) } async fn recv(&mut self) { tokio::signal::ctrl_c() .await .expect("failed to listen for ctrl-c") } } #[cfg(unix)] async fn terminate_child(mut child: Child) -> Result<ExitStatus, ForkError> { use nix::{ sys::signal::{kill, Signal::SIGTERM}, unistd::Pid, }; use std::convert::TryInto as _; if let Some(pid) = child.id() { // If the child hasn't already completed, send a SIGTERM. if let Err(e) = kill(Pid::from_raw(pid.try_into().expect("Invalid PID")), SIGTERM) { eprintln!("Failed to forward SIGTERM to child process: {}", e); } } // Wait to get the child's exit code. child.wait().await.map_err(Into::into) } #[cfg(not(unix))] async fn terminate_child(mut child: Child) -> Result<ExitStatus, ForkError> { child.kill().await?; Err(ForkError::Killed) } pub(crate) async fn fork_with_sigterm( cmd: String, args: Vec<String>, ) -> Result<ExitStatus, ForkError> { let mut child = Command::new(&cmd) .args(args) .spawn() .map_err(ForkError::FailedToFork)?; let mut sigterm = TermSignal::new()?; tokio::select! { ex = child.wait() => ex.map_err(Into::into), _ = sigterm.recv() => terminate_child(child).await } }
use super::method::mpf; use super::stat; use super::types::*; use super::weight; pub fn correct(mut xs: &mut Ensemble, truth: &V) { let dev = stat::mean(&xs) - truth; for x in xs.iter_mut() { *x = &*x - &dev; } } pub fn shake(xs: &Ensemble) -> Ensemble { let res = mpf::MergeResampler::default(); let w = weight::Weight::uniform(xs.len()); res.resampling(&w, xs) }
// This file is part of syslog2. 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/syslog2/master/COPYRIGHT. No part of syslog2, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2016 The developers of syslog2. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/syslog2/master/COPYRIGHT. extern crate process; extern crate time; extern crate libc; use self::libc::c_int; use self::process::CurrentProcess; use self::rfc3164::format_message_rfc3164; use std::ffi::CStr; use std::ffi::CString; use Priority; pub fn syslog_cstr(priority: Priority, message: &CStr) { log_to_standard_error_for_windows_and_solaris_cstr(priority, message); } // Exists because we need byte string constants, and these are for UNSIGNED bytes pub fn syslog_bytes(priority: Priority, message: &[u8]) { log_to_standard_error_for_windows_and_solaris_bytes(priority, message); } pub fn with_open_syslog<F, R>(programName: &CStr, logToStandardErrorAsWell: bool, defaultFacility: Facility, closure: F) -> R where F: Fn() -> R { enable_logging_to_standard_error(programName, logToStandardErrorAsWell, defaultFacility); closure(); }
#[derive(Clone, Deserialize)] pub struct DebugSettings { pub print_fps: bool, pub print_deaths: bool, pub print_time: bool, }
extern crate math_solver; use std::io::{stdin, BufRead}; fn main() { let stdin = stdin(); let mut stdin = stdin.lock(); loop { let mut line = String::new(); if let Err(e) = stdin.read_line(&mut line) { println!("{:?}", e); return; } let line = line.trim(); if line == "q" { return; } match math_solver::evaluate(line) { Ok(v) => println!("{:?}", v), Err(e) => { if let Some(span) = e.get_span() { println!("{}", line); println!( "{}{}", std::iter::repeat(" ").take(span.from).collect::<String>(), std::iter::repeat("^") .take(span.to - span.from) .collect::<String>() ); } println!("{:?}", e); } } } }
use float::Float; use int::Int; macro_rules! fp_overflow { (infinity, $fty:ty, $sign: expr) => { return { <$fty as Float>::from_parts( $sign, <$fty as Float>::exponent_max() as <$fty as Float>::Int, 0 as <$fty as Float>::Int) } } } macro_rules! int_to_float { ($intrinsic:ident: $ity:ty, $fty:ty) => { int_to_float!($intrinsic: $ity, $fty, "C"); }; ($intrinsic:ident: $ity:ty, $fty:ty, $abi:tt) => { #[no_mangle] pub extern $abi fn $intrinsic(i: $ity) -> $fty { if i == 0 { return 0.0 } let mant_dig = <$fty>::significand_bits() + 1; let exponent_bias = <$fty>::exponent_bias(); let n = <$ity>::bits(); let (s, a) = i.extract_sign(); let mut a = a; // number of significant digits let sd = n - a.leading_zeros(); // exponent let mut e = sd - 1; if <$ity>::bits() < mant_dig { return <$fty>::from_parts(s, (e + exponent_bias) as <$fty as Float>::Int, (a as <$fty as Float>::Int) << (mant_dig - e - 1)) } a = if sd > mant_dig { /* start: 0000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQxxxxxxxxxxxxxxxxxx * finish: 000000000000000000000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQR * 12345678901234567890123456 * 1 = msb 1 bit * P = bit MANT_DIG-1 bits to the right of 1 * Q = bit MANT_DIG bits to the right of 1 * R = "or" of all bits to the right of Q */ let mant_dig_plus_one = mant_dig + 1; let mant_dig_plus_two = mant_dig + 2; a = if sd == mant_dig_plus_one { a << 1 } else if sd == mant_dig_plus_two { a } else { (a >> (sd - mant_dig_plus_two)) as <$ity as Int>::UnsignedInt | ((a & <$ity as Int>::UnsignedInt::max_value()).wrapping_shl((n + mant_dig_plus_two) - sd) != 0) as <$ity as Int>::UnsignedInt }; /* finish: */ a |= ((a & 4) != 0) as <$ity as Int>::UnsignedInt; /* Or P into R */ a += 1; /* round - this step may add a significant bit */ a >>= 2; /* dump Q and R */ /* a is now rounded to mant_dig or mant_dig+1 bits */ if (a & (1 << mant_dig)) != 0 { a >>= 1; e += 1; } a /* a is now rounded to mant_dig bits */ } else { a.wrapping_shl(mant_dig - sd) /* a is now rounded to mant_dig bits */ }; <$fty>::from_parts(s, (e + exponent_bias) as <$fty as Float>::Int, a as <$fty as Float>::Int) } } } macro_rules! int_to_float_unadj_on_win { ($intrinsic:ident: $ity:ty, $fty:ty) => { #[cfg(all(windows, target_pointer_width="64"))] int_to_float!($intrinsic: $ity, $fty, "unadjusted"); #[cfg(not(all(windows, target_pointer_width="64")))] int_to_float!($intrinsic: $ity, $fty, "C"); }; } int_to_float!(__floatsisf: i32, f32); int_to_float!(__floatsidf: i32, f64); int_to_float!(__floatdidf: i64, f64); int_to_float_unadj_on_win!(__floattisf: i128, f32); int_to_float_unadj_on_win!(__floattidf: i128, f64); int_to_float!(__floatunsisf: u32, f32); int_to_float!(__floatunsidf: u32, f64); int_to_float!(__floatundidf: u64, f64); int_to_float!(__floatundisf: u64, f32); int_to_float_unadj_on_win!(__floatuntisf: u128, f32); int_to_float_unadj_on_win!(__floatuntidf: u128, f64); #[derive(PartialEq, Debug)] enum Sign { Positive, Negative } macro_rules! float_to_int { ($intrinsic:ident: $fty:ty, $ity:ty) => { float_to_int!($intrinsic: $fty, $ity, "C"); }; ($intrinsic:ident: $fty:ty, $ity:ty, $abi:tt) => { pub extern $abi fn $intrinsic(f: $fty) -> $ity { let fixint_min = <$ity>::min_value(); let fixint_max = <$ity>::max_value(); let fixint_bits = <$ity>::bits() as usize; let fixint_unsigned = fixint_min == 0; let sign_bit = <$fty>::sign_mask(); let significand_bits = <$fty>::significand_bits() as usize; let exponent_bias = <$fty>::exponent_bias() as usize; //let exponent_max = <$fty>::exponent_max() as usize; // Break a into sign, exponent, significand let a_rep = <$fty>::repr(f); let a_abs = a_rep & !sign_bit; // this is used to work around -1 not being available for unsigned let sign = if (a_rep & sign_bit) == 0 { Sign::Positive } else { Sign::Negative }; let mut exponent = (a_abs >> significand_bits) as usize; let significand = (a_abs & <$fty>::significand_mask()) | <$fty>::implicit_bit(); // if < 1 or unsigned & negative if exponent < exponent_bias || fixint_unsigned && sign == Sign::Negative { return 0 } exponent -= exponent_bias; // If the value is infinity, saturate. // If the value is too large for the integer type, 0. if exponent >= (if fixint_unsigned {fixint_bits} else {fixint_bits -1}) { return if sign == Sign::Positive {fixint_max} else {fixint_min} } // If 0 <= exponent < significand_bits, right shift to get the result. // Otherwise, shift left. // (sign - 1) will never overflow as negative signs are already returned as 0 for unsigned let r = if exponent < significand_bits { (significand >> (significand_bits - exponent)) as $ity } else { (significand as $ity) << (exponent - significand_bits) }; if sign == Sign::Negative { (!r).wrapping_add(1) } else { r } } } } macro_rules! float_to_int_unadj_on_win { ($intrinsic:ident: $fty:ty, $ity:ty) => { #[cfg(all(windows, target_pointer_width="64"))] float_to_int!($intrinsic: $fty, $ity, "unadjusted"); #[cfg(not(all(windows, target_pointer_width="64")))] float_to_int!($intrinsic: $fty, $ity, "C"); }; } float_to_int!(__fixsfsi: f32, i32); float_to_int!(__fixsfdi: f32, i64); float_to_int_unadj_on_win!(__fixsfti: f32, i128); float_to_int!(__fixdfsi: f64, i32); float_to_int!(__fixdfdi: f64, i64); float_to_int_unadj_on_win!(__fixdfti: f64, i128); float_to_int!(__fixunssfsi: f32, u32); float_to_int!(__fixunssfdi: f32, u64); float_to_int_unadj_on_win!(__fixunssfti: f32, u128); float_to_int!(__fixunsdfsi: f64, u32); float_to_int!(__fixunsdfdi: f64, u64); float_to_int_unadj_on_win!(__fixunsdfti: f64, u128);
pub fn roll_over(num : i32) -> f64 { if num > 6 { 0.0 } else if num <= 1 { 1.0 } else { (7 - num) as f64 / 6.0 } } #[test] fn test_roll_over() { assert_eq!(roll_over(0),1.0); assert_eq!(roll_over(1),1.0); assert_eq!(roll_over(4),0.5); assert_eq!(roll_over(6),1.0/6.0); assert_eq!(roll_over(7),0.0); }
use super::envelope::Envelope; use serde::{Deserialize, Serialize}; const TIMER_PERIOD: [u16; 16] = [ 4, 8, 16, 32, 64, 96, 128, 160, 202, 254, 380, 508, 762, 1016, 2034, 4068, ]; #[derive(Serialize, Deserialize)] pub struct Noise { pub enabled: bool, envelope: Envelope, length_counter_halt: bool, length_table: Vec<u8>, length_counter: u8, shift_register: u16, mode_flag: bool, timer_value: u16, timer_period: u16, } impl Noise { pub fn new() -> Noise { Noise { enabled: true, envelope: Envelope::new(), length_counter_halt: false, length_table: vec![ 10, 254, 20, 2, 40, 4, 80, 6, 160, 8, 60, 10, 14, 12, 26, 14, 12, 16, 24, 18, 48, 20, 96, 22, 192, 24, 72, 26, 16, 28, 32, 30, ], length_counter: 0, shift_register: 1, mode_flag: false, timer_value: 0, timer_period: 0, } } pub fn write_control(&mut self, byte: u8) { self.length_counter_halt = (byte & 0x20) != 0; self.envelope.set_constant_flag((byte & 0x10) != 0); self.envelope.set_v(byte & 0x0F); } pub fn write_mode(&mut self, byte: u8) { self.mode_flag = (byte & 0x80) != 0; self.timer_period = TIMER_PERIOD[(byte & 0x0F) as usize]; } pub fn write_length_counter(&mut self, byte: u8) { self.length_counter = self.length_table[(byte >> 3) as usize]; self.envelope.set_start(); } pub fn on_clock(&mut self) { if self.timer_value == 0 { self.timer_value = self.timer_period; self.shift_register = Noise::new_shift_value(self.shift_register, self.mode_flag); } else { self.timer_value -= 1; } } fn new_shift_value(shift_value: u16, mode_flag: bool) -> u16 { let bit_two = (shift_value & if mode_flag { 0x0020 } else { 0x0002 }) != 0; let feedback = (shift_value & 0x0001 != 0) ^ bit_two; let mut new_shift_value = shift_value; new_shift_value = new_shift_value >> 1; new_shift_value = (new_shift_value & 0xBFFF) | if feedback { 0x4000 } else { 0 }; new_shift_value } pub fn on_quarter_frame(&mut self) { self.envelope.on_clock(); } pub fn on_half_frame(&mut self) { if !self.length_counter_halt && self.length_counter > 0 { self.length_counter -= 1; } } pub fn output(&self) -> u8 { let shifter_says_no = 0x0001 & self.shift_register == 1; if shifter_says_no || self.length_counter == 0 || !self.enabled { 0 } else { self.envelope.output() } } pub fn set_enabled(&mut self, enabled: bool) { self.enabled = enabled; if !self.enabled { self.length_counter = 0; } } } #[cfg(test)] mod tests { use super::*; #[test] fn shift_feedback_no_mode() { assert_eq!(Noise::new_shift_value(0x0001, false), 0x4000); assert_eq!(Noise::new_shift_value(0x0003, false), 0x0001); assert_eq!(Noise::new_shift_value(0x0001, true), 0x4000); assert_eq!(Noise::new_shift_value(0x0021, true), 0x0010); } #[test] fn correct_length_no_mode() { let mut v = 1; for i in 0..32767 { v = Noise::new_shift_value(v, false); if i != 32766 && v == 1 { assert_ne!(v, 1); } } assert_eq!(v, 1); } #[test] fn correct_length_mode() { let mut v = 1; for i in 0..31 { v = Noise::new_shift_value(v, true); if i != 30 && v == 1 { assert_ne!(v, 1); } } assert_eq!(v, 1); } }
//extern crate regex; //use self::regex::Regex; extern crate serde_json; use self::serde_json::Value; //use std::fs::{self,File}; //use std::io::Read; //use std::path::Path; use super::*; /* static PATH_TO_GRAPHS: &'static str = "./www/graphs"; static IMPORTABLE: &'static str = r"graph(?P<n>(\d+|\d+_\d+_))_(?P<s>\d+)\.json"; pub fn list_all_graphs() -> Option<Vec<String>> { let p = Path::new(PATH_TO_GRAPHS); let imp = Regex::new(IMPORTABLE).unwrap(); let mut gn:Vec<String> = Vec::new(); for entry in fs::read_dir(p).ok()? { let file_path = entry.ok()?.path(); let file_name = file_path.to_str()?; if imp.is_match(file_name) { let capture = imp.captures(file_name).unwrap(); let name = String::from(&capture["n"]) + " " + &capture["s"]; gn.push(name); } } Some(gn) } pub fn build_graphs() -> Option<Vec<Graph>>{ let p = Path::new(PATH_TO_GRAPHS); let importable = Regex::new(r"graph(?P<n>(\d+|\d+_\d+_))_.+\.json").unwrap(); let mut graphs:Vec<Graph> = Vec::new(); for entry in fs::read_dir(p).ok()? { let file_path = entry.ok()?.path(); let file_name = file_path.to_str()?; if importable.is_match(file_name) { let mut file = File::open(file_name).unwrap(); let mut data = String::new(); file.read_to_string(&mut data).unwrap(); let capture = importable.captures(file_name).unwrap(); if let Some(g) = json_to_graph(String::from(&capture["n"]),data.as_str()) { graphs.push(g); } println!("{}",file_name); } } Some(graphs) } */ pub fn json_to_graph(data:&str) -> Option<Graph> { let val:Value = serde_json::from_str(data).ok()?; let mut g = Graph::new(); // Vertices for v in val["vertices"].as_array()? { let id = v["id"].as_i64()?; let x = v["position"]["x"].as_i64()?; let y = v["position"]["y"].as_i64()?; g.add_vertex(Vertex::new(id as i32, x as i32, y as i32)); } // Edges for e in val["edges"].as_array()? { let id = e["id"].as_i64()?; let start = e["start"].as_i64()?; let end = e["end"].as_i64()?; g.add_edge(Edge::new(id as i32, start as i32, end as i32, 0)); } Some(g) }
use crate::error::Error; use crate::WebSocketSink; use std::fmt::{self, Debug, Formatter}; pub struct WebSocketEvent<WebSocketId> { pub id: WebSocketId, pub kind: WebSocketEventKind, } #[derive(Debug)] pub struct CloseFrame { code: u32, reason: String, } pub enum WebSocketEventKind { Connected(WebSocketSink), ConnectionFailed(Error), Message(String), CloseMessage(Option<CloseFrame>), ConnectionClosed, Error(Error), } impl Debug for WebSocketEventKind { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { WebSocketEventKind::Connected(_) => write!(f, "WebSocketEventKind::Connected(...)"), WebSocketEventKind::ConnectionFailed(err) => { write!(f, "WebSocketEventKind::ConnectionFailed({:?})", err) } WebSocketEventKind::Message(msg) => write!(f, "WebSocketEventKind::Message({:?})", msg), WebSocketEventKind::CloseMessage(frame) => { write!(f, "WebSocketEventKind::CloseMessage({:?})", frame,) } WebSocketEventKind::ConnectionClosed => { write!(f, "WebSocketEventKind::ConnectionClosed") } WebSocketEventKind::Error(err) => write!(f, "WebSocketEventKind::Error({:?})", err), } } } impl<WebSocketId> WebSocketEvent<WebSocketId> { pub fn connected(id: WebSocketId, sink: WebSocketSink) -> Self { Self { id, kind: WebSocketEventKind::Connected(sink), } } pub fn connection_failed(id: WebSocketId, err: Error) -> Self { Self { id, kind: WebSocketEventKind::ConnectionFailed(err), } } pub fn message(id: WebSocketId, msg: String) -> Self { Self { id, kind: WebSocketEventKind::Message(msg), } } pub fn empty_close_msg(id: WebSocketId) -> Self { Self { id, kind: WebSocketEventKind::CloseMessage(None), } } pub fn close_msg(id: WebSocketId, code: u32, reason: String) -> Self { Self { id, kind: WebSocketEventKind::CloseMessage(Some(CloseFrame { code, reason })), } } pub fn connection_closed(id: WebSocketId) -> Self { Self { id, kind: WebSocketEventKind::ConnectionClosed, } } pub fn error(id: WebSocketId, err: Error) -> Self { Self { id, kind: WebSocketEventKind::Error(err), } } }
// Binary file using a serial communication protocol to the client #![allow(dead_code)] use std::io; use std::io::{BufRead, BufReader, Write}; use std::sync::mpsc::{Receiver, Sender}; use std::thread; mod gui; mod i2c; mod protocol; mod shared; use protocol::{IncomingMsg, OutgoingMsg}; use shared::{Event, SerialEvent}; // Default serial port location on the raspberry pi const PORT: &str = "/dev/serial0"; // Launch function for an interface module using serial for communication pub fn launch(tx: Sender<Event>, rx: Receiver<SerialEvent>) { // Open the serial port let mut serial_tx = serialport::open(PORT).expect("Failed to open serialport"); let serial_rx = serial_tx.try_clone().unwrap(); // Spawn a thread for sending OutgoingMsg to the client over serial thread::spawn(move || { for message in rx.iter() { serial_tx .write_all( serde_json::to_string(&OutgoingMsg::from(message)) .unwrap() .as_bytes(), ) .unwrap(); } }); let mut buf_reader = BufReader::new(serial_rx); // Read data over serial and parse that data into IncomingMsg in the system loop { let mut content = String::new(); match buf_reader.read_line(&mut content) { Ok(_) => { let message: IncomingMsg = serde_json::from_str(content.as_ref()).unwrap(); tx.send(Event::from(message)).unwrap(); } Err(ref e) if e.kind() == io::ErrorKind::TimedOut => (), Err(e) => eprintln!("{:?}", e), } } } // Launch the main thread using a serial interface fn main() { shared::start(launch); }
#[inline(always)] pub unsafe fn hlt() { asm!("hlt"); } #[inline(always)] #[allow(dead_code)] pub unsafe fn inb(port: u16) -> u8 { let data: u8; asm!("inb %dx,%al" : "={al}" (data) : "{dx}" (port)); data } #[inline(always)] #[allow(dead_code)] pub unsafe fn inw(port: u16) -> u16 { let data: u16; asm!("inw %dx,%ax" : "={ax}" (data) : "{dx}" (port)); data } #[inline(always)] #[allow(dead_code)] pub unsafe fn inl(port: u16) -> u32 { let data: u32; asm!("inl %dx,%eax" : "={eax}" (data) : "{dx}" (port)); data } #[inline(always)] #[allow(dead_code)] pub unsafe fn outb(port: u16, val: u8) { asm!("outb %al, %dx" : : "{al}"(val), "{dx}"(port)); } #[inline(always)] #[allow(dead_code)] pub unsafe fn outw(port: u16, val: u16) { asm!("outw %ax, %dx" : : "{ax}"(val), "{dx}"(port)); } #[inline(always)] #[allow(dead_code)] pub unsafe fn outl(port: u16, val: u32) { asm!("outl %eax, %dx" : : "{eax}"(val), "{dx}"(port)); }
use crate::process::Pid; use crate::{backend, io}; use bitflags::bitflags; #[cfg(target_os = "linux")] use crate::fd::BorrowedFd; #[cfg(linux_raw)] use crate::backend::process::wait::SiginfoExt; bitflags! { /// Options for modifying the behavior of wait/waitpid #[repr(transparent)] #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct WaitOptions: u32 { /// Return immediately if no child has exited. const NOHANG = bitcast!(backend::process::wait::WNOHANG); /// Return if a child has stopped (but not traced via [`ptrace`]) /// /// [`ptrace`]: https://man7.org/linux/man-pages/man2/ptrace.2.html const UNTRACED = bitcast!(backend::process::wait::WUNTRACED); /// Return if a stopped child has been resumed by delivery of /// [`Signal::Cont`]. const CONTINUED = bitcast!(backend::process::wait::WCONTINUED); } } #[cfg(not(any(target_os = "openbsd", target_os = "redox", target_os = "wasi")))] bitflags! { /// Options for modifying the behavior of waitid #[repr(transparent)] #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct WaitidOptions: u32 { /// Return immediately if no child has exited. const NOHANG = bitcast!(backend::process::wait::WNOHANG); /// Return if a stopped child has been resumed by delivery of /// [`Signal::Cont`] const CONTINUED = bitcast!(backend::process::wait::WCONTINUED); /// Wait for processed that have exited. const EXITED = bitcast!(backend::process::wait::WEXITED); /// Keep processed in a waitable state. const NOWAIT = bitcast!(backend::process::wait::WNOWAIT); /// Wait for processes that have been stopped. const STOPPED = bitcast!(backend::process::wait::WSTOPPED); } } /// The status of a child process after calling [`wait`]/[`waitpid`]. #[derive(Debug, Clone, Copy)] #[repr(transparent)] pub struct WaitStatus(u32); impl WaitStatus { /// Creates a `WaitStatus` out of an integer. #[inline] pub(crate) fn new(status: u32) -> Self { Self(status) } /// Converts a `WaitStatus` into its raw representation as an integer. #[inline] pub const fn as_raw(self) -> u32 { self.0 } /// Returns whether the process is currently stopped. #[inline] pub fn stopped(self) -> bool { backend::process::wait::WIFSTOPPED(self.0 as _) } /// Returns whether the process has exited normally. #[inline] pub fn exited(self) -> bool { backend::process::wait::WIFEXITED(self.0 as _) } /// Returns whether the process was terminated by a signal. #[inline] pub fn signaled(self) -> bool { backend::process::wait::WIFSIGNALED(self.0 as _) } /// Returns whether the process has continued from a job control stop. #[inline] pub fn continued(self) -> bool { backend::process::wait::WIFCONTINUED(self.0 as _) } /// Returns the number of the signal that stopped the process, /// if the process was stopped by a signal. #[inline] pub fn stopping_signal(self) -> Option<u32> { if self.stopped() { Some(backend::process::wait::WSTOPSIG(self.0 as _) as _) } else { None } } /// Returns the exit status number returned by the process, /// if it exited normally. #[inline] pub fn exit_status(self) -> Option<u32> { if self.exited() { Some(backend::process::wait::WEXITSTATUS(self.0 as _) as _) } else { None } } /// Returns the number of the signal that terminated the process, /// if the process was terminated by a signal. #[inline] pub fn terminating_signal(self) -> Option<u32> { if self.signaled() { Some(backend::process::wait::WTERMSIG(self.0 as _) as _) } else { None } } } /// The status of a process after calling [`waitid`]. #[derive(Clone, Copy)] #[repr(transparent)] #[cfg(not(any(target_os = "openbsd", target_os = "redox", target_os = "wasi")))] pub struct WaitidStatus(pub(crate) backend::c::siginfo_t); #[cfg(not(any(target_os = "openbsd", target_os = "redox", target_os = "wasi")))] impl WaitidStatus { /// Returns whether the process is currently stopped. #[inline] pub fn stopped(&self) -> bool { self.si_code() == backend::c::CLD_STOPPED } /// Returns whether the process is currently trapped. #[inline] pub fn trapped(&self) -> bool { self.si_code() == backend::c::CLD_TRAPPED } /// Returns whether the process has exited normally. #[inline] pub fn exited(&self) -> bool { self.si_code() == backend::c::CLD_EXITED } /// Returns whether the process was terminated by a signal /// and did not create a core file. #[inline] pub fn killed(&self) -> bool { self.si_code() == backend::c::CLD_KILLED } /// Returns whether the process was terminated by a signal /// and did create a core file. #[inline] pub fn dumped(&self) -> bool { self.si_code() == backend::c::CLD_DUMPED } /// Returns whether the process has continued from a job control stop. #[inline] pub fn continued(&self) -> bool { self.si_code() == backend::c::CLD_CONTINUED } /// Returns the number of the signal that stopped the process, /// if the process was stopped by a signal. #[inline] #[cfg(not(any(target_os = "netbsd", target_os = "fuchsia", target_os = "emscripten")))] pub fn stopping_signal(&self) -> Option<u32> { if self.stopped() { Some(self.si_status() as _) } else { None } } /// Returns the number of the signal that trapped the process, /// if the process was trapped by a signal. #[inline] #[cfg(not(any(target_os = "netbsd", target_os = "fuchsia", target_os = "emscripten")))] pub fn trapping_signal(&self) -> Option<u32> { if self.trapped() { Some(self.si_status() as _) } else { None } } /// Returns the exit status number returned by the process, /// if it exited normally. #[inline] #[cfg(not(any(target_os = "netbsd", target_os = "fuchsia", target_os = "emscripten")))] pub fn exit_status(&self) -> Option<u32> { if self.exited() { Some(self.si_status() as _) } else { None } } /// Returns the number of the signal that terminated the process, /// if the process was terminated by a signal. #[inline] #[cfg(not(any(target_os = "netbsd", target_os = "fuchsia", target_os = "emscripten")))] pub fn terminating_signal(&self) -> Option<u32> { if self.killed() || self.dumped() { Some(self.si_status() as _) } else { None } } /// Returns a reference to the raw platform-specific `siginfo_t` struct. #[inline] pub const fn as_raw(&self) -> &backend::c::siginfo_t { &self.0 } #[cfg(linux_raw)] fn si_code(&self) -> u32 { self.0.si_code() as u32 // CLD_ consts are unsigned } #[cfg(not(linux_raw))] fn si_code(&self) -> backend::c::c_int { self.0.si_code } #[cfg(not(any(target_os = "netbsd", target_os = "fuchsia", target_os = "emscripten")))] #[allow(unsafe_code)] fn si_status(&self) -> backend::c::c_int { // SAFETY: POSIX [specifies] that the `siginfo_t` returned by a // `waitid` call always has a valid `si_status` value. // // [specifies]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html unsafe { self.0.si_status() } } } /// The identifier to wait on in a call to [`waitid`]. #[cfg(not(any(target_os = "openbsd", target_os = "redox", target_os = "wasi")))] #[derive(Debug, Clone)] #[non_exhaustive] pub enum WaitId<'a> { /// Wait on all processes. All, /// Wait for a specific process ID. Pid(Pid), /// Wait for a specific process file descriptor. #[cfg(target_os = "linux")] PidFd(BorrowedFd<'a>), /// Eat the lifetime for non-Linux platforms. #[doc(hidden)] #[cfg(not(target_os = "linux"))] __EatLifetime(core::marker::PhantomData<&'a ()>), // TODO(notgull): Once this crate has the concept of PGIDs, add a WaitId::Pgid } /// `waitpid(pid, waitopts)`—Wait for a specific process to change state. /// /// If the pid is `None`, the call will wait for any child process whose /// process group id matches that of the calling process. /// /// If the pid is equal to `RawPid::MAX`, the call will wait for any child /// process. /// /// Otherwise if the `wrapping_neg` of pid is less than pid, the call will wait /// for any child process with a group ID equal to the `wrapping_neg` of `pid`. /// /// Otherwise, the call will wait for the child process with the given pid. /// /// On Success, returns the status of the selected process. /// /// If `NOHANG` was specified in the options, and the selected child process /// didn't change state, returns `None`. /// /// # References /// - [POSIX] /// - [Linux] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html /// [Linux]: https://man7.org/linux/man-pages/man2/waitpid.2.html #[cfg(not(target_os = "wasi"))] #[inline] pub fn waitpid(pid: Option<Pid>, waitopts: WaitOptions) -> io::Result<Option<WaitStatus>> { Ok(backend::process::syscalls::waitpid(pid, waitopts)?.map(|(_, status)| status)) } /// `wait(waitopts)`—Wait for any of the children of calling process to /// change state. /// /// On success, returns the pid of the child process whose state changed, and /// the status of said process. /// /// If `NOHANG` was specified in the options, and the selected child process /// didn't change state, returns `None`. /// /// # References /// - [POSIX] /// - [Linux] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html /// [Linux]: https://man7.org/linux/man-pages/man2/waitpid.2.html #[cfg(not(target_os = "wasi"))] #[inline] pub fn wait(waitopts: WaitOptions) -> io::Result<Option<(Pid, WaitStatus)>> { backend::process::syscalls::wait(waitopts) } /// `waitid(_, _, _, opts)`—Wait for the specified child process to change /// state. #[cfg(not(any(target_os = "openbsd", target_os = "redox", target_os = "wasi")))] #[inline] pub fn waitid<'a>( id: impl Into<WaitId<'a>>, options: WaitidOptions, ) -> io::Result<Option<WaitidStatus>> { backend::process::syscalls::waitid(id.into(), options) }
//! Code generation for `#[graphql_scalar]` macro. use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{parse_quote, spanned::Spanned}; use crate::common::{diagnostic, parse, scalar, SpanContainer}; use super::{derive::parse_derived_methods, Attr, Definition, Methods, ParseToken, TypeOrIdent}; /// [`diagnostic::Scope`] of errors for `#[graphql_scalar]` macro. const ERR: diagnostic::Scope = diagnostic::Scope::ScalarAttr; /// Expands `#[graphql_scalar]` macro into generated code. pub(crate) fn expand(attr_args: TokenStream, body: TokenStream) -> syn::Result<TokenStream> { if let Ok(mut ast) = syn::parse2::<syn::ItemType>(body.clone()) { let attrs = parse::attr::unite(("graphql_scalar", &attr_args), &ast.attrs); ast.attrs = parse::attr::strip("graphql_scalar", ast.attrs); return expand_on_type_alias(attrs, ast); } else if let Ok(mut ast) = syn::parse2::<syn::DeriveInput>(body) { let attrs = parse::attr::unite(("graphql_scalar", &attr_args), &ast.attrs); ast.attrs = parse::attr::strip("graphql_scalar", ast.attrs); return expand_on_derive_input(attrs, ast); } Err(syn::Error::new( Span::call_site(), "#[graphql_scalar] attribute is applicable to type aliases, structs, \ enums and unions only", )) } /// Expands `#[graphql_scalar]` macro placed on a type alias. fn expand_on_type_alias( attrs: Vec<syn::Attribute>, ast: syn::ItemType, ) -> syn::Result<TokenStream> { let attr = Attr::from_attrs("graphql_scalar", &attrs)?; if attr.transparent { return Err(ERR.custom_error( ast.span(), "`transparent` attribute argument isn't applicable to type aliases", )); } let methods = parse_type_alias_methods(&ast, &attr)?; let scalar = scalar::Type::parse(attr.scalar.as_deref(), &ast.generics); let def = Definition { ty: TypeOrIdent::Type(ast.ty.clone()), where_clause: attr .where_clause .map_or_else(Vec::new, |cl| cl.into_inner()), generics: ast.generics.clone(), methods, name: attr .name .map(SpanContainer::into_inner) .unwrap_or_else(|| ast.ident.to_string()), description: attr.description.map(SpanContainer::into_inner), specified_by_url: attr.specified_by_url.map(SpanContainer::into_inner), scalar, }; Ok(quote! { #ast #def }) } /// Expands `#[graphql_scalar]` macro placed on a struct, enum or union. fn expand_on_derive_input( attrs: Vec<syn::Attribute>, ast: syn::DeriveInput, ) -> syn::Result<TokenStream> { let attr = Attr::from_attrs("graphql_scalar", &attrs)?; let methods = parse_derived_methods(&ast, &attr)?; let scalar = scalar::Type::parse(attr.scalar.as_deref(), &ast.generics); let def = Definition { ty: TypeOrIdent::Ident(ast.ident.clone()), where_clause: attr .where_clause .map_or_else(Vec::new, |cl| cl.into_inner()), generics: ast.generics.clone(), methods, name: attr .name .map(SpanContainer::into_inner) .unwrap_or_else(|| ast.ident.to_string()), description: attr.description.map(SpanContainer::into_inner), specified_by_url: attr.specified_by_url.map(SpanContainer::into_inner), scalar, }; Ok(quote! { #ast #def }) } /// Parses [`Methods`] from the provided [`Attr`] for the specified type alias. fn parse_type_alias_methods(ast: &syn::ItemType, attr: &Attr) -> syn::Result<Methods> { match ( attr.to_output.as_deref().cloned(), attr.from_input.as_deref().cloned(), attr.parse_token.as_deref().cloned(), attr.with.as_deref().cloned(), ) { (Some(to_output), Some(from_input), Some(parse_token), None) => Ok(Methods::Custom { to_output, from_input, parse_token, }), (to_output, from_input, parse_token, Some(module)) => Ok(Methods::Custom { to_output: to_output.unwrap_or_else(|| parse_quote! { #module::to_output }), from_input: from_input.unwrap_or_else(|| parse_quote! { #module::from_input }), parse_token: parse_token .unwrap_or_else(|| ParseToken::Custom(parse_quote! { #module::parse_token })), }), _ => Err(ERR.custom_error( ast.span(), "all the resolvers have to be provided via `with` attribute \ argument or a combination of `to_output_with`, `from_input_with`, \ `parse_token_with`/`parse_token` attribute arguments", )), } }
pub trait YakuAttributes { fn name(&self) -> String; } pub mod situation { use crate::yaku::YakuAttributes; use crate::score::Han; /// 状況役 #[derive(Debug)] pub struct SituationYaku { /// 名前 name: String, /// 飜数 han_value: Han, } impl SituationYaku { #![allow(dead_code)] pub fn new(name: &str, han_value: u32) -> Self { Self { name: name.to_string(), han_value: Han(han_value) } } pub fn han_value(&self) -> Han { self.han_value.clone() } pub fn ready() -> Self { Self::new("立直 / Ready hand", 1) } pub fn nagashi_mangan() -> Self { Self::new("流し満貫 / Nagashi mangan", 4) } pub fn self_pick() -> Self { Self::new("門前清自摸和 / Self-pick", 1) } pub fn one_shot() -> Self { Self::new("一発 / One-shot", 1) } pub fn last_tile_from_the_wall() -> Self { Self::new("海底摸月 / Last tile from the wall", 1) } pub fn last_discard() -> Self { Self::new("河底撈魚 / Last discard", 1) } pub fn dead_wall_draw() -> Self { Self::new("嶺上開花 / Dead wall draw", 1) } pub fn robbing_a_quad() -> Self { Self::new("槍槓 / Robbing a quad", 1) } pub fn double_ready() -> Self { Self::new("ダブル立直 / Double ready", 2) } } impl YakuAttributes for SituationYaku { fn name(&self) -> String { self.name.to_string() } } } pub mod hand { use crate::yaku::YakuAttributes; use crate::evaluate::Wait; use crate::score::{Han, Fu}; use crate::tiles::Tile; /// 手役 pub struct HandYaku { /// 名前 pub name: String, /// ルール pub rule: Box<Fn(&Wait) -> Option<Han>>, /// 下位役 pub sub: Option<Box<HandYaku>>, /// 府数(平和、七対子対応) pub fu: Option<Box<Fn(&bool) -> Fu>>, } impl HandYaku { pub fn new(name: &str, sub: Option<Box<HandYaku>>, rule: Box<Fn(&Wait) -> Option<Han>>, fu: Option<Box<Fn(&bool) -> Fu>>) -> Self { HandYaku { name: name.to_string(), sub, rule, fu } } } impl YakuAttributes for HandYaku { fn name(&self) -> String { self.name.to_string() } } pub struct Yakuman { pub name: String, /// ルール pub rule: Box<Fn(&Wait, &Vec<Tile>) -> u32>, /// 下位役 pub sub: Option<Box<Yakuman>>, } impl Yakuman { pub fn new(name: &str, rule: Box<Fn(&Wait, &Vec<Tile>) -> u32>, sub: Option<Box<Yakuman>>) -> Self { Yakuman { name: name.to_string(), rule, sub } } } impl YakuAttributes for Yakuman { fn name(&self) -> String { self.name.to_string() } } }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fmt::Debug; use std::fmt::Display; use std::fmt::Formatter; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] pub struct Range { pub start: usize, pub end: usize, } pub type Span = Option<Range>; impl Debug for Range { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{}..{}", self.start, self.end) } } impl Display for Range { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{}..{}", self.start, self.end) } } impl From<Range> for std::ops::Range<usize> { fn from(range: Range) -> std::ops::Range<usize> { range.start..range.end } } impl From<std::ops::Range<usize>> for Range { fn from(range: std::ops::Range<usize>) -> Range { Range { start: range.start, end: range.end, } } } pub fn pretty_print_error(source: &str, labels: Vec<(Range, String)>) -> String { use codespan_reporting::diagnostic::Diagnostic; use codespan_reporting::diagnostic::Label; use codespan_reporting::files::SimpleFile; use codespan_reporting::term; use codespan_reporting::term::termcolor::Buffer; use codespan_reporting::term::Chars; use codespan_reporting::term::Config; let mut writer = Buffer::no_color(); let file = SimpleFile::new("SQL", source); let config = Config { chars: Chars::ascii(), before_label_lines: 3, ..Default::default() }; let labels = labels .into_iter() .enumerate() .map(|(i, (span, msg))| { if i == 0 { Label::primary((), span).with_message(msg) } else { Label::secondary((), span).with_message(msg) } }) .collect(); let diagnostic = Diagnostic::error().with_labels(labels); term::emit(&mut writer, &config, &file, &diagnostic).unwrap(); std::str::from_utf8(&writer.into_inner()) .unwrap() .to_string() }
enum SpreadsheetCell { Int(i32), Float(f32), Text(String), } fn main() { let vec: Vec<i32> = Vec::new(); let used_vec = vec![1, 2, 3]; let mut push_vec = Vec::new(); // It return error. if you not push some element. push_vec.push(1); { let vec_scope = vec![1, 2, 3]; let third: &i32 = &vec_scope[2]; let third_option: Option<&i32> = vec_scope.get(5); println!("{}", third); println!("{}", if let Some(element) = third_option { element } else { &0 }) } // free vec_scope and all elements let v1 = vec![1, 10 ,50]; for i in &v1 { println!("{}", i); } let mut v2 = vec![1, 2, 3]; for i in &mut v2 { *i *= 50; println!("{}", i); } let multi_type_vec = vec![ SpreadsheetCell::Int(10), SpreadsheetCell::Float(10.0), SpreadsheetCell::Text(String::from("it's cell")) ]; }
// The Look and Say sequence is an interesting sequence of numbers where each term is given by // describing the makeup of the previous term. // // The 1st term is given as 1. The 2nd term is 11 ('one one') because the first term (1) consisted // of a single 1. The 3rd term is then 21 ('two one') because the second term consisted of two 1s. // The first 6 terms are: // // 1 // 11 // 21 // 1211 // 111221 // 312211 use std::os::args; use std::io::stdio::stderr; fn gen_ls_sequence(seq: Vec<int>) -> Vec<int> { let mut ret: Vec<int> = vec![]; let mut last_num = seq[0]; let mut last_count = 0i; for num in seq.iter() { if last_num == *num { last_count += 1; } else { ret.push(last_count); ret.push(last_num); last_count = 1; last_num = *num; } } ret.push(last_count); ret.push(last_num); ret } fn looksay(num_iters: int) -> Vec<Vec<int>> { let mut last_seq = vec![1i]; let mut ret: Vec<Vec<int>> = vec![last_seq.clone()]; for i in range(0i, num_iters) { let cur_seq = gen_ls_sequence(last_seq); ret.push(cur_seq.clone()); last_seq = cur_seq; } ret } fn get_args() -> Result<int, &'static str> { match args().as_slice().slice(1, args().len()) { [] => Err("num_iters not supplied"), [ref n] => { match from_str::<int>(n.as_slice()) { Some(num_iters) => Ok(num_iters), None => Err("num_iters has incorrect type; int expected.") } }, [_, ..] => Err("too many parameters supplied"), } } fn print_looksay(res: Vec<Vec<int>>) { for seq in res.iter() { println!("{}", *seq); } } fn main() { match get_args() { Ok(num_iters) => { println!("{} iters will be taken.", num_iters); let res = looksay(num_iters); print_looksay(res); }, Err(msg) => { std::os::set_exit_status(1); stderr().write_line(format!("Error: {}", msg).as_slice()); } } }
use std::borrow::Cow; use std::cell::Cell; use std::convert::TryFrom; use std::ops::{Deref, Range}; use gccjit::{ BinaryOp, Block, ComparisonOp, Function, LValue, RValue, ToRValue, Type, UnaryOp, }; use rustc_codegen_ssa::MemFlags; use rustc_codegen_ssa::common::{AtomicOrdering, AtomicRmwBinOp, IntPredicate, RealPredicate, SynchronizationScope}; use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue}; use rustc_codegen_ssa::mir::place::PlaceRef; use rustc_codegen_ssa::traits::{ BackendTypes, BaseTypeMethods, BuilderMethods, ConstMethods, DerivedTypeMethods, HasCodegen, OverflowOp, StaticBuilderMethods, }; use rustc_middle::ty::{ParamEnv, Ty, TyCtxt}; use rustc_middle::ty::layout::{HasParamEnv, HasTyCtxt, TyAndLayout}; use rustc_span::Span; use rustc_span::def_id::DefId; use rustc_target::abi::{ self, Align, HasDataLayout, LayoutOf, Size, TargetDataLayout, }; use rustc_target::spec::{HasTargetSpec, Target}; use crate::common::{SignType, TypeReflection, type_is_pointer}; use crate::context::CodegenCx; use crate::type_of::LayoutGccExt; // TODO type Funclet = (); // TODO: remove this variable. static mut RETURN_VALUE_COUNT: usize = 0; enum ExtremumOperation { Max, Min, } trait EnumClone { fn clone(&self) -> Self; } impl EnumClone for AtomicOrdering { fn clone(&self) -> Self { match *self { AtomicOrdering::NotAtomic => AtomicOrdering::NotAtomic, AtomicOrdering::Unordered => AtomicOrdering::Unordered, AtomicOrdering::Monotonic => AtomicOrdering::Monotonic, AtomicOrdering::Acquire => AtomicOrdering::Acquire, AtomicOrdering::Release => AtomicOrdering::Release, AtomicOrdering::AcquireRelease => AtomicOrdering::AcquireRelease, AtomicOrdering::SequentiallyConsistent => AtomicOrdering::SequentiallyConsistent, } } } pub struct Builder<'a: 'gcc, 'gcc, 'tcx> { pub cx: &'a CodegenCx<'gcc, 'tcx>, pub block: Option<Block<'gcc>>, stack_var_count: Cell<usize>, } impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { fn with_cx(cx: &'a CodegenCx<'gcc, 'tcx>) -> Self { Builder { cx, block: None, stack_var_count: Cell::new(0), } } fn atomic_extremum(&mut self, operation: ExtremumOperation, dst: RValue<'gcc>, src: RValue<'gcc>, order: AtomicOrdering) -> RValue<'gcc> { let size = self.cx.int_width(src.get_type()) / 8; let func = self.current_func(); let load_ordering = match order { // TODO: does this make sense? AtomicOrdering::AcquireRelease | AtomicOrdering::Release => AtomicOrdering::Acquire, _ => order.clone(), }; let previous_value = self.atomic_load(dst, load_ordering.clone(), Size::from_bytes(size)); let previous_var = func.new_local(None, previous_value.get_type(), "previous_value"); let return_value = func.new_local(None, previous_value.get_type(), "return_value"); self.llbb().add_assignment(None, previous_var, previous_value); self.llbb().add_assignment(None, return_value, previous_var.to_rvalue()); let while_block = func.new_block("while"); let after_block = func.new_block("after_while"); self.llbb().end_with_jump(None, while_block); // NOTE: since jumps were added and compare_exchange doesn't expect this, the current blocks in the // state need to be updated. self.block = Some(while_block); *self.cx.current_block.borrow_mut() = Some(while_block); let comparison_operator = match operation { ExtremumOperation::Max => ComparisonOp::LessThan, ExtremumOperation::Min => ComparisonOp::GreaterThan, }; let cond1 = self.context.new_comparison(None, comparison_operator, previous_var.to_rvalue(), self.context.new_cast(None, src, previous_value.get_type())); let compare_exchange = self.compare_exchange(dst, previous_var, src, order, load_ordering, false); let cond2 = self.cx.context.new_unary_op(None, UnaryOp::LogicalNegate, compare_exchange.get_type(), compare_exchange); let cond = self.cx.context.new_binary_op(None, BinaryOp::LogicalAnd, self.cx.bool_type, cond1, cond2); while_block.end_with_conditional(None, cond, while_block, after_block); // NOTE: since jumps were added in a place rustc does not expect, the current blocks in the // state need to be updated. self.block = Some(after_block); *self.cx.current_block.borrow_mut() = Some(after_block); return_value.to_rvalue() } fn compare_exchange(&self, dst: RValue<'gcc>, cmp: LValue<'gcc>, src: RValue<'gcc>, order: AtomicOrdering, failure_order: AtomicOrdering, weak: bool) -> RValue<'gcc> { let size = self.cx.int_width(src.get_type()); let compare_exchange = self.context.get_builtin_function(&format!("__atomic_compare_exchange_{}", size / 8)); let order = self.context.new_rvalue_from_int(self.i32_type, order.to_gcc()); let failure_order = self.context.new_rvalue_from_int(self.i32_type, failure_order.to_gcc()); let weak = self.context.new_rvalue_from_int(self.bool_type, weak as i32); let void_ptr_type = self.context.new_type::<*mut ()>(); let volatile_void_ptr_type = void_ptr_type.make_volatile(); let dst = self.context.new_cast(None, dst, volatile_void_ptr_type); let expected = self.context.new_cast(None, cmp.get_address(None), void_ptr_type); // NOTE: not sure why, but we have the wrong type here. let int_type = compare_exchange.get_param(2).to_rvalue().get_type(); let src = self.context.new_cast(None, src, int_type); self.context.new_call(None, compare_exchange, &[dst, expected, src, weak, order, failure_order]) } pub fn assign(&self, lvalue: LValue<'gcc>, value: RValue<'gcc>) { self.llbb().add_assignment(None, lvalue, value); } fn assign_op(&self, lvalue: LValue<'gcc>, binary_op: BinaryOp, value: RValue<'gcc>) { self.block.expect("block").add_assignment_op(None, lvalue, binary_op, value); } fn check_call<'b>(&mut self, typ: &str, func: Function<'gcc>, args: &'b [RValue<'gcc>]) -> Cow<'b, [RValue<'gcc>]> { //let mut fn_ty = self.cx.val_ty(func); // Strip off pointers /*while self.cx.type_kind(fn_ty) == TypeKind::Pointer { fn_ty = self.cx.element_type(fn_ty); }*/ /*assert!( self.cx.type_kind(fn_ty) == TypeKind::Function, "builder::{} not passed a function, but {:?}", typ, fn_ty ); let param_tys = self.cx.func_params_types(fn_ty); let all_args_match = param_tys .iter() .zip(args.iter().map(|&v| self.val_ty(v))) .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);*/ let mut all_args_match = true; let mut param_types = vec![]; let param_count = func.get_param_count(); for (index, arg) in args.iter().enumerate().take(param_count) { let param = func.get_param(index as i32); let param = param.to_rvalue().get_type(); if param != arg.get_type() { all_args_match = false; } param_types.push(param); } if all_args_match { return Cow::Borrowed(args); } let casted_args: Vec<_> = param_types .into_iter() .zip(args.iter()) .enumerate() .map(|(i, (expected_ty, &actual_val))| { let actual_ty = actual_val.get_type(); if expected_ty != actual_ty { /*debug!( "type mismatch in function call of {:?}. \ Expected {:?} for param {}, got {:?}; injecting bitcast", func, expected_ty, i, actual_ty );*/ /*println!( "type mismatch in function call of {:?}. \ Expected {:?} for param {}, got {:?}; injecting bitcast", func, expected_ty, i, actual_ty );*/ self.bitcast(actual_val, expected_ty) } else { actual_val } }) .collect(); Cow::Owned(casted_args) } fn check_ptr_call<'b>(&mut self, typ: &str, func_ptr: RValue<'gcc>, args: &'b [RValue<'gcc>]) -> Cow<'b, [RValue<'gcc>]> { //let mut fn_ty = self.cx.val_ty(func); // Strip off pointers /*while self.cx.type_kind(fn_ty) == TypeKind::Pointer { fn_ty = self.cx.element_type(fn_ty); }*/ /*assert!( self.cx.type_kind(fn_ty) == TypeKind::Function, "builder::{} not passed a function, but {:?}", typ, fn_ty ); let param_tys = self.cx.func_params_types(fn_ty); let all_args_match = param_tys .iter() .zip(args.iter().map(|&v| self.val_ty(v))) .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);*/ let mut all_args_match = true; let mut param_types = vec![]; let gcc_func = func_ptr.get_type().is_function_ptr_type().expect("function ptr"); for (index, arg) in args.iter().enumerate().take(gcc_func.get_param_count()) { let param = gcc_func.get_param_type(index); if param != arg.get_type() { all_args_match = false; } param_types.push(param); } if all_args_match { return Cow::Borrowed(args); } let casted_args: Vec<_> = param_types .into_iter() .zip(args.iter()) .enumerate() .map(|(i, (expected_ty, &actual_val))| { let actual_ty = actual_val.get_type(); if expected_ty != actual_ty { /*debug!( "type mismatch in function call of {:?}. \ Expected {:?} for param {}, got {:?}; injecting bitcast", func, expected_ty, i, actual_ty );*/ /*println!( "type mismatch in function call of {:?}. \ Expected {:?} for param {}, got {:?}; injecting bitcast", func, expected_ty, i, actual_ty );*/ self.bitcast(actual_val, expected_ty) } else { actual_val } }) .collect(); Cow::Owned(casted_args) } fn check_store(&mut self, val: RValue<'gcc>, ptr: RValue<'gcc>) -> RValue<'gcc> { let dest_ptr_ty = self.cx.val_ty(ptr).make_pointer(); // TODO: make sure make_pointer() is okay here. let stored_ty = self.cx.val_ty(val); let stored_ptr_ty = self.cx.type_ptr_to(stored_ty); //assert_eq!(self.cx.type_kind(dest_ptr_ty), TypeKind::Pointer); if dest_ptr_ty == stored_ptr_ty { ptr } else { /*debug!( "type mismatch in store. \ Expected {:?}, got {:?}; inserting bitcast", dest_ptr_ty, stored_ptr_ty );*/ /*println!( "type mismatch in store. \ Expected {:?}, got {:?}; inserting bitcast", dest_ptr_ty, stored_ptr_ty );*/ //ptr self.bitcast(ptr, stored_ptr_ty) } } pub fn current_func(&self) -> Function<'gcc> { self.block.expect("block").get_function() } fn function_call(&mut self, func: RValue<'gcc>, args: &[RValue<'gcc>], funclet: Option<&Funclet>) -> RValue<'gcc> { //debug!("call {:?} with args ({:?})", func, args); // TODO: remove when the API supports a different type for functions. let func: Function<'gcc> = self.cx.rvalue_as_function(func); let args = self.check_call("call", func, args); //let bundle = funclet.map(|funclet| funclet.bundle()); //let bundle = bundle.as_ref().map(|b| &*b.raw); // gccjit requires to use the result of functions, even when it's not used. // That's why we assign the result to a local or call add_eval(). let return_type = func.get_return_type(); let current_block = self.current_block.borrow().expect("block"); let void_type = self.context.new_type::<()>(); let current_func = current_block.get_function(); if return_type != void_type { unsafe { RETURN_VALUE_COUNT += 1 }; let result = current_func.new_local(None, return_type, &format!("returnValue{}", unsafe { RETURN_VALUE_COUNT })); current_block.add_assignment(None, result, self.cx.context.new_call(None, func, &args)); result.to_rvalue() } else { current_block.add_eval(None, self.cx.context.new_call(None, func, &args)); // Return dummy value when not having return value. self.context.new_rvalue_from_long(self.isize_type, 0) } } fn function_ptr_call(&mut self, func_ptr: RValue<'gcc>, args: &[RValue<'gcc>], funclet: Option<&Funclet>) -> RValue<'gcc> { //debug!("func ptr call {:?} with args ({:?})", func, args); let args = self.check_ptr_call("call", func_ptr, args); //let bundle = funclet.map(|funclet| funclet.bundle()); //let bundle = bundle.as_ref().map(|b| &*b.raw); // gccjit requires to use the result of functions, even when it's not used. // That's why we assign the result to a local or call add_eval(). let gcc_func = func_ptr.get_type().is_function_ptr_type().expect("function ptr"); let return_type = gcc_func.get_return_type(); let current_block = self.current_block.borrow().expect("block"); let void_type = self.context.new_type::<()>(); let current_func = current_block.get_function(); if return_type != void_type { unsafe { RETURN_VALUE_COUNT += 1 }; let result = current_func.new_local(None, return_type, &format!("returnValue{}", unsafe { RETURN_VALUE_COUNT })); current_block.add_assignment(None, result, self.cx.context.new_call_through_ptr(None, func_ptr, &args)); result.to_rvalue() } else { if gcc_func.get_param_count() == 0 { // As a temporary workaround for unsupported LLVM intrinsics. current_block.add_eval(None, self.cx.context.new_call_through_ptr(None, func_ptr, &[])); } else { current_block.add_eval(None, self.cx.context.new_call_through_ptr(None, func_ptr, &args)); } // Return dummy value when not having return value. self.context.new_rvalue_from_long(self.isize_type, 0) } } pub fn overflow_call(&mut self, func: Function<'gcc>, args: &[RValue<'gcc>], funclet: Option<&Funclet>) -> RValue<'gcc> { //debug!("overflow_call {:?} with args ({:?})", func, args); //let bundle = funclet.map(|funclet| funclet.bundle()); //let bundle = bundle.as_ref().map(|b| &*b.raw); // gccjit requires to use the result of functions, even when it's not used. // That's why we assign the result to a local. let return_type = self.context.new_type::<bool>(); let current_block = self.current_block.borrow().expect("block"); let current_func = current_block.get_function(); // TODO: return the new_call() directly? Since the overflow function has no side-effects. unsafe { RETURN_VALUE_COUNT += 1 }; let result = current_func.new_local(None, return_type, &format!("returnValue{}", unsafe { RETURN_VALUE_COUNT })); current_block.add_assignment(None, result, self.cx.context.new_call(None, func, &args)); result.to_rvalue() } } impl<'gcc, 'tcx> HasCodegen<'tcx> for Builder<'_, 'gcc, 'tcx> { type CodegenCx = CodegenCx<'gcc, 'tcx>; } impl<'tcx> HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> { fn tcx(&self) -> TyCtxt<'tcx> { self.cx.tcx() } } impl HasDataLayout for Builder<'_, '_, '_> { fn data_layout(&self) -> &TargetDataLayout { self.cx.data_layout() } } impl<'tcx> LayoutOf for Builder<'_, '_, 'tcx> { type Ty = Ty<'tcx>; type TyAndLayout = TyAndLayout<'tcx>; fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout { self.cx.layout_of(ty) } } impl<'gcc, 'tcx> Deref for Builder<'_, 'gcc, 'tcx> { type Target = CodegenCx<'gcc, 'tcx>; fn deref(&self) -> &Self::Target { self.cx } } impl<'gcc, 'tcx> BackendTypes for Builder<'_, 'gcc, 'tcx> { type Value = <CodegenCx<'gcc, 'tcx> as BackendTypes>::Value; type Function = <CodegenCx<'gcc, 'tcx> as BackendTypes>::Function; type BasicBlock = <CodegenCx<'gcc, 'tcx> as BackendTypes>::BasicBlock; type Type = <CodegenCx<'gcc, 'tcx> as BackendTypes>::Type; type Funclet = <CodegenCx<'gcc, 'tcx> as BackendTypes>::Funclet; type DIScope = <CodegenCx<'gcc, 'tcx> as BackendTypes>::DIScope; type DILocation = <CodegenCx<'gcc, 'tcx> as BackendTypes>::DILocation; type DIVariable = <CodegenCx<'gcc, 'tcx> as BackendTypes>::DIVariable; } impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { fn build(cx: &'a CodegenCx<'gcc, 'tcx>, block: Block<'gcc>) -> Self { let mut bx = Builder::with_cx(cx); *cx.current_block.borrow_mut() = Some(block); bx.block = Some(block); bx } fn build_sibling_block(&mut self, name: &str) -> Self { let block = self.append_sibling_block(name); Self::build(self.cx, block) } fn llbb(&self) -> Block<'gcc> { self.block.expect("block") } fn append_block(cx: &'a CodegenCx<'gcc, 'tcx>, func: RValue<'gcc>, name: &str) -> Block<'gcc> { let func = cx.rvalue_as_function(func); func.new_block(name) } fn append_sibling_block(&mut self, name: &str) -> Block<'gcc> { let func = self.current_func(); func.new_block(name) } fn ret_void(&mut self) { self.llbb().end_with_void_return(None) } fn ret(&mut self, value: RValue<'gcc>) { let value = if self.structs_as_pointer.borrow().contains(&value) { // NOTE: hack to workaround a limitation of the rustc API: see comment on // CodegenCx.structs_as_pointer value.dereference(None).to_rvalue() } else { value }; self.llbb().end_with_return(None, value); } fn br(&mut self, dest: Block<'gcc>) { self.llbb().end_with_jump(None, dest) } fn cond_br(&mut self, cond: RValue<'gcc>, then_block: Block<'gcc>, else_block: Block<'gcc>) { self.llbb().end_with_conditional(None, cond, then_block, else_block) } fn switch(&mut self, value: RValue<'gcc>, default_block: Block<'gcc>, cases: impl ExactSizeIterator<Item = (u128, Block<'gcc>)>) { let mut gcc_cases = vec![]; let typ = self.val_ty(value); for (on_val, dest) in cases { let on_val = self.const_uint_big(typ, on_val); gcc_cases.push(self.context.new_case(on_val, on_val, dest)); } self.block.expect("block").end_with_switch(None, value, default_block, &gcc_cases); } fn invoke(&mut self, func: RValue<'gcc>, args: &[RValue<'gcc>], then: Block<'gcc>, catch: Block<'gcc>, funclet: Option<&Funclet>) -> RValue<'gcc> { unimplemented!(); /*debug!("invoke {:?} with args ({:?})", func, args); let args = self.check_call("invoke", func, args); let bundle = funclet.map(|funclet| funclet.bundle()); let bundle = bundle.as_ref().map(|b| &*b.raw); unsafe { llvm::LLVMRustBuildInvoke( self.llbuilder, func, args.as_ptr(), args.len() as c_uint, then, catch, bundle, UNNAMED, ) }*/ } fn unreachable(&mut self) { let func = self.context.get_builtin_function("__builtin_unreachable"); let block = self.block.expect("block"); block.add_eval(None, self.context.new_call(None, func, &[])); let return_type = block.get_function().get_return_type(); let void_type = self.context.new_type::<()>(); if return_type == void_type { block.end_with_void_return(None) } else { let return_value = self.current_func() .new_local(None, return_type, "unreachableReturn"); block.end_with_return(None, return_value) } } fn add(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { a + b } fn fadd(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { a + b } fn sub(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { a - b } fn fsub(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { a - b } fn mul(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { a * b } fn fmul(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { a * b } fn udiv(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { // TODO: convert the arguments to unsigned? a / b } fn exactudiv(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { // TODO: convert the arguments to unsigned? // TODO: poison if not exact. a / b } fn sdiv(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { // TODO: convert the arguments to signed? a / b } fn exactsdiv(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { // TODO: posion if not exact. // FIXME: rustc_codegen_ssa::mir::intrinsic uses different types for a and b but they // should be the same. let typ = a.get_type().to_signed(self); let a = self.context.new_cast(None, a, typ); let b = self.context.new_cast(None, b, typ); a / b } fn fdiv(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { a / b } fn urem(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { a % b } fn srem(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { a % b } fn frem(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { if a.get_type() == self.cx.float_type { let fmodf = self.context.get_builtin_function("fmodf"); // FIXME: this seems to produce the wrong result. return self.context.new_call(None, fmodf, &[a, b]); } assert_eq!(a.get_type(), self.cx.double_type); let fmod = self.context.get_builtin_function("fmod"); return self.context.new_call(None, fmod, &[a, b]); } fn shl(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { // FIXME: remove the casts when libgccjit can shift an unsigned number by an unsigned number. let a_type = a.get_type(); let b_type = b.get_type(); if a_type.is_unsigned(self) && b_type.is_signed(self) { //println!("shl: {:?} -> {:?}", a, b_type); let a = self.context.new_cast(None, a, b_type); let result = a << b; //println!("shl: {:?} -> {:?}", result, a_type); self.context.new_cast(None, result, a_type) } else if a_type.is_signed(self) && b_type.is_unsigned(self) { //println!("shl: {:?} -> {:?}", b, a_type); let b = self.context.new_cast(None, b, a_type); a << b } else { a << b } } fn lshr(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { // FIXME: remove the casts when libgccjit can shift an unsigned number by an unsigned number. // TODO: cast to unsigned to do a logical shift if that does not work. let a_type = a.get_type(); let b_type = b.get_type(); if a_type.is_unsigned(self) && b_type.is_signed(self) { //println!("lshl: {:?} -> {:?}", a, b_type); let a = self.context.new_cast(None, a, b_type); let result = a >> b; //println!("lshl: {:?} -> {:?}", result, a_type); self.context.new_cast(None, result, a_type) } else if a_type.is_signed(self) && b_type.is_unsigned(self) { //println!("lshl: {:?} -> {:?}", b, a_type); let b = self.context.new_cast(None, b, a_type); a >> b } else { a >> b } } fn ashr(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { // TODO: check whether behavior is an arithmetic shift for >> . // FIXME: remove the casts when libgccjit can shift an unsigned number by an unsigned number. let a_type = a.get_type(); let b_type = b.get_type(); if a_type.is_unsigned(self) && b_type.is_signed(self) { //println!("ashl: {:?} -> {:?}", a, b_type); let a = self.context.new_cast(None, a, b_type); let result = a >> b; //println!("ashl: {:?} -> {:?}", result, a_type); self.context.new_cast(None, result, a_type) } else if a_type.is_signed(self) && b_type.is_unsigned(self) { //println!("ashl: {:?} -> {:?}", b, a_type); let b = self.context.new_cast(None, b, a_type); a >> b } else { a >> b } } fn and(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { // FIXME: hack by putting the result in a variable to workaround this bug: // https://gcc.gnu.org/bugzilla//show_bug.cgi?id=95498 let res = self.current_func().new_local(None, b.get_type(), "andResult"); self.llbb().add_assignment(None, res, a & b); res.to_rvalue() } fn or(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { // FIXME: hack by putting the result in a variable to workaround this bug: // https://gcc.gnu.org/bugzilla//show_bug.cgi?id=95498 let res = self.current_func().new_local(None, b.get_type(), "orResult"); self.llbb().add_assignment(None, res, a | b); res.to_rvalue() } fn xor(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { a ^ b } fn neg(&mut self, a: RValue<'gcc>) -> RValue<'gcc> { // TODO: use new_unary_op()? self.cx.context.new_rvalue_from_long(a.get_type(), 0) - a } fn fneg(&mut self, a: RValue<'gcc>) -> RValue<'gcc> { self.cx.context.new_unary_op(None, UnaryOp::Minus, a.get_type(), a) } fn not(&mut self, a: RValue<'gcc>) -> RValue<'gcc> { let operation = if a.get_type().is_bool() { UnaryOp::LogicalNegate } else { UnaryOp::BitwiseNegate }; self.cx.context.new_unary_op(None, operation, a.get_type(), a) } fn unchecked_sadd(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { a + b } fn unchecked_uadd(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { a + b } fn unchecked_ssub(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { a - b } fn unchecked_usub(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { // TODO: should generate poison value? a - b } fn unchecked_smul(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { a * b } fn unchecked_umul(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { a * b } fn fadd_fast(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> { unimplemented!(); /*unsafe { let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, UNNAMED); llvm::LLVMRustSetHasUnsafeAlgebra(instr); instr }*/ } fn fsub_fast(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> { unimplemented!(); /*unsafe { let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, UNNAMED); llvm::LLVMRustSetHasUnsafeAlgebra(instr); instr }*/ } fn fmul_fast(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> { unimplemented!(); /*unsafe { let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, UNNAMED); llvm::LLVMRustSetHasUnsafeAlgebra(instr); instr }*/ } fn fdiv_fast(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> { unimplemented!(); /*unsafe { let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, UNNAMED); llvm::LLVMRustSetHasUnsafeAlgebra(instr); instr }*/ } fn frem_fast(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> { unimplemented!(); /*unsafe { let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, UNNAMED); llvm::LLVMRustSetHasUnsafeAlgebra(instr); instr }*/ } fn checked_binop(&mut self, oop: OverflowOp, typ: Ty<'_>, lhs: Self::Value, rhs: Self::Value) -> (Self::Value, Self::Value) { use rustc_middle::ty::{Int, IntTy::*, Uint, UintTy::*}; let new_kind = match typ.kind() { Int(t @ Isize) => Int(t.normalize(self.tcx.sess.target.pointer_width)), Uint(t @ Usize) => Uint(t.normalize(self.tcx.sess.target.pointer_width)), t @ (Uint(_) | Int(_)) => t.clone(), _ => panic!("tried to get overflow intrinsic for op applied to non-int type"), }; // TODO: remove duplication with intrinsic? let name = match oop { OverflowOp::Add => match new_kind { Int(I8) => "__builtin_add_overflow", Int(I16) => "__builtin_add_overflow", Int(I32) => "__builtin_sadd_overflow", Int(I64) => "__builtin_saddll_overflow", Int(I128) => "__builtin_add_overflow", Uint(U8) => "__builtin_add_overflow", Uint(U16) => "__builtin_add_overflow", Uint(U32) => "__builtin_uadd_overflow", Uint(U64) => "__builtin_uaddll_overflow", Uint(U128) => "__builtin_add_overflow", _ => unreachable!(), }, OverflowOp::Sub => match new_kind { Int(I8) => "__builtin_sub_overflow", Int(I16) => "__builtin_sub_overflow", Int(I32) => "__builtin_ssub_overflow", Int(I64) => "__builtin_ssubll_overflow", Int(I128) => "__builtin_sub_overflow", Uint(U8) => "__builtin_sub_overflow", Uint(U16) => "__builtin_sub_overflow", Uint(U32) => "__builtin_usub_overflow", Uint(U64) => "__builtin_usubll_overflow", Uint(U128) => "__builtin_sub_overflow", _ => unreachable!(), }, OverflowOp::Mul => match new_kind { Int(I8) => "__builtin_mul_overflow", Int(I16) => "__builtin_mul_overflow", Int(I32) => "__builtin_smul_overflow", Int(I64) => "__builtin_smulll_overflow", Int(I128) => "__builtin_mul_overflow", Uint(U8) => "__builtin_mul_overflow", Uint(U16) => "__builtin_mul_overflow", Uint(U32) => "__builtin_umul_overflow", Uint(U64) => "__builtin_umulll_overflow", Uint(U128) => "__builtin_mul_overflow", _ => unreachable!(), }, }; let intrinsic = self.context.get_builtin_function(&name); let res = self.current_func() // TODO: is it correct to use rhs type instead of the parameter typ? .new_local(None, rhs.get_type(), "binopResult") .get_address(None); let overflow = self.overflow_call(intrinsic, &[lhs, rhs, res], None); (res.dereference(None).to_rvalue(), overflow) } fn alloca(&mut self, ty: Type<'gcc>, align: Align) -> RValue<'gcc> { // FIXME: this check that we don't call get_aligned() a second time on a time. // Ideally, we shouldn't need to do this check. let aligned_type = if ty == self.cx.u128_type || ty == self.cx.i128_type { ty } else { ty.get_aligned(align.bytes()) }; // TODO: It might be better to return a LValue, but fixing the rustc API is non-trivial. self.stack_var_count.set(self.stack_var_count.get() + 1); self.current_func().new_local(None, aligned_type, &format!("stack_var_{}", self.stack_var_count.get())).get_address(None) } fn dynamic_alloca(&mut self, ty: Type<'gcc>, align: Align) -> RValue<'gcc> { unimplemented!(); /*unsafe { let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED); llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint); alloca }*/ } fn array_alloca(&mut self, ty: Type<'gcc>, len: RValue<'gcc>, align: Align) -> RValue<'gcc> { unimplemented!(); /*unsafe { let alloca = llvm::LLVMBuildArrayAlloca(self.llbuilder, ty, len, UNNAMED); llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint); alloca }*/ } fn load(&mut self, ptr: RValue<'gcc>, align: Align) -> RValue<'gcc> { let block = self.llbb(); let function = block.get_function(); // NOTE: instead of returning the dereference here, we have to assign it to a variable in // the current basic block. Otherwise, it could be used in another basic block, causing a // dereference after a drop, for instance. // TODO: handle align. let deref = ptr.dereference(None).to_rvalue(); let value_type = deref.get_type(); unsafe { RETURN_VALUE_COUNT += 1 }; let loaded_value = function.new_local(None, value_type, &format!("loadedValue{}", unsafe { RETURN_VALUE_COUNT })); block.add_assignment(None, loaded_value, deref); loaded_value.to_rvalue() } fn volatile_load(&mut self, ptr: RValue<'gcc>) -> RValue<'gcc> { //println!("5: volatile load: {:?} to {:?}", ptr, ptr.get_type().make_volatile()); let ptr = self.context.new_cast(None, ptr, ptr.get_type().make_volatile()); //println!("6"); ptr.dereference(None).to_rvalue() } fn atomic_load(&mut self, ptr: RValue<'gcc>, order: AtomicOrdering, size: Size) -> RValue<'gcc> { // TODO: handle alignment. let atomic_load = self.context.get_builtin_function(&format!("__atomic_load_{}", size.bytes())); let ordering = self.context.new_rvalue_from_int(self.i32_type, order.to_gcc()); let volatile_const_void_ptr_type = self.context.new_type::<*mut ()>().make_const().make_volatile(); let ptr = self.context.new_cast(None, ptr, volatile_const_void_ptr_type); self.context.new_call(None, atomic_load, &[ptr, ordering]) } fn load_operand(&mut self, place: PlaceRef<'tcx, RValue<'gcc>>) -> OperandRef<'tcx, RValue<'gcc>> { //debug!("PlaceRef::load: {:?}", place); assert_eq!(place.llextra.is_some(), place.layout.is_unsized()); if place.layout.is_zst() { return OperandRef::new_zst(self, place.layout); } fn scalar_load_metadata<'a, 'gcc, 'tcx>(bx: &mut Builder<'a, 'gcc, 'tcx>, load: RValue<'gcc>, scalar: &abi::Scalar) { let vr = scalar.valid_range.clone(); match scalar.value { abi::Int(..) => { let range = scalar.valid_range_exclusive(bx); if range.start != range.end { bx.range_metadata(load, range); } } abi::Pointer if vr.start() < vr.end() && !vr.contains(&0) => { bx.nonnull_metadata(load); } _ => {} } } let val = if let Some(llextra) = place.llextra { OperandValue::Ref(place.llval, Some(llextra), place.align) } else if place.layout.is_gcc_immediate() { let mut const_llval = None; /*unsafe { if let Some(global) = llvm::LLVMIsAGlobalVariable(place.llval) { if llvm::LLVMIsGlobalConstant(global) == llvm::True { const_llval = llvm::LLVMGetInitializer(global); } } }*/ let llval = const_llval.unwrap_or_else(|| { let load = self.load(place.llval, place.align); if let abi::Abi::Scalar(ref scalar) = place.layout.abi { scalar_load_metadata(self, load, scalar); } load }); OperandValue::Immediate(self.to_immediate(llval, place.layout)) } else if let abi::Abi::ScalarPair(ref a, ref b) = place.layout.abi { let b_offset = a.value.size(self).align_to(b.value.align(self).abi); let mut load = |i, scalar: &abi::Scalar, align| { let llptr = self.struct_gep(place.llval, i as u64); let load = self.load(llptr, align); scalar_load_metadata(self, load, scalar); if scalar.is_bool() { self.trunc(load, self.type_i1()) } else { load } }; OperandValue::Pair( load(0, a, place.align), load(1, b, place.align.restrict_for_offset(b_offset)), ) } else { OperandValue::Ref(place.llval, None, place.align) }; OperandRef { val, layout: place.layout } } fn write_operand_repeatedly(mut self, cg_elem: OperandRef<'tcx, RValue<'gcc>>, count: u64, dest: PlaceRef<'tcx, RValue<'gcc>>) -> Self { let zero = self.const_usize(0); let count = self.const_usize(count); let start = dest.project_index(&mut self, zero).llval; let end = dest.project_index(&mut self, count).llval; let mut header_bx = self.build_sibling_block("repeat_loop_header"); let mut body_bx = self.build_sibling_block("repeat_loop_body"); let next_bx = self.build_sibling_block("repeat_loop_next"); let ptr_type = start.get_type(); let current = self.llbb().get_function().new_local(None, ptr_type, "loop_var"); let current_val = current.to_rvalue(); self.assign(current, start); self.br(header_bx.llbb()); let keep_going = header_bx.icmp(IntPredicate::IntNE, current_val, end); header_bx.cond_br(keep_going, body_bx.llbb(), next_bx.llbb()); let align = dest.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size); cg_elem.val.store(&mut body_bx, PlaceRef::new_sized_aligned(current_val, cg_elem.layout, align)); let next = body_bx.inbounds_gep(current.to_rvalue(), &[self.const_usize(1)]); body_bx.llbb().add_assignment(None, current, next); body_bx.br(header_bx.llbb()); next_bx } fn range_metadata(&mut self, load: RValue<'gcc>, range: Range<u128>) { // TODO /*if self.sess().target.target.arch == "amdgpu" { // amdgpu/LLVM does something weird and thinks a i64 value is // split into a v2i32, halving the bitwidth LLVM expects, // tripping an assertion. So, for now, just disable this // optimization. return; } unsafe { let llty = self.cx.val_ty(load); let v = [ self.cx.const_uint_big(llty, range.start), self.cx.const_uint_big(llty, range.end), ]; llvm::LLVMSetMetadata( load, llvm::MD_range as c_uint, llvm::LLVMMDNodeInContext(self.cx.llcx, v.as_ptr(), v.len() as c_uint), ); }*/ } fn nonnull_metadata(&mut self, load: RValue<'gcc>) { // TODO /*unsafe { llvm::LLVMSetMetadata( load, llvm::MD_nonnull as c_uint, llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0), ); }*/ } fn store(&mut self, val: RValue<'gcc>, ptr: RValue<'gcc>, align: Align) -> RValue<'gcc> { self.store_with_flags(val, ptr, align, MemFlags::empty()) } fn store_with_flags(&mut self, val: RValue<'gcc>, ptr: RValue<'gcc>, align: Align, flags: MemFlags) -> RValue<'gcc> { //debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags); let ptr = self.check_store(val, ptr); self.llbb().add_assignment(None, ptr.dereference(None), val); /*let align = if flags.contains(MemFlags::UNALIGNED) { 1 } else { align.bytes() as c_uint }; llvm::LLVMSetAlignment(store, align); if flags.contains(MemFlags::VOLATILE) { llvm::LLVMSetVolatile(store, llvm::True); } if flags.contains(MemFlags::NONTEMPORAL) { // According to LLVM [1] building a nontemporal store must // *always* point to a metadata value of the integer 1. // // [1]: http://llvm.org/docs/LangRef.html#store-instruction let one = self.cx.const_i32(1); let node = llvm::LLVMMDNodeInContext(self.cx.llcx, &one, 1); llvm::LLVMSetMetadata(store, llvm::MD_nontemporal as c_uint, node); }*/ // NOTE: dummy value here since it's never used. FIXME: API should not return a value here? self.cx.context.new_rvalue_zero(self.type_i32()) } fn atomic_store(&mut self, value: RValue<'gcc>, ptr: RValue<'gcc>, order: AtomicOrdering, size: Size) { // TODO: handle alignment. let atomic_store = self.context.get_builtin_function(&format!("__atomic_store_{}", size.bytes())); let ordering = self.context.new_rvalue_from_int(self.i32_type, order.to_gcc()); let volatile_const_void_ptr_type = self.context.new_type::<*mut ()>().make_const().make_volatile(); let ptr = self.context.new_cast(None, ptr, volatile_const_void_ptr_type); // FIXME: fix libgccjit to allow comparing an integer type with an aligned integer type because // the following cast is required to avoid this error: // gcc_jit_context_new_call: mismatching types for argument 2 of function "__atomic_store_4": assignment to param arg1 (type: int) from loadedValue3577 (type: unsigned int __attribute__((aligned(4)))) let int_type = atomic_store.get_param(1).to_rvalue().get_type(); let value = self.context.new_cast(None, value, int_type); self.llbb() .add_eval(None, self.context.new_call(None, atomic_store, &[ptr, value, ordering])); } fn gep(&mut self, ptr: RValue<'gcc>, indices: &[RValue<'gcc>]) -> RValue<'gcc> { let mut result = ptr; for index in indices { result = self.context.new_array_access(None, result, *index).get_address(None).to_rvalue(); } result } fn inbounds_gep(&mut self, ptr: RValue<'gcc>, indices: &[RValue<'gcc>]) -> RValue<'gcc> { // FIXME: would be safer if doing the same thing (loop) as gep. // TODO: specify inbounds somehow. match indices.len() { 1 => { self.context.new_array_access(None, ptr, indices[0]).get_address(None) }, 2 => { let array = ptr.dereference(None); // TODO: assert that first index is 0? self.context.new_array_access(None, array, indices[1]).get_address(None) }, _ => unimplemented!(), } } fn struct_gep(&mut self, ptr: RValue<'gcc>, idx: u64) -> RValue<'gcc> { // FIXME: it would be better if the API only called this on struct, not on arrays. assert_eq!(idx as usize as u64, idx); let value = ptr.dereference(None).to_rvalue(); let value_type = value.get_type(); if value_type.is_array() { let index = self.context.new_rvalue_from_long(self.u64_type, i64::try_from(idx).expect("i64::try_from")); let element = self.context.new_array_access(None, value, index); element.get_address(None) } else if let Some(vector_type) = value_type.is_vector() { let count = vector_type.get_num_units(); let element_type = vector_type.get_element_type(); let indexes = vec![self.context.new_rvalue_from_long(element_type, i64::try_from(idx).expect("i64::try_from")); count as usize]; let indexes = self.context.new_rvalue_from_vector(None, value_type, &indexes); let variable = self.current_func.borrow().expect("func") .new_local(None, value_type, "vectorVar"); self.current_block.borrow().expect("block") .add_assignment(None, variable, value + indexes); variable.get_address(None) } else if let Some(struct_type) = value_type.is_struct() { ptr.dereference_field(None, struct_type.get_field(idx as i32)).get_address(None) } else { panic!("Unexpected type {:?}", value_type); } } /* Casts */ fn trunc(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> { // TODO: check that it indeed truncate the value. //println!("trunc: {:?} -> {:?}", value, dest_ty); self.context.new_cast(None, value, dest_ty) } fn sext(&mut self, val: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> { unimplemented!(); //unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) } } fn fptoui(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> { //println!("7: fptoui: {:?} to {:?}", value, dest_ty); let ret = self.context.new_cast(None, value, dest_ty); //println!("8"); ret //unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) } } fn fptosi(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> { self.context.new_cast(None, value, dest_ty) } fn uitofp(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> { //println!("1: uitofp: {:?} -> {:?}", value, dest_ty); let ret = self.context.new_cast(None, value, dest_ty); //println!("2"); ret } fn sitofp(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> { //println!("3: sitofp: {:?} -> {:?}", value, dest_ty); let ret = self.context.new_cast(None, value, dest_ty); //println!("4"); ret } fn fptrunc(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> { // TODO: make sure it trancates. self.context.new_cast(None, value, dest_ty) } fn fpext(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> { self.context.new_cast(None, value, dest_ty) } fn ptrtoint(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> { self.cx.ptrtoint(self.block.expect("block"), value, dest_ty) } fn inttoptr(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> { self.cx.inttoptr(self.block.expect("block"), value, dest_ty) } fn bitcast(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> { self.cx.const_bitcast(value, dest_ty) } fn intcast(&mut self, value: RValue<'gcc>, dest_typ: Type<'gcc>, is_signed: bool) -> RValue<'gcc> { // NOTE: is_signed is for value, not dest_typ. //println!("intcast: {:?} ({:?}) -> {:?}", value, value.get_type(), dest_typ); self.cx.context.new_cast(None, value, dest_typ) } fn pointercast(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> { //println!("pointercast: {:?} ({:?}) -> {:?}", value, value.get_type(), dest_ty); let val_type = value.get_type(); match (type_is_pointer(val_type), type_is_pointer(dest_ty)) { (false, true) => { // NOTE: Projecting a field of a pointer type will attemp a cast from a signed char to // a pointer, which is not supported by gccjit. return self.cx.context.new_cast(None, self.inttoptr(value, val_type.make_pointer()), dest_ty); }, (false, false) => { // When they are not pointers, we want a transmute (or reinterpret_cast). //self.cx.context.new_cast(None, value, dest_ty) self.bitcast(value, dest_ty) }, (true, true) => self.cx.context.new_cast(None, value, dest_ty), (true, false) => unimplemented!(), } } /* Comparisons */ fn icmp(&mut self, op: IntPredicate, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> { self.context.new_comparison(None, op.to_gcc_comparison(), lhs, rhs) } fn fcmp(&mut self, op: RealPredicate, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> { self.context.new_comparison(None, op.to_gcc_comparison(), lhs, rhs) } /* Miscellaneous instructions */ fn memcpy(&mut self, dst: RValue<'gcc>, dst_align: Align, src: RValue<'gcc>, src_align: Align, size: RValue<'gcc>, flags: MemFlags) { if flags.contains(MemFlags::NONTEMPORAL) { // HACK(nox): This is inefficient but there is no nontemporal memcpy. let val = self.load(src, src_align); let ptr = self.pointercast(dst, self.type_ptr_to(self.val_ty(val))); self.store_with_flags(val, ptr, dst_align, flags); return; } let size = self.intcast(size, self.type_size_t(), false); let is_volatile = flags.contains(MemFlags::VOLATILE); let dst = self.pointercast(dst, self.type_i8p()); let src = self.pointercast(src, self.type_ptr_to(self.type_void())); let memcpy = self.context.get_builtin_function("memcpy"); let block = self.block.expect("block"); // TODO: handle aligns and is_volatile. block.add_eval(None, self.context.new_call(None, memcpy, &[dst, src, size])); } fn memmove(&mut self, dst: RValue<'gcc>, dst_align: Align, src: RValue<'gcc>, src_align: Align, size: RValue<'gcc>, flags: MemFlags) { if flags.contains(MemFlags::NONTEMPORAL) { // HACK(nox): This is inefficient but there is no nontemporal memmove. let val = self.load(src, src_align); let ptr = self.pointercast(dst, self.type_ptr_to(self.val_ty(val))); self.store_with_flags(val, ptr, dst_align, flags); return; } let size = self.intcast(size, self.type_size_t(), false); let is_volatile = flags.contains(MemFlags::VOLATILE); let dst = self.pointercast(dst, self.type_i8p()); let src = self.pointercast(src, self.type_ptr_to(self.type_void())); let memmove = self.context.get_builtin_function("memmove"); let block = self.block.expect("block"); // TODO: handle is_volatile. block.add_eval(None, self.context.new_call(None, memmove, &[dst, src, size])); } fn memset(&mut self, ptr: RValue<'gcc>, fill_byte: RValue<'gcc>, size: RValue<'gcc>, align: Align, flags: MemFlags) { let is_volatile = flags.contains(MemFlags::VOLATILE); let ptr = self.pointercast(ptr, self.type_i8p()); let memset = self.context.get_builtin_function("memset"); let block = self.block.expect("block"); // TODO: handle aligns and is_volatile. //println!("memset: {:?} -> {:?}", fill_byte, self.i32_type); let fill_byte = self.context.new_cast(None, fill_byte, self.i32_type); let size = self.intcast(size, self.type_size_t(), false); block.add_eval(None, self.context.new_call(None, memset, &[ptr, fill_byte, size])); } fn select(&mut self, cond: RValue<'gcc>, then_val: RValue<'gcc>, else_val: RValue<'gcc>) -> RValue<'gcc> { let func = self.current_func(); let variable = func.new_local(None, then_val.get_type(), "selectVar"); let then_block = func.new_block("then"); let else_block = func.new_block("else"); let after_block = func.new_block("after"); self.llbb().end_with_conditional(None, cond, then_block, else_block); then_block.add_assignment(None, variable, then_val); then_block.end_with_jump(None, after_block); else_block.add_assignment(None, variable, else_val); else_block.end_with_jump(None, after_block); // NOTE: since jumps were added in a place rustc does not expect, the current blocks in the // state need to be updated. self.block = Some(after_block); *self.cx.current_block.borrow_mut() = Some(after_block); variable.to_rvalue() } #[allow(dead_code)] fn va_arg(&mut self, list: RValue<'gcc>, ty: Type<'gcc>) -> RValue<'gcc> { unimplemented!(); //unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) } } fn extract_element(&mut self, vec: RValue<'gcc>, idx: RValue<'gcc>) -> RValue<'gcc> { unimplemented!(); //unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) } } fn vector_splat(&mut self, num_elts: usize, elt: RValue<'gcc>) -> RValue<'gcc> { unimplemented!(); /*unsafe { let elt_ty = self.cx.val_ty(elt); let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64)); let vec = self.insert_element(undef, elt, self.cx.const_i32(0)); let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64); self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty)) }*/ } fn extract_value(&mut self, aggregate_value: RValue<'gcc>, idx: u64) -> RValue<'gcc> { // FIXME: it would be better if the API only called this on struct, not on arrays. assert_eq!(idx as usize as u64, idx); let value_type = aggregate_value.get_type(); if value_type.is_array() { let index = self.context.new_rvalue_from_long(self.u64_type, i64::try_from(idx).expect("i64::try_from")); let element = self.context.new_array_access(None, aggregate_value, index); element.get_address(None) } else if value_type.is_vector().is_some() { panic!(); } else if let Some(pointer_type) = value_type.get_pointee() { if let Some(struct_type) = pointer_type.is_struct() { // NOTE: hack to workaround a limitation of the rustc API: see comment on // CodegenCx.structs_as_pointer aggregate_value.dereference_field(None, struct_type.get_field(idx as i32)).to_rvalue() } else { panic!("Unexpected type {:?}", value_type); } } else if let Some(struct_type) = value_type.is_struct() { aggregate_value.access_field(None, struct_type.get_field(idx as i32)).to_rvalue() } else { panic!("Unexpected type {:?}", value_type); } /*assert_eq!(idx as c_uint as u64, idx); unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }*/ } fn insert_value(&mut self, aggregate_value: RValue<'gcc>, value: RValue<'gcc>, idx: u64) -> RValue<'gcc> { // FIXME: it would be better if the API only called this on struct, not on arrays. assert_eq!(idx as usize as u64, idx); let value_type = aggregate_value.get_type(); let lvalue = if value_type.is_array() { let index = self.context.new_rvalue_from_long(self.u64_type, i64::try_from(idx).expect("i64::try_from")); self.context.new_array_access(None, aggregate_value, index) } else if value_type.is_vector().is_some() { panic!(); } else if let Some(pointer_type) = value_type.get_pointee() { if let Some(struct_type) = pointer_type.is_struct() { // NOTE: hack to workaround a limitation of the rustc API: see comment on // CodegenCx.structs_as_pointer aggregate_value.dereference_field(None, struct_type.get_field(idx as i32)) } else { panic!("Unexpected type {:?}", value_type); } } else { panic!("Unexpected type {:?}", value_type); }; self.llbb().add_assignment(None, lvalue, value); aggregate_value } fn landing_pad(&mut self, ty: Type<'gcc>, pers_fn: RValue<'gcc>, num_clauses: usize) -> RValue<'gcc> { unimplemented!(); /*unsafe { llvm::LLVMBuildLandingPad(self.llbuilder, ty, pers_fn, num_clauses as c_uint, UNNAMED) }*/ } fn set_cleanup(&mut self, landing_pad: RValue<'gcc>) { unimplemented!(); /*unsafe { llvm::LLVMSetCleanup(landing_pad, llvm::True); }*/ } fn resume(&mut self, exn: RValue<'gcc>) -> RValue<'gcc> { unimplemented!(); //unsafe { llvm::LLVMBuildResume(self.llbuilder, exn) } } fn cleanup_pad(&mut self, parent: Option<RValue<'gcc>>, args: &[RValue<'gcc>]) -> Funclet { unimplemented!(); /*let name = const_cstr!("cleanuppad"); let ret = unsafe { llvm::LLVMRustBuildCleanupPad( self.llbuilder, parent, args.len() as c_uint, args.as_ptr(), name.as_ptr(), ) }; Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))*/ } fn cleanup_ret(&mut self, funclet: &Funclet, unwind: Option<Block<'gcc>>) -> RValue<'gcc> { unimplemented!(); /*let ret = unsafe { llvm::LLVMRustBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind) }; ret.expect("LLVM does not have support for cleanupret")*/ } fn catch_pad(&mut self, parent: RValue<'gcc>, args: &[RValue<'gcc>]) -> Funclet { unimplemented!(); /*let name = const_cstr!("catchpad"); let ret = unsafe { llvm::LLVMRustBuildCatchPad( self.llbuilder, parent, args.len() as c_uint, args.as_ptr(), name.as_ptr(), ) }; Funclet::new(ret.expect("LLVM does not have support for catchpad"))*/ } fn catch_switch(&mut self, parent: Option<RValue<'gcc>>, unwind: Option<Block<'gcc>>, num_handlers: usize) -> RValue<'gcc> { unimplemented!(); /*let name = const_cstr!("catchswitch"); let ret = unsafe { llvm::LLVMRustBuildCatchSwitch( self.llbuilder, parent, unwind, num_handlers as c_uint, name.as_ptr(), ) }; ret.expect("LLVM does not have support for catchswitch")*/ } fn add_handler(&mut self, catch_switch: RValue<'gcc>, handler: Block<'gcc>) { unimplemented!(); /*unsafe { llvm::LLVMRustAddHandler(catch_switch, handler); }*/ } fn set_personality_fn(&mut self, personality: RValue<'gcc>) { unimplemented!(); /*unsafe { llvm::LLVMSetPersonalityFn(self.llfn(), personality); }*/ } // Atomic Operations fn atomic_cmpxchg(&mut self, dst: RValue<'gcc>, cmp: RValue<'gcc>, src: RValue<'gcc>, order: AtomicOrdering, failure_order: AtomicOrdering, weak: bool) -> RValue<'gcc> { let expected = self.current_func().new_local(None, cmp.get_type(), "expected"); self.llbb().add_assignment(None, expected, cmp); let success = self.compare_exchange(dst, expected, src, order, failure_order, weak); let pair_type = self.cx.type_struct(&[src.get_type(), self.bool_type], false); let result = self.current_func().new_local(None, pair_type, "atomic_cmpxchg_result"); let align = Align::from_bits(64).expect("align"); // TODO: use good align. let value_type = result.to_rvalue().get_type(); if let Some(struct_type) = value_type.is_struct() { self.store(success, result.access_field(None, struct_type.get_field(1)).get_address(None), align); // NOTE: since success contains the call to the intrinsic, it must be stored before // expected so that we store expected after the call. self.store(expected.to_rvalue(), result.access_field(None, struct_type.get_field(0)).get_address(None), align); } // TODO: handle when value is not a struct. result.to_rvalue() } fn atomic_rmw(&mut self, op: AtomicRmwBinOp, dst: RValue<'gcc>, src: RValue<'gcc>, order: AtomicOrdering) -> RValue<'gcc> { let size = self.cx.int_width(src.get_type()) / 8; let name = match op { AtomicRmwBinOp::AtomicXchg => format!("__atomic_exchange_{}", size), AtomicRmwBinOp::AtomicAdd => format!("__atomic_fetch_add_{}", size), AtomicRmwBinOp::AtomicSub => format!("__atomic_fetch_sub_{}", size), AtomicRmwBinOp::AtomicAnd => format!("__atomic_fetch_and_{}", size), AtomicRmwBinOp::AtomicNand => format!("__atomic_fetch_nand_{}", size), AtomicRmwBinOp::AtomicOr => format!("__atomic_fetch_or_{}", size), AtomicRmwBinOp::AtomicXor => format!("__atomic_fetch_xor_{}", size), AtomicRmwBinOp::AtomicMax => return self.atomic_extremum(ExtremumOperation::Max, dst, src, order), AtomicRmwBinOp::AtomicMin => return self.atomic_extremum(ExtremumOperation::Min, dst, src, order), AtomicRmwBinOp::AtomicUMax => return self.atomic_extremum(ExtremumOperation::Max, dst, src, order), AtomicRmwBinOp::AtomicUMin => return self.atomic_extremum(ExtremumOperation::Min, dst, src, order), }; let atomic_function = self.context.get_builtin_function(name); let order = self.context.new_rvalue_from_int(self.i32_type, order.to_gcc()); let void_ptr_type = self.context.new_type::<*mut ()>(); let volatile_void_ptr_type = void_ptr_type.make_volatile(); let dst = self.context.new_cast(None, dst, volatile_void_ptr_type); // NOTE: not sure why, but we have the wrong type here. let new_src_type = atomic_function.get_param(1).to_rvalue().get_type(); let src = self.context.new_cast(None, src, new_src_type); let res = self.context.new_call(None, atomic_function, &[dst, src, order]); self.context.new_cast(None, res, src.get_type()) } fn atomic_fence(&mut self, order: AtomicOrdering, scope: SynchronizationScope) { let name = match scope { SynchronizationScope::SingleThread => "__atomic_signal_fence", SynchronizationScope::CrossThread => "__atomic_thread_fence", }; let thread_fence = self.context.get_builtin_function(name); let order = self.context.new_rvalue_from_int(self.i32_type, order.to_gcc()); self.llbb().add_eval(None, self.context.new_call(None, thread_fence, &[order])); } fn set_invariant_load(&mut self, load: RValue<'gcc>) { // NOTE: Hack to consider vtable function pointer as non-global-variable function pointer. self.normal_function_addresses.borrow_mut().insert(load); // TODO /*unsafe { llvm::LLVMSetMetadata( load, llvm::MD_invariant_load as c_uint, llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0), ); }*/ } fn lifetime_start(&mut self, ptr: RValue<'gcc>, size: Size) { // TODO //self.call_lifetime_intrinsic("llvm.lifetime.start.p0i8", ptr, size); } fn lifetime_end(&mut self, ptr: RValue<'gcc>, size: Size) { // TODO //self.call_lifetime_intrinsic("llvm.lifetime.end.p0i8", ptr, size); } fn call(&mut self, func: RValue<'gcc>, args: &[RValue<'gcc>], funclet: Option<&Funclet>) -> RValue<'gcc> { // FIXME: remove when having a proper API. let gcc_func = unsafe { std::mem::transmute(func) }; if self.functions.borrow().values().find(|value| **value == gcc_func).is_some() { let gcc_func = self.cx.rvalue_as_function(func); self.function_call(func, args, funclet) } else { // If it's a not function that was defined, it's a function pointer. self.function_ptr_call(func, args, funclet) } } fn zext(&mut self, value: RValue<'gcc>, dest_typ: Type<'gcc>) -> RValue<'gcc> { // FIXME: this does not zero-extend. if value.get_type().is_bool() && dest_typ.is_i8(&self.cx) { // FIXME: hack because base::from_immediate converts i1 to i8. // Fix the code in codegen_ssa::base::from_immediate. return value; } //println!("zext: {:?} -> {:?}", value, dest_typ); self.context.new_cast(None, value, dest_typ) } fn cx(&self) -> &CodegenCx<'gcc, 'tcx> { self.cx } fn do_not_inline(&mut self, llret: RValue<'gcc>) { unimplemented!(); //llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret); } fn set_span(&mut self, _span: Span) {} fn from_immediate(&mut self, val: Self::Value) -> Self::Value { if self.cx().val_ty(val) == self.cx().type_i1() { self.zext(val, self.cx().type_i8()) } else { val } } fn to_immediate_scalar(&mut self, val: Self::Value, scalar: &abi::Scalar) -> Self::Value { if scalar.is_bool() { return self.trunc(val, self.cx().type_i1()); } val } fn fptoui_sat(&mut self, val: RValue<'gcc>, dest_ty: Type<'gcc>) -> Option<RValue<'gcc>> { None } fn fptosi_sat(&mut self, val: RValue<'gcc>, dest_ty: Type<'gcc>) -> Option<RValue<'gcc>> { None } fn instrprof_increment(&mut self, fn_name: RValue<'gcc>, hash: RValue<'gcc>, num_counters: RValue<'gcc>, index: RValue<'gcc>) { unimplemented!(); /*debug!( "instrprof_increment() with args ({:?}, {:?}, {:?}, {:?})", fn_name, hash, num_counters, index ); let llfn = unsafe { llvm::LLVMRustGetInstrProfIncrementIntrinsic(self.cx().llmod) }; let args = &[fn_name, hash, num_counters, index]; let args = self.check_call("call", llfn, args); unsafe { let _ = llvm::LLVMRustBuildCall( self.llbuilder, llfn, args.as_ptr() as *const &llvm::Value, args.len() as c_uint, None, ); }*/ } } impl<'a, 'gcc, 'tcx> StaticBuilderMethods for Builder<'a, 'gcc, 'tcx> { fn get_static(&mut self, def_id: DefId) -> RValue<'gcc> { // Forward to the `get_static` method of `CodegenCx` self.cx().get_static(def_id) } } impl<'tcx> HasParamEnv<'tcx> for Builder<'_, '_, 'tcx> { fn param_env(&self) -> ParamEnv<'tcx> { self.cx.param_env() } } impl<'tcx> HasTargetSpec for Builder<'_, '_, 'tcx> { fn target_spec(&self) -> &Target { &self.cx.target_spec() } } trait ToGccComp { fn to_gcc_comparison(&self) -> ComparisonOp; } impl ToGccComp for IntPredicate { fn to_gcc_comparison(&self) -> ComparisonOp { match *self { IntPredicate::IntEQ => ComparisonOp::Equals, IntPredicate::IntNE => ComparisonOp::NotEquals, IntPredicate::IntUGT => ComparisonOp::GreaterThan, IntPredicate::IntUGE => ComparisonOp::GreaterThanEquals, IntPredicate::IntULT => ComparisonOp::LessThan, IntPredicate::IntULE => ComparisonOp::LessThanEquals, IntPredicate::IntSGT => ComparisonOp::GreaterThan, IntPredicate::IntSGE => ComparisonOp::GreaterThanEquals, IntPredicate::IntSLT => ComparisonOp::LessThan, IntPredicate::IntSLE => ComparisonOp::LessThanEquals, } } } impl ToGccComp for RealPredicate { fn to_gcc_comparison(&self) -> ComparisonOp { // TODO: check that ordered vs non-ordered is respected. match *self { RealPredicate::RealPredicateFalse => unreachable!(), RealPredicate::RealOEQ => ComparisonOp::Equals, RealPredicate::RealOGT => ComparisonOp::GreaterThan, RealPredicate::RealOGE => ComparisonOp::GreaterThanEquals, RealPredicate::RealOLT => ComparisonOp::LessThan, RealPredicate::RealOLE => ComparisonOp::LessThanEquals, RealPredicate::RealONE => ComparisonOp::NotEquals, RealPredicate::RealORD => unreachable!(), RealPredicate::RealUNO => unreachable!(), RealPredicate::RealUEQ => ComparisonOp::Equals, RealPredicate::RealUGT => ComparisonOp::GreaterThan, RealPredicate::RealUGE => ComparisonOp::GreaterThan, RealPredicate::RealULT => ComparisonOp::LessThan, RealPredicate::RealULE => ComparisonOp::LessThan, RealPredicate::RealUNE => ComparisonOp::NotEquals, RealPredicate::RealPredicateTrue => unreachable!(), } } } #[repr(C)] #[allow(non_camel_case_types)] enum MemOrdering { __ATOMIC_RELAXED, __ATOMIC_CONSUME, __ATOMIC_ACQUIRE, __ATOMIC_RELEASE, __ATOMIC_ACQ_REL, __ATOMIC_SEQ_CST, } trait ToGccOrdering { fn to_gcc(self) -> i32; } impl ToGccOrdering for AtomicOrdering { fn to_gcc(self) -> i32 { use MemOrdering::*; let ordering = match self { AtomicOrdering::NotAtomic => __ATOMIC_RELAXED, // TODO: check if that's the same. AtomicOrdering::Unordered => __ATOMIC_RELAXED, AtomicOrdering::Monotonic => __ATOMIC_RELAXED, // TODO: check if that's the same. AtomicOrdering::Acquire => __ATOMIC_ACQUIRE, AtomicOrdering::Release => __ATOMIC_RELEASE, AtomicOrdering::AcquireRelease => __ATOMIC_ACQ_REL, AtomicOrdering::SequentiallyConsistent => __ATOMIC_SEQ_CST, }; ordering as i32 } }
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::*; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 1000000007; fn main() { input! { a: [[usize; 3]; 3], n: usize, b: [usize; n], } let mut flag = vec![vec![false; 3]; 3]; for &bk in &b { for i in 0..3 { for j in 0..3 { if a[i][j] == bk { flag[i][j] = true; } } } } for i in 0..3 { if (0..3).all(|j| flag[i][j]) { println!("Yes"); return; } } for j in 0..3 { if (0..3).all(|i| flag[i][j]) { println!("Yes"); return; } } if flag[0][0] && flag[1][1] && flag[2][2] { println!("Yes"); return; } if flag[2][0] && flag[1][1] && flag[0][2] { println!("Yes"); return; } println!("No"); }
#![feature(async_await)] use lambda::lambda; type Err = Box<dyn std::error::Error + Send + Sync + 'static>; #[lambda] #[runtime::main] async fn main(event: String) -> Result<String, Err> { Ok(event) }
use super::{dynamic_cost::DynamicCostSolver, Item, Problem, Solution, SolverTrait}; #[derive(Debug, Clone)] pub struct FTPASSolver { pub gcd: u32, } impl SolverTrait for FTPASSolver { fn construction(&self, problem: &Problem) -> Solution { let transformed_items = problem .items .iter() .map(|&item| Item { cost: item.cost / self.gcd, ..item }) .collect(); let solution = DynamicCostSolver().construction(&Problem { items: transformed_items, ..*problem }); Solution { cost: if let Some(ref items) = solution.items { items.iter().enumerate().fold(0, |acc, (i, &used)| { if used { acc + problem.items[i].cost } else { acc } }) } else { 0 }, ..solution } } }
#![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 IProviderSpiConnectionSettings(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IProviderSpiConnectionSettings { type Vtable = IProviderSpiConnectionSettings_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf6034550_a542_4ec0_9601_a4dd68f8697b); } #[repr(C)] #[doc(hidden)] pub struct IProviderSpiConnectionSettings_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 i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ProviderSpiMode) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ProviderSpiMode) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ProviderSpiSharingMode) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ProviderSpiSharingMode) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IProviderSpiConnectionSettingsFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IProviderSpiConnectionSettingsFactory { type Vtable = IProviderSpiConnectionSettingsFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x66456b5a_0c79_43e3_9f3c_e59780ac18fa); } #[repr(C)] #[doc(hidden)] pub struct IProviderSpiConnectionSettingsFactory_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, chipselectline: i32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISpiControllerProvider(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISpiControllerProvider { type Vtable = ISpiControllerProvider_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc1686504_02ce_4226_a385_4f11fb04b41b); } impl ISpiControllerProvider { pub fn GetDeviceProvider<'a, Param0: ::windows::core::IntoParam<'a, ProviderSpiConnectionSettings>>(&self, settings: Param0) -> ::windows::core::Result<ISpiDeviceProvider> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), settings.into_param().abi(), &mut result__).from_abi::<ISpiDeviceProvider>(result__) } } } unsafe impl ::windows::core::RuntimeType for ISpiControllerProvider { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{c1686504-02ce-4226-a385-4f11fb04b41b}"); } impl ::core::convert::From<ISpiControllerProvider> for ::windows::core::IUnknown { fn from(value: ISpiControllerProvider) -> Self { value.0 .0 } } impl ::core::convert::From<&ISpiControllerProvider> for ::windows::core::IUnknown { fn from(value: &ISpiControllerProvider) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISpiControllerProvider { 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 ISpiControllerProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ISpiControllerProvider> for ::windows::core::IInspectable { fn from(value: ISpiControllerProvider) -> Self { value.0 } } impl ::core::convert::From<&ISpiControllerProvider> for ::windows::core::IInspectable { fn from(value: &ISpiControllerProvider) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ISpiControllerProvider { 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 ISpiControllerProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISpiControllerProvider_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, settings: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISpiDeviceProvider(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISpiDeviceProvider { type Vtable = ISpiDeviceProvider_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0d1c3443_304b_405c_b4f7_f5ab1074461e); } impl ISpiDeviceProvider { #[cfg(feature = "Foundation")] pub fn Close(&self) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<super::super::super::Foundation::IClosable>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } pub fn DeviceId(&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).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn ConnectionSettings(&self) -> ::windows::core::Result<ProviderSpiConnectionSettings> { 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::<ProviderSpiConnectionSettings>(result__) } } pub fn Write(&self, buffer: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), buffer.len() as u32, ::core::mem::transmute(buffer.as_ptr())).ok() } } pub fn Read(&self, buffer: &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), buffer.len() as u32, ::core::mem::transmute_copy(&buffer)).ok() } } pub fn TransferSequential(&self, writebuffer: &[<u8 as ::windows::core::DefaultType>::DefaultType], readbuffer: &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), writebuffer.len() as u32, ::core::mem::transmute(writebuffer.as_ptr()), readbuffer.len() as u32, ::core::mem::transmute_copy(&readbuffer)).ok() } } pub fn TransferFullDuplex(&self, writebuffer: &[<u8 as ::windows::core::DefaultType>::DefaultType], readbuffer: &mut [<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), writebuffer.len() as u32, ::core::mem::transmute(writebuffer.as_ptr()), readbuffer.len() as u32, ::core::mem::transmute_copy(&readbuffer)).ok() } } } unsafe impl ::windows::core::RuntimeType for ISpiDeviceProvider { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{0d1c3443-304b-405c-b4f7-f5ab1074461e}"); } impl ::core::convert::From<ISpiDeviceProvider> for ::windows::core::IUnknown { fn from(value: ISpiDeviceProvider) -> Self { value.0 .0 } } impl ::core::convert::From<&ISpiDeviceProvider> for ::windows::core::IUnknown { fn from(value: &ISpiDeviceProvider) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISpiDeviceProvider { 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 ISpiDeviceProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ISpiDeviceProvider> for ::windows::core::IInspectable { fn from(value: ISpiDeviceProvider) -> Self { value.0 } } impl ::core::convert::From<&ISpiDeviceProvider> for ::windows::core::IInspectable { fn from(value: &ISpiDeviceProvider) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ISpiDeviceProvider { 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 ISpiDeviceProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<ISpiDeviceProvider> for super::super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: ISpiDeviceProvider) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<&ISpiDeviceProvider> for super::super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: &ISpiDeviceProvider) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::IClosable> for ISpiDeviceProvider { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::IClosable> { ::windows::core::IntoParam::into_param(&self) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::IClosable> for &ISpiDeviceProvider { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::IClosable> { ::core::convert::TryInto::<super::super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[repr(C)] #[doc(hidden)] pub struct ISpiDeviceProvider_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, 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, buffer_array_size: u32, buffer: *const u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, buffer_array_size: u32, buffer: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, writeBuffer_array_size: u32, writebuffer: *const u8, readBuffer_array_size: u32, readbuffer: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, writeBuffer_array_size: u32, writebuffer: *const u8, readBuffer_array_size: u32, readbuffer: *mut u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISpiProvider(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISpiProvider { type Vtable = ISpiProvider_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96b461e2_77d4_48ce_aaa0_75715a8362cf); } impl ISpiProvider { #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetControllersAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<super::super::super::Foundation::Collections::IVectorView<ISpiControllerProvider>>> { 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::super::Foundation::IAsyncOperation<super::super::super::Foundation::Collections::IVectorView<ISpiControllerProvider>>>(result__) } } } unsafe impl ::windows::core::RuntimeType for ISpiProvider { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{96b461e2-77d4-48ce-aaa0-75715a8362cf}"); } impl ::core::convert::From<ISpiProvider> for ::windows::core::IUnknown { fn from(value: ISpiProvider) -> Self { value.0 .0 } } impl ::core::convert::From<&ISpiProvider> for ::windows::core::IUnknown { fn from(value: &ISpiProvider) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISpiProvider { 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 ISpiProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ISpiProvider> for ::windows::core::IInspectable { fn from(value: ISpiProvider) -> Self { value.0 } } impl ::core::convert::From<&ISpiProvider> for ::windows::core::IInspectable { fn from(value: &ISpiProvider) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ISpiProvider { 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 ISpiProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISpiProvider_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 = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ProviderSpiConnectionSettings(pub ::windows::core::IInspectable); impl ProviderSpiConnectionSettings { pub fn ChipSelectLine(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn SetChipSelectLine(&self, value: i32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } pub fn Mode(&self) -> ::windows::core::Result<ProviderSpiMode> { let this = self; unsafe { let mut result__: ProviderSpiMode = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ProviderSpiMode>(result__) } } pub fn SetMode(&self, value: ProviderSpiMode) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() } } pub fn DataBitLength(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn SetDataBitLength(&self, value: i32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() } } pub fn ClockFrequency(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn SetClockFrequency(&self, value: i32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value).ok() } } pub fn SharingMode(&self) -> ::windows::core::Result<ProviderSpiSharingMode> { let this = self; unsafe { let mut result__: ProviderSpiSharingMode = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ProviderSpiSharingMode>(result__) } } pub fn SetSharingMode(&self, value: ProviderSpiSharingMode) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value).ok() } } pub fn Create(chipselectline: i32) -> ::windows::core::Result<ProviderSpiConnectionSettings> { Self::IProviderSpiConnectionSettingsFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), chipselectline, &mut result__).from_abi::<ProviderSpiConnectionSettings>(result__) }) } pub fn IProviderSpiConnectionSettingsFactory<R, F: FnOnce(&IProviderSpiConnectionSettingsFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<ProviderSpiConnectionSettings, IProviderSpiConnectionSettingsFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for ProviderSpiConnectionSettings { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Spi.Provider.ProviderSpiConnectionSettings;{f6034550-a542-4ec0-9601-a4dd68f8697b})"); } unsafe impl ::windows::core::Interface for ProviderSpiConnectionSettings { type Vtable = IProviderSpiConnectionSettings_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf6034550_a542_4ec0_9601_a4dd68f8697b); } impl ::windows::core::RuntimeName for ProviderSpiConnectionSettings { const NAME: &'static str = "Windows.Devices.Spi.Provider.ProviderSpiConnectionSettings"; } impl ::core::convert::From<ProviderSpiConnectionSettings> for ::windows::core::IUnknown { fn from(value: ProviderSpiConnectionSettings) -> Self { value.0 .0 } } impl ::core::convert::From<&ProviderSpiConnectionSettings> for ::windows::core::IUnknown { fn from(value: &ProviderSpiConnectionSettings) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ProviderSpiConnectionSettings { 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 ProviderSpiConnectionSettings { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ProviderSpiConnectionSettings> for ::windows::core::IInspectable { fn from(value: ProviderSpiConnectionSettings) -> Self { value.0 } } impl ::core::convert::From<&ProviderSpiConnectionSettings> for ::windows::core::IInspectable { fn from(value: &ProviderSpiConnectionSettings) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ProviderSpiConnectionSettings { 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 ProviderSpiConnectionSettings { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for ProviderSpiConnectionSettings {} unsafe impl ::core::marker::Sync for ProviderSpiConnectionSettings {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct ProviderSpiMode(pub i32); impl ProviderSpiMode { pub const Mode0: ProviderSpiMode = ProviderSpiMode(0i32); pub const Mode1: ProviderSpiMode = ProviderSpiMode(1i32); pub const Mode2: ProviderSpiMode = ProviderSpiMode(2i32); pub const Mode3: ProviderSpiMode = ProviderSpiMode(3i32); } impl ::core::convert::From<i32> for ProviderSpiMode { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ProviderSpiMode { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ProviderSpiMode { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Spi.Provider.ProviderSpiMode;i4)"); } impl ::windows::core::DefaultType for ProviderSpiMode { 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 ProviderSpiSharingMode(pub i32); impl ProviderSpiSharingMode { pub const Exclusive: ProviderSpiSharingMode = ProviderSpiSharingMode(0i32); pub const Shared: ProviderSpiSharingMode = ProviderSpiSharingMode(1i32); } impl ::core::convert::From<i32> for ProviderSpiSharingMode { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ProviderSpiSharingMode { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ProviderSpiSharingMode { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Spi.Provider.ProviderSpiSharingMode;i4)"); } impl ::windows::core::DefaultType for ProviderSpiSharingMode { type DefaultType = Self; }
use crate::lib::{default_sub_command, file_to_lines, parse_lines, Command}; use anyhow::Error; use clap::{value_t_or_exit, App, Arg, ArgMatches, SubCommand}; use nom::{ branch::alt, bytes::complete::take, character::complete, combinator::{map, map_parser, map_res}, multi::fold_many1, sequence::tuple, }; use simple_error::SimpleError; use strum::VariantNames; use strum_macros::{EnumString, EnumVariantNames}; pub const BINARY_BOARDING: Command = Command::new(sub_command, "binary-boarding", run); #[derive(Debug, EnumString, EnumVariantNames)] #[strum(serialize_all = "kebab_case")] enum BoardingIdStategy { HighestInList, MissingFromList, } #[derive(Debug)] struct BinaryBoardingArgs { file: String, strategy: BoardingIdStategy, } #[derive(Debug)] struct BoardingPass { row: usize, column: usize, } impl BoardingPass { fn seat_id(&self) -> usize { self.row * 8 + self.column } } fn sub_command() -> App<'static, 'static> { default_sub_command(&BINARY_BOARDING, "Takes a file with boarding passes and finds the highest seat id", "Path to the input file. Input should be newline separated boarding passes.") .arg( Arg::with_name("strategy") .short("s") .help( "What strategy to use when finding the boarding id.\n\n\ highest-in-list: Finds the highest boarding id in the list\n\ missing-from-list: searching for the missing boarding id or 0 if many missing ids\n", ) .takes_value(true) .possible_values(&BoardingIdStategy::VARIANTS) .required(true), ) .subcommand( SubCommand::with_name("part1") .about("Finds the highest boarding id from the default input") .version("1.0.0"), ) .subcommand( SubCommand::with_name("part2") .about("Finds the missing boarding id from the default input") .version("1.0.0"), ) } fn run(arguments: &ArgMatches) -> Result<(), Error> { let binary_boarding_arguments = match arguments.subcommand_name() { Some("part1") => BinaryBoardingArgs { file: "day5/input.txt".to_string(), strategy: BoardingIdStategy::HighestInList, }, Some("part2") => BinaryBoardingArgs { file: "day5/input.txt".to_string(), strategy: BoardingIdStategy::MissingFromList, }, _ => BinaryBoardingArgs { file: value_t_or_exit!(arguments.value_of("file"), String), strategy: value_t_or_exit!(arguments.value_of("strategy"), BoardingIdStategy), }, }; process_boarding_passes(&binary_boarding_arguments) .map(|result| { println!("{:#?}", result); }) .map(|_| ()) } fn process_boarding_passes(binary_boarding_arguments: &BinaryBoardingArgs) -> Result<usize, Error> { file_to_lines(&binary_boarding_arguments.file) .and_then(|lines| parse_lines(lines, parse_boarding_pass_line)) .map(|boarding_passes| match binary_boarding_arguments.strategy { BoardingIdStategy::HighestInList => find_highest_boarding_id(boarding_passes), BoardingIdStategy::MissingFromList => find_missing_boarding_id(boarding_passes), }) } fn find_highest_boarding_id(boarding_passes: Vec<BoardingPass>) -> usize { boarding_passes.into_iter().fold(0, |max, value| { if max > value.seat_id() { max } else { value.seat_id() } }) } fn find_missing_boarding_id(boarding_passes: Vec<BoardingPass>) -> usize { let mut boarding_ids: Vec<usize> = boarding_passes .into_iter() .map(|boarding_pass| boarding_pass.seat_id()) .collect(); boarding_ids.sort(); boarding_ids .windows(2) .map(|window| (window[0], window[1])) .find(|(low, high)| (low + 2) == *high) .map(|(low, _)| low + 1) .unwrap_or(0) } fn parse_boarding_pass_line(line: &String) -> Result<BoardingPass, Error> { tuple(( map_res( map_parser( take(7usize), fold_many1( alt(( map(complete::char('F'), |_| "0"), map(complete::char('B'), |_| "1"), )), String::new(), |mut acc: String, digit| { acc.push_str(digit); acc }, ), ), |result| usize::from_str_radix(&result, 2), ), map_res( map_parser( take(3usize), fold_many1( alt(( map(complete::char('L'), |_| "0"), map(complete::char('R'), |_| "1"), )), String::new(), |mut acc: String, digit| { acc.push_str(digit); acc }, ), ), |result| usize::from_str_radix(&result, 2), ), ))(line.as_str()) .map_err(|_: nom::Err<nom::error::Error<&str>>| SimpleError::new("Parse Error").into()) .map(|(_, (row, column))| BoardingPass { row: row, column: column, }) }
#![cfg(test)] use crate::headers::{Header, HeaderMapExt, HeaderValue}; pub fn encode<'a, H: Header>(header: H) -> HeaderValue { let mut map = hyper::http::HeaderMap::new(); map.typed_insert(header); map.get(H::name()).unwrap().clone() }
// Copyright 2020, The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use crate::{ backoff::ConstantBackoff, builder::CommsBuilder, connection_manager::ConnectionManagerEvent, memsocket, message::{InboundMessage, OutboundMessage}, multiaddr::{Multiaddr, Protocol}, peer_manager::{Peer, PeerFeatures}, pipeline, pipeline::SinkService, protocol::{messaging::MessagingEvent, ProtocolEvent, Protocols}, runtime, test_utils::node_identity::build_node_identity, transports::MemoryTransport, types::CommsSubstream, CommsNode, }; use bytes::Bytes; use futures::{channel::mpsc, AsyncReadExt, AsyncWriteExt, SinkExt, StreamExt}; use std::{collections::HashSet, convert::identity, hash::Hash, sync::Arc, time::Duration}; use tari_storage::HashmapDatabase; use tari_test_utils::{collect_stream, unpack_enum}; async fn spawn_node( protocols: Protocols<CommsSubstream>, ) -> (CommsNode, mpsc::Receiver<InboundMessage>, mpsc::Sender<OutboundMessage>) { let addr = format!("/memory/{}", memsocket::acquire_next_memsocket_port()) .parse::<Multiaddr>() .unwrap(); let node_identity = build_node_identity(PeerFeatures::COMMUNICATION_NODE); node_identity.set_public_address(addr.clone()).unwrap(); let (inbound_tx, inbound_rx) = mpsc::channel(10); let (outbound_tx, outbound_rx) = mpsc::channel(10); let comms_node = CommsBuilder::new() // These calls are just to get rid of unused function warnings. // <IrrelevantCalls> .with_executor(runtime::current_executor()) .with_dial_backoff(ConstantBackoff::new(Duration::from_millis(500))) .on_shutdown(|| {}) // </IrrelevantCalls> .with_listener_address(addr) .with_transport(MemoryTransport) .with_peer_storage(HashmapDatabase::new()) .with_node_identity(node_identity) .with_protocols(protocols) .build() .unwrap(); let comms_node = comms_node .with_messaging_pipeline( pipeline::Builder::new() // Outbound messages will be forwarded "as is" to outbound messaging .with_outbound_pipeline(outbound_rx, identity) .max_concurrent_inbound_tasks(1) // Inbound messages will be forwarded "as is" to inbound_tx .with_inbound_pipeline(SinkService::new(inbound_tx)) .finish(), ) .spawn() .await .unwrap(); unpack_enum!(Protocol::Memory(_port) = comms_node.listening_address().iter().next().unwrap()); // This call is to get rid of unused function warnings comms_node.peer_manager(); (comms_node, inbound_rx, outbound_tx) } #[tokio_macros::test_basic] async fn peer_to_peer_custom_protocols() { const TEST_PROTOCOL: Bytes = Bytes::from_static(b"/tari/test"); const ANOTHER_TEST_PROTOCOL: Bytes = Bytes::from_static(b"/tari/test-again"); const TEST_MSG: &[u8] = b"Hello Tari"; const ANOTHER_TEST_MSG: &[u8] = b"Comms is running smoothly"; // Setup test protocols let (test_sender, _test_protocol_rx1) = mpsc::channel(10); let (another_test_sender, mut another_test_protocol_rx1) = mpsc::channel(10); let protocols1 = Protocols::new() .add(&[TEST_PROTOCOL], test_sender) .add(&[ANOTHER_TEST_PROTOCOL], another_test_sender); let (test_sender, mut test_protocol_rx2) = mpsc::channel(10); let (another_test_sender, _another_test_protocol_rx2) = mpsc::channel(10); let protocols2 = Protocols::new() .add(&[TEST_PROTOCOL], test_sender) .add(&[ANOTHER_TEST_PROTOCOL], another_test_sender); let (comms_node1, _, _) = spawn_node(protocols1).await; let (comms_node2, _, _) = spawn_node(protocols2).await; let node_identity1 = comms_node1.node_identity(); let node_identity2 = comms_node2.node_identity(); comms_node1 .peer_manager() .add_peer(Peer::new( node_identity2.public_key().clone(), node_identity2.node_id().clone(), node_identity2.public_address().clone().into(), Default::default(), Default::default(), &[TEST_PROTOCOL, ANOTHER_TEST_PROTOCOL], )) .await .unwrap(); let mut conn_man_events1 = comms_node1.subscribe_connection_manager_events(); let mut conn_man_requester1 = comms_node1.connection_manager(); let mut conn_man_events2 = comms_node2.subscribe_connection_manager_events(); let mut conn1 = conn_man_requester1 .dial_peer(node_identity2.node_id().clone()) .await .unwrap(); // Check that both nodes get the PeerConnected event. We subscribe after the nodes are initialized // so we miss those events. let next_event = conn_man_events2.next().await.unwrap().unwrap(); unpack_enum!(ConnectionManagerEvent::PeerConnected(conn2) = Arc::try_unwrap(next_event).unwrap()); let next_event = conn_man_events1.next().await.unwrap().unwrap(); unpack_enum!(ConnectionManagerEvent::PeerConnected(_conn) = &*next_event); // Let's speak both our test protocols let mut negotiated_substream1 = conn1.open_substream(&TEST_PROTOCOL).await.unwrap(); assert_eq!(negotiated_substream1.protocol, TEST_PROTOCOL); negotiated_substream1.stream.write_all(TEST_MSG).await.unwrap(); let mut negotiated_substream2 = conn2.open_substream(&ANOTHER_TEST_PROTOCOL).await.unwrap(); assert_eq!(negotiated_substream2.protocol, ANOTHER_TEST_PROTOCOL); negotiated_substream2.stream.write_all(ANOTHER_TEST_MSG).await.unwrap(); // Read TEST_PROTOCOL message to node 2 from node 1 let negotiation = test_protocol_rx2.next().await.unwrap(); assert_eq!(negotiation.protocol, TEST_PROTOCOL); unpack_enum!(ProtocolEvent::NewInboundSubstream(node_id, substream) = negotiation.event); assert_eq!(&*node_id, node_identity1.node_id()); let mut buf = [0u8; TEST_MSG.len()]; substream.read_exact(&mut buf).await.unwrap(); assert_eq!(buf, TEST_MSG); // Read ANOTHER_TEST_PROTOCOL message to node 1 from node 2 let negotiation = another_test_protocol_rx1.next().await.unwrap(); assert_eq!(negotiation.protocol, ANOTHER_TEST_PROTOCOL); unpack_enum!(ProtocolEvent::NewInboundSubstream(node_id, substream) = negotiation.event); assert_eq!(&*node_id, node_identity2.node_id()); let mut buf = [0u8; ANOTHER_TEST_MSG.len()]; substream.read_exact(&mut buf).await.unwrap(); assert_eq!(buf, ANOTHER_TEST_MSG); comms_node1.shutdown().await; comms_node2.shutdown().await; } #[tokio_macros::test_basic] async fn peer_to_peer_messaging() { const NUM_MSGS: usize = 100; let (comms_node1, inbound_rx1, mut outbound_tx1) = spawn_node(Protocols::new()).await; let (comms_node2, inbound_rx2, mut outbound_tx2) = spawn_node(Protocols::new()).await; let messaging_events1 = comms_node1.subscribe_messaging_events(); let messaging_events2 = comms_node2.subscribe_messaging_events(); let node_identity1 = comms_node1.node_identity(); let node_identity2 = comms_node2.node_identity(); comms_node1 .peer_manager() .add_peer(Peer::new( node_identity2.public_key().clone(), node_identity2.node_id().clone(), node_identity2.public_address().clone().into(), Default::default(), Default::default(), &[], )) .await .unwrap(); // Send NUM_MSGS messages from node 1 to node 2 for i in 0..NUM_MSGS { let outbound_msg = OutboundMessage::new( node_identity2.node_id().clone(), format!("#{:0>3} - comms messaging is so hot right now!", i).into(), ); outbound_tx1.send(outbound_msg).await.unwrap(); } let messages1_to_2 = collect_stream!(inbound_rx2, take = NUM_MSGS, timeout = Duration::from_secs(10)); let events = collect_stream!(messaging_events1, take = NUM_MSGS, timeout = Duration::from_secs(10)); events.into_iter().map(Result::unwrap).for_each(|m| { unpack_enum!(MessagingEvent::MessageSent(_t) = &*m); }); let events = collect_stream!(messaging_events2, take = NUM_MSGS, timeout = Duration::from_secs(10)); events.into_iter().map(Result::unwrap).for_each(|m| { unpack_enum!(MessagingEvent::MessageReceived(_n, _t) = &*m); }); // Send NUM_MSGS messages from node 2 to node 1 for i in 0..NUM_MSGS { let outbound_msg = OutboundMessage::new( node_identity1.node_id().clone(), format!("#{:0>3} - comms messaging is so hot right now!", i).into(), ); outbound_tx2.send(outbound_msg).await.unwrap(); } let messages2_to_1 = collect_stream!(inbound_rx1, take = NUM_MSGS, timeout = Duration::from_secs(10)); // Check that we got all the messages let check_messages = |msgs: Vec<InboundMessage>| { for (i, msg) in msgs.iter().enumerate() { let expected_msg_prefix = format!("#{:0>3}", i); // 0..4 zero padded prefix bytes e.g. #003, #023, #100 assert_eq!(&msg.body[0..4], expected_msg_prefix.as_bytes()); } }; assert_eq!(messages1_to_2.len(), NUM_MSGS); check_messages(messages1_to_2); assert_eq!(messages2_to_1.len(), NUM_MSGS); check_messages(messages2_to_1); comms_node1.shutdown().await; comms_node2.shutdown().await; } #[tokio_macros::test_basic] async fn peer_to_peer_messaging_simultaneous() { const NUM_MSGS: usize = 10; let (comms_node1, inbound_rx1, mut outbound_tx1) = spawn_node(Protocols::new()).await; let (comms_node2, inbound_rx2, mut outbound_tx2) = spawn_node(Protocols::new()).await; let o1 = outbound_tx1.clone(); let o2 = outbound_tx2.clone(); let node_identity1 = comms_node1.node_identity().clone(); let node_identity2 = comms_node2.node_identity().clone(); comms_node1 .peer_manager() .add_peer(Peer::new( node_identity2.public_key().clone(), node_identity2.node_id().clone(), node_identity2.public_address().clone().into(), Default::default(), Default::default(), &[], )) .await .unwrap(); comms_node2 .peer_manager() .add_peer(Peer::new( node_identity1.public_key().clone(), node_identity1.node_id().clone(), node_identity1.public_address().clone().into(), Default::default(), Default::default(), &[], )) .await .unwrap(); // Simultaneously send messages between the two nodes let rt_handle = runtime::current_executor(); let handle1 = rt_handle.spawn(async move { for i in 0..NUM_MSGS { let outbound_msg = OutboundMessage::new( node_identity2.node_id().clone(), format!("#{:0>3} - comms messaging is so hot right now!", i).into(), ); outbound_tx1.send(outbound_msg).await.unwrap(); } }); let handle2 = rt_handle.spawn(async move { for i in 0..NUM_MSGS { let outbound_msg = OutboundMessage::new( node_identity1.node_id().clone(), format!("#{:0>3} - comms messaging is so hot right now!", i).into(), ); outbound_tx2.send(outbound_msg).await.unwrap(); } }); handle1.await.unwrap(); handle2.await.unwrap(); // Tasks are finished, let's see if all the messages made it though let messages1_to_2 = collect_stream!(inbound_rx2, take = NUM_MSGS, timeout = Duration::from_secs(10)); let messages2_to_1 = collect_stream!(inbound_rx1, take = NUM_MSGS, timeout = Duration::from_secs(10)); assert!(has_unique_elements(messages1_to_2.into_iter().map(|m| m.body))); assert!(has_unique_elements(messages2_to_1.into_iter().map(|m| m.body))); drop(o1); drop(o2); comms_node1.shutdown().await; comms_node2.shutdown().await; } fn has_unique_elements<T>(iter: T) -> bool where T: IntoIterator, T::Item: Eq + Hash, { let mut uniq = HashSet::new(); iter.into_iter().all(move |x| uniq.insert(x)) }
use crate::cmp::clamp; use super::flag::Flag; use super::numeric::Inv; static VARINACE_FACTOR: f64 = 2.0; #[derive(Debug)] pub struct Hypothesis { pub inv_depth: Inv, pub variance: f64, valid_min: Inv, valid_max: Inv, } fn range(inv_depth: Inv, variance: f64) -> (f64, f64) { let min = f64::from(inv_depth) - VARINACE_FACTOR * variance; let max = f64::from(inv_depth) + VARINACE_FACTOR * variance; (min, max) } pub fn check_args( inv_depth: Inv, variance: f64, inv_depth_range: (Inv, Inv) ) -> Result<(), Flag> { if f64::from(inv_depth) <= 0. { return Err(Flag::NegativePriorDepth); } let (valid_min, valid_max) = inv_depth_range; let (min, max) = range(inv_depth, variance); if max <= f64::from(valid_min) || f64::from(valid_max) <= min { return Err(Flag::HypothesisOutOfSerchRange); } Ok(()) } impl Hypothesis { pub fn new( inv_depth: Inv, variance: f64, inv_depth_range: (Inv, Inv), ) -> Hypothesis { let (valid_min, valid_max) = inv_depth_range; Hypothesis { inv_depth: inv_depth, variance: variance, valid_min: valid_min, valid_max: valid_max } } pub fn range(&self) -> (Inv, Inv) { let (min, max) = range(self.inv_depth, self.variance); let valid_min = f64::from(self.valid_min); let valid_max = f64::from(self.valid_max); let min = Inv::from(clamp(min, valid_min, valid_max)); let max = Inv::from(clamp(max, valid_min, valid_max)); (min, max) } } pub fn try_make_hypothesis( inv_depth: Inv, variance: f64, inv_depth_range: (Inv, Inv) ) -> Result<Hypothesis, Flag> { check_args(inv_depth, variance, inv_depth_range)?; Ok(Hypothesis::new(inv_depth, variance, inv_depth_range)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_new() { // predicted range fits in [min, max] let range = (Inv::from(0.4), Inv::from(1.0)); let (min, max) = Hypothesis::new(Inv::from(0.7), 0.1, range).range(); approx::assert_abs_diff_eq!(f64::from(min), 0.5); approx::assert_abs_diff_eq!(f64::from(max), 0.9); // inv_depth - factor * variance < min < inv_depth + factor * variance let (min, max) = Hypothesis::new(Inv::from(0.3), 0.1, range).range(); approx::assert_abs_diff_eq!(f64::from(min), 0.4); approx::assert_abs_diff_eq!(f64::from(max), 0.5); // inv_depth - factor * variance < max < inv_depth + factor * variance let (min, max) = Hypothesis::new(Inv::from(0.9), 0.1, range).range(); approx::assert_abs_diff_eq!(f64::from(min), 0.7); approx::assert_abs_diff_eq!(f64::from(max), 1.0); let flag = Flag::HypothesisOutOfSerchRange; // inv_depth - factor * variance < inv_depth + factor * variance < min assert_eq!(check_args(Inv::from(0.1), 0.1, range).unwrap_err(), flag); // max < inv_depth - factor * variance < inv_depth + factor * variance assert_eq!(check_args(Inv::from(1.5), 0.1, range).unwrap_err(), flag); // inv_depth - factor * variance < inv_depth + factor * variance == min assert_eq!(check_args(Inv::from(0.2), 0.1, range).unwrap_err(), flag); // max == inv_depth - factor * variance < inv_depth + factor * variance assert_eq!(check_args(Inv::from(1.2), 0.1, range).unwrap_err(), flag); } }
use micro_lambda::lambda; fn main() { lambda(handler); } fn handler(event: &str) -> std::result::Result<String, String> { println!("{}", event); if event.contains("fail") { return Err("ERROR".to_string()); } Ok("SUCCESS".to_string()) }
use std::cmp::{max, min}; use std::collections::{HashMap, VecDeque}; use std::iter::FromIterator; use adaptive_radix_tree::u64_art_map::U64ArtMap; use crate::algos::book::*; /// Price-time priority (or FIFO) matching engine implemented using an Adaptive Radix Tree for /// indexing. /// /// Implemented as a state-machine to be used for replication with Raft. #[derive(Debug, Clone)] pub struct FIFOBook { ask_price_buckets: U64ArtMap<VecDeque<Order>>, bid_price_buckets: U64ArtMap<VecDeque<Order>>, orders: HashMap<OrderId, Price>, } impl FIFOBook { pub fn new() -> Self { Self { ask_price_buckets: U64ArtMap::new(), bid_price_buckets: U64ArtMap::new(), orders: Default::default(), } } fn pop_bid(&mut self) -> Option<Order> { while let Some((price, mut bucket)) = self.bid_price_buckets.maximum_mut() { if !bucket.is_empty() { let result = bucket.pop_front().unwrap(); if bucket.is_empty() { self.bid_price_buckets.delete(price); } return Some(result); } } None } fn push_bid(&mut self, order: Order) { match self.bid_price_buckets.get_mut(&order.price) { None => { self.bid_price_buckets .insert(order.price, VecDeque::from(vec![order])); } Some(bucket) => { bucket.push_back(order); } } } fn pop_ask(&mut self) -> Option<Order> { while let Some((price, mut bucket)) = self.ask_price_buckets.minimum_mut() { if !bucket.is_empty() { let result = bucket.pop_front().unwrap(); if bucket.is_empty() { self.ask_price_buckets.delete(price); } return Some(result); } } None } fn push_ask(&mut self, order: Order) { match self.ask_price_buckets.get_mut(&order.price) { None => { self.ask_price_buckets .insert(order.price, VecDeque::from(vec![order])); } Some(bucket) => { bucket.push_back(order); } }; } fn merge(&mut self, ask: Order, bid: Order) -> Option<(Trade, Option<Order>)> { let ask_id = ask.id(); let bid_id = bid.id(); let result = Order::merge(ask, bid); if let Some((_, remainder)) = &result { if remainder.as_ref().map_or(true, |rem| !rem.has_id(ask_id)) { self.orders.remove(&ask_id); } if remainder.as_ref().map_or(true, |rem| !rem.has_id(bid_id)) { self.orders.remove(&bid_id); } } result } } /// Order book interface implementation impl Book for FIFOBook { /// Adds a buy or sell order to the book fn apply(&mut self, order: Order) { self.orders .insert((order.client_id, order.seq_number), order.price); match order.side { Side::Buy => self.push_bid(order), Side::Sell => self.push_ask(order), }; } /// Fills tradeable orders in the book and returns the generated trades. fn check_for_trades(&mut self) -> Vec<Trade> { let mut trades = vec![]; let (mut bid, mut ask) = match (self.pop_bid(), self.pop_ask()) { (Some(bid_new), Some(ask_new)) => (bid_new, ask_new), _ => return trades, }; while let Some((trade, remainder)) = self.merge(ask, bid) { trades.push(trade); if let Some(rem) = remainder { match rem.side { Side::Buy => { if let Some(ask_new) = self.pop_ask() { ask = ask_new; bid = rem; } else { self.push_bid(rem); return trades; } } Side::Sell => { if let Some(bid_new) = self.pop_bid() { bid = bid_new; ask = rem; } else { self.push_ask(rem); return trades; } } } } else { match (self.pop_bid(), self.pop_ask()) { (Some(bid_new), Some(ask_new)) => { bid = bid_new; ask = ask_new; } _ => return trades, }; } } trades } /// Cancels the given order from the book fn cancel(&mut self, order_id: OrderId, side: Side) -> bool { if let Some(price) = self.orders.remove(&order_id) { let side_buckets = match side { Side::Buy => &mut self.bid_price_buckets, Side::Sell => &mut self.ask_price_buckets, }; if let Some(bucket) = side_buckets.get_mut(&price) { if let Some(index) = bucket .iter() .position(|order| (order.client_id, order.seq_number) == order_id) { bucket.remove(index); return true; } } } false } } #[cfg(test)] mod tests { use rand::Rng; // Note this useful idiom: importing names from outer (for mod tests) scope. use super::*; fn make_default_order(side: Side, price: u64, size: u64, seq_number: u64) -> Order { Order { client_id: 1, seq_number, price, size, side, } } fn make_tradeable_book() -> FIFOBook { let mut book = FIFOBook::new(); for &buy_at in &[2, 3] { book.apply(make_default_order(Side::Buy, buy_at, 1, buy_at)); } for &sell_at in &[2, 3, 4, 5] { book.apply(make_default_order(Side::Sell, sell_at, 1, 10 + sell_at)); } book } #[test] fn test_check_trades() { let mut book = make_tradeable_book(); let trades = book.check_for_trades(); //println!("Book: {:?}", &book); println!("Trades: {:?}", &trades); assert_eq!(trades.is_empty(), false); assert_eq!(book.orders.len(), 4); } #[test] fn test_cancel() { let mut book = FIFOBook::new(); book.apply(Order { client_id: 12, seq_number: 1234, price: 1, size: 1, side: Side::Buy, }); let success = book.cancel((12, 1234), Side::Buy); //println!("Book: {:?}", &book); assert!(success); assert_eq!(book.orders.len(), 0); } #[test] fn test_partial_fill_works() { let mut book = FIFOBook::new(); book.apply(make_default_order(Side::Buy, 3, 10, 1)); book.apply(make_default_order(Side::Sell, 2, 3, 2)); book.apply(make_default_order(Side::Sell, 2, 6, 3)); book.apply(make_default_order(Side::Sell, 3, 3, 4)); let trades = book.check_for_trades(); println!("Book: {:?}", &book); println!("Trades: {:?}", &trades); assert_eq!(trades.len(), 3); assert_eq!( book.bid_price_buckets .get_mut(&3) .map(|b| b.is_empty()) .unwrap_or(true), true ); assert_eq!( book.ask_price_buckets .get_mut(&3) .map(|b| b.is_empty()) .unwrap_or(true), false ); } #[ignore] #[test] fn test_check_trades_performance() { let orders = generate_tradable_orders(100_000); measure_book_performance(orders); } fn measure_book_performance(orders: Vec<Order>) { let mut book = FIFOBook::new(); for order in orders { book.apply(order); book.check_for_trades(); } } fn generate_tradable_orders(n: u64) -> Vec<Order> { let mut rand = rand::thread_rng(); let mut last_ask = 0; let mut last_bid = 0; let mut orders = vec![]; for _ in 0..n { let (price, size, side) = if rand.gen_bool(0.5) { // Generate buy order let price = std::cmp::max( 1, std::cmp::min(1000, last_ask as i64 + rand.gen_range(-10..10)), ) as u64; last_bid = price; (price, rand.gen_range(0..20), Side::Buy) } else { // Generate sell order let price = std::cmp::max( 1, std::cmp::min(1000, last_bid as i64 + rand.gen_range(-10..10)), ) as u64; last_ask = price; (price, rand.gen_range(0..20), Side::Sell) }; orders.push(Order { client_id: 0, seq_number: 0, size, side, price, }); } return orders; } #[ignore] #[test] fn test_large_book() { let mut book = FIFOBook::new(); for i in 0..100000 { let order = Order { client_id: 0, seq_number: 0, price: rand::thread_rng().gen_range(120000..=130000), size: rand::thread_rng().gen_range(1..=20), side: Side::Buy, }; book.apply(order); let order = Order { client_id: 0, seq_number: 0, price: rand::thread_rng().gen_range(120000..=130000), size: rand::thread_rng().gen_range(1..=20), side: Side::Sell, }; book.apply(order); } // Clear trades out of the book book.check_for_trades(); for price in 120000..=130000 { println!( "{:?}: {:?} -- {:?}", price, book.bid_price_buckets .get_mut(&price) .map_or(0, |bucket| bucket.len()), book.ask_price_buckets .get_mut(&price) .map_or(0, |bucket| bucket.len()) ) } } }
use amethyst::{ core::math::Vector2, ecs::prelude::{Component, VecStorage, DenseVecStorage} }; use ncollide2d as nc; pub struct HP { pub value: u32 } impl Component for HP { type Storage = DenseVecStorage<Self>; } pub struct Power { pub value: u32, } impl Component for Power { type Storage = DenseVecStorage<Self>; } pub enum PlayerState { Exiting, Idle, Walking, Attacking, Climbing, Crouching } pub struct Player { pub snapback: Vector2<f32>, pub lr_input_state: f32, pub state: PlayerState, pub belly: u8, } impl Player { pub fn belly_max(&self) -> u8 { 10 } } impl Component for Player { type Storage = DenseVecStorage<Self>; } #[derive(Clone, Debug)] pub struct Collider { pub slab_handle: nc::pipeline::object::CollisionObjectSlabHandle, } impl Component for Collider { type Storage = VecStorage<Self>; } pub struct Motion { pub velocity: Vector2<f32>, pub acceleration: Vector2<f32>, } impl Component for Motion { type Storage = VecStorage<Self>; } pub enum FoodType { Carrot, Apple, Blueberries, Clover } pub struct Food { fillingness: u8, } impl Food { pub fn new(food_type: FoodType) -> Self { match food_type { FoodType::Carrot => Food { fillingness: 3 }, FoodType::Apple => Food { fillingness: 6 }, FoodType::Blueberries => Food { fillingness: 1 }, FoodType::Clover => Food { fillingness: 0 }, } } pub fn fillingness(&self) -> u8 { self.fillingness } } impl Component for Food { type Storage = VecStorage<Self>; } pub struct Exit; impl Component for Exit { type Storage = VecStorage<Self>; }
// Translated from C++ to Rust. The original C++ code can be found at // https://github.com/jk-jeon/dragonbox and carries the following license: // // Copyright 2020-2021 Junekey Jeon // // The contents of this file may be used under the terms of // the Apache License v2.0 with LLVM Exceptions. // // (See accompanying file LICENSE-Apache or copy at // https://llvm.org/foundation/relicensing/LICENSE.txt) // // Alternatively, the contents of this file may be used under the terms of // the Boost Software License, Version 1.0. // (See accompanying file LICENSE-Boost or copy at // https://www.boost.org/LICENSE_1_0.txt) // // Unless required by applicable law or agreed to in writing, this software // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. pub(crate) type EntryType = u128; const MIN_K: i32 = -292; const MAX_K: i32 = 326; pub(crate) unsafe fn get(k: i32) -> EntryType { debug_assert!(k >= MIN_K && k <= MAX_K); *CACHE.get_unchecked((k - MIN_K) as usize) } pub(crate) trait EntryTypeExt { fn high(&self) -> u64; fn low(&self) -> u64; } impl EntryTypeExt for EntryType { fn high(&self) -> u64 { (self >> 64) as u64 } fn low(&self) -> u64 { *self as u64 } } static CACHE: [EntryType; 619] = [ 0xff77b1fcbebcdc4f_25e8e89c13bb0f7b, 0x9faacf3df73609b1_77b191618c54e9ad, 0xc795830d75038c1d_d59df5b9ef6a2418, 0xf97ae3d0d2446f25_4b0573286b44ad1e, 0x9becce62836ac577_4ee367f9430aec33, 0xc2e801fb244576d5_229c41f793cda740, 0xf3a20279ed56d48a_6b43527578c11110, 0x9845418c345644d6_830a13896b78aaaa, 0xbe5691ef416bd60c_23cc986bc656d554, 0xedec366b11c6cb8f_2cbfbe86b7ec8aa9, 0x94b3a202eb1c3f39_7bf7d71432f3d6aa, 0xb9e08a83a5e34f07_daf5ccd93fb0cc54, 0xe858ad248f5c22c9_d1b3400f8f9cff69, 0x91376c36d99995be_23100809b9c21fa2, 0xb58547448ffffb2d_abd40a0c2832a78b, 0xe2e69915b3fff9f9_16c90c8f323f516d, 0x8dd01fad907ffc3b_ae3da7d97f6792e4, 0xb1442798f49ffb4a_99cd11cfdf41779d, 0xdd95317f31c7fa1d_40405643d711d584, 0x8a7d3eef7f1cfc52_482835ea666b2573, 0xad1c8eab5ee43b66_da3243650005eed0, 0xd863b256369d4a40_90bed43e40076a83, 0x873e4f75e2224e68_5a7744a6e804a292, 0xa90de3535aaae202_711515d0a205cb37, 0xd3515c2831559a83_0d5a5b44ca873e04, 0x8412d9991ed58091_e858790afe9486c3, 0xa5178fff668ae0b6_626e974dbe39a873, 0xce5d73ff402d98e3_fb0a3d212dc81290, 0x80fa687f881c7f8e_7ce66634bc9d0b9a, 0xa139029f6a239f72_1c1fffc1ebc44e81, 0xc987434744ac874e_a327ffb266b56221, 0xfbe9141915d7a922_4bf1ff9f0062baa9, 0x9d71ac8fada6c9b5_6f773fc3603db4aa, 0xc4ce17b399107c22_cb550fb4384d21d4, 0xf6019da07f549b2b_7e2a53a146606a49, 0x99c102844f94e0fb_2eda7444cbfc426e, 0xc0314325637a1939_fa911155fefb5309, 0xf03d93eebc589f88_793555ab7eba27cb, 0x96267c7535b763b5_4bc1558b2f3458df, 0xbbb01b9283253ca2_9eb1aaedfb016f17, 0xea9c227723ee8bcb_465e15a979c1cadd, 0x92a1958a7675175f_0bfacd89ec191eca, 0xb749faed14125d36_cef980ec671f667c, 0xe51c79a85916f484_82b7e12780e7401b, 0x8f31cc0937ae58d2_d1b2ecb8b0908811, 0xb2fe3f0b8599ef07_861fa7e6dcb4aa16, 0xdfbdcece67006ac9_67a791e093e1d49b, 0x8bd6a141006042bd_e0c8bb2c5c6d24e1, 0xaecc49914078536d_58fae9f773886e19, 0xda7f5bf590966848_af39a475506a899f, 0x888f99797a5e012d_6d8406c952429604, 0xaab37fd7d8f58178_c8e5087ba6d33b84, 0xd5605fcdcf32e1d6_fb1e4a9a90880a65, 0x855c3be0a17fcd26_5cf2eea09a550680, 0xa6b34ad8c9dfc06f_f42faa48c0ea481f, 0xd0601d8efc57b08b_f13b94daf124da27, 0x823c12795db6ce57_76c53d08d6b70859, 0xa2cb1717b52481ed_54768c4b0c64ca6f, 0xcb7ddcdda26da268_a9942f5dcf7dfd0a, 0xfe5d54150b090b02_d3f93b35435d7c4d, 0x9efa548d26e5a6e1_c47bc5014a1a6db0, 0xc6b8e9b0709f109a_359ab6419ca1091c, 0xf867241c8cc6d4c0_c30163d203c94b63, 0x9b407691d7fc44f8_79e0de63425dcf1e, 0xc21094364dfb5636_985915fc12f542e5, 0xf294b943e17a2bc4_3e6f5b7b17b2939e, 0x979cf3ca6cec5b5a_a705992ceecf9c43, 0xbd8430bd08277231_50c6ff782a838354, 0xece53cec4a314ebd_a4f8bf5635246429, 0x940f4613ae5ed136_871b7795e136be9a, 0xb913179899f68584_28e2557b59846e40, 0xe757dd7ec07426e5_331aeada2fe589d0, 0x9096ea6f3848984f_3ff0d2c85def7622, 0xb4bca50b065abe63_0fed077a756b53aa, 0xe1ebce4dc7f16dfb_d3e8495912c62895, 0x8d3360f09cf6e4bd_64712dd7abbbd95d, 0xb080392cc4349dec_bd8d794d96aacfb4, 0xdca04777f541c567_ecf0d7a0fc5583a1, 0x89e42caaf9491b60_f41686c49db57245, 0xac5d37d5b79b6239_311c2875c522ced6, 0xd77485cb25823ac7_7d633293366b828c, 0x86a8d39ef77164bc_ae5dff9c02033198, 0xa8530886b54dbdeb_d9f57f830283fdfd, 0xd267caa862a12d66_d072df63c324fd7c, 0x8380dea93da4bc60_4247cb9e59f71e6e, 0xa46116538d0deb78_52d9be85f074e609, 0xcd795be870516656_67902e276c921f8c, 0x806bd9714632dff6_00ba1cd8a3db53b7, 0xa086cfcd97bf97f3_80e8a40eccd228a5, 0xc8a883c0fdaf7df0_6122cd128006b2ce, 0xfad2a4b13d1b5d6c_796b805720085f82, 0x9cc3a6eec6311a63_cbe3303674053bb1, 0xc3f490aa77bd60fc_bedbfc4411068a9d, 0xf4f1b4d515acb93b_ee92fb5515482d45, 0x991711052d8bf3c5_751bdd152d4d1c4b, 0xbf5cd54678eef0b6_d262d45a78a0635e, 0xef340a98172aace4_86fb897116c87c35, 0x9580869f0e7aac0e_d45d35e6ae3d4da1, 0xbae0a846d2195712_8974836059cca10a, 0xe998d258869facd7_2bd1a438703fc94c, 0x91ff83775423cc06_7b6306a34627ddd0, 0xb67f6455292cbf08_1a3bc84c17b1d543, 0xe41f3d6a7377eeca_20caba5f1d9e4a94, 0x8e938662882af53e_547eb47b7282ee9d, 0xb23867fb2a35b28d_e99e619a4f23aa44, 0xdec681f9f4c31f31_6405fa00e2ec94d5, 0x8b3c113c38f9f37e_de83bc408dd3dd05, 0xae0b158b4738705e_9624ab50b148d446, 0xd98ddaee19068c76_3badd624dd9b0958, 0x87f8a8d4cfa417c9_e54ca5d70a80e5d7, 0xa9f6d30a038d1dbc_5e9fcf4ccd211f4d, 0xd47487cc8470652b_7647c32000696720, 0x84c8d4dfd2c63f3b_29ecd9f40041e074, 0xa5fb0a17c777cf09_f468107100525891, 0xcf79cc9db955c2cc_7182148d4066eeb5, 0x81ac1fe293d599bf_c6f14cd848405531, 0xa21727db38cb002f_b8ada00e5a506a7d, 0xca9cf1d206fdc03b_a6d90811f0e4851d, 0xfd442e4688bd304a_908f4a166d1da664, 0x9e4a9cec15763e2e_9a598e4e043287ff, 0xc5dd44271ad3cdba_40eff1e1853f29fe, 0xf7549530e188c128_d12bee59e68ef47d, 0x9a94dd3e8cf578b9_82bb74f8301958cf, 0xc13a148e3032d6e7_e36a52363c1faf02, 0xf18899b1bc3f8ca1_dc44e6c3cb279ac2, 0x96f5600f15a7b7e5_29ab103a5ef8c0ba, 0xbcb2b812db11a5de_7415d448f6b6f0e8, 0xebdf661791d60f56_111b495b3464ad22, 0x936b9fcebb25c995_cab10dd900beec35, 0xb84687c269ef3bfb_3d5d514f40eea743, 0xe65829b3046b0afa_0cb4a5a3112a5113, 0x8ff71a0fe2c2e6dc_47f0e785eaba72ac, 0xb3f4e093db73a093_59ed216765690f57, 0xe0f218b8d25088b8_306869c13ec3532d, 0x8c974f7383725573_1e414218c73a13fc, 0xafbd2350644eeacf_e5d1929ef90898fb, 0xdbac6c247d62a583_df45f746b74abf3a, 0x894bc396ce5da772_6b8bba8c328eb784, 0xab9eb47c81f5114f_066ea92f3f326565, 0xd686619ba27255a2_c80a537b0efefebe, 0x8613fd0145877585_bd06742ce95f5f37, 0xa798fc4196e952e7_2c48113823b73705, 0xd17f3b51fca3a7a0_f75a15862ca504c6, 0x82ef85133de648c4_9a984d73dbe722fc, 0xa3ab66580d5fdaf5_c13e60d0d2e0ebbb, 0xcc963fee10b7d1b3_318df905079926a9, 0xffbbcfe994e5c61f_fdf17746497f7053, 0x9fd561f1fd0f9bd3_feb6ea8bedefa634, 0xc7caba6e7c5382c8_fe64a52ee96b8fc1, 0xf9bd690a1b68637b_3dfdce7aa3c673b1, 0x9c1661a651213e2d_06bea10ca65c084f, 0xc31bfa0fe5698db8_486e494fcff30a63, 0xf3e2f893dec3f126_5a89dba3c3efccfb, 0x986ddb5c6b3a76b7_f89629465a75e01d, 0xbe89523386091465_f6bbb397f1135824, 0xee2ba6c0678b597f_746aa07ded582e2d, 0x94db483840b717ef_a8c2a44eb4571cdd, 0xba121a4650e4ddeb_92f34d62616ce414, 0xe896a0d7e51e1566_77b020baf9c81d18, 0x915e2486ef32cd60_0ace1474dc1d122f, 0xb5b5ada8aaff80b8_0d819992132456bb, 0xe3231912d5bf60e6_10e1fff697ed6c6a, 0x8df5efabc5979c8f_ca8d3ffa1ef463c2, 0xb1736b96b6fd83b3_bd308ff8a6b17cb3, 0xddd0467c64bce4a0_ac7cb3f6d05ddbdf, 0x8aa22c0dbef60ee4_6bcdf07a423aa96c, 0xad4ab7112eb3929d_86c16c98d2c953c7, 0xd89d64d57a607744_e871c7bf077ba8b8, 0x87625f056c7c4a8b_11471cd764ad4973, 0xa93af6c6c79b5d2d_d598e40d3dd89bd0, 0xd389b47879823479_4aff1d108d4ec2c4, 0x843610cb4bf160cb_cedf722a585139bb, 0xa54394fe1eedb8fe_c2974eb4ee658829, 0xce947a3da6a9273e_733d226229feea33, 0x811ccc668829b887_0806357d5a3f5260, 0xa163ff802a3426a8_ca07c2dcb0cf26f8, 0xc9bcff6034c13052_fc89b393dd02f0b6, 0xfc2c3f3841f17c67_bbac2078d443ace3, 0x9d9ba7832936edc0_d54b944b84aa4c0e, 0xc5029163f384a931_0a9e795e65d4df12, 0xf64335bcf065d37d_4d4617b5ff4a16d6, 0x99ea0196163fa42e_504bced1bf8e4e46, 0xc06481fb9bcf8d39_e45ec2862f71e1d7, 0xf07da27a82c37088_5d767327bb4e5a4d, 0x964e858c91ba2655_3a6a07f8d510f870, 0xbbe226efb628afea_890489f70a55368c, 0xeadab0aba3b2dbe5_2b45ac74ccea842f, 0x92c8ae6b464fc96f_3b0b8bc90012929e, 0xb77ada0617e3bbcb_09ce6ebb40173745, 0xe55990879ddcaabd_cc420a6a101d0516, 0x8f57fa54c2a9eab6_9fa946824a12232e, 0xb32df8e9f3546564_47939822dc96abfa, 0xdff9772470297ebd_59787e2b93bc56f8, 0x8bfbea76c619ef36_57eb4edb3c55b65b, 0xaefae51477a06b03_ede622920b6b23f2, 0xdab99e59958885c4_e95fab368e45ecee, 0x88b402f7fd75539b_11dbcb0218ebb415, 0xaae103b5fcd2a881_d652bdc29f26a11a, 0xd59944a37c0752a2_4be76d3346f04960, 0x857fcae62d8493a5_6f70a4400c562ddc, 0xa6dfbd9fb8e5b88e_cb4ccd500f6bb953, 0xd097ad07a71f26b2_7e2000a41346a7a8, 0x825ecc24c873782f_8ed400668c0c28c9, 0xa2f67f2dfa90563b_728900802f0f32fb, 0xcbb41ef979346bca_4f2b40a03ad2ffba, 0xfea126b7d78186bc_e2f610c84987bfa9, 0x9f24b832e6b0f436_0dd9ca7d2df4d7ca, 0xc6ede63fa05d3143_91503d1c79720dbc, 0xf8a95fcf88747d94_75a44c6397ce912b, 0x9b69dbe1b548ce7c_c986afbe3ee11abb, 0xc24452da229b021b_fbe85badce996169, 0xf2d56790ab41c2a2_fae27299423fb9c4, 0x97c560ba6b0919a5_dccd879fc967d41b, 0xbdb6b8e905cb600f_5400e987bbc1c921, 0xed246723473e3813_290123e9aab23b69, 0x9436c0760c86e30b_f9a0b6720aaf6522, 0xb94470938fa89bce_f808e40e8d5b3e6a, 0xe7958cb87392c2c2_b60b1d1230b20e05, 0x90bd77f3483bb9b9_b1c6f22b5e6f48c3, 0xb4ecd5f01a4aa828_1e38aeb6360b1af4, 0xe2280b6c20dd5232_25c6da63c38de1b1, 0x8d590723948a535f_579c487e5a38ad0f, 0xb0af48ec79ace837_2d835a9df0c6d852, 0xdcdb1b2798182244_f8e431456cf88e66, 0x8a08f0f8bf0f156b_1b8e9ecb641b5900, 0xac8b2d36eed2dac5_e272467e3d222f40, 0xd7adf884aa879177_5b0ed81dcc6abb10, 0x86ccbb52ea94baea_98e947129fc2b4ea, 0xa87fea27a539e9a5_3f2398d747b36225, 0xd29fe4b18e88640e_8eec7f0d19a03aae, 0x83a3eeeef9153e89_1953cf68300424ad, 0xa48ceaaab75a8e2b_5fa8c3423c052dd8, 0xcdb02555653131b6_3792f412cb06794e, 0x808e17555f3ebf11_e2bbd88bbee40bd1, 0xa0b19d2ab70e6ed6_5b6aceaeae9d0ec5, 0xc8de047564d20a8b_f245825a5a445276, 0xfb158592be068d2e_eed6e2f0f0d56713, 0x9ced737bb6c4183d_55464dd69685606c, 0xc428d05aa4751e4c_aa97e14c3c26b887, 0xf53304714d9265df_d53dd99f4b3066a9, 0x993fe2c6d07b7fab_e546a8038efe402a, 0xbf8fdb78849a5f96_de98520472bdd034, 0xef73d256a5c0f77c_963e66858f6d4441, 0x95a8637627989aad_dde7001379a44aa9, 0xbb127c53b17ec159_5560c018580d5d53, 0xe9d71b689dde71af_aab8f01e6e10b4a7, 0x9226712162ab070d_cab3961304ca70e9, 0xb6b00d69bb55c8d1_3d607b97c5fd0d23, 0xe45c10c42a2b3b05_8cb89a7db77c506b, 0x8eb98a7a9a5b04e3_77f3608e92adb243, 0xb267ed1940f1c61c_55f038b237591ed4, 0xdf01e85f912e37a3_6b6c46dec52f6689, 0x8b61313bbabce2c6_2323ac4b3b3da016, 0xae397d8aa96c1b77_abec975e0a0d081b, 0xd9c7dced53c72255_96e7bd358c904a22, 0x881cea14545c7575_7e50d64177da2e55, 0xaa242499697392d2_dde50bd1d5d0b9ea, 0xd4ad2dbfc3d07787_955e4ec64b44e865, 0x84ec3c97da624ab4_bd5af13bef0b113f, 0xa6274bbdd0fadd61_ecb1ad8aeacdd58f, 0xcfb11ead453994ba_67de18eda5814af3, 0x81ceb32c4b43fcf4_80eacf948770ced8, 0xa2425ff75e14fc31_a1258379a94d028e, 0xcad2f7f5359a3b3e_096ee45813a04331, 0xfd87b5f28300ca0d_8bca9d6e188853fd, 0x9e74d1b791e07e48_775ea264cf55347e, 0xc612062576589dda_95364afe032a819e, 0xf79687aed3eec551_3a83ddbd83f52205, 0x9abe14cd44753b52_c4926a9672793543, 0xc16d9a0095928a27_75b7053c0f178294, 0xf1c90080baf72cb1_5324c68b12dd6339, 0x971da05074da7bee_d3f6fc16ebca5e04, 0xbce5086492111aea_88f4bb1ca6bcf585, 0xec1e4a7db69561a5_2b31e9e3d06c32e6, 0x9392ee8e921d5d07_3aff322e62439fd0, 0xb877aa3236a4b449_09befeb9fad487c3, 0xe69594bec44de15b_4c2ebe687989a9b4, 0x901d7cf73ab0acd9_0f9d37014bf60a11, 0xb424dc35095cd80f_538484c19ef38c95, 0xe12e13424bb40e13_2865a5f206b06fba, 0x8cbccc096f5088cb_f93f87b7442e45d4, 0xafebff0bcb24aafe_f78f69a51539d749, 0xdbe6fecebdedd5be_b573440e5a884d1c, 0x89705f4136b4a597_31680a88f8953031, 0xabcc77118461cefc_fdc20d2b36ba7c3e, 0xd6bf94d5e57a42bc_3d32907604691b4d, 0x8637bd05af6c69b5_a63f9a49c2c1b110, 0xa7c5ac471b478423_0fcf80dc33721d54, 0xd1b71758e219652b_d3c36113404ea4a9, 0x83126e978d4fdf3b_645a1cac083126ea, 0xa3d70a3d70a3d70a_3d70a3d70a3d70a4, 0xcccccccccccccccc_cccccccccccccccd, 0x8000000000000000_0000000000000000, 0xa000000000000000_0000000000000000, 0xc800000000000000_0000000000000000, 0xfa00000000000000_0000000000000000, 0x9c40000000000000_0000000000000000, 0xc350000000000000_0000000000000000, 0xf424000000000000_0000000000000000, 0x9896800000000000_0000000000000000, 0xbebc200000000000_0000000000000000, 0xee6b280000000000_0000000000000000, 0x9502f90000000000_0000000000000000, 0xba43b74000000000_0000000000000000, 0xe8d4a51000000000_0000000000000000, 0x9184e72a00000000_0000000000000000, 0xb5e620f480000000_0000000000000000, 0xe35fa931a0000000_0000000000000000, 0x8e1bc9bf04000000_0000000000000000, 0xb1a2bc2ec5000000_0000000000000000, 0xde0b6b3a76400000_0000000000000000, 0x8ac7230489e80000_0000000000000000, 0xad78ebc5ac620000_0000000000000000, 0xd8d726b7177a8000_0000000000000000, 0x878678326eac9000_0000000000000000, 0xa968163f0a57b400_0000000000000000, 0xd3c21bcecceda100_0000000000000000, 0x84595161401484a0_0000000000000000, 0xa56fa5b99019a5c8_0000000000000000, 0xcecb8f27f4200f3a_0000000000000000, 0x813f3978f8940984_4000000000000000, 0xa18f07d736b90be5_5000000000000000, 0xc9f2c9cd04674ede_a400000000000000, 0xfc6f7c4045812296_4d00000000000000, 0x9dc5ada82b70b59d_f020000000000000, 0xc5371912364ce305_6c28000000000000, 0xf684df56c3e01bc6_c732000000000000, 0x9a130b963a6c115c_3c7f400000000000, 0xc097ce7bc90715b3_4b9f100000000000, 0xf0bdc21abb48db20_1e86d40000000000, 0x96769950b50d88f4_1314448000000000, 0xbc143fa4e250eb31_17d955a000000000, 0xeb194f8e1ae525fd_5dcfab0800000000, 0x92efd1b8d0cf37be_5aa1cae500000000, 0xb7abc627050305ad_f14a3d9e40000000, 0xe596b7b0c643c719_6d9ccd05d0000000, 0x8f7e32ce7bea5c6f_e4820023a2000000, 0xb35dbf821ae4f38b_dda2802c8a800000, 0xe0352f62a19e306e_d50b2037ad200000, 0x8c213d9da502de45_4526f422cc340000, 0xaf298d050e4395d6_9670b12b7f410000, 0xdaf3f04651d47b4c_3c0cdd765f114000, 0x88d8762bf324cd0f_a5880a69fb6ac800, 0xab0e93b6efee0053_8eea0d047a457a00, 0xd5d238a4abe98068_72a4904598d6d880, 0x85a36366eb71f041_47a6da2b7f864750, 0xa70c3c40a64e6c51_999090b65f67d924, 0xd0cf4b50cfe20765_fff4b4e3f741cf6d, 0x82818f1281ed449f_bff8f10e7a8921a4, 0xa321f2d7226895c7_aff72d52192b6a0d, 0xcbea6f8ceb02bb39_9bf4f8a69f764490, 0xfee50b7025c36a08_02f236d04753d5b4, 0x9f4f2726179a2245_01d762422c946590, 0xc722f0ef9d80aad6_424d3ad2b7b97ef5, 0xf8ebad2b84e0d58b_d2e0898765a7deb2, 0x9b934c3b330c8577_63cc55f49f88eb2f, 0xc2781f49ffcfa6d5_3cbf6b71c76b25fb, 0xf316271c7fc3908a_8bef464e3945ef7a, 0x97edd871cfda3a56_97758bf0e3cbb5ac, 0xbde94e8e43d0c8ec_3d52eeed1cbea317, 0xed63a231d4c4fb27_4ca7aaa863ee4bdd, 0x945e455f24fb1cf8_8fe8caa93e74ef6a, 0xb975d6b6ee39e436_b3e2fd538e122b44, 0xe7d34c64a9c85d44_60dbbca87196b616, 0x90e40fbeea1d3a4a_bc8955e946fe31cd, 0xb51d13aea4a488dd_6babab6398bdbe41, 0xe264589a4dcdab14_c696963c7eed2dd1, 0x8d7eb76070a08aec_fc1e1de5cf543ca2, 0xb0de65388cc8ada8_3b25a55f43294bcb, 0xdd15fe86affad912_49ef0eb713f39ebe, 0x8a2dbf142dfcc7ab_6e3569326c784337, 0xacb92ed9397bf996_49c2c37f07965404, 0xd7e77a8f87daf7fb_dc33745ec97be906, 0x86f0ac99b4e8dafd_69a028bb3ded71a3, 0xa8acd7c0222311bc_c40832ea0d68ce0c, 0xd2d80db02aabd62b_f50a3fa490c30190, 0x83c7088e1aab65db_792667c6da79e0fa, 0xa4b8cab1a1563f52_577001b891185938, 0xcde6fd5e09abcf26_ed4c0226b55e6f86, 0x80b05e5ac60b6178_544f8158315b05b4, 0xa0dc75f1778e39d6_696361ae3db1c721, 0xc913936dd571c84c_03bc3a19cd1e38e9, 0xfb5878494ace3a5f_04ab48a04065c723, 0x9d174b2dcec0e47b_62eb0d64283f9c76, 0xc45d1df942711d9a_3ba5d0bd324f8394, 0xf5746577930d6500_ca8f44ec7ee36479, 0x9968bf6abbe85f20_7e998b13cf4e1ecb, 0xbfc2ef456ae276e8_9e3fedd8c321a67e, 0xefb3ab16c59b14a2_c5cfe94ef3ea101e, 0x95d04aee3b80ece5_bba1f1d158724a12, 0xbb445da9ca61281f_2a8a6e45ae8edc97, 0xea1575143cf97226_f52d09d71a3293bd, 0x924d692ca61be758_593c2626705f9c56, 0xb6e0c377cfa2e12e_6f8b2fb00c77836c, 0xe498f455c38b997a_0b6dfb9c0f956447, 0x8edf98b59a373fec_4724bd4189bd5eac, 0xb2977ee300c50fe7_58edec91ec2cb657, 0xdf3d5e9bc0f653e1_2f2967b66737e3ed, 0x8b865b215899f46c_bd79e0d20082ee74, 0xae67f1e9aec07187_ecd8590680a3aa11, 0xda01ee641a708de9_e80e6f4820cc9495, 0x884134fe908658b2_3109058d147fdcdd, 0xaa51823e34a7eede_bd4b46f0599fd415, 0xd4e5e2cdc1d1ea96_6c9e18ac7007c91a, 0x850fadc09923329e_03e2cf6bc604ddb0, 0xa6539930bf6bff45_84db8346b786151c, 0xcfe87f7cef46ff16_e612641865679a63, 0x81f14fae158c5f6e_4fcb7e8f3f60c07e, 0xa26da3999aef7749_e3be5e330f38f09d, 0xcb090c8001ab551c_5cadf5bfd3072cc5, 0xfdcb4fa002162a63_73d9732fc7c8f7f6, 0x9e9f11c4014dda7e_2867e7fddcdd9afa, 0xc646d63501a1511d_b281e1fd541501b8, 0xf7d88bc24209a565_1f225a7ca91a4226, 0x9ae757596946075f_3375788de9b06958, 0xc1a12d2fc3978937_0052d6b1641c83ae, 0xf209787bb47d6b84_c0678c5dbd23a49a, 0x9745eb4d50ce6332_f840b7ba963646e0, 0xbd176620a501fbff_b650e5a93bc3d898, 0xec5d3fa8ce427aff_a3e51f138ab4cebe, 0x93ba47c980e98cdf_c66f336c36b10137, 0xb8a8d9bbe123f017_b80b0047445d4184, 0xe6d3102ad96cec1d_a60dc059157491e5, 0x9043ea1ac7e41392_87c89837ad68db2f, 0xb454e4a179dd1877_29babe4598c311fb, 0xe16a1dc9d8545e94_f4296dd6fef3d67a, 0x8ce2529e2734bb1d_1899e4a65f58660c, 0xb01ae745b101e9e4_5ec05dcff72e7f8f, 0xdc21a1171d42645d_76707543f4fa1f73, 0x899504ae72497eba_6a06494a791c53a8, 0xabfa45da0edbde69_0487db9d17636892, 0xd6f8d7509292d603_45a9d2845d3c42b6, 0x865b86925b9bc5c2_0b8a2392ba45a9b2, 0xa7f26836f282b732_8e6cac7768d7141e, 0xd1ef0244af2364ff_3207d795430cd926, 0x8335616aed761f1f_7f44e6bd49e807b8, 0xa402b9c5a8d3a6e7_5f16206c9c6209a6, 0xcd036837130890a1_36dba887c37a8c0f, 0x802221226be55a64_c2494954da2c9789, 0xa02aa96b06deb0fd_f2db9baa10b7bd6c, 0xc83553c5c8965d3d_6f92829494e5acc7, 0xfa42a8b73abbf48c_cb772339ba1f17f9, 0x9c69a97284b578d7_ff2a760414536efb, 0xc38413cf25e2d70d_fef5138519684aba, 0xf46518c2ef5b8cd1_7eb258665fc25d69, 0x98bf2f79d5993802_ef2f773ffbd97a61, 0xbeeefb584aff8603_aafb550ffacfd8fa, 0xeeaaba2e5dbf6784_95ba2a53f983cf38, 0x952ab45cfa97a0b2_dd945a747bf26183, 0xba756174393d88df_94f971119aeef9e4, 0xe912b9d1478ceb17_7a37cd5601aab85d, 0x91abb422ccb812ee_ac62e055c10ab33a, 0xb616a12b7fe617aa_577b986b314d6009, 0xe39c49765fdf9d94_ed5a7e85fda0b80b, 0x8e41ade9fbebc27d_14588f13be847307, 0xb1d219647ae6b31c_596eb2d8ae258fc8, 0xde469fbd99a05fe3_6fca5f8ed9aef3bb, 0x8aec23d680043bee_25de7bb9480d5854, 0xada72ccc20054ae9_af561aa79a10ae6a, 0xd910f7ff28069da4_1b2ba1518094da04, 0x87aa9aff79042286_90fb44d2f05d0842, 0xa99541bf57452b28_353a1607ac744a53, 0xd3fa922f2d1675f2_42889b8997915ce8, 0x847c9b5d7c2e09b7_69956135febada11, 0xa59bc234db398c25_43fab9837e699095, 0xcf02b2c21207ef2e_94f967e45e03f4bb, 0x8161afb94b44f57d_1d1be0eebac278f5, 0xa1ba1ba79e1632dc_6462d92a69731732, 0xca28a291859bbf93_7d7b8f7503cfdcfe, 0xfcb2cb35e702af78_5cda735244c3d43e, 0x9defbf01b061adab_3a0888136afa64a7, 0xc56baec21c7a1916_088aaa1845b8fdd0, 0xf6c69a72a3989f5b_8aad549e57273d45, 0x9a3c2087a63f6399_36ac54e2f678864b, 0xc0cb28a98fcf3c7f_84576a1bb416a7dd, 0xf0fdf2d3f3c30b9f_656d44a2a11c51d5, 0x969eb7c47859e743_9f644ae5a4b1b325, 0xbc4665b596706114_873d5d9f0dde1fee, 0xeb57ff22fc0c7959_a90cb506d155a7ea, 0x9316ff75dd87cbd8_09a7f12442d588f2, 0xb7dcbf5354e9bece_0c11ed6d538aeb2f, 0xe5d3ef282a242e81_8f1668c8a86da5fa, 0x8fa475791a569d10_f96e017d694487bc, 0xb38d92d760ec4455_37c981dcc395a9ac, 0xe070f78d3927556a_85bbe253f47b1417, 0x8c469ab843b89562_93956d7478ccec8e, 0xaf58416654a6babb_387ac8d1970027b2, 0xdb2e51bfe9d0696a_06997b05fcc0319e, 0x88fcf317f22241e2_441fece3bdf81f03, 0xab3c2fddeeaad25a_d527e81cad7626c3, 0xd60b3bd56a5586f1_8a71e223d8d3b074, 0x85c7056562757456_f6872d5667844e49, 0xa738c6bebb12d16c_b428f8ac016561db, 0xd106f86e69d785c7_e13336d701beba52, 0x82a45b450226b39c_ecc0024661173473, 0xa34d721642b06084_27f002d7f95d0190, 0xcc20ce9bd35c78a5_31ec038df7b441f4, 0xff290242c83396ce_7e67047175a15271, 0x9f79a169bd203e41_0f0062c6e984d386, 0xc75809c42c684dd1_52c07b78a3e60868, 0xf92e0c3537826145_a7709a56ccdf8a82, 0x9bbcc7a142b17ccb_88a66076400bb691, 0xc2abf989935ddbfe_6acff893d00ea435, 0xf356f7ebf83552fe_0583f6b8c4124d43, 0x98165af37b2153de_c3727a337a8b704a, 0xbe1bf1b059e9a8d6_744f18c0592e4c5c, 0xeda2ee1c7064130c_1162def06f79df73, 0x9485d4d1c63e8be7_8addcb5645ac2ba8, 0xb9a74a0637ce2ee1_6d953e2bd7173692, 0xe8111c87c5c1ba99_c8fa8db6ccdd0437, 0x910ab1d4db9914a0_1d9c9892400a22a2, 0xb54d5e4a127f59c8_2503beb6d00cab4b, 0xe2a0b5dc971f303a_2e44ae64840fd61d, 0x8da471a9de737e24_5ceaecfed289e5d2, 0xb10d8e1456105dad_7425a83e872c5f47, 0xdd50f1996b947518_d12f124e28f77719, 0x8a5296ffe33cc92f_82bd6b70d99aaa6f, 0xace73cbfdc0bfb7b_636cc64d1001550b, 0xd8210befd30efa5a_3c47f7e05401aa4e, 0x8714a775e3e95c78_65acfaec34810a71, 0xa8d9d1535ce3b396_7f1839a741a14d0d, 0xd31045a8341ca07c_1ede48111209a050, 0x83ea2b892091e44d_934aed0aab460432, 0xa4e4b66b68b65d60_f81da84d5617853f, 0xce1de40642e3f4b9_36251260ab9d668e, 0x80d2ae83e9ce78f3_c1d72b7c6b426019, 0xa1075a24e4421730_b24cf65b8612f81f, 0xc94930ae1d529cfc_dee033f26797b627, 0xfb9b7cd9a4a7443c_169840ef017da3b1, 0x9d412e0806e88aa5_8e1f289560ee864e, 0xc491798a08a2ad4e_f1a6f2bab92a27e2, 0xf5b5d7ec8acb58a2_ae10af696774b1db, 0x9991a6f3d6bf1765_acca6da1e0a8ef29, 0xbff610b0cc6edd3f_17fd090a58d32af3, 0xeff394dcff8a948e_ddfc4b4cef07f5b0, 0x95f83d0a1fb69cd9_4abdaf101564f98e, 0xbb764c4ca7a4440f_9d6d1ad41abe37f1, 0xea53df5fd18d5513_84c86189216dc5ed, 0x92746b9be2f8552c_32fd3cf5b4e49bb4, 0xb7118682dbb66a77_3fbc8c33221dc2a1, 0xe4d5e82392a40515_0fabaf3feaa5334a, 0x8f05b1163ba6832d_29cb4d87f2a7400e, 0xb2c71d5bca9023f8_743e20e9ef511012, 0xdf78e4b2bd342cf6_914da9246b255416, 0x8bab8eefb6409c1a_1ad089b6c2f7548e, 0xae9672aba3d0c320_a184ac2473b529b1, 0xda3c0f568cc4f3e8_c9e5d72d90a2741e, 0x8865899617fb1871_7e2fa67c7a658892, 0xaa7eebfb9df9de8d_ddbb901b98feeab7, 0xd51ea6fa85785631_552a74227f3ea565, 0x8533285c936b35de_d53a88958f87275f, 0xa67ff273b8460356_8a892abaf368f137, 0xd01fef10a657842c_2d2b7569b0432d85, 0x8213f56a67f6b29b_9c3b29620e29fc73, 0xa298f2c501f45f42_8349f3ba91b47b8f, 0xcb3f2f7642717713_241c70a936219a73, 0xfe0efb53d30dd4d7_ed238cd383aa0110, 0x9ec95d1463e8a506_f4363804324a40aa, 0xc67bb4597ce2ce48_b143c6053edcd0d5, 0xf81aa16fdc1b81da_dd94b7868e94050a, 0x9b10a4e5e9913128_ca7cf2b4191c8326, 0xc1d4ce1f63f57d72_fd1c2f611f63a3f0, 0xf24a01a73cf2dccf_bc633b39673c8cec, 0x976e41088617ca01_d5be0503e085d813, 0xbd49d14aa79dbc82_4b2d8644d8a74e18, 0xec9c459d51852ba2_ddf8e7d60ed1219e, 0x93e1ab8252f33b45_cabb90e5c942b503, 0xb8da1662e7b00a17_3d6a751f3b936243, 0xe7109bfba19c0c9d_0cc512670a783ad4, 0x906a617d450187e2_27fb2b80668b24c5, 0xb484f9dc9641e9da_b1f9f660802dedf6, 0xe1a63853bbd26451_5e7873f8a0396973, 0x8d07e33455637eb2_db0b487b6423e1e8, 0xb049dc016abc5e5f_91ce1a9a3d2cda62, 0xdc5c5301c56b75f7_7641a140cc7810fb, 0x89b9b3e11b6329ba_a9e904c87fcb0a9d, 0xac2820d9623bf429_546345fa9fbdcd44, 0xd732290fbacaf133_a97c177947ad4095, 0x867f59a9d4bed6c0_49ed8eabcccc485d, 0xa81f301449ee8c70_5c68f256bfff5a74, 0xd226fc195c6a2f8c_73832eec6fff3111, 0x83585d8fd9c25db7_c831fd53c5ff7eab, 0xa42e74f3d032f525_ba3e7ca8b77f5e55, 0xcd3a1230c43fb26f_28ce1bd2e55f35eb, 0x80444b5e7aa7cf85_7980d163cf5b81b3, 0xa0555e361951c366_d7e105bcc332621f, 0xc86ab5c39fa63440_8dd9472bf3fefaa7, 0xfa856334878fc150_b14f98f6f0feb951, 0x9c935e00d4b9d8d2_6ed1bf9a569f33d3, 0xc3b8358109e84f07_0a862f80ec4700c8, 0xf4a642e14c6262c8_cd27bb612758c0fa, 0x98e7e9cccfbd7dbd_8038d51cb897789c, 0xbf21e44003acdd2c_e0470a63e6bd56c3, 0xeeea5d5004981478_1858ccfce06cac74, 0x95527a5202df0ccb_0f37801e0c43ebc8, 0xbaa718e68396cffd_d30560258f54e6ba, 0xe950df20247c83fd_47c6b82ef32a2069, 0x91d28b7416cdd27e_4cdc331d57fa5441, 0xb6472e511c81471d_e0133fe4adf8e952, 0xe3d8f9e563a198e5_58180fddd97723a6, 0x8e679c2f5e44ff8f_570f09eaa7ea7648, 0xb201833b35d63f73_2cd2cc6551e513da, 0xde81e40a034bcf4f_f8077f7ea65e58d1, 0x8b112e86420f6191_fb04afaf27faf782, 0xadd57a27d29339f6_79c5db9af1f9b563, 0xd94ad8b1c7380874_18375281ae7822bc, 0x87cec76f1c830548_8f2293910d0b15b5, 0xa9c2794ae3a3c69a_b2eb3875504ddb22, 0xd433179d9c8cb841_5fa60692a46151eb, 0x849feec281d7f328_dbc7c41ba6bcd333, 0xa5c7ea73224deff3_12b9b522906c0800, 0xcf39e50feae16bef_d768226b34870a00, 0x81842f29f2cce375_e6a1158300d46640, 0xa1e53af46f801c53_60495ae3c1097fd0, 0xca5e89b18b602368_385bb19cb14bdfc4, 0xfcf62c1dee382c42_46729e03dd9ed7b5, 0x9e19db92b4e31ba9_6c07a2c26a8346d1, 0xc5a05277621be293_c7098b7305241885, 0xf70867153aa2db38_b8cbee4fc66d1ea7, ];
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtCore/qeasingcurve.h // dst-file: /src/core/qeasingcurve.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 std::ops::Deref; use super::qpoint::*; // 773 // use super::qvector::*; // 775 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QEasingCurve_Class_Size() -> c_int; // proto: void QEasingCurve::QEasingCurve(const QEasingCurve & other); fn C_ZN12QEasingCurveC2ERKS_(arg0: *mut c_void) -> u64; // proto: void QEasingCurve::~QEasingCurve(); fn C_ZN12QEasingCurveD2Ev(qthis: u64 /* *mut c_void*/); // proto: EasingFunction QEasingCurve::customType(); fn C_ZNK12QEasingCurve10customTypeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: qreal QEasingCurve::overshoot(); fn C_ZNK12QEasingCurve9overshootEv(qthis: u64 /* *mut c_void*/) -> c_double; // proto: void QEasingCurve::setPeriod(qreal period); fn C_ZN12QEasingCurve9setPeriodEd(qthis: u64 /* *mut c_void*/, arg0: c_double); // proto: void QEasingCurve::addTCBSegment(const QPointF & nextPoint, qreal t, qreal c, qreal b); fn C_ZN12QEasingCurve13addTCBSegmentERK7QPointFddd(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_double, arg2: c_double, arg3: c_double); // proto: void QEasingCurve::addCubicBezierSegment(const QPointF & c1, const QPointF & c2, const QPointF & endPoint); fn C_ZN12QEasingCurve21addCubicBezierSegmentERK7QPointFS2_S2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void); // proto: qreal QEasingCurve::period(); fn C_ZNK12QEasingCurve6periodEv(qthis: u64 /* *mut c_void*/) -> c_double; // proto: qreal QEasingCurve::valueForProgress(qreal progress); fn C_ZNK12QEasingCurve16valueForProgressEd(qthis: u64 /* *mut c_void*/, arg0: c_double) -> c_double; // proto: void QEasingCurve::setAmplitude(qreal amplitude); fn C_ZN12QEasingCurve12setAmplitudeEd(qthis: u64 /* *mut c_void*/, arg0: c_double); // proto: void QEasingCurve::swap(QEasingCurve & other); fn C_ZN12QEasingCurve4swapERS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QEasingCurve::setOvershoot(qreal overshoot); fn C_ZN12QEasingCurve12setOvershootEd(qthis: u64 /* *mut c_void*/, arg0: c_double); // proto: QVector<QPointF> QEasingCurve::toCubicSpline(); fn C_ZNK12QEasingCurve13toCubicSplineEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: qreal QEasingCurve::amplitude(); fn C_ZNK12QEasingCurve9amplitudeEv(qthis: u64 /* *mut c_void*/) -> c_double; } // <= ext block end // body block begin => // class sizeof(QEasingCurve)=8 #[derive(Default)] pub struct QEasingCurve { // qbase: None, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QEasingCurve { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QEasingCurve { return QEasingCurve{qclsinst: qthis, ..Default::default()}; } } // proto: void QEasingCurve::QEasingCurve(const QEasingCurve & other); impl /*struct*/ QEasingCurve { pub fn new<T: QEasingCurve_new>(value: T) -> QEasingCurve { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QEasingCurve_new { fn new(self) -> QEasingCurve; } // proto: void QEasingCurve::QEasingCurve(const QEasingCurve & other); impl<'a> /*trait*/ QEasingCurve_new for (&'a QEasingCurve) { fn new(self) -> QEasingCurve { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QEasingCurveC2ERKS_()}; let ctysz: c_int = unsafe{QEasingCurve_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN12QEasingCurveC2ERKS_(arg0)}; let rsthis = QEasingCurve{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QEasingCurve::~QEasingCurve(); impl /*struct*/ QEasingCurve { pub fn free<RetType, T: QEasingCurve_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QEasingCurve_free<RetType> { fn free(self , rsthis: & QEasingCurve) -> RetType; } // proto: void QEasingCurve::~QEasingCurve(); impl<'a> /*trait*/ QEasingCurve_free<()> for () { fn free(self , rsthis: & QEasingCurve) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QEasingCurveD2Ev()}; unsafe {C_ZN12QEasingCurveD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: EasingFunction QEasingCurve::customType(); impl /*struct*/ QEasingCurve { pub fn customType<RetType, T: QEasingCurve_customType<RetType>>(& self, overload_args: T) -> RetType { return overload_args.customType(self); // return 1; } } pub trait QEasingCurve_customType<RetType> { fn customType(self , rsthis: & QEasingCurve) -> RetType; } // proto: EasingFunction QEasingCurve::customType(); impl<'a> /*trait*/ QEasingCurve_customType<u64> for () { fn customType(self , rsthis: & QEasingCurve) -> u64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QEasingCurve10customTypeEv()}; let mut ret = unsafe {C_ZNK12QEasingCurve10customTypeEv(rsthis.qclsinst)}; return ret as u64; // 3 // return 1; } } // proto: qreal QEasingCurve::overshoot(); impl /*struct*/ QEasingCurve { pub fn overshoot<RetType, T: QEasingCurve_overshoot<RetType>>(& self, overload_args: T) -> RetType { return overload_args.overshoot(self); // return 1; } } pub trait QEasingCurve_overshoot<RetType> { fn overshoot(self , rsthis: & QEasingCurve) -> RetType; } // proto: qreal QEasingCurve::overshoot(); impl<'a> /*trait*/ QEasingCurve_overshoot<f64> for () { fn overshoot(self , rsthis: & QEasingCurve) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QEasingCurve9overshootEv()}; let mut ret = unsafe {C_ZNK12QEasingCurve9overshootEv(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // proto: void QEasingCurve::setPeriod(qreal period); impl /*struct*/ QEasingCurve { pub fn setPeriod<RetType, T: QEasingCurve_setPeriod<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setPeriod(self); // return 1; } } pub trait QEasingCurve_setPeriod<RetType> { fn setPeriod(self , rsthis: & QEasingCurve) -> RetType; } // proto: void QEasingCurve::setPeriod(qreal period); impl<'a> /*trait*/ QEasingCurve_setPeriod<()> for (f64) { fn setPeriod(self , rsthis: & QEasingCurve) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QEasingCurve9setPeriodEd()}; let arg0 = self as c_double; unsafe {C_ZN12QEasingCurve9setPeriodEd(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QEasingCurve::addTCBSegment(const QPointF & nextPoint, qreal t, qreal c, qreal b); impl /*struct*/ QEasingCurve { pub fn addTCBSegment<RetType, T: QEasingCurve_addTCBSegment<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addTCBSegment(self); // return 1; } } pub trait QEasingCurve_addTCBSegment<RetType> { fn addTCBSegment(self , rsthis: & QEasingCurve) -> RetType; } // proto: void QEasingCurve::addTCBSegment(const QPointF & nextPoint, qreal t, qreal c, qreal b); impl<'a> /*trait*/ QEasingCurve_addTCBSegment<()> for (&'a QPointF, f64, f64, f64) { fn addTCBSegment(self , rsthis: & QEasingCurve) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QEasingCurve13addTCBSegmentERK7QPointFddd()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1 as c_double; let arg2 = self.2 as c_double; let arg3 = self.3 as c_double; unsafe {C_ZN12QEasingCurve13addTCBSegmentERK7QPointFddd(rsthis.qclsinst, arg0, arg1, arg2, arg3)}; // return 1; } } // proto: void QEasingCurve::addCubicBezierSegment(const QPointF & c1, const QPointF & c2, const QPointF & endPoint); impl /*struct*/ QEasingCurve { pub fn addCubicBezierSegment<RetType, T: QEasingCurve_addCubicBezierSegment<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addCubicBezierSegment(self); // return 1; } } pub trait QEasingCurve_addCubicBezierSegment<RetType> { fn addCubicBezierSegment(self , rsthis: & QEasingCurve) -> RetType; } // proto: void QEasingCurve::addCubicBezierSegment(const QPointF & c1, const QPointF & c2, const QPointF & endPoint); impl<'a> /*trait*/ QEasingCurve_addCubicBezierSegment<()> for (&'a QPointF, &'a QPointF, &'a QPointF) { fn addCubicBezierSegment(self , rsthis: & QEasingCurve) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QEasingCurve21addCubicBezierSegmentERK7QPointFS2_S2_()}; 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_ZN12QEasingCurve21addCubicBezierSegmentERK7QPointFS2_S2_(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: qreal QEasingCurve::period(); impl /*struct*/ QEasingCurve { pub fn period<RetType, T: QEasingCurve_period<RetType>>(& self, overload_args: T) -> RetType { return overload_args.period(self); // return 1; } } pub trait QEasingCurve_period<RetType> { fn period(self , rsthis: & QEasingCurve) -> RetType; } // proto: qreal QEasingCurve::period(); impl<'a> /*trait*/ QEasingCurve_period<f64> for () { fn period(self , rsthis: & QEasingCurve) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QEasingCurve6periodEv()}; let mut ret = unsafe {C_ZNK12QEasingCurve6periodEv(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // proto: qreal QEasingCurve::valueForProgress(qreal progress); impl /*struct*/ QEasingCurve { pub fn valueForProgress<RetType, T: QEasingCurve_valueForProgress<RetType>>(& self, overload_args: T) -> RetType { return overload_args.valueForProgress(self); // return 1; } } pub trait QEasingCurve_valueForProgress<RetType> { fn valueForProgress(self , rsthis: & QEasingCurve) -> RetType; } // proto: qreal QEasingCurve::valueForProgress(qreal progress); impl<'a> /*trait*/ QEasingCurve_valueForProgress<f64> for (f64) { fn valueForProgress(self , rsthis: & QEasingCurve) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QEasingCurve16valueForProgressEd()}; let arg0 = self as c_double; let mut ret = unsafe {C_ZNK12QEasingCurve16valueForProgressEd(rsthis.qclsinst, arg0)}; return ret as f64; // 1 // return 1; } } // proto: void QEasingCurve::setAmplitude(qreal amplitude); impl /*struct*/ QEasingCurve { pub fn setAmplitude<RetType, T: QEasingCurve_setAmplitude<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setAmplitude(self); // return 1; } } pub trait QEasingCurve_setAmplitude<RetType> { fn setAmplitude(self , rsthis: & QEasingCurve) -> RetType; } // proto: void QEasingCurve::setAmplitude(qreal amplitude); impl<'a> /*trait*/ QEasingCurve_setAmplitude<()> for (f64) { fn setAmplitude(self , rsthis: & QEasingCurve) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QEasingCurve12setAmplitudeEd()}; let arg0 = self as c_double; unsafe {C_ZN12QEasingCurve12setAmplitudeEd(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QEasingCurve::swap(QEasingCurve & other); impl /*struct*/ QEasingCurve { pub fn swap<RetType, T: QEasingCurve_swap<RetType>>(& self, overload_args: T) -> RetType { return overload_args.swap(self); // return 1; } } pub trait QEasingCurve_swap<RetType> { fn swap(self , rsthis: & QEasingCurve) -> RetType; } // proto: void QEasingCurve::swap(QEasingCurve & other); impl<'a> /*trait*/ QEasingCurve_swap<()> for (&'a QEasingCurve) { fn swap(self , rsthis: & QEasingCurve) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QEasingCurve4swapERS_()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN12QEasingCurve4swapERS_(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QEasingCurve::setOvershoot(qreal overshoot); impl /*struct*/ QEasingCurve { pub fn setOvershoot<RetType, T: QEasingCurve_setOvershoot<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setOvershoot(self); // return 1; } } pub trait QEasingCurve_setOvershoot<RetType> { fn setOvershoot(self , rsthis: & QEasingCurve) -> RetType; } // proto: void QEasingCurve::setOvershoot(qreal overshoot); impl<'a> /*trait*/ QEasingCurve_setOvershoot<()> for (f64) { fn setOvershoot(self , rsthis: & QEasingCurve) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QEasingCurve12setOvershootEd()}; let arg0 = self as c_double; unsafe {C_ZN12QEasingCurve12setOvershootEd(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QVector<QPointF> QEasingCurve::toCubicSpline(); impl /*struct*/ QEasingCurve { pub fn toCubicSpline<RetType, T: QEasingCurve_toCubicSpline<RetType>>(& self, overload_args: T) -> RetType { return overload_args.toCubicSpline(self); // return 1; } } pub trait QEasingCurve_toCubicSpline<RetType> { fn toCubicSpline(self , rsthis: & QEasingCurve) -> RetType; } // proto: QVector<QPointF> QEasingCurve::toCubicSpline(); impl<'a> /*trait*/ QEasingCurve_toCubicSpline<u64> for () { fn toCubicSpline(self , rsthis: & QEasingCurve) -> u64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QEasingCurve13toCubicSplineEv()}; let mut ret = unsafe {C_ZNK12QEasingCurve13toCubicSplineEv(rsthis.qclsinst)}; return ret as u64; // 5 // return 1; } } // proto: qreal QEasingCurve::amplitude(); impl /*struct*/ QEasingCurve { pub fn amplitude<RetType, T: QEasingCurve_amplitude<RetType>>(& self, overload_args: T) -> RetType { return overload_args.amplitude(self); // return 1; } } pub trait QEasingCurve_amplitude<RetType> { fn amplitude(self , rsthis: & QEasingCurve) -> RetType; } // proto: qreal QEasingCurve::amplitude(); impl<'a> /*trait*/ QEasingCurve_amplitude<f64> for () { fn amplitude(self , rsthis: & QEasingCurve) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QEasingCurve9amplitudeEv()}; let mut ret = unsafe {C_ZNK12QEasingCurve9amplitudeEv(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // <= body block end
use std::result; use std::io::Error as IoError; use std::fmt; macro_rules! impl_error { ($from:ty, $to:path) => { impl From<$from> for Error { fn from(e: $from) -> Self { $to(format!("{:?}", e)) } } } } pub type Result<T> = result::Result<T, Error>; #[derive(Debug)] pub enum Error { IO(String), LicenseAPINotFound, LicenseAPIMustBeValid, LicenseAPIMustBeInConsistentState, LicenseCodeMustBeValid, TrialExpired, ProductExpired, SubscriptionExpired, } impl_error!{IoError, Error::IO} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let msg = match *self { Error::IO(ref e) => format!("{}", e), Error::LicenseAPINotFound => format!("Entitlement guru is hallucinating. License can’t be verified."), Error::LicenseAPIMustBeValid => format!("Entitlement library is tampered. License can’t be verified"), Error::LicenseCodeMustBeValid => format!("Entitlement library activate_code is tampered. License can’t be verified"), Error::LicenseAPIMustBeInConsistentState => format!("Entitlement library is not in consistent state. Can happen when library is not freed upon use. License can’t be verified."), Error::TrialExpired => format!("Entitlement trial expired. Please contact sales sales@rio.company to buy license."), Error::ProductExpired => format!("Entitlement trial expired. Please contact sales sales@rio.company to buy license."), Error::SubscriptionExpired => format!("Entitlement activation code invalid. Please contact sales@rio.company to buy license (or) provide a valid code."), }; write!(f, "{}", msg) } }
//! Module for API context management. //! //! This module defines traits and structs that can be used to manage //! contextual data related to a request, as it is passed through a series of //! hyper services. //! //! See the `context_tests` module below for examples of how to use. use crate::XSpanId; use crate::auth::{AuthData, Authorization}; use std::marker::Sized; /// Defines methods for accessing, modifying, adding and removing the data stored /// in a context. Used to specify the requirements that a hyper service makes on /// a generic context type that it receives with a request, e.g. /// /// ```rust /// # use openapi_context::context::*; /// # use futures::future::ok; /// # use std::future::Future; /// # use std::marker::PhantomData; /// # /// # struct MyItem; /// # fn do_something_with_my_item(item: &MyItem) {} /// # /// struct MyService<C> { /// marker: PhantomData<C>, /// } /// /// impl<C> hyper::service::Service for MyService<C> /// where C: Has<MyItem> + Send + 'static /// { /// type ReqBody = ContextualPayload<hyper::Body, C>; /// type ResBody = hyper::Body; /// type Error = std::io::Error; /// type Future = Box<dyn Future<Item=hyper::Response<Self::ResBody>, Error=Self::Error>>; /// fn call(&mut self, req : hyper::Request<Self::ReqBody>) -> Self::Future { /// let (head, body) = req.into_parts(); /// do_something_with_my_item(Has::<MyItem>::get(&body.context)); /// Box::new(ok(hyper::Response::new(hyper::Body::empty()))) /// } /// } /// /// # fn main() {} /// ``` pub trait Has<T> { /// Get an immutable reference to the value. fn get(&self) -> &T; /// Get a mutable reference to the value. fn get_mut(&mut self) -> &mut T; /// Set the value. fn set(&mut self, value: T); } /// Defines a method for permanently extracting a value, changing the resulting /// type. Used to specify that a hyper service consumes some data from the context, /// making it unavailable to later layers, e.g. /// /// ```rust /// # extern crate hyper; /// # extern crate swagger; /// # extern crate futures; /// # /// # use swagger::context::*; /// # use futures::future::{Future, ok}; /// # use std::marker::PhantomData; /// # /// struct MyItem1; /// struct MyItem2; /// struct MyItem3; /// /// struct MiddlewareService<T, C> { /// inner: T, /// marker: PhantomData<C>, /// } /// /// impl<T, C, D, E> hyper::service::Service for MiddlewareService<T, C> /// where /// C: Pop<MyItem1, Result=D> + Send + 'static, /// D: Pop<MyItem2, Result=E>, /// E: Pop<MyItem3>, /// E::Result: Send + 'static, /// T: hyper::service::Service<ReqBody=ContextualPayload<hyper::Body, E::Result>> /// { /// type ReqBody = ContextualPayload<hyper::Body, C>; /// type ResBody = T::ResBody; /// type Error = T::Error; /// type Future = T::Future; /// fn call(&mut self, req : hyper::Request<Self::ReqBody>) -> Self::Future { /// let (head, body) = req.into_parts(); /// let context = body.context; /// /// // type annotations optional, included for illustrative purposes /// let (_, context): (MyItem1, D) = context.pop(); /// let (_, context): (MyItem2, E) = context.pop(); /// let (_, context): (MyItem3, E::Result) = context.pop(); /// /// let req = hyper::Request::from_parts(head, ContextualPayload { inner: body.inner, context }); /// self.inner.call(req) /// } /// } /// /// # fn main() {} pub trait Pop<T> { /// The type that remains after the value has been popped. type Result; /// Extracts a value. fn pop(self) -> (T, Self::Result); } /// Defines a method for inserting a value, changing the resulting /// type. Used to specify that a hyper service adds some data from the context, /// making it available to later layers, e.g. /// /// ```rust /// # extern crate hyper; /// # extern crate swagger; /// # extern crate futures; /// # /// # use swagger::context::*; /// # use futures::future::{Future, ok}; /// # use std::marker::PhantomData; /// # /// struct MyItem1; /// struct MyItem2; /// struct MyItem3; /// /// struct MiddlewareService<T, C> { /// inner: T, /// marker: PhantomData<C>, /// } /// /// impl<T, C, D, E> hyper::service::Service for MiddlewareService<T, C> /// where /// C: Push<MyItem1, Result=D> + Send + 'static, /// D: Push<MyItem2, Result=E>, /// E: Push<MyItem3>, /// E::Result: Send + 'static, /// T: hyper::service::Service<ReqBody=ContextualPayload<hyper::Body, E::Result>> /// { /// type ReqBody = ContextualPayload<hyper::Body, C>; /// type ResBody = T::ResBody; /// type Error = T::Error; /// type Future = T::Future; /// fn call(&mut self, req : hyper::Request<Self::ReqBody>) -> Self::Future { /// let (head, body) = req.into_parts(); /// let context = body.context /// .push(MyItem1{}) /// .push(MyItem2{}) /// .push(MyItem3{}); /// let req = hyper::Request::from_parts(head, ContextualPayload { inner: body.inner, context }); /// self.inner.call(req) /// } /// } /// /// # fn main() {} pub trait Push<T> { /// The type that results from adding an item. type Result; /// Inserts a value. fn push(self, v: T) -> Self::Result; } /// Defines a struct that can be used to build up contexts recursively by /// adding one item to the context at a time, and a unit struct representing an /// empty context. The first argument is the name of the newly defined context struct /// that is used to add an item to the context, the second argument is the name of /// the empty context struct, and subsequent arguments are the types /// that can be stored in contexts built using these struct. /// /// A cons list built using the generated context type will implement Has<T> and Pop<T> /// for each type T that appears in the list, provided that the list only /// contains the types that were passed to the macro invocation after the context /// type name. /// /// All list types constructed using the generated types will implement `Push<T>` /// for all types `T` that appear in the list passed to the macro invocation. /// /// E.g. /// /// ```rust /// # use openapi_context::{new_context_type, Has, Pop, Push}; /// /// #[derive(Default)] /// struct MyType1; /// #[derive(Default)] /// struct MyType2; /// #[derive(Default)] /// struct MyType3; /// #[derive(Default)] /// struct MyType4; /// /// new_context_type!(MyContext, MyEmpContext, MyType1, MyType2, MyType3); /// /// fn use_has_my_type_1<T: Has<MyType1>> (_: &T) {} /// fn use_has_my_type_2<T: Has<MyType2>> (_: &T) {} /// fn use_has_my_type_3<T: Has<MyType3>> (_: &T) {} /// fn use_has_my_type_4<T: Has<MyType4>> (_: &T) {} /// /// // will implement `Has<MyType1>` and `Has<MyType2>` because these appear /// // in the type, and were passed to `new_context_type!`. Will not implement /// // `Has<MyType3>` even though it was passed to `new_context_type!`, because /// // it is not included in the type. /// type ExampleContext = MyContext<MyType1, MyContext<MyType2, MyEmpContext>>; /// /// // Will not implement `Has<MyType4>` even though it appears in the type, /// // because `MyType4` was not passed to `new_context_type!`. /// type BadContext = MyContext<MyType1, MyContext<MyType4, MyEmpContext>>; /// /// fn main() { /// let context : ExampleContext = /// MyEmpContext::default() /// .push(MyType2{}) /// .push(MyType1{}); /// /// use_has_my_type_1(&context); /// use_has_my_type_2(&context); /// // use_has_my_type_3(&context); // will fail /// /// // Will fail because `MyType4`// was not passed to `new_context_type!` /// // let context = MyEmpContext::default().push(MyType4{}); /// /// let bad_context: BadContext = BadContext::default(); /// // use_has_my_type_4(&bad_context); // will fail /// /// } /// ``` /// /// See the `context_tests` module for more usage examples. #[macro_export] macro_rules! new_context_type { ($context_name:ident, $empty_context_name:ident, $($types:ty),+ ) => { /// Wrapper type for building up contexts recursively, adding one item /// to the context at a time. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct $context_name<T, C> { head: T, tail: C, } /// Unit struct representing an empty context with no data in it. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct $empty_context_name; // implement `Push<T>` on the empty context type for each type `T` that // was passed to the macro $( impl Push<$types> for $empty_context_name { type Result = $context_name<$types, Self>; fn push(self, item: $types) -> Self::Result { $context_name{head: item, tail: Self::default()} } } // implement `Has<T>` for a list where `T` is the type of the head impl<C> $crate::Has<$types> for $context_name<$types, C> { fn set(&mut self, item: $types) { self.head = item; } fn get(&self) -> &$types { &self.head } fn get_mut(&mut self) -> &mut $types { &mut self.head } } // implement `Pop<T>` for a list where `T` is the type of the head impl<C> $crate::Pop<$types> for $context_name<$types, C> { type Result = C; fn pop(self) -> ($types, Self::Result) { (self.head, self.tail) } } // implement `Push<U>` for non-empty lists, for each type `U` that was passed // to the macro impl<C, T> Push<$types> for $context_name<T, C> { type Result = $context_name<$types, Self>; fn push(self, item: $types) -> Self::Result { $context_name{head: item, tail: self} } } )+ // Add implementations of `Has<T>` and `Pop<T>` when `T` is any type stored in // the list, not just the head. new_context_type!(impl extend_has $context_name, $empty_context_name, $($types),+); }; // "HELPER" MACRO CASE - NOT FOR EXTERNAL USE // takes a type `Type1` ($head) and a non-empty list of types `Types` ($tail). First calls // another helper macro to define the following impls, for each `Type2` in `Types`: // ``` // impl<C: Has<Type1> Has<Type1> for $context_name<Type2, C> {...} // impl<C: Has<Type2> Has<Type2> for $context_name<Type1, C> {...} // impl<C: Pop<Type1> Pop<Type1> for $context_name<Type2, C> {...} // impl<C: Pop<Type2> Pop<Type2> for $context_name<Type1, C> {...} // ``` // then calls itself again with the rest of the list. The end result is to define the above // impls for all distinct pairs of types in the original list. (impl extend_has $context_name:ident, $empty_context_name:ident, $head:ty, $($tail:ty),+ ) => { new_context_type!( impl extend_has_helper $context_name, $empty_context_name, $head, $($tail),+ ); new_context_type!(impl extend_has $context_name, $empty_context_name, $($tail),+); }; // "HELPER" MACRO CASE - NOT FOR EXTERNAL USE // base case of the preceding helper macro - was passed an empty list of types, so // we don't need to do anything. (impl extend_has $context_name:ident, $empty_context_name:ident, $head:ty) => {}; // "HELPER" MACRO CASE - NOT FOR EXTERNAL USE // takes a type `Type1` ($type) and a non-empty list of types `Types` ($types). For // each `Type2` in `Types`, defines the following impls: // ``` // impl<C: Has<Type1> Has<Type1> for $context_name<Type2, C> {...} // impl<C: Has<Type2> Has<Type2> for $context_name<Type1, C> {...} // impl<C: Pop<Type1> Pop<Type1> for $context_name<Type2, C> {...} // impl<C: Pop<Type2> Pop<Type2> for $context_name<Type1, C> {...} // ``` // (impl extend_has_helper $context_name:ident, $empty_context_name:ident, $type:ty, $($types:ty),+ ) => { $( impl<C: $crate::Has<$type>> $crate::Has<$type> for $context_name<$types, C> { fn set(&mut self, item: $type) { self.tail.set(item); } fn get(&self) -> &$type { self.tail.get() } fn get_mut(&mut self) -> &mut $type { self.tail.get_mut() } } impl<C: $crate::Has<$types>> $crate::Has<$types> for $context_name<$type, C> { fn set(&mut self, item: $types) { self.tail.set(item); } fn get(&self) -> &$types { self.tail.get() } fn get_mut(&mut self) -> &mut $types { self.tail.get_mut() } } impl<C> $crate::Pop<$type> for $context_name<$types, C> where C: Pop<$type> { type Result = $context_name<$types, C::Result>; fn pop(self) -> ($type, Self::Result) { let (value, tail) = self.tail.pop(); (value, $context_name{ head: self.head, tail}) } } impl<C> $crate::Pop<$types> for $context_name<$type, C> where C: Pop<$types> { type Result = $context_name<$type, C::Result>; fn pop(self) -> ($types, Self::Result) { let (value, tail) = self.tail.pop(); (value, $context_name{ head: self.head, tail}) } } )+ }; } // Create a default context type to export. new_context_type!( ContextBuilder, EmptyContext, XSpanId, Option<AuthData>, Option<Authorization> ); /// Macro for easily defining context types. The first argument should be a /// context type created with `new_context_type!` and subsequent arguments are the /// types to be stored in the context, with the outermost first. /// /// ```rust /// # use openapi_context::{new_context_type, make_context_ty, Has, Pop, Push}; /// /// # struct Type1; /// # struct Type2; /// # struct Type3; /// /// # new_context_type!(MyContext, MyEmptyContext, Type1, Type2, Type3); /// /// // the following two types are identical /// type ExampleContext1 = make_context_ty!(MyContext, MyEmptyContext, Type1, Type2, Type3); /// type ExampleContext2 = MyContext<Type1, MyContext<Type2, MyContext<Type3, MyEmptyContext>>>; /// /// // e.g. this wouldn't compile if they were different types /// fn do_nothing(input: ExampleContext1) -> ExampleContext2 { /// input /// } /// /// # fn main() {} /// ``` #[macro_export] macro_rules! make_context_ty { ($context_name:ident, $empty_context_name:ident, $type:ty $(, $types:ty)* $(,)* ) => { $context_name<$type, make_context_ty!($context_name, $empty_context_name, $($types),*)> }; ($context_name:ident, $empty_context_name:ident $(,)* ) => { $empty_context_name }; } /// Macro for easily defining context values. The first argument should be a /// context type created with `new_context_type!` and subsequent arguments are the /// values to be stored in the context, with the outermost first. /// /// ```rust /// # use openapi_context::{new_context_type, make_context, Has, Pop, Push}; /// /// # #[derive(PartialEq, Eq, Debug)] /// # struct Type1; /// # #[derive(PartialEq, Eq, Debug)] /// # struct Type2; /// # #[derive(PartialEq, Eq, Debug)] /// # struct Type3; /// /// # new_context_type!(MyContext, MyEmptyContext, Type1, Type2, Type3); /// /// fn main() { /// // the following are equivalent /// let context1 = make_context!(MyContext, MyEmptyContext, Type1 {}, Type2 {}, Type3 {}); /// let context2 = MyEmptyContext::default() /// .push(Type3{}) /// .push(Type2{}) /// .push(Type1{}); /// /// assert_eq!(context1, context2); /// } /// ``` #[macro_export] macro_rules! make_context { ($context_name:ident, $empty_context_name:ident, $value:expr $(, $values:expr)* $(,)*) => { make_context!($context_name, $empty_context_name, $($values),*).push($value) }; ($context_name:ident, $empty_context_name:ident $(,)* ) => { $empty_context_name::default() }; } /// Context wrapper, to bind an API with a context. #[derive(Debug)] pub struct ContextWrapper<T, C> { api: T, context: C, } impl<T, C> ContextWrapper<T, C> { /// Create a new ContextWrapper, binding the API and context. pub fn new(api: T, context: C) -> ContextWrapper<T, C> { ContextWrapper { api, context } } /// Borrows the API. pub fn api(&self) -> &T { &self.api } /// Borrows the API mutably. pub fn api_mut(&mut self) -> &mut T { &mut self.api } /// Borrows the context. pub fn context(&self) -> &C { &self.context } } impl<T: Clone, C: Clone> Clone for ContextWrapper<T, C> { fn clone(&self) -> Self { ContextWrapper { api: self.api.clone(), context: self.context.clone(), } } } /// Trait to extend an API to make it easy to bind it to a context. pub trait ContextWrapperExt<'a, C> where Self: Sized, { /// Binds this API to a context. fn with_context(self: Self, context: C) -> ContextWrapper<Self, C> { ContextWrapper::<Self, C>::new(self, context) } } /// This represents context provided as part of the request or the response #[derive(Debug)] pub struct ContextualPayload<Ctx> where Ctx: Send + 'static, { /// The inner payload for this request/response pub inner: hyper::Request<hyper::Body>, /// Request or Response Context pub context: Ctx, } #[cfg(test)] mod context_tests { use super::*; struct ContextItem1; struct ContextItem2; struct ContextItem3; fn use_item_1_owned(_: ContextItem1) {} fn use_item_2(_: &ContextItem2) {} fn use_item_3_owned(_: ContextItem3) {} // Example of use by a service in its main.rs file. At this point you know // all the hyper service layers you will be using, and what requirements // their contexts types have. Use the `new_context_type!` macro to create // a context type and empty context type that are capable of containing all the // types that your hyper services require. new_context_type!( MyContext, MyEmptyContext, ContextItem1, ContextItem2, ContextItem3 ); }
use proptest::prop_assert_eq; use liblumen_alloc::erts::term::prelude::*; use crate::erlang::binary_to_atom_2::result; use crate::test::strategy; #[test] fn without_binary_errors_badarg() { crate::test::without_binary_with_encoding_is_not_binary(file!(), result); } #[test] fn with_binary_without_atom_encoding_errors_badarg() { crate::test::with_binary_without_atom_encoding_errors_badarg(file!(), result); } #[test] fn with_binary_with_atom_without_name_encoding_errors_badarg() { crate::test::with_binary_with_atom_without_name_encoding_errors_badarg(file!(), result); } #[test] fn with_utf8_binary_with_encoding_returns_atom_with_binary_name() { run!( |arc_process| { ( strategy::term::binary::is_utf8(arc_process.clone()), strategy::term::is_encoding(), ) }, |(binary, encoding)| { let byte_vec: Vec<u8> = match binary.decode().unwrap() { TypedTerm::HeapBinary(heap_binary) => heap_binary.as_bytes().to_vec(), TypedTerm::SubBinary(subbinary) => subbinary.full_byte_iter().collect(), TypedTerm::ProcBin(process_binary) => process_binary.as_bytes().to_vec(), TypedTerm::BinaryLiteral(process_binary) => process_binary.as_bytes().to_vec(), typed_term => panic!("typed_term = {:?}", typed_term), }; let s = std::str::from_utf8(&byte_vec).unwrap(); prop_assert_eq!(result(binary, encoding), Ok(Atom::str_to_term(s))); 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 crate::registry::service_context::GenerateService; use crate::tests::fakes::base::Service; use failure::{format_err, Error}; use fuchsia_zircon as zx; use {parking_lot::RwLock, std::sync::Arc}; /// A helper class that gathers services through registration and directs /// the appropriate channels to them. pub struct ServiceRegistry { services: Vec<Arc<RwLock<dyn Service + Send + Sync>>>, } impl ServiceRegistry { pub fn create() -> Arc<RwLock<ServiceRegistry>> { return Arc::new(RwLock::new(ServiceRegistry { services: Vec::new() })); } pub fn register_service(&mut self, service: Arc<RwLock<dyn Service + Send + Sync>>) { self.services.push(service); } fn service_channel(&self, service_name: &str, channel: zx::Channel) -> Result<(), Error> { for service_handle in self.services.iter() { let service = service_handle.read(); if service.can_handle_service(service_name) { return service.process_stream(service_name, channel); } } return Err(format_err!("channel not handled for service: {}", service_name)); } pub fn serve(registry_handle: Arc<RwLock<ServiceRegistry>>) -> Option<GenerateService> { return Some(Box::new(move |service_name: &str, channel: zx::Channel| { return registry_handle.read().service_channel(service_name, channel); })); } }
use crate::controller; use crate::editor_transport; use crate::project_root::find_project_root; use crate::thread_worker::Worker; use crate::types::*; use crate::util::*; use crossbeam_channel::{after, never, select, Sender}; use lsp_types::notification::Notification; use lsp_types::*; use std::collections::HashMap; use std::time::Duration; struct ControllerHandle { worker: Worker<EditorRequest, Void>, } type Controllers = HashMap<Route, ControllerHandle>; /// Start the main event loop. /// /// This function starts editor transport and routes incoming editor requests to controllers. /// One controller is spawned per unique route, which is essentially a product of editor session, /// file type (represented as language id) and project (represented as project root path). /// /// `initial_request` could be passed to avoid extra synchronization churn if event loop is started /// as a result of request from editor. pub fn start(config: &Config, initial_request: Option<String>) -> i32 { info!("Starting main event loop"); let editor = editor_transport::start(&config.server.session, initial_request); if let Err(code) = editor { return code; } let editor = editor.unwrap(); let languages = config.language.clone(); let filetypes = filetype_to_language_id_map(config); let mut controllers: Controllers = HashMap::default(); let timeout = config.server.timeout; 'event_loop: loop { let timeout_channel = if timeout > 0 { after(Duration::from_secs(timeout)) } else { never() }; select! { recv(timeout_channel) -> _ => { info!("Exiting session after {} seconds of inactivity", timeout); break 'event_loop } recv(editor.from_editor) -> request => { // editor.receiver was closed, either because of the unrecoverable error or timeout // nothing we can do except to gracefully exit by stopping session // luckily, next `kak-lsp --request` invocation would spin up fresh session if request.is_err() { break 'event_loop; } // should be safe to unwrap as we just checked request for being None // done this way instead of `match` to reduce nesting let request = request.unwrap(); // editor explicitely asked us to stop kak-lsp session // (and we stop, even if other editor sessions are using this kak-lsp session) if request.method == "stop" { break 'event_loop; } // editor exited, we need to cleanup associated controllers if request.method == notification::Exit::METHOD { exit_editor_session(&mut controllers, &request); continue 'event_loop; } let language_id = filetypes.get(&request.meta.filetype); if language_id.is_none() { debug!( "Language server is not configured for filetype `{}`", &request.meta.filetype ); continue 'event_loop; } let language_id = language_id.unwrap(); let root_path = find_project_root(&language_id, &languages[language_id].roots, &request.meta.buffile); let route = Route { session: request.meta.session.clone(), language: language_id.clone(), root: root_path.clone(), }; debug!("Routing editor request to {:?}", route); use std::collections::hash_map::Entry; match controllers.entry(route.clone()) { Entry::Occupied(controller_entry) => { if controller_entry.get().worker.sender().send(request.clone()).is_err() { if let Some(fifo) = request.meta.fifo { cancel_blocking_request(fifo); } controller_entry.remove(); error!("Failed to send message to controller"); continue 'event_loop; } } Entry::Vacant(controller_entry) => { if let Some(fifo) = request.meta.fifo { cancel_blocking_request(fifo); // As Kakoune triggers BufClose after KakEnd we don't want to spawn a // new controller in that case. In normal situation it's unlikely to // get didClose message without running controller, unless it crashed // before. In that case didClose can be safely ignored as well. } else if request.method != notification::DidCloseTextDocument::METHOD { debug!("Spawning a new controller for {:?}", route); controller_entry.insert(spawn_controller( config.clone(), route, request, editor.to_editor.sender().clone(), )); } } } } } } stop_session(&mut controllers); 0 } /// When server is not running it's better to cancel blocking request. /// Because server can take a long time to initialize or can fail to start. /// We assume that it's less annoying for user to just repeat command later /// than to wait, cancel, and repeat. fn cancel_blocking_request(fifo: String) { debug!("Blocking request but LSP server is not running"); let command = "lsp-show-error 'Language server is not running, cancelling blocking request'"; std::fs::write(fifo, command).expect("Failed to write command to fifo"); } /// Reap controllers associated with editor session. fn exit_editor_session(controllers: &mut Controllers, request: &EditorRequest) { info!( "Editor session `{}` closed, shutting down associated language servers", request.meta.session ); controllers.retain(|route, controller| { if route.session == request.meta.session { info!("Exit {} in project {}", route.language, route.root); // to notify kak-lsp about editor session end we use the same `exit` notification as // used in LSP spec to notify language server to exit, thus we can just clone request // and pass it along if controller.worker.sender().send(request.clone()).is_err() { error!("Failed to send stop message to language server"); } false } else { true } }); } /// Shut down all language servers and exit. fn stop_session(controllers: &mut Controllers) { let request = EditorRequest { meta: EditorMeta { session: "".to_string(), buffile: "".to_string(), filetype: "".to_string(), client: None, version: 0, fifo: None, }, method: notification::Exit::METHOD.to_string(), params: toml::Value::Table(toml::value::Table::default()), ranges: None, }; info!("Shutting down language servers and exiting"); for (route, controller) in controllers.drain() { if controller.worker.sender().send(request.clone()).is_err() { error!("Failed to send stop message to language server"); } info!("Exit {} in project {}", route.language, route.root); } } fn spawn_controller( config: Config, route: Route, request: EditorRequest, to_editor: Sender<EditorResponse>, ) -> ControllerHandle { // NOTE 1024 is arbitrary let channel_capacity = 1024; let worker = Worker::spawn("Controller", channel_capacity, move |receiver, _| { controller::start(to_editor, receiver, &route, request, config); }); ControllerHandle { worker } }
//! service for scheduling compactor tasks. #![deny( rustdoc::broken_intra_doc_links, rust_2018_idioms, missing_debug_implementations, unreachable_pub )] #![warn( missing_docs, clippy::todo, clippy::dbg_macro, clippy::explicit_iter_loop, clippy::clone_on_ref_ptr, // See https://github.com/influxdata/influxdb_iox/pull/1671 clippy::future_not_send, unused_crate_dependencies )] #![allow(clippy::missing_docs_in_private_items)] use std::collections::HashSet; use backoff::BackoffConfig; use data_types::PartitionId; use iox_time::TimeProvider; // Workaround for "unused crate" lint false positives. use workspace_hack as _; pub(crate) mod commit; pub(crate) use commit::mock::MockCommit; pub use commit::{Commit, CommitWrapper, Error as CommitError}; mod error; pub use error::ErrorKind; mod local_scheduler; #[allow(unused_imports)] // for testing pub(crate) use local_scheduler::partition_done_sink::mock::MockPartitionDoneSink; pub use local_scheduler::{ combos::throttle_partition::Error as ThrottleError, partitions_source_config::PartitionsSourceConfig, shard_config::ShardConfig, LocalSchedulerConfig, }; pub(crate) use local_scheduler::{ combos::unique_partitions::Error as UniquePartitionsError, id_only_partition_filter::IdOnlyPartitionFilter, partition_done_sink::Error as PartitionDoneSinkError, partition_done_sink::PartitionDoneSink, LocalScheduler, }; // partitions_source trait mod partitions_source; pub(crate) use partitions_source::*; // scheduler trait and associated types mod scheduler; pub use scheduler::*; use std::sync::Arc; use iox_catalog::interface::Catalog; /// Instantiate a compaction scheduler service pub fn create_scheduler( config: SchedulerConfig, catalog: Arc<dyn Catalog>, time_provider: Arc<dyn TimeProvider>, metrics: Arc<metric::Registry>, shadow_mode: bool, ) -> Arc<dyn Scheduler> { match config { SchedulerConfig::Local(scheduler_config) => { let scheduler = LocalScheduler::new( scheduler_config, BackoffConfig::default(), catalog, time_provider, metrics, shadow_mode, ); Arc::new(scheduler) } } } /// Create a new [`Scheduler`] for testing. /// /// If no mocked_partition_ids, the scheduler will use a [`LocalScheduler`] in default configuration. /// Whereas if mocked_partition_ids are provided, the scheduler will use a [`LocalScheduler`] with [`PartitionsSourceConfig::Fixed`]. pub fn create_test_scheduler( catalog: Arc<dyn Catalog>, time_provider: Arc<dyn TimeProvider>, mocked_partition_ids: Option<Vec<PartitionId>>, ) -> Arc<dyn Scheduler> { let scheduler_config = match mocked_partition_ids { None => SchedulerConfig::default(), Some(partition_ids) => SchedulerConfig::Local(LocalSchedulerConfig { commit_wrapper: None, partitions_source_config: PartitionsSourceConfig::Fixed( partition_ids.into_iter().collect::<HashSet<PartitionId>>(), ), shard_config: None, ignore_partition_skip_marker: false, }), }; create_scheduler( scheduler_config, catalog, time_provider, Arc::new(metric::Registry::default()), false, ) } #[cfg(test)] mod tests { use iox_tests::TestCatalog; use iox_time::{MockProvider, Time}; use super::*; #[test] fn test_display_will_not_change_for_external_tests() { let scheduler = create_test_scheduler( TestCatalog::new().catalog(), Arc::new(MockProvider::new(Time::MIN)), None, ); assert_eq!(scheduler.to_string(), "local_compaction_scheduler"); let scheduler = create_test_scheduler( TestCatalog::new().catalog(), Arc::new(MockProvider::new(Time::MIN)), Some(vec![PartitionId::new(0)]), ); assert_eq!(scheduler.to_string(), "local_compaction_scheduler"); } #[tokio::test] async fn test_test_scheduler_with_mocked_parition_ids() { let partitions = vec![PartitionId::new(0), PartitionId::new(1234242)]; let scheduler = create_test_scheduler( TestCatalog::new().catalog(), Arc::new(MockProvider::new(Time::MIN)), Some(partitions.clone()), ); let mut result = scheduler .get_jobs() .await .iter() .map(|j| j.partition_id) .collect::<Vec<PartitionId>>(); result.sort(); assert_eq!(result, partitions); } }
#![allow(unused_imports, unused_variables, dead_code)] extern crate futures; #[macro_use] extern crate futures_io; extern crate futures_mio; extern crate trust_dns; mod dns_query; use dns_query::Message; use futures::{Future, Poll, oneshot, Oneshot, Complete}; use futures::stream::Stream; use futures_mio::{Loop, UdpSocket, Sender, Receiver}; use std::thread; use std::collections::{VecDeque, HashMap}; use std::net::{self, SocketAddr}; use std::io; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; static DNS_REQ_ID: AtomicUsize = ATOMIC_USIZE_INIT; pub fn next_request_id() -> u16 { DNS_REQ_ID.fetch_add(1, Ordering::Relaxed) as u16 } type Request = (Message, Complete<Message>); struct Resolver { socket: UdpSocket, remote: SocketAddr, receiver: Receiver<Request>, queue: VecDeque<Request>, requests: HashMap<u16, Complete<Message>>, buffer: Vec<u8>, } struct ResolverHandle { sender: Sender<Request>, thread: thread::JoinHandle<()>, } impl Resolver { pub fn new(socket: UdpSocket, remote: SocketAddr, receiver: Receiver<Request>) -> Self { Resolver { socket: socket, remote: remote, receiver: receiver, queue: VecDeque::new(), requests: HashMap::new(), buffer: Vec::with_capacity(2048) } } } impl Future for Resolver { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { while let Poll::Ok(Some(req)) = self.receiver.poll() { self.queue.push_back(req) } while let Some((mut req, complete)) = self.queue.pop_front() { if let Poll::Ok(_) = self.socket.poll_write() { self.buffer.clear(); let id = next_request_id(); req.id(id); dns_query::encode_message(&mut self.buffer, &req); let n = try_nb!(self.socket.send_to(&self.buffer, &self.remote)); self.requests.insert(id, complete); } else { self.queue.push_front((req, complete)); } } while let Poll::Ok(_) = self.socket.poll_read() { let mut buf = [0u8; 512]; let (n, addr) = try_nb!(self.socket.recv_from(&mut buf)); if addr != self.remote { println!("Discarding message from unexpected address: want {:?}, got {:?}", self.remote, addr); } let msg = dns_query::decode_message(&mut buf); if let Some(complete) = self.requests.remove(&msg.get_id()) { complete.complete(msg) } else { } } Poll::NotReady } } impl ResolverHandle { pub fn query(&self, q: Message) -> Oneshot<Message> { let (c, p) = oneshot::<Message>(); self.sender.send((q, c)).unwrap(); p } pub fn join(self) { self.thread.join().unwrap(); } } fn resolver(remote: SocketAddr) -> ResolverHandle { use std::sync::mpsc; let (txa, rxa) = mpsc::channel::<Sender<Request>>(); let t = thread::spawn(move || { let mut lp = Loop::new().unwrap(); let (tx, rx) = lp.handle().channel::<Request>(); let rx = lp.run(rx).unwrap(); let socket_bind = lp.handle().udp_bind(&"0.0.0.0:0".parse().unwrap()); let socket = lp.run(socket_bind).unwrap(); let resolver = Resolver::new(socket, remote, rx); txa.send(tx).unwrap(); lp.run(resolver).unwrap(); }); ResolverHandle { sender: rxa.recv().unwrap(), thread: t, } } fn main() { let r = resolver("8.8.8.8:53".parse().unwrap()); let q = dns_query::build_query_message(dns_query::any_query("google.com")); let p1 = r.query(q); let q = dns_query::build_query_message(dns_query::any_query("apple.com")); let p2 = r.query(q); p1.map(|m| { println!("c1 got message:{:?}\n", m); }).forget(); p2.map(|m| { println!("c2 got message:{:?}\n", m); }).forget(); r.join(); }
// Copyright 2020-2021, The Tremor Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // TODO: Add correlation of reads and replies. #![cfg(not(tarpaulin_include))] use crate::sink::{prelude::*, Reply}; use crate::source::prelude::*; use async_channel::Sender; use halfbrown::HashMap; use serde::Deserialize; use sled::{CompareAndSwapError, IVec}; use std::boxed::Box; use tremor_pipeline::EventIdGenerator; use tremor_value::literal; #[derive(Deserialize, Debug, Clone)] pub struct Config { dir: String, } pub struct Kv { sink_url: TremorUrl, event_origin_uri: EventOriginUri, idgen: EventIdGenerator, reply_tx: Sender<Reply>, db: sled::Db, } fn decode(mut v: Option<IVec>, codec: &mut dyn Codec, ingest_ns: u64) -> Result<Value<'static>> { if let Some(v) = v.as_mut() { let data: &mut [u8] = v; // TODO: We could optimize this Ok(codec .decode(data, ingest_ns)? .unwrap_or_default() .into_static()) } else { Ok(Value::null()) } } fn ok(k: Vec<u8>, v: Value<'static>) -> Value<'static> { literal!({ "ok": { "key": Value::Bytes(k.into()), "value": v } }) } impl Kv { fn execute( &self, cmd: Command, codec: &mut dyn Codec, ingest_ns: u64, ) -> Result<Value<'static>> { match cmd { Command::Get { key } => { decode(self.db.get(&key)?, codec, ingest_ns).map(|v| ok(key, v)) } Command::Put { key, value } => decode( self.db.insert(&key, codec.encode(value)?)?, codec, ingest_ns, ) .map(|v| ok(key, v)), Command::Delete { key } => { decode(self.db.remove(&key)?, codec, ingest_ns).map(|v| ok(key, v)) } Command::Cas { key, old, new } => { if let Err(CompareAndSwapError { current, proposed }) = self.db.compare_and_swap( &key, old.map(|v| codec.encode(v)).transpose()?, new.map(|v| codec.encode(v)).transpose()?, )? { Ok(literal!({ "key": Value::Bytes(key.into()), "error": { "current": decode(current, codec, ingest_ns)?, "proposed": decode(proposed, codec, ingest_ns)? } })) } else { Ok(ok(key, Value::null())) } } Command::Scan { start, end } => { let i = match (start, end) { (None, None) => self.db.range::<Vec<u8>, _>(..), (Some(start), None) => self.db.range(start..), (None, Some(end)) => self.db.range(..end), (Some(start), Some(end)) => self.db.range(start..end), }; let mut res = Vec::with_capacity(32); for e in i { let (key, e) = e?; let key: &[u8] = &key; let value = literal!({ "key": Value::Bytes(key.to_vec().into()), "value": decode(Some(e), codec, ingest_ns)? }); res.push(value); } Ok(literal!({ "ok": res })) } } } } impl offramp::Impl for Kv { fn from_config(config: &Option<OpConfig>) -> Result<Box<dyn Offramp>> { if let Some(config) = config { let config: Config = serde_yaml::from_value(config.clone())?; let db = sled::open(&config.dir)?; let event_origin_uri = EventOriginUri { uid: 0, scheme: "tremor-kv".to_string(), host: "localhost".to_string(), port: None, path: config.dir.split('/').map(ToString::to_string).collect(), }; // dummy let (dummy_tx, _) = async_channel::bounded(1); Ok(SinkManager::new_box(Kv { sink_url: TremorUrl::from_onramp_id("kv")?, // dummy value idgen: EventIdGenerator::new(0), reply_tx: dummy_tx, // dummy, will be replaced in init event_origin_uri, db, })) } else { Err("[KV Offramp] Offramp requires a config".into()) } } } #[derive(Debug)] enum Command<'v> { /// ```json /// {"get": {"key": "the-key"}} /// ``` Get { key: Vec<u8> }, /// ```json /// {"put": {"key": "the-key", "value": "the-value"}} /// ``` Put { key: Vec<u8>, value: &'v Value<'v> }, /// ```json /// {"delete": {"key": "the-key"}} /// ``` Delete { key: Vec<u8> }, /// ```json /// {"scan": { /// "start": "key1", /// "end": "key2", /// } /// ``` Scan { start: Option<Vec<u8>>, end: Option<Vec<u8>>, }, /// ```json /// {"cas": { /// "key": "key" /// "old": "<value|null|not-set>", /// "new": "<value|null|not-set>", /// } /// ``` Cas { key: Vec<u8>, old: Option<&'v Value<'v>>, new: Option<&'v Value<'v>>, }, } impl<'v> Command<'v> { fn op_name(&self) -> &'static str { match self { Command::Get { .. } => "get", Command::Put { .. } => "put", Command::Delete { .. } => "delete", Command::Scan { .. } => "scan", Command::Cas { .. } => "cas", } } fn key(&self) -> Option<Vec<u8>> { match self { Command::Get { key, .. } | Command::Put { key, .. } | Command::Delete { key } | Command::Cas { key, .. } => Some(key.clone()), Command::Scan { .. } => None, } } } #[async_trait::async_trait] impl Sink for Kv { #[allow(clippy::too_many_lines, clippy::option_if_let_else)] async fn on_event( &mut self, _input: &str, codec: &mut dyn Codec, _codec_map: &HashMap<String, Box<dyn Codec>>, event: Event, ) -> ResultVec { let mut r = Vec::with_capacity(10); let ingest_ns = tremor_common::time::nanotime(); let cmds = event.value_meta_iter().map(|(v, m)| { let command_res = if let Some(g) = v.get("get") { g.get_bytes("key") .ok_or_else(|| "Missing or invalid `key` field".into()) .map(|key| Command::Get { key: key.to_vec() }) } else if let Some(p) = v.get("put") { p.get_bytes("key") .ok_or_else(|| "Missing or invalid `key` field".into()) .and_then(|key| { p.get("value") .map(|value| Command::Put { key: key.to_vec(), value, }) .ok_or_else(|| "Missing `value` field".into()) }) } else if let Some(c) = v.get("cas") { c.get_bytes("key") .ok_or_else(|| "Missing or invalid `key` field".into()) .map(|key| Command::Cas { key: key.to_vec(), old: c.get("old"), new: c.get("new"), }) } else if let Some(d) = v.get("delete") { d.get_bytes("key") .ok_or_else(|| "Missing or invalid `key` field".into()) .map(|key| Command::Delete { key: key.to_vec() }) } else if let Some(s) = v.get("scan") { Ok(Command::Scan { start: s.get_bytes("start").map(|v| v.to_vec()), end: s.get_bytes("end").map(|v| v.to_vec()), }) } else { Err(format!("Invalid KV command: {}", v)) }; ( command_res.map_err(|e| ErrorKind::KvError(e).into()), m.get("correlation"), ) }); let mut first_error = None; // note: we always try to execute all commands / handle all errors. // we might want to exit early in some cases though for (cmd_or_err, correlation) in cmds { let executed = match cmd_or_err { Ok(cmd) => { let name = cmd.op_name(); let key = cmd.key(); self.execute(cmd, codec, ingest_ns) .map(|res| (name, res)) .map_err(|e| (Some(name), key, e)) } Err(e) => Err((None, None, e)), }; match executed { Ok((op, data)) => { let mut id = self.idgen.next_id(); id.track(&event.id); let mut meta = Value::object_with_capacity(2); meta.try_insert("kv", literal!({ "op": op })); if let Some(correlation) = correlation { meta.try_insert("correlation", correlation.clone_static()); } let e = Event { id, ingest_ns, data: (data, meta).into(), origin_uri: Some(self.event_origin_uri.clone()), ..Event::default() }; r.push(Reply::Response(OUT, e)); } Err((op, key, e)) => { // send ERR response and log err let mut id = self.idgen.next_id(); id.track(&event.id); let data = literal!({ "key": key.map_or_else(Value::null, |v| Value::Bytes(v.into())), "error": e.to_string(), }); let mut meta = Value::object_with_capacity(3); meta.try_insert("kv", literal!({ "op": op })); meta.try_insert("error", e.to_string()); if let Some(correlation) = correlation { meta.try_insert("correlation", correlation.clone_static()); } let err_event = Event { id, ingest_ns, data: (data, meta).into(), origin_uri: Some(self.event_origin_uri.clone()), ..Event::default() }; r.push(Reply::Response(ERR, err_event)); first_error.get_or_insert(e); } } } if let Some(e) = first_error { // send away all response events asynchronously before for reply in r { if let Err(e) = self.reply_tx.send(reply).await { error!("[Sink::{}] Error sending error reply: {}", self.sink_url, e); } } // trigger CB fail Err(e) } else { Ok(Some(r)) } } async fn on_signal(&mut self, _signal: Event) -> ResultVec { Ok(None) } #[allow(clippy::too_many_arguments)] async fn init( &mut self, sink_uid: u64, sink_url: &TremorUrl, _codec: &dyn Codec, _codec_map: &HashMap<String, Box<dyn Codec>>, _processors: Processors<'_>, _is_linked: bool, reply_channel: Sender<sink::Reply>, ) -> Result<()> { self.event_origin_uri.uid = sink_uid; self.sink_url = sink_url.clone(); self.idgen.set_source(sink_uid); self.reply_tx = reply_channel; Ok(()) } fn is_active(&self) -> bool { true } fn auto_ack(&self) -> bool { true } fn default_codec(&self) -> &str { "json" } async fn terminate(&mut self) {} }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use hyper_rustls; use rustls; use { fuchsia_async::{ net::{TcpConnector, TcpStream}, EHandle, }, futures::{ compat::Compat, future::{Future, FutureExt, TryFutureExt}, io::{self, AsyncReadExt}, ready, task::{Context, Poll, SpawnExt}, }, hyper::{ client::{ connect::{Connect, Connected, Destination}, Client, }, Body, }, std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}, std::pin::Pin, }; /// A Fuchsia-compatible hyper client configured for making HTTP requests. pub type HttpClient = Client<HyperConnector, Body>; /// A Fuchsia-compatible hyper client configured for making HTTP and HTTPS requests. pub type HttpsClient = Client<hyper_rustls::HttpsConnector<HyperConnector>, Body>; /// A future that yields a hyper-compatible TCP stream. pub struct HyperTcpConnector(Result<TcpConnector, Option<io::Error>>); impl Future for HyperTcpConnector { type Output = Result<(Compat<TcpStream>, Connected), io::Error>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let connector = self.0.as_mut().map_err(|x| x.take().unwrap())?; let stream = ready!(connector.poll_unpin(cx)?); Poll::Ready(Ok((stream.compat(), Connected::new()))) } } /// A Fuchsia-compatible implementation of hyper's `Connect` trait which allows /// creating a TcpStream to a particular destination. pub struct HyperConnector; impl Connect for HyperConnector { type Transport = Compat<TcpStream>; type Error = io::Error; type Future = Compat<HyperTcpConnector>; fn connect(&self, dst: Destination) -> Self::Future { let res = (|| { let host = dst.host(); let port = match dst.port() { Some(port) => port, None => { if dst.scheme() == "https" { 443 } else { 80 } } }; let addr = if let Some(addr) = parse_ip_addr(host, port) { addr } else { // TODO(cramertj): smarter DNS-- nonblocking, don't just pick first addr (host, port).to_socket_addrs()?.next().ok_or_else(|| { io::Error::new(io::ErrorKind::Other, "destination resolved to no address") })? }; TcpStream::connect(addr) })(); HyperTcpConnector(res.map_err(Some)).compat() } } /// Returns a new Fuchsia-compatible hyper client for making HTTP requests. pub fn new_client() -> HttpClient { Client::builder().executor(EHandle::local().compat()).build(HyperConnector) } pub fn new_https_client_dangerous(tls: rustls::ClientConfig) -> HttpsClient { let https = hyper_rustls::HttpsConnector::from((HyperConnector, tls)); Client::builder().executor(EHandle::local().compat()).build(https) } /// Returns a new Fuchsia-compatible hyper client for making HTTP and HTTPS requests. pub fn new_https_client() -> HttpsClient { let mut tls = rustls::ClientConfig::new(); tls.root_store.add_server_trust_anchors(&webpki_roots_fuchsia::TLS_SERVER_ROOTS); new_https_client_dangerous(tls) } fn parse_ip_addr(host: &str, port: u16) -> Option<SocketAddr> { if let Ok(addr) = host.parse::<Ipv4Addr>() { return Some(SocketAddr::V4(SocketAddrV4::new(addr, port))); } // IpV6 literals are always in [] if !host.starts_with("[") || !host.ends_with(']') { return None; } let host = &host[1..host.len() - 1]; // IPv6 addresses with zones always contains "%25", which is "%" URL encoded. let mut host_parts = host.splitn(2, "%25"); let addr = host_parts.next()?.parse::<Ipv6Addr>().ok()?; let scope_id = match host_parts.next() { Some(zone_id) => { // rfc6874 section 4 states: // // The security considerations from the URI syntax specification // [RFC3986] and the IPv6 Scoped Address Architecture specification // [RFC4007] apply. In particular, this URI format creates a specific // pathway by which a deceitful zone index might be communicated, as // mentioned in the final security consideration of the Scoped Address // Architecture specification. It is emphasised that the format is // intended only for debugging purposes, but of course this intention // does not prevent misuse. // // To limit this risk, implementations MUST NOT allow use of this format // except for well-defined usages, such as sending to link-local // addresses under prefix fe80::/10. At the time of writing, this is // the only well-defined usage known. // // Since the only known use-case of IPv6 Zone Identifiers on Fuchsia is to communicate // with link-local devices, restrict addresse to link-local zone identifiers. // // TODO: use Ipv6Addr::is_unicast_link_local_strict when available in stable rust. if addr.segments()[..4] != [0xfe80, 0, 0, 0] { return None; } // TODO(21415 and 39402): the netstack team is still working on how we should convert // IPv6 zone_ids into scope_ids (see http://fxb/21415). However, both golang and curl // allow for an integer zone_id to be treated as the scope_id, so copy that behavior // until 21415 the proper solution is figured out. // // When we do start parsing more complex zone_ids, we should validate that the value // matches rfc6874 grammar `ZoneID = 1*( unreserved / pct-encoded )`. zone_id.parse::<u32>().ok()? } None => 0, }; Some(SocketAddr::V6(SocketAddrV6::new(addr, port, 0, scope_id))) } #[cfg(test)] mod test { use super::*; use fuchsia_async::Executor; #[test] fn can_create_client() { let _exec = Executor::new().unwrap(); let _client = new_client(); } #[test] fn can_create_https_client() { let _exec = Executor::new().unwrap(); let _client = new_https_client(); } #[test] fn test_parse_ipv4_addr() { let addr = parse_ip_addr("1.2.3.4", 8080); let expected = "1.2.3.4:8080".parse::<SocketAddr>().unwrap(); assert_eq!(addr, Some(expected)); } #[test] fn test_parse_invalid_addresses() { assert_eq!(parse_ip_addr("1.2.3", 8080), None); assert_eq!(parse_ip_addr("1.2.3.4.5", 8080), None); assert_eq!(parse_ip_addr("localhost", 8080), None); assert_eq!(parse_ip_addr("[fe80::1:2:3:4", 8080), None); assert_eq!(parse_ip_addr("[[fe80::1:2:3:4]", 8080), None); } #[test] fn test_parse_ipv6_addr() { let addr = parse_ip_addr("[fe80::1:2:3:4]", 8080); let expected = "[fe80::1:2:3:4]:8080".parse::<SocketAddr>().unwrap(); assert_eq!(addr, Some(expected)); } #[test] fn test_parse_ipv6_addr_with_zone() { let expected = "fe80::1:2:3:4".parse::<Ipv6Addr>().unwrap(); let addr = parse_ip_addr("[fe80::1:2:3:4%250]", 8080); assert_eq!(addr, Some(SocketAddr::V6(SocketAddrV6::new(expected, 8080, 0, 0)))); let addr = parse_ip_addr("[fe80::1:2:3:4%252]", 8080); assert_eq!(addr, Some(SocketAddr::V6(SocketAddrV6::new(expected, 8080, 0, 2)))); } #[test] fn test_parse_ipv6_addr_with_zone_does_not_support_interface_names() { let addr = parse_ip_addr("[fe80::1:2:3:4%25lo]", 8080); assert_eq!(addr, None); } #[test] fn test_parse_ipv6_addr_with_zone_must_be_local() { let addr = parse_ip_addr("[fe81::1:2:3:4%252]", 8080); assert_eq!(addr, None); } }
use super::ai::AI; use super::grid::Grid; use super::{Coordinates, Direction, InputEvent, Player, Side}; use crossterm::event::{read, Event}; use crossterm::style::{Color, Print, ResetColor, SetBackgroundColor, SetForegroundColor}; use crossterm::{cursor, event, execute}; use std::collections::HashMap; use std::io; use std::io::stdout; use std::iter; #[derive(Debug, PartialEq)] pub struct TicTacToe { pub cursor: Coordinates, pub grid: Grid, pub ai_algo: AI, pub marked_positions: HashMap<Coordinates, Player>, } impl TicTacToe { pub fn from(grid: Grid, ai_algo: AI) -> crossterm::Result<Self> { let initial_grid_coords = Coordinates { x: 0, y: 0 }; Self::move_cursor_to_grid(&initial_grid_coords)?; let Side(side) = grid.side; let marked_positions: HashMap<Coordinates, Player> = HashMap::with_capacity(side.pow(2).into()); Ok(Self { cursor: initial_grid_coords, grid: grid, ai_algo: ai_algo, marked_positions: marked_positions, }) } /// The game loop reads player input and performs actions based on this input. pub fn game_loop(&mut self) -> crossterm::Result<()> { let mut event: InputEvent; loop { event = self.read_input_event()?; match event { InputEvent::Direction(direction) => { self.handle_direction(direction)?; } InputEvent::Quit => { break; } InputEvent::Mark => { let marked = self.mark_cross(); // Let's ignore if the player sets a mark at an already marked position. if marked.is_err() { continue; } let player_has_won = self.check_for_victory(&Player::Cross); if player_has_won { self.screen_message("You've won the game!")?; break; } let game_has_drawed = !self.grid_has_empty_boxes(); if game_has_drawed { self.screen_message("The game was a draw!")?; break; } let player_cursor = self.cursor; let ai_cursor = self .ai_algo .get_marker(&self.marked_positions, &self.grid.side); self.set_cursor_to_grid(&ai_cursor)?; self.mark_zero()?; let ai_has_won = self.check_for_victory(&Player::Zero); if ai_has_won { self.screen_message("AI won the game!")?; break; } self.set_cursor_to_grid(&player_cursor)?; } } } Ok(()) } pub fn screen_message(&self, msg: &str) -> crossterm::Result<()> { let Side(side) = self.grid.side; // Cleanup any previous text execute!( stdout(), cursor::MoveTo(0, side + 1), SetBackgroundColor(Color::Black), Print(iter::repeat(" ").take(100).collect::<String>()), ResetColor )?; execute!( stdout(), cursor::MoveTo(0, side + 1), SetForegroundColor(Color::Black), SetBackgroundColor(Color::White), Print(msg), ResetColor )?; // Good idea to move the cursor on to the next line since it seems // terminals in raw mode do not put an empty line at the end of STDOUT // by themselves. execute!(stdout(), cursor::MoveTo(0, side + 2))?; Ok(()) } /// Performs movement in the grid. fn handle_direction(&mut self, direction: Direction) -> crossterm::Result<()> { let Side(side) = &self.grid.side; let mut grid_coords = self.cursor + direction.get_relative_coords(); if grid_coords.x >= *side as i16 { grid_coords.x = *side as i16 - 1; } if grid_coords.y >= *side as i16 { grid_coords.y = *side as i16 - 1; } if grid_coords.x < 0 { grid_coords.x = 0; } if grid_coords.y < 0 { grid_coords.y = 0; } Self::move_cursor_to_grid(&grid_coords)?; self.cursor = grid_coords; Ok(()) } /// Read and translate keyboard input to an `InputEvent`. fn read_input_event(&self) -> crossterm::Result<InputEvent> { loop { if let Event::Key(k) = read()? { match k.code { event::KeyCode::Enter => return Ok(InputEvent::Mark), event::KeyCode::Char('w') => return Ok(InputEvent::Direction(Direction::Up)), event::KeyCode::Char('s') => return Ok(InputEvent::Direction(Direction::Down)), event::KeyCode::Char('a') => return Ok(InputEvent::Direction(Direction::Left)), event::KeyCode::Char('d') => { return Ok(InputEvent::Direction(Direction::Right)) } event::KeyCode::Esc => return Ok(InputEvent::Quit), _ => {} }; }; } } /// Moves and places the cursor on the specified coordinates. pub fn set_cursor_to_grid(&mut self, position: &Coordinates) -> crossterm::Result<()> { Self::move_cursor_to_grid(position)?; self.cursor = position.clone(); Ok(()) } /// Moves the cursor on the specified grid coordinates visually. pub fn move_cursor_to_grid(position: &Coordinates) -> crossterm::Result<()> { let screen_coords = Grid::grid_coords_to_screen_coords(position); Ok(Self::move_cursor_to_screen(&screen_coords)?) } /// Moves the cursor on the specified screen coordinates visually. pub fn move_cursor_to_screen(position: &Coordinates) -> crossterm::Result<()> { execute!( stdout(), cursor::MoveTo(position.x as u16, position.y as u16) )?; Ok(()) } /// Place a character mark on the current position of the cursor. fn mark(&mut self, player: Player) -> crossterm::Result<&Self> { if self.marked_positions.get(&self.cursor).is_none() { self.grid.mark_at(self.cursor, player.to_char())?; self.marked_positions.insert(self.cursor, player); // The cursor automatically increments in x-axis after placing the mark. // Let's bring it back to its original position. Self::move_cursor_to_grid(&self.cursor)?; Ok(self) } else { Err(io::Error::new( io::ErrorKind::Other, "the position has already been marked", )) } } pub fn mark_cross(&mut self) -> crossterm::Result<&Self> { Ok(self.mark(Player::Cross)?) } pub fn mark_zero(&mut self) -> crossterm::Result<&Self> { Ok(self.mark(Player::Zero)?) } pub fn grid_has_empty_boxes(&self) -> bool { let Side(side) = self.grid.side; self.marked_positions.len() != side.pow(2).into() } pub fn check_for_victory(&self, player: &Player) -> bool { let Side(side) = self.grid.side; let mut victory = true; // Check if any vertical pattern is complete for x in 0..(side as i16) { victory = true; for y in 0..(side as i16) { if self.marked_positions.get(&Coordinates { x, y }) != Some(player) { victory = false; break; } } if victory { return true; } } // Check if any horizontal pattern is complete for y in 0..(side as i16) { victory = true; for x in 0..(side as i16) { if self.marked_positions.get(&Coordinates { x, y }) != Some(player) { victory = false; break; } } if victory { return true; } } // Check if top-left to bottom-right pattern is complete for z in 0..(side as i16) { victory = true; if self.marked_positions.get(&Coordinates { x: z, y: z }) != Some(player) { victory = false; break; } } if victory { return true; } // Check if bottom-left to top-right pattern is complete for x in 0..(side as i16) { victory = true; let y = side as i16 - x - 1; if self.marked_positions.get(&Coordinates { x, y }) != Some(player) { victory = false; break; } } if victory { return true; } false } }
use std::collections::HashMap; use std::io::Error; use std::net::Ipv4Addr; use std::net::Ipv6Addr; use std::net::SocketAddr; use std::net::UdpSocket; use std::sync::RwLock; use std::time::Duration; use std::time::Instant; use colored::*; use crossbeam; use crossbeam::channel; use super::config; use super::utils; use std::ops::Add; const UDP_WAIT_TIME: u64 = 1500; pub struct DNSServe { pub config: config::Config, pub udp: UdpSocket, pub local: UdpSocket, pub mp: RwLock<HashMap<(u8, u8), (SocketAddr, u8, u8, Vec<u8>)>>, pub rule4: HashMap<String, Ipv4Addr>, pub rule6: HashMap<String, Ipv6Addr>, pub channel: RwLock<HashMap<(u8, u8), channel::Sender<bool>>>, pub cache: RwLock<HashMap<Vec<u8>, (Instant, Vec<u8>)>>, } impl DNSServe { pub fn build( config: config::Config, rule4: HashMap<String, Ipv4Addr>, rule6: HashMap<String, Ipv6Addr>, ) -> Result<DNSServe, Error> { let udp = UdpSocket::bind(config.Local).expect("Remote UDP Bind failed"); let local = UdpSocket::bind(config.Listen).expect("Local UDP Bind failed"); udp.connect(config.DNSPod).expect("UDP Connect Failed"); return Ok(DNSServe { config, udp, local, mp: RwLock::new(HashMap::new()), rule4, rule6, channel: RwLock::new(HashMap::new()), cache: RwLock::new(HashMap::new()), }); } pub fn local(&self, mut buf: Vec<u8>, LocalIndex: u16, (amt, src): (usize, SocketAddr)) { let (pack, p) = super::utils::QS::unpack(&buf).expect("QR Unpack Failed"); let (name, raw) = super::utils::network::GetName(&pack); let mut work = true; for i in 0..name.len() { work &= (pack.qd[i].qtype == utils::qtype::Type::A && self.rule4.contains_key(&name[i])) || (pack.qd[i].qtype == utils::qtype::Type::AAAA && self.rule6.contains_key(&name[i])); } match work { true => { if self.config.Debug > 1 { println!("{}", "Solved By Local!".bright_yellow()); } let mut NoError = true; let mut ms = Vec::new(); ms.extend_from_slice(&buf[0..p]); //QR=1 let mut s = utils::math::ntohc(ms[2]); s |= 0b10_00_00_00; ms[2] = utils::math::htonc(s); let mut valid: u32 = 0; for i in 0..name.len() { if (pack.qd[i].qtype == utils::qtype::Type::A && self.rule4.get(&name[i]).unwrap().is_unspecified()) || (pack.qd[i].qtype == utils::qtype::Type::AAAA && self.rule6.get(&name[i]).unwrap().is_unspecified()) { NoError = false; } else { valid += 1; //Name ms.extend_from_slice(&raw[i]); if pack.qd[i].qtype == utils::qtype::Type::A { //Type=A ms.push(0); ms.push(1); } else { //Type=AAAA ms.push(0); ms.push(0x1C); } //Class=IN ms.push(0); ms.push(1); //TTL ms.push(((self.config.TTL & 0xFF_00_00_00) >> 24) as u8); ms.push(((self.config.TTL & 0x00_FF_00_00) >> 16) as u8); ms.push(((self.config.TTL & 0x00_00_FF_00) >> 8) as u8); ms.push((self.config.TTL & 0x00_00_00_FF) as u8); if pack.qd[i].qtype == utils::qtype::Type::A { //IPv4 //RDLength=4 ms.push(0); ms.push(4); //RData=IPv4 Address let ip = self.rule4.get(&name[i]).unwrap(); // println!("{} {}", name[i], ip); for i in &ip.octets() { ms.push(i.clone()); } } else { //IPv6 //RDLength=16 ms.push(0); ms.push(0x10); //RData=IPv6 Address let ip = self.rule6.get(&name[i]).unwrap(); for i in &ip.octets() { ms.push(i.clone()); } } } } //RCode if !NoError { let mut s = utils::math::ntohc(ms[3]); s &= 0b11_11_00_00; s |= 0b00_00_00_11; ms[3] = utils::math::htonc(s); if self.config.Debug > 1 { println!("{}", "Local Banned!".bright_yellow()); } } //ANCount ms[6] = ((valid & 0xFF_00) >> 8) as u8; ms[7] = (valid & 0x00_FF) as u8; //NSCount ms[8] = 0; ms[9] = 0; //ARCount ms[10] = 0; ms[11] = 0; self.local.send_to(&ms, &src).unwrap(); } false => { let (f1, f2) = utils::network::GetIndex(&buf); let mut cached = { let cache_lock = self.cache.read().unwrap(); match cache_lock.contains_key(&buf[12..amt]) { true => { let (op, res) = cache_lock.get(&buf[12..amt]).unwrap().clone(); if Instant::now() > op.clone() { std::mem::drop(cache_lock); let mut cache_lock = self.cache.write().unwrap(); cache_lock.remove(&buf[12..amt].to_vec()).unwrap(); std::mem::drop(cache_lock); Vec::new() } else { res } } false => Vec::new(), } }; match cached.is_empty() { true => { if self.config.Debug > 1 { println!("{}", "cached is_empty!".bright_yellow()); } let id1: u8 = ((LocalIndex & 0xFF_00) >> 8) as u8; let id2: u8 = (LocalIndex & 0x00_FF) as u8; let mut lock = self.mp.write().expect("Local Mutex Failed"); lock.insert( (id1, id2), (src.clone(), f1, f2, buf[12..amt].to_vec().clone()), ); std::mem::drop(lock); utils::network::ModifyIndex(&mut buf, id1, id2); let (send, rev) = channel::bounded(0); let mut channel_lock = self.channel.write().unwrap(); channel_lock.insert((id1, id2), send); std::mem::drop(channel_lock); let mut done = false; for i in 0..2 { self.udp.send(&buf[0..amt]).expect("Remote send failed"); match rev.recv_timeout(Duration::from_millis(UDP_WAIT_TIME)) { Ok(val) => { done = true; break; } Err(err) => { let res = format!("UDP Delay Occurred :{}", err); println!("{}", res.bright_red()); } } } if !done { println!("{}", "UDP Give Up".red()); utils::network::ModifyIndex(&mut buf, f1, f2); //set RCode=ServeFail let mut s = utils::math::ntohc(buf[3]); s &= 0b11_11_00_00; s |= 0b00_00_00_10; buf[3] = utils::math::htonc(s); self.local .send_to(&buf[0..amt], src) .expect("Call back Err Failed"); } else { if self.config.Debug > 1 { println!("{}", "Turn to Remote!".bright_yellow()); } } let mut channel_lock = self.channel.write().unwrap(); channel_lock.remove(&(id1, id2)).unwrap(); std::mem::drop(channel_lock); } false => { if self.config.Debug > 0 { println!("{}", "Cached!".bright_cyan()); } utils::network::ModifyIndex(&mut cached, f1, f2); self.local .send_to(&cached, src) .expect("Cached info failed"); } } } } } pub fn remote(&self, mut buf2: Vec<u8>, (amt, src): (usize, SocketAddr)) { let id = utils::network::GetIndex(&buf2); let lock = self.mp.read().expect("Remote Mutex Failed"); let (target, id1, id2, query) = lock.get(&id).unwrap().clone(); std::mem::drop(lock); utils::network::ModifyIndex(&mut buf2, id1.clone(), id2.clone()); self.local .send_to(&buf2[0..amt], target) .expect("Remote send back Failed"); let channel_lock = self.channel.read().unwrap(); if channel_lock.contains_key(&id) { let sender = channel_lock.get(&id).unwrap().clone(); sender.send(true).unwrap(); } std::mem::drop(channel_lock); let mut cache_lock = self.cache.write().unwrap(); let ttl = super::utils::network::GetTTL(&buf2); cache_lock.insert( query.clone(), ( Instant::now().add(Duration::from_secs(ttl as u64)), buf2[0..amt].to_vec().clone(), ), ); std::mem::drop(cache_lock); } pub fn ListenLocal(&self) { let mut buf: Vec<u8> = vec![0; self.config.BufferSize as usize]; let mut LocalIndex: u16 = 114; crossbeam::thread::scope(|s| loop { let (amt, src) = match self.local.recv_from(&mut buf) { Ok(x) => x, Err(x) => { let res = format!("Local {}", x); println!("{}", res.bright_red()); continue; } }; if self.config.Debug > 0 { let res = format!("Local received {} bytes : {:?}", amt, src); println!("{}", res.bright_blue()); } if self.config.Debug > 2 { utils::network::output(&buf, amt); } let copy = buf.clone(); s.spawn(move |_| self.local(copy, LocalIndex.clone(), (amt, src))); LocalIndex = (LocalIndex + 1) & 0xFFFF; }) .unwrap(); } pub fn ListenRemote(&self) { let mut buf2: Vec<u8> = vec![0; self.config.BufferSize as usize]; let scope = crossbeam::thread::scope(|s| loop { let (amt, src) = match self.udp.recv_from(&mut buf2) { Ok(x) => x, Err(x) => { let res = format!("Remote {}", x); println!("{}", res.bright_red()); continue; } }; if self.config.Debug > 0 { let res = format!("Remote received {} bytes : {:?}", amt, src); println!("{}", res.bright_green()); } if self.config.Debug > 2 { utils::network::output(&buf2, amt); } let copy = buf2.clone(); s.spawn(move |_| self.remote(copy, (amt, src))); }) .unwrap(); } pub fn CacheReduce(&self) { loop { std::thread::sleep(Duration::from_secs(self.config.Cache)); let mut lock = self.cache.write().expect("Cleaner Mutex Failed"); let copy = lock.clone(); for (Q, (ins, ans)) in &copy { if Instant::now() > ins.clone() { lock.remove(Q); } } std::mem::drop(lock); } } pub fn run(self) { println!("{}", "Thread Spawned\n".cyan()); crossbeam::thread::scope(|s| { s.spawn(|_| self.ListenLocal()); s.spawn(|_| self.ListenRemote()); s.spawn(|_| self.CacheReduce()); }) .expect("crossbeam Failed"); } }
#![allow(non_camel_case_types)] use super::access_flags::*; use super::attribute::*; use super::constant_pool::*; use super::field::FieldInfo; use super::instruction::{Instruction, InstructionKind}; use super::method::MethodInfo; use std::fs::File; use std::io::{BufReader, Read}; type u1 = u8; type u2 = u16; type u4 = u32; use RefKind::*; #[derive(Debug)] pub struct ClassFile { pub minor_version: u2, pub major_version: u2, pub constant_pool_count: u2, pub constant_pools: Vec<ConstantPool>, pub access_flags: u2, pub this_class: u2, pub super_class: u2, pub interfaces_count: u2, pub interfaces: Vec<u2>, pub fields_count: u2, pub fields: Vec<FieldInfo>, pub methods_count: u2, pub methods: Vec<MethodInfo>, pub attributes_count: u2, pub attributes: Vec<AttributeInfo>, } #[derive(Debug)] pub struct ClassFileReader { reader: BufReader<File>, } impl ClassFile { pub fn new(filename: &str) -> Result<Self, std::io::Error> { let mut reader = ClassFileReader::new(filename)?; if let Some(classfile) = reader.read() { /* TODO-Low: - Format checking. - Check the file satisfies constraints or not. - Verification. */ Ok(classfile) } else { unimplemented!() } } } impl ClassFileReader { fn new(filename: &str) -> Result<Self, std::io::Error> { let reader = BufReader::new(File::open(filename)?); Ok(Self { reader }) } fn read(&mut self) -> Option<ClassFile> { macro_rules! read_n_times { ($n: expr, $read_function: ident) => {{ let mut v = vec![]; for _ in 0..$n { v.push(self.$read_function()); } v }}; } let magic = self.read_u4(); if magic != 0xCAFEBABE { return None; } let minor_version = self.read_u2(); let major_version = self.read_u2(); let constant_pool_count = self.read_u2(); let constant_pools = read_n_times!(constant_pool_count - 1, read_constant_pool); let access_flags = self.read_u2(); let this_class = self.read_u2(); let super_class = self.read_u2(); let interfaces_count = self.read_u2(); let interfaces = read_n_times!(interfaces_count, read_u2); let fields_count = self.read_u2(); let fields = { let mut v = vec![]; for _ in 0..fields_count { let access_flags = self.read_u2(); let name_index = self.read_u2(); let descriptor_index = self.read_u2(); let attributes_count = self.read_u2(); let attributes = { let mut v = vec![]; for _ in 0..attributes_count { v.push(self.read_attribute(&constant_pools)); } v }; v.push(FieldInfo { access_flags, name_index, descriptor_index, attributes_count, attributes, }); } v }; let methods_count = self.read_u2(); let methods = { let mut v = vec![]; for _ in 0..methods_count { let access_flags = AccessFlags::from(self.read_u2()); let name_index = self.read_u2(); let descriptor_index = self.read_u2(); let attributes_count = self.read_u2(); let attributes = { let mut v = vec![]; println!("methods: attributes"); for _ in 0..attributes_count { v.push(self.read_attribute(&constant_pools)); } v }; v.push(MethodInfo { access_flags, name_index, descriptor_index, attributes_count, attributes, }); } v }; println!("attributes_count"); let attributes_count = self.read_u2(); let attributes = { let mut v = vec![]; for _ in 0..attributes_count { v.push(self.read_attribute(&constant_pools)); } v }; Some(ClassFile { minor_version, major_version, constant_pool_count, constant_pools, access_flags, this_class, super_class, interfaces_count, interfaces, fields_count, fields, methods_count, methods, attributes_count, attributes, }) } fn read_attribute(&mut self, constant_pools: &[ConstantPool]) -> AttributeInfo { use ConstantPool::*; let attribute_name_index = self.read_u2(); let attribute_length = self.read_u4(); let name = match constant_pools .get(attribute_name_index as usize - 1) .unwrap() { Utf8 { bytes, .. } => bytes, _ => unreachable!(), }; let info = match name.as_str() { "Code" => { let max_stack = self.read_u2(); let max_locals = self.read_u2(); let code_length = self.read_u4(); let code = { let mut v = vec![]; let mut eaten = 0; while eaten < code_length { let kind = InstructionKind::from(self.read_u1()); eaten += 1; let argc = kind.argc(); let mut args = vec![]; if argc == -1 { unimplemented!() } else { for _ in 0..argc { args.push(self.read_u1()); eaten += 1; } } v.push(dbg!(Instruction { kind, args })); } // for _ in 0..code_length { // let code = self.read_u1(); // } v }; let exception_table_length = self.read_u2(); let exception_table = { let mut v = vec![]; for _ in 0..exception_table_length { let start_pc = self.read_u2(); let end_pc = self.read_u2(); let handler_pc = self.read_u2(); let catch_type = self.read_u2(); v.push(ExceptionTable { start_pc, end_pc, handler_pc, catch_type, }); } v }; let attributes_count = self.read_u2(); let attributes = { let mut v = vec![]; for _ in 0..attributes_count { let attr = dbg!(self.read_attribute(constant_pools)); v.push(attr); } v }; AttributeInfoKind::Code { max_stack, max_locals, code_length, code, exception_table_length, exception_table, attributes_count, attributes, } } "LineNumberTable" => { let line_number_table_length = self.read_u2(); let line_number_table = { let mut v = vec![]; for _ in 0..line_number_table_length { let start_pc = self.read_u2(); let line_number = self.read_u2(); v.push(LineNumberTable { start_pc, line_number, }); } v }; AttributeInfoKind::LineNumberTable { line_number_table_length, line_number_table, } } "SourceFile" => AttributeInfoKind::SourceFile(self.read_u2()), _ => { dbg!(name); unimplemented!() } }; AttributeInfo { attribute_name_index, attribute_length, info, } } fn read_constant_pool(&mut self) -> ConstantPool { use ConstantPool::*; let tag = self.read_u1(); match tag { 7 => Class(self.read_u2()), 9 | 10 | 11 => FieldRef { tag: RefKind::from(tag as u8), class_index: self.read_u2(), name_and_type_index: self.read_u2(), }, 8 => String(self.read_u2()), 3 => Integer(self.read_u4()), 4 => Float(self.read_u4()), 5 => Long { high: self.read_u4(), low: self.read_u4(), }, 6 => Double { high: self.read_u4(), low: self.read_u4(), }, 12 => NameAndType { descriptor_index: self.read_u2(), name_index: self.read_u2(), }, 1 => { let length = self.read_u2(); let bytes = std::string::String::from_utf8({ let mut v = vec![]; for _ in 0..length { v.push(self.read_u1()); } v }) .unwrap(); Utf8 { length, bytes } } n => { eprintln!("header {:?} is unimplemented.", n); unimplemented!() } } } fn read_u1(&mut self) -> u1 { let mut buf = [0u8; 1]; match self.reader.read_exact(&mut buf) { Ok(_) => buf[0], _ => unimplemented!(), } } fn read_u2(&mut self) -> u2 { let mut buf = [0u8; 2]; match self.reader.read_exact(&mut buf) { Ok(_) => ((buf[0] as u2) << 8) + buf[1] as u2, err => { dbg!(err); unimplemented!() } } } fn read_u4(&mut self) -> u4 { let mut buf = [0u8; 4]; match self.reader.read_exact(&mut buf) { Ok(_) => { ((buf[0] as u4) << 24) + ((buf[1] as u4) << 16) + ((buf[2] as u4) << 8) + buf[3] as u4 } _ => unimplemented!(), } } }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use types::U256; pub const BLOCK_TIME_SEC: u32 = 20; pub const BLOCK_WINDOW: u32 = 24; use logger::prelude::*; use traits::ChainReader; pub fn difficult_1_target() -> U256 { U256::max_value() } pub fn current_hash_rate(target: &[u8]) -> u64 { // current_hash_rate = (difficult_1_target/target_current) * difficult_1_hash/block_per_esc let target_u256: U256 = target.into(); (difficult_1_target() / target_u256).low_u64() / (BLOCK_TIME_SEC as u64) } pub fn get_next_work_required(chain: &dyn ChainReader) -> U256 { let blocks = { let mut blocks: Vec<BlockInfo> = vec![]; let mut count = 0; let current_block = chain.head_block(); let mut current_number = current_block.header().number() + 1; loop { if count == BLOCK_WINDOW || current_number <= 0 { break; } current_number -= 1; let block = chain.get_block_by_number(current_number).unwrap().unwrap(); if block.header().timestamp() == 0 { continue; } let block_info = BlockInfo { timestamp: block.header().timestamp(), target: difficult_to_target(block.header().difficult()), }; blocks.push(block_info); count += 1; } blocks }; if blocks.len() <= 1 { info!( "Block length less than 1, set target to 1 difficult:{:?}", difficult_1_target() / 100.into() ); return difficult_1_target() / 100.into(); } let mut avg_time: u64 = 0; let mut avg_target = U256::zero(); let mut latest_block_index = 0; let block_n = blocks.len() - 1; while latest_block_index < block_n { let solve_time = blocks[latest_block_index].timestamp - blocks[latest_block_index + 1].timestamp; avg_time += solve_time * (block_n - latest_block_index) as u64; debug!( "solve_time:{:?}, avg_time:{:?}, block_n:{:?}", solve_time, avg_time, block_n ); avg_target = avg_target + blocks[latest_block_index].target / block_n.into(); latest_block_index += 1 } avg_time = avg_time / ((block_n as u64) * ((block_n + 1) as u64) / 2); if avg_time == 0 { avg_time = 1 } let time_plan = BLOCK_TIME_SEC; // new_target = avg_target * avg_time_used/time_plan // avoid the target increase or reduce too fast. let new_target = if let Some(new_target) = (avg_target / time_plan.into()).checked_mul(avg_time.into()) { if new_target / 2.into() > avg_target { info!("target increase too fast, limit to 2 times"); avg_target * 2 } else if new_target < avg_target / 2.into() { info!("target reduce too fase, limit to 2 times"); avg_target / 2.into() } else { new_target } } else { info!("target large than max value, set to 1_difficult"); difficult_1_target() }; info!( "avg_time:{:?}s, time_plan:{:?}s, target: {:?}", avg_time, time_plan, new_target ); new_target } pub fn target_to_difficult(target: U256) -> U256 { difficult_1_target() / target } pub fn difficult_to_target(difficult: U256) -> U256 { difficult_1_target() / difficult } #[derive(Clone)] pub struct BlockInfo { pub timestamp: u64, pub target: U256, }
//! The module keeping track of the possible game errors. use std::error::Error; use std::fmt; /// All possible error states the game can end up in. #[derive(Debug)] pub(crate) enum GameError { Unknown, } impl Error for GameError { fn source(&self) -> Option<&(dyn Error + 'static)> { use GameError::*; match self { Unknown => None, } } } impl fmt::Display for GameError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use GameError::*; match self { Unknown => f.write_str("unknown!"), } } }
use super::{NSObject, Object, BOOL, SEL}; use std::{ cmp, ffi::CStr, fmt, hash, ops::Deref, os::raw::{c_char, c_int}, panic::RefUnwindSafe, ptr, }; /// An Objective-C class. /// /// See [documentation](https://developer.apple.com/documentation/objectivec/class). /// /// # Usage /// /// This is an opaque type meant to be used behind a shared reference `&Class`, /// which is semantically equivalent to `Class _Nonnull`. /// /// A nullable class is defined as `Option<&Class>`, which is semantically /// equivalent to `Class _Nullable`. #[repr(C)] pub struct Class( // `Object` stores static data in the `__DATA` section, which is needed to // store class data. Internally, this is accomplished with `UnsafeCell`. Object, ); // Although this uses `UnsafeCell`, it does not point to any Rust types. impl RefUnwindSafe for Class {} impl Deref for Class { type Target = Object; #[inline] fn deref(&self) -> &Self::Target { &self.0 } } impl AsRef<Object> for Class { #[inline] fn as_ref(&self) -> &Object { self } } impl fmt::Debug for Class { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_tuple("Class").field(&self.name()).finish() } } impl PartialEq for Class { #[inline] fn eq(&self, other: &Self) -> bool { ptr::eq(self, other) } } impl Eq for Class {} impl PartialOrd for Class { #[inline] fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for Class { #[inline] fn cmp(&self, other: &Self) -> cmp::Ordering { (self as *const Self).cmp(&(other as *const Self)) } } impl hash::Hash for Class { #[inline] fn hash<H: hash::Hasher>(&self, state: &mut H) { (self as *const Self).hash(state); } } impl Class { /// Returns the class definition of a specified class, or `None` if the /// class is not registered with the Objective-C runtime. #[inline] pub fn get(name: &CStr) -> Option<&'static Class> { unsafe { objc_getClass(name.as_ptr()) } } /// Returns the number of classes registered with the Objective-C runtime. #[inline] pub fn count() -> usize { unsafe { objc_getClassList(ptr::null_mut(), 0) as usize } } /// Returns all classes registered with the Objective-C runtime. pub fn all() -> Vec<&'static Class> { let len = Self::count(); let mut all = Vec::<&'static Class>::with_capacity(len); unsafe { objc_getClassList(all.as_mut_ptr(), len as c_int); all.set_len(len); } all } #[inline] pub(crate) fn alloc(&self) -> NSObject { unsafe { _msg_send![self, alloc] } } /// Returns a reference to this class as an Objective-C object. #[inline] pub const fn as_object(&self) -> &Object { &self.0 } /// Returns `true` if this class implements or inherits a method that can /// respond to a specified message. /// /// See [documentation](https://developer.apple.com/documentation/objectivec/1418956-nsobject/1418583-respondstoselector). #[inline] pub fn responds_to_selector(&self, selector: SEL) -> bool { unsafe { _msg_send![self, respondsToSelector: selector => BOOL] != 0 } } /// Returns `true` if instances of this class implement or inherit a method /// that can respond to a specified message. /// /// See [documentation](https://developer.apple.com/documentation/objectivec/nsobject/1418555-instancesrespondtoselector). #[inline] pub fn instances_respond_to_selector(&self, selector: SEL) -> bool { unsafe { _msg_send![self, instancesRespondToSelector: selector => BOOL] != 0 } } /// Returns the name of this class. #[inline] pub fn name(&self) -> &CStr { unsafe { CStr::from_ptr(class_getName(self)) } } /// Returns this class's superclass, or `None` if this is a root class /// (e.g. [`NSObject`](struct.NSObject.html)). #[inline] pub fn superclass(&self) -> Option<&Class> { unsafe { class_getSuperclass(self) } } /// Returns an iterator over the superclasses of this class. #[inline] pub fn superclass_iter(&self) -> impl Iterator<Item = &Class> + Copy { #[derive(Copy, Clone)] struct Iter<'a>(&'a Class); impl<'a> Iterator for Iter<'a> { type Item = &'a Class; #[inline] fn next(&mut self) -> Option<Self::Item> { let superclass = self.0.superclass()?; self.0 = superclass; Some(superclass) } } // There are no more superclasses after the root is reached. impl std::iter::FusedIterator for Iter<'_> {} Iter(self) } /// Returns the number of superclasses of this class. #[inline] pub fn superclass_count(&self) -> usize { self.superclass_iter().count() } /// Returns `true` if this class has a superclass. #[inline] pub fn is_subclass(&self) -> bool { self.superclass().is_some() } /// Returns `true` if this class is a subclass of, or identical to, the /// other class. pub fn is_subclass_of(&self, other: &Self) -> bool { if self == other { true } else { self.superclass_iter().any(|superclass| superclass == other) } } /// Returns the size of instances of this class. #[inline] pub fn instance_size(&self) -> usize { unsafe { class_getInstanceSize(self) } } } extern "C" { fn objc_getClass(name: *const c_char) -> Option<&'static Class>; fn objc_getClassList(buf: *mut &'static Class, buf_len: c_int) -> c_int; fn class_getName(class: &Class) -> *const c_char; fn class_getSuperclass(class: &Class) -> Option<&Class>; fn class_getInstanceSize(class: &Class) -> usize; }
pub struct Solution; impl Solution { pub fn is_additive_number(num: String) -> bool { for i in 1.. { if i + 1 + i > num.len() { break; } for j in 1.. { if i + j + i.max(j) > num.len() { break; } if num.as_bytes()[i] == b'0' && j > 2 { break; } let mut a = 0; let mut b = i; let mut c = i + j; loop { let sum = add(&num[a..b], &num[b..c]); let d = c + sum.len(); if d > num.len() || &num[c..d] != &sum { break; } if d == num.len() { return true; } a = b; b = c; c = d; } } } return false; } } fn add(a: &str, b: &str) -> String { let mut c = Vec::new(); let mut a = a.bytes().rev(); let mut b = b.bytes().rev(); let mut carry = 0; loop { match (a.next(), b.next()) { (None, None) => { if carry > 0 { c.push(b'0' + carry); } c.reverse(); return String::from_utf8(c).unwrap(); } (Some(x), None) | (None, Some(x)) => { let sum = (x - b'0') + carry; c.push(b'0' + sum % 10); carry = sum / 10; } (Some(x), Some(y)) => { let sum = (x - b'0') + (y - b'0') + carry; c.push(b'0' + sum % 10); carry = sum / 10; } } } } #[test] fn test0306() { fn case(num: &str, want: bool) { let got = Solution::is_additive_number(num.to_string()); assert_eq!(got, want); } case("112358", true); case("199100199", true); case("123", true); case("199001200", false); case("101", true); }
//! libc specifics //! //! These are all re-exports from the [libc crate] and are intended for local //! use w/ APIs that uses a C-like ABI, like [ALSA][crate::alsa]. //! //! [libc crate]: https://crates.io/crates/libc #[doc(inherit)] pub use ::libc::eventfd; #[doc(inherit)] pub use ::libc::free; #[doc(inherit)] pub use ::libc::nfds_t; #[doc(inherit)] pub use ::libc::EFD_NONBLOCK; #[doc(inherit)] pub use ::libc::{c_char, c_int, c_long, c_short, c_uint, c_ulong, c_void}; #[doc(inherit)] pub use ::libc::{poll, pollfd, POLLIN, POLLOUT}; #[doc(inherit)] pub use ::libc::{read, write};
pub mod crypto; pub mod error; pub mod keystore; pub mod networks; pub mod pkcs8; pub mod store; pub mod wallet;
use smartcore::dataset::breast_cancer; use smartcore::dataset::diabetes; use smartcore::dataset::iris; use std::fs::File; use std::io::prelude::*; // DenseMatrix wrapper around Vec use smartcore::linalg::naive::dense_matrix::DenseMatrix; // Imports for KNN classifier use smartcore::math::distance::*; use smartcore::neighbors::knn_classifier::*; // Linear regression use smartcore::linear::linear_regression::LinearRegression; // Logistic regression use smartcore::linear::logistic_regression::LogisticRegression; // Model performance use smartcore::metrics::accuracy; // K-fold CV use smartcore::model_selection::{cross_val_predict, cross_validate, KFold}; use crate::utils; pub fn save_restore_knn() { // Load Iris dataset let iris_data = iris::load_dataset(); // Turn Iris dataset into NxM matrix let x = DenseMatrix::from_array( iris_data.num_samples, iris_data.num_features, &iris_data.data, ); // These are our target class labels let y = iris_data.target; // Fit KNN classifier to Iris dataset let knn = KNNClassifier::fit(&x, &y, Default::default()).unwrap(); // File name for the model let file_name = "iris_knn.model"; // Save the model { let knn_bytes = bincode::serialize(&knn).expect("Can not serialize the model"); File::create(file_name) .and_then(|mut f| f.write_all(&knn_bytes)) .expect("Can not persist model"); } // Load the model let knn: KNNClassifier<f32, euclidian::Euclidian> = { let mut buf: Vec<u8> = Vec::new(); File::open(&file_name) .and_then(|mut f| f.read_to_end(&mut buf)) .expect("Can not load model"); bincode::deserialize(&buf).expect("Can not deserialize the model") }; //Predict class labels let y_hat = knn.predict(&x).unwrap(); // Predict class labels // Calculate training error println!("accuracy: {}", accuracy(&y, &y_hat)); // Prints 0.96 } // This example is expired by // https://scikit-learn.org/stable/auto_examples/model_selection/plot_cv_predict.html pub fn lr_cross_validate() { // Load dataset let breast_cancer_data = breast_cancer::load_dataset(); let x = DenseMatrix::from_array( breast_cancer_data.num_samples, breast_cancer_data.num_features, &breast_cancer_data.data, ); // These are our target values let y = breast_cancer_data.target; // cross-validated estimator let results = cross_validate( LogisticRegression::fit, &x, &y, Default::default(), KFold::default().with_n_splits(3), accuracy, ) .unwrap(); println!( "Test score: {}, training score: {}", results.mean_test_score(), results.mean_train_score() ); } // This example is expired by // https://scikit-learn.org/stable/auto_examples/model_selection/plot_cv_predict.html pub fn plot_cross_val_predict() { // Load Diabetes dataset let diabetes_data = diabetes::load_dataset(); let x = DenseMatrix::from_array( diabetes_data.num_samples, diabetes_data.num_features, &diabetes_data.data, ); // These are our target values let y = diabetes_data.target; // Generate cross-validated estimates for each input data point let y_hat = cross_val_predict( LinearRegression::fit, &x, &y, Default::default(), KFold::default().with_n_splits(10), ) .unwrap(); // Assemble XY dataset for the scatter plot let xy = DenseMatrix::from_2d_vec( &y_hat .into_iter() .zip(y.into_iter()) .map(|(x1, x2)| vec![x1, x2]) .collect(), ); // Plot XY utils::scatterplot(&xy, None, "cross_val_predict").unwrap(); }
use wasm_bindgen::prelude::*; use wasm_bindgen_futures::JsFuture; use js_sys::Promise; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] struct Data<T>{ value: T, } type StrData = Data<String>; #[wasm_bindgen] extern { #[wasm_bindgen(js_namespace = console)] fn log(s: String); #[wasm_bindgen(js_namespace = sample)] fn initial_value() -> Promise; } #[wasm_bindgen] pub async fn sample(v: Promise) -> Result<JsValue, JsValue> { let data = JsFuture::from(v) .await .and_then(|v| from_jsvalue::<StrData>(&v))?; let init_data = JsFuture::from(initial_value()) .await .and_then(|v| from_jsvalue::<StrData>(&v))?; log(format!("*** init={:?}, arg={:?}", init_data, data)); let res = StrData { value: format!("{}/{}", init_data.value, data.value) }; to_jsvalue(&res) } fn to_jsvalue<T>(v: &T) -> Result<JsValue, JsValue> where T: serde::Serialize, { JsValue::from_serde(v) .map_err(|e| JsValue::from(e.to_string())) } fn from_jsvalue<T>(v: &JsValue) -> Result<T, JsValue> where T: for<'a> serde::Deserialize<'a> { JsValue::into_serde::<T>(v) .map_err(|e| JsValue::from(e.to_string())) }
use crate::*; use reqwest::header::HeaderValue; use reqwest::{header, Client, Url}; use std::io::prelude::*; /// Returns the body of the response from a get request to onfido on the endpoint indicated. /// Returns a Box<Error> if it fails to resolve the url, if the request fails to be sent or if its body can't be read pub fn get_onfido(url: Url, api_token: &str) -> Result<reqwest::Response> { let resp = Client::new() .get(url) .header(header::AUTHORIZATION, format!("Token token={}", api_token)) .send()?; Ok(resp) } pub fn post_onfido(url: Url, api_token: &str, payload: String) -> Result<reqwest::Response> { let mut headers = header::HeaderMap::new(); headers.append( header::AUTHORIZATION, HeaderValue::from_str(&format!("Token token={}", api_token))?, ); headers.append( header::CONTENT_TYPE, HeaderValue::from_static("application/json"), ); let resp = Client::new() .post(url) .headers(headers) .body(payload) .send()?; Ok(resp) } pub fn post_data_onfido(url: Url, api_token: &str, payload: Vec<u8>) -> Result<String> { let mut headers = header::HeaderMap::new(); headers.append( header::AUTHORIZATION, HeaderValue::from_str(&format!("Token token={}", api_token))?, ); headers.append( header::CONTENT_TYPE, HeaderValue::from_static("multipart/form-data"), ); let mut resp = Client::new() .post(url) .headers(headers) .body(payload) .send()?; let mut buf = String::new(); resp.read_to_string(&mut buf)?; Ok(buf) } pub fn delete_onfido(url: Url, api_token: &str) -> Result<String> { let mut resp = Client::new() .delete(url) .header(header::AUTHORIZATION, format!("Token token={}", api_token)) .send()?; let mut buf = String::new(); resp.read_to_string(&mut buf)?; Ok(buf) }
use std::{mem, ptr, slice, u64, cmp}; #[derive(Debug, Clone, Copy, PartialEq)] pub enum Error { Corrupted, Truncated, } type Result<T> = std::result::Result<T, Error>; fn decode_varint_u32_slow(data: &[u8]) -> Result<(u32, u8)> { let mut res = 0; for i in 0..data.len() { let b = data[i]; res |= (b as u32 & 0x7f) << (i * 7); if b < 0x80 { return Ok((res, i as u8 + 1)); } } Err(Error::Truncated) } fn decode_varint_u32_fallback(data: &[u8]) -> Result<(u32, u8)> { if data.len() >= 5 || *data.last().unwrap() < 0x80 { let mut res = 0; for i in 0..4 { let b = unsafe { *data.get_unchecked(i) }; res |= ((b & 0x7f) as u32) << (i * 7); if b < 0x80 { return Ok((res, i as u8 + 1)); } } let b = unsafe { *data.get_unchecked(4) }; res |= (b as u32) << (4 * 7); // Technically, it should be <= 15, but protobuf requires not check the boundary. if b < 0x80 { return Ok((res, 5)); } for i in 5..cmp::min(10, data.len()) { let b = unsafe { *data.get_unchecked(i) }; if b < 0x80 { return Ok((res, i as u8 + 1)); } } if data.len() >= 10 { return Err(Error::Corrupted); } else { return Err(Error::Truncated); } } decode_varint_u32_slow(data) } fn decode_varint_u64_slow(data: &[u8]) -> Result<(u64, u8)> { let mut res = 0; for i in 0..data.len() { let b = data[i]; res |= (b as u64 & 0x7f) << (i * 7); if b < 0x80 { return Ok((res, i as u8 + 1)); } } Err(Error::Truncated) } fn decode_varint_u64_fallback(data: &[u8]) -> Result<(u64, u8)> { if data.len() >= 10 || *data.last().unwrap() < 0x80 { let mut res = 0; for i in 0..9 { let b = unsafe { *data.get_unchecked(i) }; res |= ((b & 0x7f) as u64) << (i * 7); if b < 0x80 { return Ok((res, i as u8 + 1)); } } let b = unsafe { *data.get_unchecked(9) }; if b <= 1 { res |= (b as u64) << (9 * 7); return Ok((res, 10)); } return Err(Error::Corrupted); } decode_varint_u64_slow(data) } #[inline] pub fn decode_varint_s32(data: &[u8]) -> Result<(i32, u8)> { let (r, n) = decode_varint_u32(data)?; Ok((unzig_zag_32(r), n)) } #[inline] pub fn decode_varint_i32(data: &[u8]) -> Result<(i32, u8)> { let (r, n) = decode_varint_u32(data)?; Ok((r as i32, n)) } #[inline] pub fn decode_varint_u32(data: &[u8]) -> Result<(u32, u8)> { if !data.is_empty() { // process with value < 127 independently at first // since it matches most of the cases. if data[0] < 0x80 { let res = u32::from(data[0]); return Ok((res, 1)); } return decode_varint_u32_fallback(data); } Err(Error::Truncated) } #[inline] pub fn decode_varint_s64(data: &[u8]) -> Result<(i64, u8)> { let (r, n) = decode_varint_u64(data)?; Ok((unzig_zag_64(r), n)) } #[inline] pub fn decode_varint_i64(data: &[u8]) -> Result<(i64, u8)> { let (r, n) = decode_varint_u64(data)?; Ok((r as i64, n)) } #[inline] pub fn decode_varint_u64(data: &[u8]) -> Result<(u64, u8)> { if !data.is_empty() { // process with value < 127 independently at first // since it matches most of the cases. if data[0] < 0x80 { let res = u64::from(data[0]); return Ok((res, 1)); } return decode_varint_u64_fallback(data); } Err(Error::Truncated) } macro_rules! var_encode { ($t:ty, $arr_func:ident, $enc_func:ident, $max:expr) => { pub unsafe fn $arr_func(start: *mut u8, mut n: $t) -> usize { let mut cur = start; while n >= 0x80 { ptr::write(cur, 0x80 | n as u8); n >>= 7; cur = cur.add(1); } ptr::write(cur, n as u8); cur as usize - start as usize + 1 } pub fn $enc_func(data: &mut Vec<u8>, n: $t) { let left = data.capacity() - data.len(); if left >= $max { let old_len = data.len(); unsafe { let start = data.as_mut_ptr().add(old_len); let len = $arr_func(start, n); data.set_len(old_len + len); } return; } let mut buf = [0; $max]; unsafe { let start = buf.as_mut_ptr(); let len = $arr_func(start, n); let written = slice::from_raw_parts(start, len); data.extend_from_slice(written); } } }; } var_encode!(u32, encode_varint_u32_to_array, encode_varint_u32, 5); var_encode!(u64, encode_varint_u64_to_array, encode_varint_u64, 10); #[inline] pub fn encode_varint_s32(data: &mut Vec<u8>, n: i32) { let n = zig_zag_32(n); encode_varint_u32(data, n); } #[inline] pub fn encode_varint_i32(data: &mut Vec<u8>, n: i32) { if n >= 0 { encode_varint_u32(data, n as u32) } else { encode_varint_i64(data, n as i64) } } #[inline] pub fn encode_varint_s64(data: &mut Vec<u8>, n: i64) { let n = zig_zag_64(n); encode_varint_u64(data, n); } #[inline] pub fn encode_varint_i64(data: &mut Vec<u8>, n: i64) { let n = n as u64; encode_varint_u64(data, n); } #[inline] pub fn varint_u32_bytes_len(mut n: u32) -> u32 { n |= 0x01; ((31 - n.leading_zeros()) * 9 + 73) / 64 } #[inline] pub fn varint_i32_bytes_len(i: i32) -> u32 { varint_i64_bytes_len(i as i64) } #[inline] pub fn varint_s32_bytes_len(n: i32) -> u32 { varint_u32_bytes_len(zig_zag_32(n)) } #[inline] pub fn varint_u64_bytes_len(mut n: u64) -> u32 { n |= 0x01; ((63 - n.leading_zeros()) * 9 + 73) / 64 } #[inline] pub fn varint_i64_bytes_len(i: i64) -> u32 { varint_u64_bytes_len(i as u64) } #[inline] pub fn varint_s64_bytes_len(n: i64) -> u32 { varint_u64_bytes_len(zig_zag_64(n)) } #[inline] pub fn fixed_i64_bytes_len(_: i64) -> u32 { 8 } #[inline] pub fn fixed_s64_bytes_len(_: i64) -> u32 { 8 } #[inline] pub fn fixed_i32_bytes_len(_: i32) -> u32 { 4 } #[inline] pub fn fixed_s32_bytes_len(_: i32) -> u32 { 4 } #[inline] pub fn f32_bytes_len(_: f32) -> u32 { 4 } #[inline] pub fn f64_bytes_len(_: f64) -> u32 { 8 } #[inline] pub fn zig_zag_64(n: i64) -> u64 { ((n << 1) ^ (n >> 63)) as u64 } #[inline] pub fn unzig_zag_64(n: u64) -> i64 { ((n >> 1) ^ (!(n & 1)).wrapping_add(1)) as i64 } #[inline] pub fn zig_zag_32(n: i32) -> u32 { ((n << 1) ^ (n >> 31)) as u32 } #[inline] pub fn unzig_zag_32(n: u32) -> i32 { ((n >> 1) ^ (!(n & 1)).wrapping_add(1)) as i32 } #[inline] pub fn encode_tag(field_number: u32, wired_id: u32) -> u32 { (field_number << 3) | wired_id } macro_rules! encode_fixed { ($t:ty, $ti:ident, $len:expr, $enc_func:ident, $dec_func:ident) => { #[inline] pub fn $enc_func(data: &mut Vec<u8>, n: $t) { let n = n.to_le(); let b: [u8; $len] = unsafe { mem::transmute(n) }; data.extend_from_slice(&b) } #[inline] pub fn $dec_func(data: &[u8]) -> Result<$t> { let mut b: $t = 0; if data.len() >= $len { unsafe { let buf = &mut b as *mut $t as *mut u8; let data = data.as_ptr(); ptr::copy_nonoverlapping(data, buf, $len); } Ok($ti::from_le(b)) } else { Err(Error::Corrupted) } } }; } encode_fixed!(i32, i32, 4, encode_fixed_i32, decode_fixed_i32); encode_fixed!(i64, i64, 8, encode_fixed_i64, decode_fixed_i64); #[inline] pub fn encode_fixed_f32(data: &mut Vec<u8>, n: f32) { let n = n.to_bits(); encode_fixed_i32(data, n as i32) } #[inline] pub fn decode_fixed_f32(data: &[u8]) -> Result<f32> { decode_fixed_i32(data).map(|n| f32::from_bits(n as u32)) } #[inline] pub fn encode_fixed_f64(data: &mut Vec<u8>, n: f64) { let n = n.to_bits(); encode_fixed_i64(data, n as i64) } #[inline] pub fn decode_fixed_f64(data: &[u8]) -> Result<f64> { decode_fixed_i64(data).map(|n| f64::from_bits(n as u64)) } #[inline] pub fn encode_fixed_s32(data: &mut Vec<u8>, n: i32) { encode_fixed_i32(data, zig_zag_32(n) as i32) } #[inline] pub fn decode_fixed_s32(data: &[u8]) -> Result<i32> { decode_fixed_i32(data).map(|i| unzig_zag_32(i as u32)) } #[inline] pub fn encode_fixed_s64(data: &mut Vec<u8>, n: i64) { encode_fixed_i64(data, zig_zag_64(n) as i64) } #[inline] pub fn decode_fixed_s64(data: &[u8]) -> Result<i64> { decode_fixed_i64(data).map(|i| unzig_zag_64(i as u64)) } #[inline] pub fn encode_bytes(data: &mut Vec<u8>, bytes: &[u8]) { encode_varint_u32(data, bytes.len() as u32); data.extend_from_slice(bytes); } #[inline] pub fn decode_bytes<'a>(data: &'a [u8]) -> Result<(&'a [u8], usize)> { let (len, read) = decode_varint_u32(data)?; let res = if data.len() > len as usize { unsafe { data.get_unchecked(read as usize..len as usize) } } else { return Err(Error::Truncated); }; Ok((res, read as usize + len as usize)) } #[cfg(test)] mod test { use super::*; use std::{i64, u32}; macro_rules! check_res { ($num:ident, $res:expr, $len:expr, 1) => { let (res, read) = $res; assert_eq!(res, $num, "decode for {}", $num); assert_eq!(usize::from(read), $len, "decode for {}", $num); }; ($num:ident, $res:expr, $len:expr, 0) => { let res = $res; assert_eq!(res, $num, "decode for {}", $num); }; } macro_rules! make_test { ($test_name:ident, $cases:expr, $enc:ident, $dec:ident, $len:ident, $check_len:tt) => { #[test] fn $test_name() { let cases = $cases; let mut large_buffer = Vec::with_capacity(11); for (bin, n) in cases { let mut output = vec![]; $enc(&mut output, n); assert_eq!(output, bin, "encode for {}", n); large_buffer.clear(); $enc(&mut large_buffer, n); assert_eq!(large_buffer, bin, "encode for {}", n); assert_eq!($len(n), bin.len() as u32, "{:?}", n); check_res!( n, $dec(&mut output.as_slice()).unwrap(), bin.len(), $check_len ); } } }; ($test_name:ident, $cases:expr, $enc:ident, $dec:ident, $len:ident) => { make_test!($test_name, $cases, $enc, $dec, $len, 1); }; } make_test!( test_varint_i64, vec![ (vec![1], 1), (vec![255, 255, 255, 255, 255, 255, 255, 255, 255, 1], -1), (vec![2], 2), (vec![254, 255, 255, 255, 255, 255, 255, 255, 255, 1], -2), (vec![255, 255, 255, 255, 7], 2147483647), (vec![128, 128, 128, 128, 248, 255, 255, 255, 255, 1], -2147483648), (vec![0], 0), (vec![128, 1], 128), (vec![150, 1], 150), ], encode_varint_i64, decode_varint_i64, varint_i64_bytes_len ); make_test!( test_varint_s64, vec![ (vec![2], 1), (vec![1], -1), (vec![4], 2), (vec![3], -2), (vec![0], 0), (vec![128, 2], 128), (vec![255, 1], -128), (vec![172, 2], 150), (vec![254, 255, 255, 255, 15], 2147483647), (vec![255, 255, 255, 255, 15], -2147483648), ( vec![254, 255, 255, 255, 255, 255, 255, 255, 255, 1], 9223372036854775807 ), ( vec![255, 255, 255, 255, 255, 255, 255, 255, 255, 1], -9223372036854775808 ), ], encode_varint_s64, decode_varint_s64, varint_s64_bytes_len ); make_test!( test_varint_u64, vec![ (vec![1], 1), (vec![150, 1], 150), (vec![127], 127), (vec![128, 127], 16256), (vec![128, 128, 127], 2080768), (vec![128, 128, 128, 127], 266338304), (vec![128, 128, 128, 128, 127], 34091302912), (vec![128, 128, 128, 128, 128, 127], 4363686772736), (vec![128, 128, 128, 128, 128, 128, 127], 558551906910208), ( vec![128, 128, 128, 128, 128, 128, 128, 127], 71494644084506624 ), ( vec![128, 128, 128, 128, 128, 128, 128, 128, 127], 9151314442816847872 ), (vec![255, 255, 255, 255, 15], u32::MAX as u64), ( vec![255, 255, 255, 255, 255, 255, 255, 255, 255, 1], u64::MAX ), ], encode_varint_u64, decode_varint_u64, varint_u64_bytes_len ); make_test!( test_varint_u32, vec![ (vec![1], 1), (vec![150, 1], 150), (vec![127], 127), (vec![128, 127], 16256), (vec![128, 128, 127], 2080768), (vec![128, 128, 128, 127], 266338304), (vec![255, 255, 255, 255, 15], u32::MAX), ], encode_varint_u32, decode_varint_u32, varint_u32_bytes_len ); make_test!( test_varint_i32, vec![ (vec![1], 1), (vec![255, 255, 255, 255, 255, 255, 255, 255, 255, 1], -1), (vec![254, 255, 255, 255, 255, 255, 255, 255, 255, 1], -2), (vec![0], 0), (vec![128, 1], 128), (vec![150, 1], 150), (vec![255, 255, 255, 255, 7], 2147483647), (vec![128, 128, 128, 128, 248, 255, 255, 255, 255, 1], -2147483648), ], encode_varint_i32, decode_varint_i32, varint_i32_bytes_len ); make_test!( test_varint_s32, vec![ (vec![2], 1), (vec![1], -1), (vec![4], 2), (vec![3], -2), (vec![0], 0), (vec![128, 2], 128), (vec![255, 1], -128), (vec![172, 2], 150), (vec![254, 255, 255, 255, 15], 2147483647), (vec![255, 255, 255, 255, 15], -2147483648), ], encode_varint_s32, decode_varint_s32, varint_s32_bytes_len ); make_test!( test_fixed_i32, vec![ (vec![1, 0, 0, 0], 1), (vec![255, 255, 255, 255], -1), (vec![2, 0, 0, 0], 2), (vec![254, 255, 255, 255], -2), (vec![0, 0, 0, 0], 0), (vec![128, 0, 0, 0], 128), (vec![128, 255, 255, 255], -128), (vec![150, 0, 0, 0], 150), (vec![255, 255, 255, 127], 2147483647), (vec![0, 0, 0, 128], -2147483648), ], encode_fixed_i32, decode_fixed_i32, fixed_i32_bytes_len, 0 ); make_test!( test_fixed_i64, vec![ (vec![1, 0, 0, 0, 0, 0, 0, 0], 1), (vec![255, 255, 255, 255, 255, 255, 255, 255], -1), (vec![2, 0, 0, 0, 0, 0, 0, 0], 2), (vec![254, 255, 255, 255, 255, 255, 255, 255], -2), (vec![0, 0, 0, 0, 0, 0, 0, 0], 0), (vec![128, 0, 0, 0, 0, 0, 0, 0], 128), (vec![128, 255, 255, 255, 255, 255, 255, 255], -128), (vec![150, 0, 0, 0, 0, 0, 0, 0], 150), (vec![255, 255, 255, 127, 0, 0, 0, 0], 2147483647), (vec![0, 0, 0, 128, 255, 255, 255, 255], -2147483648), (vec![255, 255, 255, 255, 255, 255, 255, 127], i64::MAX), (vec![0, 0, 0, 0, 0, 0, 0, 128], i64::MIN), ], encode_fixed_i64, decode_fixed_i64, fixed_i64_bytes_len, 0 ); make_test!( test_f32, vec![ (vec![0x00, 0x00, 0x80, 0x3f], 1f32), (vec![0x00, 0x00, 0x80, 0xbf], -1f32), (vec![0x00, 0x00, 0x00, 0x40], 2f32), (vec![0x00, 0x00, 0x00, 0xc0], -2f32), (vec![0x00, 0x00, 0x00, 0x00], 0f32), (vec![0x00, 0x00, 0x00, 0x43], 128f32), (vec![0x00, 0x00, 0x00, 0xc3], -128f32), (vec![0xc3, 0xf5, 0x48, 0x40], 3.14), (vec![0x00, 0x00, 0x00, 0x4f], 2147483647f32), ], encode_fixed_f32, decode_fixed_f32, f32_bytes_len, 0 ); make_test!( test_f64, vec![ (vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f], 1f64), (vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xbf], -1f64), (vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40], 2f64), (vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0], -2f64), (vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 0f64), (vec![0x1f, 0x85, 0xeb, 0x51, 0xb8, 0x1e, 0x09, 0x40], 3.14), ], encode_fixed_f64, decode_fixed_f64, f64_bytes_len, 0 ); }
use nalgebra::Vector3; use crate::{LumpData, LumpType, PrimitiveRead}; use std::io::{Read, Result as IOResult}; pub struct TextureData { pub reflectivity: Vector3<f32>, pub name_string_table_id: i32, pub width: i32, pub height: i32, pub view_width: i32, pub view_height: i32 } impl LumpData for TextureData { fn lump_type() -> LumpType { LumpType::TextureData } fn lump_type_hdr() -> Option<LumpType> { None } fn element_size(_version: i32) -> usize { 32 } fn read(reader: &mut dyn Read, _version: i32) -> IOResult<Self> { Ok(Self { reflectivity: Vector3::new(reader.read_f32()?, reader.read_f32()?, reader.read_f32()?), name_string_table_id: reader.read_i32()?, width: reader.read_i32()?, height: reader.read_i32()?, view_width: reader.read_i32()?, view_height: reader.read_i32()? }) } }
pub(crate) mod core; pub(crate) mod external; #[cfg(feature = "std")] pub(crate) mod std; pub(crate) mod ty_impls;
// auto generated, do not modify. // created: Wed Jan 20 00:44:03 2016 // src-file: /QtNetwork/qnetworkconfigmanager.h // dst-file: /src/network/qnetworkconfigmanager.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::super::core::qobject::QObject; // 771 use std::ops::Deref; use super::super::core::qstring::QString; // 771 use super::qnetworkconfiguration::QNetworkConfiguration; // 773 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QNetworkConfigurationManager_Class_Size() -> c_int; // proto: bool QNetworkConfigurationManager::isOnline(); fn _ZNK28QNetworkConfigurationManager8isOnlineEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QNetworkConfiguration QNetworkConfigurationManager::configurationFromIdentifier(const QString & identifier); fn _ZNK28QNetworkConfigurationManager27configurationFromIdentifierERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QNetworkConfigurationManager::updateConfigurations(); fn _ZN28QNetworkConfigurationManager20updateConfigurationsEv(qthis: u64 /* *mut c_void*/); // proto: void QNetworkConfigurationManager::QNetworkConfigurationManager(const QNetworkConfigurationManager & ); fn _ZN28QNetworkConfigurationManagerC2ERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QNetworkConfiguration QNetworkConfigurationManager::defaultConfiguration(); fn _ZNK28QNetworkConfigurationManager20defaultConfigurationEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QNetworkConfigurationManager::QNetworkConfigurationManager(QObject * parent); fn _ZN28QNetworkConfigurationManagerC2EP7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: const QMetaObject * QNetworkConfigurationManager::metaObject(); fn _ZNK28QNetworkConfigurationManager10metaObjectEv(qthis: u64 /* *mut c_void*/); // proto: void QNetworkConfigurationManager::~QNetworkConfigurationManager(); fn _ZN28QNetworkConfigurationManagerD2Ev(qthis: u64 /* *mut c_void*/); fn QNetworkConfigurationManager_SlotProxy_connect__ZN28QNetworkConfigurationManager18onlineStateChangedEb(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QNetworkConfigurationManager_SlotProxy_connect__ZN28QNetworkConfigurationManager15updateCompletedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QNetworkConfigurationManager_SlotProxy_connect__ZN28QNetworkConfigurationManager20configurationChangedERK21QNetworkConfiguration(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QNetworkConfigurationManager_SlotProxy_connect__ZN28QNetworkConfigurationManager20configurationRemovedERK21QNetworkConfiguration(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QNetworkConfigurationManager_SlotProxy_connect__ZN28QNetworkConfigurationManager18configurationAddedERK21QNetworkConfiguration(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); } // <= ext block end // body block begin => // class sizeof(QNetworkConfigurationManager)=1 #[derive(Default)] pub struct QNetworkConfigurationManager { qbase: QObject, pub qclsinst: u64 /* *mut c_void*/, pub _configurationAdded: QNetworkConfigurationManager_configurationAdded_signal, pub _onlineStateChanged: QNetworkConfigurationManager_onlineStateChanged_signal, pub _configurationRemoved: QNetworkConfigurationManager_configurationRemoved_signal, pub _updateCompleted: QNetworkConfigurationManager_updateCompleted_signal, pub _configurationChanged: QNetworkConfigurationManager_configurationChanged_signal, } impl /*struct*/ QNetworkConfigurationManager { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QNetworkConfigurationManager { return QNetworkConfigurationManager{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QNetworkConfigurationManager { type Target = QObject; fn deref(&self) -> &QObject { return & self.qbase; } } impl AsRef<QObject> for QNetworkConfigurationManager { fn as_ref(& self) -> & QObject { return & self.qbase; } } // proto: bool QNetworkConfigurationManager::isOnline(); impl /*struct*/ QNetworkConfigurationManager { pub fn isOnline<RetType, T: QNetworkConfigurationManager_isOnline<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isOnline(self); // return 1; } } pub trait QNetworkConfigurationManager_isOnline<RetType> { fn isOnline(self , rsthis: & QNetworkConfigurationManager) -> RetType; } // proto: bool QNetworkConfigurationManager::isOnline(); impl<'a> /*trait*/ QNetworkConfigurationManager_isOnline<i8> for () { fn isOnline(self , rsthis: & QNetworkConfigurationManager) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK28QNetworkConfigurationManager8isOnlineEv()}; let mut ret = unsafe {_ZNK28QNetworkConfigurationManager8isOnlineEv(rsthis.qclsinst)}; return ret as i8; // return 1; } } // proto: QNetworkConfiguration QNetworkConfigurationManager::configurationFromIdentifier(const QString & identifier); impl /*struct*/ QNetworkConfigurationManager { pub fn configurationFromIdentifier<RetType, T: QNetworkConfigurationManager_configurationFromIdentifier<RetType>>(& self, overload_args: T) -> RetType { return overload_args.configurationFromIdentifier(self); // return 1; } } pub trait QNetworkConfigurationManager_configurationFromIdentifier<RetType> { fn configurationFromIdentifier(self , rsthis: & QNetworkConfigurationManager) -> RetType; } // proto: QNetworkConfiguration QNetworkConfigurationManager::configurationFromIdentifier(const QString & identifier); impl<'a> /*trait*/ QNetworkConfigurationManager_configurationFromIdentifier<QNetworkConfiguration> for (&'a QString) { fn configurationFromIdentifier(self , rsthis: & QNetworkConfigurationManager) -> QNetworkConfiguration { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK28QNetworkConfigurationManager27configurationFromIdentifierERK7QString()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {_ZNK28QNetworkConfigurationManager27configurationFromIdentifierERK7QString(rsthis.qclsinst, arg0)}; let mut ret1 = QNetworkConfiguration::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QNetworkConfigurationManager::updateConfigurations(); impl /*struct*/ QNetworkConfigurationManager { pub fn updateConfigurations<RetType, T: QNetworkConfigurationManager_updateConfigurations<RetType>>(& self, overload_args: T) -> RetType { return overload_args.updateConfigurations(self); // return 1; } } pub trait QNetworkConfigurationManager_updateConfigurations<RetType> { fn updateConfigurations(self , rsthis: & QNetworkConfigurationManager) -> RetType; } // proto: void QNetworkConfigurationManager::updateConfigurations(); impl<'a> /*trait*/ QNetworkConfigurationManager_updateConfigurations<()> for () { fn updateConfigurations(self , rsthis: & QNetworkConfigurationManager) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN28QNetworkConfigurationManager20updateConfigurationsEv()}; unsafe {_ZN28QNetworkConfigurationManager20updateConfigurationsEv(rsthis.qclsinst)}; // return 1; } } // proto: void QNetworkConfigurationManager::QNetworkConfigurationManager(const QNetworkConfigurationManager & ); impl /*struct*/ QNetworkConfigurationManager { pub fn new<T: QNetworkConfigurationManager_new>(value: T) -> QNetworkConfigurationManager { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QNetworkConfigurationManager_new { fn new(self) -> QNetworkConfigurationManager; } // proto: void QNetworkConfigurationManager::QNetworkConfigurationManager(const QNetworkConfigurationManager & ); impl<'a> /*trait*/ QNetworkConfigurationManager_new for (&'a QNetworkConfigurationManager) { fn new(self) -> QNetworkConfigurationManager { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN28QNetworkConfigurationManagerC2ERKS_()}; let ctysz: c_int = unsafe{QNetworkConfigurationManager_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; unsafe {_ZN28QNetworkConfigurationManagerC2ERKS_(qthis_ph, arg0)}; let qthis: u64 = qthis_ph; let rsthis = QNetworkConfigurationManager{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QNetworkConfiguration QNetworkConfigurationManager::defaultConfiguration(); impl /*struct*/ QNetworkConfigurationManager { pub fn defaultConfiguration<RetType, T: QNetworkConfigurationManager_defaultConfiguration<RetType>>(& self, overload_args: T) -> RetType { return overload_args.defaultConfiguration(self); // return 1; } } pub trait QNetworkConfigurationManager_defaultConfiguration<RetType> { fn defaultConfiguration(self , rsthis: & QNetworkConfigurationManager) -> RetType; } // proto: QNetworkConfiguration QNetworkConfigurationManager::defaultConfiguration(); impl<'a> /*trait*/ QNetworkConfigurationManager_defaultConfiguration<QNetworkConfiguration> for () { fn defaultConfiguration(self , rsthis: & QNetworkConfigurationManager) -> QNetworkConfiguration { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK28QNetworkConfigurationManager20defaultConfigurationEv()}; let mut ret = unsafe {_ZNK28QNetworkConfigurationManager20defaultConfigurationEv(rsthis.qclsinst)}; let mut ret1 = QNetworkConfiguration::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QNetworkConfigurationManager::QNetworkConfigurationManager(QObject * parent); impl<'a> /*trait*/ QNetworkConfigurationManager_new for (&'a QObject) { fn new(self) -> QNetworkConfigurationManager { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN28QNetworkConfigurationManagerC2EP7QObject()}; let ctysz: c_int = unsafe{QNetworkConfigurationManager_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; unsafe {_ZN28QNetworkConfigurationManagerC2EP7QObject(qthis_ph, arg0)}; let qthis: u64 = qthis_ph; let rsthis = QNetworkConfigurationManager{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: const QMetaObject * QNetworkConfigurationManager::metaObject(); impl /*struct*/ QNetworkConfigurationManager { pub fn metaObject<RetType, T: QNetworkConfigurationManager_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QNetworkConfigurationManager_metaObject<RetType> { fn metaObject(self , rsthis: & QNetworkConfigurationManager) -> RetType; } // proto: const QMetaObject * QNetworkConfigurationManager::metaObject(); impl<'a> /*trait*/ QNetworkConfigurationManager_metaObject<()> for () { fn metaObject(self , rsthis: & QNetworkConfigurationManager) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK28QNetworkConfigurationManager10metaObjectEv()}; unsafe {_ZNK28QNetworkConfigurationManager10metaObjectEv(rsthis.qclsinst)}; // return 1; } } // proto: void QNetworkConfigurationManager::~QNetworkConfigurationManager(); impl /*struct*/ QNetworkConfigurationManager { pub fn free<RetType, T: QNetworkConfigurationManager_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QNetworkConfigurationManager_free<RetType> { fn free(self , rsthis: & QNetworkConfigurationManager) -> RetType; } // proto: void QNetworkConfigurationManager::~QNetworkConfigurationManager(); impl<'a> /*trait*/ QNetworkConfigurationManager_free<()> for () { fn free(self , rsthis: & QNetworkConfigurationManager) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN28QNetworkConfigurationManagerD2Ev()}; unsafe {_ZN28QNetworkConfigurationManagerD2Ev(rsthis.qclsinst)}; // return 1; } } #[derive(Default)] // for QNetworkConfigurationManager_configurationAdded pub struct QNetworkConfigurationManager_configurationAdded_signal{poi:u64} impl /* struct */ QNetworkConfigurationManager { pub fn configurationAdded(&self) -> QNetworkConfigurationManager_configurationAdded_signal { return QNetworkConfigurationManager_configurationAdded_signal{poi:self.qclsinst}; } } impl /* struct */ QNetworkConfigurationManager_configurationAdded_signal { pub fn connect<T: QNetworkConfigurationManager_configurationAdded_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QNetworkConfigurationManager_configurationAdded_signal_connect { fn connect(self, sigthis: QNetworkConfigurationManager_configurationAdded_signal); } #[derive(Default)] // for QNetworkConfigurationManager_onlineStateChanged pub struct QNetworkConfigurationManager_onlineStateChanged_signal{poi:u64} impl /* struct */ QNetworkConfigurationManager { pub fn onlineStateChanged(&self) -> QNetworkConfigurationManager_onlineStateChanged_signal { return QNetworkConfigurationManager_onlineStateChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QNetworkConfigurationManager_onlineStateChanged_signal { pub fn connect<T: QNetworkConfigurationManager_onlineStateChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QNetworkConfigurationManager_onlineStateChanged_signal_connect { fn connect(self, sigthis: QNetworkConfigurationManager_onlineStateChanged_signal); } #[derive(Default)] // for QNetworkConfigurationManager_configurationRemoved pub struct QNetworkConfigurationManager_configurationRemoved_signal{poi:u64} impl /* struct */ QNetworkConfigurationManager { pub fn configurationRemoved(&self) -> QNetworkConfigurationManager_configurationRemoved_signal { return QNetworkConfigurationManager_configurationRemoved_signal{poi:self.qclsinst}; } } impl /* struct */ QNetworkConfigurationManager_configurationRemoved_signal { pub fn connect<T: QNetworkConfigurationManager_configurationRemoved_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QNetworkConfigurationManager_configurationRemoved_signal_connect { fn connect(self, sigthis: QNetworkConfigurationManager_configurationRemoved_signal); } #[derive(Default)] // for QNetworkConfigurationManager_updateCompleted pub struct QNetworkConfigurationManager_updateCompleted_signal{poi:u64} impl /* struct */ QNetworkConfigurationManager { pub fn updateCompleted(&self) -> QNetworkConfigurationManager_updateCompleted_signal { return QNetworkConfigurationManager_updateCompleted_signal{poi:self.qclsinst}; } } impl /* struct */ QNetworkConfigurationManager_updateCompleted_signal { pub fn connect<T: QNetworkConfigurationManager_updateCompleted_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QNetworkConfigurationManager_updateCompleted_signal_connect { fn connect(self, sigthis: QNetworkConfigurationManager_updateCompleted_signal); } #[derive(Default)] // for QNetworkConfigurationManager_configurationChanged pub struct QNetworkConfigurationManager_configurationChanged_signal{poi:u64} impl /* struct */ QNetworkConfigurationManager { pub fn configurationChanged(&self) -> QNetworkConfigurationManager_configurationChanged_signal { return QNetworkConfigurationManager_configurationChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QNetworkConfigurationManager_configurationChanged_signal { pub fn connect<T: QNetworkConfigurationManager_configurationChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QNetworkConfigurationManager_configurationChanged_signal_connect { fn connect(self, sigthis: QNetworkConfigurationManager_configurationChanged_signal); } // onlineStateChanged(_Bool) extern fn QNetworkConfigurationManager_onlineStateChanged_signal_connect_cb_0(rsfptr:fn(i8), arg0: c_char) { println!("{}:{}", file!(), line!()); let rsarg0 = arg0 as i8; rsfptr(rsarg0); } extern fn QNetworkConfigurationManager_onlineStateChanged_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(i8)>, arg0: c_char) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = arg0 as i8; // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QNetworkConfigurationManager_onlineStateChanged_signal_connect for fn(i8) { fn connect(self, sigthis: QNetworkConfigurationManager_onlineStateChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkConfigurationManager_onlineStateChanged_signal_connect_cb_0 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QNetworkConfigurationManager_SlotProxy_connect__ZN28QNetworkConfigurationManager18onlineStateChangedEb(arg0, arg1, arg2)}; } } impl /* trait */ QNetworkConfigurationManager_onlineStateChanged_signal_connect for Box<Fn(i8)> { fn connect(self, sigthis: QNetworkConfigurationManager_onlineStateChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkConfigurationManager_onlineStateChanged_signal_connect_cb_box_0 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QNetworkConfigurationManager_SlotProxy_connect__ZN28QNetworkConfigurationManager18onlineStateChangedEb(arg0, arg1, arg2)}; } } // updateCompleted() extern fn QNetworkConfigurationManager_updateCompleted_signal_connect_cb_1(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QNetworkConfigurationManager_updateCompleted_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QNetworkConfigurationManager_updateCompleted_signal_connect for fn() { fn connect(self, sigthis: QNetworkConfigurationManager_updateCompleted_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkConfigurationManager_updateCompleted_signal_connect_cb_1 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QNetworkConfigurationManager_SlotProxy_connect__ZN28QNetworkConfigurationManager15updateCompletedEv(arg0, arg1, arg2)}; } } impl /* trait */ QNetworkConfigurationManager_updateCompleted_signal_connect for Box<Fn()> { fn connect(self, sigthis: QNetworkConfigurationManager_updateCompleted_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkConfigurationManager_updateCompleted_signal_connect_cb_box_1 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QNetworkConfigurationManager_SlotProxy_connect__ZN28QNetworkConfigurationManager15updateCompletedEv(arg0, arg1, arg2)}; } } // configurationChanged(const class QNetworkConfiguration &) extern fn QNetworkConfigurationManager_configurationChanged_signal_connect_cb_2(rsfptr:fn(QNetworkConfiguration), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QNetworkConfiguration::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QNetworkConfigurationManager_configurationChanged_signal_connect_cb_box_2(rsfptr_raw:*mut Box<Fn(QNetworkConfiguration)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QNetworkConfiguration::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QNetworkConfigurationManager_configurationChanged_signal_connect for fn(QNetworkConfiguration) { fn connect(self, sigthis: QNetworkConfigurationManager_configurationChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkConfigurationManager_configurationChanged_signal_connect_cb_2 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QNetworkConfigurationManager_SlotProxy_connect__ZN28QNetworkConfigurationManager20configurationChangedERK21QNetworkConfiguration(arg0, arg1, arg2)}; } } impl /* trait */ QNetworkConfigurationManager_configurationChanged_signal_connect for Box<Fn(QNetworkConfiguration)> { fn connect(self, sigthis: QNetworkConfigurationManager_configurationChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkConfigurationManager_configurationChanged_signal_connect_cb_box_2 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QNetworkConfigurationManager_SlotProxy_connect__ZN28QNetworkConfigurationManager20configurationChangedERK21QNetworkConfiguration(arg0, arg1, arg2)}; } } // configurationRemoved(const class QNetworkConfiguration &) extern fn QNetworkConfigurationManager_configurationRemoved_signal_connect_cb_3(rsfptr:fn(QNetworkConfiguration), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QNetworkConfiguration::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QNetworkConfigurationManager_configurationRemoved_signal_connect_cb_box_3(rsfptr_raw:*mut Box<Fn(QNetworkConfiguration)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QNetworkConfiguration::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QNetworkConfigurationManager_configurationRemoved_signal_connect for fn(QNetworkConfiguration) { fn connect(self, sigthis: QNetworkConfigurationManager_configurationRemoved_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkConfigurationManager_configurationRemoved_signal_connect_cb_3 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QNetworkConfigurationManager_SlotProxy_connect__ZN28QNetworkConfigurationManager20configurationRemovedERK21QNetworkConfiguration(arg0, arg1, arg2)}; } } impl /* trait */ QNetworkConfigurationManager_configurationRemoved_signal_connect for Box<Fn(QNetworkConfiguration)> { fn connect(self, sigthis: QNetworkConfigurationManager_configurationRemoved_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkConfigurationManager_configurationRemoved_signal_connect_cb_box_3 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QNetworkConfigurationManager_SlotProxy_connect__ZN28QNetworkConfigurationManager20configurationRemovedERK21QNetworkConfiguration(arg0, arg1, arg2)}; } } // configurationAdded(const class QNetworkConfiguration &) extern fn QNetworkConfigurationManager_configurationAdded_signal_connect_cb_4(rsfptr:fn(QNetworkConfiguration), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QNetworkConfiguration::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QNetworkConfigurationManager_configurationAdded_signal_connect_cb_box_4(rsfptr_raw:*mut Box<Fn(QNetworkConfiguration)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QNetworkConfiguration::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QNetworkConfigurationManager_configurationAdded_signal_connect for fn(QNetworkConfiguration) { fn connect(self, sigthis: QNetworkConfigurationManager_configurationAdded_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkConfigurationManager_configurationAdded_signal_connect_cb_4 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QNetworkConfigurationManager_SlotProxy_connect__ZN28QNetworkConfigurationManager18configurationAddedERK21QNetworkConfiguration(arg0, arg1, arg2)}; } } impl /* trait */ QNetworkConfigurationManager_configurationAdded_signal_connect for Box<Fn(QNetworkConfiguration)> { fn connect(self, sigthis: QNetworkConfigurationManager_configurationAdded_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkConfigurationManager_configurationAdded_signal_connect_cb_box_4 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QNetworkConfigurationManager_SlotProxy_connect__ZN28QNetworkConfigurationManager18configurationAddedERK21QNetworkConfiguration(arg0, arg1, arg2)}; } } // <= body block end
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn serialize_operation_analyze_document( input: &crate::input::AnalyzeDocumentInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_analyze_document_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_analyze_expense( input: &crate::input::AnalyzeExpenseInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_analyze_expense_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_detect_document_text( input: &crate::input::DetectDocumentTextInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_detect_document_text_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_document_analysis( input: &crate::input::GetDocumentAnalysisInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_document_analysis_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_document_text_detection( input: &crate::input::GetDocumentTextDetectionInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_document_text_detection_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_start_document_analysis( input: &crate::input::StartDocumentAnalysisInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_start_document_analysis_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_start_document_text_detection( input: &crate::input::StartDocumentTextDetectionInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_start_document_text_detection_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) }
use std::net::TcpStream; use std::io::*; use std::time::Duration; use rustcat::lib; fn connect(host: &String, port: &String) -> TcpStream { let conn_string = format!("{}:{}", host, port); let stream = TcpStream::connect(&conn_string) .expect("Could not connect to address."); println!("Connected to {}", conn_string); stream.set_read_timeout(Some(Duration::from_millis(150))).unwrap(); return stream; } pub fn write_loop(args: lib::CliArgs) -> std::io::Result<()> { let host = args.host; let port = args.port; let stream = connect(&host, &port); let mut response: Vec<u8>; let mut query = String::new(); let outfile = args.output; let mut reader = std::io::BufReader::new(&stream); let mut writer = std::io::BufWriter::new(&stream); loop { response = lib::read_til_empty(&mut reader); response.retain(|&x| x != 0x00); println!("{}\n", String::from_utf8_lossy(&mut response)); if outfile.is_some() { lib::hexdump(true, response.len(), &response.as_slice(), outfile.as_ref().unwrap()); } response.clear(); read_user_query(&mut query); if outfile.is_some() { lib::hexdump(false, query.len(), &query.as_bytes(), outfile.as_ref().unwrap()); } query.push('\n'); let n_bytes = writer.write(query.as_bytes()) .expect("Unable to write query, connection closed."); if n_bytes == 0{ println!("No bytes written, connection closed."); break Ok(()); } writer.flush().expect("Unable to flush stream."); query.clear(); } } fn read_user_query(mut query: &mut String) { print!("> "); std::io::stdout().flush().unwrap(); std::io::stdin().read_line(&mut query).expect("Error reading query"); if query.trim().is_empty() { query.clear(); read_user_query(&mut query); } }
use crate::integer::Integer; use core::ops::Sub; // Sub The subtraction operator -. // ['Integer', 'Integer', 'Integer', 'Integer::subtract_assign', 'lhs', // ['ref_mut'], ['ref']] impl Sub<Integer> for Integer { type Output = Integer; fn sub(mut self, rhs: Integer) -> Self::Output { Integer::subtract_assign(&mut self, &rhs); self } } // ['Integer', '&Integer', 'Integer', 'Integer::subtract_assign', 'lhs', // ['ref_mut'], []] impl Sub<&Integer> for Integer { type Output = Integer; fn sub(mut self, rhs: &Integer) -> Self::Output { Integer::subtract_assign(&mut self, rhs); self } } // ['&Integer', 'Integer', 'Integer', 'Integer::subtract', 'no', [], ['ref']] impl Sub<Integer> for &Integer { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(self, &rhs) } } // ['&Integer', '&Integer', 'Integer', 'Integer::subtract', 'no', [], []] impl Sub<&Integer> for &Integer { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(self, rhs) } } // ['Integer', 'i8', 'Integer', 'Integer::subtract_c_long_assign', 'lhs', // ['ref_mut'], []] impl Sub<i8> for Integer { type Output = Integer; fn sub(mut self, rhs: i8) -> Self::Output { Integer::subtract_c_long_assign(&mut self, rhs); self } } // ['Integer', '&i8', 'Integer', 'Integer::subtract_c_long_assign', 'lhs', // ['ref_mut'], ['deref']] impl Sub<&i8> for Integer { type Output = Integer; fn sub(mut self, rhs: &i8) -> Self::Output { Integer::subtract_c_long_assign(&mut self, *rhs); self } } // ['&Integer', 'i8', 'Integer', 'Integer::subtract_c_long', 'no', [], []] impl Sub<i8> for &Integer { type Output = Integer; fn sub(self, rhs: i8) -> Self::Output { Integer::subtract_c_long(self, rhs) } } // ['&Integer', '&i8', 'Integer', 'Integer::subtract_c_long', 'no', [], // ['deref']] impl Sub<&i8> for &Integer { type Output = Integer; fn sub(self, rhs: &i8) -> Self::Output { Integer::subtract_c_long(self, *rhs) } } // ['i8', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], ['ref']] impl Sub<Integer> for i8 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(self), &rhs) } } // ['i8', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], []] impl Sub<&Integer> for i8 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(self), rhs) } } // ['&i8', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}, 'deref'], ['ref']] impl Sub<Integer> for &i8 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), &rhs) } } // ['&i8', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}, 'deref'], []] impl Sub<&Integer> for &i8 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), rhs) } } // ['Integer', 'u8', 'Integer', 'Integer::subtract_c_long_assign', 'lhs', // ['ref_mut'], []] impl Sub<u8> for Integer { type Output = Integer; fn sub(mut self, rhs: u8) -> Self::Output { Integer::subtract_c_long_assign(&mut self, rhs); self } } // ['Integer', '&u8', 'Integer', 'Integer::subtract_c_long_assign', 'lhs', // ['ref_mut'], ['deref']] impl Sub<&u8> for Integer { type Output = Integer; fn sub(mut self, rhs: &u8) -> Self::Output { Integer::subtract_c_long_assign(&mut self, *rhs); self } } // ['&Integer', 'u8', 'Integer', 'Integer::subtract_c_long', 'no', [], []] impl Sub<u8> for &Integer { type Output = Integer; fn sub(self, rhs: u8) -> Self::Output { Integer::subtract_c_long(self, rhs) } } // ['&Integer', '&u8', 'Integer', 'Integer::subtract_c_long', 'no', [], // ['deref']] impl Sub<&u8> for &Integer { type Output = Integer; fn sub(self, rhs: &u8) -> Self::Output { Integer::subtract_c_long(self, *rhs) } } // ['u8', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], ['ref']] impl Sub<Integer> for u8 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(self), &rhs) } } // ['u8', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], []] impl Sub<&Integer> for u8 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(self), rhs) } } // ['&u8', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}, 'deref'], ['ref']] impl Sub<Integer> for &u8 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), &rhs) } } // ['&u8', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}, 'deref'], []] impl Sub<&Integer> for &u8 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), rhs) } } // ['Integer', 'i16', 'Integer', 'Integer::subtract_c_long_assign', 'lhs', // ['ref_mut'], []] impl Sub<i16> for Integer { type Output = Integer; fn sub(mut self, rhs: i16) -> Self::Output { Integer::subtract_c_long_assign(&mut self, rhs); self } } // ['Integer', '&i16', 'Integer', 'Integer::subtract_c_long_assign', 'lhs', // ['ref_mut'], ['deref']] impl Sub<&i16> for Integer { type Output = Integer; fn sub(mut self, rhs: &i16) -> Self::Output { Integer::subtract_c_long_assign(&mut self, *rhs); self } } // ['&Integer', 'i16', 'Integer', 'Integer::subtract_c_long', 'no', [], []] impl Sub<i16> for &Integer { type Output = Integer; fn sub(self, rhs: i16) -> Self::Output { Integer::subtract_c_long(self, rhs) } } // ['&Integer', '&i16', 'Integer', 'Integer::subtract_c_long', 'no', [], // ['deref']] impl Sub<&i16> for &Integer { type Output = Integer; fn sub(self, rhs: &i16) -> Self::Output { Integer::subtract_c_long(self, *rhs) } } // ['i16', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], ['ref']] impl Sub<Integer> for i16 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(self), &rhs) } } // ['i16', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], []] impl Sub<&Integer> for i16 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(self), rhs) } } // ['&i16', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}, 'deref'], ['ref']] impl Sub<Integer> for &i16 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), &rhs) } } // ['&i16', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', // {'convert': 'Integer'}, 'deref'], []] impl Sub<&Integer> for &i16 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), rhs) } } // ['Integer', 'u16', 'Integer', 'Integer::subtract_c_long_assign', 'lhs', // ['ref_mut'], []] impl Sub<u16> for Integer { type Output = Integer; fn sub(mut self, rhs: u16) -> Self::Output { Integer::subtract_c_long_assign(&mut self, rhs); self } } // ['Integer', '&u16', 'Integer', 'Integer::subtract_c_long_assign', 'lhs', // ['ref_mut'], ['deref']] impl Sub<&u16> for Integer { type Output = Integer; fn sub(mut self, rhs: &u16) -> Self::Output { Integer::subtract_c_long_assign(&mut self, *rhs); self } } // ['&Integer', 'u16', 'Integer', 'Integer::subtract_c_long', 'no', [], []] impl Sub<u16> for &Integer { type Output = Integer; fn sub(self, rhs: u16) -> Self::Output { Integer::subtract_c_long(self, rhs) } } // ['&Integer', '&u16', 'Integer', 'Integer::subtract_c_long', 'no', [], // ['deref']] impl Sub<&u16> for &Integer { type Output = Integer; fn sub(self, rhs: &u16) -> Self::Output { Integer::subtract_c_long(self, *rhs) } } // ['u16', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], ['ref']] impl Sub<Integer> for u16 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(self), &rhs) } } // ['u16', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], []] impl Sub<&Integer> for u16 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(self), rhs) } } // ['&u16', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}, 'deref'], ['ref']] impl Sub<Integer> for &u16 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), &rhs) } } // ['&u16', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', // {'convert': 'Integer'}, 'deref'], []] impl Sub<&Integer> for &u16 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), rhs) } } // ['Integer', 'i32', 'Integer', 'Integer::subtract_c_long_assign', 'lhs', // ['ref_mut'], []] impl Sub<i32> for Integer { type Output = Integer; fn sub(mut self, rhs: i32) -> Self::Output { Integer::subtract_c_long_assign(&mut self, rhs); self } } // ['Integer', '&i32', 'Integer', 'Integer::subtract_c_long_assign', 'lhs', // ['ref_mut'], ['deref']] impl Sub<&i32> for Integer { type Output = Integer; fn sub(mut self, rhs: &i32) -> Self::Output { Integer::subtract_c_long_assign(&mut self, *rhs); self } } // ['&Integer', 'i32', 'Integer', 'Integer::subtract_c_long', 'no', [], []] impl Sub<i32> for &Integer { type Output = Integer; fn sub(self, rhs: i32) -> Self::Output { Integer::subtract_c_long(self, rhs) } } // ['&Integer', '&i32', 'Integer', 'Integer::subtract_c_long', 'no', [], // ['deref']] impl Sub<&i32> for &Integer { type Output = Integer; fn sub(self, rhs: &i32) -> Self::Output { Integer::subtract_c_long(self, *rhs) } } // ['i32', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], ['ref']] impl Sub<Integer> for i32 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(self), &rhs) } } // ['i32', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], []] impl Sub<&Integer> for i32 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(self), rhs) } } // ['&i32', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}, 'deref'], ['ref']] impl Sub<Integer> for &i32 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), &rhs) } } // ['&i32', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', // {'convert': 'Integer'}, 'deref'], []] impl Sub<&Integer> for &i32 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), rhs) } } // ['Integer', 'u32', 'Integer', 'Integer::subtract_c_long_assign', 'lhs', // ['ref_mut'], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Sub<u32> for Integer { type Output = Integer; fn sub(mut self, rhs: u32) -> Self::Output { Integer::subtract_c_long_assign(&mut self, rhs); self } } // ['Integer', '&u32', 'Integer', 'Integer::subtract_c_long_assign', 'lhs', // ['ref_mut'], ['deref']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Sub<&u32> for Integer { type Output = Integer; fn sub(mut self, rhs: &u32) -> Self::Output { Integer::subtract_c_long_assign(&mut self, *rhs); self } } // ['&Integer', 'u32', 'Integer', 'Integer::subtract_c_long', 'no', [], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Sub<u32> for &Integer { type Output = Integer; fn sub(self, rhs: u32) -> Self::Output { Integer::subtract_c_long(self, rhs) } } // ['&Integer', '&u32', 'Integer', 'Integer::subtract_c_long', 'no', [], // ['deref']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Sub<&u32> for &Integer { type Output = Integer; fn sub(self, rhs: &u32) -> Self::Output { Integer::subtract_c_long(self, *rhs) } } // ['u32', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], ['ref']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Sub<Integer> for u32 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(self), &rhs) } } // ['u32', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Sub<&Integer> for u32 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(self), rhs) } } // ['&u32', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}, 'deref'], ['ref']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Sub<Integer> for &u32 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), &rhs) } } // ['&u32', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', // {'convert': 'Integer'}, 'deref'], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Sub<&Integer> for &u32 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), rhs) } } // ['Integer', 'i64', 'Integer', 'Integer::subtract_c_long_assign', 'lhs', // ['ref_mut'], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Sub<i64> for Integer { type Output = Integer; fn sub(mut self, rhs: i64) -> Self::Output { Integer::subtract_c_long_assign(&mut self, rhs); self } } // ['Integer', '&i64', 'Integer', 'Integer::subtract_c_long_assign', 'lhs', // ['ref_mut'], ['deref']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Sub<&i64> for Integer { type Output = Integer; fn sub(mut self, rhs: &i64) -> Self::Output { Integer::subtract_c_long_assign(&mut self, *rhs); self } } // ['&Integer', 'i64', 'Integer', 'Integer::subtract_c_long', 'no', [], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Sub<i64> for &Integer { type Output = Integer; fn sub(self, rhs: i64) -> Self::Output { Integer::subtract_c_long(self, rhs) } } // ['&Integer', '&i64', 'Integer', 'Integer::subtract_c_long', 'no', [], // ['deref']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Sub<&i64> for &Integer { type Output = Integer; fn sub(self, rhs: &i64) -> Self::Output { Integer::subtract_c_long(self, *rhs) } } // ['i64', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], ['ref']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Sub<Integer> for i64 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(self), &rhs) } } // ['i64', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Sub<&Integer> for i64 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(self), rhs) } } // ['&i64', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}, 'deref'], ['ref']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Sub<Integer> for &i64 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), &rhs) } } // ['&i64', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', // {'convert': 'Integer'}, 'deref'], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Sub<&Integer> for &i64 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), rhs) } } // ['Integer', 'u32', 'Integer', 'Integer::subtract_assign', 'lhs', ['ref_mut'], // ['ref', {'convert': 'Integer'}]] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Sub<u32> for Integer { type Output = Integer; fn sub(mut self, rhs: u32) -> Self::Output { Integer::subtract_assign(&mut self, &Integer::from(rhs)); self } } // ['Integer', '&u32', 'Integer', 'Integer::subtract_assign', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Sub<&u32> for Integer { type Output = Integer; fn sub(mut self, rhs: &u32) -> Self::Output { Integer::subtract_assign(&mut self, &Integer::from(*rhs)); self } } // ['&Integer', 'u32', 'Integer', 'Integer::subtract', 'no', [], ['ref', // {'convert': 'Integer'}]] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Sub<u32> for &Integer { type Output = Integer; fn sub(self, rhs: u32) -> Self::Output { Integer::subtract(self, &Integer::from(rhs)) } } // ['&Integer', '&u32', 'Integer', 'Integer::subtract', 'no', [], ['ref', // {'convert': 'Integer'}, 'deref']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Sub<&u32> for &Integer { type Output = Integer; fn sub(self, rhs: &u32) -> Self::Output { Integer::subtract(self, &Integer::from(*rhs)) } } // ['u32', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], ['ref']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Sub<Integer> for u32 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(self), &rhs) } } // ['u32', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], []] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Sub<&Integer> for u32 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(self), rhs) } } // ['&u32', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}, 'deref'], ['ref']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Sub<Integer> for &u32 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), &rhs) } } // ['&u32', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', // {'convert': 'Integer'}, 'deref'], []] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Sub<&Integer> for &u32 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), rhs) } } // ['Integer', 'i64', 'Integer', 'Integer::subtract_assign', 'lhs', ['ref_mut'], // ['ref', {'convert': 'Integer'}]] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Sub<i64> for Integer { type Output = Integer; fn sub(mut self, rhs: i64) -> Self::Output { Integer::subtract_assign(&mut self, &Integer::from(rhs)); self } } // ['Integer', '&i64', 'Integer', 'Integer::subtract_assign', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Sub<&i64> for Integer { type Output = Integer; fn sub(mut self, rhs: &i64) -> Self::Output { Integer::subtract_assign(&mut self, &Integer::from(*rhs)); self } } // ['&Integer', 'i64', 'Integer', 'Integer::subtract', 'no', [], ['ref', // {'convert': 'Integer'}]] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Sub<i64> for &Integer { type Output = Integer; fn sub(self, rhs: i64) -> Self::Output { Integer::subtract(self, &Integer::from(rhs)) } } // ['&Integer', '&i64', 'Integer', 'Integer::subtract', 'no', [], ['ref', // {'convert': 'Integer'}, 'deref']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Sub<&i64> for &Integer { type Output = Integer; fn sub(self, rhs: &i64) -> Self::Output { Integer::subtract(self, &Integer::from(*rhs)) } } // ['i64', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], ['ref']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Sub<Integer> for i64 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(self), &rhs) } } // ['i64', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], []] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Sub<&Integer> for i64 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(self), rhs) } } // ['&i64', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}, 'deref'], ['ref']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Sub<Integer> for &i64 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), &rhs) } } // ['&i64', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', // {'convert': 'Integer'}, 'deref'], []] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Sub<&Integer> for &i64 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), rhs) } } // ['Integer', 'u64', 'Integer', 'Integer::subtract_assign', 'lhs', ['ref_mut'], // ['ref', {'convert': 'Integer'}]] impl Sub<u64> for Integer { type Output = Integer; fn sub(mut self, rhs: u64) -> Self::Output { Integer::subtract_assign(&mut self, &Integer::from(rhs)); self } } // ['Integer', '&u64', 'Integer', 'Integer::subtract_assign', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&u64> for Integer { type Output = Integer; fn sub(mut self, rhs: &u64) -> Self::Output { Integer::subtract_assign(&mut self, &Integer::from(*rhs)); self } } // ['&Integer', 'u64', 'Integer', 'Integer::subtract', 'no', [], ['ref', // {'convert': 'Integer'}]] impl Sub<u64> for &Integer { type Output = Integer; fn sub(self, rhs: u64) -> Self::Output { Integer::subtract(self, &Integer::from(rhs)) } } // ['&Integer', '&u64', 'Integer', 'Integer::subtract', 'no', [], ['ref', // {'convert': 'Integer'}, 'deref']] impl Sub<&u64> for &Integer { type Output = Integer; fn sub(self, rhs: &u64) -> Self::Output { Integer::subtract(self, &Integer::from(*rhs)) } } // ['u64', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], ['ref']] impl Sub<Integer> for u64 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(self), &rhs) } } // ['u64', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], []] impl Sub<&Integer> for u64 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(self), rhs) } } // ['&u64', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}, 'deref'], ['ref']] impl Sub<Integer> for &u64 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), &rhs) } } // ['&u64', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', // {'convert': 'Integer'}, 'deref'], []] impl Sub<&Integer> for &u64 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), rhs) } } // ['Integer', 'i128', 'Integer', 'Integer::subtract_assign', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}]] impl Sub<i128> for Integer { type Output = Integer; fn sub(mut self, rhs: i128) -> Self::Output { Integer::subtract_assign(&mut self, &Integer::from(rhs)); self } } // ['Integer', '&i128', 'Integer', 'Integer::subtract_assign', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&i128> for Integer { type Output = Integer; fn sub(mut self, rhs: &i128) -> Self::Output { Integer::subtract_assign(&mut self, &Integer::from(*rhs)); self } } // ['&Integer', 'i128', 'Integer', 'Integer::subtract', 'no', [], ['ref', // {'convert': 'Integer'}]] impl Sub<i128> for &Integer { type Output = Integer; fn sub(self, rhs: i128) -> Self::Output { Integer::subtract(self, &Integer::from(rhs)) } } // ['&Integer', '&i128', 'Integer', 'Integer::subtract', 'no', [], ['ref', // {'convert': 'Integer'}, 'deref']] impl Sub<&i128> for &Integer { type Output = Integer; fn sub(self, rhs: &i128) -> Self::Output { Integer::subtract(self, &Integer::from(*rhs)) } } // ['i128', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], ['ref']] impl Sub<Integer> for i128 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(self), &rhs) } } // ['i128', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', // {'convert': 'Integer'}], []] impl Sub<&Integer> for i128 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(self), rhs) } } // ['&i128', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', // {'convert': 'Integer'}, 'deref'], ['ref']] impl Sub<Integer> for &i128 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), &rhs) } } // ['&i128', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', // {'convert': 'Integer'}, 'deref'], []] impl Sub<&Integer> for &i128 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), rhs) } } // ['Integer', 'u128', 'Integer', 'Integer::subtract_assign', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}]] impl Sub<u128> for Integer { type Output = Integer; fn sub(mut self, rhs: u128) -> Self::Output { Integer::subtract_assign(&mut self, &Integer::from(rhs)); self } } // ['Integer', '&u128', 'Integer', 'Integer::subtract_assign', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&u128> for Integer { type Output = Integer; fn sub(mut self, rhs: &u128) -> Self::Output { Integer::subtract_assign(&mut self, &Integer::from(*rhs)); self } } // ['&Integer', 'u128', 'Integer', 'Integer::subtract', 'no', [], ['ref', // {'convert': 'Integer'}]] impl Sub<u128> for &Integer { type Output = Integer; fn sub(self, rhs: u128) -> Self::Output { Integer::subtract(self, &Integer::from(rhs)) } } // ['&Integer', '&u128', 'Integer', 'Integer::subtract', 'no', [], ['ref', // {'convert': 'Integer'}, 'deref']] impl Sub<&u128> for &Integer { type Output = Integer; fn sub(self, rhs: &u128) -> Self::Output { Integer::subtract(self, &Integer::from(*rhs)) } } // ['u128', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', {'convert': // 'Integer'}], ['ref']] impl Sub<Integer> for u128 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(self), &rhs) } } // ['u128', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', // {'convert': 'Integer'}], []] impl Sub<&Integer> for u128 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(self), rhs) } } // ['&u128', 'Integer', 'Integer', 'Integer::subtract', 'no', ['ref', // {'convert': 'Integer'}, 'deref'], ['ref']] impl Sub<Integer> for &u128 { type Output = Integer; fn sub(self, rhs: Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), &rhs) } } // ['&u128', '&Integer', 'Integer', 'Integer::subtract', 'no', ['ref', // {'convert': 'Integer'}, 'deref'], []] impl Sub<&Integer> for &u128 { type Output = Integer; fn sub(self, rhs: &Integer) -> Self::Output { Integer::subtract(&Integer::from(*self), rhs) } }
mod draw; use libary::polygon_generator; use libary::ghs; use libary::melkmanns; use libary::util::{Point}; fn main() { let polys1 = polygon_generator::gen_polygon(8); draw::draw_aw_stepbystep( &polys1, &[-1, -1]); } fn _draw_ghs_test (){ let a = Point{x:-1.0 ,y: 0.0}; let b = Point{x:-1.0 ,y:-1.0}; let c = Point{x:0.0 ,y:-2.0}; let d = Point{x:2.0 ,y: 0.0}; let e = Point{x:0.0 ,y: 0.0}; let f = Point{x:2.0 ,y: 0.0}; let g = Point{x:2.0 ,y: 1.0}; let _poly = vec!(a,b,c,d,e,f,g,a); let p = Point{x:0.0, y: 0.0}; let o = Point{x:3.0, y: 0.0}; let l = Point{x:-4.0, y: 1.0}; let y = Point{x:6.0, y: 2.0}; let s = Point{x:-8.0, y: 3.0}; let f = Point{x:-8.0, y: 0.0}; let poly2 = vec!(p,o,l,y,s, f, p); let a = Point{x:-1.0, y: 20.0}; let b = Point{x:0.0, y:20.0}; let c = Point{x:0.0, y: 21.0}; let d = Point{x:-1.0, y: 21.0}; let poly1 = vec!(a,b,c,d,a); let deque = melkmanns::algorithm_hull(&poly2); let deque1 = melkmanns::algorithm_hull1(&poly2); let polys = vec!(poly1, poly2); for p in deque { println! ("cc {}, {}", p.x, p.y); } for p in deque1 { println! ("c {}, {}", p.x, p.y); } // draw::draw_deque_static(&polys, true); } #[test] fn name() { let polys = polygon_generator::gen_polygon(10); let hull = melkmanns::algorithm_hull(&polys[0]); let s0 = hull.as_slices(); let mut p0 = s0.0.to_vec(); p0.extend_from_slice(s0.1); //p0.reverse(); let hull = melkmanns::algorithm_hull(&polys[1]); let s1 = hull.as_slices(); let mut p1 = s1.0.to_vec(); p1.extend_from_slice(s1.1); let (l_arr, u_arr) = ghs::generate_u_l (&p1); p1.reverse(); let (l_arr_rev, u_arr_rev) = ghs::generate_u_l (&p1); for i in 0..l_arr.len() { assert_eq! (l_arr[i].x, u_arr_rev[ u_arr_rev.len()-1-i ].x ); assert_eq! (l_arr[i].y, u_arr_rev[ u_arr_rev.len()-1-i ].y ); } }
use std::fs::read_to_string; use std::cmp::min; use std::collections::VecDeque; fn read_param(prog: &Vec<i32>, base: i32, pos: usize, i: usize) -> i32 { match prog[pos] / 10_i32.pow(i as u32 + 1) % 10 { 0 => prog[prog[pos + i] as usize], 1 => prog[pos + i], 2 => prog[(base + prog[pos + i]) as usize], _ => panic!("invalid parameter mode"), } } fn write_param(prog: &Vec<i32>, base: i32, pos: usize, i: usize) -> usize { match prog[pos] / 10_i32.pow(i as u32 + 1) % 10 { 0 => prog[pos + i] as usize, 2 => (base + prog[pos + i]) as usize, _ => panic!("invalid parameter mode"), } } fn run(mut prog: Vec<i32>) -> ((usize, usize), [[i32; 43]; 43]) { let (mut pos, mut base, mut dist, mut trail, mut coords, mut oxygen) = (0, 0, [[1400; 43]; 43], vec![], (21, 21), (0, 0)); dist[coords.1][coords.0] = 0; loop { let op = prog[pos]; if op == 99 { break; } match op % 100 { 1 => { let store = write_param(&prog, base, pos, 3); prog[store] = read_param(&prog, base, pos, 1) + read_param(&prog, base, pos, 2); pos += 4; }, 2 => { let store = write_param(&prog, base, pos, 3); prog[store] = read_param(&prog, base, pos, 1) * read_param(&prog, base, pos, 2); pos += 4; }, 3 => { let store = write_param(&prog, base, pos, 1); if coords.1 > 0 && dist[coords.1 - 1][coords.0] == 1400 { prog[store] = 1; trail.push((coords.0, coords.1, 2)); coords.1 -= 1; } else if coords.1 < 42 && dist[coords.1 + 1][coords.0] == 1400 { prog[store] = 2; trail.push((coords.0, coords.1, 1)); coords.1 += 1; } else if coords.0 > 0 && dist[coords.1][coords.0 - 1] == 1400 { prog[store] = 3; trail.push((coords.0, coords.1, 4)); coords.0 -= 1; } else if coords.0 < 42 && dist[coords.1][coords.0 + 1] == 1400 { prog[store] = 4; trail.push((coords.0, coords.1, 3)); coords.0 += 1; } else { let prev = trail.pop().unwrap(); coords = (prev.0, prev.1); prog[store] = prev.2; } pos += 2; }, 4 => { match read_param(&prog, base, pos, 1) { 0 => { dist[coords.1][coords.0] = -1; let prev = trail.pop().unwrap(); coords = (prev.0, prev.1); }, 1 => { if trail.is_empty() { break; } let prev = trail[trail.len() - 1]; dist[coords.1][coords.0] = min(dist[coords.1][coords.0], dist[prev.1][prev.0] + 1); }, 2 => { let prev = trail[trail.len() - 1]; dist[coords.1][coords.0] = min(dist[coords.1][coords.0], dist[prev.1][prev.0] + 1); oxygen = coords; }, _ => panic!("invalid status"), } pos += 2; }, 5 => pos = if read_param(&prog, base, pos, 1) != 0 { read_param(&prog, base, pos, 2) as usize } else { pos + 3 }, 6 => pos = if read_param(&prog, base, pos, 1) == 0 { read_param(&prog, base, pos, 2) as usize } else { pos + 3 }, 7 => { let store = write_param(&prog, base, pos, 3); prog[store] = if read_param(&prog, base, pos, 1) < read_param(&prog, base, pos, 2) { 1 } else { 0 }; pos += 4; }, 8 => { let store = write_param(&prog, base, pos, 3); prog[store] = if read_param(&prog, base, pos, 1) == read_param(&prog, base, pos, 2) { 1 } else { 0 }; pos += 4; }, 9 => { base += read_param(&prog, base, pos, 1); pos += 2; } _ => panic!("invalid opcode"), } } (oxygen, dist) } fn main() { let mut prog = read_to_string("in_15.txt").unwrap().trim_end().split(',').map(|int| int.parse::<i32>().unwrap()).collect::<Vec<_>>(); prog.resize(2700, 0); let ((oxygen, dist), mut bfs, mut visit, mut time) = (run(prog), VecDeque::new(), [[false; 43]; 43], 0); println!("Part A: {}", dist[oxygen.1][oxygen.0]); // 230 bfs.push_back((oxygen.0, oxygen.1, 0)); while !bfs.is_empty() { let node = bfs.pop_front().unwrap(); visit[node.1][node.0] = true; time = node.2; if node.1 > 0 && dist[node.1 - 1][node.0] >= 0 && !visit[node.1 - 1][node.0] { bfs.push_back((node.0, node.1 - 1, node.2 + 1)); } if node.1 < 42 && dist[node.1 + 1][node.0] >= 0 && !visit[node.1 + 1][node.0] { bfs.push_back((node.0, node.1 + 1, node.2 + 1)); } if node.0 > 0 && dist[node.1][node.0 - 1] >= 0 && !visit[node.1][node.0 - 1] { bfs.push_back((node.0 - 1, node.1, node.2 + 1)); } if node.0 < 42 && dist[node.1][node.0 + 1] >= 0 && !visit[node.1][node.0 + 1] { bfs.push_back((node.0 + 1, node.1, node.2 + 1)); } } println!("Part B: {}", time); // 288 }
use std::ops::{Mul, Add}; fn magic<T: Mul + Add + Copy>(par1: T, par2: T) -> (<T as Mul>::Output, <T as Add>::Output) { (par1 * par2, par1 + par2) } fn main() { println!("{:?}", magic(3, 4)); }
//! Cheesy way to easily wrap text in console colors. //! Example: //! ``` //! use phd::color; //! println!("{}Error: {}{}", color::Red, "Something broke.", color::Reset); //! ``` use std::{ fmt, sync::atomic::{AtomicBool, Ordering as AtomicOrdering}, }; /// Whether to show colors or not. /// Defaults to true. static SHOW_COLORS: AtomicBool = AtomicBool::new(true); /// Hide colors. pub fn hide_colors() { SHOW_COLORS.swap(false, AtomicOrdering::Relaxed); } /// Are we showing colors are not? pub fn showing_colors() -> bool { SHOW_COLORS.load(AtomicOrdering::Relaxed) } macro_rules! color { ($t:ident, $code:expr) => { #[allow(missing_docs)] pub struct $t; impl fmt::Display for $t { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if showing_colors() { write!(f, "\x1b[{}m", $code) } else { write!(f, "") } } } }; } color!(Black, 90); color!(Red, 91); color!(Green, 92); color!(Yellow, 93); color!(Blue, 94); color!(Magenta, 95); color!(Cyan, 96); color!(White, 97); color!(DarkBlack, 30); color!(DarkRed, 31); color!(DarkGreen, 32); color!(DarkYellow, 33); color!(DarkBlue, 34); color!(DarkMagenta, 35); color!(DarkCyan, 36); color!(DarkWhite, 37); color!(Reset, 0); color!(Bold, 1); color!(Underline, 4);
use nannou::prelude::*; fn main() { nannou::app(model).update(update).simple_window(view).run(); } struct Model {} fn model(_app: &App) -> Model { Model {} } fn update(_app: &App, _model: &mut Model, _update: Update) {} fn view(_app: &App, _model: &Model, frame: Frame) { frame.clear(PURPLE); }
// 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 carnelian::{ set_node_color, App, AppAssistant, Color, Label, Paint, ViewAssistant, ViewAssistantContext, ViewAssistantPtr, ViewKey, }; use failure::Error; use fidl::endpoints::{RequestStream, ServiceMarker}; use fidl_fuchsia_modular::{SessionShellMarker, SessionShellRequest, SessionShellRequestStream}; use fuchsia_async as fasync; use fuchsia_scenic::{Circle, Rectangle, SessionPtr, ShapeNode}; use fuchsia_syslog::{self as fx_log, fx_log_err, fx_log_info, fx_log_warn}; use futures::{TryFutureExt, TryStreamExt}; use std::env; const BACKGROUND_Z: f32 = 0.0; const LABEL_Z: f32 = BACKGROUND_Z - 0.01; const INDICATOR_Z: f32 = BACKGROUND_Z - 0.02; struct SessionShellAppAssistant; impl AppAssistant for SessionShellAppAssistant { fn setup(&mut self) -> Result<(), Error> { Ok(()) } fn create_view_assistant( &mut self, _: ViewKey, session: &SessionPtr, ) -> Result<ViewAssistantPtr, Error> { Ok(Box::new(SessionShellViewAssistant::new(session)?)) } fn outgoing_services_names(&self) -> Vec<&'static str> { [SessionShellMarker::NAME].to_vec() } fn handle_service_connection_request( &mut self, _service_name: &str, channel: fasync::Channel, ) -> Result<(), Error> { Self::spawn_session_shell_service(SessionShellRequestStream::from_channel(channel)); Ok(()) } } impl SessionShellAppAssistant { fn spawn_session_shell_service(stream: SessionShellRequestStream) { fx_log_info!("spawning a session shell implementation"); fasync::spawn_local( stream .map_ok(move |req| match req { SessionShellRequest::AttachView { view_id: _, view_holder_token: _, .. } => { fx_log_info!("SessionShell::AttachView()"); } SessionShellRequest::AttachView2 { view_id: _, view_holder_token: _, .. } => { fx_log_info!("SessionShell::AttachView2()"); } SessionShellRequest::DetachView { view_id: _, .. } => { fx_log_info!("SessionShell::DetachView()"); } }) .try_collect::<()>() .unwrap_or_else(|e| fx_log_err!("Session shell failed: {:?}", e)), ) } } struct SessionShellViewAssistant { background_node: ShapeNode, label: Label, indicator_node: ShapeNode, bg_color: Color, fg_color: Color, } impl SessionShellViewAssistant { fn new(session: &SessionPtr) -> Result<SessionShellViewAssistant, Error> { Ok(SessionShellViewAssistant { background_node: ShapeNode::new(session.clone()), label: Label::new(&session, "Hello, world!")?, indicator_node: ShapeNode::new(session.clone()), fg_color: Color::from_hash_code("#00FF41")?, bg_color: Color::from_hash_code("#0D0208")?, }) } } impl ViewAssistant for SessionShellViewAssistant { fn setup(&mut self, context: &ViewAssistantContext) -> Result<(), Error> { set_node_color( context.session(), &self.background_node, &Color::from_hash_code("#0D0208")?, ); context.root_node().add_child(&self.background_node); context.root_node().add_child(self.label.node()); set_node_color(context.session(), &self.indicator_node, &Color::from_hash_code("#00FF41")?); context.root_node().add_child(&self.indicator_node); Ok(()) } fn update(&mut self, context: &ViewAssistantContext) -> Result<(), Error> { if context.size.width == 0.0 && context.size.height == 0.0 { fx_log_warn!("skipping update – got drawing context of size 0x0"); return Ok(()); } // Position and size the background. let center_x = context.size.width * 0.5; let center_y = context.size.height * 0.5; self.background_node.set_shape(&Rectangle::new( context.session().clone(), context.size.width, context.size.height, )); self.background_node.set_translation(center_x, center_y, BACKGROUND_Z); // Update and position the label. let paint = Paint { fg: self.fg_color, bg: self.bg_color }; let min_dimension = context.size.width.min(context.size.height); let font_size = (min_dimension / 8.0).ceil().min(32.0); let top_y = font_size; self.label.update(font_size as u32, &paint)?; self.label.node().set_translation(center_x, top_y, LABEL_Z); // Update and position the indicator. let circle_radius = context.size.width.min(context.size.height) * 0.25; self.indicator_node.set_shape(&Circle::new(context.session().clone(), circle_radius)); self.indicator_node.set_translation(center_x, center_y, INDICATOR_Z); Ok(()) } } fn main() -> Result<(), Error> { env::set_var("RUST_BACKTRACE", "full"); fx_log::init_with_tags(&["voila_test_session_shell"])?; fx_log::set_severity(fx_log::levels::INFO); let assistant = SessionShellAppAssistant {}; App::run(Box::new(assistant)) }
use actix_web::{get, post, web, Error, HttpResponse}; use deadpool_postgres::Pool; use juniper::http::graphiql::graphiql_source; use juniper::http::GraphQLRequest; use std::sync::Arc; use crate::graphql::{Context, Schema}; #[get("/graphql")] pub async fn get_graphql() -> HttpResponse { // Note! if you change this url please // change the post api point too let html = graphiql_source("/v1/graphql"); HttpResponse::Ok().content_type("text/html").body(html) } // Note! if you change this url please // change the graphiql_source url too #[post("/v1/graphql")] pub async fn post_graphql( pool: web::Data<Pool>, schema: web::Data<Arc<Schema>>, data: web::Json<GraphQLRequest>, ) -> Result<HttpResponse, Error> { // get pool reference // and pass it to context let ctx = Context { // get reference to inner object Pool db: pool.get_ref().to_owned(), }; // execute query and serialize response let res = web::block(move || { let res = data.execute(&schema, &ctx); Ok::<_, serde_json::error::Error>(serde_json::to_string(&res)?) }) .await .map_err(Error::from)?; // return OK result Ok( HttpResponse::Ok() .content_type("application/json") .body(res), ) }
#![warn(unused_imports)] use core::fmt; use core::mem::zeroed; use riscv::register::sstatus::{self, Sstatus, SPP::*}; // 中断处理过程中需要保存的上下文(Context)向量 // 在处理中断之前,必须要保存所有可能被修改的寄存器,并且在处理完成后恢复。 // 保存所有通用寄存器,sepc、scause 和 stval 这三个会被硬件自动写入的 CSR 寄存器,以及 sstatus (因为中断可能会涉及到权限的切换,以及中断的开关,这些都会修改 sstatus。) // scause 以及 stval 将不会放在 Context 而仅仅被看做一个临时的变量 // 为了状态的保存与恢复,我们可以先用栈上的一小段空间来把需要保存的全部通用寄存器和 CSR 寄存器保存在栈上,保存完之后在跳转到 Rust 编写的中断处理函数 /// ### `#[repr(C)]` 属性 /// 要求 struct 按照 C 语言的规则进行内存分布,否则 Rust 可能按照其他规则进行内存排布 #[repr(C)] // 和C语言保持一致 #[derive(Clone, Copy)] pub struct Context { pub x: [usize; 32], // 32 个通用寄存器 pub sstatus: Sstatus, // 具有许多状态位,控制全局中断使能等。 pub sepc: usize // Exception Program Counter, 用来记录触发中断的指令的地址。 } // status的标志位: // spp:中断前系统处于内核态(1)还是用户态(0) // sie:内核态是否允许中断。对用户态而言,无论 sie 取何值都开启中断. OS启动(初始化)时不能允许sie=1 // spie:中断前是否开中断(用户态中断时可能 sie 为 0) /// 创建一个用 0 初始化的 Context /// /// 这里使用 [`core::mem::zeroed()`] 来强行用全 0 初始化。 /// 因为在一些类型中,0 数值可能不合法(例如引用),所以 [`zeroed()`] 是 unsafe 的 impl Default for Context { fn default() -> Self { unsafe { zeroed() } } } #[allow(unused)] impl Context { /// 获取栈指针 pub fn sp(&self) -> usize { self.x[2] } /// 设置栈指针 pub fn set_sp(&mut self, value: usize) -> &mut Self { self.x[2] = value; self } /// 获取返回地址 pub fn ra(&self) -> usize { self.x[1] } /// 设置返回地址 pub fn set_ra(&mut self, value: usize) -> &mut Self { self.x[1] = value; self } /// 按照函数调用规则写入参数 /// /// 没有考虑一些特殊情况,例如超过 8 个参数,或 struct 空间展开 pub fn set_arguments(&mut self, arguments: &[usize]) -> &mut Self { assert!(arguments.len() <= 8); self.x[10..(10 + arguments.len())].copy_from_slice(arguments); self } /// 为线程构建初始 `Context` pub fn new( stack_top: usize, entry_point: usize, arguments: Option<&[usize]>, is_user: bool, ) -> Self { let mut context = Self::default(); // 设置栈顶指针 context.set_sp(stack_top); // 设置初始参数 if let Some(args) = arguments { context.set_arguments(args); } // 设置入口地址 context.sepc = entry_point; // 设置 sstatus context.sstatus = sstatus::read(); if is_user { context.sstatus.set_spp(User); } else { context.sstatus.set_spp(Supervisor); } // 这样设置 SPIE 位,使得替换 sstatus 后关闭中断, // 而在 sret 到用户线程时开启中断。详见 SPIE 和 SIE 的定义 context.sstatus.set_spie(true); context } } const REG_NAMES: [&str; 32] = [ "x0(zero)", "x1(ra)", "x2(sp)", "x3(gp)", "x4(tp)", "x5(t0)", "x6(t1)", "x7(t3)", "x8(fp/s0)", "x9(s1)", "x10(a0)", "x11(a1)", "x12(a2)", "x13(a3)", "x14(a4)", "x15(a5)", "x16(a6)", "x17(a7)", "x18(s2)", "x19(s3)", "x20(s4)", "x21(s5)", "x22(s6)", "x23(s7)", "x24(s8)", "x25(s9)", "x26(s10)", "x27(s11)", "x28(t3)", "x29(t4)", "x30(t5)", "x31(t6)", ]; // 加入Context的格式化输出 impl fmt::Debug for Context { // `f` 是一个缓冲区(buffer),此方法必须将格式化后的字符串写入其中 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, " {:?} (uie={}, sie={}, upie={}, spie={})\n", self.sstatus, self.sstatus.uie(), self.sstatus.sie(), self.sstatus.upie(), self.sstatus.spie() )?; write!(f, " sepc = 0x{:016x}\n", self.sepc)?; for i in 0..32 { write!(f, " {:9} = 0x{:016x}\n", REG_NAMES[i], self.x[i])?; } Ok(()) } }
use std::borrow::{Borrow, Cow}; use std::collections::HashMap; use futures::future::Future; use log::{debug, info}; use rusoto_core::credential::AwsCredentials; use rusoto_core::param::{Params, ServiceParams}; use rusoto_core::signature::{SignedRequest, SignedRequestPayload}; use rusoto_core::Region; use rusoto_core::{DefaultCredentialsProvider, ProvideAwsCredentials}; use serde::{Deserialize, Serialize}; // Reference: // https://github.com/hashicorp/vault/blob/d12547c7faa9c216d1411827bc16606535cb3e61/builtin/credential/aws/path_login.go#L1640 const IAM_SERVER_ID_HEADER: &str = "X-Vault-AWS-IAM-Server-ID"; /// Returns AWS credentials according to the behaviour documented /// [here](https://rusoto.github.io/rusoto/rusoto_credential/struct.ChainProvider.html). pub fn credentials() -> Result<AwsCredentials, crate::Error> { let provider = DefaultCredentialsProvider::new()?; Ok(provider.credentials().wait()?) } /// Payload for use when authenticating with Vault AWS Authentication using the IAM method /// /// See [Vault's Documentation](https://www.vaultproject.io/docs/auth/aws.html#iam-auth-method) /// for more information. #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] pub struct VaultAwsAuthIamPayload { /// HTTP method used in the signed request. Currently only `POST` is supported pub iam_http_request_method: String, /// Base64-encoded HTTP URL used in the signed request pub iam_request_url: String, /// Base64-encoded body of the signed request pub iam_request_body: String, /// Headers of the signed request pub iam_request_headers: HashMap<String, Vec<String>>, } impl VaultAwsAuthIamPayload { /// Create a payload for use with Vault AWS Authentication using the IAM method /// /// If you do not provide a `region`, we will use a the "global" AWS STS endpoint. /// /// If the Vault AWS Authentication method has the /// [`iam_server_id_header_value`](https://www.vaultproject.io/api/auth/aws/index.html#iam_server_id_header_value) /// configured, you *must* provide the configured value in the `header_value` parameter. #[allow(clippy::needless_pass_by_value)] pub fn new<S, R>( credentials: &AwsCredentials, header_value: Option<S>, region: Option<R>, ) -> Self where S: AsRef<str>, R: Borrow<Region>, { info!("Building Login Payload for AWS authentication to Vault"); let region = region .as_ref() .map(|r| Cow::Borrowed(r.borrow())) .unwrap_or_else(|| { debug!("No region provided: using \"global\" us-east-1 endpoint."); Cow::Owned(Region::Custom { name: "us-east-1".to_string(), endpoint: "sts.amazonaws.com".to_string(), }) }); // Code below is referenced from the code for // https://rusoto.github.io/rusoto/rusoto_sts/trait.Sts.html#tymethod.get_caller_identity // Additional processing for Vault is referenced from Vault CLI's source code: // https://github.com/hashicorp/vault/blob/master/builtin/credential/aws/cli.go let mut request = SignedRequest::new("POST", "sts", &region, "/"); let mut params = Params::new(); params.put("Action", "GetCallerIdentity"); params.put("Version", "2011-06-15"); request.set_payload(Some( serde_urlencoded::to_string(&params).unwrap().into_bytes(), )); request.set_content_type("application/x-www-form-urlencoded".to_owned()); if let Some(value) = header_value { if !value.as_ref().is_empty() { request.add_header(IAM_SERVER_ID_HEADER, value.as_ref()); } } request.sign_with_plus(credentials, true); let uri = format!( "{}://{}{}", request.scheme(), request.hostname(), request.canonical_path() ); let payload = match request.payload { Some(SignedRequestPayload::Buffer(ref buffer)) => base64::encode(buffer), _ => unreachable!("Payload was set above"), }; // We need to convert the headers from bytes back into Strings... let headers = request .headers .iter() .map(|(k, v)| { let values = v .iter() .map(|v| unsafe { String::from_utf8_unchecked(v.to_vec()) }) .collect(); (k.to_string(), values) }) .collect(); let result = Self { iam_http_request_method: "POST".to_string(), iam_request_url: base64::encode(&uri), iam_request_body: payload, iam_request_headers: headers, }; debug!("AWS Payload: {:#?}", result); result } } #[cfg(test)] pub(crate) mod tests { use super::*; // mock_key, mock_secret pub(crate) fn credentials() -> Result<AwsCredentials, crate::Error> { let provider = rusoto_mock::MockCredentialsProvider; Ok(provider.credentials().wait()?) } pub(crate) fn vault_aws_iam_payload( header_value: Option<&str>, region: Option<Region>, ) -> Result<VaultAwsAuthIamPayload, crate::Error> { let cred = credentials()?; Ok(VaultAwsAuthIamPayload::new(&cred, header_value, region)) } #[test] fn vault_aws_iam_payload_has_expected_values() -> Result<(), crate::Error> { let region = Region::UsEast1; let payload = vault_aws_iam_payload(Some("vault.example.com"), Some(region.clone()))?; assert_eq!(payload.iam_http_request_method, "POST"); assert_eq!( payload.iam_request_url, base64::encode(&format!("https://sts.{}.amazonaws.com/", region.name())) ); assert_eq!( payload.iam_request_body, base64::encode("Action=GetCallerIdentity&Version=2011-06-15") ); assert!(payload.iam_request_headers.contains_key("authorization")); assert_eq!( payload .iam_request_headers .get(&IAM_SERVER_ID_HEADER.to_lowercase()), Some(&vec!["vault.example.com".to_string()]) ); Ok(()) } #[test] fn vault_aws_iam_payload_has_default_global_region() -> Result<(), crate::Error> { let payload = vault_aws_iam_payload(Some("vault.example.com"), None)?; assert_eq!(payload.iam_http_request_method, "POST"); assert_eq!( payload.iam_request_url, base64::encode("https://sts.amazonaws.com/") ); assert_eq!( payload.iam_request_body, base64::encode("Action=GetCallerIdentity&Version=2011-06-15") ); assert!(payload.iam_request_headers.contains_key("authorization")); assert_eq!( payload .iam_request_headers .get(&IAM_SERVER_ID_HEADER.to_lowercase()), Some(&vec!["vault.example.com".to_string()]) ); Ok(()) } }
#![feature(test)] extern crate test; use test::Bencher; macro_rules! bench { ($name:ident) => { #[bench] #[allow(non_snake_case)] fn $name(b: &mut Bencher) { let src = include_str!(concat!( "../tests/data/", stringify!($name), ".gcode" )); b.bytes = src.len() as u64; b.iter(|| gcode::parse(src).count()); } }; } bench!(program_1); bench!(program_2); bench!(program_3); bench!(PI_octcat);
use rust_client::models; #[allow(unused_imports)] use serde_json::Value; use std::collections::HashMap; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Metadata { #[serde(rename = "operation", skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(rename = "cloud_provider", skip_serializing_if = "Option::is_none")] pub cloud_provider: Option<models::CloudProviderInfo>, #[serde(rename = "labels", skip_serializing_if = "Option::is_none")] pub labels: Option<HashMap<String, String>>, } impl Metadata { pub fn new() -> Self { Metadata { operation: None, cloud_provider: None, labels: None, } } pub fn get_operation(&self) -> String { self.operation.clone().unwrap() } pub fn set_operation(&mut self, op: String) { self.operation = Some(op); } pub fn get_cloud_provider(&self) -> models::CloudProviderInfo { self.cloud_provider.clone().unwrap() } } #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct Config { #[serde(rename = "kind", skip_serializing_if = "Option::is_none")] pub kind: Option<String>, #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option<Metadata>, #[serde(rename = "spec", skip_serializing_if = "Option::is_none")] pub spec: Option<Value>, } impl Config { pub fn new() -> Self { Config { kind: None, metadata: Some(Metadata::new()), spec: None, } } pub fn get_kind(&self) -> String { self.kind.clone().unwrap() } pub fn get_metadata(&self) -> Metadata { self.metadata.clone().unwrap() } pub fn muted_with_metadata(&mut self, meta: Metadata) -> &mut Self { self.metadata = Some(meta); self } pub fn get_spec(&self) -> Value { self.spec.clone().unwrap() } pub fn validate(&mut self) { let k = self.get_kind(); let op = self.get_metadata().get_operation(); if k.is_empty() || op.is_empty() { panic!("input error, config not supported!") } if op != "create" && op != "delete" { panic!("input error, operation {:?} not supported!", op) } if k != "ComputeResource" && k != "StorageResource" && k != "NetworkResource" { panic!("unspported resource kind {}", k); } } }
use crate::prelude::*; use super::super::c_char_to_vkstring; use std::os::raw::c_char; #[repr(C)] #[derive(Debug)] pub struct VkDisplayPropertiesKHR { pub display: VkDisplayKHR, pub displayName: *const c_char, pub physicalDimensions: VkExtent2D, pub physicalResolution: VkExtent2D, pub supportedTransforms: VkSurfaceTransformFlagBitsKHR, pub planeReorderPossible: VkBool32, pub persistentContent: VkBool32, } impl VkDisplayPropertiesKHR { pub fn display_name(&self) -> Result<VkString, String> { c_char_to_vkstring(self.displayName) } }
use std::ffi::CString; use std::io; use std::os; use std::os::raw::{c_char, c_int}; use firefly_util::fs; extern "C" { #[cfg(windows)] pub fn LLVMFireflyLink( argc: c_int, argv: *const *const c_char, stdout: os::windows::io::RawHandle, stderr: os::windows::io::RawHandle, ) -> bool; #[cfg(not(windows))] pub fn LLVMFireflyLink( argc: c_int, argv: *const *const c_char, stdout: os::unix::io::RawFd, stderr: os::unix::io::RawFd, ) -> bool; } /// Invoke the statically linked `lld` linker with the given arguments. /// /// NOTE: Assumes that the first value of the argument vector contains the /// program name which informs lld which flavor of linker is being run. pub fn link(argv: &[CString]) -> Result<(), ()> { // Acquire exclusive access to stdout/stderr for the linker let stdout = io::stdout(); let stderr = io::stderr(); let stdout_lock = stdout.lock(); let stderr_lock = stderr.lock(); let stdout_fd = fs::get_file_descriptor(&stdout_lock); let stderr_fd = fs::get_file_descriptor(&stderr_lock); let argc = argv.len(); let mut c_argv = Vec::with_capacity(argc); for arg in argv { c_argv.push(arg.as_ptr()); } let is_ok = unsafe { LLVMFireflyLink(argc as c_int, c_argv.as_ptr(), stdout_fd, stderr_fd) }; if is_ok { Ok(()) } else { Err(()) } }
/*! An application that load different interfaces using the partial feature. All partials are represented as the same generic struct. Requires the following features: `cargo run --example partials_generic_d --features "listbox frame combobox"` */ extern crate native_windows_gui as nwg; extern crate native_windows_derive as nwd; use std::fmt::Display; use std::cell::RefCell; use nwd::{NwgUi, NwgPartial}; use nwg::NativeUi; #[derive(NwgUi)] pub struct PartialGenericDemo<T1: Display + Default + 'static, T2, T3> where T2: Display + Default + 'static, T3: Display + Default + 'static { #[nwg_control(size: (500, 200), position: (300, 300), title: "Many generic UI", flags: "WINDOW|VISIBLE")] #[nwg_events(OnWindowClose: [PartialGenericDemo::exit])] window: nwg::Window, #[nwg_control(collection: vec![data.f1_ui.title, data.f2_ui.title, data.f3_ui.title], size: (180, 180), position: (10, 10))] #[nwg_events(OnListBoxSelect: [PartialGenericDemo::change_interface])] menu: nwg::ListBox<&'static str>, #[nwg_control(size: (290, 180), position: (200, 10))] frame1: nwg::Frame, #[nwg_control(size: (290, 180), position: (200, 10), flags: "BORDER")] frame2: nwg::Frame, #[nwg_control(size: (290, 180), position: (200, 10), flags: "BORDER")] frame3: nwg::Frame, #[nwg_partial(parent: frame1)] #[nwg_events((save_btn, OnButtonClick): [PartialGenericDemo::show(SELF, CTRL)])] f1_ui: GenericFrameUi<T1>, #[nwg_partial(parent: frame2)] #[nwg_events((save_btn, OnButtonClick): [PartialGenericDemo::show(SELF, CTRL)])] f2_ui: GenericFrameUi<T2>, #[nwg_partial(parent: frame3)] #[nwg_events((save_btn, OnButtonClick): [PartialGenericDemo::show(SELF, CTRL)])] f3_ui: GenericFrameUi<T3>, } impl<T1, T2, T3> PartialGenericDemo<T1, T2, T3> where T1: Display + Default, T2: Display + Default, T3: Display + Default { fn change_interface(&self) { let frames = [&self.frame1, &self.frame2, &self.frame3]; frames.iter().for_each(|f| f.set_visible(false)); let selected_frame = match self.menu.selection() { Some(x) => frames[x], None => frames[0], }; selected_frame.set_visible(true); } fn show<T: Display + Default>(&self, frame: &GenericFrameUi<T>) { let message = match frame.combobox.selection() { Some(v) => format!("'{}' is our choice from '{}' frame", frame.combobox.collection()[v], frame.title), None => "Please choose something".to_owned(), }; nwg::simple_message("Show message", &message); } fn exit(&self) { nwg::stop_thread_dispatch(); } } #[derive(NwgPartial)] pub struct GenericFrameUi<T: Display + Default + 'static> { title: &'static str, #[nwg_control(size: (270, 40), position: (10, 10), text: data.text)] l: nwg::Label, text: &'static str, #[nwg_control(collection: data.combo_items.borrow_mut().take().unwrap_or_default(), selected_index: Some(0), size: (270, 40), position: (10, 60))] combobox: nwg::ComboBox<T>, combo_items: RefCell<Option<Vec<T>>>, #[nwg_control(text: "Show", size: (270, 40), position: (10, 110))] save_btn: nwg::Button, } fn main() { nwg::init().expect("Failed to init Native Windows GUI"); nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font"); let demo = PartialGenericDemo { window: Default::default(), menu: Default::default(), frame1: Default::default(), frame2: Default::default(), frame3: Default::default(), f1_ui: GenericFrameUi { title: "Numbers", text: "i32 numbers", combo_items: Some(vec![1, 2, 3]).into(), l: Default::default(), combobox: Default::default(), save_btn: Default::default(), }, f2_ui: GenericFrameUi { title: "Strings", text: "Static strings", combo_items: Some(vec!["String 1", "String 2", "String 3"]).into(), l: Default::default(), combobox: Default::default(), save_btn: Default::default(), }, f3_ui: GenericFrameUi { title: "Booleans", text: "Bool values", combo_items: Some(vec![true, false, false]).into(), l: Default::default(), combobox: Default::default(), save_btn: Default::default(), }, }; let _ui = PartialGenericDemo::build_ui(demo).expect("Failed to build UI"); nwg::dispatch_thread_events(); }
fn func() -> i32 { // if as a expression and as implicit return statement if true { if false { 1 } else { 2 } } else { 3 } } fn main() { // let a: i32 = 0; let a: i32 = 1; // let a: i32 = 3; // let a: i32 = 4; if a == 0 { printf("Is zero\n"); } else if a % 2 == 0 { printf("Is even\n"); } else { if a == 1 { printf("Is one\n"); } printf("Is odd\n"); } // if as a expression in assignment a = if true { 1 } else { 2 }; func(); }
// Copyright Jeron A. Lau 2017 - 2018. // Dual-licensed under either the MIT License or the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) //! Render graphics to a computer or phone screen, and get input. Great for //! both video games and apps! //! //! NOTICE: This crate has been consolidated into the [ADI](https://crates.io/crates/adi) crate.
//! Contains `Scanner`, an on-demand producer of tokens. use crate::runtime::Line; use crate::{ErrorKind, PiccoloError, Token, TokenKind}; use std::collections::VecDeque; /// Converts a piccolo source into a stream of [`Token`]. /// /// Operates in a scan-on-demand fashion. A consumer of tokens calls the [`next_token`] /// method, which produces the next token from the source. A consumer can also /// look ahead in the stream using [`peek_token`], which produces tokens as /// required. /// /// [`Token`]s internally are stored in a [`VecDeque`] which increases in size if /// the scanner produces new tokens when [`next_token`] is called. In Piccolo, the /// parser calls `peek_token` with a maximum of 2, so the size of the token buffer /// is never larger than 2 tokens. /// /// [`VecDeque`]: https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html /// [`Token`]: ../struct.Token.html /// [`next_token`]: ./struct.Scanner.html#method.next_token /// [`peek_token`]: ./struct.Scanner.html#method.peek_token #[derive(Debug)] pub struct Scanner<'a> { source: &'a [u8], tokens: VecDeque<Token<'a>>, start: usize, current: usize, line: Line, } impl<'a> Scanner<'a> { /// Create a new `Scanner` from a source. pub fn new(source: &'a str) -> Self { Scanner { source: source.as_bytes(), tokens: VecDeque::new(), start: 0, current: 0, line: 1, } } #[cfg(feature = "pc-debug")] pub(super) fn scan_all(mut self) -> Result<Vec<Token<'a>>, PiccoloError> { while self.next()?.kind != TokenKind::Eof {} Ok(self.tokens.drain(0..).collect()) } /// Produce the next token, moving it out of the scanner. Returns [`TokenKind::Eof`] /// if the scanner is at the end of the source. /// /// [`TokenKind::Eof`]: ../struct.TokenKind.html pub fn next_token(&mut self) -> Result<Token<'a>, PiccoloError> { if self.tokens.is_empty() { self.next()?; } Ok(self.tokens.pop_front().unwrap()) } /// Looks ahead in the token stream, generating tokens if they do not exist. pub fn peek_token<'b>(&'b mut self, idx: usize) -> Result<&'b Token<'a>, PiccoloError> { if self.tokens.is_empty() { self.next()?; } while self.tokens.len() <= idx { self.next()?; } Ok(&self.tokens[idx]) } fn slurp_whitespace(&mut self) { while self.peek_char() == b'#' || is_whitespace(self.peek_char()) { if self.peek_char() == b'#' { while !self.is_at_end() && self.peek_char() != b'\n' { self.advance_char(); } } while !self.is_at_end() && is_whitespace(self.peek_char()) { if self.advance_char() == b'\n' { self.line += 1; } } } } fn next<'b>(&'b mut self) -> Result<&'b Token<'a>, PiccoloError> { self.slurp_whitespace(); if self.is_at_end() { self.add_token(TokenKind::Eof)?; return Ok(&self.tokens[self.tokens.len() - 1]); } self.start = self.current; let tk = match self.advance_char() { b'[' => TokenKind::LeftBracket, b']' => TokenKind::RightBracket, b'(' => TokenKind::LeftParen, b')' => TokenKind::RightParen, b',' => TokenKind::Comma, b'+' => { if self.peek_char() == b'=' { self.advance_char(); TokenKind::PlusAssign } else { TokenKind::Plus } } b'-' => { if self.peek_char() == b'=' { self.advance_char(); TokenKind::MinusAssign } else { TokenKind::Minus } } b'*' => { if self.peek_char() == b'=' { self.advance_char(); TokenKind::MultiplyAssign } else { TokenKind::Multiply } } b'/' => { if self.peek_char() == b'=' { self.advance_char(); TokenKind::DivideAssign } else { TokenKind::Divide } } b'^' => { if self.peek_char() == b'=' { self.advance_char(); TokenKind::BitwiseXorAssign } else { TokenKind::BitwiseXor } } b'%' => { if self.peek_char() == b'=' { self.advance_char(); TokenKind::ModuloAssign } else { TokenKind::Modulo } } b'@' => TokenKind::At, b'$' => TokenKind::Dollar, b'\'' => TokenKind::SingleQuote, b'`' => TokenKind::Grave, b'{' => TokenKind::LeftBrace, b'}' => TokenKind::RightBrace, b':' => TokenKind::Colon, b'?' => TokenKind::Question, b'\\' => TokenKind::Backslash, b';' => TokenKind::Semicolon, b'~' => TokenKind::Tilde, b'&' => { if self.peek_char() == b'&' { self.advance_char(); TokenKind::LogicalAnd } else if self.peek_char() == b'=' { self.advance_char(); TokenKind::BitwiseAndAssign } else { TokenKind::BitwiseAnd } } b'|' => { if self.peek_char() == b'|' { self.advance_char(); TokenKind::LogicalOr } else if self.peek_char() == b'=' { self.advance_char(); TokenKind::BitwiseOrAssign } else { TokenKind::BitwiseOr } } b'.' => { if self.peek_char() == b'.' { self.advance_char(); if self.peek_char() == b'.' { self.advance_char(); TokenKind::InclusiveRange } else { TokenKind::ExclusiveRange } } else { TokenKind::Period } } b'!' => { if self.peek_char() == b'=' { self.advance_char(); TokenKind::NotEqual } else { TokenKind::Not } } b'=' => { if self.peek_char() == b'=' { self.advance_char(); TokenKind::Equal } else if self.peek_char() == b':' { self.advance_char(); TokenKind::Declare } else { TokenKind::Assign } } b'>' => { if self.peek_char() == b'=' { self.advance_char(); TokenKind::GreaterEqual } else if self.peek_char() == b'>' { self.advance_char(); if self.peek_char() == b'=' { self.advance_char(); TokenKind::ShiftRightAssign } else { TokenKind::ShiftRight } } else { TokenKind::Greater } } b'<' => { if self.peek_char() == b'=' { self.advance_char(); TokenKind::LessEqual } else if self.peek_char() == b'<' { self.advance_char(); if self.peek_char() == b'=' { self.advance_char(); TokenKind::ShiftLeftAssign } else { TokenKind::ShiftLeft } } else { TokenKind::Less } } b'"' => self.scan_string()?, c => { if is_digit(c) { self.scan_number()? } else if is_whitespace(c) { panic!("found whitespace where there shouldn't be any"); } else { self.identifier_or_keyword()? } } }; self.add_token(tk)?; Ok(&self.tokens[self.tokens.len() - 1]) } fn identifier_or_keyword(&mut self) -> Result<TokenKind, PiccoloError> { while !is_non_identifier(self.peek_char()) { self.advance_char(); } if let Some(tk) = into_keyword(self.lexeme()?) { Ok(tk) } else { Ok(TokenKind::Identifier) } } fn scan_string(&mut self) -> Result<TokenKind, PiccoloError> { let line_start = self.line; while self.peek_char() != b'"' && !self.is_at_end() { if self.peek_char() == b'\n' { self.line += 1; } if self.peek_char() == b'\\' { self.advance_char(); self.line += 1; } self.advance_char(); } if self.is_at_end() { Err(PiccoloError::new(ErrorKind::UnterminatedString).line(line_start)) } else { self.advance_char(); Ok(TokenKind::String) } } fn scan_number(&mut self) -> Result<TokenKind, PiccoloError> { while is_digit(self.peek_char()) { self.advance_char(); } if self.peek_char() == b'.' { let range = self.lookahead_char(1) == b'.'; while self.current != 0 && is_digit(self.peek_char()) { self.reverse_char(); } if !range { return self.scan_float(); } } let value = self.lexeme()?; if let Ok(i) = value.parse::<i64>() { Ok(TokenKind::Integer(i)) } else { Err(PiccoloError::new(ErrorKind::InvalidNumberLiteral { literal: value.to_owned(), }) .line(self.line)) } } fn scan_float(&mut self) -> Result<TokenKind, PiccoloError> { while is_digit(self.peek_char()) { self.advance_char(); } if self.peek_char() == b'.' { self.advance_char(); while is_digit(self.peek_char()) { self.advance_char(); } } let value = self.lexeme()?; if let Ok(f) = value.parse::<f64>() { Ok(TokenKind::Double(f)) } else { Err(PiccoloError::new(ErrorKind::InvalidNumberLiteral { literal: value.to_owned(), }) .line(self.line)) } } fn add_token(&mut self, kind: TokenKind) -> Result<(), PiccoloError> { self.tokens .push_back(Token::new(kind, self.lexeme()?, self.line)); Ok(()) } fn lexeme(&self) -> Result<&'a str, PiccoloError> { Ok(core::str::from_utf8( &self.source[self.start..self.current], )?) } fn is_at_end(&self) -> bool { self.current >= self.source.len() } fn advance_char(&mut self) -> u8 { self.current += 1; self.source[self.current - 1] } fn reverse_char(&mut self) -> u8 { self.current -= 1; self.source[self.current] } fn peek_char(&mut self) -> u8 { if self.is_at_end() { b'\0' } else { self.source[self.current] } } fn lookahead_char(&mut self, n: usize) -> u8 { if self.is_at_end() || self.current + n >= self.source.len() { b'\0' } else { self.source[self.current + n] } } } fn into_keyword(s: &str) -> Option<TokenKind> { match s { "do" => Some(TokenKind::Do), "end" => Some(TokenKind::End), "fn" => Some(TokenKind::Fn), "if" => Some(TokenKind::If), "else" => Some(TokenKind::Else), "while" => Some(TokenKind::While), "for" => Some(TokenKind::For), "in" => Some(TokenKind::In), "data" => Some(TokenKind::Data), "let" => Some(TokenKind::Let), "is" => Some(TokenKind::Is), "me" => Some(TokenKind::Me), "new" => Some(TokenKind::New), "err" => Some(TokenKind::Err), "break" => Some(TokenKind::Break), "continue" => Some(TokenKind::Continue), "retn" => Some(TokenKind::Retn), "assert" => Some(TokenKind::Assert), "true" => Some(TokenKind::True), "false" => Some(TokenKind::False), "nil" => Some(TokenKind::Nil), _ => None, } } fn is_digit(c: u8) -> bool { (b'0'..=b'9').contains(&c) } pub(super) fn is_whitespace(c: u8) -> bool { c == 0x09 // tab || c == 0x0A // line feed || c == 0x0B // line tab || c == 0x0C // form feed || c == 0x0D // carriage return || c == 0x20 // space // || c == 0x85 // next line !! represented in utf-8 as C2 85 // || c == 0xA0 // no-break space !! represented in utf-8 as C2 A0 } fn is_non_identifier(c: u8) -> bool { is_whitespace(c) || c == 0x00 || c == b'#' || c == b'[' || c == b']' || c == b'(' || c == b')' || c == b',' || c == b'-' || c == b'+' || c == b'*' || c == b'/' || c == b'^' || c == b'%' || c == b'&' || c == b'|' || c == b'.' || c == b'!' || c == b':' || c == b'=' || c == b'>' || c == b'<' || c == b'"' || c == b'@' || c == b'$' || c == b'\'' || c == b'`' || c == b'{' || c == b'}' || c == b':' || c == b'?' || c == b'\\' || c == b';' || c == b'~' } #[cfg(test)] mod test { use super::{Scanner, Token, TokenKind}; #[test] fn multi_char_ops() { let src = "++=--=//=**=%%="; let mut scanner = Scanner::new(src); while scanner.next().unwrap().kind != TokenKind::Eof {} let tokens: Vec<TokenKind> = scanner.tokens.drain(0..).map(|t| t.kind).collect(); assert_eq!( tokens, &[ TokenKind::Plus, TokenKind::PlusAssign, TokenKind::Minus, TokenKind::MinusAssign, TokenKind::Divide, TokenKind::DivideAssign, TokenKind::Multiply, TokenKind::MultiplyAssign, TokenKind::Modulo, TokenKind::ModuloAssign, TokenKind::Eof, ], ); let src = "&&&=&|||=|"; let mut scanner = Scanner::new(src); while scanner.next().unwrap().kind != TokenKind::Eof {} let tokens: Vec<TokenKind> = scanner.tokens.drain(0..).map(|t| t.kind).collect(); assert_eq!( tokens, &[ TokenKind::LogicalAnd, TokenKind::BitwiseAndAssign, TokenKind::BitwiseAnd, TokenKind::LogicalOr, TokenKind::BitwiseOrAssign, TokenKind::BitwiseOr, TokenKind::Eof, ] ); let src = "<<<=<<==<"; let mut scanner = Scanner::new(src); while scanner.next().unwrap().kind != TokenKind::Eof {} let tokens: Vec<TokenKind> = scanner.tokens.drain(0..).map(|t| t.kind).collect(); assert_eq!( tokens, &[ TokenKind::ShiftLeft, TokenKind::LessEqual, TokenKind::ShiftLeftAssign, TokenKind::Assign, TokenKind::Less, TokenKind::Eof ] ); } #[test] fn scanner() { let src = "a = 3\nio.prln(a)\n"; let mut scanner = Scanner::new(src); assert_eq!( scanner.peek_token(0).unwrap(), &Token::new(TokenKind::Identifier, "a", 1) ); assert_eq!( scanner.peek_token(1).unwrap(), &Token::new(TokenKind::Assign, "=", 1) ); assert_eq!( scanner.next_token().unwrap(), Token::new(TokenKind::Identifier, "a", 1) ); assert_eq!( scanner.peek_token(0).unwrap(), &Token::new(TokenKind::Assign, "=", 1) ); assert_eq!( scanner.next_token().unwrap(), Token::new(TokenKind::Assign, "=", 1) ); assert_eq!( scanner.next_token().unwrap(), Token::new(TokenKind::Integer(3), "3", 1) ); assert_eq!( scanner.next_token().unwrap(), Token::new(TokenKind::Identifier, "io", 2) ); assert_eq!( scanner.next_token().unwrap(), Token::new(TokenKind::Period, ".", 2) ); assert_eq!( scanner.next_token().unwrap(), Token::new(TokenKind::Identifier, "prln", 2) ); } #[test] fn scanner2() { // 0 1 2 3 45 678 let src = "a = 3\nio.prln(a)\n"; let mut scanner = Scanner::new(src); assert_eq!( scanner.peek_token(0).unwrap(), &Token::new(TokenKind::Identifier, "a", 1) ); assert_eq!( scanner.peek_token(1).unwrap(), &Token::new(TokenKind::Assign, "=", 1) ); assert_eq!( scanner.peek_token(0).unwrap(), &Token::new(TokenKind::Identifier, "a", 1) ); assert_eq!( scanner.peek_token(6).unwrap(), &Token::new(TokenKind::LeftParen, "(", 2) ); assert_eq!( scanner.peek_token(8).unwrap(), &Token::new(TokenKind::RightParen, ")", 2) ); assert_eq!( scanner.next_token().unwrap(), Token::new(TokenKind::Identifier, "a", 1) ); assert_eq!( scanner.next_token().unwrap(), Token::new(TokenKind::Assign, "=", 1) ); assert_eq!( scanner.next_token().unwrap(), Token::new(TokenKind::Integer(3), "3", 1) ); assert_eq!( scanner.next_token().unwrap(), Token::new(TokenKind::Identifier, "io", 2) ); } }
use diesel::Connection as ConnectionTrait; use diesel::sqlite::SqliteConnection; use dotenv::dotenv; use rocket::http::Status; use rocket::request::{Request, FromRequest, Outcome}; use rocket::outcome::Outcome::*; use r2d2::{Pool, PooledConnection as R2PooledConnection, GetTimeout, Config}; use r2d2_diesel::ConnectionManager; use std::env; pub type Connection = SqliteConnection; pub type ConnectionPool = Pool<ConnectionManager<Connection>>; pub type PooledConnection = R2PooledConnection<ConnectionManager<Connection>>; lazy_static! { pub static ref DATABASE_URL: String = { dotenv().ok(); env::var("DATABASE_URL").expect("DATABASE_URL must be set") }; pub static ref CONNECTION_POOL: ConnectionPool = create_connection_pool(); } /// Establish a database connection /// /// Normally it's preferable to get one out of the connection pool, /// but this works to create one from scratch. pub fn establish_connection() -> Connection { Connection::establish(&DATABASE_URL).expect(&format!("Error connecting to {}", *DATABASE_URL)) } pub fn create_connection_pool() -> ConnectionPool { let config = Config::default(); let manager = ConnectionManager::<Connection>::new(DATABASE_URL.clone()); Pool::new(config, manager).expect("Failed to create pool.") } /// Database connection request guard /// /// Add this guard to your request to get a connection to the DB pub struct DB(PooledConnection); impl DB { pub fn conn(&self) -> &Connection { &*self.0 } } impl<'a, 'r> FromRequest<'a, 'r> for DB { type Error = GetTimeout; fn from_request(_: &'a Request<'r>) -> Outcome<Self, Self::Error> { match CONNECTION_POOL.get() { Ok(conn) => Success(DB(conn)), Err(e) => Failure((Status::InternalServerError, e)), } } }
use std::env; use mio::net::{TcpListener, TcpStream}; fn main() { let args: Vec<String> = env::args().collect(); match args[1].as_str() { "server" => { let addr = args[2].parse().unwrap(); println!("listen on {}", addr); let _listener = TcpListener::bind(&addr).unwrap(); loop { } } "client" => { let addr = args[2].parse().unwrap(); println!("connect to {}", addr); let _stream = TcpStream::connect(&addr).unwrap(); loop { } } _ => { panic!("{} is not expected", args[1]); } } }
use svg::node::element::path::{Command, Data}; use svg::node::element::tag::Path; use svg::parser::Event; pub fn parse_path(path_to_svg_file: &str) -> Vec<Point2> { let mut content = String::new(); let mut points = vec![]; let path = vec![]; let mut current_point = pt2(0.0, 0.0); for event in svg::open(path_to_svg_file, &mut content).unwrap() { match event { Event::Tag(Path, _, attributes) => { let data = attributes.get("d").unwrap(); let data = Data::parse(data).unwrap(); for command in data.iter() { match command { &Command::Move(position, params) => { dbg!(position, params); } &Command::Line(..) => { println!("Line!"); dbg!(position, params); } _ => {} } } } _ => {} } } }
use rocket::Request; #[catch(404)] pub fn view(req: &Request) -> String { format!("Sorry, '{}' is not a valid path.", req.uri()) }
use super::component_prelude::*; pub struct Player { pub settings: PlayerSettings, pub acceleration: Vector, pub max_velocity: (Option<f32>, Option<f32>), pub jump_data: Option<PlayerJumpSettings>, pub used_dash: bool, } impl Player { pub fn set_normal_speed(&mut self) { self.acceleration = self.settings.normal_speed.acceleration.clone(); self.max_velocity = self.settings.normal_speed.max_velocity.clone(); } pub fn set_run_speed(&mut self) { self.acceleration = self.settings.run_speed.acceleration.clone(); self.max_velocity = self.settings.run_speed.max_velocity.clone(); } } impl Component for Player { type Storage = HashMapStorage<Self>; } impl From<PlayerSettings> for Player { fn from(settings: PlayerSettings) -> Player { Player { acceleration: settings.normal_speed.acceleration.clone(), max_velocity: settings.normal_speed.max_velocity.clone(), jump_data: None, used_dash: false, settings: settings, } } }
#[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::IRQENABLE { #[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 DES_IRQENABLE_M_CONTEX_INR { bits: bool, } impl DES_IRQENABLE_M_CONTEX_INR { #[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 _DES_IRQENABLE_M_CONTEX_INW<'a> { w: &'a mut W, } impl<'a> _DES_IRQENABLE_M_CONTEX_INW<'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 DES_IRQENABLE_M_DATA_INR { bits: bool, } impl DES_IRQENABLE_M_DATA_INR { #[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 _DES_IRQENABLE_M_DATA_INW<'a> { w: &'a mut W, } impl<'a> _DES_IRQENABLE_M_DATA_INW<'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 DES_IRQENABLE_M_DATA_OUTR { bits: bool, } impl DES_IRQENABLE_M_DATA_OUTR { #[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 _DES_IRQENABLE_M_DATA_OUTW<'a> { w: &'a mut W, } impl<'a> _DES_IRQENABLE_M_DATA_OUTW<'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 } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - If this bit is set to 1 the context interrupt is enabled"] #[inline(always)] pub fn des_irqenable_m_contex_in(&self) -> DES_IRQENABLE_M_CONTEX_INR { let bits = ((self.bits >> 0) & 1) != 0; DES_IRQENABLE_M_CONTEX_INR { bits } } #[doc = "Bit 1 - If this bit is set to 1 the data input interrupt is enabled"] #[inline(always)] pub fn des_irqenable_m_data_in(&self) -> DES_IRQENABLE_M_DATA_INR { let bits = ((self.bits >> 1) & 1) != 0; DES_IRQENABLE_M_DATA_INR { bits } } #[doc = "Bit 2 - If this bit is set to 1 the data output interrupt is enabled"] #[inline(always)] pub fn des_irqenable_m_data_out(&self) -> DES_IRQENABLE_M_DATA_OUTR { let bits = ((self.bits >> 2) & 1) != 0; DES_IRQENABLE_M_DATA_OUTR { 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 - If this bit is set to 1 the context interrupt is enabled"] #[inline(always)] pub fn des_irqenable_m_contex_in(&mut self) -> _DES_IRQENABLE_M_CONTEX_INW { _DES_IRQENABLE_M_CONTEX_INW { w: self } } #[doc = "Bit 1 - If this bit is set to 1 the data input interrupt is enabled"] #[inline(always)] pub fn des_irqenable_m_data_in(&mut self) -> _DES_IRQENABLE_M_DATA_INW { _DES_IRQENABLE_M_DATA_INW { w: self } } #[doc = "Bit 2 - If this bit is set to 1 the data output interrupt is enabled"] #[inline(always)] pub fn des_irqenable_m_data_out(&mut self) -> _DES_IRQENABLE_M_DATA_OUTW { _DES_IRQENABLE_M_DATA_OUTW { w: self } } }
pub mod create_sorted_array_through_instructions; pub mod find_the_most_competitive_subsequence; pub mod rotate_image;
use std::io::{Cursor, Write}; use byteorder::{NetworkEndian, WriteBytesExt}; use super::Packet; impl Packet { pub fn encode(&self) -> Vec<u8> { assert!(self.server_name.as_deref().map(|x| x.len()).unwrap_or(0) < 64); assert!(self.boot_file_name.as_deref().map(|x| x.len()).unwrap_or(0) < 128); let mut cursor = { let mut buf = Vec::<u8>::new(); buf.resize(236, 0); Cursor::new(buf) }; cursor.write_u8(self.bootp_message_type.into()).unwrap(); cursor.write_u8(self.htype).unwrap(); cursor.write_u8(self.hlen).unwrap(); cursor.write_u8(self.hops).unwrap(); cursor.write_u32::<NetworkEndian>(self.xid).unwrap(); cursor.write_u16::<NetworkEndian>(self.secs).unwrap(); cursor.write_u16::<NetworkEndian>(self.flags).unwrap(); cursor.write_all(&self.ciaddr.octets()[..]).unwrap(); cursor.write_all(&self.yiaddr.octets()[..]).unwrap(); cursor.write_all(&self.siaddr.octets()[..]).unwrap(); cursor.write_all(&self.giaddr.octets()[..]).unwrap(); cursor.write_all(&self.mac.get_raw()[..]).unwrap(); if let Some(server_name) = self.server_name.as_deref() { cursor.write_all(server_name.as_bytes()).unwrap(); cursor.set_position(cursor.position() + 64 - server_name.len() as u64); } else { cursor.set_position(cursor.position() + 64); } if let Some(boot_file_name) = self.boot_file_name.as_deref() { cursor.write_all(boot_file_name.as_bytes()).unwrap(); cursor.set_position(cursor.position() + 128 - boot_file_name.len() as u64); } else { cursor.set_position(cursor.position() + 128); } assert_eq!(cursor.position(), 236); if !self.options.is_empty() { cursor.write_all(&[99, 130, 83, 99]).unwrap(); for (&tag, option) in self.options.iter() { cursor.write_u8(tag).unwrap(); cursor.write_u8(option.len()).unwrap(); option.encode(&mut cursor).unwrap(); } cursor.write_u8(0xff).unwrap(); } cursor.into_inner() } }
extern crate aoc; use std::cmp; use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::prelude::*; use std::io::{self, BufReader}; use std::str::FromStr; #[derive(Debug, Hash, Eq, PartialEq)] struct Point { x: u16, y: u16, } impl FromStr for Point { type Err = io::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let index = s .find(',') .ok_or(io::Error::from(io::ErrorKind::InvalidData))?; let x = s[0..index] .parse::<u16>() .map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?;; let y = s[index + 2..] .parse::<u16>() .map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?;; Ok(Point { x, y }) } } fn main() -> Result<(), io::Error> { let arg = aoc::get_cmdline_arg()?; let points = BufReader::new(File::open(arg)?) .lines() .map(|line| line.unwrap()) .map(|line| line.parse::<Point>().unwrap()) .collect::<Vec<_>>(); let (max_x, max_y) = max_size(&points); let mut id_map = HashMap::new(); let mut board = vec![vec![0i32; max_x]; max_y]; for (i, p) in points.iter().enumerate() { let id = (i + 1) as i32; board[p.y as usize][p.x as usize] = id; id_map.insert(p, id); } let mut dist_map = HashMap::new(); for y in 0..max_y { for x in 0..max_x { let p = Point { x: x as u16, y: y as u16, }; if id_map.contains_key(&p) { continue; } dist_map.clear(); for (point, id) in &id_map { let d = m_dist(&p, point); dist_map.insert(id, d); } let (id, d) = dist_map .iter() .min_by(|(_, d0), (_, d1)| d0.cmp(d1)) .unwrap(); match dist_map .iter() .filter(|(i, _)| *i != id) .find(|(_, dd)| d == *dd) { Some(_) => {} None => board[y][x] = **id, } } } // for i in 0..board.len() { // for j in 0..board[i].len() { // let v = board[i][j]; // if v == 0 { // print!("{:2}", " ."); // } else { // print!("{:2}", v); // } // } // println!(); // } let mut infinites = HashSet::new(); for i in board[0].iter() { if *i != 0 { infinites.insert(*i); } } for i in board[board.len() - 1].iter() { if *i != 0 { infinites.insert(*i); } } for i in 0..board.len() { let v = *board[i].first().unwrap(); if v != 0 { infinites.insert(v); } let v = *board[i].last().unwrap(); if v != 0 { infinites.insert(v); } } let mut areas = vec![]; for (_, v) in id_map.iter().filter(|(_, id)| !infinites.contains(id)) { let mut count = 0; for row in &board { count += row.iter().filter(|a| *a == v).count(); } areas.push(count); } println!("part 1: {}", areas.iter().max().unwrap()); let mut size = 0; for y in 0..max_y { for x in 0..max_x { let p = Point { x: x as u16, y: y as u16, }; let mut sum = 0; for (point, _) in &id_map { sum += m_dist(&p, point); } if sum < 10_000 { size += 1; } } } println!("part 2: {}", size); Ok(()) } fn max_size<'a>(points: &'a Vec<Point>) -> (usize, usize) { let mut max_x = 0usize; let mut max_y = 0usize; for Point { x, y } in points { max_x = cmp::max(*x as usize, max_x); max_y = cmp::max(*y as usize, max_y); } (max_x + 1, max_y + 1) } fn m_dist<'a>(a: &'a Point, b: &'a Point) -> u16 { (a.x as i16 - b.x as i16).abs() as u16 + (a.y as i16 - b.y as i16).abs() as u16 }
//! # merkle_tree_rust //! `merkle_tree_rust` contains methods to generate string list and the //! merkle tree upon the list use sha2::{Sha256, Digest}; use rand::{thread_rng, Rng}; use rand::distributions::Alphanumeric; use anyhow::Result; // Redundant, but more readable use anyhow::*; use rayon::prelude::*; /// Parse the 2nd element of the list input, then convert it to an integer. /// /// Return an integer parsed. /// /// # Examples /// /// ``` /// let args = vec!["a".into(), "100".into()]; /// let tx_num = merkle_tree_rust::parse_args(&args).unwrap(); /// assert_eq!(tx_num, 100); /// ``` /// /// # Errors /// An error is returned under the following conditions: /// * If the list input has less than 2 elements /// * If the 2nd element of the list input is not an integer /// * If the 2nd element of the list input is an integer, but its value is less than 1 /// * If the 2nd element of the list input is an integer, but greater than the OS' memory locating ability pub fn parse_args(args: &[String]) -> Result<usize, String> { if args.len() < 2 { return Err("At least one argument is expected, command example:\n\ncargo run 100".into()); } let tx_num = match args[1].parse::<usize>() { Ok(i) => { if i < 1 { return Err("The argument must be an interger greater than 0!".into()); } else { i } }, Err(e) => { let e_msg = format!("{}, command example:\n\ncargo run 100", e.to_string()); return Err(e_msg); } }; Ok(tx_num) } /// Generate a string list whose size is ```tx_num```. /// /// Return a string list. /// /// # Examples /// /// ``` /// let txs = merkle_tree_rust::make_txs(99); /// assert_eq!(99, txs.len()); /// ``` pub fn make_txs(tx_num: usize) -> Vec<Bit256> { let mut txs = Vec::new(); for _i in 0..tx_num { let rand_string: String = thread_rng() .sample_iter(&Alphanumeric) .take(64) .collect(); txs.push(rand_string); } txs } /// The type for the result of sha256 hash. pub type Bit256 = String; fn get_sha256(input: impl AsRef<[u8]> ) -> Bit256{ let mut hasher = Sha256::new(); hasher.update(input); hex::encode(hasher.finalize().as_slice()) // ? sha2 crate have method to convert result to hex string? } // if the number of hashed is odd and greater than 1, duplicate the last hash fn dupl_last_odd_list(mut hashes: Vec<Bit256>) -> Vec<Bit256> { if hashes.len() > 1 && hashes.len() % 2 == 1 { hashes.push(hashes.last().unwrap().into()); } hashes } /// Create a merkle tree from a string list by the following steps: /// * Hash each element of the string list, make a new list from the hashing results. /// * Take the new list as level 0 of the merkle tree /// * Iterate each 2 elements of the top level of the merkle tree, calculate hashing results from each 2 elements, push the hashing results as "latest" top level of the merkle tree /// * If the top level of the merkle tree has more than one elements, repeat previous step. Otherwise, return the merkle tree. /// /// Return the merkle tree created. /// /// # Multi-threaded /// The multi-threaded attemp by rayon's threadpool is not successful. Although hashing process is running in new thread, the whole algorithm runs sequentially. It would be easier to achive if the ```pool.install``` returns something like ```JoinHandle``` or ```Future```. /// /// The single threaded version [here](https://github.com/livelybug/merkle-tree-rust/commit/97395e8055ae3f82350102142e97c6a31e4c823b), the main part of algorithm looks like: /// ```txt /// for idx in (0..hashes.len()).step_by(2) { /// let combined_str = format!("{}{}", hashes[idx], hashes[idx + 1]); /// let res = get_sha256(&combined_str); /// hashes_computed.push(res); /// } /// ``` /// /// # Examples /// /// ``` /// let mut txs = Vec::new(); /// txs.push("a".into()); txs.push("b".into()); txs.push("c".into()); /// txs.push("d".into()); /// let merkle_tree = merkle_tree_rust::make_merkle_tree(&txs).unwrap(); /// assert_eq!("58c89d709329eb37285837b042ab6ff72c7c8f74de0446b091b6a0131c102cfd", merkle_tree.last().unwrap()[0]); /// ``` /// /// # Errors /// An error is returned if the string list input is empty pub fn make_merkle_tree(txs: &Vec<String>) -> Result<Vec<Vec<Bit256>>>{ // Cannot accept empty tx list if txs.len() == 0 { return Err(anyhow!("Creating a merkle tree, string list input cannot be empty!")); } // Compute the hashes of input txs let mut tx_hashes= Vec::new(); for tx in txs { tx_hashes.push(get_sha256(tx)); } // The hashes of input tx as level 0 of merkel tree let mut merkle_tree = Vec::new(); // if the number of hashed is odd and greater than 1, duplicate the last hash tx_hashes = dupl_last_odd_list(tx_hashes); merkle_tree.push(tx_hashes); // if the last level has more than 1 element, continue calculating while merkle_tree.last().unwrap().len() > 1 { let hashes = merkle_tree.last().unwrap(); // println!("current level = {}, hashes = {:?}", merkle_tree.len() - 1, hashes); let mut hashes_computed: Vec<String> = (0..(hashes.len() / 2)).into_par_iter().map( |idx| { // combine each pair of hashes to generate new hash let combined_str = format!("{}{}", hashes[idx * 2], hashes[idx * 2 + 1]); get_sha256(&combined_str) }).collect(); // if the number of hashes is odd and greater than 1, duplicate the last hash hashes_computed = dupl_last_odd_list(hashes_computed); merkle_tree.push(hashes_computed); } println!("last level = {}, root hash = {:?}", merkle_tree.len() - 1, merkle_tree.last().unwrap()); Ok(merkle_tree) } /// The type for element of merkle proof. #[derive(Debug)] pub struct ProofElement(i8, Bit256); fn _get_merkle_proof(merkle_tree: &Vec<Vec<String>>, hash: &Bit256, mut proof: Vec<ProofElement>, mut level: usize) -> Vec<ProofElement> { if merkle_tree[level].len() == 1 { return proof; } // Get the index of current hash from the current level of merkle tree let index = merkle_tree[level].iter().position(|r| r.eq(hash) ).unwrap(); let tmp_idx = (index % 2) as i8; // If ```temp_idx``` is 1, the proof element tuple is ```(0, merkle_tree[level][index - 1].clone())``` // If ```temp_idx``` is 0, the proof element tuple is ```(1, merkle_tree[level][index + 1].clone())``` let paired_hash = merkle_tree[level][index + 1 - (tmp_idx * 2) as usize].clone(); proof.push(ProofElement((tmp_idx - 1) * -1, paired_hash)); // Get the hash linked to current hash and paired hash let _hash = merkle_tree[level + 1][(index - tmp_idx as usize) / 2].clone(); if level + 1 >= merkle_tree.len() { panic!("Something wrong when getting merkle proof, index out of boundary!") } level = level + 1; _get_merkle_proof(merkle_tree, &_hash, proof, level) } /// Create a merkle proof from a string list and one element of the list. /// * The merkle proof is a tuple list. Each tuple is (pos, paired_hash), where ```pos``` is the position of the paired_hash in the pair to be hashed. ```pos``` is 0 if the paired_hash is on the left of the pair. /// /// Return the tuple list. /// /// # Errors /// An error is returned if the string list input is empty pub fn get_merkle_proof(txs: &Vec<String>, tx: &str) -> Result<Vec<ProofElement>> { // Cannot accept empty tx list if txs.len() == 0 { return Err(anyhow!("Creating a merkle proof, string list input cannot be empty!")); } // The transaction to be verified through the merkle proof must be existing in the original transaction list of the merkle tree if !txs.contains(&tx.into()) { return Err(anyhow!("Creating a merkle proof of a transaction, but the transaction is not found in the transaction list!")); } // Get merkle tree let merkle_tree = make_merkle_tree(txs)?; // Create merkle proof - a tuple list let mut proof: Vec<ProofElement> = Vec::new(); let hash = get_sha256(tx); proof = _get_merkle_proof(&merkle_tree, &hash, proof, 0); Ok(proof) } /// Calculate along the merkle proof input to get the merkle root. /// /// Return the merkle root. /// /// # Examples /// /// ``` /// let mut txs = Vec::new(); /// txs.push("a".into()); txs.push("b".into()); txs.push("c".into()); /// txs.push("d".into()); /// let proof = merkle_tree_rust::get_merkle_proof(&txs, "a").unwrap(); /// let root = merkle_tree_rust::get_root_by_proof("a", &proof).unwrap(); /// assert_eq!("58c89d709329eb37285837b042ab6ff72c7c8f74de0446b091b6a0131c102cfd" ,root); /// ``` /// /// # Errors /// An error is returned if the merkle proof input is empty. pub fn get_root_by_proof(tx: &str, proof: &Vec<ProofElement>) -> Result<Bit256> { // Cannot accept empty tx list if proof.len() == 0 { return Err(anyhow!("Calculate along the merkle proof to get the merkle root, the merkle proof cannot be empty!")); } // hash the tx let mut hash = get_sha256(tx); // verify through the proof for pe in proof { let concat = if pe.0 == 0 { format!("{}{}", pe.1, hash) } else { format!("{}{}",hash, pe.1) }; hash = get_sha256(concat); } Ok(hash) } #[cfg(test)] mod tests { use super::*; #[test] fn test_args_parser() { let args = vec!["a".into(), "b".into()]; let err = parse_args(&args).unwrap_err(); assert_eq!("invalid digit found in string, command example:\n\ncargo run 100", err); let args = vec!["a".into(), "0".into()]; let err = parse_args(&args).unwrap_err(); assert_eq!("The argument must be an interger greater than 0!", err); let args = vec!["a".into()]; let err = parse_args(&args).unwrap_err(); assert_eq!("At least one argument is expected, command example:\n\ncargo run 100", err); let args = vec!["a".into(), "100".into()]; let tx_num = parse_args(&args).unwrap(); assert_eq!(100, tx_num); } #[test] fn test_txs_gen() { let txs = make_txs(99); assert_eq!(99, txs.len()); } #[test] fn test_merkle_tree() { let mut txs = Vec::new(); let err = make_merkle_tree(&txs).unwrap_err(); assert_eq!("Creating a merkle tree, string list input cannot be empty!", err.to_string()); txs.push("a".into()); txs.push("b".into()); txs.push("c".into()); txs.push("d".into()); let merkle_tree = make_merkle_tree(&txs).unwrap(); assert_eq!("58c89d709329eb37285837b042ab6ff72c7c8f74de0446b091b6a0131c102cfd", merkle_tree.last().unwrap()[0]); txs.push("e".into()); let merkle_tree = make_merkle_tree(&txs).unwrap(); assert_eq!("3615e586768e706351e326736e446554c49123d0e24c169d3ecf9b791a82636b", merkle_tree.last().unwrap()[0]); txs.push("f".into()); txs.push("g".into()); let merkle_tree = make_merkle_tree(&txs).unwrap(); assert_eq!("61198f165d0f10dc1cd3f688bb7c5cf9f0d6f892532a6ebd984fb9b6bb124dd8", merkle_tree.last().unwrap()[0]); } #[test] fn test_get_merkle_proof() { let mut txs = Vec::new(); let err = get_merkle_proof(&txs, "a").unwrap_err(); assert_eq!("Creating a merkle proof, string list input cannot be empty!", err.to_string()); txs.push("a".into()); txs.push("b".into()); txs.push("c".into()); txs.push("d".into()); let err = get_merkle_proof(&txs, "z").unwrap_err(); assert_eq!("Creating a merkle proof of a transaction, but the transaction is not found in the transaction list!", err.to_string()); let proof = get_merkle_proof(&txs, "a").unwrap(); let root = get_root_by_proof("a", &proof).unwrap(); assert_eq!("58c89d709329eb37285837b042ab6ff72c7c8f74de0446b091b6a0131c102cfd" ,root); txs.push("e".into()); let proof = get_merkle_proof(&txs, "e").unwrap(); let root = get_root_by_proof("e", &proof).unwrap(); assert_eq!("3615e586768e706351e326736e446554c49123d0e24c169d3ecf9b791a82636b", root); txs.push("f".into()); txs.push("g".into()); let proof = get_merkle_proof(&txs, "f").unwrap(); let root = get_root_by_proof("f", &proof).unwrap(); assert_eq!("61198f165d0f10dc1cd3f688bb7c5cf9f0d6f892532a6ebd984fb9b6bb124dd8", root); } }
// 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 { crate::utils, fuchsia_zircon::sys as zx, wlan_mlme::{ buffer::{BufferProvider, InBuf, OutBuf}, client, common::{frame_len, mac, sequence::SequenceManager}, device, }, }; #[no_mangle] pub extern "C" fn mlme_write_open_auth_frame( provider: BufferProvider, seq_mgr: &mut SequenceManager, bssid: &[u8; 6], client_addr: &[u8; 6], out_buf: &mut OutBuf, ) -> i32 { let frame_len = frame_len!(mac::MgmtHdr, mac::AuthHdr); let buf_result = provider.get_buffer(frame_len); let mut buf = unwrap_or_bail!(buf_result, zx::ZX_ERR_NO_RESOURCES); let write_result = client::write_open_auth_frame(&mut buf[..], *bssid, *client_addr, seq_mgr); let written_bytes = unwrap_or_bail!(write_result, zx::ZX_ERR_INTERNAL).written_bytes(); *out_buf = OutBuf::from(buf, written_bytes); zx::ZX_OK } #[no_mangle] pub extern "C" fn mlme_write_keep_alive_resp_frame( provider: BufferProvider, seq_mgr: &mut SequenceManager, bssid: &[u8; 6], client_addr: &[u8; 6], out_buf: &mut OutBuf, ) -> i32 { let frame_len = frame_len!(mac::DataHdr); let buf_result = provider.get_buffer(frame_len); let mut buf = unwrap_or_bail!(buf_result, zx::ZX_ERR_NO_RESOURCES); let write_result = client::write_keep_alive_resp_frame(&mut buf[..], *bssid, *client_addr, seq_mgr); let written_bytes = unwrap_or_bail!(write_result, zx::ZX_ERR_INTERNAL).written_bytes(); *out_buf = OutBuf::from(buf, written_bytes); zx::ZX_OK } #[no_mangle] pub extern "C" fn mlme_deliver_eth_frame( device: &device::Device, provider: &BufferProvider, dst_addr: &[u8; 6], src_addr: &[u8; 6], protocol_id: u16, payload: *const u8, payload_len: usize, ) -> i32 { let frame_len = frame_len!(mac::EthernetIIHdr) + payload_len; let buf_result = provider.get_buffer(frame_len); let mut buf = unwrap_or_bail!(buf_result, zx::ZX_ERR_NO_RESOURCES); // It is safe here because `payload_slice` does not outlive `payload`. let payload_slice = unsafe { utils::as_slice(payload, payload_len) }; let write_result = client::write_eth_frame(&mut buf[..], *dst_addr, *src_addr, protocol_id, payload_slice); let written_bytes = unwrap_or_bail!(write_result, zx::ZX_ERR_IO_OVERRUN).written_bytes(); device.deliver_ethernet(&buf.as_slice()[0..written_bytes]) }
use std::hash::Hasher; /// A hasher optimized for hashing component type IDs. #[derive(Default)] pub struct ComponentTypeIdHasher(u64); impl Hasher for ComponentTypeIdHasher { #[inline] fn finish(&self) -> u64 { self.0 } #[inline] fn write_u64(&mut self, seed: u64) { // This must only be used to hash one value. debug_assert_eq!(self.0, 0); self.0 = seed; } fn write(&mut self, _bytes: &[u8]) { // This should not be called, only write_u64. unimplemented!() } } /// A hasher optimized for hashing types that are represented as a u64. #[derive(Default)] pub struct U64Hasher(u64); impl Hasher for U64Hasher { #[inline] fn finish(&self) -> u64 { self.0 } #[inline] fn write_u64(&mut self, seed: u64) { // This must only be used to hash one value. debug_assert_eq!(self.0, 0); let max_prime = 11_400_714_819_323_198_549u64; self.0 = max_prime.wrapping_mul(seed); } fn write(&mut self, _bytes: &[u8]) { // This should not be called, only write_u64. unimplemented!() } } #[test] fn hasher() { fn verify<T: 'static + ?Sized>() { use core::{any::TypeId, hash::Hash}; let mut hasher = ComponentTypeIdHasher::default(); let type_id = TypeId::of::<T>(); type_id.hash(&mut hasher); assert_eq!(hasher.finish(), unsafe { core::mem::transmute::<TypeId, u64>(type_id) }); } verify::<usize>(); verify::<()>(); verify::<str>(); verify::<&'static str>(); verify::<[u8; 20]>(); }