text
stringlengths
8
4.13M
use nalgebra::Scalar; use crate::{Pose, PoseCovariance}; pub trait OdometryModel<N: Scalar + Copy> { fn update_all(&self, dt: N, poses: &mut [Pose<N>]) { for pose in poses { *pose = self.update_one(dt, *pose); } } fn update_one(&self, dt: N, pose: Pose<N>) -> Pose<N>; } pub trait GaussianOdometryModel<N: Scalar> { fn mean(&self, dt: N, curr: Pose<N>) -> Pose<N>; fn covariance(&self, dt: N, curr: Pose<N>) -> PoseCovariance<N>; } pub trait LinearOdometryModel<N> {} impl<LOM: LinearOdometryModel<N>, N: Scalar + Copy> OdometryModel<N> for LOM { fn update_one(&self, _dt: N, _pose: Pose<N>) -> Pose<N> { // self.mean(dt, pose) + randomly_sample_from_gaussian todo!(); } fn update_all(&self, _dt: N, _poses: &mut [Pose<N>]) { // let mean = self.mean(dt, pose); // mean + randomly_sample_alot_from_gaussian todo!(); } } pub struct UnscentedOdometryModel<M> { model: M, } impl<N, M> GaussianOdometryModel<N> for UnscentedOdometryModel<M> where N: Scalar + Copy, M: OdometryModel<N>, { fn mean(&self, _dt: N, _curr: Pose<N>) -> Pose<N> { todo!() } fn covariance(&self, _dt: N, _curr: Pose<N>) -> PoseCovariance<N> { todo!() } }
use crate::impl_pnext; use crate::prelude::*; use std::os::raw::c_void; use std::ptr; #[repr(C)] #[derive(Debug)] pub struct VkBufferCreateInfo { pub sType: VkStructureType, pub pNext: *const c_void, pub flags: VkBufferCreateFlagBits, pub size: VkDeviceSize, pub usage: VkBufferUsageFlagBits, pub sharingMode: VkSharingMode, pub queueFamilyIndexCount: u32, pub pQueueFamilyIndices: *const u32, } impl VkBufferCreateInfo { pub fn new<'a, 'b: 'a, T, U>( flags: T, size: VkDeviceSize, usage: U, sharing_mode: VkSharingMode, queue_family_indices: &'b [u32], ) -> VkBufferCreateInfo where T: Into<VkBufferCreateFlagBits>, U: Into<VkBufferUsageFlagBits>, { VkBufferCreateInfo { sType: VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, pNext: ptr::null(), flags: flags.into(), size, usage: usage.into(), sharingMode: sharing_mode, queueFamilyIndexCount: queue_family_indices.len() as u32, pQueueFamilyIndices: queue_family_indices.as_ptr(), } } } impl_pnext!(VkBufferCreateInfo, VkBufferDeviceAddressCreateInfoEXT); impl_pnext!(VkBufferCreateInfo, VkExternalMemoryBufferCreateInfo);
use crate::{ event::{self, Event}, sinks::util::{ encoding::{EncodingConfig, EncodingConfiguration}, StreamSink, }, topology::config::{DataType, SinkConfig, SinkContext, SinkDescription}, }; use async_trait::async_trait; use futures::pin_mut; use futures::stream::{Stream, StreamExt}; use futures01::future; use serde::{Deserialize, Serialize}; use tokio::io::{self, AsyncWriteExt}; use super::streaming_sink::{self, StreamingSink}; #[derive(Deserialize, Serialize, Debug)] #[serde(rename_all = "lowercase")] pub enum Target { Stdout, Stderr, } impl Default for Target { fn default() -> Self { Target::Stdout } } #[derive(Deserialize, Serialize, Debug)] #[serde(deny_unknown_fields)] pub struct ConsoleSinkConfig { #[serde(default)] pub target: Target, pub encoding: EncodingConfig<Encoding>, } #[derive(Deserialize, Serialize, Debug, Eq, PartialEq, Clone)] #[serde(rename_all = "snake_case")] pub enum Encoding { Text, Json, } inventory::submit! { SinkDescription::new_without_default::<ConsoleSinkConfig>("console") } #[typetag::serde(name = "console")] impl SinkConfig for ConsoleSinkConfig { fn build(&self, cx: SinkContext) -> crate::Result<(super::RouterSink, super::Healthcheck)> { let encoding = self.encoding.clone(); let output: Box<dyn io::AsyncWrite + Send + Sync + Unpin> = match self.target { Target::Stdout => Box::new(io::stdout()), Target::Stderr => Box::new(io::stderr()), }; let sink = WriterSink { output, encoding }; let sink = streaming_sink::compat::adapt_to_topology(sink); let sink = StreamSink::new(sink, cx.acker()); Ok((Box::new(sink), Box::new(future::ok(())))) } fn input_type(&self) -> DataType { DataType::Any } fn sink_type(&self) -> &'static str { "console" } } fn encode_event( mut event: Event, encoding: &EncodingConfig<Encoding>, ) -> Result<String, serde_json::Error> { encoding.apply_rules(&mut event); match event { Event::Log(log) => match encoding.codec() { Encoding::Json => serde_json::to_string(&log), Encoding::Text => { let s = log .get(&event::log_schema().message_key()) .map(|v| v.to_string_lossy()) .unwrap_or_else(|| "".into()); Ok(s) } }, Event::Metric(metric) => serde_json::to_string(&metric), } } async fn write_event_to_output( mut output: impl io::AsyncWrite + Send + Unpin, event: Event, encoding: &EncodingConfig<Encoding>, ) -> Result<(), std::io::Error> { let mut buf = encode_event(event, encoding).map_err(|err| io::Error::new(io::ErrorKind::Other, err))?; buf.push('\n'); output.write_all(buf.as_bytes()).await?; Ok(()) } struct WriterSink { output: Box<dyn io::AsyncWrite + Send + Sync + Unpin>, encoding: EncodingConfig<Encoding>, } #[async_trait] impl StreamingSink for WriterSink { async fn run( &mut self, input: impl Stream<Item = Event> + Send + Sync + 'static, ) -> crate::Result<()> { let output = &mut self.output; pin_mut!(output); pin_mut!(input); while let Some(event) = input.next().await { write_event_to_output(&mut output, event, &self.encoding).await? } Ok(()) } } #[cfg(test)] mod test { use super::{encode_event, Encoding, EncodingConfig}; use crate::event::metric::{Metric, MetricKind, MetricValue}; use crate::event::{Event, Value}; use chrono::{offset::TimeZone, Utc}; #[test] fn encodes_raw_logs() { let event = Event::from("foo"); assert_eq!( "foo", encode_event(event, &EncodingConfig::from(Encoding::Text)).unwrap() ); } #[test] fn encodes_log_events() { let mut event = Event::new_empty_log(); let log = event.as_mut_log(); log.insert("x", Value::from("23")); log.insert("z", Value::from(25)); log.insert("a", Value::from("0")); let encoded = encode_event(event, &EncodingConfig::from(Encoding::Json)); let expected = r#"{"a":"0","x":"23","z":25}"#; assert_eq!(encoded.unwrap(), expected); } #[test] fn encodes_counter() { let event = Event::Metric(Metric { name: "foos".into(), timestamp: Some(Utc.ymd(2018, 11, 14).and_hms_nano(8, 9, 10, 11)), tags: Some( vec![ ("key2".to_owned(), "value2".to_owned()), ("key1".to_owned(), "value1".to_owned()), ("Key3".to_owned(), "Value3".to_owned()), ] .into_iter() .collect(), ), kind: MetricKind::Incremental, value: MetricValue::Counter { value: 100.0 }, }); assert_eq!( r#"{"name":"foos","timestamp":"2018-11-14T08:09:10.000000011Z","tags":{"Key3":"Value3","key1":"value1","key2":"value2"},"kind":"incremental","counter":{"value":100.0}}"#, encode_event(event, &EncodingConfig::from(Encoding::Text)).unwrap() ); } #[test] fn encodes_set() { let event = Event::Metric(Metric { name: "users".into(), timestamp: None, tags: None, kind: MetricKind::Incremental, value: MetricValue::Set { values: vec!["bob".into()].into_iter().collect(), }, }); assert_eq!( r#"{"name":"users","timestamp":null,"tags":null,"kind":"incremental","set":{"values":["bob"]}}"#, encode_event(event, &EncodingConfig::from(Encoding::Text)).unwrap() ); } #[test] fn encodes_histogram_without_timestamp() { let event = Event::Metric(Metric { name: "glork".into(), timestamp: None, tags: None, kind: MetricKind::Incremental, value: MetricValue::Distribution { values: vec![10.0], sample_rates: vec![1], }, }); assert_eq!( r#"{"name":"glork","timestamp":null,"tags":null,"kind":"incremental","distribution":{"values":[10.0],"sample_rates":[1]}}"#, encode_event(event, &EncodingConfig::from(Encoding::Text)).unwrap() ); } }
use futures::{future, try_ready, Future, Poll}; use linkerd2_error::Error; pub type Data = hyper::body::Chunk; pub type Response = http::Response<Payload>; pub type ResponseFuture = Box<dyn Future<Item = Response, Error = Error> + Send + 'static>; pub struct BoxedService<A>( Box< dyn tower::Service< http::Request<A>, Response = Response, Error = Error, Future = ResponseFuture, > + Send, >, ); pub struct Layer<A, B> { _marker: std::marker::PhantomData<fn(A) -> B>, } pub struct Make<M, A, B> { inner: M, _marker: std::marker::PhantomData<fn(A) -> B>, } impl<A, B> Clone for Layer<A, B> { fn clone(&self) -> Self { Self { _marker: self._marker, } } } impl<M: Clone, A, B> Clone for Make<M, A, B> { fn clone(&self) -> Self { Self { inner: self.inner.clone(), _marker: self._marker, } } } impl<A, B> Layer<A, B> where A: 'static, B: hyper::body::Payload<Data = Data, Error = Error> + 'static, { pub fn new() -> Self { Layer { _marker: std::marker::PhantomData, } } } impl<M, A, B> tower::layer::Layer<M> for Layer<A, B> { type Service = Make<M, A, B>; fn layer(&self, inner: M) -> Self::Service { Self::Service { inner, _marker: std::marker::PhantomData, } } } impl<T, M, A, B> tower::Service<T> for Make<M, A, B> where A: 'static, M: tower::MakeService<T, http::Request<A>, Response = http::Response<B>>, M::Error: Into<Error> + 'static, M::Service: Send + 'static, <M::Service as tower::Service<http::Request<A>>>::Future: Send + 'static, B: hyper::body::Payload<Data = Data, Error = Error> + 'static, { type Response = BoxedService<A>; type Error = M::MakeError; type Future = future::Map<M::Future, fn(M::Service) -> BoxedService<A>>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.inner.poll_ready() } fn call(&mut self, target: T) -> Self::Future { self.inner.make_service(target).map(BoxedService::new) } } struct Inner<S, A, B> { service: S, _marker: std::marker::PhantomData<fn(A) -> B>, } struct InnerFuture<F, B> { future: F, _marker: std::marker::PhantomData<fn() -> B>, } pub struct Payload { inner: Box<dyn hyper::body::Payload<Data = Data, Error = Error> + Send + 'static>, } struct NoPayload; impl<A: 'static> BoxedService<A> { fn new<S, B>(service: S) -> Self where S: tower::Service<http::Request<A>, Response = http::Response<B>> + Send + 'static, S::Future: Send + 'static, S::Error: Into<Error> + 'static, B: hyper::body::Payload<Data = Data, Error = Error> + 'static, { BoxedService(Box::new(Inner { service, _marker: std::marker::PhantomData, })) } } impl<A> tower::Service<http::Request<A>> for BoxedService<A> { type Response = Response; type Error = Error; type Future = ResponseFuture; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.0.poll_ready() } fn call(&mut self, req: http::Request<A>) -> Self::Future { self.0.call(req) } } impl<S, A, B> tower::Service<http::Request<A>> for Inner<S, A, B> where S: tower::Service<http::Request<A>, Response = http::Response<B>>, S::Error: Into<Error> + 'static, S::Future: Send + 'static, B: hyper::body::Payload<Data = Data, Error = Error> + 'static, { type Response = Response; type Error = Error; type Future = ResponseFuture; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.service.poll_ready().map_err(Into::into) } fn call(&mut self, req: http::Request<A>) -> Self::Future { let future = self.service.call(req); Box::new(InnerFuture { future, _marker: std::marker::PhantomData, }) } } impl<F, B> Future for InnerFuture<F, B> where F: Future<Item = http::Response<B>>, F::Error: Into<Error>, B: hyper::body::Payload<Data = Data, Error = Error> + 'static, { type Item = Response; type Error = Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { let rsp: http::Response<B> = try_ready!(self.future.poll().map_err(Into::into)); let rsp: Response = rsp.map(|inner| Payload { inner: Box::new(inner), }); Ok(rsp.into()) } } impl Default for Payload { fn default() -> Self { Self { inner: Box::new(NoPayload), } } } impl hyper::body::Payload for Payload { type Data = Data; type Error = Error; fn is_end_stream(&self) -> bool { self.inner.is_end_stream() } fn poll_data(&mut self) -> Poll<Option<Self::Data>, Self::Error> { self.inner.poll_data().map_err(Into::into) } fn poll_trailers(&mut self) -> Poll<Option<http::HeaderMap>, Self::Error> { self.inner.poll_trailers().map_err(Into::into) } } impl hyper::body::Payload for NoPayload { type Data = Data; type Error = Error; fn is_end_stream(&self) -> bool { true } fn poll_data(&mut self) -> Poll<Option<Self::Data>, Self::Error> { Ok(None.into()) } fn poll_trailers(&mut self) -> Poll<Option<http::HeaderMap>, Self::Error> { Ok(None.into()) } } impl<S: Clone, A, B> Clone for Inner<S, A, B> { fn clone(&self) -> Self { Self { service: self.service.clone(), _marker: self._marker, } } }
use crate::raw::{flann_index_t, FLANNParameters}; use std::fmt::Debug; use std::os::raw::{c_int, c_uint}; pub unsafe trait Indexable: Clone + Debug + Default { type ResultType: Clone + Debug + Default; unsafe fn build_index( dataset: *mut Self, rows: c_int, cols: c_int, speedup: *mut f32, flann_params: *mut FLANNParameters, ) -> flann_index_t; unsafe fn add_points( index_ptr: flann_index_t, points: *mut Self, rows: c_int, columns: c_int, rebuild_threshold: f32, ) -> c_int; unsafe fn remove_point(index_ptr: flann_index_t, point_id: c_uint) -> c_int; unsafe fn get_point(index_ptr: flann_index_t, point_id: c_uint) -> *mut Self; unsafe fn veclen(index_ptr: flann_index_t) -> c_uint; unsafe fn size(index_ptr: flann_index_t) -> c_uint; unsafe fn used_memory(index_ptr: flann_index_t) -> c_int; unsafe fn find_nearest_neighbors_index( index_id: flann_index_t, testset: *mut Self, trows: c_int, indices: *mut c_int, dists: *mut Self::ResultType, nn: c_int, flann_params: *mut FLANNParameters, ) -> c_int; unsafe fn radius_search( index_ptr: flann_index_t, query: *mut Self, indices: *mut c_int, dists: *mut Self::ResultType, max_nn: c_int, radius: f32, flann_params: *mut FLANNParameters, ) -> c_int; unsafe fn free_index(index_id: flann_index_t, flann_params: *mut FLANNParameters) -> c_int; }
//! https://github.com/lumen/otp/tree/lumen/lib/edoc/src use super::*; test_compiles_lumen_otp!(edoc); test_compiles_lumen_otp!(edoc_data); test_compiles_lumen_otp!(edoc_doclet); test_compiles_lumen_otp!(edoc_extract); test_compiles_lumen_otp!(edoc_layout); test_compiles_lumen_otp!(edoc_lib); test_compiles_lumen_otp!(edoc_macros); test_compiles_lumen_otp!(edoc_refs imports "lib/edoc/src/edoc_lib"); test_compiles_lumen_otp!(edoc_report); test_compiles_lumen_otp!(edoc_run); test_compiles_lumen_otp!(edoc_scanner); test_compiles_lumen_otp!(edoc_specs); test_compiles_lumen_otp!(edoc_tags); test_compiles_lumen_otp!(edoc_types); test_compiles_lumen_otp!(edoc_wiki); fn includes() -> Vec<&'static str> { let mut includes = super::includes(); includes.extend(vec!["lib/edoc/include", "lib/edoc/src"]); includes } fn relative_directory_path() -> PathBuf { super::relative_directory_path().join("edoc/src") }
#![cfg_attr(not(feature = "std"), no_std)] #![recursion_limit = "256"] #[macro_use] extern crate log; use core::convert::TryInto; use core::convert::TryFrom; use move_vm::data::ExecutionContext; use sp_std::prelude::*; use codec::{FullCodec, FullEncode}; use frame_support::{decl_module, decl_storage, dispatch}; use frame_system::{ensure_signed, ensure_root}; use move_vm::mvm::Mvm; use move_vm::Vm; use move_vm::types::Gas; use move_vm::types::ModuleTx; use move_vm::types::Transaction; use move_core_types::account_address::AccountAddress; use move_core_types::language_storage::CORE_CODE_ADDRESS; pub mod addr; pub mod event; pub mod mvm; pub mod oracle; pub mod result; pub mod storage; use result::Error; pub use event::Event; use event::*; use storage::MoveVmStorage; use storage::VmStorageAdapter; use mvm::TryCreateMoveVm; use mvm::TryGetStaticMoveVm; use mvm::TryCreateMoveVmWrapped; use mvm::VmWrapperTy; /// Configure the pallet by specifying the parameters and types on which it depends. pub trait Trait: frame_system::Trait + timestamp::Trait { /// Because this pallet emits events, it depends on the runtime's definition of an event. type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>; // type BlockNumber: Into<u64>; } // The pallet's runtime storage items. // https://substrate.dev/docs/en/knowledgebase/runtime/storage decl_storage! { // A unique name is used to ensure that the pallet's storage items are isolated. // This name may be updated, but each pallet in the runtime must use a unique name. // ---------------------------------vvvvvvvvvvvvvv trait Store for Module<T: Trait> as Mvm { // Learn more about declaring storage items: // https://substrate.dev/docs/en/knowledgebase/runtime/storage#declaring-storage-items /// Storage for move- write-sets contains code & resources pub VMStorage: map hasher(blake2_128_concat) Vec<u8> => Option<Vec<u8>>; } } // Dispatchable functions allows users to interact with the pallet and invoke state changes. // These functions materialize as "extrinsics", which are often compared to transactions. // Dispatchable functions must be annotated with a weight and must return a DispatchResult. decl_module! { pub struct Module<T: Trait> for enum Call where origin: T::Origin, T::BlockNumber: TryInto<u64>, // <<T as frame_system::Trait>::BlockNumber as TryInto<u64>>::Error: std::fmt::Debug { // Errors must be initialized if they are used by the pallet. type Error = Error<T>; fn deposit_event() = default; #[weight = 10_000] pub fn execute(origin, tx_bc: Vec<u8>) -> dispatch::DispatchResultWithPostInfo { let transaction = Transaction::try_from(&tx_bc[..]).map_err(|_| Error::<T>::TransactionValidationError)?; let vm = Self::try_get_or_create_move_vm()?; let gas = Self::get_move_gas_limit()?; let tx = { let signers = if transaction.signers_count() == 0 { Vec::with_capacity(0) } else if let Ok(account) = ensure_signed(origin) { debug!("executing `execute` with signed {:?}", account); let sender = addr::account_to_bytes(&account); debug!("converted sender: {:?}", sender); vec![AccountAddress::new(sender)] } else { // TODO: support multiple signers Vec::with_capacity(0) }; if transaction.signers_count() as usize != signers.len() { error!("Transaction signers num isn't eq signers: {} != {}", transaction.signers_count(), signers.len()); return Err(Error::<T>::TransactionSignersNumError.into()); } transaction.into_script(signers).map_err(|_| Error::<T>::TransactionValidationError)? }; let ctx = { let height = frame_system::Module::<T>::block_number().try_into().map_err(|_|Error::<T>::NumConversionError)?; let time = <timestamp::Module<T>>::get().try_into().map_err(|_|Error::<T>::NumConversionError)? .try_into().map_err(|_|Error::<T>::NumConversionError)?; ExecutionContext::new(time, height) }; let res = vm.execute_script(gas, ctx, tx); debug!("execution result: {:?}", res); // produce result with spended gas: let result = result::from_vm_result::<T>(res)?; Ok(result) } #[weight = 10_000] pub fn publish(origin, module_bc: Vec<u8>) -> dispatch::DispatchResultWithPostInfo { let who = ensure_signed(origin)?; debug!("executing `publish` with signed {:?}", who); let vm = Self::try_get_or_create_move_vm()?; let gas = Self::get_move_gas_limit()?; let tx = { let sender = addr::account_to_bytes(&who); debug!("converted sender: {:?}", sender); ModuleTx::new(module_bc, AccountAddress::new(sender)) }; let res = vm.publish_module(gas, tx); debug!("publish result: {:?}", res); // produce result with spended gas: let result = result::from_vm_result::<T>(res)?; // Emit an event: Self::deposit_event(RawEvent::ModulePublished(who)); Ok(result) } #[weight = 100_000] /// Batch publish std-modules by root account only pub fn publish_std(origin, modules: Vec<Vec<u8>>) -> dispatch::DispatchResultWithPostInfo { ensure_root(origin)?; debug!("executing `publish STD` with root"); let vm = Self::try_get_or_create_move_vm()?; let mut _gas_used = 0; let mut results = Vec::with_capacity(modules.len()); 'deploy: for module in modules.into_iter() { let gas = Self::get_move_gas_limit(/* TODO: - gas_used */)?; let tx = ModuleTx::new(module, CORE_CODE_ADDRESS); let res = vm.publish_module(gas, tx); debug!("publish result: {:?}", res); let is_ok = result::is_ok(&res); _gas_used += res.gas_used; results.push(res); if !is_ok { break 'deploy; } // Emit an event: Self::deposit_event(RawEvent::StdModulePublished); } // produce result with spended gas: let result = result::from_vm_results::<T>(&results)?; Ok(result) } fn on_finalize(n: T::BlockNumber) { Self::try_get_or_create_move_vm().unwrap().clear(); trace!("MoveVM cleared on {:?}", n); } } } impl<T: Trait> Module<T> { fn get_move_gas_limit() -> Result<Gas, Error<T>> { // TODO: gas-table & min-max values shoud be in genesis/config let max_gas_amount = (u64::MAX / 1000) - 42; // TODO: get native value let gas_unit_price = 1; Gas::new(max_gas_amount, gas_unit_price).map_err(|_| Error::InvalidGasAmountMaxValue) } } /// Get storage adapter ready for the VM impl<T: Trait, K, V> MoveVmStorage<T, K, V> for Module<T> where K: FullEncode, V: FullCodec, { type VmStorage = VMStorage; } impl<T: Trait> TryCreateMoveVm<T> for Module<T> { type Vm = Mvm<VmStorageAdapter<VMStorage>, DefaultEventHandler, oracle::DummyOracle>; type Error = Error<T>; fn try_create_move_vm() -> Result<Self::Vm, Self::Error> { trace!("MoveVM created"); let oracle = Default::default(); Mvm::new( Self::move_vm_storage(), Self::create_move_event_handler(), oracle, ) .map_err(|err| { error!("{}", err); Error::InvalidVMConfig }) } } impl<T: Trait> TryGetStaticMoveVm<DefaultEventHandler> for Module<T> { type Vm = VmWrapperTy<VMStorage>; type Error = Error<T>; fn try_get_or_create_move_vm() -> Result<&'static Self::Vm, Self::Error> { #[cfg(not(feature = "std"))] use once_cell::race::OnceBox as OnceCell; #[cfg(feature = "std")] use once_cell::sync::OnceCell; static VM: OnceCell<VmWrapperTy<VMStorage>> = OnceCell::new(); VM.get_or_try_init(|| { #[cfg(feature = "std")] { Self::try_create_move_vm_wrapped() } #[cfg(not(feature = "std"))] Self::try_create_move_vm_wrapped().map(Box::from) }) } } impl<T: Trait> DepositMoveEvent for Module<T> { fn deposit_move_event(e: MoveEventArguments) { debug!( "MoveVM Event: {:?} {:?} {:?} {:?}", e.addr, e.caller, e.ty_tag, e.message ); // Emit an event: use codec::Encode; Self::deposit_event(RawEvent::Event( e.addr, e.ty_tag.encode(), e.message, e.caller, )); } }
#![feature(external_doc)] use ema_rs::EMA; use ta_common::traits::Indicator; #[doc(include = "../README.md")] pub struct PPO { short_period: u32, long_ema: EMA, short_ema: EMA, index: u32, } impl PPO { pub fn new(short_period: u32, long_period: u32) -> PPO { Self { short_period, long_ema: EMA::new(long_period), short_ema: EMA::new(short_period), index: 0, } } } impl Indicator<f64, Option<f64>> for PPO { fn next(&mut self, input: f64) -> Option<f64> { let long = self.long_ema.next(input); let short = self.short_ema.next(input); return if self.index >= self.short_period - 1 { let ppo = 100_f64 * (short - long) / long; Some(ppo) } else { self.index = self.index + 1; None }; } fn reset(&mut self) { self.short_ema.reset(); self.long_ema.reset(); self.index = 0; } } #[cfg(test)] mod tests { use crate::PPO; use ta_common::traits::Indicator; #[test] fn add_works() { let mut ppo = PPO::new(2, 5); assert_eq!(ppo.next(81.59), None); assert_eq!(ppo.next(81.06), Some(-0.21699967245331922)); assert_eq!(ppo.next(82.87), Some(0.5209675887612042)); assert_eq!(ppo.next(83.00), Some(0.6190403299147216)); assert_eq!(ppo.next(83.61), Some(0.7468846224456406)); assert_eq!(ppo.next(83.15), Some(0.4239424161439804)); assert_eq!(ppo.next(82.84), Some(0.13356017757692787)); assert_eq!(ppo.next(83.99), Some(0.4997247953737079)); assert_eq!(ppo.next(84.55), Some(0.690806261787222)); assert_eq!(ppo.next(84.36), Some(0.503265546395477)); assert_eq!(ppo.next(85.53), Some(0.8097662523725208)); assert_eq!(ppo.next(86.54), Some(1.0883304662225042)); assert_eq!(ppo.next(86.89), Some(1.039770979517235)); assert_eq!(ppo.next(87.77), Some(1.1327352631554244)); assert_eq!(ppo.next(87.29), Some(0.7158876517890078)); } }
mod math_lib; fn main() { println!("Sum of two number using module along with main.rs {} " , math_lib::basic::sum(50,50)); }
#![deny(warnings)] use tokio::fs::File; use tokio_util::codec::{BytesCodec, FramedRead}; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Method, Request, Response, Result, Server, StatusCode}; static INDEX: &str = "examples/send_file_index.html"; static NOTFOUND: &[u8] = b"Not Found"; #[tokio::main] async fn main() { pretty_env_logger::init(); let addr = "127.0.0.1:1337".parse().unwrap(); let make_service = make_service_fn(|_| async { Ok::<_, hyper::Error>(service_fn(response_examples)) }); let server = Server::bind(&addr).serve(make_service); println!("Listening on http://{}", addr); if let Err(e) = server.await { eprintln!("server error: {}", e); } } async fn response_examples(req: Request<Body>) -> Result<Response<Body>> { match (req.method(), req.uri().path()) { (&Method::GET, "/") | (&Method::GET, "/index.html") => simple_file_send(INDEX).await, (&Method::GET, "/no_file.html") => { // Test what happens when file cannot be be found simple_file_send("this_file_should_not_exist.html").await } _ => Ok(not_found()), } } /// HTTP status code 404 fn not_found() -> Response<Body> { Response::builder() .status(StatusCode::NOT_FOUND) .body(NOTFOUND.into()) .unwrap() } async fn simple_file_send(filename: &str) -> Result<Response<Body>> { // Serve a file by asynchronously reading it by chunks using tokio-util crate. if let Ok(file) = File::open(filename).await { let stream = FramedRead::new(file, BytesCodec::new()); let body = Body::wrap_stream(stream); return Ok(Response::new(body)); } Ok(not_found()) }
pub struct Solution; impl Solution { pub fn is_perfect_square(num: i32) -> bool { if num == 1 { return true; } let num = num as i64; let mut a = 1; let mut b = num; while b - a != 1 { let c = (a + b) / 2; if c * c <= num { a = c; } else { b = c; } } a * a == num } } #[test] fn test0367() { fn case(num: i32, want: bool) { let got = Solution::is_perfect_square(num); assert_eq!(got, want); } case(16, true); case(14, false); }
use std::convert::TryInto; use std::sync::Arc; use liblumen_alloc::erts::message::Message; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::*; use liblumen_alloc::erts::timeout::{ReceiveTimeout, Timeout}; use lumen_rt_core::process::current_process; use lumen_rt_core::time::monotonic; use lumen_rt_core::timer::{self, SourceEvent}; #[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ReceiveState { // Indicates to the caller that a message is available to peek Peek = 0, // Indicates to the caller that no message was available and the process // was transitioned to the waiting state. Wait = 1, // Indicates to the caller that the receive timed out Timeout = 2, } /// This structure manages the context for a receive state machine. /// /// It is critical that the layout for this structure be carefully /// maintained, as the compiler generates code which accesses it. Any /// changes that modify the layout or semantics of this structure must /// be synchronized with codegen. #[repr(C)] pub struct ReceiveContext { /// This field contains the absolute timeout in monotonic time (if applicable) /// associated with this receive operation. timeout: ReceiveTimeout, /// This field contains a timer reference used to wake the process if a message /// is never received, if a timeout was set. If no timeout was set, then this /// has a value of Term::None, and is unused. timer_reference: Term, /// This field is a pointer to a Message stored in the mailbox. Each Message is /// an entry in an intrusive, doubly-linked list which forms the queue of the /// mailbox. This pointer is used to get a cursor in that list, which is then /// used to obtain a reference to the message if the cursor is valid and points /// to a message which is still in the mailbox. If the message is not in the mailbox, /// the cursor returns None, otherwise it returns Some(&Message). /// /// NOTE: The only valid values for this pointer are null, or a pointer to a Message struct /// which is still live at the given address. For this reason it is not permitted to /// perform garbage collection while a receive context is live. This is in general not an /// issue, since a GC should only occur prior to, or after, a receive context is released. /// However, as an additional layer of defense, we add an assertion in the garbage_collect function /// of the process that raises if the process is in the Waiting state (the only state in which it /// should be possible for the garbage collector to be invoked). /// /// In the future, if we need to permit garbage collection during receives, we can do this /// by storing the live receive context in the mailbox state, and fixing up this pointer during /// GC. Rather than getting the whole struct when calling `start`, we'd just return a pointer to /// the context instead. message: *const Message, } impl ReceiveContext { #[inline] fn new(arc_process: Arc<Process>, timeout: Timeout) -> Self { let now = monotonic::time(); let timeout = ReceiveTimeout::new(now, timeout); let timer_reference = if let Some(monotonic) = timeout.monotonic() { timer::start(monotonic, SourceEvent::StopWaiting, arc_process).unwrap() } else { Term::NONE }; Self { timer_reference, message: core::ptr::null(), timeout, } } #[inline] fn timeout(&mut self) -> bool { let now = monotonic::time(); if self.timeout.is_timed_out(now) { self.cancel_timer(); true } else { false } } fn cancel_timer(&mut self) { if self.timer_reference != Term::NONE { let boxed_timer_reference: Boxed<Reference> = self.timer_reference.try_into().unwrap(); timer::cancel(&boxed_timer_reference); self.timer_reference = Term::NONE; } } } /// This function is called to construct a receive state machine, it performs no other work beyond just /// setting up the context for the state machine itself. The following state transition graph summarizes how the /// caller is expected to manage the state machine. /// /// start -> next <---------<-------- yield /// | | | /// | | | /// v | | /// received --> peek | /// | | | /// | v | /// | pop | /// | | | /// | v | /// timeout ---> done | /// | | /// wait ---------------------^ /// /// The state transitions here are `start`, `next`, `peek`, `pop` and `done`, and generally correspond to functions /// in this module. The `wait` state occurs when there are no messages available, and so the process is /// suspended until either a message is received or a timeout occurs. In either case, the process will resume, /// try to transition via `next` and branch accordingly. /// /// Yielding is implemented by the caller, the only behavioral semantics that must be preserved are that /// garbage collection may not occur during this yield, and that other processes must have the opportunity /// to execute during the yield so as to ensure forward progress. /// /// When `next` transitions to the received state, the next transition is `peek`, which will either `pop` /// the received message in the case where the peeked message matches one of the receive patterns; or it /// will transition to `next` and try again with the next message. /// /// NOTE: As of this writing, `peek` is implemented via generated code that directly accesses the message data. #[export_name = "__lumen_builtin_receive_start"] pub extern "C-unwind" fn builtin_receive_start(timeout: Term) -> ReceiveContext { let to = match timeout.decode().unwrap() { TypedTerm::Atom(atom) if atom == "infinity" => Timeout::Infinity, TypedTerm::SmallInteger(si) => Timeout::from_millis(si).expect("invalid timeout value"), _ => unreachable!("should never get non-atom/non-integer receive timeout"), }; let p = current_process(); ReceiveContext::new(p.clone(), to) } /// This function is called in three places: /// /// * Upon entering the receive state machine /// * During a selective receive, when a peeked message does not match /// * After waiting to be woken by the scheduler due to message receipt or time out /// /// This function determines whether or not a message is available, and what state to transition /// to next. #[export_name = "__lumen_builtin_receive_next"] pub extern "C-unwind" fn builtin_receive_next(context: &mut ReceiveContext) -> ReceiveState { let p = current_process(); let mbox_lock = p.mailbox.lock(); let mut mbox = mbox_lock.borrow_mut(); let cursor = if context.message.is_null() { // If no cursor has been obtained yet, try again mbox.cursor() } else { // If we have a cursor, move it to the next message in the queue let mut cursor = unsafe { mbox.cursor_from_ptr(context.message) }; cursor.move_prev(); cursor }; // If we have a message, proceed to `peek` // if let Some(message) = cursor.get() { context.message = message as *const Message; ReceiveState::Peek } else if context.timeout() { ReceiveState::Timeout } else { p.wait(); ReceiveState::Wait } } /// This function is called after a message was peeked, matched successfully and the receive /// state machine is entering its exit phase. The peeked message is removed from the mailbox, /// but its storage is left as-is, i.e. messages allocated in heap fragments remain in their /// fragment until a garbage collection is performed. Since a GC cycle fixes up any pointers /// contained in roots or the heap, we don't need to concern ourselves with where the terms /// live at this stage. #[export_name = "__lumen_builtin_receive_pop"] pub extern "C-unwind" fn builtin_receive_pop(context: &mut ReceiveContext) { let p = current_process(); let mbox_lock = p.mailbox.lock(); let mut mbox = mbox_lock.borrow_mut(); // Remove the message at the current cursor mbox.remove(context.message); // Reset the cursor state in the receive context context.message = core::ptr::null(); } /// This function is called when the receive state machine is exiting and is used to clean /// up any data in the context which we don't want to leave dangling. For now, that is simply /// the timer associated with the context. #[export_name = "__lumen_builtin_receive_done"] pub extern "C-unwind" fn builtin_receive_done(context: &mut ReceiveContext) { context.cancel_timer(); }
use proc_macro2::TokenStream; use quote::ToTokens; use std::cell::RefCell; /// Used to more easily implement ToTokens. pub struct ToTokenFnMut<F> { func: RefCell<F>, } impl<F> ToTokenFnMut<F> where F: FnMut(&mut TokenStream), { pub fn new(f: F) -> Self { Self { func: RefCell::new(f), } } #[allow(dead_code)] pub fn boxed<'a>(f: F) -> Box<dyn ToTokens + 'a> where F: 'a, { Box::new(Self::new(f)) } } impl<F> ToTokens for ToTokenFnMut<F> where F: FnMut(&mut TokenStream), { fn to_tokens(&self, tokens: &mut TokenStream) { RefCell::borrow_mut(&self.func)(tokens); } }
extern crate engine; extern crate simple_logger; use std::env; fn main() { simple_logger::init().unwrap(); let exe = env::current_exe().unwrap(); let root = exe.parent().unwrap(); let runner = engine::Builder::create(root.to_path_buf()).build(); let result = runner.run(); match result { Err(e) => println!("{}", e), _ => (), } }
fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let n: usize = rd.get(); let xy: Vec<(i64, i64)> = (0..n) .map(|_| { let x: i64 = rd.get(); let y: i64 = rd.get(); (x, y) }) .collect(); let m: usize = rd.get(); let mut a = Vec::new(); a.push(vec![vec![1, 0, 0], vec![0, 1, 0], vec![0, 0, 1]]); for o in 0..m { let tp: usize = rd.get(); let b = match tp { 1 => vec![vec![0, 1, 0], vec![-1, 0, 0], vec![0, 0, 1]], 2 => vec![vec![0, -1, 0], vec![1, 0, 0], vec![0, 0, 1]], 3 => { let p: i64 = rd.get(); vec![vec![-1, 0, p * 2], vec![0, 1, 0], vec![0, 0, 1]] } 4 => { let p: i64 = rd.get(); vec![vec![1, 0, 0], vec![0, -1, p * 2], vec![0, 0, 1]] } _ => unreachable!(), }; let mut c = vec![vec![0, 0, 0], vec![0, 0, 0], vec![0, 0, 0]]; for i in 0..3 { for j in 0..3 { for k in 0..3 { c[i][j] += b[i][k] * a[o][k][j]; } } } a.push(c); } let q: usize = rd.get(); for _ in 0..q { let i: usize = rd.get(); let j: usize = rd.get(); let a = &a[i]; let (x, y) = xy[j - 1]; println!( "{} {}", a[0][0] * x + a[0][1] * y + a[0][2], a[1][0] * x + a[1][1] * y + a[1][2] ); } } pub struct ProconReader<R> { r: R, line: String, i: usize, } impl<R: std::io::BufRead> ProconReader<R> { pub fn new(reader: R) -> Self { Self { r: reader, line: String::new(), i: 0, } } pub fn get<T>(&mut self) -> T where T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug, { self.skip_blanks(); assert!(self.i < self.line.len()); assert_ne!(&self.line[self.i..=self.i], " "); let line = &self.line[self.i..]; let end = line.find(' ').unwrap_or_else(|| line.len()); let s = &line[..end]; self.i += end; s.parse() .unwrap_or_else(|_| panic!("parse error `{}`", self.line)) } fn skip_blanks(&mut self) { loop { let start = self.line[self.i..].find(|ch| ch != ' '); match start { Some(j) => { self.i += j; break; } None => { self.line.clear(); self.i = 0; let num_bytes = self.r.read_line(&mut self.line).unwrap(); assert!(num_bytes > 0, "reached EOF :("); self.line = self.line.trim_end_matches(&['\r', '\n'][..]).to_string(); } } } } pub fn get_vec<T>(&mut self, n: usize) -> Vec<T> where T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug, { (0..n).map(|_| self.get()).collect() } }
//! Shared types (e.g. for a domain name) //! //! This module defines basic types, that are necessary throughout `dynonym` but unavailable in the //! [standard library][std]. Sometimes, equivalent types are present in third-party crates but we //! try to avoid them in order to provide a stable API. In case, the equivalent type is necessary //! to use the API of a dependency, this module provides a conversion. //! //! [std]: https://doc.rust-lang.org/std/ use rocket::http::RawStr; use rocket::request::FromFormValue; use std::convert::TryInto; use std::fmt::{self, Display, Formatter}; use std::str::FromStr; use trust_dns::rr::domain::Name; use trust_dns_proto::error::ProtoError; /// A domain name. /// /// A `Domain` represents a domain name as used in the Domain Name System (DNS). /// /// Warning: At the moment, a `Domain` is merely a tuple struct wrapping a `String`. The API even /// provides public access to the inner field. However, this is not considered to be stable and /// may change in the future without being considered to be a breaking change. #[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] pub struct Domain(pub String); impl Display for Domain { fn fmt(&self, f: &mut Formatter) -> fmt::Result { self.0.fmt(f) } } impl FromStr for Domain { type Err = &'static str; // TODO Use a proper error type when improving Domain! fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Domain(s.into())) } } impl<'v> FromFormValue<'v> for Domain { type Error = &'v RawStr; fn from_form_value(v: &'v RawStr) -> Result<Self, Self::Error> { let inner = String::from_form_value(v)?; Ok(Domain(inner)) } } impl TryInto<Name> for Domain { type Error = ProtoError; fn try_into(self) -> Result<Name, Self::Error> { Name::parse(&self.0, None) } } /// A salted and cryptographically hashed string. /// /// A `Hash` represents a string that was salted and cryptographically hashed using the bcrypt /// algorithm. The salt is stored alongside the hash. A `Hash` is well suited to store encrypted /// passwords. /// /// Since `Hash` implements `From<&str>`, the preferred method to obtain a `Hash` is to convert a /// string slice using `Into<Hash>` as shown in the example below. /// /// A `Hash` can be compared to a given string slice (== verified) with the method [`is`]. /// /// Because of different, randomly chosen salts, two hashes are (almost) never equal, even if /// obtained from the exact same plain text. /// /// [`is`]: #method.is /// /// # Example /// /// ``` /// use dynonym::types::Hash; /// /// // Create /// let h: Hash = "foo".into(); /// /// // Verify /// assert!( h.is("foo")); /// assert!(!h.is("bar")); /// ``` #[derive(Debug, Deserialize, Eq, PartialEq, Serialize)] pub struct Hash(String); impl Hash { /// Verifies whether `self` is a hashed version of the given string slice. pub fn is(&self, plain: &str) -> bool { use bcrypt::verify; verify(plain, &self.0).unwrap() } } impl<'a> From<&'a str> for Hash { fn from(plain: &'a str) -> Self { use bcrypt::{hash, DEFAULT_COST}; let hash = hash(plain, DEFAULT_COST).unwrap(); Hash(hash) } } #[cfg(test)] mod tests { use super::*; #[test] fn hash_eq() { let h: Hash = "foo".into(); assert!(h.is("foo")); } #[test] fn hash_ne() { let h: Hash = "foo".into(); assert!(!h.is("bar")); } #[test] fn hash_salt() { let h1: Hash = "foo".into(); let h2: Hash = "foo".into(); assert!(h1 != h2); // different salts! } }
use sodiumoxide::crypto::*; fn use_box_basic () { let (ourpk, oursk) = box_::gen_keypair(); // normally theirpk is sent by the other party let (theirpk, theirsk) = box_::gen_keypair(); let nonce = box_::gen_nonce(); let plaintext = b"some data"; let ciphertext = box_::seal(plaintext, &nonce, &theirpk, &oursk); let their_plaintext = box_::open(&ciphertext, &nonce, &ourpk, &theirsk).unwrap(); assert!(plaintext == &their_plaintext[..]); } fn main () { // basic usage use_box_basic(); }
use std::fmt::{self, Debug, Write}; use std::ops::{Index, IndexMut}; use itertools::Itertools; use unicode_width::UnicodeWidthChar; use super::{Bounds, Color, Coordinates, Size}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Cell { pub c: Option<char>, pub color: Option<Color>, } impl Default for Cell { fn default() -> Self { Cell { c: None, color: None, } } } impl From<char> for Cell { fn from(c: char) -> Self { Cell { c: Some(c), color: None, } } } #[derive(Default)] pub struct Screen { pub size: Size, cells: Vec<Cell>, } impl Screen { pub fn new(size: Size) -> Self { Screen { size, cells: vec![Cell::default(); (size.width * size.height).into()], } } pub fn iter_rows(&self) -> impl Iterator<Item = impl Iterator<Item = &Cell>> { (0..usize::from(self.size.height)).map(move |row| { let width = usize::from(self.size.width); let row_start = row * width; self.cells[row_start..row_start + width].iter() }) } /// Convenience method to write a string starting at a specific coordinate. If the string is /// longer than the width of the screen, it is truncated. pub fn write(&mut self, Coordinates { y, x, .. }: Coordinates, text: &str) { let mut offset = 0u16; for c in text.chars() { if offset >= self.size.width { break; } let width = c.width().unwrap_or(0) as u16; // TODO: Maybe should be 1? if width != 0 { self[(y, (x + offset))].c = Some(c); } offset += width; } } /// Apply a color to cells within a rectangular region. pub fn apply_color(&mut self, bounds: Bounds, color: Color) { debug_assert!(!bounds.is_empty()); for y in bounds.min.y..bounds.max.y { for x in bounds.min.x..bounds.max.x { self[(y, x)].color = Some(color); } } } /// Returns the index in the underlying storage that corresponds to the given row and column. /// /// # Panics /// /// Panics if the row or column are out of bounds. fn idx(&self, (row, col): (u16, u16)) -> usize { assert!( row < self.size.height, "there are {} rows but the row is {}", self.size.height, row ); assert!( col < self.size.width, "there are {} columns but the column is {}", self.size.width, col ); usize::from(row * self.size.width + col) } /// Erase all screen contents. pub fn clear(&mut self) { for cell in &mut self.cells { *cell = Cell::default(); } } } impl Index<(u16, u16)> for Screen { type Output = Cell; fn index(&self, (row, col): (u16, u16)) -> &Self::Output { &self.cells[self.idx((row, col))] } } impl IndexMut<(u16, u16)> for Screen { fn index_mut(&mut self, (row, col): (u16, u16)) -> &mut Self::Output { let idx = self.idx((row, col)); &mut self.cells[idx] } } impl Debug for Screen { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for row in self.iter_rows() { f.write_str(&row.map(|cell| format!("{:?}", cell)).join(", "))?; f.write_char('\n')?; } Ok(()) } } #[cfg(test)] mod tests { use euclid::size2; use super::{Bounds, Cell, Color, Coordinates, Screen, Size}; #[test] fn indexing() { let mut buf = Screen::new(Size::new(3, 3)); buf[(0, 0)] = Cell::from('a'); buf[(2, 2)] = Cell::from('z'); assert_eq!(buf.cells[0], Cell::from('a')); assert_eq!(buf.cells[8], Cell::from('z')); } #[test] #[should_panic = "there are 10 rows"] fn indexing_out_of_bounds_row() { let buf = Screen::new(Size::new(10, 10)); let _ = &buf[(11, 0)]; } #[test] #[should_panic = "there are 3 columns"] fn indexing_out_of_bounds_col() { let buf = Screen::new(Size::new(3, 3)); let _ = &buf[(0, 3)]; } #[test] fn iter_rows() { let mut buf = Screen::new(Size::new(3, 3)); buf[(0, 0)] = Cell::from('a'); let rows = buf .iter_rows() .map(|row| row.cloned().collect::<Vec<_>>()) .collect::<Vec<_>>(); assert_eq!( rows, vec![ vec![Cell::from('a'), Cell::default(), Cell::default()], vec![Cell::default(), Cell::default(), Cell::default()], vec![Cell::default(), Cell::default(), Cell::default()], ] ); } #[test] fn write_too_long() { let mut buf = Screen::new(Size::new(2, 1)); buf.write(Coordinates::zero(), "hello, world"); assert_eq!( buf.iter_rows().next().unwrap().collect::<Vec<_>>(), vec![&Cell::from('h'), &Cell::from('e')], ); } #[test] fn write_fullwidth() { let mut buf = Screen::new(size2(6, 1)); buf.write(Coordinates::zero(), "ABC"); assert_eq!(buf[(0, 0)], Cell::from('A')); assert_eq!(buf[(0, 1)], Cell::default()); assert_eq!(buf[(0, 2)], Cell::from('B')); } #[test] fn apply_color() { let mut buf = Screen::new(Size::new(3, 3)); let bounds = Bounds::new(Coordinates::new(1, 1), Coordinates::new(2, 2)); buf.apply_color(bounds, Color::BLUE); assert_eq!(buf[(0, 0)].color, None); assert_eq!(buf[(1, 1)].color, Some(Color::BLUE)); assert_eq!(buf[(1, 2)].color, None); } }
// 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. //! System service for managing cellular modems #![feature(async_await, await_macro, futures_api, arbitrary_self_types)] #![deny(warnings)] use { failure::{Error, ResultExt}, fidl::endpoints::{RequestStream, ServiceMarker}, fidl_fuchsia_telephony_manager::{ManagerMarker, ManagerRequest, ManagerRequestStream}, fidl_fuchsia_telephony_ril::{RadioInterfaceLayerMarker, RadioInterfaceLayerProxy}, fuchsia_app::{ client::{App, Launcher}, fuchsia_single_component_package_url, server::ServicesServer, }, fuchsia_async as fasync, fuchsia_syslog::{self as syslog, macros::*}, fuchsia_vfs_watcher::{WatchEvent, Watcher}, fuchsia_zircon as zx, futures::{future, Future, TryFutureExt, TryStreamExt}, parking_lot::RwLock, qmi::connect_transport_device, std::fs::File, std::path::{Path, PathBuf}, std::sync::Arc, }; const QMI_TRANSPORT: &str = "/dev/class/qmi-transport"; const RIL_URI: &str = fuchsia_single_component_package_url!("ril-qmi"); pub fn connect_qmi_transport(path: PathBuf) -> Result<fasync::Channel, zx::Status> { let file = File::open(&path)?; let chan = connect_transport_device(&file)?; Ok(fasync::Channel::from_channel(chan)?) } pub async fn start_qmi_modem(chan: zx::Channel) -> Result<Radio, Error> { let launcher = Launcher::new().context("Failed to open launcher service")?; let app = launcher.launch(RIL_URI.to_string(), None).context("Failed to launch qmi-modem service")?; let ril = app.connect_to_service(RadioInterfaceLayerMarker)?; let _success = await!(ril.connect_transport(chan.into()))?; Ok(Radio::new(app, ril)) } pub fn start_service( mgr: Arc<Manager>, channel: fasync::Channel, ) -> impl Future<Output = Result<(), Error>> { let stream = ManagerRequestStream::from_channel(channel); stream .try_for_each(move |evt| { let _ = match evt { ManagerRequest::IsAvailable { responder } => { responder.send(!mgr.radios.read().is_empty()) } // TODO(bwb): Get based on iface id, not just first one ManagerRequest::GetRilHandle { ril_iface, responder } => { fx_log_info!("Vending a RIL handle to another process"); let radios = mgr.radios.read(); match radios.first() { Some(radio) => { let resp = radio.app.pass_to_service( RadioInterfaceLayerMarker, ril_iface.into_channel(), ); responder.send(resp.is_ok()) } None => responder.send(false), } } }; future::ready(Ok(())) }) .map_err(|e| e.into()) } pub struct Radio { pub app: App, // TODO(bwb) Deref into Ril proxy? #[allow(dead_code)] // TODO(bwb) remove dead_code, needed to retain ownership for now. ril: RadioInterfaceLayerProxy, } impl Radio { pub fn new(app: App, ril: RadioInterfaceLayerProxy) -> Self { Radio { app, ril } } } pub struct Manager { radios: RwLock<Vec<Radio>>, } impl Manager { pub fn new() -> Self { Manager { radios: RwLock::new(vec![]) } } async fn watch_new_devices(&self) -> Result<(), Error> { // TODO(bwb): make more generic to support non-qmi devices let path: &Path = Path::new(QMI_TRANSPORT); let dir = File::open(QMI_TRANSPORT).unwrap(); let mut watcher = Watcher::new(&dir).unwrap(); while let Some(msg) = await!(watcher.try_next())? { match msg.event { WatchEvent::EXISTING | WatchEvent::ADD_FILE => { let qmi_path = path.join(msg.filename); fx_log_info!("Connecting to {}", qmi_path.display()); let file = File::open(&qmi_path)?; let channel = qmi::connect_transport_device(&file)?; let svc = await!(start_qmi_modem(channel))?; self.radios.write().push(svc); } _ => (), } } Ok(()) } } fn main() -> Result<(), Error> { syslog::init_with_tags(&["modem-mgr"]).expect("Can't init logger"); fx_log_info!("Starting modem-mgr..."); let mut executor = fasync::Executor::new().context("Error creating executor")?; let manager = Arc::new(Manager::new()); let mgr = manager.clone(); let device_watcher = manager.watch_new_devices(); let server = ServicesServer::new() .add_service((ManagerMarker::NAME, move |chan: fasync::Channel| { fx_log_info!("Spawning Management Interface"); fasync::spawn( start_service(mgr.clone(), chan) .unwrap_or_else(|e| fx_log_err!("Failed to spawn {:?}", e)), ) })) .start()?; executor.run_singlethreaded(device_watcher.try_join(server)).map(|_| ()) }
// An example that demonstrates a basic 2D lighting effect extern crate nalgebra; extern crate ncollide2d; extern crate quicksilver; use nalgebra::{zero, Isometry2}; use ncollide2d::query::{Ray, RayCast}; use quicksilver::{ Result, geom::{Rectangle, Vector}, graphics::{Color, GpuTriangle, Mesh, Vertex}, lifecycle::{Event, Settings, State, Window, run}, }; use std::cmp::Ordering; struct Raycast { // the rectangles to raycast against regions: Vec<Rectangle>, // the points to send rays to targets: Vec<Vector>, // the vertices to draw to the screen mesh: Mesh } impl State for Raycast { fn new() -> Result<Raycast> { //The different squares that cast shadows let regions = vec![ Rectangle::new_sized((800, 600)), // Feel free to add or remove rectangles to this list // to see the effect on the lighting Rectangle::new((200, 200), (100, 100)), Rectangle::new((400, 200), (100, 100)), Rectangle::new((400, 400), (100, 100)), Rectangle::new((200, 400), (100, 100)), Rectangle::new((50, 50), (50, 50)), Rectangle::new((550, 300), (64, 64)) ]; // Build the list of targets to cast rays to let targets = regions .iter() .flat_map(|region| { vec![ region.top_left(), region.top_left() + region.size().x_comp(), region.top_left() + region.size().y_comp(), region.top_left() + region.size(), ].into_iter() }) .collect(); Ok(Raycast { regions, targets, mesh: Mesh::new(), }) } fn event(&mut self, event: &Event, window: &mut Window) -> Result<()> { if let &Event::MouseMoved(_) = event { let mouse = window.mouse().pos(); self.mesh.clear(); let distance_to = |point: &Vector| (*point - mouse).len(); let angle_to = |point: &Vertex| (point.pos - mouse).angle(); // Raycast towards all targets and find the vertices for i in 0..self.targets.len() { let angle = (self.targets[i] - mouse).angle(); let mut cast_ray = |direction: f32| { // Create a Ray from the mouse to the target let start = mouse.into_point(); let direction = Vector::from_angle(direction).into_vector(); let ray = Ray::new(start, direction); // Perform the actual raycast, returning the target and an iterator of collisions let identity = Isometry2::new(zero(), zero()); let cast = self.regions .iter() .filter_map(|region| { region.into_aabb().toi_with_ray(&identity, &ray, false) }) .map(|toi: f32| (ray.origin + toi * ray.dir).into()) .min_by(|a: &Vector, b: &Vector| { distance_to(a) .partial_cmp(&distance_to(b)) .unwrap_or(Ordering::Equal) }); if let Some(pos) = cast { self.mesh.vertices.push(Vertex { pos, tex_pos: None, col: Color::WHITE, }); } }; // Make sure to cast rays around corners to avoid jitteriness cast_ray(angle - 0.001); cast_ray(angle); cast_ray(angle + 0.001); } // Sort the vertices to form a visibility polygon self.mesh.vertices.sort_by(|a, b| { angle_to(a) .partial_cmp(&angle_to(b)) .unwrap_or(Ordering::Equal) }); // Insert the mouse as a vertex for the center of the polygon self.mesh.vertices.insert( 0, Vertex { pos: mouse, tex_pos: None, col: Color::WHITE, }, ); // Calculate the number of triangles needed to draw the poly let triangle_count = self.mesh.vertices.len() as u32 - 1; for index in 0..triangle_count { self.mesh.triangles.push(GpuTriangle { z: 0.0, indices: [ 0, index as u32 + 1, (index as u32 + 1) % triangle_count + 1 ], image: None }); } } Ok(()) } fn draw(&mut self, window: &mut Window) -> Result<()> { window.clear(Color::BLACK)?; window.mesh().extend(&self.mesh); Ok(()) } } fn main() { run::<Raycast>("Raycast", Vector::new(800, 600), Settings::default()); }
use crate::{ fmx_Data, fmx_DataVect, fmx_ExprEnv, fmx_ExtPluginType, fmx__fmxcpt, fmx_ptrtype, write_to_u16_buff, AllowedVersions, ApplicationVersion, Data, DataVect, ExprEnv, ExternStringType, ExternVersion, FMError, FM_ExprEnv_RegisterExternalFunctionEx, FM_ExprEnv_RegisterScriptStep, FM_ExprEnv_UnRegisterExternalFunction, FM_ExprEnv_UnRegisterScriptStep, QuadChar, Text, }; use widestring::U16CStr; /// Implement this trait for your plugin struct. The different functions are used to give FileMaker information about the plugin. You also need to register all your functions/script steps in the trait implementation. /// /// # Example /// ```rust /// # use fm_plugin::prelude::*; /// # use fm_plugin::{DataVect, ExprEnv, Data, FMError}; /// # struct MyFunction; /// # impl FileMakerFunction for MyFunction { /// # fn function(id: i16, env: &ExprEnv, args: &DataVect, result: &mut Data) -> FMError { /// # FMError::NoError /// # } /// # } /// struct MyPlugin; /// /// impl Plugin for MyPlugin { /// fn id() -> &'static [u8; 4] { &b"MyPl" } /// fn name() -> &'static str { "MY PLUGIN" } /// fn description() -> &'static str { "Does all sorts of great things." } /// fn url() -> &'static str { "http://myplugin.com" } /// /// fn register_functions() -> Vec<Registration> { /// vec![Registration::Function { /// id: 100, /// name: "MyPlugin_MyFunction", /// definition: "MyPlugin_MyFunction( arg1 ; arg2 )", /// description: "Does some really great stuff.", /// min_args: 2, /// max_args: 2, /// display_in_dialogs: true, /// compatibility_flags: Compatibility::Future as u32, /// min_ext_version: ExternVersion::V160, /// min_fm_version: "18.0.2", /// allowed_versions: AllowedVersions {developer: true, pro: true, web: true, sase: true, runtime: true}, /// function_ptr: Some(MyFunction::extern_func), /// } /// ] /// } /// } /// ``` pub trait Plugin { /// Unique 4 letter identifier for the plug-in. fn id() -> &'static [u8; 4]; /// Plug-in's name. fn name() -> &'static str; /// Description of the plug-in. fn description() -> &'static str; /// Url to send users to from the help in FileMaker. The function's name that the user will be appended to the url when clicked. fn url() -> &'static str; /// Register all custom functions/script steps fn register_functions() -> Vec<Registration>; /// Defaults to false fn enable_configure_button() -> bool { false } /// Defaults to true fn enable_init_and_shutdown() -> bool { true } /// Defaults to false fn enable_idle() -> bool { false } /// Defaults to false fn enable_file_and_session_shutdown() -> bool { false } fn session_shutdown(_session_id: fmx_ptrtype) {} fn file_shutdown(_session_id: fmx_ptrtype, _file_id: fmx_ptrtype) {} fn preferences() {} fn idle(_session_id: fmx_ptrtype) {} fn not_idle(_session_id: fmx_ptrtype) {} fn script_paused(_session_id: fmx_ptrtype) {} fn script_running(_session_id: fmx_ptrtype) {} fn un_safe(_session_id: fmx_ptrtype) {} } pub trait PluginInternal<T> where T: Plugin, { fn get_string( which_string: ExternStringType, _win_lang_id: u32, out_buffer_size: u32, out_buffer: *mut u16, ) { use ExternStringType::*; let string = match which_string { Name => T::name().to_string(), AppConfig => T::description().to_string(), Options => { let mut options: String = ::std::str::from_utf8(T::id()).unwrap().to_string(); options.push('1'); options.push(if T::enable_configure_button() { 'Y' } else { 'n' }); options.push('n'); options.push(if T::enable_init_and_shutdown() { 'Y' } else { 'n' }); options.push(if T::enable_idle() { 'Y' } else { 'n' }); options.push(if T::enable_file_and_session_shutdown() { 'Y' } else { 'n' }); options.push('n'); options } HelpUrl => T::url().to_string(), Blank => "".to_string(), }; unsafe { write_to_u16_buff(out_buffer, out_buffer_size, &string) } } fn initialize( ext_version: ExternVersion, app_version: ApplicationVersion, app_version_number: fmx_ptrtype, ) -> ExternVersion { let plugin_id = QuadChar::new(T::id()); for f in T::register_functions() { if ext_version < f.min_ext_version() || !f.is_fm_version_allowed(&app_version) || !is_version_high_enough(app_version_number, f.min_fm_version()) { continue; } if f.register(&plugin_id) != FMError::NoError { return ExternVersion::DoNotEnable; } } ExternVersion::V190 } fn shutdown(version: ExternVersion) { let plugin_id = QuadChar::new(T::id()); for f in T::register_functions() { if version < f.min_ext_version() { continue; } f.unregister(&plugin_id); } } } fn is_version_high_enough(app_version_number: fmx_ptrtype, min_version: &str) -> bool { let string = unsafe { U16CStr::from_ptr_str(app_version_number as *const u16) }; let string = string.to_string_lossy(); let version_number = string.split(' ').last().unwrap(); let (major, minor, patch) = semantic_version(version_number); let (min_major, min_minor, min_patch) = semantic_version(min_version); match (major, min_major, minor, min_minor, patch, min_patch) { (None, None, ..) => false, (Some(major), Some(min_major), ..) if major < min_major => false, (Some(major), Some(min_major), ..) if major > min_major => true, (Some(major), Some(min_major), _, None, ..) if major == min_major => true, (.., Some(minor), Some(min_minor), _, _) if minor < min_minor => false, (.., Some(minor), Some(min_minor), _, _) if minor > min_minor => true, (.., Some(minor), Some(min_minor), _, None) if minor == min_minor => true, (.., Some(patch), Some(min_patch)) if patch < min_patch => false, (.., Some(patch), Some(min_patch)) if patch > min_patch => true, _ => true, } } fn semantic_version(version: &str) -> (Option<u8>, Option<u8>, Option<u8>) { let mut str_vec = version.split('.'); let major = str_vec.next(); let minor = str_vec.next(); let patch = str_vec.next(); ( match major { Some(n) => n.parse::<u8>().ok(), None => None, }, match minor { Some(n) => n.parse::<u8>().ok(), None => None, }, match patch { Some(n) => n.parse::<u8>().ok(), None => None, }, ) } /// Sets up the entry point for every FileMaker call into the plug-in. The function then dispatches the calls to the various trait functions you can implement. /// Impl [`Plugin`][Plugin] for your plugin struct, and then call the macro on it. /// /// # Example /// ```rust /// use fm_plugin::prelude::*; /// /// struct MyPlugin; /// /// impl Plugin for MyPlugin { /// # fn id()-> &'static [u8; 4] { b"TEST" } /// # fn name()-> &'static str { "TEST" } /// # fn description()-> &'static str { "TEST" } /// # fn url()-> &'static str { "TEST" } /// # fn register_functions()-> Vec<Registration> { Vec::new() } /// // ... /// } /// /// register_plugin!(MyPlugin); /// ``` /// /// # Macro Contents ///```rust /// # use fm_plugin::prelude::*; /// # #[macro_export] /// # macro_rules! register_plugin { /// # ($x:ident) => { /// #[no_mangle] /// pub static mut gfmx_ExternCallPtr: *mut fmx_ExternCallStruct = std::ptr::null_mut(); /// /// #[no_mangle] /// unsafe extern "C" fn FMExternCallProc(pb: *mut fmx_ExternCallStruct) { /// // Setup global defined in fmxExtern.h (this will be obsoleted in a later header file) /// gfmx_ExternCallPtr = pb; /// use FMExternCallType::*; /// /// // Message dispatcher /// match (*pb).whichCall { /// Init => { /// (*pb).result = $x::initialize( /// (*pb).extnVersion, /// ApplicationVersion::from((*pb).parm1), /// (*pb).parm2, /// ) as u64 /// } /// Idle => { /// use IdleType::*; /// match IdleType::from((*pb).parm1) { /// Idle => $x::idle((*pb).parm2), /// NotIdle => $x::not_idle((*pb).parm2), /// ScriptPaused => $x::script_paused((*pb).parm2), /// ScriptRunning => $x::script_running((*pb).parm2), /// Unsafe => $x::un_safe((*pb).parm2), /// } /// } /// Shutdown => $x::shutdown((*pb).extnVersion), /// AppPrefs => $x::preferences(), /// GetString => $x::get_string( /// (*pb).parm1.into(), /// (*pb).parm2 as u32, /// (*pb).parm3 as u32, /// (*pb).result as *mut u16, /// ), /// SessionShutdown => $x::session_shutdown((*pb).parm2), /// FileShutdown => $x::file_shutdown((*pb).parm2, (*pb).parm3), /// } /// } /// /// impl PluginInternal<$x> for $x {} /// /// pub fn execute_filemaker_script<F, S>( /// file_name: F, /// script_name: S, /// control: ScriptControl, /// parameter: Option<Data>, /// ) -> FMError /// where /// F: ToText, /// S: ToText, /// { /// unsafe { /// (*gfmx_ExternCallPtr).execute_filemaker_script( /// file_name, /// script_name, /// control, /// parameter, /// ) /// } /// } /// /// lazy_static! { /// static ref GLOBAL_STATE: RwLock<HashMap<String, String>> = RwLock::new(HashMap::new()); /// } /// /// pub fn store_state(key: &str, value: &str) { /// let mut hmap = GLOBAL_STATE.write().unwrap(); /// (*hmap).insert(String::from(key), String::from(value)); /// } /// /// pub fn get_state(key: &str) -> Option<String> { /// let hmap = GLOBAL_STATE.read().unwrap(); /// (*hmap).get(key).cloned() /// } /// # }; /// # } /// /// ``` #[macro_export] macro_rules! register_plugin { ($x:ident) => { #[no_mangle] pub static mut gfmx_ExternCallPtr: *mut fmx_ExternCallStruct = std::ptr::null_mut(); #[no_mangle] unsafe extern "C" fn FMExternCallProc(pb: *mut fmx_ExternCallStruct) { // Setup global defined in fmxExtern.h (this will be obsoleted in a later header file) gfmx_ExternCallPtr = pb; use FMExternCallType::*; // Message dispatcher match (*pb).whichCall { Init => { (*pb).result = $x::initialize( (*pb).extnVersion, ApplicationVersion::from((*pb).parm1), (*pb).parm2, ) as u64 } Idle => { use IdleType::*; match IdleType::from((*pb).parm1) { Idle => $x::idle((*pb).parm2), NotIdle => $x::not_idle((*pb).parm2), ScriptPaused => $x::script_paused((*pb).parm2), ScriptRunning => $x::script_running((*pb).parm2), Unsafe => $x::un_safe((*pb).parm2), } } Shutdown => $x::shutdown((*pb).extnVersion), AppPrefs => $x::preferences(), GetString => $x::get_string( (*pb).parm1.into(), (*pb).parm2 as u32, (*pb).parm3 as u32, (*pb).result as *mut u16, ), SessionShutdown => $x::session_shutdown((*pb).parm2), FileShutdown => $x::file_shutdown((*pb).parm2, (*pb).parm3), } } impl PluginInternal<$x> for $x {} pub fn execute_filemaker_script<F, S>( file_name: F, script_name: S, control: ScriptControl, parameter: Option<Data>, ) -> FMError where F: ToText, S: ToText, { unsafe { (*gfmx_ExternCallPtr).execute_filemaker_script( file_name, script_name, control, parameter, ) } } lazy_static! { static ref GLOBAL_STATE: RwLock<HashMap<String, String>> = RwLock::new(HashMap::new()); } pub fn store_state(key: &str, value: &str) { let mut hmap = GLOBAL_STATE.write().unwrap(); (*hmap).insert(String::from(key), String::from(value)); } pub fn get_state(key: &str) -> Option<String> { let hmap = GLOBAL_STATE.read().unwrap(); (*hmap).get(key).cloned() } }; } /// Register [`ScriptSteps`][Registration::ScriptStep] and [`Functions`][Registration::Function] for your plugin. /// # Function Registration /// Registration enables the function so that it appears in the calculation dialog in the application. /// /// * `id` is the unique id that you can use to represent which function was called, it will be passed back to the registered function as the first parameter (see the parameter of the same name in [`fmx_ExtPluginType`][fmx_ExtPluginType]). /// * `name` is the name of the function as it should appear in the calculation formula. /// * `definition` is the suggested syntax that will appear in the list of functions in the calculation dialog. /// * `description` is the text that will display when auto-entered into the calculation dialog. The format is "type ahead word list|description text". /// * `min_args` is the number of required parameters for the function. `0` is the smallest valid value. /// * `max_args` is the maximum number of parameters that they user should be able to specify in the calculation dialog and still have correct syntax usage for the function. Use `-1` to allow a variable number of parameters up to the number supported by calculation formulas in the application. /// * `compatible_flags` see bit flags above. /// * `function_ptr` is the pointer to the function that must match the signature defined by [`fmx_ExtPluginType`][fmx_ExtPluginType]. If you implement [`FileMakerFunction`][FileMakerFunction] for your function, then you can just reference [`MyFunction.extern_func`][FileMakerFunction::extern_func] here. /// /// # Script Step Registration /// /// [`Registration::ScriptStep::definition`][Registration::ScriptStep::definition] must contain XML defining the script step options. Up to ten script parameters can be specified in addition to the optional target parameter. All the parameters are defined with `<Parameter>` tags in a `<PluginStep>` grouping. /// /// The attributes for a `<Parameter>` tag include: /// /// * `Type` - if not one of the following four types, the parameter is ignored /// 1. `Calc` - a standard Specify button that brings up the calculation dialog. When the script step is executed, the calculation will be evaluated and its results passed to the plug-in /// 2. `Bool` - simple check box that returns the value of `0` or `1` /// 3. `List` - a static drop-down or pop-up list in which the id of the item selected is returned. The size limit of this list is limited by the capabilities of the UI widgets used to display it. A `List` type parameter expects to contain `<Value>` tags as specified below /// 4. `Target` - will include a specify button that uses the new `Insert From Target` field targeting dialog that allows a developer to put the results of a script step into a field (whether or not it is on a layout), into a variable, or insert into the current active field on a layout. If no `Target` is defined then the result `Data` object is ignored. If there are multiple `Target` definitions, only the first one will be honored. /// /// * `ID` - A value in the range of `0` to `9` which is used as an index into the `DataVect` parms object for the plug-in to retrieve the value of the parameter. Indexes that are not in range or duplicated will cause the parameter to be ignored. A parameter of type `Target` ignores this attribute if specified /// /// * `Label` - The name of parameter or control that is displayed in the UI /// /// * `DataType` - only used by the `Calc` and `Target` parameter types. If not specified or not one of the six data types, the type `Text` will be used /// 1. `Text` /// 2. `Number` /// 3. `Date` /// 4. `Time` /// 5. `Timestamp` /// 6. `Container` /// /// * `ShowInline` - value is either true or false. If defined and true, will cause the parameter to show up inlined with the script step in the Scripting Workspace /// /// * `Default` - either the numeric index of the default list item or the true/false value for a bool item. Ignored for calc and target parameters /// /// Parameters of type `List` are expected to contain `<Value>` tags whose values are used to construct the drop-down or pop-up list. The id of a value starts at zero but specific id can be given to a value by defining an `ID` attribute. If later values do not have an `ID` attributes the id will be set to the previous values id plus one. /// /// Sample XML description: ///```xml ///<PluginStep> /// <Parameter ID="0" Type="Calc" DataType="text" ShowInline="true" Label="Mood"/> /// <Parameter ID="1" Type="List" ShowInline="true" Label="Color"> /// <Value ID="0">Red</Value> /// <Value ID="1">Green</Value> /// <Value ID="2">Blue</Value> /// </Parameter> /// <Parameter ID="2" Type="Bool" Label="Beep when happy"/> ///</PluginStep> ///``` pub enum Registration { Function { id: i16, name: &'static str, definition: &'static str, description: &'static str, min_args: i16, max_args: i16, display_in_dialogs: bool, compatibility_flags: u32, min_ext_version: ExternVersion, min_fm_version: &'static str, allowed_versions: AllowedVersions, function_ptr: fmx_ExtPluginType, }, ScriptStep { id: i16, name: &'static str, definition: &'static str, description: &'static str, display_in_dialogs: bool, compatibility_flags: u32, min_ext_version: ExternVersion, min_fm_version: &'static str, allowed_versions: AllowedVersions, function_ptr: fmx_ExtPluginType, }, } impl Registration { /// Called automatically by [`register_plugin!`][register_plugin]. pub fn register(&self, plugin_id: &QuadChar) -> FMError { let mut _x = fmx__fmxcpt::new(); let (id, n, desc, def, display, flags, func_ptr) = match *self { Registration::Function { id, name, description, definition, display_in_dialogs, compatibility_flags, function_ptr, .. } => ( id, name, description, definition, display_in_dialogs, compatibility_flags, function_ptr, ), Registration::ScriptStep { id, name, description, definition, display_in_dialogs, compatibility_flags, function_ptr, .. } => ( id, name, description, definition, display_in_dialogs, compatibility_flags, function_ptr, ), }; let mut name = Text::new(); name.assign(n); let mut description = Text::new(); description.assign(desc); let mut definition = Text::new(); definition.assign(def); let flags = if display { 0x0000FF00 } else { 0 } | flags; let error = match self { Registration::Function { min_args, max_args, .. } => unsafe { FM_ExprEnv_RegisterExternalFunctionEx( plugin_id.ptr, id, name.ptr, definition.ptr, description.ptr, *min_args, *max_args, flags, func_ptr, &mut _x, ) }, Registration::ScriptStep { .. } => unsafe { FM_ExprEnv_RegisterScriptStep( plugin_id.ptr, id, name.ptr, definition.ptr, description.ptr, flags, func_ptr, &mut _x, ) }, }; _x.check(); error } /// Returns minimum allowed sdk version for a function/script step. pub fn min_ext_version(&self) -> ExternVersion { match self { Registration::Function { min_ext_version, .. } => *min_ext_version, Registration::ScriptStep { min_ext_version, .. } => *min_ext_version, } } /// Returns minimum allowed FileMaker version for a function/script step. pub fn min_fm_version(&self) -> &str { match self { Registration::Function { min_fm_version, .. } | Registration::ScriptStep { min_fm_version, .. } => *min_fm_version, } } pub fn is_fm_version_allowed(&self, version: &ApplicationVersion) -> bool { let allowed_versions = match self { Registration::Function { allowed_versions, .. } | Registration::ScriptStep { allowed_versions, .. } => allowed_versions, }; use ApplicationVersion::*; match version { Developer => allowed_versions.developer, Pro => allowed_versions.pro, Runtime => allowed_versions.runtime, SASE => allowed_versions.sase, Web => allowed_versions.web, } } /// Called automatically by [`register_plugin!`][register_plugin]. pub fn unregister(&self, plugin_id: &QuadChar) { let mut _x = fmx__fmxcpt::new(); match self { Registration::Function { id, .. } => unsafe { FM_ExprEnv_UnRegisterExternalFunction(plugin_id.ptr, *id, &mut _x); }, Registration::ScriptStep { id, .. } => unsafe { FM_ExprEnv_UnRegisterScriptStep(plugin_id.ptr, *id, &mut _x); }, } _x.check(); } } pub trait FileMakerFunction { /// Define your custom function here. Set the return value to the result parameter. fn function(id: i16, env: &ExprEnv, args: &DataVect, result: &mut Data) -> FMError; /// Entry point for FileMaker to call your function. extern "C" fn extern_func( id: i16, env_ptr: *const fmx_ExprEnv, args_ptr: *const fmx_DataVect, result_ptr: *mut fmx_Data, ) -> FMError { let arguments = DataVect::from_ptr(args_ptr); let env = ExprEnv::from_ptr(env_ptr); let mut result = Data::from_ptr(result_ptr); Self::function(id, &env, &arguments, &mut result) } }
pub mod error; pub use self::error::*; mod ppm; mod image; #[cfg(feature="gui")] mod gui; mod buckets; pub use self::buckets::*; use scene::*; use vec3::*; use std::fs::File; use std::path::Path; pub trait Output { fn begin(&mut self) -> Result<()> {Ok(())} fn put_pixel(&mut self, x: u32, y: u32, color: &Vec3<f64>) -> Result<()>; fn begin_bucket(&mut self, bucket: &Bucket) -> Result<()> {Ok(())} fn put_bucket(&mut self, bucket: &Bucket, pixels: &Vec<Vec<Vec3<f64>>>) -> Result<()> { for (y, row) in pixels.iter().enumerate() { for (x, pixel) in row.iter().enumerate() { self.put_pixel(bucket.x+x as u32, bucket.y+y as u32, pixel)?; } } Ok(()) } fn end(&mut self) -> Result<()> {Ok(())} fn wait_to_exit(&mut self) {} } #[derive(Debug, Clone)] pub enum OutputFormat { #[cfg(feature="gui")] Gui, Ppm, Png, Jpg, } #[derive(Debug, Clone)] pub struct OutputSettings { pub format: OutputFormat, pub filename_template: String, pub width: u32, pub height: u32, } impl OutputSettings { pub fn set_filename_template(&mut self, tmpl: String) -> Result<()> { let p = Path::new(&tmpl); if let Some(ext) = p.extension() { self.format = match ext.to_str().unwrap() { "png" => OutputFormat::Png, "jpg" => OutputFormat::Jpg, "jpegg" => OutputFormat::Jpg, _ => { return Err(Error::UnsupportedImageFormat.into()) } }; self.filename_template = tmpl.clone(); Ok(()) } else { Err(Error::UnsupportedImageFormat.into()) } } } pub fn new_output(settings: &OutputSettings, scene: &Scene) -> Result<Box<Output>> { match settings.format { #[cfg(feature="gui")] OutputFormat::Gui => Ok(Box::new(gui::GuiOutput::new(settings, scene)?)), OutputFormat::Ppm => Ok(Box::new(ppm::PpmOutput::new(settings, scene)?)), OutputFormat::Png => { let png = image::ImageOutput8::new(settings, scene)?; Ok(Box::new(png)) }, OutputFormat::Jpg => { let jpg = image::ImageOutput8::new(settings, scene)?; Ok(Box::new(jpg)) }, } } // Frame # (w/padding), Scene, RenderLayer, Camera, RenderPass, Extension (and custom), Version (custom label), date, time fn path_from_template(template: &str, scene: &Scene) -> String { String::from(template) }
//! Valiu Liquidity Network - Node mod chain_spec; mod cli; mod command; mod rpc; mod service; fn main() -> sc_cli::Result<()> { command::run() }
#![feature(trait_alias)] #![feature(extended_key_value_attributes)] #![feature(type_alias_impl_trait)] #![allow(dead_code)] pub mod filters; pub mod odometry; pub mod sensor_models; mod datatypes; mod utils { pub mod collect_vec; pub mod fmap; pub mod gaussian; pub mod searcher_util; } pub use datatypes::*; pub mod notes;
use serde::Serialize; use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn add(a: u32, b: u32) -> u32 { a + (b * 2) } #[wasm_bindgen] #[derive(Serialize)] pub struct Movie { title: String, description: String, pub rating: f32, } #[wasm_bindgen] impl Movie { #[wasm_bindgen(getter)] pub fn title(&self) -> String { self.title.clone() } pub fn about(&self) -> String { format!("{} - {}", self.title.clone(), self.rating) } } #[wasm_bindgen] pub fn get_movie() -> Movie { Movie { title: "A Great Movie".to_string(), description: "Description for the movie".to_string(), rating: 3.7, } } // `Vec<Movie>` can't go through the wasm border // * It can be converted to an `Array` (or an `Array<Movie>` to keep inner type details) -> see `get_movies_array` // * Or it can be converted to a `JsValue` using serde, in which case only data is transferred (with every serializable // field): field `description` is available in JS but not method `about` -> see `get_movies_js` pub fn get_movies() -> Vec<Movie> { vec![ Movie { title: "A Great Movie".to_string(), description: "Description for the movie".to_string(), rating: 3.7, }, Movie { title: "Another movie".to_string(), description: "Meh".to_string(), rating: 2.0, }, ] } use wasm_bindgen::JsCast; #[wasm_bindgen] extern "C" { #[wasm_bindgen(typescript_type = "Array<Movie>")] pub type MovieArray; } #[wasm_bindgen] pub fn get_movies_array() -> MovieArray { get_movies() .into_iter() .map(JsValue::from) .collect::<js_sys::Array>() .unchecked_into::<MovieArray>() } #[wasm_bindgen] pub fn get_movies_js() -> Result<JsValue, JsValue> { Ok(serde_wasm_bindgen::to_value(&get_movies())?) }
use std::{ fmt::{Display, Formatter, Result as FmtResult}, ops::{Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub, SubAssign}, }; #[derive(Copy, Clone)] pub struct Vec3([f64; 3]); impl Vec3 { #[inline] pub const fn new(a: f64, b: f64, c: f64) -> Vec3 { Vec3([a, b, c]) } #[inline] pub fn x(&self) -> f64 { self[0] } #[inline] pub fn y(&self) -> f64 { self[1] } #[inline] pub fn z(&self) -> f64 { self[2] } #[inline] pub fn r(&self) -> f64 { self[0] } #[inline] pub fn g(&self) -> f64 { self[1] } #[inline] pub fn b(&self) -> f64 { self[2] } #[inline] pub fn length(&self) -> f64 { self.sq_len().sqrt() } #[inline] pub fn sq_len(&self) -> f64 { self[0] * self[0] + self[1] * self[1] + self[2] * self[2] } #[inline] pub fn dot(&self, v: &Vec3) -> f64 { self[0] * v[0] + self[1] * v[1] + self[2] * v[2] } #[inline] pub fn cross(&self, v: &Vec3) -> Vec3 { Vec3([ self[1] * v[2] - self[2] * v[1], self[2] * v[0] - self[0] * v[2], self[0] * v[1] - self[1] * v[0], ]) } #[inline] pub fn make_unit_vector(&mut self) { let k = 1.0f64 / (self[0] * self[0] + self[1] * self[1] + self[2] * self[2]); self[0] *= k; self[1] *= k; self[2] *= k; } #[inline] pub fn unit_vector(&self) -> Vec3 { let length = self.length(); Vec3([self[0] / length, self[1] / length, self[2] / length]) } } impl Add for Vec3 { type Output = Vec3; fn add(self, o: Vec3) -> Vec3 { Vec3([self[0] + o[0], self[1] + o[1], self[2] + o[2]]) } } impl AddAssign for Vec3 { fn add_assign(&mut self, o: Vec3) { self.0[0] += o.0[0]; self.0[1] += o.0[1]; self.0[2] += o.0[2]; } } impl Sub for Vec3 { type Output = Vec3; fn sub(self, o: Vec3) -> Vec3 { Vec3([self[0] - o[0], self[1] - o[1], self[2] - o[2]]) } } impl SubAssign for Vec3 { fn sub_assign(&mut self, o: Vec3) { self[0] -= o[0]; self[1] -= o[1]; self[2] -= o[2]; } } impl Neg for Vec3 { type Output = Vec3; fn neg(self) -> Vec3 { Vec3([-self[0], -self[1], -self[2]]) } } impl MulAssign<Vec3> for Vec3 { fn mul_assign(&mut self, o: Vec3) { self[0] *= o[0]; self[1] *= o[1]; self[2] *= o[2]; } } impl MulAssign<f64> for Vec3 { fn mul_assign(&mut self, o: f64) { self[0] *= o; self[1] *= o; self[2] *= o; } } impl Mul<f64> for Vec3 { type Output = Vec3; fn mul(self, o: f64) -> Vec3 { Vec3([self[0] * o, self[1] * o, self[2] * o]) } } impl Mul<Vec3> for Vec3 { type Output = Vec3; fn mul(self, o: Vec3) -> Vec3 { Vec3([self[0] * o[0], self[1] * o[1], self[2] * o[2]]) } } impl Div<Vec3> for Vec3 { type Output = Vec3; fn div(self, o: Vec3) -> Vec3 { Vec3([self[0] / o[0], self[1] / o[1], self[2] / o[2]]) } } impl Div<f64> for Vec3 { type Output = Vec3; fn div(self, o: f64) -> Vec3 { let o = 1.0 / o; Vec3([self[0] * o, self[1] * o, self[2] * o]) } } impl DivAssign<f64> for Vec3 { fn div_assign(&mut self, o: f64) { let o = 1.0 / o; self.0[0] *= o; self.0[1] *= o; self.0[2] *= o; } } impl Index<usize> for Vec3 { type Output = f64; fn index(&self, q: usize) -> &f64 { &self.0[q] } } impl IndexMut<usize> for Vec3 { fn index_mut(&mut self, q: usize) -> &mut f64 { &mut self.0[q] } } impl Display for Vec3 { fn fmt(&self, f: &mut Formatter) -> FmtResult { f.write_fmt(format_args!("{} {} {}", self[0], self[1], self[2])) } }
use crate::prelude::*; #[derive(NativeClass)] #[inherit(Node)] pub struct DodgeTheCreepsInstance { engine: RPopsEngine<Renderables>, } #[methods] impl DodgeTheCreepsInstance { fn _init(owner: Node) -> Self { let mut instance = DodgeTheCreepsInstance { engine: RPopsEngine::<Renderables>::new(owner) }; // Add systems instance.engine.set_systems(create_systems()); // Add resources let renderables = Models::<Renderables>::default(); instance.engine.resources.insert(load_renderables(renderables)); instance } #[export] fn _ready(&mut self, _owner: Node) { // Call engine _ready self.engine._ready(_owner); use CreatureRenderables::*; let renderables = self.engine.resources.get::<Models<Renderables>>().unwrap(); let player = renderables.data_from_t(&Renderables::Creatures(Player)).unwrap(); self.engine.world.insert( (), (0..1).map(|_| ( Renderable { index: player.1, template: player.0 }, GDSpatial, Position { x: 240f32, y: 450f32, rotation: euclid::Angle::radians(0f32) }, TakesInput { speed: 400f32 / 60f32 }, Velocity::default(), Collider { width: 25.0, height: 25.0, offset_x: 0.0, offset_y: -2.5}, PlayerComp { }, )) ); } #[export] fn _physics_process(&mut self, owner: Node, delta: f64) { self.engine._physics_process(owner, delta); } } // Function that registers all exposed classes to Godot fn init(handle: gdnative::init::InitHandle) { handle.add_class::<DodgeTheCreepsInstance>(); } // macros that create the entry-points of the dynamic library. godot_gdnative_init!(); godot_nativescript_init!(init); godot_gdnative_terminate!();
use ggez::{self, GameResult, graphics}; use gui; const CAPTURE_MESSAGE: &'static str = "You were captured!"; pub struct CaptureGui; impl gui::Gui for CaptureGui { fn update(&mut self, _mouse_x: f32, _mouse_y: f32) -> GameResult<()> { Ok(()) } fn draw(&mut self, ctx: &mut ggez::Context, font: &graphics::Font, _mouse_x: f32, _mouse_y: f32) -> GameResult<()> { gui::draw_rectangle(ctx, graphics::Point2::new(0.0, 0.0), graphics::Point2::new(::SCALED_SIZE.0, ::SCALED_SIZE.1), graphics::Color::new(0.1, 0.1, 0.1, 0.8))?; let text = graphics::Text::new(ctx, CAPTURE_MESSAGE, font)?; let text_width = text.width() as f32; let text_height = text.height() as f32; graphics::draw_ex(ctx, &text, graphics::DrawParam { src: graphics::Rect::one(), dest: graphics::Point2::new((::SCREEN_SIZE.0 as f32 - text_width) / 2.0, (::SCREEN_SIZE.1 as f32 - text_height) / 2.0), rotation: 0.0, scale: graphics::Point2::new(1.0, 1.0), offset: graphics::Point2::new(0.0, 0.0), shear: graphics::Point2::new(0.0, 0.0), color: None, }); Ok(()) } fn mouse_pressed(&mut self, _mouse_x: f32, _mouse_y: f32) {} fn mouse_released(&mut self, _mouse_x: f32, _mouse_y: f32) {} }
mod structure; mod function; mod scene; mod object; pub use scene::Scene; pub use object::Object; use std::env; fn main() { let args: Vec<String> = env::args().collect(); match args.len() { 1 => { eprintln!("Usage: {} scene.json", args[0]); }, _ => { let mut scene = Scene::load(args[1].as_str()); println!("{}", scene.objects.len()); scene.render(); } } }
pub fn diff(f: &dyn Fn(f64)->f64, x: f64, h: f64) -> f64 { return (f(x+h)-f(x-h))/(2.0*h); } pub fn diffn(n: u32, f: &dyn Fn(f64)->f64, x: f64, h: f64) -> f64 { if n==0 { return f(x); }else if n==1 { return diff(f,x,h); }else{ return (diffn(n-1,f,x+h,h)-diffn(n-1,f,x-h,h))/(2.0*h); } }
use std::fmt; #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; pub struct MemoryStats { allocated: Bytes, resident: Bytes, } impl MemoryStats { pub fn current() -> MemoryStats { jemalloc_ctl::epoch::advance().unwrap(); MemoryStats { allocated: Bytes(jemalloc_ctl::stats::allocated::mib().unwrap().read().unwrap()), resident: Bytes(jemalloc_ctl::stats::resident::mib().unwrap().read().unwrap()), } } } impl fmt::Display for MemoryStats { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!( fmt, "{} allocated {} resident", self.allocated, self.resident, ) } } #[derive(Default)] struct Bytes(usize); impl fmt::Display for Bytes { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let bytes = self.0; if bytes < 4096 { return write!(f, "{} bytes", bytes); } let kb = bytes / 1024; if kb < 4096 { return write!(f, "{}kb", kb); } let mb = kb / 1024; write!(f, "{}mb", mb) } } impl std::ops::AddAssign<usize> for Bytes { fn add_assign(&mut self, x: usize) { self.0 += x; } }
use std::collections::HashSet; use std::sync::Arc; use chrono::{Duration, Utc}; use true_layer::{Client as TrueLayerClient, Transaction}; use crate::{db, Db}; const FIVE_MINS: std::time::Duration = std::time::Duration::from_secs(300); pub fn start_worker(db: Db, true_layer: Arc<TrueLayerClient>) { tokio::task::spawn(worker(db, true_layer)); } async fn worker(db: Db, true_layer: Arc<TrueLayerClient>) { loop { if let Err(e) = sync_transactions(&db, true_layer.as_ref()).await { log::error!("sync failed: {}", e); } tokio::time::delay_for(FIVE_MINS).await; } } async fn sync_transactions(db: &Db, true_layer: &TrueLayerClient) -> anyhow::Result<()> { let today = Utc::now().date().and_hms(0, 0, 0); for account in db::accounts::all(&db).await? { if db::transactions::has_any(db, &account.id).await? { log::info!( "syncing transactions since {} for account '{}'", today, account.id ); let saved = db::transactions::ids_after(&db, &account.id, today).await?; let new = true_layer .transactions(&account.id, today, Utc::now()) .await?; if changed(&new, saved) { log::info!( "changes detected for account '{}', refreshing transactions", account.id ); let new = new .into_iter() .map(|t| true_layer_to_db(t, &account.id)) .collect::<Vec<_>>(); db::transactions::delete_after(&db, &account.id, today).await?; db::transactions::insert_many(&db, &new).await?; log::info!("{} transactions inserted into db", new.len()); } else { log::info!( "no changes detected for account '{}', nothing to do", account.id, ); } } else { log::info!( "first sync for account '{}', fetching all transactions", account.id ); let to = Utc::now(); let from = to - Duration::days(365 * 6); let transactions = true_layer .transactions(&account.id, from, to) .await? .into_iter() .map(|t| db::transactions::Transaction { id: t.transaction_id, account_id: account.id.to_owned(), timestamp: t.timestamp, amount: t.amount, currency: t.currency, transaction_type: Some(t.transaction_type), category: Some(t.transaction_category), description: Some(t.description), merchant_name: t.merchant_name, }) .collect::<Vec<_>>(); db::transactions::insert_many(db, &transactions).await?; log::info!("{} transactions inserted into db", transactions.len()); } } Ok(()) } fn changed(new: &[Transaction], old: Vec<String>) -> bool { if new.len() != old.len() { return true; } let mut ids = HashSet::new(); for id in old { ids.insert(id); } for t in new { if !ids.contains(&t.transaction_id) { return true; } } false } fn true_layer_to_db(t: Transaction, account: &str) -> db::transactions::Transaction { db::transactions::Transaction { id: t.transaction_id, account_id: account.to_owned(), timestamp: t.timestamp, amount: t.amount, currency: t.currency, transaction_type: Some(t.transaction_type), category: Some(t.transaction_category), description: Some(t.description), merchant_name: t.merchant_name, } }
use crow::Context; use crow_anim::AnimationStorage; use crate::{ config::GameConfig, data::Components, environment::{World, WorldData}, input::InputState, save::SaveData, systems::Systems, time::Time, }; pub struct Ressources { pub input_state: InputState, pub time: Time, pub config: GameConfig, pub pressed_space: Option<JumpBuffer>, pub animation_storage: AnimationStorage, pub world: World, pub fadeout: Option<Fadeout>, pub delayed_actions: Vec<DelayedAction>, pub last_save: SaveData, pub debug_draw: bool, } impl Ressources { pub fn new(config: GameConfig, world_data: WorldData, last_save: SaveData) -> Self { Ressources { input_state: InputState::new(), time: Time::new(config.fps), config, pressed_space: None, animation_storage: AnimationStorage::new(), world: World::new(world_data), fadeout: None, delayed_actions: Vec::new(), last_save, debug_draw: false, } } pub fn reset(&mut self) { self.fadeout = None; self.delayed_actions.clear(); self.world.reset(); } } pub struct JumpBuffer(pub u8); #[derive(Default, Debug, Clone)] pub struct Fadeout { pub current: f32, pub frames_left: usize, } pub type Action = dyn FnOnce( &mut Context, &mut Systems, &mut Components, &mut Ressources, ) -> Result<(), crow::Error>; pub struct DelayedAction { pub frames_left: usize, pub action: Box<Action>, }
fn get_type_name<T>(_: &T) -> String { String::from(format!("{:?}", std::any::type_name::<T>())) } fn hello_world() -> String { "Hello World".to_string() } fn main() { let s: String = hello_world(); println!("{}", &s); let t = get_type_name(&s); println!("typeof \"{}\" -> {}", &s, &t); }
use std::collections::HashSet; use std::iter::FromIterator; use std::sync::mpsc::channel; use std::time::Duration; use timely::dataflow::channels::pact::Pipeline; use timely::dataflow::operators::Operator; use declarative_dataflow::binding::Binding; use declarative_dataflow::plan::{Hector, Implementable, Union}; use declarative_dataflow::server::Server; use declarative_dataflow::timestamp::Time; use declarative_dataflow::{Aid, Datom, Plan, Rule, Value}; use declarative_dataflow::{AttributeConfig, IndexDirection, QuerySupport}; use Value::{Eid, Number, String}; struct Case { description: &'static str, plan: Plan<Aid>, transactions: Vec<Vec<Datom<Aid>>>, expectations: Vec<Vec<(Vec<Value>, u64, isize)>>, } fn dependencies(case: &Case) -> HashSet<Aid> { let mut deps = HashSet::new(); for binding in case.plan.into_bindings().iter() { if let Binding::Attribute(binding) = binding { deps.insert(binding.source_attribute.clone()); } } deps } fn run_cases(mut cases: Vec<Case>) { for case in cases.drain(..) { timely::execute_directly(move |worker| { let mut server = Server::<Aid, u64, u64>::new(Default::default()); let (send_results, results) = channel(); dbg!(case.description); let mut deps = dependencies(&case); let plan = case.plan.clone(); for tx in case.transactions.iter() { for datum in tx { deps.insert(datum.1.clone()); } } worker.dataflow::<u64, _, _>(|scope| { for dep in deps.iter() { let config = AttributeConfig { trace_slack: Some(Time::TxId(1)), query_support: QuerySupport::AdaptiveWCO, index_direction: IndexDirection::Both, ..Default::default() }; server.create_attribute(scope, dep.clone(), config).unwrap(); } server .test_single(scope, Rule::named("query", plan)) .inner .sink(Pipeline, "Results", move |input| { input.for_each(|_time, data| { for datum in data.iter() { send_results.send(datum.clone()).unwrap() } }); }); }); let mut transactions = case.transactions.clone(); let mut next_tx = 0; for (tx_id, tx_data) in transactions.drain(..).enumerate() { next_tx += 1; server.transact(tx_data, 0, 0).unwrap(); server.advance_domain(None, next_tx).unwrap(); worker.step_while(|| server.is_any_outdated()); let mut expected: HashSet<(Vec<Value>, u64, isize)> = HashSet::from_iter(case.expectations[tx_id].iter().cloned()); for _i in 0..expected.len() { match results.recv_timeout(Duration::from_millis(400)) { Err(_err) => { panic!("No result."); } Ok(result) => { if !expected.remove(&result) { panic!("Unknown result {:?}.", result); } } } } match results.recv_timeout(Duration::from_millis(400)) { Err(_err) => {} Ok(result) => { panic!("Extraneous result {:?}", result); } } } }); } } #[test] fn or() { let data = vec![ Datom::add(1, ":name", String("Ivan".to_string())), Datom::add(1, ":age", Number(10)), Datom::add(2, ":name", String("Ivan".to_string())), Datom::add(2, ":age", Number(20)), Datom::add(3, ":name", String("Oleg".to_string())), Datom::add(3, ":age", Number(10)), Datom::add(4, ":name", String("Oleg".to_string())), Datom::add(4, ":age", Number(20)), Datom::add(5, ":name", String("Ivan".to_string())), Datom::add(5, ":age", Number(10)), Datom::add(6, ":name", String("Ivan".to_string())), Datom::add(6, ":age", Number(20)), ]; run_cases(vec![ Case { description: "[:find ?e :where (or [?e :name Oleg] [?e :age 10])]", plan: Plan::Union(Union { variables: vec![0], plans: vec![ Plan::Hector(Hector { variables: vec![0], bindings: vec![ Binding::attribute(0, ":name", 1), Binding::constant(1, String("Oleg".to_string())), ], }), Plan::Hector(Hector { variables: vec![0], bindings: vec![ Binding::attribute(0, ":age", 1), Binding::constant(1, Number(10)), ], }), ], }), transactions: vec![data.clone()], expectations: vec![vec![ (vec![Eid(1)], 0, 1), (vec![Eid(3)], 0, 1), (vec![Eid(4)], 0, 1), (vec![Eid(5)], 0, 1), ]], }, Case { description: "[:find ?e :where (or [?e :name Oleg] [?e :age 30])] (one branch empty)", plan: Plan::Union(Union { variables: vec![0], plans: vec![ Plan::Hector(Hector { variables: vec![0], bindings: vec![ Binding::attribute(0, ":name", 1), Binding::constant(1, String("Oleg".to_string())), ], }), Plan::Hector(Hector { variables: vec![0], bindings: vec![ Binding::attribute(0, ":age", 1), Binding::constant(1, Number(30)), ], }), ], }), transactions: vec![data.clone()], expectations: vec![vec![(vec![Eid(3)], 0, 1), (vec![Eid(4)], 0, 1)]], }, Case { description: "[:find ?e :where (or [?e :name Petr] [?e :age 30])] (both empty)", plan: Plan::Union(Union { variables: vec![0], plans: vec![ Plan::Hector(Hector { variables: vec![0], bindings: vec![ Binding::attribute(0, ":name", 1), Binding::constant(1, String("Petr".to_string())), ], }), Plan::Hector(Hector { variables: vec![0], bindings: vec![ Binding::attribute(0, ":age", 1), Binding::constant(1, Number(30)), ], }), ], }), transactions: vec![data.clone()], expectations: vec![vec![]], }, // @TODO must be able to identify the conflict between the two // constant bindings // // Case { // description: "[:find ?e :where [?e :name Ivan] (or [?e :name Oleg] [?e :age 10])] (join with 1 var)", // plan: Plan::Union(Union { // variables: vec![0], // plans: vec![ // Plan::Hector(Hector { // variables: vec![0], // bindings: vec![ // Binding::attribute(0, ":name", 1), // Binding::constant(1, String("Ivan".to_string())), // Binding::constant(1, String("Oleg".to_string())), // ], // }), // Plan::Hector(Hector { // variables: vec![0], // bindings: vec![ // Binding::attribute(0, ":name", 1), // Binding::constant(1, String("Ivan".to_string())), // Binding::attribute(0, ":age", 2), // Binding::constant(2, Number(10)), // ], // }), // ], // }), // transactions: vec![data.clone()], // expectations: vec![vec![ // (vec![Eid(1)], 0, 1), // (vec![Eid(5)], 0, 1), // ]], // }, Case { description: "[:find ?e :where [?e :age ?a] (or (and [?e :name Ivan] [1 :age a]) (and [?e :name Oleg] [2 :age a]))] (join with 2 vars)", plan: Plan::Union(Union { variables: vec![0], plans: vec![ Plan::Hector(Hector { variables: vec![0], bindings: vec![ Binding::attribute(0, ":age", 2), Binding::attribute(0, ":name", 1), Binding::constant(1, String("Ivan".to_string())), Binding::attribute(3, ":age", 2), Binding::constant(3, Eid(1)), ], }), Plan::Hector(Hector { variables: vec![0], bindings: vec![ Binding::attribute(0, ":age", 2), Binding::attribute(0, ":name", 1), Binding::constant(1, String("Oleg".to_string())), Binding::attribute(3, ":age", 2), Binding::constant(3, Eid(2)), ], }), ], }), transactions: vec![data.clone()], expectations: vec![vec![ (vec![Eid(1)], 0, 1), (vec![Eid(5)], 0, 1), (vec![Eid(4)], 0, 1), ]], }, ]); } #[test] fn or_join() { let data = vec![ Datom::add(1, ":name", String("Ivan".to_string())), Datom::add(1, ":age", Number(10)), Datom::add(2, ":name", String("Ivan".to_string())), Datom::add(2, ":age", Number(20)), Datom::add(3, ":name", String("Oleg".to_string())), Datom::add(3, ":age", Number(10)), Datom::add(4, ":name", String("Oleg".to_string())), Datom::add(4, ":age", Number(20)), Datom::add(5, ":name", String("Ivan".to_string())), Datom::add(5, ":age", Number(10)), Datom::add(6, ":name", String("Ivan".to_string())), Datom::add(6, ":age", Number(20)), ]; run_cases(vec![Case { description: "[:find ?e :where (or-join [?e] [?e :name ?n] (and [?e :age ?a] [?e :name ?n]))]", plan: Plan::Union(Union { variables: vec![0], plans: vec![ Plan::Hector(Hector { variables: vec![0], bindings: vec![Binding::attribute(0, ":name", 2)], }), Plan::Hector(Hector { variables: vec![0], bindings: vec![ Binding::attribute(0, ":age", 1), Binding::attribute(0, ":name", 2), ], }), ], }), transactions: vec![data.clone()], expectations: vec![vec![ (vec![Eid(1)], 0, 1), (vec![Eid(2)], 0, 1), (vec![Eid(3)], 0, 1), (vec![Eid(4)], 0, 1), (vec![Eid(5)], 0, 1), (vec![Eid(6)], 0, 1), ]], }]); }
use super::Square88; use itertools::*; pub const ALL_SQUARES: Square88 = Square88(0); pub const UNDEFINED_SQUARE: Square88 = Square88(0xFF); pub const A8: Square88 = Square88(0x0); pub const B8: Square88 = Square88(0x1); pub const C8: Square88 = Square88(0x2); pub const D8: Square88 = Square88(0x3); pub const E8: Square88 = Square88(0x4); pub const F8: Square88 = Square88(0x5); pub const G8: Square88 = Square88(0x6); pub const H8: Square88 = Square88(0x7); pub const A7: Square88 = Square88(0x10); pub const B7: Square88 = Square88(0x11); pub const C7: Square88 = Square88(0x12); pub const D7: Square88 = Square88(0x13); pub const E7: Square88 = Square88(0x14); pub const F7: Square88 = Square88(0x15); pub const G7: Square88 = Square88(0x16); pub const H7: Square88 = Square88(0x17); pub const A6: Square88 = Square88(0x20); pub const B6: Square88 = Square88(0x21); pub const C6: Square88 = Square88(0x22); pub const D6: Square88 = Square88(0x23); pub const E6: Square88 = Square88(0x24); pub const F6: Square88 = Square88(0x25); pub const G6: Square88 = Square88(0x26); pub const H6: Square88 = Square88(0x27); pub const A5: Square88 = Square88(0x30); pub const B5: Square88 = Square88(0x31); pub const C5: Square88 = Square88(0x32); pub const D5: Square88 = Square88(0x33); pub const E5: Square88 = Square88(0x34); pub const F5: Square88 = Square88(0x35); pub const G5: Square88 = Square88(0x36); pub const H5: Square88 = Square88(0x37); pub const A4: Square88 = Square88(0x40); pub const B4: Square88 = Square88(0x41); pub const C4: Square88 = Square88(0x42); pub const D4: Square88 = Square88(0x43); pub const E4: Square88 = Square88(0x44); pub const F4: Square88 = Square88(0x45); pub const G4: Square88 = Square88(0x46); pub const H4: Square88 = Square88(0x47); pub const A3: Square88 = Square88(0x50); pub const B3: Square88 = Square88(0x51); pub const C3: Square88 = Square88(0x52); pub const D3: Square88 = Square88(0x53); pub const E3: Square88 = Square88(0x54); pub const F3: Square88 = Square88(0x55); pub const G3: Square88 = Square88(0x56); pub const H3: Square88 = Square88(0x57); pub const A2: Square88 = Square88(0x60); pub const B2: Square88 = Square88(0x61); pub const C2: Square88 = Square88(0x62); pub const D2: Square88 = Square88(0x63); pub const E2: Square88 = Square88(0x64); pub const F2: Square88 = Square88(0x65); pub const G2: Square88 = Square88(0x66); pub const H2: Square88 = Square88(0x67); pub const A1: Square88 = Square88(0x70); pub const B1: Square88 = Square88(0x71); pub const C1: Square88 = Square88(0x72); pub const D1: Square88 = Square88(0x73); pub const E1: Square88 = Square88(0x74); pub const F1: Square88 = Square88(0x75); pub const G1: Square88 = Square88(0x76); pub const H1: Square88 = Square88(0x77); impl Iterator for Square88 { type Item = Square88; fn next(&mut self) -> Option<Self::Item> { if self.0 == 120 { None } else { if self.0 & 0x88 != 0 { self.0 += 8 } let copy = *self; self.0 += 1; Some(copy) } } } #[test] fn all_squares() { assert_eq!(ALL_SQUARES.collect_vec(), vec![A8, B8, C8, D8, E8, F8, G8, H8, A7, B7, C7, D7, E7, F7, G7, H7, A6, B6, C6, D6, E6, F6, G6, H6, A5, B5, C5, D5, E5, F5, G5, H5, A4, B4, C4, D4, E4, F4, G4, H4, A3, B3, C3, D3, E3, F3, G3, H3, A2, B2, C2, D2, E2, F2, G2, H2, A1, B1, C1, D1, E1, F1, G1, H1]); } #[test] fn invalid() { assert_eq!(UNDEFINED_SQUARE.is_valid(), false); } #[test] fn is_valid() { for s in ALL_SQUARES { assert_eq!(s.is_valid(), true); } }
pub struct Adjacent<I> { position: (usize, usize), h: usize, w: usize, direction: I, } impl<I> Adjacent<I> where I: Iterator<Item = (isize, isize)>, { pub fn new(position: (usize, usize), h: usize, w: usize, direction: I) -> Self { Self { position, h, w, direction, } } } impl<I> Iterator for Adjacent<I> where I: Iterator<Item = (isize, isize)>, { type Item = (usize, usize); fn next(&mut self) -> Option<(usize, usize)> { while let Some((di, dj)) = self.direction.next() { let (i, j) = self.position; let ni = i as isize + di; let nj = j as isize + dj; if 0 <= ni && ni < self.h as isize && 0 <= nj && nj < self.w as isize { return Some((ni as usize, nj as usize)); } } None } } fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let h: usize = rd.get(); let w: usize = rd.get(); let sy: usize = rd.get(); let sx: usize = rd.get(); let gy: usize = rd.get(); let gx: usize = rd.get(); let sy = sy - 1; let sx = sx - 1; let gy = gy - 1; let gx = gx - 1; let a: Vec<Vec<char>> = (0..h) .map(|_| { let s: String = rd.get(); s.chars().collect() }) .collect(); let inf = std::u64::MAX / 2; let mut d = vec![vec![inf; w]; h]; let mut q = std::collections::VecDeque::new(); d[sy][sx] = 0; q.push_back((sy, sx)); const D1: [(isize, isize); 4] = [(-1, 0), (1, 0), (0, -1), (0, 1)]; #[rustfmt::skip] const D2: [(isize, isize); 24] = [ (-2, -2), (-2, -1), (-2, 0), (-2, 1), (-2, 2), (-1, -2), (-1, -1), (-1, 0), (-1, 1), (-1, 2), ( 0, -2), ( 0, -1), ( 0, 1), ( 0, 2), ( 1, -2), ( 1, -1), ( 1, 0), ( 1, 1), ( 1, 2), ( 2, -2), ( 2, -1), ( 2, 0), ( 2, 1), ( 2, 2), ]; while let Some((y, x)) = q.pop_front() { for (ny, nx) in Adjacent::new((y, x), h, w, D1.iter().copied()) { if a[ny][nx] == '.' { if d[ny][nx] > d[y][x] { d[ny][nx] = d[y][x]; q.push_front((ny, nx)); } } } for (ny, nx) in Adjacent::new((y, x), h, w, D2.iter().copied()) { if a[ny][nx] == '.' { if d[ny][nx] > d[y][x] + 1 { d[ny][nx] = d[y][x] + 1; q.push_back((ny, nx)); } } } } let ans = d[gy][gx]; if ans < inf { println!("{}", ans); } else { println!("{}", -1); } } pub struct ProconReader<R: std::io::Read> { reader: R, } impl<R: std::io::Read> ProconReader<R> { pub fn new(reader: R) -> Self { Self { reader } } pub fn get<T: std::str::FromStr>(&mut self) -> T { use std::io::Read; let buf = self .reader .by_ref() .bytes() .map(|b| b.unwrap()) .skip_while(|&byte| byte == b' ' || byte == b'\n' || byte == b'\r') .take_while(|&byte| byte != b' ' && byte != b'\n' && byte != b'\r') .collect::<Vec<_>>(); std::str::from_utf8(&buf) .unwrap() .parse() .ok() .expect("Parse Error.") } }
// 栈(Stack)与堆(Heap) // 在 Rust 这样的系统编程语言中,值位于栈上海市堆上在更大程度上影响力语言的行为以及为何必须做出这样的抉择 // 栈和堆都是代码在运行时可供使用的内存,但是它们的结构不同,栈以放入值的顺序存储值并以相反顺序取出值, // 这叫做 后进先出(last in, first out),想象跌盘子,在顶部增加,从顶部拿走 // 增加数据叫做 进栈(pushing onto the stack),移除数据叫做 出栈(popping off the stack) // 栈的操作是十分快速的,这主要得益于它存取数据的方式:因为数据存取的位置总是在栈顶而不需要寻找一个位置存放或读取 // 另一个让操作栈快速的属性是,栈中的所有数据都必须占用已知且固定的大小 // 在编译是大小未知或大小可能变化的数据,要改为存储在堆上 // 堆是缺乏租住的:当向堆放入数据时,你要请求一定大小的空间,操作系统在堆的某处找到一块足够大的空位,然后标记为已使用 // 并返回一个表示该位置地址的 指针(pointer),这个过程叫做 在堆上分配内存(allocating on the heap), // 有时简称为 分配(allocating) // 将数据推入栈中并不认为是分配,因为指针的大小是已知并且是固定的, // 你可以将指针存储在栈上,不过当实际需要数据时,必须访问指针 // 跟踪哪部分代码正在使用堆上的哪些数据,最大限度的减少堆上的重复数据的数量,以及清理堆上不再使用的数据确保不会耗尽空间 // 这些问题正是所有权(ownership)系统要处理的 /// 所有权的规则: /// 1.Rust 中的每一个值都有一个被称为其 所有者(owner)的变量 Each value in Rust has a variable that's called its owner /// 2.值有且只有一个所有者 There can only be one owner at a time /// 3.当所有者(变量)离开作用域,这个值被丢弃 When the owner goes out of scope, the value will be dropped mod strings; fn main() { // variable scope { // 变量 s 绑定到一个字符串字面值,这个值是硬编码到程序代码中的, // 这个变量从声明的点开始到当前 作用域 结束时都说有效的 let s = "hello"; } // {} 就是变量 s 的作用域 // 复习: // 简单变量类型: i32, u32, usize, f32, char字符, &str字符串, bool布尔, tuple元组, array数组 // 简单变量类型存储在栈上,当离开作用域时值被移出栈 // 使用 String::from 从字面值创建String类型 // 字符串字面值在编译期就知道其内容(不可变),所以文本被直接硬编码进最终的可执行文件中,这使得字符串字面值快速高效 // 对于 String 类型,需要支持可变、可增长的文本片段,需要在堆上分配一块在编译时未知大小的内存来存放,这意味着: // 1.必须在运行时向操作系统请求内存 // 2.需要一个当我们处理完 String 时将内存返回给操作系统的方法 // Rust: 内存在拥有它的变量离开作用域后就被自动释放,Rust 为我们自动调用了一个特殊的函数 drop { let mut s = String::from("hello"); // 从此处起 s 是有效的 s.push_str(", world!"); // 使用 s println!("{}", s); // 使用 s } // 此作用域已结束,s 不再有效 // 在 C++ 中,这种 item 在生命周期结束是释放资源的模式被称作 资源获取即初始化(Resource Acquisition Is Initialization, RAII) // 这个模式对编写 Rust 代码的方式有着深远的影响,现在它看起来很简单, // 不过在复杂的场景下代码的行为可能是不可预测的,比如当多个变量使用在堆上分配的内存时。。。 // 变量和数据交互的方式1:移动(move) let x = 5; // 将 5 绑定到 x let y = x; // 生成一个值 x 的拷贝并绑定到 y,因为整数是已知固定大小的简单值,所以这两个5被放入了栈中 println!("{}", x); let s1 = String::from("hello"); let s2 = s1; // 我们从栈上拷贝了s1的ptr、len、capacity,但并没有复制ptr所指向的堆上数据 // 这看上去像其他语言的浅拷贝,但是 Rust 会将第一个变量置为无效,所以这个操作被称为 移动(move) // 这里隐含了一个设计选择:Rust 永远不会自动创建数据的"深拷贝" // println!("{}", s1); // s1 is moved to s2, s1 is out of scope here // 当 s2 和 s1 离开作用域,他们都会尝试释放相同的内存,这是一个叫做 二次释放(double free)的错误 // 两次释放相同的内存会导致内存污染,他可能导致潜在的安全漏洞 // String // name | value index | value // ptr ------> 0 h // len 5 1 e // capacity 5 2 l // 3 l // 4 l // 变量和数据交互的方式2:克隆(clone) // 如果我们确实需要深度复制 String 中堆上的数据而不仅仅是栈上的数据,可以使用一个 clone 的通用函数 let s1 = String::from("hello"); let s2 = s1.clone(); // 当出现 clone 调用时,你知道一些特定的代码被执行并且这些代码可能相当消耗资源 println!("s1 = {}, s2 = {}", s1, s2); // 这里没有调用clone,原因是像整型这样的在编译是已知大小的类型被整个存储在栈上,所以值的拷贝是快速的 // 这意味着没有理由在创建变量y后使x无效,所以这里没有深浅拷贝的区别 let x = 5; let y = x; println!("x = {}, y = {}", x, y); // Rust 有一个叫做 Copy trait的特殊注解,可以用在类似整型这样的存储在栈上的类型上 // 如果一个类型拥有 Copy trait,一个旧的变量在将其赋值给其他变量后仍然可用 // 如下是一些 Copy 的类型: // 所有整数类型,如 u32 // 布尔类型 bool // 所有浮点数类型,如 f64 // 字符类型,char // 元组 tuple 当且仅当其包含的类型也都是 Copy 的时候,如(i32, i32),但(i32, String)就不是 // 所有权与函数 // 将值传递给函数在语义上与给变量赋值相似,向函数传值可能会移动或复制,就像赋值语句一样 let s = String::from("hello"); takes_ownership(s); // s的值移动到函数里 ... // 所以到这一行不再有效 // print!("{}", s); // error: value borrowed here after move let x = 5; // x 进入作用域 makes_copy(x); // 但 i32 是 Copy 的,所以在后面可以继续使用 x // 返回值与作用域 返回值也可以转移所有权 let s1 = gives_ownership(); // gives_ownership 将返回值移給 s1 let s2 = String::from("hello"); // s2 进入作用域 /* 变量的所有权总是遵循相同的模式:将值赋给另一个变量时移动它。 当持有堆中数据值的变量离开作用域时,其值将通过 drop 被清理掉,除非数据被移动到另一个变量所有 在每一个函数中多获取所有权并接着返回所有权有些啰嗦... 如果我们想要函数使用一个值但不获取所有权该怎么办呢?每次传进去再返回来就有点烦了。。 我们可以使用元组返回多个值,但显得形式主义,对此,Rust 提供了一个功能,叫做 引用(references) */ let s1 = String::from("hello"); let (s2, len) = calculate_length(s1); println!("The length of '{}' is {}.", s2, len); let s1 = String::from("hello"); // 使用 & 传递引用,它们允许你使用值但不获取其所有权 // &s1 语法让我们创建一个 指向 值 s1 的应用,但是并不拥有它 // 因为不拥有这个值,当引用离开作用域是其指向的值也不会被丢弃,仅仅丢掉该引用本身 // (如果引用的值比引用被提前 drop 编译器如何捕捉到?) let len = calculate_length2(&s1); println!("The length of '{}' is {}.", s1, len); /* s s1 name | value name | value index | value ptr -------->ptr --------> 0 h len 5 1 e capacity 5 2 l 3 l 4 o */ // 可变引用:必须是 mut 类型,必须创建一个 &mut 的可变引用 let mut s = String::from("hello"); change2(&mut s); println!("{}", s); // 可变引用有一个很大的限制:在特定作用域中的特定数据有且只有一个可变引用 // 这个限制的好处是 Rust 可以在编译时就避免数据竞争:比如 // 两个或多个指针访问同一数据 // 至少有一个指针被用来写入数据 // 没有同步数据访问的机制 // 数据竞争会导致未定义行为,难以在运行时追踪,并且难以诊断和修复 // Rust 避免了这种情况的发生,因为它甚至不会编译存在数据竞争的代码! //let r1 = &mut s; //let r2 = &mut s; // error: second mutable borrow occurs here //println!("{}, {}", r1, r2); let mut s = String::from("hello"); { let r1 = &mut s; } // r1 在这里离开了作用域,所以此后又可以新建可变引用了 let r2 = &mut s; // 类似的规则也存在与同时使用可变与不可变引用中:即不能在特定作用域特定数据同时存在可变引用与不可变引用 //let r1 = &s; // no problem //let r2 = &s; // no problem //let r3 = &mut s; // big problem! cannot borrow `s` mutable because it is also borrowed as immutable //println!("{}, {}, {}", r1, r2, r3); let r1 = &s; // 一个引用的作用域从声明的地方开始一直持续到最后一次使用为止 let r2 = &s; println!("{} and {}", r1, r2); // 函数入参,移动 // 此位置之后 r1 和 r2 不再使用(则r1 r2作用域到此为止) let r3 = &mut s; // 没问题 change2(r3); println!("{}", r3); // println!("{}", r1); // 若在此处用到r1,则r1的作用域到这一行,就会包含了&mut的作用域,从而报错 // cannot borrow `s` as mutable because it is also borrowed as immutable // 悬垂引用(Dangling References)释放了内存后依然有位置保留了指向它的指针 // Rust 编译器确保引用永远也不会编程悬垂状态: // 当你拥有一些数据的引用,编译器确保数据不会在其引用之前离开作用域 //let reference_to_nothing = dangle(); // missing lifetime specifier /* 复习: 对特定作用域特定数据,要么只能有一个可变引用,要么只能有多个不可变引用 引用必须总是有效(不会有悬垂指针) */ // 另一个不拥有所有权的数据类型是 slice // slice 允许你引用集合中一段连续的元素序列,而不用引用整个集合(很像golang里面的slice) let s = String::from("hello"); let hello = &s[0..5]; // .. 表示[),如果需要表示闭区间,需要使用 ..= //let world = &s[6..=11]; // thread main panicked at 'byte index 6 is out of bounds of `hello` let slice = &s[0..=2]; let slice = &s[..=2]; let slice = &s[3..s.len()]; let slice = &s[..s.len()]; let slice = &s[..]; // 字符串 slice range的索引必须位于有效的UTF-8字符边界内, // 如果尝试从一个多字节字符的中间位置创建字符串slice,则程序将会因错误而退出 // 字符串 slice 的类型声明协作 &str let s = String::from("hello world"); let world = first_word(&s); // s.clear(); // error! 当拥有某值的不可变引用时,就不能再获取一个可变引用,此处 clear 需要清空 String,它尝试获取一个可变引用,它失败了 // Rust 不仅使得我们的API简单易用,也在编译时就消除了一整类的错误! // println!("the first world is: {}", world); // 字符串字面值就是 slice,字符串字面值存在二进制文件中,它是一个指向二进制程序中特定位置的 slice, // 这也是为什么字面值是不可变的,&str 是一个不可变引用 let my_string = String::from("hello world"); let word = first_word(&my_string[..]); let s = "Hello world!"; let word = first_word(&s[..]); let word = first_word(s); let a = [1, 2, 3, 4, 5]; let slice = &a[1..3]; println!("slice: {:?}", slice); // [2, 3] // 所有权系统影响了 Rust 中很多其他部分的工作方式 } // 返回单词结尾的索引 //fn first_word(s: &String) -> usize { // let bytes = s.as_bytes(); // 转化为字节数组 // for (i, &item) in bytes.iter().enumerate() { // if item == b' ' { // return i; // } // } // s.len() //} // fn first_word(s: &str) -> &str {} // 定义一个获取字符串 slice 而不是 String引用 的函数使得我们的API更具统一并且不会丢失任何内容 //fn first_word(s: &String) -> &str { fn first_word(s: &str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[..i]; } } return &s[..]; } //fn dangle() -> &String { // let s = String::from("hello"); // &s //} // 在这里 s 离开作用域并被 drop,此时 s 的引用的生命周期不能长于 s,编译不过 // help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from fn no_dangle() -> String { let s = String::from("hello"); s // 返回 s,所有权被移交,所以没有值被释放 } // 正如变量默认是不可变的,引用也一样,默认不允许修改引用的值 //fn change(some_string: &String) { // some_string.push_str(", world"); // cannot borrow immutable variable as mutable //} fn change2(some_string: &mut String) { some_string.push_str(", world"); } fn calculate_length(s: String) -> (String, usize) { // 获取所有权,再返回所有权 let length = s.len(); (s, length) } // 我们将获取引用作为函数参数称为 借用(borrowing) fn calculate_length2(s: &String) -> usize { // 以一个对象的引用作为参数而不是获取值的所有权,s 是对 String 的引用 s.len() } // 这里 s 离开了作用域,但因为它并不拥有其引用值的所有权,所以其引用值不会发生 drop fn gives_ownership() -> String { // gives_ownership 将返回值移动给调用它的函数 let some_string = String::from("hello"); // some_string 进入作用域 some_string // 返回 some_string 并移出给被调用的函数 } // takes_and_give_back 将传入字符串并返回该值 fn takes_and_gives_back(a_string: String) -> String { // a_string 进入作用域 a_string // 返回 a_string 并移出给调用的函数 } fn takes_ownership(some_string: String) { // some_string 进入作用域 println!("{}", some_string); } // 这里 some_string 移出作用域并调用 drop 方法,占用的内存被释放 fn makes_copy(some_integer: i32) { // some_integer 进入作用域 println!("{}", some_integer) } // 这里 some_integer 移出作用域,不会有特殊操作(可理解为函数出栈起参数自动被弹出?)
extern crate navitia_model; extern crate serde_json; use navitia_model::collection::{Collection, Idx, Id}; use navitia_model::relations::IdxSet; use navitia_model::{GetCorresponding, PtObjects}; fn get<T, U>(idx: Idx<T>, collection: &Collection<U>, objects: &PtObjects) -> Vec<String> where U: Id<U>, IdxSet<T>: GetCorresponding<U>, { let from = [idx].iter().cloned().collect(); let to = objects.get_corresponding(&from); to.iter().map(|idx| collection[*idx].id().to_string()).collect() } fn main() { let args: Vec<_> = std::env::args().collect(); let objects = navitia_model::ntfs::read("."); let from = objects.lines.get_idx(&args[1]).unwrap(); println!("commercial_modes: {:?}", get(from, &objects.commercial_modes, &objects)); println!("physical_modes: {:?}", get(from, &objects.physical_modes, &objects)); //let json = serde_json::to_string(&objects).unwrap(); //println!("{}", json); }
use crate::{CoordinateType, Line, LineString, MultiPolygon, Polygon, Rect, Triangle}; use num_traits::Float; use crate::algorithm::winding_order::twice_signed_ring_area; /// Signed planar area of a geometry. /// /// # Examples /// /// ``` /// use geo::polygon; /// use geo::algorithm::area::Area; /// /// let mut polygon = polygon![ /// (x: 0., y: 0.), /// (x: 5., y: 0.), /// (x: 5., y: 6.), /// (x: 0., y: 6.), /// (x: 0., y: 0.), /// ]; /// /// assert_eq!(polygon.area(), 30.); /// /// polygon.exterior_mut(|line_string| { /// line_string.0.reverse(); /// }); /// /// assert_eq!(polygon.area(), -30.); /// ``` pub trait Area<T> where T: CoordinateType, { fn area(&self) -> T; } // Calculation of simple (no interior holes) Polygon area pub(crate) fn get_linestring_area<T>(linestring: &LineString<T>) -> T where T: Float, { twice_signed_ring_area(linestring) / (T::one() + T::one()) } impl<T> Area<T> for Line<T> where T: CoordinateType, { fn area(&self) -> T { T::zero() } } impl<T> Area<T> for Polygon<T> where T: Float, { fn area(&self) -> T { self.interiors() .iter() .fold(get_linestring_area(self.exterior()), |total, next| { total - get_linestring_area(next) }) } } impl<T> Area<T> for MultiPolygon<T> where T: Float, { fn area(&self) -> T { self.0 .iter() .fold(T::zero(), |total, next| total + next.area()) } } impl<T> Area<T> for Rect<T> where T: CoordinateType, { fn area(&self) -> T { self.width() * self.height() } } impl<T> Area<T> for Triangle<T> where T: Float, { fn area(&self) -> T { self.to_lines() .iter() .fold(T::zero(), |total, line| total + line.determinant()) / (T::one() + T::one()) } } #[cfg(test)] mod test { use crate::algorithm::area::Area; use crate::{line_string, polygon, Coordinate, Line, MultiPolygon, Polygon, Rect, Triangle}; // Area of the polygon #[test] fn area_empty_polygon_test() { let poly: Polygon<f32> = polygon![]; assert_relative_eq!(poly.area(), 0.); } #[test] fn area_one_point_polygon_test() { let poly = polygon![(x: 1., y: 0.)]; assert_relative_eq!(poly.area(), 0.); } #[test] fn area_polygon_test() { let polygon = polygon![ (x: 0., y: 0.), (x: 5., y: 0.), (x: 5., y: 6.), (x: 0., y: 6.), (x: 0., y: 0.) ]; assert_relative_eq!(polygon.area(), 30.); } #[test] fn rectangle_test() { let rect1: Rect<f32> = Rect::new(Coordinate { x: 10., y: 30. }, Coordinate { x: 20., y: 40. }); assert_relative_eq!(rect1.area(), 100.); let rect2: Rect<i32> = Rect::new(Coordinate { x: 10, y: 30 }, Coordinate { x: 20, y: 40 }); assert_eq!(rect2.area(), 100); } #[test] fn area_polygon_inner_test() { let poly = polygon![ exterior: [ (x: 0., y: 0.), (x: 10., y: 0.), (x: 10., y: 10.), (x: 0., y: 10.), (x: 0., y: 0.) ], interiors: [ [ (x: 1., y: 1.), (x: 2., y: 1.), (x: 2., y: 2.), (x: 1., y: 2.), (x: 1., y: 1.), ], [ (x: 5., y: 5.), (x: 6., y: 5.), (x: 6., y: 6.), (x: 5., y: 6.), (x: 5., y: 5.) ], ], ]; assert_relative_eq!(poly.area(), 98.); } #[test] fn area_multipolygon_test() { let poly0 = polygon![ (x: 0., y: 0.), (x: 10., y: 0.), (x: 10., y: 10.), (x: 0., y: 10.), (x: 0., y: 0.) ]; let poly1 = polygon![ (x: 1., y: 1.), (x: 2., y: 1.), (x: 2., y: 2.), (x: 1., y: 2.), (x: 1., y: 1.) ]; let poly2 = polygon![ (x: 5., y: 5.), (x: 6., y: 5.), (x: 6., y: 6.), (x: 5., y: 6.), (x: 5., y: 5.) ]; let mpoly = MultiPolygon(vec![poly0, poly1, poly2]); assert_relative_eq!(mpoly.area(), 102.); assert_relative_eq!(mpoly.area(), 102.); } #[test] fn area_line_test() { let line1 = Line::new(Coordinate { x: 0.0, y: 0.0 }, Coordinate { x: 1.0, y: 1.0 }); assert_relative_eq!(line1.area(), 0.); } #[test] fn area_triangle_test() { let triangle = Triangle( Coordinate { x: 0.0, y: 0.0 }, Coordinate { x: 1.0, y: 0.0 }, Coordinate { x: 0.0, y: 1.0 }, ); assert_relative_eq!(triangle.area(), 0.5); let triangle = Triangle( Coordinate { x: 0.0, y: 0.0 }, Coordinate { x: 0.0, y: 1.0 }, Coordinate { x: 1.0, y: 0.0 }, ); assert_relative_eq!(triangle.area(), -0.5); } }
#[cfg(feature = "nightly")] pub use proc_macro::Diagnostic; use proc_macro2::{Span, TokenStream}; pub trait EmitErrorExt { fn emit_error(self) -> TokenStream; } impl EmitErrorExt for Result<TokenStream, Error> { fn emit_error(self) -> TokenStream { self.unwrap_or_else(Error::emit) } } #[cfg(feature = "nightly")] pub struct Error(Diagnostic); #[cfg(feature = "nightly")] impl Error { pub fn help<T: Into<String>>(self, msg: T) -> Self { Self(self.0.help(msg)) } pub fn note<T: Into<String>>(self, msg: T) -> Self { Self(self.0.note(msg)) } pub fn emit(self) -> TokenStream { self.0.emit(); TokenStream::new() } } #[cfg(not(feature = "nightly"))] pub struct Error { span: Span, msg: String, } #[cfg(not(feature = "nightly"))] impl Error { pub fn help<T: Into<String>>(mut self, msg: T) -> Self { self.msg += "\n"; self.msg += &msg.into(); self } pub fn note<T: Into<String>>(self, msg: T) -> Self { self.help(msg) } pub fn emit(self) -> TokenStream { syn::Error::new(self.span, self.msg).into_compile_error() } } #[cfg(feature = "nightly")] pub struct Warning(Diagnostic); #[cfg(feature = "nightly")] impl Warning { pub fn emit(self) { self.0.emit(); } } #[cfg(not(feature = "nightly"))] pub struct Warning { msg: String, } #[cfg(not(feature = "nightly"))] impl Warning { pub fn emit(self) { eprintln!("{}", self.msg) } } pub trait DiagnosticShim { /// Create a diagnostic fn error<T: Into<String>>(self, msg: T) -> Error; fn warning<T: Into<String>>(self, msg: T) -> Warning; } #[cfg(feature = "nightly")] impl DiagnosticShim for Span { fn error<T: Into<String>>(self, msg: T) -> Error { Error(self.unstable().error(msg)) } fn warning<T: Into<String>>(self, msg: T) -> Warning { Warning(self.unstable().warning(msg)) } } #[cfg(not(feature = "nightly"))] impl DiagnosticShim for Span { fn error<T: Into<String>>(self, msg: T) -> Error { Error { msg: msg.into(), span: self, } } fn warning<T: Into<String>>(self, msg: T) -> Warning { Warning { msg: msg.into() } } }
extern crate serde; mod test_utils; // use flexi_logger::LoggerHandle; use hdbconnect_async::{HdbResult, HdbReturnValue, HdbValue}; // use log::{debug, info}; #[tokio::test] async fn test_051_management_console() -> HdbResult<()> { let connection = test_utils::get_authenticated_connection().await?; let mut stmt = connection .prepare("CALL MANAGEMENT_CONSOLE_PROC(?, ?, ?)") .await?; let hdb_response = stmt.execute(&("encryption status", "ld3670:30807")).await?; for hdb_return_value in hdb_response.into_iter() { #[allow(unreachable_patterns)] // needed to avoid wrong error message in VS Code match hdb_return_value { HdbReturnValue::ResultSet(result_set) => { println!("{result_set:?}"); } HdbReturnValue::AffectedRows(vec_usize) => { for val in vec_usize { println!("Affected rows: {val}"); } } HdbReturnValue::OutputParameters(output_parameters) => { println!("Output parameters"); for op in output_parameters.into_values().into_iter() { println!(" Output parameter: {op:?}"); match op { HdbValue::ASYNC_BLOB(blob) => { println!("Value: {:?}", blob.into_bytes().await?); } HdbValue::ASYNC_CLOB(clob) => { println!("Value: {}", clob.into_string().await?); } HdbValue::ASYNC_NCLOB(nclob) => { println!("Value: {}", nclob.into_string().await?); } _ => { println!("Value: {op}"); } } } } HdbReturnValue::Success => { println!("Success"); } #[cfg(feature = "dist_tx")] HdbReturnValue::XaTransactionIds(vec_ta_ids) => { println!("Transaction-ids"); for val in vec_ta_ids { println!(" transaction-id: {val:?}"); } } _ => {} } } Ok(()) }
use std::ops::{Deref, DerefMut}; use n3_machine_ffi::{Program, Query, Result, WorkHandler}; pub trait PyMachine { fn is_running(&self) -> bool; fn py_spawn(&mut self, program: &mut Program, handler: &WorkHandler) -> Result<()>; fn py_terminate(&mut self) -> Result<()>; } pub trait ProcessMachine<P>: PyMachine { fn new(process: P) -> Self where Self: Sized; fn verify_query(query: &Query) -> Vec<Query>; } impl<T, P> PyMachine for T where T: ProcessMachine<P> + Deref<Target = P> + DerefMut, P: PyMachine, { fn is_running(&self) -> bool { self.deref().is_running() } fn py_spawn(&mut self, program: &mut Program, handler: &WorkHandler) -> Result<()> { self.deref_mut().py_spawn(program, handler) } fn py_terminate(&mut self) -> Result<()> { self.deref_mut().py_terminate() } }
use super::*; pub fn consumable<IEVec: AsRef<Vec<ItemEffect>>>( name: &str, size: usize, effects: IEVec, ) -> ConsumableBuilder { ConsumableBuilder { consumable: Consumable { size, effects: effects.as_ref().clone(), name: name.to_owned(), max_uses: 1, uses: 1, }, } } pub fn equipment<S: AsRef<Slot>, IEVec: AsRef<Vec<ItemEffect>>>( name: &str, size: usize, slot: S, effects: IEVec, ) -> EquipmentBuilder { EquipmentBuilder { equipment: Equipment { slot: slot.as_ref().clone(), name: name.to_owned(), effects: effects.as_ref().clone(), size: size, damage: 0, prefix: None, suffix: None, }, } } pub struct ConsumableBuilder { consumable: Consumable, } pub struct EquipmentBuilder { equipment: Equipment, } impl ConsumableBuilder { pub fn build(&self) -> Consumable { self.consumable.clone() } pub fn uses(mut self, uses: usize) -> ConsumableBuilder { self.consumable.uses = uses; self.consumable.max_uses = uses; self } pub fn remaining_uses(mut self, uses: usize, max_uses: usize) -> ConsumableBuilder { self.consumable.uses = uses; self.consumable.max_uses = max_uses; self } } impl EquipmentBuilder { pub fn build(&self) -> Equipment { self.equipment.clone() } pub fn damage(mut self, damage: i32) -> EquipmentBuilder { self.equipment.damage = damage; self } pub fn prefix<P: AsRef<Prefix>>(mut self, prefix: P) -> EquipmentBuilder { self.equipment.prefix = Some(prefix.as_ref().clone()); self } pub fn suffix<S: AsRef<Suffix>>(mut self, suffix: S) -> EquipmentBuilder { self.equipment.suffix = Some(suffix.as_ref().clone()); self } }
/// Useful functionality for command-line interfaces. /// /// Features CLI prompts, colored & stacked outputs. #[cfg(feature = "cli")] pub mod cli; /// Regroupment of system utilities, filesystem stuff, and portable wrappers around platform-specific /// functionality. #[cfg(feature = "sys")] pub mod sys; #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } }
use std::iter::Peekable; #[test] fn peekable_test() { let mut chars = "carlos23Lande5".chars().peekable(); assert_eq!(parse_string(&mut chars), "carlos"); assert_eq!(chars.next(), Some('2')); assert_eq!(chars.next(), Some('3')); assert_eq!(parse_string(&mut chars), "Lande"); assert_eq!(chars.next(), Some('5')); } #[allow(dead_code)] fn parse_string<'a, I>(content: &'a mut Peekable<I>) -> String where I: Iterator<Item = char>, { let mut res = String::new(); loop { match content.peek() { Some(v) if !(*v).is_numeric() => { &res.push(*v); } _ => return res, } content.next(); } }
#[doc = "Reader of register FTSR2"] pub type R = crate::R<u32, super::FTSR2>; #[doc = "Writer for register FTSR2"] pub type W = crate::W<u32, super::FTSR2>; #[doc = "Register FTSR2 `reset()`'s with value 0"] impl crate::ResetValue for super::FTSR2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Falling trigger event configuration bit of line 32\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TR32_A { #[doc = "0: Falling edge trigger is disabled"] DISABLED = 0, #[doc = "1: Falling edge trigger is enabled"] ENABLED = 1, } impl From<TR32_A> for bool { #[inline(always)] fn from(variant: TR32_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TR32`"] pub type TR32_R = crate::R<bool, TR32_A>; impl TR32_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TR32_A { match self.bits { false => TR32_A::DISABLED, true => TR32_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == TR32_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == TR32_A::ENABLED } } #[doc = "Write proxy for field `TR32`"] pub struct TR32_W<'a> { w: &'a mut W, } impl<'a> TR32_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TR32_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Falling edge trigger is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(TR32_A::DISABLED) } #[doc = "Falling edge trigger is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(TR32_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Falling trigger event configuration bit of line 33"] pub type TR33_A = TR32_A; #[doc = "Reader of field `TR33`"] pub type TR33_R = crate::R<bool, TR32_A>; #[doc = "Write proxy for field `TR33`"] pub struct TR33_W<'a> { w: &'a mut W, } impl<'a> TR33_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TR33_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Falling edge trigger is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(TR32_A::DISABLED) } #[doc = "Falling edge trigger is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(TR32_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } impl R { #[doc = "Bit 0 - Falling trigger event configuration bit of line 32"] #[inline(always)] pub fn tr32(&self) -> TR32_R { TR32_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Falling trigger event configuration bit of line 33"] #[inline(always)] pub fn tr33(&self) -> TR33_R { TR33_R::new(((self.bits >> 1) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Falling trigger event configuration bit of line 32"] #[inline(always)] pub fn tr32(&mut self) -> TR32_W { TR32_W { w: self } } #[doc = "Bit 1 - Falling trigger event configuration bit of line 33"] #[inline(always)] pub fn tr33(&mut self) -> TR33_W { TR33_W { w: self } } }
use test_winrt_classes::*; use windows::core::*; use Component::Classes::*; use Component::Interfaces::*; #[test] fn static_class() -> Result<()> { assert!(Static::Method()? == 0); assert!(Static::Property()? == 0); assert!(Static::ReadOnly()? == 0); Static::SetProperty(123)?; assert!(Static::Method()? == 123); assert!(Static::Property()? == 123); assert!(Static::ReadOnly()? == 123); Ok(()) } #[test] fn activatable() -> Result<()> { let c = Activatable::new()?; assert!(c.Property()? == 0); let c = Activatable::CreateInstance(123)?; assert!(c.Property()? == 123); Ok(()) } #[test] fn creator() -> Result<()> { let c = Creator::Create(123)?; assert!(c.Property()? == 123); Ok(()) } #[test] fn required() -> Result<()> { let c = Required::new()?; assert!(c.Property()? == 0); c.SetProperty(123)?; assert!(c.Property()? == 123); let r: IProperty = c.cast()?; assert!(r.Property()? == 123); r.SetProperty(456)?; assert!(c.Property()? == 456); let r: IProperty = c.into(); assert!(r.Property()? == 456); Ok(()) }
use crate::derive_stable_abi_from_str as derive_sabi; use abi_stable_shared::test_utils::must_panic; use as_derive_utils::test_framework::Tests; /// For testing that adding #[repr(C)] makes the derive macro not panic. const RECTANGLE_DEF_REPR: &str = r##" pub struct Rectangle { x:u32, y:u32, w:u16, h:u32, } "##; #[test] fn test_cases() { Tests::load("stable_abi").run_test(derive_sabi); } #[test] fn check_struct_repr_attrs() { let rect_def = RECTANGLE_DEF_REPR; must_panic(|| derive_sabi(rect_def).unwrap()).expect("TEST BUG"); let invalid_reprs = vec![ "Rust", "u8", "i8", "u16", "i16", "u32", "i32", "u64", "i64", "usize", "isize", ]; for invalid_repr in invalid_reprs { let with_repr_rust = format!( "#[repr({repr})]\n{struct_def}", repr = invalid_repr, struct_def = rect_def, ); assert!(derive_sabi(&with_repr_rust).is_err()) } derive_sabi(&format!("#[repr(C)]\n{}", rect_def)).unwrap(); derive_sabi(&format!("#[repr(transparent)]\n{}", rect_def)).unwrap(); }
use ndarray::prelude::*; use petgraph::visit::{EdgeRef, IntoEdgeReferences, IntoNodeIdentifiers}; use petgraph_drawing::{Drawing, DrawingIndex}; use std::collections::HashMap; pub fn ideal_edge_lengths<G>( graph: G, coordinates: &Drawing<G::NodeId, f32>, d: &Array2<f32>, ) -> f32 where G: IntoEdgeReferences + IntoNodeIdentifiers, G::NodeId: DrawingIndex, { let node_indices = graph .node_identifiers() .enumerate() .map(|(i, u)| (u, i)) .collect::<HashMap<_, _>>(); let mut s = 0.; for e in graph.edge_references() { let u = e.source(); let v = e.target(); let (x1, y1) = coordinates.position(u).unwrap(); let (x2, y2) = coordinates.position(v).unwrap(); let l = d[[node_indices[&u], node_indices[&v]]]; s += (((x1 - x2).hypot(y1 - y2) - l) / l).powi(2); } s }
extern crate lzf; use lzf::compress; use lzf::decompress; fn main() { let lorem = "\r\n\r\n\r\n\r\n ALICE'S ADVENTURES IN WONDERLAND\r\n"; println!("lorem.len: {}", lorem.len()); let compressed = compress(lorem.as_bytes()).unwrap(); println!("l: {}", compressed.len()); let decompressed = decompress(&compressed[..], lorem.len()).unwrap(); println!("l: {:?}", decompressed.len()); }
extern crate num_bigint; extern crate num_traits; extern crate hex; extern crate rand; extern crate openssl; use num_bigint::BigUint; use num_bigint::*; use num_traits::*; use openssl::symm::{decrypt, Cipher, Crypter, encrypt}; use num_bigint::Sign::*; use rand::Rng; pub struct Dh { pub private_key: BigInt, pub public_key: BigInt, pub other_public: BigInt, pub key: BigInt, pub p: BigInt, pub g: BigInt, } pub struct DhMitm { pub a_public_key: BigInt, pub b_public_key: BigInt, pub p: BigInt, pub g: BigInt, pub key: BigInt, } impl Dh { pub fn new() -> Dh { Dh { private_key: BigInt::one(), public_key: BigInt::one(), other_public: BigInt::one(), key: BigInt::one(), p: BigInt::one(), g: BigInt::one() } } pub fn start_exchange(&mut self) -> (BigInt, BigInt, BigInt) { let mut rng = rand::thread_rng(); let p_buff = "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"; let mut p_buff_u8 = Vec::new(); for i in 0..p_buff.len() { p_buff_u8.push(u8::from_str_radix(&p_buff[i..i + 1], 16).unwrap()); } self.p = BigInt::from_radix_be(Plus, &p_buff_u8, 16).unwrap(); self.g = BigInt::from(2 as u32); while self.public_key == BigInt::one() { self.private_key = rng.gen_bigint(1000); // rand self.public_key = modexp(&self.g, &self.private_key, &self.p); } (self.p.clone(), self.g.clone(), self.public_key.clone()) } pub fn reply(&mut self, p: BigInt, g: BigInt, A: BigInt) -> BigInt { let mut rng = rand::thread_rng(); self.p = p; self.g = g; self.other_public = A; while self.public_key == BigInt::one() { self.private_key = rng.gen_bigint(1000); // rand self.public_key = modexp(&self.g, &self.private_key, &self.p); } self.key = modexp(&self.other_public, &self.private_key, &self.p); self.public_key.clone() } pub fn other_key_update(&mut self, other: BigInt) { self.other_public = other; self.key = modexp(&self.other_public, &self.private_key, &self.p) } pub fn aes_cbc_from_key(&mut self, message: & [u8]) -> Vec<u8>{ let iv = gen_rand_key(); let cipher = Cipher::aes_128_ecb(); let mut key = self.key.to_bytes_be().1; while key.len()<16{ key.push(0); } let mut encrypt_vec = encrypt( cipher, &key[0..16], Some(&iv), & message, ).expect("error"); println!("len: {}",encrypt_vec.len()); encrypt_vec.extend_from_slice(&iv); encrypt_vec } } impl DhMitm{ pub fn new() -> DhMitm{ DhMitm{a_public_key: BigInt::one(), b_public_key: BigInt::one(),p: BigInt::one(), g: BigInt::one(), key: BigInt::one()} } pub fn forward_start(&mut self,p: BigInt, g: BigInt, A: BigInt) -> (BigInt,BigInt,BigInt){ self.p = p; self.g = g; self.a_public_key = A; (self.p.clone(),self.g.clone(),self.p.clone()) } pub fn forward_reply(&mut self, B: BigInt) -> BigInt{ self.b_public_key = B; self.key = BigInt::zero(); self.p.clone() } pub fn crack_message(&self,message: &[u8]) -> Vec<u8>{ let mut iv = &message[message.len()-16..]; println!("len: {}",message.len()); let mut plaintext = &message[..message.len()-16]; println!("len: {}",plaintext.len()); let mut key = self.key.to_bytes_be().1; while key.len()<16{ key.push(0); } let cipher = Cipher::aes_128_ecb(); decrypt( cipher, &key[0..16], Some(&iv), &plaintext, ).expect("error") } } fn gen_rand_key() -> Vec<u8>{ let mut rng = rand::thread_rng(); let mut vec = Vec::new(); for i in 0..16{ vec.push(rng.gen::<u8>()); } vec } fn modexp(b: &BigInt, e: &BigInt, m: &BigInt) -> BigInt { let mut b = b.clone(); let mut e = e.clone(); let mut res = BigInt::one(); let two = 2.to_bigint().unwrap(); while e > BigInt::zero() { if e.clone() % two.clone() == BigInt::one() { res = (res.clone() * b.clone()) % m.clone(); } b = (b.clone() * b.clone()) % m.clone(); e = e.clone() / two.clone(); } res % m }
use std::{ future::Future, pin::Pin, task::{Context, Poll}, time::Duration, }; use pin_project_lite::pin_project; use crate::{ actor::Actor, clock::{sleep, Instant, Sleep}, fut::ActorStream, }; pin_project! { /// Stream for the [`timeout`](super::ActorStreamExt::timeout) method. #[derive(Debug)] #[must_use = "streams do nothing unless polled"] pub struct Timeout<S> { #[pin] stream: S, dur: Duration, reset_timeout: bool, #[pin] timeout: Sleep, } } impl<S> Timeout<S> { pub(super) fn new(stream: S, timeout: Duration) -> Self { Self { stream, dur: timeout, reset_timeout: false, timeout: sleep(timeout), } } } impl<S, A> ActorStream<A> for Timeout<S> where S: ActorStream<A>, A: Actor, { type Item = Result<S::Item, ()>; fn poll_next( self: Pin<&mut Self>, act: &mut A, ctx: &mut A::Context, task: &mut Context<'_>, ) -> Poll<Option<Result<S::Item, ()>>> { let mut this = self.project(); match this.stream.poll_next(act, ctx, task) { Poll::Ready(Some(res)) => { *this.reset_timeout = true; Poll::Ready(Some(Ok(res))) } Poll::Ready(None) => Poll::Ready(None), Poll::Pending => { // only reset timeout when poll_next returns Ready and followed by Pending after. if *this.reset_timeout { *this.reset_timeout = false; this.timeout.as_mut().reset(Instant::now() + *this.dur); } // check timeout this.timeout.poll(task).map(|_| Some(Err(()))) } } } }
use vec3::Vec3; use num_traits::Float; use util::*; #[derive(Debug)] #[allow(non_snake_case)] pub struct Ray<T: Float> { A: Vec3<T>, B: Vec3<T>, /// Timestamp of when this ray was fired. t: f64, } impl<T: Float> Ray<T> { pub fn new(a: Vec3<T>, b: Vec3<T>) -> Ray<T> { Ray { A: a, B: b, t: 0.0, } } pub fn new_time(a: Vec3<T>, b: Vec3<T>, time: f64) -> Ray<T> { Ray { A: a, B: b, t: time, } } #[inline(always)] pub fn origin(&self) -> Vec3<T> { self.A } #[inline(always)] pub fn direction(&self) -> Vec3<T> { self.B } #[inline(always)] pub fn time(&self) -> f64 { self.t } pub fn point_at_parameter(&self, t: T) -> Vec3<T> { self.A + self.B * t } } impl <T: Float + fmt::Display> fmt::Display for Ray<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let p = f.precision().unwrap_or(3); write!(f, "Ray({:.*}, {:.*}, {:.*})", p, self.A, p, self.B, p, self.t) } } #[cfg(test)] mod tests { use super::*; use vec3::Vec3; #[test] fn test_ray() { let a = Ray::new(Vec3::new(1.0, 2.0, 3.0), Vec3::new(4.0, 5.0, 6.0)); assert_eq!(a.origin(), Vec3::new(1.0, 2.0, 3.0)); assert_eq!(a.direction(), Vec3::new(4.0, 5.0, 6.0)); } #[test] fn test_p_at_p() { let a = Ray::new(Vec3::new(1.0, 2.0, 3.0), Vec3::new(4.0, 5.0, 6.0)); assert_eq!(a.point_at_parameter(0.5), Vec3::new(3.0, 4.5, 6.0)); } }
// Translated from C to Rust. The original C code can be found at // https://github.com/ulfjack/ryu and carries the following license: // // Copyright 2018 Ulf Adams // // The contents of this file may be used under the terms of the Apache License, // Version 2.0. // // (See accompanying file LICENSE-Apache or copy at // http://www.apache.org/licenses/LICENSE-2.0) // // 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. extern crate rand; extern crate ryu; #[macro_use] mod macros; use std::{f32, str}; fn print(f: f32) -> String { let mut bytes = [0u8; 24]; let n = unsafe { ryu::raw::f2s_buffered_n(f, &mut bytes[0]) }; let s = str::from_utf8(&bytes[..n]).unwrap(); s.to_owned() } fn pretty(f: f32) -> String { ryu::Buffer::new().format(f).to_owned() } #[test] fn test_ryu() { check!(3E-1, 0.3); check!(1.234E12, 1234000000000.0); check!(1.234E13, 1.234e13); check!(2.71828E0, 2.71828); check!(1.1E32, 1.1e32); check!(1.1E-32, 1.1e-32); check!(2.7182817E0, 2.7182817); check!(1E-45, 1e-45); check!(3.4028235E38, 3.4028235e38); check!(-1.234E-3, -0.001234); } #[test] fn test_random() { let mut bytes = [0u8; 24]; let mut buffer = ryu::Buffer::new(); for _ in 0..1000000 { let f = rand::random(); let n = unsafe { ryu::raw::f2s_buffered_n(f, &mut bytes[0]) }; assert_eq!(f, str::from_utf8(&bytes[..n]).unwrap().parse().unwrap()); assert_eq!(f, buffer.format(f).parse().unwrap()); } } #[test] fn test_non_finite() { for i in 0u32..1 << 23 { let f = f32::from_bits((((1 << 8) - 1) << 23) + i); assert!(!f.is_finite(), "f={}", f); ryu::Buffer::new().format(f); } } #[test] fn test_basic() { check!(0E0, 0.0); check!(-0E0, -0.0); check!(1E0, 1.0); check!(-1E0, -1.0); assert_eq!(print(f32::NAN), "NaN"); assert_eq!(print(f32::INFINITY), "Infinity"); assert_eq!(print(f32::NEG_INFINITY), "-Infinity"); } #[test] fn test_switch_to_subnormal() { check!(1.1754944E-38, 1.1754944e-38); } #[test] fn test_min_and_max() { assert_eq!(f32::from_bits(0x7f7fffff), 3.4028235e38); check!(3.4028235E38, 3.4028235e38); assert_eq!(f32::from_bits(1), 1e-45); check!(1E-45, 1e-45); } // Check that we return the exact boundary if it is the shortest // representation, but only if the original floating point number is even. #[test] fn test_boundary_round_even() { check!(3.355445E7, 33554450.0); check!(9E9, 9000000000.0); check!(3.436672E10, 34366720000.0); } // If the exact value is exactly halfway between two shortest representations, // then we round to even. It seems like this only makes a difference if the // last two digits are ...2|5 or ...7|5, and we cut off the 5. #[test] fn test_exact_value_round_even() { check!(3.0540412E5, 305404.12); check!(8.0990312E3, 8099.0312); } #[test] fn test_lots_of_trailing_zeros() { // Pattern for the first test: 00111001100000000000000000000000 check!(2.4414062E-4, 0.00024414062); check!(2.4414062E-3, 0.0024414062); check!(4.3945312E-3, 0.0043945312); check!(6.3476562E-3, 0.0063476562); } #[test] fn test_regression() { check!(4.7223665E21, 4.7223665e21); check!(8.388608E6, 8388608.0); check!(1.6777216E7, 16777216.0); check!(3.3554436E7, 33554436.0); check!(6.7131496E7, 67131496.0); check!(1.9310392E-38, 1.9310392e-38); check!(-2.47E-43, -2.47e-43); check!(1.993244E-38, 1.993244e-38); check!(4.1039004E3, 4103.9004); check!(5.3399997E9, 5339999700.0); check!(6.0898E-39, 6.0898e-39); check!(1.0310042E-3, 0.0010310042); check!(2.882326E17, 2.882326e17); check!(7.038531E-26, 7.038531e-26); check!(9.223404E17, 9.223404e17); check!(6.710887E7, 67108870.0); check!(1E-44, 1e-44); check!(2.816025E14, 2.816025e14); check!(9.223372E18, 9.223372e18); check!(1.5846086E29, 1.5846086e29); check!(1.1811161E19, 1.1811161e19); check!(5.368709E18, 5.368709e18); check!(4.6143166E18, 4.6143166e18); check!(7.812537E-3, 0.007812537); check!(1E-45, 1e-45); check!(1.18697725E20, 1.18697725e20); check!(1.00014165E-36, 1.00014165e-36); check!(2E2, 200.0); check!(3.3554432E7, 33554432.0); } #[test] fn test_looks_like_pow5() { // These numbers have a mantissa that is the largest power of 5 that fits, // and an exponent that causes the computation for q to result in 10, which // is a corner case for Ryu. assert_eq!(f32::from_bits(0x5D1502F9), 6.7108864e17); check!(6.7108864E17, 6.7108864e17); assert_eq!(f32::from_bits(0x5D9502F9), 1.3421773e18); check!(1.3421773E18, 1.3421773e18); assert_eq!(f32::from_bits(0x5E1502F9), 2.6843546e18); check!(2.6843546E18, 2.6843546e18); } #[test] fn test_output_length() { check!(1E0, 1.0); // already tested in Basic check!(1.2E0, 1.2); check!(1.23E0, 1.23); check!(1.234E0, 1.234); check!(1.2345E0, 1.2345); check!(1.23456E0, 1.23456); check!(1.234567E0, 1.234567); check!(1.2345678E0, 1.2345678); check!(1.23456735E-36, 1.23456735e-36); }
#[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmAttachMilContent ( hwnd : super::super::Foundation:: HWND ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmDefWindowProc ( hwnd : super::super::Foundation:: HWND , msg : u32 , wparam : super::super::Foundation:: WPARAM , lparam : super::super::Foundation:: LPARAM , plresult : *mut super::super::Foundation:: LRESULT ) -> super::super::Foundation:: BOOL ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmDetachMilContent ( hwnd : super::super::Foundation:: HWND ) -> ::windows_sys::core::HRESULT ); #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`, `\"Win32_Graphics_Gdi\"`*"] fn DwmEnableBlurBehindWindow ( hwnd : super::super::Foundation:: HWND , pblurbehind : *const DWM_BLURBEHIND ) -> ::windows_sys::core::HRESULT ); ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] fn DwmEnableComposition ( ucompositionaction : u32 ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmEnableMMCSS ( fenablemmcss : super::super::Foundation:: BOOL ) -> ::windows_sys::core::HRESULT ); #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Controls"))] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`, `\"Win32_UI_Controls\"`*"] fn DwmExtendFrameIntoClientArea ( hwnd : super::super::Foundation:: HWND , pmarinset : *const super::super::UI::Controls:: MARGINS ) -> ::windows_sys::core::HRESULT ); ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] fn DwmFlush ( ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmGetColorizationColor ( pcrcolorization : *mut u32 , pfopaqueblend : *mut super::super::Foundation:: BOOL ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmGetCompositionTimingInfo ( hwnd : super::super::Foundation:: HWND , ptiminginfo : *mut DWM_TIMING_INFO ) -> ::windows_sys::core::HRESULT ); ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] fn DwmGetGraphicsStreamClient ( uindex : u32 , pclientuuid : *mut ::windows_sys::core::GUID ) -> ::windows_sys::core::HRESULT ); ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] fn DwmGetGraphicsStreamTransformHint ( uindex : u32 , ptransform : *mut MilMatrix3x2D ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmGetTransportAttributes ( pfisremoting : *mut super::super::Foundation:: BOOL , pfisconnected : *mut super::super::Foundation:: BOOL , pdwgeneration : *mut u32 ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmGetUnmetTabRequirements ( appwindow : super::super::Foundation:: HWND , value : *mut DWM_TAB_WINDOW_REQUIREMENTS ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmGetWindowAttribute ( hwnd : super::super::Foundation:: HWND , dwattribute : DWMWINDOWATTRIBUTE , pvattribute : *mut ::core::ffi::c_void , cbattribute : u32 ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmInvalidateIconicBitmaps ( hwnd : super::super::Foundation:: HWND ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmIsCompositionEnabled ( pfenabled : *mut super::super::Foundation:: BOOL ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmModifyPreviousDxFrameDuration ( hwnd : super::super::Foundation:: HWND , crefreshes : i32 , frelative : super::super::Foundation:: BOOL ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmQueryThumbnailSourceSize ( hthumbnail : isize , psize : *mut super::super::Foundation:: SIZE ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmRegisterThumbnail ( hwnddestination : super::super::Foundation:: HWND , hwndsource : super::super::Foundation:: HWND , phthumbnailid : *mut isize ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmRenderGesture ( gt : GESTURE_TYPE , ccontacts : u32 , pdwpointerid : *const u32 , ppoints : *const super::super::Foundation:: POINT ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmSetDxFrameDuration ( hwnd : super::super::Foundation:: HWND , crefreshes : i32 ) -> ::windows_sys::core::HRESULT ); #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`, `\"Win32_Graphics_Gdi\"`*"] fn DwmSetIconicLivePreviewBitmap ( hwnd : super::super::Foundation:: HWND , hbmp : super::Gdi:: HBITMAP , pptclient : *const super::super::Foundation:: POINT , dwsitflags : u32 ) -> ::windows_sys::core::HRESULT ); #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`, `\"Win32_Graphics_Gdi\"`*"] fn DwmSetIconicThumbnail ( hwnd : super::super::Foundation:: HWND , hbmp : super::Gdi:: HBITMAP , dwsitflags : u32 ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmSetPresentParameters ( hwnd : super::super::Foundation:: HWND , ppresentparams : *mut DWM_PRESENT_PARAMETERS ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmSetWindowAttribute ( hwnd : super::super::Foundation:: HWND , dwattribute : DWMWINDOWATTRIBUTE , pvattribute : *const ::core::ffi::c_void , cbattribute : u32 ) -> ::windows_sys::core::HRESULT ); ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] fn DwmShowContact ( dwpointerid : u32 , eshowcontact : DWM_SHOWCONTACT ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmTetherContact ( dwpointerid : u32 , fenable : super::super::Foundation:: BOOL , pttether : super::super::Foundation:: POINT ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmTransitionOwnedWindow ( hwnd : super::super::Foundation:: HWND , target : DWMTRANSITION_OWNEDWINDOW_TARGET ) -> ::windows_sys::core::HRESULT ); ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] fn DwmUnregisterThumbnail ( hthumbnailid : isize ) -> ::windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")] ::windows_targets::link ! ( "dwmapi.dll""system" #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] fn DwmUpdateThumbnailProperties ( hthumbnailid : isize , ptnproperties : *const DWM_THUMBNAIL_PROPERTIES ) -> ::windows_sys::core::HRESULT ); #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_COLOR_DEFAULT: u32 = 4294967295u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_COLOR_NONE: u32 = 4294967294u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_BB_BLURREGION: u32 = 2u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_BB_ENABLE: u32 = 1u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_BB_TRANSITIONONMAXIMIZED: u32 = 4u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_CLOAKED_APP: u32 = 1u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_CLOAKED_INHERITED: u32 = 4u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_CLOAKED_SHELL: u32 = 2u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_EC_DISABLECOMPOSITION: u32 = 0u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_EC_ENABLECOMPOSITION: u32 = 1u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_FRAME_DURATION_DEFAULT: i32 = -1i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_SIT_DISPLAYFRAME: u32 = 1u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_TNP_OPACITY: u32 = 4u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_TNP_RECTDESTINATION: u32 = 1u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_TNP_RECTSOURCE: u32 = 2u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_TNP_SOURCECLIENTAREAONLY: u32 = 16u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_TNP_VISIBLE: u32 = 8u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const c_DwmMaxAdapters: u32 = 16u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const c_DwmMaxMonitors: u32 = 16u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const c_DwmMaxQueuedBuffers: u32 = 8u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub type DWMFLIP3DWINDOWPOLICY = i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMFLIP3D_DEFAULT: DWMFLIP3DWINDOWPOLICY = 0i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMFLIP3D_EXCLUDEBELOW: DWMFLIP3DWINDOWPOLICY = 1i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMFLIP3D_EXCLUDEABOVE: DWMFLIP3DWINDOWPOLICY = 2i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMFLIP3D_LAST: DWMFLIP3DWINDOWPOLICY = 3i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub type DWMNCRENDERINGPOLICY = i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMNCRP_USEWINDOWSTYLE: DWMNCRENDERINGPOLICY = 0i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMNCRP_DISABLED: DWMNCRENDERINGPOLICY = 1i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMNCRP_ENABLED: DWMNCRENDERINGPOLICY = 2i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMNCRP_LAST: DWMNCRENDERINGPOLICY = 3i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub type DWMTRANSITION_OWNEDWINDOW_TARGET = i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMTRANSITION_OWNEDWINDOW_NULL: DWMTRANSITION_OWNEDWINDOW_TARGET = -1i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMTRANSITION_OWNEDWINDOW_REPOSITION: DWMTRANSITION_OWNEDWINDOW_TARGET = 0i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub type DWMWINDOWATTRIBUTE = i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_NCRENDERING_ENABLED: DWMWINDOWATTRIBUTE = 1i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_NCRENDERING_POLICY: DWMWINDOWATTRIBUTE = 2i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_TRANSITIONS_FORCEDISABLED: DWMWINDOWATTRIBUTE = 3i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_ALLOW_NCPAINT: DWMWINDOWATTRIBUTE = 4i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_CAPTION_BUTTON_BOUNDS: DWMWINDOWATTRIBUTE = 5i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_NONCLIENT_RTL_LAYOUT: DWMWINDOWATTRIBUTE = 6i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_FORCE_ICONIC_REPRESENTATION: DWMWINDOWATTRIBUTE = 7i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_FLIP3D_POLICY: DWMWINDOWATTRIBUTE = 8i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_EXTENDED_FRAME_BOUNDS: DWMWINDOWATTRIBUTE = 9i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_HAS_ICONIC_BITMAP: DWMWINDOWATTRIBUTE = 10i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_DISALLOW_PEEK: DWMWINDOWATTRIBUTE = 11i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_EXCLUDED_FROM_PEEK: DWMWINDOWATTRIBUTE = 12i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_CLOAK: DWMWINDOWATTRIBUTE = 13i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_CLOAKED: DWMWINDOWATTRIBUTE = 14i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_FREEZE_REPRESENTATION: DWMWINDOWATTRIBUTE = 15i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_PASSIVE_UPDATE_MODE: DWMWINDOWATTRIBUTE = 16i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_USE_HOSTBACKDROPBRUSH: DWMWINDOWATTRIBUTE = 17i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_USE_IMMERSIVE_DARK_MODE: DWMWINDOWATTRIBUTE = 20i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_WINDOW_CORNER_PREFERENCE: DWMWINDOWATTRIBUTE = 33i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_BORDER_COLOR: DWMWINDOWATTRIBUTE = 34i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_CAPTION_COLOR: DWMWINDOWATTRIBUTE = 35i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_TEXT_COLOR: DWMWINDOWATTRIBUTE = 36i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_VISIBLE_FRAME_BORDER_THICKNESS: DWMWINDOWATTRIBUTE = 37i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_SYSTEMBACKDROP_TYPE: DWMWINDOWATTRIBUTE = 38i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWA_LAST: DWMWINDOWATTRIBUTE = 39i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub type DWM_SHOWCONTACT = u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMSC_DOWN: DWM_SHOWCONTACT = 1u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMSC_UP: DWM_SHOWCONTACT = 2u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMSC_DRAG: DWM_SHOWCONTACT = 4u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMSC_HOLD: DWM_SHOWCONTACT = 8u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMSC_PENBARREL: DWM_SHOWCONTACT = 16u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMSC_NONE: DWM_SHOWCONTACT = 0u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMSC_ALL: DWM_SHOWCONTACT = 4294967295u32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub type DWM_SOURCE_FRAME_SAMPLING = i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_SOURCE_FRAME_SAMPLING_POINT: DWM_SOURCE_FRAME_SAMPLING = 0i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_SOURCE_FRAME_SAMPLING_COVERAGE: DWM_SOURCE_FRAME_SAMPLING = 1i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWM_SOURCE_FRAME_SAMPLING_LAST: DWM_SOURCE_FRAME_SAMPLING = 2i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub type DWM_SYSTEMBACKDROP_TYPE = i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMSBT_AUTO: DWM_SYSTEMBACKDROP_TYPE = 0i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMSBT_NONE: DWM_SYSTEMBACKDROP_TYPE = 1i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMSBT_MAINWINDOW: DWM_SYSTEMBACKDROP_TYPE = 2i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMSBT_TRANSIENTWINDOW: DWM_SYSTEMBACKDROP_TYPE = 3i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMSBT_TABBEDWINDOW: DWM_SYSTEMBACKDROP_TYPE = 4i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub type DWM_TAB_WINDOW_REQUIREMENTS = i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMTWR_NONE: DWM_TAB_WINDOW_REQUIREMENTS = 0i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMTWR_IMPLEMENTED_BY_SYSTEM: DWM_TAB_WINDOW_REQUIREMENTS = 1i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMTWR_WINDOW_RELATIONSHIP: DWM_TAB_WINDOW_REQUIREMENTS = 2i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMTWR_WINDOW_STYLES: DWM_TAB_WINDOW_REQUIREMENTS = 4i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMTWR_WINDOW_REGION: DWM_TAB_WINDOW_REQUIREMENTS = 8i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMTWR_WINDOW_DWM_ATTRIBUTES: DWM_TAB_WINDOW_REQUIREMENTS = 16i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMTWR_WINDOW_MARGINS: DWM_TAB_WINDOW_REQUIREMENTS = 32i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMTWR_TABBING_ENABLED: DWM_TAB_WINDOW_REQUIREMENTS = 64i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMTWR_USER_POLICY: DWM_TAB_WINDOW_REQUIREMENTS = 128i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMTWR_GROUP_POLICY: DWM_TAB_WINDOW_REQUIREMENTS = 256i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMTWR_APP_COMPAT: DWM_TAB_WINDOW_REQUIREMENTS = 512i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub type DWM_WINDOW_CORNER_PREFERENCE = i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWCP_DEFAULT: DWM_WINDOW_CORNER_PREFERENCE = 0i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWCP_DONOTROUND: DWM_WINDOW_CORNER_PREFERENCE = 1i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWCP_ROUND: DWM_WINDOW_CORNER_PREFERENCE = 2i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const DWMWCP_ROUNDSMALL: DWM_WINDOW_CORNER_PREFERENCE = 3i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub type GESTURE_TYPE = i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const GT_PEN_TAP: GESTURE_TYPE = 0i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const GT_PEN_DOUBLETAP: GESTURE_TYPE = 1i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const GT_PEN_RIGHTTAP: GESTURE_TYPE = 2i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const GT_PEN_PRESSANDHOLD: GESTURE_TYPE = 3i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const GT_PEN_PRESSANDHOLDABORT: GESTURE_TYPE = 4i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const GT_TOUCH_TAP: GESTURE_TYPE = 5i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const GT_TOUCH_DOUBLETAP: GESTURE_TYPE = 6i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const GT_TOUCH_RIGHTTAP: GESTURE_TYPE = 7i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const GT_TOUCH_PRESSANDHOLD: GESTURE_TYPE = 8i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const GT_TOUCH_PRESSANDHOLDABORT: GESTURE_TYPE = 9i32; #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub const GT_TOUCH_PRESSANDTAP: GESTURE_TYPE = 10i32; #[repr(C, packed(1))] #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`, `\"Win32_Graphics_Gdi\"`*"] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub struct DWM_BLURBEHIND { pub dwFlags: u32, pub fEnable: super::super::Foundation::BOOL, pub hRgnBlur: super::Gdi::HRGN, pub fTransitionOnMaximized: super::super::Foundation::BOOL, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy for DWM_BLURBEHIND {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::clone::Clone for DWM_BLURBEHIND { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] #[cfg(feature = "Win32_Foundation")] pub struct DWM_PRESENT_PARAMETERS { pub cbSize: u32, pub fQueue: super::super::Foundation::BOOL, pub cRefreshStart: u64, pub cBuffer: u32, pub fUseSourceRate: super::super::Foundation::BOOL, pub rateSource: UNSIGNED_RATIO, pub cRefreshesPerFrame: u32, pub eSampling: DWM_SOURCE_FRAME_SAMPLING, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DWM_PRESENT_PARAMETERS {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DWM_PRESENT_PARAMETERS { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`, `\"Win32_Foundation\"`*"] #[cfg(feature = "Win32_Foundation")] pub struct DWM_THUMBNAIL_PROPERTIES { pub dwFlags: u32, pub rcDestination: super::super::Foundation::RECT, pub rcSource: super::super::Foundation::RECT, pub opacity: u8, pub fVisible: super::super::Foundation::BOOL, pub fSourceClientAreaOnly: super::super::Foundation::BOOL, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DWM_THUMBNAIL_PROPERTIES {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DWM_THUMBNAIL_PROPERTIES { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub struct DWM_TIMING_INFO { pub cbSize: u32, pub rateRefresh: UNSIGNED_RATIO, pub qpcRefreshPeriod: u64, pub rateCompose: UNSIGNED_RATIO, pub qpcVBlank: u64, pub cRefresh: u64, pub cDXRefresh: u32, pub qpcCompose: u64, pub cFrame: u64, pub cDXPresent: u32, pub cRefreshFrame: u64, pub cFrameSubmitted: u64, pub cDXPresentSubmitted: u32, pub cFrameConfirmed: u64, pub cDXPresentConfirmed: u32, pub cRefreshConfirmed: u64, pub cDXRefreshConfirmed: u32, pub cFramesLate: u64, pub cFramesOutstanding: u32, pub cFrameDisplayed: u64, pub qpcFrameDisplayed: u64, pub cRefreshFrameDisplayed: u64, pub cFrameComplete: u64, pub qpcFrameComplete: u64, pub cFramePending: u64, pub qpcFramePending: u64, pub cFramesDisplayed: u64, pub cFramesComplete: u64, pub cFramesPending: u64, pub cFramesAvailable: u64, pub cFramesDropped: u64, pub cFramesMissed: u64, pub cRefreshNextDisplayed: u64, pub cRefreshNextPresented: u64, pub cRefreshesDisplayed: u64, pub cRefreshesPresented: u64, pub cRefreshStarted: u64, pub cPixelsReceived: u64, pub cPixelsDrawn: u64, pub cBuffersEmpty: u64, } impl ::core::marker::Copy for DWM_TIMING_INFO {} impl ::core::clone::Clone for DWM_TIMING_INFO { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub struct MilMatrix3x2D { pub S_11: f64, pub S_12: f64, pub S_21: f64, pub S_22: f64, pub DX: f64, pub DY: f64, } impl ::core::marker::Copy for MilMatrix3x2D {} impl ::core::clone::Clone for MilMatrix3x2D { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[doc = "*Required features: `\"Win32_Graphics_Dwm\"`*"] pub struct UNSIGNED_RATIO { pub uiNumerator: u32, pub uiDenominator: u32, } impl ::core::marker::Copy for UNSIGNED_RATIO {} impl ::core::clone::Clone for UNSIGNED_RATIO { fn clone(&self) -> Self { *self } }
mod utils; use std::mem; use wasm_bindgen::prelude::*; // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; // If want to print the message to console, use log! extern crate web_sys; macro_rules! log { ( $( $t:tt )* ) => { web_sys::console::log_1(&format!( $( $t )* ).into()); } } // #[wasm_bindgen] // extern { // fn alert(s: &str); // } // #[wasm_bindgen] // pub fn greet() { // alert("Hello, pine-ws!"); // } // #[wasm_bindgen] // pub fn send_example_to_js() -> JsValue { // let mut field1 = HashMap::new(); // field1.insert(0, String::from("ex")); // let example = Example { // field1, // field2: vec![vec![1., 2.], vec![3., 4.]], // field3: [1., 2., 3., 4.] // }; // JsValue::from_serde(&example).unwrap() // } use pine::runtime::{ AnySeries, InputVal, NoneCallback, OutputData, OutputDataCollect, OutputInfo, PineFormatError, PlotInfo, StrOptionsData, SymbolInfo, }; use pine::PineScript; use std::convert::TryInto; use std::f64; use std::mem::transmute; use std::rc::Rc; #[wasm_bindgen] pub fn init_panic_hook() { utils::set_panic_hook(); } #[wasm_bindgen] pub struct ExportPineRunner { script: *mut (), } #[wasm_bindgen] pub fn new_runner() -> ExportPineRunner { let box_script = Box::new(PineScript::new(Some(&NoneCallback()))); ExportPineRunner { script: Box::into_raw(box_script) as *mut (), } } #[wasm_bindgen] pub fn parse_src(runner: &mut ExportPineRunner, src: String) -> Result<(), JsValue> { let runner_ins = unsafe { let script = transmute::<*mut (), *mut PineScript>(runner.script); script.as_mut().unwrap() }; match runner_ins.parse_src(src) { Ok(_) => Ok(()), Err(errs) => Err(JsValue::from_serde(&errs).unwrap()), } } #[wasm_bindgen] pub fn gen_io_info(runner: &mut ExportPineRunner) -> Result<JsValue, JsValue> { let runner_ins = unsafe { let script = transmute::<*mut (), *mut PineScript>(runner.script); script.as_mut().unwrap() }; match runner_ins.gen_io_info() { Ok(io_info) => Ok(JsValue::from_serde(&io_info).unwrap()), Err(errs) => Err(JsValue::from_serde(&errs).unwrap()), } } #[wasm_bindgen] pub struct ExportOutputData { output_data: *mut Option<OutputData>, } #[wasm_bindgen] pub fn output_series(output: &mut ExportOutputData) -> *mut f64 { let mut res: Vec<f64> = Vec::new(); let output_d = unsafe { transmute::<_, &mut Option<OutputData>>(output.output_data) }; match output_d { None => res.push(0f64), Some(output_d) => { res.push(output_d.series.len() as f64); for data in output_d.series.iter() { // For every output data, first push the length of data vec res.push(data.len() as f64); for ones in data.iter() { match ones { Some(fv) => res.push(*fv), None => res.push(f64::NAN), } } } } } res.shrink_to_fit(); let ptr = res.as_mut_ptr(); mem::forget(res); // prevent deallocation in Rust ptr } #[wasm_bindgen] pub fn output_options(output: &mut ExportOutputData) -> JsValue { let output_d = unsafe { transmute::<_, &mut Option<OutputData>>(output.output_data) }; match output_d { None => { let opts: Vec<String> = vec![]; JsValue::from_serde(&opts).unwrap() } Some(output_d) => { let opts: Vec<_> = output_d .colors .iter() .map(|d| d.options.join("|")) .collect(); JsValue::from_serde(&opts).unwrap() } } } #[wasm_bindgen] pub fn output_colors(output: &mut ExportOutputData) -> *mut i32 { let mut res: Vec<i32> = Vec::new(); let output_d = unsafe { transmute::<_, &mut Option<OutputData>>(output.output_data) }; match output_d { None => res.push(0i32), Some(output_d) => { res.push(output_d.colors.len() as i32); for data in output_d.colors.iter() { // For every output data, first push the length of data vec res.push(data.values.len() as i32); for ones in data.values.iter() { match ones { Some(fv) => res.push(*fv), None => res.push(0), } } } } } res.shrink_to_fit(); let ptr = res.as_mut_ptr(); mem::forget(res); // prevent deallocation in Rust ptr } #[wasm_bindgen] pub struct ExportOutputArray { outputs: *mut OutputDataCollect, } impl Drop for ExportOutputArray { fn drop(&mut self) { unsafe { Box::from_raw(self.outputs); } } } #[wasm_bindgen] pub fn output_array(array: &ExportOutputArray) -> JsValue { let output = unsafe { transmute::<_, &mut OutputDataCollect>(array.outputs) }; JsValue::from_serde(&vec![output.from, output.to, output.data_list.len() as i32]).unwrap() } #[wasm_bindgen] pub fn output_array_get(array: &ExportOutputArray, i: usize) -> ExportOutputData { let output = unsafe { transmute::<_, &mut OutputDataCollect>(array.outputs) }; ExportOutputData { output_data: &mut output.data_list[i], } } fn output_data_to_slice(output: OutputDataCollect) -> ExportOutputArray { ExportOutputArray { outputs: Box::into_raw(Box::new(output)), } } #[wasm_bindgen] pub fn run_with_input( runner: &mut ExportPineRunner, input_val: JsValue, ) -> Result<ExportOutputArray, JsValue> { let runner_ins = unsafe { let script = transmute::<*mut (), *mut PineScript>(runner.script); script.as_mut().unwrap() }; let input: Vec<Option<InputVal>> = input_val.into_serde().unwrap(); match runner_ins.run_with_input(input) { Ok(output) => Ok(output_data_to_slice(output)), Err(err) => Err(JsValue::from_serde(&err).unwrap()), } } fn slice_input_data(origin_data: &[f64], index: usize, count: usize) -> Vec<Option<f64>> { origin_data[index * count..(index + 1) * count] .iter() .map(|s| if *s == f64::NAN { None } else { Some(*s) }) .collect() } fn slice_input_data_i64(origin_data: &[f64], index: usize, count: usize) -> Vec<Option<i64>> { origin_data[index * count..(index + 1) * count] .iter() .map(|s| Some(*s as i64)) .collect() } fn transfer_input_data( src_strs: Vec<String>, count: usize, data: &[f64], ) -> Vec<(&'static str, AnySeries)> { src_strs .into_iter() .enumerate() .map(|(i, s)| match s.as_str() { "close" => ( "close", AnySeries::from_float_vec(slice_input_data(data, i, count)), ), "open" => ( "open", AnySeries::from_float_vec(slice_input_data(data, i, count)), ), "high" => ( "high", AnySeries::from_float_vec(slice_input_data(data, i, count)), ), "low" => ( "low", AnySeries::from_float_vec(slice_input_data(data, i, count)), ), "time" => ( "_time", AnySeries::from_int_vec(slice_input_data_i64(data, i, count)), ), "volume" => ( "volume", AnySeries::from_int_vec(slice_input_data_i64(data, i, count)), ), _ => unreachable!(), }) .collect() } #[wasm_bindgen] pub fn run_with_data( runner: &mut ExportPineRunner, srcs: JsValue, count: usize, data: &[f64], syminfo: JsValue, ) -> Result<ExportOutputArray, JsValue> { let runner_ins = unsafe { let script = transmute::<*mut (), *mut PineScript>(runner.script); script.as_mut().unwrap() }; let src_strs: Vec<String> = srcs.into_serde().unwrap(); debug_assert_eq!(data.len(), src_strs.len() * count); let input_data = transfer_input_data(src_strs, count, data); let info: Option<Rc<SymbolInfo>> = match syminfo.into_serde() { Ok(info) => Some(Rc::new(info)), Err(_) => None, }; log!("Get sym info {:?}", info); match runner_ins.run_with_datal(input_data, count, info) { Ok(output) => Ok(output_data_to_slice(output)), Err(err) => Err(JsValue::from_serde(&err).unwrap()), } } #[wasm_bindgen] pub fn run( runner: &mut ExportPineRunner, input_val: JsValue, srcs: JsValue, count: usize, data: &[f64], syminfo: JsValue, ) -> Result<ExportOutputArray, JsValue> { let runner_ins = unsafe { let script = transmute::<*mut (), *mut PineScript>(runner.script); script.as_mut().unwrap() }; let src_strs: Vec<String> = srcs.into_serde().unwrap(); debug_assert_eq!(data.len(), src_strs.len() * count); let input: Vec<Option<InputVal>> = input_val.into_serde().unwrap(); let input_data = transfer_input_data(src_strs, count, data); let info: Option<Rc<SymbolInfo>> = match syminfo.into_serde() { Ok(info) => Some(Rc::new(info)), Err(_) => None, }; match runner_ins.runl(input, input_data, count, info) { Ok(output) => Ok(output_data_to_slice(output)), Err(err) => Err(JsValue::from_serde(&err).unwrap()), } } #[wasm_bindgen] pub fn update( runner: &mut ExportPineRunner, srcs: JsValue, count: usize, data: &[f64], ) -> Result<ExportOutputArray, JsValue> { let runner_ins = unsafe { let script = transmute::<*mut (), *mut PineScript>(runner.script); script.as_mut().unwrap() }; let src_strs: Vec<String> = srcs.into_serde().unwrap(); debug_assert_eq!(data.len(), src_strs.len() * count); let input_data = transfer_input_data(src_strs, count, data); match runner_ins.updatel(input_data, count) { Ok(output) => Ok(output_data_to_slice(output)), Err(err) => Err(JsValue::from_serde(&err).unwrap()), } } #[wasm_bindgen] pub fn update_from( runner: &mut ExportPineRunner, srcs: JsValue, from: i32, count: usize, data: &[f64], ) -> Result<ExportOutputArray, JsValue> { let runner_ins = unsafe { let script = transmute::<*mut (), *mut PineScript>(runner.script); script.as_mut().unwrap() }; let src_strs: Vec<String> = srcs.into_serde().unwrap(); debug_assert_eq!(data.len(), src_strs.len() * count); let input_data = transfer_input_data(src_strs, count, data); match runner_ins.update_froml(input_data, from, count) { Ok(output) => Ok(output_data_to_slice(output)), Err(err) => Err(JsValue::from_serde(&err).unwrap()), } } impl Drop for ExportPineRunner { fn drop(&mut self) { unsafe { let script = transmute::<*mut (), *mut PineScript>(self.script); Box::from_raw(script); }; } }
// 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 anyerror::AnyError; use common_meta_stoerr::MetaBytesError; use common_meta_stoerr::MetaStorageError; /// Errors that occur when encode/decode #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, thiserror::Error)] #[error("SledBytesError: {source}")] pub struct SledBytesError { #[source] pub source: AnyError, } impl SledBytesError { pub fn new(error: &(impl std::error::Error + 'static)) -> Self { Self { source: AnyError::new(error), } } } impl From<serde_json::Error> for SledBytesError { fn from(e: serde_json::Error) -> Self { Self::new(&e) } } impl From<std::string::FromUtf8Error> for SledBytesError { fn from(e: std::string::FromUtf8Error) -> Self { Self::new(&e) } } // TODO: remove this: after refactoring, sled should not use MetaStorageError directly. impl From<SledBytesError> for MetaStorageError { fn from(e: SledBytesError) -> Self { MetaStorageError::BytesError(MetaBytesError::new(&e)) } }
use std::path::Path; use regex::Regex; use chrono::NaiveDate; use util; include!(concat!(env!("OUT_DIR"), "/post.rs")); fn extract_data_from_filename(filename: &str) -> (&str, &str, u8) { let re = Regex::new(r"^(\d{4}-\d{2}-\d{2})-(\d{3})-(.+)$").unwrap(); let cap = re.captures(filename).unwrap(); let date_str = cap.at(1).unwrap(); let seq = cap.at(2).unwrap().parse::<u8>().unwrap(); let slug = cap.at(3).unwrap(); (date_str, slug, seq) } impl Post { pub fn new(src: &Path) -> Post { fn friendly_date(date: &str) -> String { NaiveDate::parse_from_str(date, "%Y-%m-%d").unwrap().format("%B %d, %Y").to_string() } let filename = src.file_stem().unwrap().to_str().unwrap(); let (date_str, slug, seq) = extract_data_from_filename(filename); let (front_matter, content) = util::parse_front_matter_and_content(src).unwrap(); let title: String = match front_matter.get("title") { Some(t) => t.to_owned(), None => slug.to_owned() }; Post { title: title, slug: slug.to_owned(), content: util::render_markdown(&content), date: date_str.to_owned(), seq: seq, relative_url: format!("p/{}", slug), friendly_date: friendly_date(date_str), } } pub fn fname(&self) -> String { format!("{}-{}-{}", self.date, self.seq, self.slug).to_owned() } pub fn relative_url(&self) -> String { self.relative_url.clone() } } #[test] fn constructs_post_from_filename() { let post = Post::new(Path::new("fixtures/003/_posts/2015-10-26-001-merry-xmas.markdown")); assert_eq!(post.slug, "merry-xmas"); assert_eq!(post.date, "2015-10-26".to_owned()); assert_eq!(post.seq, 1); assert_eq!(post.friendly_date, "October 26, 2015".to_owned()) } #[test] fn reads_title_from_front_matter() { let post = Post::new(Path::new("fixtures/005/_posts/2015-10-26-001-merry-xmas.markdown")); assert_eq!(post.title, "wild merry xmas!".to_owned()); } #[test] fn title_is_taken_from_slug_if_missing() { let post = Post::new(Path::new("fixtures/005/_posts/2015-10-26-002-meh.markdown")); assert_eq!(post.title, "meh".to_owned()); }
// Copyright 2020 - 2021 Alex Dukhno // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::query_engine_old::QueryEngineOld; use native_tls::Identity; use postgre_sql::wire_protocol::PgWireAcceptor; use std::{ env, env::VarError, io::{self, Read}, net::TcpListener, path::{Path, PathBuf}, sync::{Arc, Mutex}, thread, }; use storage::Database; #[derive(Default, Clone)] pub struct NodeEngineOld; impl NodeEngineOld { pub fn start(&self, database: Database) { let listener = TcpListener::bind("0.0.0.0:5432").expect("create listener"); for stream in listener.incoming() { match stream { Err(_) => break, Ok(socket) => { let db = database.clone(); thread::spawn(move || -> io::Result<()> { let acceptor: PgWireAcceptor<Identity> = match (pfx_certificate_path(), pfx_certificate_password()) { (Ok(path), Ok(pass)) => { let mut buff = vec![]; let mut file = std::fs::File::open(path).unwrap(); file.read_to_end(&mut buff)?; PgWireAcceptor::new(Some(Identity::from_pkcs12(&buff, &pass).unwrap())) } _ => PgWireAcceptor::new(None), }; let connection = acceptor.accept(socket).unwrap(); let arc = Arc::new(Mutex::new(connection)); let mut query_engine = QueryEngineOld::new(arc.clone(), db); log::debug!("ready to handle query"); loop { let mut guard = arc.lock().unwrap(); let result = guard.receive(); drop(guard); log::debug!("{:?}", result); match result { Err(e) => { log::error!("UNEXPECTED ERROR: {:?}", e); return Err(e); } Ok(Err(e)) => { log::error!("UNEXPECTED ERROR: {:?}", e); return Err(io::ErrorKind::InvalidInput.into()); } Ok(Ok(client_request)) => match query_engine.execute(client_request) { Ok(()) => {} Err(_) => { break Ok(()); } }, } } }); } } } } } fn pfx_certificate_path() -> Result<PathBuf, VarError> { let file = env::var("PFX_CERTIFICATE_FILE")?; let path = Path::new(&file); if path.is_absolute() { return Ok(path.to_path_buf()); } let current_dir = env::current_dir().unwrap(); Ok(current_dir.as_path().join(path)) } fn pfx_certificate_password() -> Result<String, VarError> { env::var("PFX_CERTIFICATE_PASSWORD") }
//! https://github.com/lumen/otp/tree/lumen/lib/dialyzer/src use super::*; test_compiles_lumen_otp!(dialyzer); test_compiles_lumen_otp!(dialyzer_analysis_callgraph); test_compiles_lumen_otp!(dialyzer_behaviours); test_compiles_lumen_otp!(dialyzer_callgraph); test_compiles_lumen_otp!(dialyzer_cl); test_compiles_lumen_otp!(dialyzer_cl_parse); test_compiles_lumen_otp!(dialyzer_clean_core); test_compiles_lumen_otp!(dialyzer_codeserver); test_compiles_lumen_otp!(dialyzer_contracts); test_compiles_lumen_otp!(dialyzer_coordinator); test_compiles_lumen_otp!(dialyzer_dataflow); test_compiles_lumen_otp!(dialyzer_dep); test_compiles_lumen_otp!(dialyzer_explanation); test_compiles_lumen_otp!(dialyzer_gui_wx); test_compiles_lumen_otp!(dialyzer_options); test_compiles_lumen_otp!(dialyzer_plt); test_compiles_lumen_otp!(dialyzer_race_data_server imports "lib/stdlib/src/dict", "lib/stdlib/src/ordsets"); test_compiles_lumen_otp!(dialyzer_races); test_compiles_lumen_otp!(dialyzer_succ_typings); test_compiles_lumen_otp!(dialyzer_timing imports "lib/stdlib/src/io_lib", "lib/stdlib/src/io_lib"); test_compiles_lumen_otp!(dialyzer_typesig); test_compiles_lumen_otp!(dialyzer_utils); test_compiles_lumen_otp!(dialyzer_worker); test_compiles_lumen_otp!(typer); fn includes() -> Vec<&'static str> { let mut includes = super::includes(); includes.push("lib/dialyzer/src"); includes } fn relative_directory_path() -> PathBuf { super::relative_directory_path().join("dialyzer/src") }
fn main() { proconio::input!{k:u64,a:u64,b:u64}; for i in a..=b{ if i%k==0{ println!("OK"); return } } println!("NG") }
extern crate hyper; extern crate serde; extern crate serde_json; extern crate futures; extern crate uuid; extern crate hyper_tls; extern crate postgres; extern crate crypto; extern crate rustc_serialize as serialize; use crypto::digest::Digest; //use crypto::sha2::Sha256; use serialize::base64::{STANDARD, ToBase64}; use uuid::Uuid; use postgres::{Connection, TlsMode, params::ConnectParams}; use futures::future::*; use futures::Stream; use std::fmt::Debug; use hyper::StatusCode; use hyper::Uri; use hyper::Error; use hyper_tls::HttpsConnector; #[macro_use] extern crate serde_derive; use hyper::{Body, Request, Response, Server, Method, service::Service}; use hyper::rt::Future; use hyper::service::service_fn; fn main() { let addr = ([127, 0, 0, 1], 3000).into(); let server = Server::bind(&addr) .serve(|| { service_fn(handler) }) .map_err(|e| eprintln!("server AppError: {}", e)); hyper::rt::run(server); } fn handler(req: Request<Body>) -> impl Future<Item=Response<Body>, Error=hyper::Error> { parse(req) .and_then(handle) } fn parse(req: Request<Body>) -> impl Future<Item=RawRequest, Error=hyper::Error> { let method = req.method().clone(); let target = req.uri().to_string(); parse_body(req.into_body()) .and_then(move |body| { ok(RawRequest { method, target, body }) }) } fn parse_body(body: Body) -> impl Future<Item=Vec<u8>, Error=hyper::Error> { body.fold(Vec::new(), |mut v, chunk| { v.extend(&chunk[..]); ok::<_, hyper::Error>(v) }) } struct RawRequest { method: Method, target: String, body: Vec<u8> } fn handle(req: RawRequest) -> impl Future<Item=Response<Body>, Error=hyper::Error> { (match (req.method, req.target.as_str(), req.body) { (Method::POST, "/login", body) => handle_basic_login(body), (Method::POST, "/login/fb", body) => handle_fb_login(body), _ => Box::new(err(AppError::RoutingError)) }) .then(|res| { match res { Ok(session) => successful_login(session), Err(error) => error_to_response(error) } }) .from_err() } impl std::convert::From<AppError> for hyper::Error { fn from(error: AppError) -> Self { panic!("I don't know what to do") } } fn error_to_response(error: AppError) -> Box<Future<Item=Response<Body>, Error=hyper::Error> + Send> { Box::new(ok(Response::builder() .status(error.to_status()) .body(Body::empty()) .unwrap() )) } fn handle_basic_login(body: Vec<u8>) -> Box<Future<Item=Session, Error=AppError> + Send> { let basic_login_request = BasicLoginRequest::from(body).unwrap(); println!("login {} {}", basic_login_request.email, basic_login_request.password); authorize_basic(basic_login_request) } fn handle_fb_login(body: Vec<u8>) -> Box<Future<Item=Session, Error=AppError> + Send> { let req = FBLoginRequest::from(body).unwrap(); println!("login {}", req.token); authorize_fb(req) } fn authorize_fb(req: FBLoginRequest) -> Box<Future<Item=Session, Error=AppError> + Send> { let url = format!("https://graph.facebook.com/me?access_token={}", req.token); match url.as_str().parse::<Uri>() { Ok(uri) => { let https = HttpsConnector::new(4).unwrap(); let client = hyper::Client::builder().build::<_, hyper::Body>(https); println!("checking fb auth token, url: {}", uri); Box::new( client .get(uri) .map_err(|error| { // TOOD: to AppError match error.into_cause() { Some(err) => println!("{}", err.description()), None => println!("хрен разберет") } AppError::ApplicationError }) .and_then(check_status) .and_then(get_fb_user_data) .and_then(upsertUser) .and_then(create_session) ) }, Err(err) => { println!("fb response failed, {}", err); Box::new(futures::future::err(AppError::BadRequest)) } } } fn check_status(resp: Response<Body>) -> impl Future<Item=Response<Body>, Error=AppError> + Send { println!("{}", resp.status()); match resp.status() { hyper::StatusCode::OK => ok(resp), error => err(AppError::from(error)) } } fn get_fb_user_data(resp: Response<Body>) -> impl Future<Item=User, Error=AppError> + Send { convert_and_parse(resp) .map_err(|err| AppError::ApplicationError) .and_then(|parsed| { let fb_data : serde_json::Value = serde_json::from_slice(&parsed).unwrap(); ok(User { id: fb_data["id"].to_string(), email: fb_data["email"].to_string(), password: "s".to_string() }) }) } fn convert_and_parse(resp: Response<Body>) -> impl Future<Item=Vec<u8>, Error=hyper::Error> + Send { parse_body(resp.into_body()) } fn upsertUser(user: User) -> impl Future<Item=User, Error=AppError> + Send { ok(user) } #[derive(Serialize, Deserialize)] struct FBLoginRequest { token: String } impl FBLoginRequest { fn from(body: Vec<u8>) -> Result<FBLoginRequest, AppError> { Ok(serde_json::from_slice(&body).unwrap()) } } fn successful_login(session: Session) -> Box<Future<Item=Response<Body>, Error=hyper::Error> + Send> { Box::new(ok(Response::builder() .status(200) .body(Body::from(serde_json::to_string(&session).unwrap())).unwrap())) } #[derive(Serialize, Deserialize)] struct Session { id: String } fn authorize_basic(req: BasicLoginRequest) -> Box<Future<Item=Session, Error=AppError> + Send> { Box::new(find_user_by_email(&req.email) .and_then(move | user| { validate_password(user, req.password) })) } fn validate_password(user: User, password: String) -> Box<Future<Item=Session, Error=AppError> + Send> { match password::check_password(&user.password, &password) { Ok(true) => create_session(user), Ok(false) => Box::new(err(AppError::Unauthorized)), Err(_) => Box::new(err(AppError::ApplicationError)) } } pub mod password { use crypto::digest::Digest; use crypto::hmac::Hmac; use crypto::mac::Mac; use crypto::sha2::Sha256; use crypto::mac::MacResult; use serialize::base64::{STANDARD, ToBase64, Config, CharacterSet, Newline}; pub fn check_password(hashed_password: &str, password: &str) -> Result<bool, super::AppError> { let mut sha = Sha256::new(); let mut hmac = Hmac::new(sha, b"my key"); hmac.input(password.as_bytes()); let hash1 = hmac.result().code().to_base64(Config {char_set: CharacterSet::Standard, newline: Newline::CRLF, pad: true, line_length: Some(76)}); println!("password supplied: {}, password in db: {}, hash: {}", password, hashed_password, hash1); match hash1 == hashed_password { true => { println!("User authorized"); Ok(true) }, false => { println!("User NOT authorized"); Err(super::AppError::Unauthorized) } } } } fn create_session(user: User) -> Box<Future<Item=Session, Error=AppError> + Send> { let session = Session { id: uuid::Uuid::new_v4().to_string() }; Box::new(match Connection::connect("postgres://postgres:1@localhost:5432/auth", TlsMode::None) { Ok(conn) => match &conn.execute("INSERT into public.session (session_id, user_id) values($1,$2)", &[ &session.id, &user.id ]) { Ok(_) => ok(session), Err(error) => { println!("Pos1{}", error); err(AppError::ApplicationError) } } Err(error) => { println!("Pos2{}", error); err(AppError::ApplicationError) } }) } fn find_user_by_email(email: &str) -> Box<Future<Item=User, Error=AppError> + Send> { Box::new(match Connection::connect("postgres://postgres:1@localhost:5432/auth", TlsMode::None) { Ok(conn) => match &conn.query("SELECT id, email, password FROM public.person where email = $1", &[ &email ]) { Ok(rows) => if !rows.is_empty() { let row = rows.get(0); println!("found user"); ok(User { id: row.get("id"), email: row.get("email"), password: row.get("password") }) } else { println!("no user found"); err(AppError::Unauthorized) }, Err(error) => { println!("Pos1{}", error); err(AppError::ApplicationError) } } Err(error) => { println!("Pos2{}", error); err(AppError::ApplicationError) } }) } #[derive(Serialize, Deserialize)] pub enum AppError { ApplicationError, RoutingError, Unauthorized, BadRequest } impl AppError { fn from(statusCode: hyper::StatusCode) -> AppError { match statusCode { hyper::StatusCode::NOT_FOUND => AppError::RoutingError, hyper::StatusCode::FORBIDDEN => AppError::Unauthorized, _ => AppError::BadRequest } } fn to_status(&self) -> StatusCode { (match &self { AppError::ApplicationError => StatusCode::from_u16(500), AppError::RoutingError => StatusCode::from_u16(404), AppError::Unauthorized => StatusCode::from_u16(403), AppError::BadRequest => StatusCode::from_u16(400) }).unwrap() } } impl Debug for AppError { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { Ok(()) } } struct User { pub id: String, pub email: String, pub password: String } #[derive(Serialize, Deserialize)] struct BasicLoginRequest { email: String, password: String } impl BasicLoginRequest { fn from(body: Vec<u8>) -> Result<BasicLoginRequest, AppError> { Ok(serde_json::from_slice(&body).unwrap()) } }
use move_vm::data::Oracle; #[derive(Clone, Copy, Default)] pub struct DummyOracle; impl Oracle for DummyOracle { fn get_price(&self, _ticker: &str) -> Option<u128> { None } }
use std::fs::File; use std::io::{BufRead, BufReader}; use std::collections::HashMap; fn main() { println!("Part 1 checksum is: {}", part_1()); println!("Part 2 correct box ids: {:?}", part_2()); } fn part_1() -> i32 { let filename = "src/input.txt"; let mut pairs = 0; let mut triplets = 0; let file = File::open(filename).unwrap(); let reader = BufReader::new(file); for line in reader.lines() { match line { Ok(str) => { let mut hash = HashMap::new(); for id in str.chars() { match hash.get(&id) { Some(count) => hash.insert(id, count + 1), _ => hash.insert(id, 1) }; } let mut has_pair = false; let mut has_triplet = false; for val in hash.values() { if val == &2 { has_pair = true; } else if val == &3 { has_triplet = true; } } if has_pair { pairs += 1; } if has_triplet { triplets += 1; } } Err(e) => println!("Could not read line: {}", e) } } return pairs * triplets; } fn part_2() -> (String, String) { let filename = "src/input.txt"; let file = File::open(filename).unwrap(); let reader = BufReader::new(file); let mut box_ids: Vec<String> = vec![]; let mut common_box_ids: (String, String) = (String::from("DID"), String::from("NOT WORK")); for line in reader.lines() { match line { Ok(str) => { for box_id in &box_ids { let mut num_of_different_indexs = 0; let mut current_chars = str.chars(); for char_a in box_id.chars() { if char_a != current_chars.next().unwrap() { num_of_different_indexs += 1; } } if num_of_different_indexs <= 1 { common_box_ids = (box_id.clone(), str.clone()); } } box_ids.push(str); } Err(e) => println!("Could not read line: {}", e) } } return common_box_ids; }
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(generic_associated_types)] //FIXME(#44265): The lifetime shadowing and type parameter shadowing // should cause an error. Now it compiles (errorneously) and this will be addressed // by a future PR. Then remove the following: // compile-pass trait Shadow<'a> { type Bar<'a>; // Error: shadowed lifetime } trait NoShadow<'a> { type Bar<'b>; // OK } impl<'a> NoShadow<'a> for &'a u32 { type Bar<'a> = i32; // Error: shadowed lifetime } trait ShadowT<T> { type Bar<T>; // Error: shadowed type parameter } trait NoShadowT<T> { type Bar<U>; // OK } impl<T> NoShadowT<T> for Option<T> { type Bar<T> = i32; // Error: shadowed type parameter } fn main() {}
#[doc = "Reader of register D3PCR2L"] pub type R = crate::R<u32, super::D3PCR2L>; #[doc = "Writer for register D3PCR2L"] pub type W = crate::W<u32, super::D3PCR2L>; #[doc = "Register D3PCR2L `reset()`'s with value 0"] impl crate::ResetValue for super::D3PCR2L { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `PCS35`"] pub type PCS35_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PCS35`"] pub struct PCS35_W<'a> { w: &'a mut W, } impl<'a> PCS35_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 6)) | (((value as u32) & 0x03) << 6); self.w } } #[doc = "Reader of field `PCS34`"] pub type PCS34_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PCS34`"] pub struct PCS34_W<'a> { w: &'a mut W, } impl<'a> PCS34_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 4)) | (((value as u32) & 0x03) << 4); self.w } } #[doc = "Reader of field `PCS41`"] pub type PCS41_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PCS41`"] pub struct PCS41_W<'a> { w: &'a mut W, } impl<'a> PCS41_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 18)) | (((value as u32) & 0x03) << 18); self.w } } impl R { #[doc = "Bits 6:7 - D3 Pending request clear input signal selection on Event input x = truncate ((n+64)/2)"] #[inline(always)] pub fn pcs35(&self) -> PCS35_R { PCS35_R::new(((self.bits >> 6) & 0x03) as u8) } #[doc = "Bits 4:5 - D3 Pending request clear input signal selection on Event input x = truncate ((n+64)/2)"] #[inline(always)] pub fn pcs34(&self) -> PCS34_R { PCS34_R::new(((self.bits >> 4) & 0x03) as u8) } #[doc = "Bits 18:19 - D3 Pending request clear input signal selection on Event input x = truncate ((n+64)/2)"] #[inline(always)] pub fn pcs41(&self) -> PCS41_R { PCS41_R::new(((self.bits >> 18) & 0x03) as u8) } } impl W { #[doc = "Bits 6:7 - D3 Pending request clear input signal selection on Event input x = truncate ((n+64)/2)"] #[inline(always)] pub fn pcs35(&mut self) -> PCS35_W { PCS35_W { w: self } } #[doc = "Bits 4:5 - D3 Pending request clear input signal selection on Event input x = truncate ((n+64)/2)"] #[inline(always)] pub fn pcs34(&mut self) -> PCS34_W { PCS34_W { w: self } } #[doc = "Bits 18:19 - D3 Pending request clear input signal selection on Event input x = truncate ((n+64)/2)"] #[inline(always)] pub fn pcs41(&mut self) -> PCS41_W { PCS41_W { w: self } } }
#[macro_use] extern crate rouille; use std::io; fn main() { // This example demonstrates how to handle HTML forms. // Note that like all examples we only listen on `localhost`, so you can't access this server // from another machine than your own. println!("Now listening on localhost:8000"); rouille::start_server("localhost:8000", move |request| { rouille::log(&request, io::stdout(), || { router!(request, (GET) (/) => { // When viewing the home page, we return an HTML document described below. rouille::Response::html(FORM) }, (POST) (/submit) => { // This is the route that is called when the user submits the form of the // home page. // We query the data with the `post_input!` macro. Each field of the macro // corresponds to an element of the form. // If the macro returns an error (for example if a field is missing, which // can happen if you screw up the form or if the user made a manual request) // we return a 400 response. let data = try_or_400!(post_input!(request, { txt: String, files: Vec<rouille::input::post::BufferedFile>, })); // We just print what was received on stdout. Of course in a real application // you probably want to process the data, eg. store it in a database. println!("Received data: {:?}", data); rouille::Response::html("Success! <a href=\"/\">Go back</a>.") }, _ => rouille::Response::empty_404() ) }) }); } // The HTML document of the home page. static FORM: &'static str = r#" <html> <head> <title>Form</title> </head> <body> <form action="submit" method="POST" enctype="multipart/form-data"> <p><input type="text" name="txt" placeholder="Some text" /></p> <p><input type="file" name="files" multiple /></p> <p><button>Upload</button></p> </form> </body> </html> "#;
use ffi::cfhost::*; pub struct Host { host_ref: CFHostRef } impl Host { fn new_with_name(host_name: &str) { } }
use std::any::Any; use crate::Mutator; /// A [`FilterMutator`] provides a way to filter values outputted by a mutator. /// Given any [`Mutator<Value=T>`] and a function [`Fn(&T) -> bool`] it creates /// a new mutator which can generate all the values of `T` the underlying /// mutator can, except those for which the filtering function returns false. pub struct FilterMutator<M, F> { mutator: M, filter: F, } impl<M, F> FilterMutator<M, F> { /// Creates a new [`FilterMutator`]. /// /// Note that the mutator will filter all values for which the filtering /// function returns _false_. pub fn new<T>(mutator: M, filter: F) -> FilterMutator<M, F> where M: Mutator<T>, T: Clone + 'static, F: Fn(&T) -> bool, Self: 'static, { FilterMutator { mutator, filter } } } impl<T, M, F> Mutator<T> for FilterMutator<M, F> where M: Mutator<T>, T: Clone + 'static, F: Fn(&T) -> bool, Self: 'static, { #[doc(hidden)] type Cache = <M as Mutator<T>>::Cache; #[doc(hidden)] type MutationStep = <M as Mutator<T>>::MutationStep; #[doc(hidden)] type ArbitraryStep = <M as Mutator<T>>::ArbitraryStep; #[doc(hidden)] type UnmutateToken = <M as Mutator<T>>::UnmutateToken; #[doc(hidden)] #[no_coverage] fn initialize(&self) { self.mutator.initialize(); } #[doc(hidden)] #[no_coverage] fn default_arbitrary_step(&self) -> Self::ArbitraryStep { self.mutator.default_arbitrary_step() } #[doc(hidden)] #[no_coverage] fn is_valid(&self, value: &T) -> bool { self.mutator.is_valid(value) && (self.filter)(value) } #[doc(hidden)] #[no_coverage] fn validate_value(&self, value: &T) -> Option<Self::Cache> { let x = self.mutator.validate_value(value); if x.is_some() && (self.filter)(value) == false { None } else { x } } #[doc(hidden)] #[no_coverage] fn default_mutation_step(&self, value: &T, cache: &Self::Cache) -> Self::MutationStep { self.mutator.default_mutation_step(value, cache) } #[doc(hidden)] #[no_coverage] fn max_complexity(&self) -> f64 { self.mutator.max_complexity() } #[doc(hidden)] #[no_coverage] fn global_search_space_complexity(&self) -> f64 { self.mutator.global_search_space_complexity() } #[doc(hidden)] #[no_coverage] fn min_complexity(&self) -> f64 { self.mutator.min_complexity() } #[doc(hidden)] #[no_coverage] fn complexity(&self, value: &T, cache: &Self::Cache) -> f64 { self.mutator.complexity(value, cache) } #[doc(hidden)] #[no_coverage] fn ordered_arbitrary(&self, step: &mut Self::ArbitraryStep, max_cplx: f64) -> Option<(T, f64)> { loop { let x = self.mutator.ordered_arbitrary(step, max_cplx); if let Some(x) = x { if (self.filter)(&x.0) { return Some(x); } } else { return None; } } } #[doc(hidden)] #[no_coverage] fn random_arbitrary(&self, max_cplx: f64) -> (T, f64) { loop { let x = self.mutator.random_arbitrary(max_cplx); if (self.filter)(&x.0) { return x; } } } #[doc(hidden)] #[no_coverage] fn ordered_mutate( &self, value: &mut T, cache: &mut Self::Cache, step: &mut Self::MutationStep, subvalue_provider: &dyn crate::SubValueProvider, max_cplx: f64, ) -> Option<(Self::UnmutateToken, f64)> { loop { if let Some((t, cplx)) = self .mutator .ordered_mutate(value, cache, step, subvalue_provider, max_cplx) { if (self.filter)(value) { return Some((t, cplx)); } else { self.mutator.unmutate(value, cache, t); } } else { return None; } } } #[doc(hidden)] #[no_coverage] fn random_mutate(&self, value: &mut T, cache: &mut Self::Cache, max_cplx: f64) -> (Self::UnmutateToken, f64) { loop { let (t, cplx) = self.mutator.random_mutate(value, cache, max_cplx); if (self.filter)(value) { return (t, cplx); } else { self.mutator.unmutate(value, cache, t); } } } #[doc(hidden)] #[no_coverage] fn unmutate(&self, value: &mut T, cache: &mut Self::Cache, t: Self::UnmutateToken) { self.mutator.unmutate(value, cache, t) } #[doc(hidden)] #[no_coverage] fn visit_subvalues<'a>(&self, value: &'a T, cache: &'a Self::Cache, visit: &mut dyn FnMut(&'a dyn Any, f64)) { self.mutator.visit_subvalues(value, cache, visit) } }
use core::Material;
use chrono::{DateTime, Utc}; use mongodb::bson::oid::ObjectId; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::convert::TryFrom; #[derive(Serialize, Deserialize, Debug, Clone)] struct Quantity { #[serde(skip_serializing_if = "Option::is_none")] value: Option<Value>, #[serde(skip_serializing_if = "Option::is_none")] unit: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] struct Ingredient { name: String, quantity: Option<Quantity>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Cocktail { #[serde(rename = "_id", skip_serializing_if = "Option::is_none")] id: Option<ObjectId>, slug: String, name: String, ingredients: Vec<Ingredient>, instructions: Vec<String>, #[serde(skip_serializing_if = "Option::is_none")] pub date_added: Option<DateTime<Utc>>, #[serde(skip_serializing_if = "Option::is_none")] pub date_updated: Option<DateTime<Utc>>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct CocktailJSON { #[serde(skip_serializing_if = "Option::is_none")] id: Option<String>, slug: String, name: String, ingredients: Vec<Ingredient>, instructions: Vec<String>, #[serde(skip_serializing_if = "Option::is_none")] date_added: Option<DateTime<Utc>>, #[serde(skip_serializing_if = "Option::is_none")] date_updated: Option<DateTime<Utc>>, } impl From<Cocktail> for CocktailJSON { fn from(cocktail: Cocktail) -> Self { Self { id: cocktail.id.map(|id| id.to_hex()), slug: cocktail.slug, name: cocktail.name, ingredients: cocktail.ingredients, instructions: cocktail.instructions, date_added: cocktail.date_added, date_updated: cocktail.date_updated, } } } impl TryFrom<CocktailJSON> for Cocktail { type Error = mongodb::bson::oid::Error; fn try_from(cocktail: CocktailJSON) -> Result<Self, Self::Error> { let cocktail_oid = match cocktail.id { Some(id) => Some(ObjectId::with_string(&id)?), None => None, }; Ok(Self { id: cocktail_oid, slug: cocktail.slug, name: cocktail.name, ingredients: cocktail.ingredients, instructions: cocktail.instructions, date_added: cocktail.date_added, date_updated: cocktail.date_updated, }) } }
// Copyright (c) 2018-2022 Ministerio de Fomento // Instituto de Ciencias de la Construcción Eduardo Torroja (IETcc-CSIC) // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // Author(s): Rafael Villar Burke <pachi@ietcc.csic.es>, // Daniel Jiménez González <dani@ietcc.csic.es>, // Marta Sorribes Gil <msorribes@ietcc.csic.es> use crate::types::*; use crate::Components; use crate::Factors; // ==================== Conversión a XML de CTE y CEE /// Muestra en formato XML de CTE y CEE /// /// Esta función usa un formato compatible con el formato XML del certificado de eficiencia /// energética del edificio definido en el documento de apoyo de la certificación energética /// correspondiente. pub trait AsCteXml { /// Get list of values fn to_xml(&self) -> String; /// Helper function -> XML escape symbols fn escape_xml(unescaped: &str) -> String { unescaped .replace('&', "&amp;") .replace('<', "&lt;") .replace('>', "&gt;") .replace('\\', "&apos;") .replace('"', "&quot;") } /// Convert list of numbers to string of comma separated values (2 decimal digits) fn format_values_2f(values: &[f32]) -> String { values .iter() .map(|v| format!("{:.2}", v)) .collect::<Vec<String>>() .join(",") } } // ================= Implementaciones ==================== impl AsCteXml for EnergyPerformance { fn to_xml(&self) -> String { // Data let RenNrenCo2 { ren, nren, .. } = self.balance_m2.we.b; // Formatting let wfstring = self.wfactors.to_xml(); let components_string = self.components.to_xml(); // Final assembly format!( "<BalanceEPB> {} {} <kexp>{:.2}</kexp> <AreaRef>{:.2}</AreaRef><!-- área de referencia [m2] --> <Epm2><!-- C_ep [kWh/m2.an] --> <tot>{:.1}</tot> <nren>{:.1}</nren> </Epm2> </BalanceEPB>", wfstring, components_string, self.k_exp, self.arearef, ren + nren, nren ) } } impl AsCteXml for Meta { fn to_xml(&self) -> String { format!( "<Metadato><Clave>{}</Clave><Valor>{}</Valor></Metadato>", <Self as AsCteXml>::escape_xml(&self.key), <Self as AsCteXml>::escape_xml(&self.value) ) } } impl AsCteXml for Factor { fn to_xml(&self) -> String { let Factor { carrier, source, dest, step, ren, nren, co2, comment, } = self; let comentario = if comment.is_empty() {String::new()} else { format!("<Comentario>{}</Comentario>", <Self as AsCteXml>::escape_xml(comment)) }; format!( "<Factor><Vector>{}</Vector><Origen>{}</Origen><Destino>{}</Destino><Paso>{}</Paso><ren>{:.3}</ren><nren>{:.3}</nren><co2>{:.3}</co2>{}</Factor>", carrier, source, dest, step, ren, nren, co2, comentario ) } } impl AsCteXml for Factors { fn to_xml(&self) -> String { let Factors { wmeta, wdata } = self; let wmetastring = wmeta .iter() .map(AsCteXml::to_xml) .collect::<Vec<String>>() .join("\n"); let wdatastring = wdata .iter() .map(AsCteXml::to_xml) .collect::<Vec<String>>() .join("\n"); format!( "<FactoresDePaso> {} {} </FactoresDePaso>", wmetastring, wdatastring ) } } impl AsCteXml for Components { fn to_xml(&self) -> String { let Components { meta, data, needs, } = self; let metastring = meta .iter() .map(AsCteXml::to_xml) .collect::<Vec<String>>() .join("\n"); let datastring = data .iter() .map(AsCteXml::to_xml) .collect::<Vec<String>>() .join("\n"); let needsdatastring = { let mut res = vec![]; if let Some(nd) = &needs.ACS { res.push(format!("<Demanda><Servicio>ACS</Servicio><Valores>{}</Valores>", <Self as AsCteXml>::format_values_2f(nd))) }; if let Some(nd) = &needs.CAL { res.push(format!("<Demanda><Servicio>CAL</Servicio><Valores>{}</Valores>", <Self as AsCteXml>::format_values_2f(nd))) }; if let Some(nd) = &needs.REF { res.push(format!("<Demanda><Servicio>REF</Servicio><Valores>{}</Valores>", <Self as AsCteXml>::format_values_2f(nd))) }; res.join("\n") }; format!( "<Componentes> {} {} {} </Componentes>", metastring, datastring, needsdatastring ) } } impl AsCteXml for Energy { fn to_xml(&self) -> String { match self { Energy::Used(e) => e.to_xml(), Energy::Prod(e) => e.to_xml(), Energy::Aux(e) => e.to_xml(), Energy::Out(e) => e.to_xml(), } } } impl AsCteXml for EProd { /// Convierte componente de energía producida a XML fn to_xml(&self) -> String { let Self { id, source, values, comment, } = self; let comentario = if comment.is_empty() {String::new()} else { format!("<Comentario>{}</Comentario>", <Self as AsCteXml>::escape_xml(comment)) }; format!( "<Produccion><Id>{}</Id><Origen>{}</Origen><Valores>{}</Valores>{}</Produccion>", id, source, <Self as AsCteXml>::format_values_2f(values), comentario ) } } impl AsCteXml for EUsed { /// Convierte componente de energía consumida a XML fn to_xml(&self) -> String { let Self { id, carrier, service, values, comment, } = self; let comentario = if comment.is_empty() {String::new()} else { format!("<Comentario>{}</Comentario>", <Self as AsCteXml>::escape_xml(comment)) }; format!( "<Consumo><Id>{}</Id><Vector>{}</Vector><Servicio>{}</Servicio><Valores>{}</Valores>{}</Consumo>", id, carrier, service, <Self as AsCteXml>::format_values_2f(values), comentario ) } } impl AsCteXml for EAux { /// Convierte componente de energía auxiliar a XML fn to_xml(&self) -> String { let Self { id, service, values, comment, } = self; let comentario = if comment.is_empty() {String::new()} else { format!("<Comentario>{}</Comentario>", <Self as AsCteXml>::escape_xml(comment)) }; format!( "<EAux><Id>{}</Id><Servicio>{}</Servicio><Valores>{}</Valores>{}</EAux>", id, service, <Self as AsCteXml>::format_values_2f(values), comentario ) } } impl AsCteXml for EOut { /// Convierte componente de energía auxiliar a XML fn to_xml(&self) -> String { let Self { id, service, values, comment, } = self; let comentario = if comment.is_empty() {String::new()} else { format!("<Comentario>{}</Comentario>", <Self as AsCteXml>::escape_xml(comment)) }; format!( "<Salida><Id>{}</Id><Servicio>{}</Servicio><Valores>{}</Valores>{}</Salida>", id, service, <Self as AsCteXml>::format_values_2f(values), comentario ) } } impl AsCteXml for Needs { /// Convierte elementos de demanda del edificio a XML fn to_xml(&self) -> String { let Self { service, values } = self; format!( "<DemandaEdificio><Servicio>{}</Servicio><Valores>{}</Valores></DemandaEdificio>", service, <Self as AsCteXml>::format_values_2f(values) ) } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type DnssdRegistrationResult = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct DnssdRegistrationStatus(pub i32); impl DnssdRegistrationStatus { pub const Success: Self = Self(0i32); pub const InvalidServiceName: Self = Self(1i32); pub const ServerError: Self = Self(2i32); pub const SecurityError: Self = Self(3i32); } impl ::core::marker::Copy for DnssdRegistrationStatus {} impl ::core::clone::Clone for DnssdRegistrationStatus { fn clone(&self) -> Self { *self } } pub type DnssdServiceInstance = *mut ::core::ffi::c_void; pub type DnssdServiceInstanceCollection = *mut ::core::ffi::c_void; pub type DnssdServiceWatcher = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct DnssdServiceWatcherStatus(pub i32); impl DnssdServiceWatcherStatus { pub const Created: Self = Self(0i32); pub const Started: Self = Self(1i32); pub const EnumerationCompleted: Self = Self(2i32); pub const Stopping: Self = Self(3i32); pub const Stopped: Self = Self(4i32); pub const Aborted: Self = Self(5i32); } impl ::core::marker::Copy for DnssdServiceWatcherStatus {} impl ::core::clone::Clone for DnssdServiceWatcherStatus { fn clone(&self) -> Self { *self } }
use std::collections::HashMap; #[derive(Clone, Debug, Eq, PartialEq)] pub struct GuardRule { pub origin: String, pub ty: RuleType, pub level: RuleLevel, pub scope: RuleScope, pub expr: Expr, pub ops: Vec<Operator>, pub assert: RuleAssert } #[derive(Clone, Debug, Eq, PartialEq)] pub enum LayeredRule { Normal(NormalLayered), Onion(OnionArch) } #[derive(Clone, Debug, Eq, PartialEq)] pub struct NormalLayered { } #[derive(Clone, Debug, Eq, PartialEq)] pub struct OnionArch { } impl Default for GuardRule { fn default() -> Self { GuardRule { origin: "".to_string(), ty: RuleType::Normal, level: RuleLevel::Class, scope: RuleScope::All, expr: Expr::Identifier("".to_string()), ops: vec![], assert: RuleAssert::Empty } } } impl GuardRule { pub fn assert_sized(rule: &GuardRule) -> usize { let mut size = 0; match &rule.assert { RuleAssert::Sized(sized) => { size = *sized; } _ => {} } size } pub fn assert_string(rule: &GuardRule) -> String { let mut string = "".to_string(); match &rule.assert { RuleAssert::Stringed(str) => { string = str.clone(); } _ => {} } string } pub fn package_level(rule: &GuardRule) -> (bool, RuleLevel, String) { let mut string = "".to_string(); let mut level = RuleLevel::Package; let mut has_capture = false; match &rule.assert { RuleAssert::Leveled(lv, package_ident) => { has_capture = true; level = lv.clone(); string = package_ident.clone(); } _ => {} } return (has_capture, level, string); } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum RuleType { Normal, Layer, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum RuleLevel { Package, Function, Class, Struct, } #[derive(Clone, Debug, Eq, PartialEq)] pub enum RuleScope { All, PathDefine(String), Extend(String), Assignable(String), Implementation(String), MatchRegex(String), } #[derive(Clone, Debug, Eq, PartialEq)] pub enum Expr { PropsCall(Vec<String>), Identifier(String) } /// A function call, can be a filter or a global function #[derive(Clone, Debug, Eq, PartialEq)] pub struct FunctionCall { /// The name of the function pub name: String, /// The args of the function: key -> value pub args: HashMap<String, Expr>, } impl FunctionCall { pub fn new(name: String) -> FunctionCall { FunctionCall { name, args: Default::default() } } } impl Default for FunctionCall { fn default() -> Self { FunctionCall { name: "".to_string(), args: Default::default() } } } #[derive(Clone, Debug, Eq, PartialEq)] pub enum Operator { /// > Gt, /// >= Gte, /// < Lt, /// <= Lte, /// == Eq, /// != Ineq, /// and And, /// or Or, /// ! /// not Not, // string assert operator StartsWith, Endswith, Contains, // package operators Inside, ResideIn, Accessed, DependBy } #[derive(Clone, Debug, Eq, PartialEq)] pub enum RuleAssert { Empty, Stringed(String), Leveled(RuleLevel, String), ArrayStringed(Vec<String>), Sized(usize), }
use crate::homogeneous::Homogeneous; use ndarray::{Array, Array2, ArrayBase, ArrayView1, ArrayView2, Axis, Data, LinalgScalar, Ix1, Ix2, stack}; pub trait Transform<A, D, Rhs> { fn transform(&self, points0: &Rhs) -> Array<A, D>; } macro_rules! impl_transform { (for $($d:ty),+) => { $(impl<A, S1, S2> Transform<A, $d, ArrayBase<S2, $d>> for ArrayBase<S1, Ix2> where S1: Data<Elem = A>, S2: Data<Elem = A>, A: LinalgScalar, { fn transform(&self, points0: &ArrayBase<S2, $d>) -> Array<A, $d> { let points0 = &points0.to_homogeneous(); let points0 = points0.t(); let points1 = self.dot(&points0); let points1 = points1.t(); points1.from_homogeneous().to_owned() } })* } } impl_transform!(for Ix1, Ix2); pub fn get_rotation<'a, A, S>( transform: &'a ArrayBase<S, Ix2> ) -> ArrayView2<'a, A> where S: Data<Elem = A>, A: LinalgScalar, { transform.slice(s![0..3, 0..3]) } pub fn get_translation<'a, A, S>( transform: &'a ArrayBase<S, Ix2> ) -> ArrayView1<'a, A> where S: Data<Elem = A>, A: LinalgScalar, { transform.slice(s![0..3, 3]) } pub fn make_matrix<A, S1, S2>( rotation: &ArrayBase<S1, Ix2>, translation: &ArrayBase<S2, Ix1> ) -> Array2<A> where S1: Data<Elem = A>, S2: Data<Elem = A>, A: LinalgScalar { let d = rotation.shape()[1]; let translation = translation.to_owned(); let translation = translation.into_shape((d, 1)).unwrap(); stack![ Axis(0), stack![Axis(1), rotation.view(), translation.view()], stack![Axis(1), Array::zeros((1, d)), Array::ones((1, 1))] ] } pub fn inv_transform<A, S>(transform: &ArrayBase<S, Ix2>) -> Array2<A> where S: Data<Elem = A>, A: LinalgScalar + std::ops::Neg<Output = A> { let rotation = get_rotation(&transform); let t = get_translation(&transform); let rt = rotation.t().dot(&t); return make_matrix(&rotation.t(), &(rt.map(|&e| -e))); } #[cfg(test)] mod tests { use super::*; use ndarray::{arr1, arr2}; #[test] fn test_transform_points() { let points0 = arr2(&[[1, 2, 5], [4, -2, 3]]); let transform10 = arr2(&[ [1, 0, 0, 1], [0, 0, -1, 2], [0, 1, 0, 3], [0, 0, 0, 1], ]); let points1 = arr2(&[[2, -3, 5], [5, -1, 1]]); assert_eq!(transform10.transform(&points0), points1); } #[test] fn test_transform_point() { let point0 = arr1(&[1, 2, 5]); let transform10 = arr2(&[ [1, 0, 0, 1], [0, 0, -1, 2], [0, 1, 0, 3], [0, 0, 0, 1], ]); let point1 = arr1(&[2, -3, 5]); assert_eq!(transform10.transform(&point0), point1); } #[test] fn test_get_rotation() { let transform = arr2(&[[1, 2, 3, -1], [4, 5, 6, -2], [7, 8, 9, -3], [0, 0, 0, 1]]); let expected = arr2(&[[1, 2, 3], [4, 5, 6], [7, 8, 9]]); assert_eq!(get_rotation(&transform.view()), expected.view()); } #[test] fn test_get_translation() { let transform = arr2(&[[1, 2, 3, -1], [4, 5, 6, -2], [7, 8, 9, -3], [0, 0, 0, 1]]); let expected = arr1(&[-1, -2, -3]); assert_eq!(get_translation(&transform.view()), expected.view()); } #[test] fn test_make_matrix() { let rotation = arr2(&[[1, 2, 3], [4, 5, 6], [7, 8, 9]]); let translation = arr1(&[-1, -2, -3]); let expected = arr2(&[[1, 2, 3, -1], [4, 5, 6, -2], [7, 8, 9, -3], [0, 0, 0, 1]]); assert_eq!(make_matrix(&rotation, &translation), expected); } #[test] fn test_inv_transform() { let transform = arr2(&[[1., 0., 0., -1.], [0., 0., 1., -2.], [0., -1., 0., 3.], [0., 0., 0., 1.]]); assert_eq!(inv_transform(&transform).dot(&transform), arr2(&[[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]])); } }
use candy_frontend::{ cst::{Cst, CstKind, UnwrapWhitespaceAndComment}, module::{Module, ModuleDb}, position::PositionConversionDb, rcst_to_cst::RcstToCst, }; use enumset::EnumSet; use lsp_types::{self, SemanticToken}; use crate::semantic_tokens::{SemanticTokenType, SemanticTokensBuilder}; pub fn semantic_tokens<DB: ModuleDb + PositionConversionDb + RcstToCst>( db: &DB, module: Module, ) -> Vec<SemanticToken> { let text = db.get_module_content_as_string(module.clone()).unwrap(); let line_start_offsets = db.line_start_offsets(module.clone()); let mut builder = SemanticTokensBuilder::new(&*text, &*line_start_offsets); let cst = db.cst(module).unwrap(); visit_csts(&mut builder, &cst, None); builder.finish() } fn visit_csts( builder: &mut SemanticTokensBuilder<'_>, csts: &[Cst], token_type_for_identifier: Option<SemanticTokenType>, ) { for cst in csts { visit_cst(builder, cst, token_type_for_identifier) } } fn visit_cst( builder: &mut SemanticTokensBuilder<'_>, cst: &Cst, token_type_for_identifier: Option<SemanticTokenType>, ) { match &cst.kind { CstKind::EqualsSign => builder.add( cst.data.span.clone(), SemanticTokenType::Operator, EnumSet::empty(), ), CstKind::Comma | CstKind::Dot | CstKind::Colon | CstKind::ColonEqualsSign | CstKind::Bar | CstKind::OpeningParenthesis | CstKind::ClosingParenthesis | CstKind::OpeningBracket | CstKind::ClosingBracket | CstKind::OpeningCurlyBrace | CstKind::ClosingCurlyBrace => {} CstKind::Arrow => builder.add( cst.data.span.clone(), SemanticTokenType::Operator, EnumSet::empty(), ), CstKind::SingleQuote => {} // handled by parent CstKind::DoubleQuote => {} // handled by parent CstKind::Percent => builder.add( cst.data.span.clone(), SemanticTokenType::Operator, EnumSet::empty(), ), CstKind::Octothorpe => {} // handled by parent CstKind::Whitespace(_) | CstKind::Newline(_) => {} CstKind::Comment { octothorpe, .. } => { visit_cst(builder, octothorpe, None); builder.add( cst.data.span.clone(), SemanticTokenType::Comment, EnumSet::empty(), ); } CstKind::TrailingWhitespace { child, whitespace } => { visit_cst(builder, child, token_type_for_identifier); visit_csts(builder, whitespace, token_type_for_identifier); } CstKind::Identifier { .. } => builder.add( cst.data.span.clone(), token_type_for_identifier.unwrap_or(SemanticTokenType::Variable), EnumSet::empty(), ), CstKind::Symbol { .. } => builder.add( cst.data.span.clone(), SemanticTokenType::Symbol, EnumSet::empty(), ), CstKind::Int { .. } => builder.add( cst.data.span.clone(), SemanticTokenType::Int, EnumSet::empty(), ), CstKind::OpeningText { opening_single_quotes, opening_double_quote, } => { for opening_single_quote in opening_single_quotes { builder.add( opening_single_quote.data.span.clone(), SemanticTokenType::Text, EnumSet::empty(), ); } builder.add( opening_double_quote.data.span.clone(), SemanticTokenType::Text, EnumSet::empty(), ); } CstKind::ClosingText { closing_double_quote, closing_single_quotes, } => { builder.add( closing_double_quote.data.span.clone(), SemanticTokenType::Text, EnumSet::empty(), ); for closing_single_quote in closing_single_quotes { builder.add( closing_single_quote.data.span.clone(), SemanticTokenType::Text, EnumSet::empty(), ); } } CstKind::Text { opening, parts, closing, } => { visit_cst(builder, opening, None); for part in parts { visit_cst(builder, part, None); } visit_cst(builder, closing, None); } CstKind::TextPart(_) => builder.add( cst.data.span.clone(), SemanticTokenType::Text, EnumSet::empty(), ), CstKind::TextInterpolation { opening_curly_braces, expression, closing_curly_braces, } => { for opening_curly_brace in opening_curly_braces { visit_cst(builder, opening_curly_brace, None); } visit_cst(builder, expression, None); for closing_curly_brace in closing_curly_braces { visit_cst(builder, closing_curly_brace, None); } } CstKind::BinaryBar { left, bar, right } => { visit_cst(builder, left, None); visit_cst(builder, bar, None); visit_cst(builder, right, None); } CstKind::Parenthesized { opening_parenthesis, inner, closing_parenthesis, } => { visit_cst(builder, opening_parenthesis, None); visit_cst(builder, inner, None); visit_cst(builder, closing_parenthesis, None); } CstKind::Call { receiver, arguments, } => { visit_cst(builder, receiver, Some(SemanticTokenType::Function)); visit_csts(builder, arguments, None); } CstKind::List { opening_parenthesis, items, closing_parenthesis, } => { visit_cst(builder, opening_parenthesis, None); visit_csts(builder, items, token_type_for_identifier); visit_cst(builder, closing_parenthesis, None); } CstKind::ListItem { value, comma } => { visit_cst(builder, value, token_type_for_identifier); if let Some(comma) = comma { visit_cst(builder, comma, None); } } CstKind::Struct { opening_bracket, fields, closing_bracket, } => { visit_cst(builder, opening_bracket, None); visit_csts(builder, fields, token_type_for_identifier); visit_cst(builder, closing_bracket, None); } CstKind::StructField { key_and_colon, value, comma, } => { if let Some(box (key, colon)) = key_and_colon { visit_cst(builder, key, token_type_for_identifier); visit_cst(builder, colon, None); } visit_cst(builder, value, token_type_for_identifier); if let Some(comma) = comma { visit_cst(builder, comma, None); } } CstKind::StructAccess { struct_, dot, key } => { visit_cst(builder, struct_, None); visit_cst(builder, dot, None); visit_cst( builder, key, Some(token_type_for_identifier.unwrap_or(SemanticTokenType::Symbol)), ); } CstKind::Match { expression, percent, cases, } => { visit_cst(builder, expression, None); visit_cst(builder, percent, None); visit_csts(builder, cases, None); } CstKind::MatchCase { pattern, arrow, body, } => { visit_cst(builder, pattern, None); visit_cst(builder, arrow, None); visit_csts(builder, body, None); } CstKind::Function { opening_curly_brace, parameters_and_arrow, body, closing_curly_brace, } => { visit_cst(builder, opening_curly_brace, None); if let Some((parameters, arrow)) = parameters_and_arrow { visit_csts(builder, parameters, Some(SemanticTokenType::Parameter)); visit_cst(builder, arrow, None); } visit_csts(builder, body, None); visit_cst(builder, closing_curly_brace, None); } CstKind::Assignment { left, assignment_sign, body, } => { if let CstKind::Call { receiver, arguments, } = &left.kind { visit_cst(builder, receiver, Some(SemanticTokenType::Function)); visit_csts(builder, arguments, Some(SemanticTokenType::Parameter)); } else { let token_type = if let [single] = body.as_slice() && single.unwrap_whitespace_and_comment().kind.is_function() { SemanticTokenType::Function } else { SemanticTokenType::Variable }; visit_cst(builder, left, Some(token_type)); } visit_cst(builder, assignment_sign, None); visit_csts(builder, body, None); } CstKind::Error { .. } => {} } }
// use simdeez::*; #![cfg(target_arch = "x86_64")] use std::arch::x86_64::*; // DP high components and caller ignores returned high components #[inline] pub fn hi_dp_ss(a: __m128, b: __m128) -> __m128 { unsafe { // 0 1 2 3 -> 1 + 2 + 3, 0, 0, 0 let mut res: __m128 = _mm_mul_ps(a, b); // 0 1 2 3 -> 1 1 3 3 let hi = _mm_movehdup_ps(res); // 0 1 2 3 + 1 1 3 3 -> (0 + 1, 1 + 1, 2 + 3, 3 + 3) let sum = _mm_add_ps(hi, res); // unpacklo: 0 0 1 1 res = _mm_add_ps(sum, _mm_unpacklo_ps(res, res)); // (1 + 2 + 3, _, _, _) _mm_movehl_ps(res, res) } } /// Reciprocal with an additional single Newton-Raphson refinement #[inline] pub fn rcp_nr1(a: __m128) -> __m128 { //! ```f(x) = 1/x - a //! f'(x) = -1/x^2 //! x_{n+1} = x_n - f(x)/f'(x) //! = 2x_n - a x_n^2 = x_n (2 - a x_n) //! ``` //! ~2.7x baseline with ~22 bits of accuracy unsafe { let xn: __m128 = _mm_rcp_ps(a); let axn: __m128 = _mm_mul_ps(a, xn); _mm_mul_ps(xn, _mm_sub_ps(_mm_set1_ps(2.0), axn)) } } /// Reciprocal sqrt with an additional single Newton-Raphson refinement. #[inline] pub fn rsqrt_nr1(a: __m128) -> __m128 { //! ```f(x) = 1/x^2 - a //! f'(x) = -1/(2x^(3/2)) //! Let x_n be the estimate, and x_{n+1} be the refinement //! x_{n+1} = x_n - f(x)/f'(x) //! = 0.5 * x_n * (3 - a x_n^2) //!``` //! From Intel optimization manual: expected performance is ~5.2x //! baseline (sqrtps + divps) with ~22 bits of accuracy unsafe { let xn = _mm_rsqrt_ps(a); let mut axn2 = _mm_mul_ps(xn, xn); axn2 = _mm_mul_ps(a, axn2); let xn3 = _mm_sub_ps(_mm_set1_ps(3.0), axn2); _mm_mul_ps(_mm_mul_ps(_mm_set1_ps(0.5), xn), xn3) } } // Sqrt Newton-Raphson is evaluated in terms of rsqrt_nr1 #[inline] pub fn sqrt_nr1(a: __m128) -> __m128 { unsafe { _mm_mul_ps(a, rsqrt_nr1(a)) } } #[cfg(target_feature = "sse4.1")] #[inline] pub fn hi_dp(a: __m128, b: __m128) -> __m128 { unsafe { _mm_dp_ps(a, b, 0b11100001) } } #[cfg(target_feature = "sse4.1")] #[inline] pub fn hi_dp_bc(a: __m128, b: __m128) -> __m128 { unsafe { _mm_dp_ps(a, b, 0b11101111) } } #[cfg(target_feature = "sse4.1")] #[inline] pub fn dp(a: __m128, b: __m128) -> __m128 { unsafe { _mm_dp_ps(a, b, 0b11110001) } } #[cfg(target_feature = "sse4.1")] #[inline] pub fn dp_bc(a: __m128, b: __m128) -> __m128 { unsafe { _mm_dp_ps(a, b, 0xff) } } #[cfg(not(target_feature = "sse4.1"))] // // Equivalent to _mm_dp_ps(a, b, 0b11100001); #[inline] pub fn hi_dp(a: __m128, b: __m128) -> __m128 { // 0 1 2 3 -> 1 + 2 + 3, 0, 0, 0 unsafe { let mut out = _mm_mul_ps(a, b); // 0 1 2 3 -> 1 1 3 3 let hi = _mm_movehdup_ps(out); // 0 1 2 3 + 1 1 3 3 -> (0 + 1, 1 + 1, 2 + 3, 3 + 3) let sum = _mm_add_ps(hi, out); // unpacklo: 0 0 1 1 out = _mm_add_ps(sum, _mm_unpacklo_ps(out, out)); // (1 + 2 + 3, _, _, _) out = _mm_movehl_ps(out, out); _mm_and_ps(out, _mm_castsi128_ps(_mm_set_epi32(0, 0, 0, -1))) } } #[cfg(not(target_feature = "sse4.1"))] #[inline] pub fn hi_dp_bc(a: __m128, b: __m128) -> __m128 { unsafe { // Multiply across and mask low component let mut out = _mm_mul_ps(a, b); // 0 1 2 3 -> 1 1 3 3 let hi = _mm_movehdup_ps(out); // 0 1 2 3 + 1 1 3 3 -> (0 + 1, 1 + 1, 2 + 3, 3 + 3) let sum = _mm_add_ps(hi, out); // unpacklo: 0 0 1 1 out = _mm_add_ps(sum, _mm_unpacklo_ps(out, out)); // port comment: see https://github.com/Ziriax/KleinSharp/blob/master/KleinSharp.ConstSwizzleTool/Program.cs _mm_shuffle_ps(out, out, (2 << 6) | (2 << 4) | (2 << 2) | 2) } } #[cfg(not(target_feature = "sse4.1"))] #[inline] pub fn dp(a: __m128, b: __m128) -> __m128 { unsafe { // Multiply across and shift right (shifting in zeros) let mut out = _mm_mul_ps(a, b); let hi = _mm_movehdup_ps(out); // (a1 b1, a2 b2, a3 b3, 0) + (a2 b2, a2 b2, 0, 0) // = (a1 b1 + a2 b2, _, a3 b3, 0) out = _mm_add_ps(hi, out); out = _mm_add_ss(out, _mm_movehl_ps(hi, out)); _mm_and_ps(out, _mm_castsi128_ps(_mm_set_epi32(0, 0, 0, -1))) } } #[cfg(not(target_feature = "sse4.1"))] #[inline] pub fn dp_bc(a: __m128, b: __m128) -> __m128 { unsafe { // Multiply across and shift right (shifting in zeros) let mut out = _mm_mul_ps(a, b); let hi = _mm_movehdup_ps(out); // (a1 b1, a2 b2, a3 b3, 0) + (a2 b2, a2 b2, 0, 0) // = (a1 b1 + a2 b2, _, a3 b3, 0) out = _mm_add_ps(hi, out); out = _mm_add_ss(out, _mm_movehl_ps(hi, out)); // port comment: see https://github.com/Ziriax/KleinSharp/blob/master/KleinSharp.ConstSwizzleTool/Program.cs // return KLN_SWIZZLE(out, 0, 0, 0, 0); _mm_shuffle_ps(out, out, 0) } } #[cfg(test)] mod tests { #[cfg(target_arch = "x86_64")] use std::arch::x86_64::*; fn approx_eq(a: f32, b: f32) { assert!((a - b).abs() < 1e-6) } #[test] fn rcp_nr1() { let mut buf: [f32; 4] = [0.0, 0.0, 0.0, 0.0]; unsafe { let a: __m128 = _mm_set_ps(4.0, 3.0, 2.0, 1.0); let b: __m128 = super::rcp_nr1(a); _mm_store_ps(&mut (buf[0]), b); } approx_eq(buf[0], 1.0); approx_eq(buf[1], 0.5); approx_eq(buf[2], 1.0 / 3.0); approx_eq(buf[3], 0.25); } }
use std::io::Read; pub fn format(index: usize, link: &str) -> String { format!("[{}]:{}", index + 1, link) } pub fn convert<R, F>(mut reader: R, formatter: F) -> String where R: Read, F: Fn(usize, &str) -> String, { let mut is_codeblock = false; let mut is_hiperlink = false; let mut collected_links: Vec<String> = vec![]; let mut links_stack: Vec<String> = vec![]; let mut last_byte = b'\0'; let mut bytes = vec![]; let mut byte = [0u8]; while reader.read(&mut byte).expect("failed to read file") != 0 { let c = byte[0]; if c == b'`' && is_codeblock { is_codeblock = false; bytes.push(c); } else if c == b'`' && !is_codeblock { is_codeblock = true; bytes.push(c); } else if c == b'[' && !is_codeblock { links_stack.push("".into()); bytes.push(c); } else if c == b'(' && last_byte == b']' && !is_codeblock { is_hiperlink = true; } else if c == b')' && !is_codeblock && is_hiperlink { is_hiperlink = false; if let Some(link) = links_stack.pop() { let pointer = if let Some(position) = collected_links.iter().position(|l| l == &link) { position + 1 } else { collected_links.push(link); collected_links.len() }; bytes.push(b'['); for b in pointer.to_string().bytes() { bytes.push(b.clone()); } bytes.push(b']'); } else { bytes.push(c); } } else if !is_codeblock && is_hiperlink { if let Some(link) = links_stack.last_mut() { link.push(c as char); } else { bytes.push(c); } } else { bytes.push(c); }; last_byte = c; } if !collected_links.is_empty() { bytes.push(b'\n'); bytes.push(b'\n'); for (i, link) in collected_links.iter().enumerate() { for b in formatter(i, link).bytes() { bytes.push(b); } bytes.push(b'\n'); } } String::from_utf8(bytes).expect("failed to render") }
// Copyright 2020-2021, The Tremor Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::api::prelude::*; #[derive(Serialize)] struct OnRampWrap { artefact: tremor_runtime::config::OnRamp, instances: Vec<String>, } pub async fn list_artefact(req: Request) -> Result<Response> { let repo = &req.state().world.repo; let result: Vec<_> = repo .list_onramps() .await? .iter() .filter_map(|v| v.artefact().map(String::from)) .collect(); reply(req, result, false, StatusCode::Ok).await } pub async fn publish_artefact(req: Request) -> Result<Response> { let (req, data): (_, tremor_runtime::config::OnRamp) = decode(req).await?; let url = build_url(&["onramp", &data.id])?; let repo = &req.state().world.repo; let result = repo.publish_onramp(&url, false, data).await?; reply(req, result, true, StatusCode::Created).await } pub async fn unpublish_artefact(req: Request) -> Result<Response> { let id = req.param("aid").unwrap_or_default(); let url = build_url(&["onramp", id])?; let repo = &req.state().world.repo; let result = repo.unpublish_onramp(&url).await?; reply(req, result, true, StatusCode::Ok).await } pub async fn get_artefact(req: Request) -> Result<Response> { let id = req.param("aid").unwrap_or_default(); let url = build_url(&["onramp", id])?; let repo = &req.state().world.repo; let result = repo.find_onramp(&url).await?.ok_or_else(Error::not_found)?; let result = OnRampWrap { artefact: result.artefact, instances: result .instances .iter() .filter_map(|v| v.instance().map(String::from)) .collect(), }; reply(req, result, false, StatusCode::Ok).await }
use crate::{ dag::{ResolveError, UnexpectedResolved}, Block, Error, Ipfs, IpfsTypes, }; use async_stream::stream; use cid::Cid; use futures::stream::Stream; use ipfs_unixfs::file::{visit::IdleFileVisit, FileReadFailed}; use std::borrow::Borrow; use std::ops::Range; /// IPFS cat operation, producing a stream of file bytes. This is generic over the different kinds /// of ways to own an `Ipfs` value in order to support both operating with borrowed `Ipfs` value /// and an owned value. Passing an owned value allows the return value to be `'static`, which can /// be helpful in some contexts, like the http. /// /// Returns a stream of bytes on the file pointed with the Cid. pub async fn cat<'a, Types, MaybeOwned>( ipfs: MaybeOwned, starting_point: impl Into<StartingPoint>, range: Option<Range<u64>>, ) -> Result<impl Stream<Item = Result<Vec<u8>, TraversalFailed>> + Send + 'a, TraversalFailed> where Types: IpfsTypes, MaybeOwned: Borrow<Ipfs<Types>> + Send + 'a, { let mut visit = IdleFileVisit::default(); if let Some(range) = range { visit = visit.with_target_range(range); } // Get the root block to start the traversal. The stream does not expose any of the file // metadata. To get to it the user needs to create a Visitor over the first block. let Block { cid, data } = match starting_point.into() { StartingPoint::Left(path) => { let borrow = ipfs.borrow(); let dag = borrow.dag(); let (resolved, _) = dag .resolve(path, true) .await .map_err(TraversalFailed::Resolving)?; resolved .into_unixfs_block() .map_err(TraversalFailed::Path)? } StartingPoint::Right(block) => block, }; let mut cache = None; // Start the visit from the root block. We need to move the both components as Options into the // stream as we can't yet return them from this Future context. let (visit, bytes) = match visit.start(&data) { Ok((bytes, _, _, visit)) => { let bytes = if !bytes.is_empty() { Some(bytes.to_vec()) } else { None }; (visit, bytes) } Err(e) => { return Err(TraversalFailed::Walking(cid, e)); } }; // FIXME: we could use the above file_size to set the content-length ... but calculating it // with the ranges is not ... trivial? // using async_stream here at least to get on faster; writing custom streams is not too easy // but this might be easy enough to write open. Ok(stream! { if let Some(bytes) = bytes { yield Ok(bytes); } let mut visit = match visit { Some(visit) => visit, None => return, }; loop { // TODO: if it was possible, it would make sense to start downloading N of these // we could just create an FuturesUnordered which would drop the value right away. that // would probably always cost many unnecessary clones, but it would be nice to "shut" // the subscriber so that it will only resolve to a value but still keep the operation // going. Not that we have any "operation" concept of the Want yet. let (next, _) = visit.pending_links(); let borrow = ipfs.borrow(); let Block { cid, data } = match borrow.get_block(next).await { Ok(block) => block, Err(e) => { yield Err(TraversalFailed::Loading(next.to_owned(), e)); return; }, }; match visit.continue_walk(&data, &mut cache) { Ok((bytes, next_visit)) => { if !bytes.is_empty() { // TODO: manual implementation could allow returning just the slice yield Ok(bytes.to_vec()); } match next_visit { Some(v) => visit = v, None => return, } } Err(e) => { yield Err(TraversalFailed::Walking(cid, e)); return; } } } }) } /// The starting point for unixfs walks. Can be converted from IpfsPath and Blocks, and Cids can be /// converted to IpfsPath. pub enum StartingPoint { Left(crate::IpfsPath), Right(Block), } impl<T: Into<crate::IpfsPath>> From<T> for StartingPoint { fn from(a: T) -> Self { Self::Left(a.into()) } } impl From<Block> for StartingPoint { fn from(b: Block) -> Self { Self::Right(b) } } /// Types of failures which can occur while walking the UnixFS graph. #[derive(Debug, thiserror::Error)] pub enum TraversalFailed { /// Failure to resolve the given path; does not happen when given a block. #[error("path resolving failed")] Resolving(#[source] ResolveError), /// The given path was resolved to non dag-pb block, does not happen when starting the walk /// from a block. #[error("path resolved to unexpected")] Path(#[source] UnexpectedResolved), /// Loading of a block during walk failed #[error("loading of {} failed", .0)] Loading(Cid, #[source] Error), /// Processing of the block failed #[error("walk failed on {}", .0)] Walking(Cid, #[source] FileReadFailed), }
use async_trait::async_trait; use rbatis::crud::CRUDTable; use mav::{ChainType, NetType, WalletType, CTrue}; use mav::kits::sql_left_join_get_b; use mav::ma::{Dao, MBtcChainToken, MBtcChainTokenDefault, MBtcChainTokenShared, MWallet, MBtcChainTokenAuth}; use crate::{Chain2WalletType, ChainShared, ContextTrait, deref_type, Load, WalletError}; #[derive(Debug, Default)] pub struct BtcChainToken { pub m: MBtcChainToken, pub btc_chain_token_shared: BtcChainTokenShared, } deref_type!(BtcChainToken,MBtcChainToken); #[async_trait] impl Load for BtcChainToken { type MType = MBtcChainToken; async fn load(&mut self, context: &dyn ContextTrait, m: Self::MType) -> Result<(), WalletError> { self.m = m; let rb = context.db().wallets_db(); let token_shared = MBtcChainTokenShared::fetch_by_id(rb, "", &self.chain_token_shared_id).await?; let token_shared = token_shared.ok_or_else(|| WalletError::NoneError(format!("do not find id:{}, in {}", &self.chain_token_shared_id, MBtcChainTokenShared::table_name())))?; self.btc_chain_token_shared.load(context, token_shared).await?; Ok(()) } } #[derive(Debug, Default)] pub struct BtcChainTokenShared { pub m: MBtcChainTokenShared, //pub token_shared: TokenShared, } deref_type!(BtcChainTokenShared,MBtcChainTokenShared); impl From<MBtcChainTokenShared> for BtcChainTokenShared { fn from(token_shared: MBtcChainTokenShared) -> Self { Self { m: token_shared, } } } #[async_trait] impl Load for BtcChainTokenShared { type MType = MBtcChainTokenShared; async fn load(&mut self, _: &dyn ContextTrait, m: Self::MType) -> Result<(), WalletError> { self.m = m; Ok(()) } } #[derive(Debug, Default)] pub struct BtcChainTokenDefault { pub m: MBtcChainTokenDefault, pub btc_chain_token_shared: BtcChainTokenShared, } deref_type!(BtcChainTokenDefault,MBtcChainTokenDefault); impl BtcChainTokenDefault { pub async fn list_by_net_type(context: &dyn ContextTrait, net_type: &NetType) -> Result<Vec<BtcChainTokenDefault>, WalletError> { let tx_id = ""; let wallets_db = context.db().wallets_db(); let tokens_shared: Vec<MBtcChainTokenShared> = { let default_name = MBtcChainTokenDefault::table_name(); let shared_name = MBtcChainTokenShared::table_name(); let wrapper = wallets_db.new_wrapper() .eq(format!("{}.{}", default_name, MBtcChainTokenDefault::net_type).as_str(), net_type.to_string()); let sql = { //wrapper = wrapper; let t = sql_left_join_get_b(&default_name, &MBtcChainTokenDefault::chain_token_shared_id, &shared_name, &MBtcChainTokenShared::id); format!("{} where {}", t, &wrapper.sql) }; wallets_db.fetch_prepare(tx_id, &sql, &wrapper.args).await? }; let mut tokens_default = { let wrapper = wallets_db.new_wrapper() .eq(MBtcChainTokenDefault::net_type, net_type.to_string()) .eq(MBtcChainTokenDefault::status, CTrue) .order_by(true, &[MBtcChainTokenDefault::position]); MBtcChainTokenDefault::list_by_wrapper(wallets_db, tx_id, &wrapper).await? }; for token_default in &mut tokens_default { for token_shared in &tokens_shared { if token_default.chain_token_shared_id == token_shared.id { token_default.chain_token_shared = token_shared.clone(); } } } let btc_tokens = tokens_default.iter().map(|token|BtcChainTokenDefault{ m: token.clone(), btc_chain_token_shared: BtcChainTokenShared::from(token.chain_token_shared.clone()), }).collect::<Vec<BtcChainTokenDefault>>(); Ok(btc_tokens) } } #[derive(Debug, Default)] pub struct BtcChainTokenAuth { pub m: MBtcChainTokenAuth, pub btc_chain_token_shared: BtcChainTokenShared, } deref_type!(BtcChainTokenAuth,MBtcChainTokenAuth); impl BtcChainTokenAuth{ pub async fn list_by_net_type(context: &dyn ContextTrait, net_type: &NetType, start_item: u64, page_size: u64) -> Result<Vec<BtcChainTokenAuth>, WalletError> { let tx_id = ""; let wallets_db = context.db().wallets_db(); let page_query = format!(" limit {} offset {}", page_size, start_item); let mut tokens_auth = { let wrapper = wallets_db.new_wrapper() .eq(MBtcChainTokenAuth::net_type, net_type.to_string()) .eq(MBtcChainTokenAuth::status, CTrue) .order_by(false, &[MBtcChainTokenAuth::create_time]).push_sql(&page_query); MBtcChainTokenAuth::list_by_wrapper(wallets_db, tx_id, &wrapper).await? }; let token_shared_id = format!("id in (SELECT {} FROM {} WHERE {}='{}' ORDER by {} desc {})", MBtcChainTokenAuth::chain_token_shared_id, MBtcChainTokenAuth::table_name(), MBtcChainTokenAuth::net_type, net_type.to_string(), MBtcChainTokenAuth::create_time, page_query); let token_shared_wrapper = wallets_db.new_wrapper().push_sql(&token_shared_id); let tokens_shared = MBtcChainTokenShared::list_by_wrapper(wallets_db, tx_id, &token_shared_wrapper).await?; let mut target_tokens = vec![]; for token_auth in &mut tokens_auth { for token_shared in &tokens_shared { let mut token = BtcChainTokenAuth::default(); if token_auth.chain_token_shared_id == token_shared.id { token.m = token_auth.clone(); token.btc_chain_token_shared = BtcChainTokenShared::from(token_shared.clone()); target_tokens.push(token) } } } Ok(target_tokens) } } #[derive(Debug, Default)] pub struct BtcChain { pub chain_shared: ChainShared, pub tokens: Vec<BtcChainToken>, } impl Chain2WalletType for BtcChain { fn chain_type(wallet_type: &WalletType,net_type:&NetType) -> ChainType { match (wallet_type,net_type) { (WalletType::Normal,NetType::Main) => ChainType::BTC, (WalletType::Test,NetType::Test) => ChainType::BtcTest, (WalletType::Test,NetType::Private) => ChainType::BtcPrivate, (WalletType::Test,NetType::PrivateTest) => ChainType::BtcPrivateTest, _ => ChainType::BtcTest, } } } /*#[async_trait]*/ impl BtcChain { pub async fn load(&mut self, context: &dyn ContextTrait, mw: MWallet,net_type:&NetType) -> Result<(), WalletError> { self.chain_shared.set_m(&mw); // let wallet_type = WalletType::from(&mw.wallet_type); // self.chain_shared.m.chain_type = self.to_chain_type(&wallet_type).to_string(); let wallet_type = WalletType::from(mw.wallet_type.as_str()); let chain_type = BtcChain::chain_type(&wallet_type, &net_type).to_string(); {//load address let wallet_id = self.chain_shared.wallet_id.clone(); self.chain_shared.set_addr(context, &wallet_id, &chain_type).await?; self.chain_shared.m.chain_type = chain_type.clone(); } {//load token let rb = context.db().data_db( &net_type); let wrapper = rb.new_wrapper() .eq(MBtcChainToken::wallet_id, mw.id.clone()) .eq(MBtcChainToken::chain_type, chain_type); let ms = MBtcChainToken::list_by_wrapper(&rb, "", &wrapper).await?; self.tokens.clear(); for it in ms { let mut token = BtcChainToken::default(); token.load(context, it).await?; self.tokens.push(token); } } Ok(()) } } #[derive(Debug, Default, Clone)] pub struct BtcNowLoadBlock{ pub height: u64, pub header_hash: String, pub timestamp: String, } #[derive(Debug, Default, Clone)] pub struct BtcBalance{ pub balance: u64, pub height: u64, }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtCore/qcommandlineparser.h // dst-file: /src/core/qcommandlineparser.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::qstringlist::*; // 773 use super::qstring::*; // 773 use super::qcommandlineoption::*; // 773 use super::qcoreapplication::*; // 773 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QCommandLineParser_Class_Size() -> c_int; // proto: void QCommandLineParser::process(const QStringList & arguments); fn C_ZN18QCommandLineParser7processERK11QStringList(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QString QCommandLineParser::value(const QString & name); fn C_ZNK18QCommandLineParser5valueERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QString QCommandLineParser::errorText(); fn C_ZNK18QCommandLineParser9errorTextEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QCommandLineParser::clearPositionalArguments(); fn C_ZN18QCommandLineParser24clearPositionalArgumentsEv(qthis: u64 /* *mut c_void*/); // proto: QStringList QCommandLineParser::values(const QCommandLineOption & option); fn C_ZNK18QCommandLineParser6valuesERK18QCommandLineOption(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: bool QCommandLineParser::isSet(const QString & name); fn C_ZNK18QCommandLineParser5isSetERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char; // proto: void QCommandLineParser::showHelp(int exitCode); fn C_ZN18QCommandLineParser8showHelpEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: bool QCommandLineParser::addOption(const QCommandLineOption & commandLineOption); fn C_ZN18QCommandLineParser9addOptionERK18QCommandLineOption(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char; // proto: void QCommandLineParser::showVersion(); fn C_ZN18QCommandLineParser11showVersionEv(qthis: u64 /* *mut c_void*/); // proto: QCommandLineOption QCommandLineParser::addHelpOption(); fn C_ZN18QCommandLineParser13addHelpOptionEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QStringList QCommandLineParser::optionNames(); fn C_ZNK18QCommandLineParser11optionNamesEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: bool QCommandLineParser::isSet(const QCommandLineOption & option); fn C_ZNK18QCommandLineParser5isSetERK18QCommandLineOption(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char; // proto: void QCommandLineParser::addPositionalArgument(const QString & name, const QString & description, const QString & syntax); fn C_ZN18QCommandLineParser21addPositionalArgumentERK7QStringS2_S2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void); // proto: void QCommandLineParser::~QCommandLineParser(); fn C_ZN18QCommandLineParserD2Ev(qthis: u64 /* *mut c_void*/); // proto: void QCommandLineParser::process(const QCoreApplication & app); fn C_ZN18QCommandLineParser7processERK16QCoreApplication(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QString QCommandLineParser::helpText(); fn C_ZNK18QCommandLineParser8helpTextEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QStringList QCommandLineParser::values(const QString & name); fn C_ZNK18QCommandLineParser6valuesERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QString QCommandLineParser::applicationDescription(); fn C_ZNK18QCommandLineParser22applicationDescriptionEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QString QCommandLineParser::value(const QCommandLineOption & option); fn C_ZNK18QCommandLineParser5valueERK18QCommandLineOption(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QCommandLineOption QCommandLineParser::addVersionOption(); fn C_ZN18QCommandLineParser16addVersionOptionEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QStringList QCommandLineParser::positionalArguments(); fn C_ZNK18QCommandLineParser19positionalArgumentsEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QCommandLineParser::setApplicationDescription(const QString & description); fn C_ZN18QCommandLineParser25setApplicationDescriptionERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QCommandLineParser::QCommandLineParser(); fn C_ZN18QCommandLineParserC2Ev() -> u64; // proto: bool QCommandLineParser::parse(const QStringList & arguments); fn C_ZN18QCommandLineParser5parseERK11QStringList(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char; // proto: QStringList QCommandLineParser::unknownOptionNames(); fn C_ZNK18QCommandLineParser18unknownOptionNamesEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; } // <= ext block end // body block begin => // class sizeof(QCommandLineParser)=8 #[derive(Default)] pub struct QCommandLineParser { // qbase: None, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QCommandLineParser { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QCommandLineParser { return QCommandLineParser{qclsinst: qthis, ..Default::default()}; } } // proto: void QCommandLineParser::process(const QStringList & arguments); impl /*struct*/ QCommandLineParser { pub fn process<RetType, T: QCommandLineParser_process<RetType>>(& self, overload_args: T) -> RetType { return overload_args.process(self); // return 1; } } pub trait QCommandLineParser_process<RetType> { fn process(self , rsthis: & QCommandLineParser) -> RetType; } // proto: void QCommandLineParser::process(const QStringList & arguments); impl<'a> /*trait*/ QCommandLineParser_process<()> for (&'a QStringList) { fn process(self , rsthis: & QCommandLineParser) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLineParser7processERK11QStringList()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN18QCommandLineParser7processERK11QStringList(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QString QCommandLineParser::value(const QString & name); impl /*struct*/ QCommandLineParser { pub fn value<RetType, T: QCommandLineParser_value<RetType>>(& self, overload_args: T) -> RetType { return overload_args.value(self); // return 1; } } pub trait QCommandLineParser_value<RetType> { fn value(self , rsthis: & QCommandLineParser) -> RetType; } // proto: QString QCommandLineParser::value(const QString & name); impl<'a> /*trait*/ QCommandLineParser_value<QString> for (&'a QString) { fn value(self , rsthis: & QCommandLineParser) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK18QCommandLineParser5valueERK7QString()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK18QCommandLineParser5valueERK7QString(rsthis.qclsinst, arg0)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QString QCommandLineParser::errorText(); impl /*struct*/ QCommandLineParser { pub fn errorText<RetType, T: QCommandLineParser_errorText<RetType>>(& self, overload_args: T) -> RetType { return overload_args.errorText(self); // return 1; } } pub trait QCommandLineParser_errorText<RetType> { fn errorText(self , rsthis: & QCommandLineParser) -> RetType; } // proto: QString QCommandLineParser::errorText(); impl<'a> /*trait*/ QCommandLineParser_errorText<QString> for () { fn errorText(self , rsthis: & QCommandLineParser) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK18QCommandLineParser9errorTextEv()}; let mut ret = unsafe {C_ZNK18QCommandLineParser9errorTextEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QCommandLineParser::clearPositionalArguments(); impl /*struct*/ QCommandLineParser { pub fn clearPositionalArguments<RetType, T: QCommandLineParser_clearPositionalArguments<RetType>>(& self, overload_args: T) -> RetType { return overload_args.clearPositionalArguments(self); // return 1; } } pub trait QCommandLineParser_clearPositionalArguments<RetType> { fn clearPositionalArguments(self , rsthis: & QCommandLineParser) -> RetType; } // proto: void QCommandLineParser::clearPositionalArguments(); impl<'a> /*trait*/ QCommandLineParser_clearPositionalArguments<()> for () { fn clearPositionalArguments(self , rsthis: & QCommandLineParser) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLineParser24clearPositionalArgumentsEv()}; unsafe {C_ZN18QCommandLineParser24clearPositionalArgumentsEv(rsthis.qclsinst)}; // return 1; } } // proto: QStringList QCommandLineParser::values(const QCommandLineOption & option); impl /*struct*/ QCommandLineParser { pub fn values<RetType, T: QCommandLineParser_values<RetType>>(& self, overload_args: T) -> RetType { return overload_args.values(self); // return 1; } } pub trait QCommandLineParser_values<RetType> { fn values(self , rsthis: & QCommandLineParser) -> RetType; } // proto: QStringList QCommandLineParser::values(const QCommandLineOption & option); impl<'a> /*trait*/ QCommandLineParser_values<QStringList> for (&'a QCommandLineOption) { fn values(self , rsthis: & QCommandLineParser) -> QStringList { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK18QCommandLineParser6valuesERK18QCommandLineOption()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK18QCommandLineParser6valuesERK18QCommandLineOption(rsthis.qclsinst, arg0)}; let mut ret1 = QStringList::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QCommandLineParser::isSet(const QString & name); impl /*struct*/ QCommandLineParser { pub fn isSet<RetType, T: QCommandLineParser_isSet<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isSet(self); // return 1; } } pub trait QCommandLineParser_isSet<RetType> { fn isSet(self , rsthis: & QCommandLineParser) -> RetType; } // proto: bool QCommandLineParser::isSet(const QString & name); impl<'a> /*trait*/ QCommandLineParser_isSet<i8> for (&'a QString) { fn isSet(self , rsthis: & QCommandLineParser) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK18QCommandLineParser5isSetERK7QString()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK18QCommandLineParser5isSetERK7QString(rsthis.qclsinst, arg0)}; return ret as i8; // 1 // return 1; } } // proto: void QCommandLineParser::showHelp(int exitCode); impl /*struct*/ QCommandLineParser { pub fn showHelp<RetType, T: QCommandLineParser_showHelp<RetType>>(& self, overload_args: T) -> RetType { return overload_args.showHelp(self); // return 1; } } pub trait QCommandLineParser_showHelp<RetType> { fn showHelp(self , rsthis: & QCommandLineParser) -> RetType; } // proto: void QCommandLineParser::showHelp(int exitCode); impl<'a> /*trait*/ QCommandLineParser_showHelp<()> for (Option<i32>) { fn showHelp(self , rsthis: & QCommandLineParser) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLineParser8showHelpEi()}; let arg0 = (if self.is_none() {0} else {self.unwrap()}) as c_int; unsafe {C_ZN18QCommandLineParser8showHelpEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QCommandLineParser::addOption(const QCommandLineOption & commandLineOption); impl /*struct*/ QCommandLineParser { pub fn addOption<RetType, T: QCommandLineParser_addOption<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addOption(self); // return 1; } } pub trait QCommandLineParser_addOption<RetType> { fn addOption(self , rsthis: & QCommandLineParser) -> RetType; } // proto: bool QCommandLineParser::addOption(const QCommandLineOption & commandLineOption); impl<'a> /*trait*/ QCommandLineParser_addOption<i8> for (&'a QCommandLineOption) { fn addOption(self , rsthis: & QCommandLineParser) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLineParser9addOptionERK18QCommandLineOption()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN18QCommandLineParser9addOptionERK18QCommandLineOption(rsthis.qclsinst, arg0)}; return ret as i8; // 1 // return 1; } } // proto: void QCommandLineParser::showVersion(); impl /*struct*/ QCommandLineParser { pub fn showVersion<RetType, T: QCommandLineParser_showVersion<RetType>>(& self, overload_args: T) -> RetType { return overload_args.showVersion(self); // return 1; } } pub trait QCommandLineParser_showVersion<RetType> { fn showVersion(self , rsthis: & QCommandLineParser) -> RetType; } // proto: void QCommandLineParser::showVersion(); impl<'a> /*trait*/ QCommandLineParser_showVersion<()> for () { fn showVersion(self , rsthis: & QCommandLineParser) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLineParser11showVersionEv()}; unsafe {C_ZN18QCommandLineParser11showVersionEv(rsthis.qclsinst)}; // return 1; } } // proto: QCommandLineOption QCommandLineParser::addHelpOption(); impl /*struct*/ QCommandLineParser { pub fn addHelpOption<RetType, T: QCommandLineParser_addHelpOption<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addHelpOption(self); // return 1; } } pub trait QCommandLineParser_addHelpOption<RetType> { fn addHelpOption(self , rsthis: & QCommandLineParser) -> RetType; } // proto: QCommandLineOption QCommandLineParser::addHelpOption(); impl<'a> /*trait*/ QCommandLineParser_addHelpOption<QCommandLineOption> for () { fn addHelpOption(self , rsthis: & QCommandLineParser) -> QCommandLineOption { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLineParser13addHelpOptionEv()}; let mut ret = unsafe {C_ZN18QCommandLineParser13addHelpOptionEv(rsthis.qclsinst)}; let mut ret1 = QCommandLineOption::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QStringList QCommandLineParser::optionNames(); impl /*struct*/ QCommandLineParser { pub fn optionNames<RetType, T: QCommandLineParser_optionNames<RetType>>(& self, overload_args: T) -> RetType { return overload_args.optionNames(self); // return 1; } } pub trait QCommandLineParser_optionNames<RetType> { fn optionNames(self , rsthis: & QCommandLineParser) -> RetType; } // proto: QStringList QCommandLineParser::optionNames(); impl<'a> /*trait*/ QCommandLineParser_optionNames<QStringList> for () { fn optionNames(self , rsthis: & QCommandLineParser) -> QStringList { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK18QCommandLineParser11optionNamesEv()}; let mut ret = unsafe {C_ZNK18QCommandLineParser11optionNamesEv(rsthis.qclsinst)}; let mut ret1 = QStringList::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QCommandLineParser::isSet(const QCommandLineOption & option); impl<'a> /*trait*/ QCommandLineParser_isSet<i8> for (&'a QCommandLineOption) { fn isSet(self , rsthis: & QCommandLineParser) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK18QCommandLineParser5isSetERK18QCommandLineOption()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK18QCommandLineParser5isSetERK18QCommandLineOption(rsthis.qclsinst, arg0)}; return ret as i8; // 1 // return 1; } } // proto: void QCommandLineParser::addPositionalArgument(const QString & name, const QString & description, const QString & syntax); impl /*struct*/ QCommandLineParser { pub fn addPositionalArgument<RetType, T: QCommandLineParser_addPositionalArgument<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addPositionalArgument(self); // return 1; } } pub trait QCommandLineParser_addPositionalArgument<RetType> { fn addPositionalArgument(self , rsthis: & QCommandLineParser) -> RetType; } // proto: void QCommandLineParser::addPositionalArgument(const QString & name, const QString & description, const QString & syntax); impl<'a> /*trait*/ QCommandLineParser_addPositionalArgument<()> for (&'a QString, &'a QString, Option<&'a QString>) { fn addPositionalArgument(self , rsthis: & QCommandLineParser) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLineParser21addPositionalArgumentERK7QStringS2_S2_()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = (if self.2.is_none() {QString::new(()).qclsinst} else {self.2.unwrap().qclsinst}) as *mut c_void; unsafe {C_ZN18QCommandLineParser21addPositionalArgumentERK7QStringS2_S2_(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: void QCommandLineParser::~QCommandLineParser(); impl /*struct*/ QCommandLineParser { pub fn free<RetType, T: QCommandLineParser_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QCommandLineParser_free<RetType> { fn free(self , rsthis: & QCommandLineParser) -> RetType; } // proto: void QCommandLineParser::~QCommandLineParser(); impl<'a> /*trait*/ QCommandLineParser_free<()> for () { fn free(self , rsthis: & QCommandLineParser) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLineParserD2Ev()}; unsafe {C_ZN18QCommandLineParserD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: void QCommandLineParser::process(const QCoreApplication & app); impl<'a> /*trait*/ QCommandLineParser_process<()> for (&'a QCoreApplication) { fn process(self , rsthis: & QCommandLineParser) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLineParser7processERK16QCoreApplication()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN18QCommandLineParser7processERK16QCoreApplication(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QString QCommandLineParser::helpText(); impl /*struct*/ QCommandLineParser { pub fn helpText<RetType, T: QCommandLineParser_helpText<RetType>>(& self, overload_args: T) -> RetType { return overload_args.helpText(self); // return 1; } } pub trait QCommandLineParser_helpText<RetType> { fn helpText(self , rsthis: & QCommandLineParser) -> RetType; } // proto: QString QCommandLineParser::helpText(); impl<'a> /*trait*/ QCommandLineParser_helpText<QString> for () { fn helpText(self , rsthis: & QCommandLineParser) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK18QCommandLineParser8helpTextEv()}; let mut ret = unsafe {C_ZNK18QCommandLineParser8helpTextEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QStringList QCommandLineParser::values(const QString & name); impl<'a> /*trait*/ QCommandLineParser_values<QStringList> for (&'a QString) { fn values(self , rsthis: & QCommandLineParser) -> QStringList { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK18QCommandLineParser6valuesERK7QString()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK18QCommandLineParser6valuesERK7QString(rsthis.qclsinst, arg0)}; let mut ret1 = QStringList::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QString QCommandLineParser::applicationDescription(); impl /*struct*/ QCommandLineParser { pub fn applicationDescription<RetType, T: QCommandLineParser_applicationDescription<RetType>>(& self, overload_args: T) -> RetType { return overload_args.applicationDescription(self); // return 1; } } pub trait QCommandLineParser_applicationDescription<RetType> { fn applicationDescription(self , rsthis: & QCommandLineParser) -> RetType; } // proto: QString QCommandLineParser::applicationDescription(); impl<'a> /*trait*/ QCommandLineParser_applicationDescription<QString> for () { fn applicationDescription(self , rsthis: & QCommandLineParser) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK18QCommandLineParser22applicationDescriptionEv()}; let mut ret = unsafe {C_ZNK18QCommandLineParser22applicationDescriptionEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QString QCommandLineParser::value(const QCommandLineOption & option); impl<'a> /*trait*/ QCommandLineParser_value<QString> for (&'a QCommandLineOption) { fn value(self , rsthis: & QCommandLineParser) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK18QCommandLineParser5valueERK18QCommandLineOption()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK18QCommandLineParser5valueERK18QCommandLineOption(rsthis.qclsinst, arg0)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QCommandLineOption QCommandLineParser::addVersionOption(); impl /*struct*/ QCommandLineParser { pub fn addVersionOption<RetType, T: QCommandLineParser_addVersionOption<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addVersionOption(self); // return 1; } } pub trait QCommandLineParser_addVersionOption<RetType> { fn addVersionOption(self , rsthis: & QCommandLineParser) -> RetType; } // proto: QCommandLineOption QCommandLineParser::addVersionOption(); impl<'a> /*trait*/ QCommandLineParser_addVersionOption<QCommandLineOption> for () { fn addVersionOption(self , rsthis: & QCommandLineParser) -> QCommandLineOption { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLineParser16addVersionOptionEv()}; let mut ret = unsafe {C_ZN18QCommandLineParser16addVersionOptionEv(rsthis.qclsinst)}; let mut ret1 = QCommandLineOption::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QStringList QCommandLineParser::positionalArguments(); impl /*struct*/ QCommandLineParser { pub fn positionalArguments<RetType, T: QCommandLineParser_positionalArguments<RetType>>(& self, overload_args: T) -> RetType { return overload_args.positionalArguments(self); // return 1; } } pub trait QCommandLineParser_positionalArguments<RetType> { fn positionalArguments(self , rsthis: & QCommandLineParser) -> RetType; } // proto: QStringList QCommandLineParser::positionalArguments(); impl<'a> /*trait*/ QCommandLineParser_positionalArguments<QStringList> for () { fn positionalArguments(self , rsthis: & QCommandLineParser) -> QStringList { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK18QCommandLineParser19positionalArgumentsEv()}; let mut ret = unsafe {C_ZNK18QCommandLineParser19positionalArgumentsEv(rsthis.qclsinst)}; let mut ret1 = QStringList::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QCommandLineParser::setApplicationDescription(const QString & description); impl /*struct*/ QCommandLineParser { pub fn setApplicationDescription<RetType, T: QCommandLineParser_setApplicationDescription<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setApplicationDescription(self); // return 1; } } pub trait QCommandLineParser_setApplicationDescription<RetType> { fn setApplicationDescription(self , rsthis: & QCommandLineParser) -> RetType; } // proto: void QCommandLineParser::setApplicationDescription(const QString & description); impl<'a> /*trait*/ QCommandLineParser_setApplicationDescription<()> for (&'a QString) { fn setApplicationDescription(self , rsthis: & QCommandLineParser) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLineParser25setApplicationDescriptionERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN18QCommandLineParser25setApplicationDescriptionERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QCommandLineParser::QCommandLineParser(); impl /*struct*/ QCommandLineParser { pub fn new<T: QCommandLineParser_new>(value: T) -> QCommandLineParser { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QCommandLineParser_new { fn new(self) -> QCommandLineParser; } // proto: void QCommandLineParser::QCommandLineParser(); impl<'a> /*trait*/ QCommandLineParser_new for () { fn new(self) -> QCommandLineParser { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLineParserC2Ev()}; let ctysz: c_int = unsafe{QCommandLineParser_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let qthis: u64 = unsafe {C_ZN18QCommandLineParserC2Ev()}; let rsthis = QCommandLineParser{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: bool QCommandLineParser::parse(const QStringList & arguments); impl /*struct*/ QCommandLineParser { pub fn parse<RetType, T: QCommandLineParser_parse<RetType>>(& self, overload_args: T) -> RetType { return overload_args.parse(self); // return 1; } } pub trait QCommandLineParser_parse<RetType> { fn parse(self , rsthis: & QCommandLineParser) -> RetType; } // proto: bool QCommandLineParser::parse(const QStringList & arguments); impl<'a> /*trait*/ QCommandLineParser_parse<i8> for (&'a QStringList) { fn parse(self , rsthis: & QCommandLineParser) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLineParser5parseERK11QStringList()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN18QCommandLineParser5parseERK11QStringList(rsthis.qclsinst, arg0)}; return ret as i8; // 1 // return 1; } } // proto: QStringList QCommandLineParser::unknownOptionNames(); impl /*struct*/ QCommandLineParser { pub fn unknownOptionNames<RetType, T: QCommandLineParser_unknownOptionNames<RetType>>(& self, overload_args: T) -> RetType { return overload_args.unknownOptionNames(self); // return 1; } } pub trait QCommandLineParser_unknownOptionNames<RetType> { fn unknownOptionNames(self , rsthis: & QCommandLineParser) -> RetType; } // proto: QStringList QCommandLineParser::unknownOptionNames(); impl<'a> /*trait*/ QCommandLineParser_unknownOptionNames<QStringList> for () { fn unknownOptionNames(self , rsthis: & QCommandLineParser) -> QStringList { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK18QCommandLineParser18unknownOptionNamesEv()}; let mut ret = unsafe {C_ZNK18QCommandLineParser18unknownOptionNamesEv(rsthis.qclsinst)}; let mut ret1 = QStringList::inheritFrom(ret as u64); return ret1; // return 1; } } // <= body block end
// 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::collections::HashMap; use common_exception::ErrorCode; use common_exception::Result; use common_expression::Scalar; #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] pub struct TableArgs { pub positioned: Vec<Scalar>, pub named: HashMap<String, Scalar>, } impl TableArgs { pub fn is_empty(&self) -> bool { self.named.is_empty() && self.positioned.is_empty() } pub fn new_positioned(args: Vec<Scalar>) -> Self { Self { positioned: args, named: HashMap::new(), } } pub fn new_named(args: HashMap<String, Scalar>) -> Self { Self { positioned: vec![], named: args, } } /// Check TableArgs only contain positioned args. /// Also check num of positioned if num is not None. /// /// Returns the vec of positioned args. pub fn expect_all_positioned( &self, func_name: &str, num: Option<usize>, ) -> Result<Vec<Scalar>> { if !self.named.is_empty() { Err(ErrorCode::BadArguments(format!( "{} accept positioned args only", func_name ))) } else if let Some(n) = num { if n != self.positioned.len() { Err(ErrorCode::BadArguments(format!( "{} must accept exactly {} positioned args", func_name, n ))) } else { Ok(self.positioned.clone()) } } else { Ok(self.positioned.clone()) } } /// Check TableArgs only contain named args. /// /// Returns the map of named args. pub fn expect_all_named(&self, func_name: &str) -> Result<HashMap<String, Scalar>> { if !self.positioned.is_empty() { Err(ErrorCode::BadArguments(format!( "{} accept named args only", func_name ))) } else { Ok(self.named.clone()) } } }
use std::collections::{HashMap, HashSet}; use std::sync::mpsc; use message; pub enum Message { ClientConnected(mpsc::Sender<message::Message>, u64), ClientGone(u64), MessageReceived(message::Message), } pub struct Dispatcher { pub tx: mpsc::Sender<Message>, input: mpsc::Receiver<Message>, clients: HashMap<u64, mpsc::Sender<message::Message>>, followers: HashMap<u64, HashSet<u64>>, } impl Dispatcher { pub fn new() -> Dispatcher { let (tx, rx) = mpsc::channel(); Dispatcher { tx: tx, input: rx, clients: HashMap::new(), followers: HashMap::new(), } } pub fn run(mut self) { for msg in &self.input { match msg { Message::ClientConnected(tx, id) => { println!("client {} connected", id); self.clients.insert(id, tx); }, Message::ClientGone(id) => { println!("client {} disconnected", id); self.clients.remove(&id); }, Message::MessageReceived(m) => { match m.event { message::Event::Broadcast => for id in self.clients.keys() { &self.send(m, id); }, message::Event::Follow(src, dst) => { { let dst_followers = self.followers.entry(dst).or_insert(HashSet::new()); dst_followers.insert(src); } &self.send(m, &dst); }, message::Event::Unfollow(src, dst) => if let Some(fs) = self.followers.get_mut(&dst) { fs.remove(&src); }, message::Event::PrivMsg(_, dst) => { &self.send(m, &dst); }, message::Event::Status(src) => { let empty = HashSet::with_capacity(0); for dst in self.followers.get(&src).unwrap_or(&empty) { &self.send(m, dst); } }, } } } } for (_, tx) in self.clients { drop(tx); } } fn send(&self, m: message::Message, dst: &u64) { if let Some(tx) = self.clients.get(dst) { // println!("sending {} to client {}", m, dst); if let Err(_) = tx.send(m) { println!("client {} is gone, removing", dst); self.tx.send(Message::ClientGone(*dst)).unwrap(); } } } }
/*! # Ruby Parser - a library for parsing Ruby syntax ruby-parser is a library that provides the APIs needed to lex the Ruby programming language's syntax into a stream of tokens. ## Parser combinators This library is provided as a set of parser combinator functions, powered by [nom](https://docs.rs/nom/). All of the parser combinators are structured to semantically reflect the ISO Ruby specification, but minor deviations from the spec have been made when necessary (namely, re-ordering alternative parsers to consume the largest production first). The top-level parser combinators that return tokens are publically exported within the parsers module. !*/ extern crate nom; #[macro_use] mod macros; pub mod ast; pub mod lexer; mod parsers; pub use nom::error::ErrorKind; /// Parses a ruby program pub fn parse(i: lexer::Input) -> lexer::ProgramResult { parsers::program::program(i) }
use std::thread; fn main() { let thread_1 = thread::spawn(|| { "Hello" }); thread::sleep(std::time::Duration::from_millis(100)); let thread_2 = thread::spawn(|| { "Rust" }); println!("{:?}", thread_2.join().unwrap()); println!("{:?}", thread_1.join().unwrap()); }
pub struct GameState { map: Map::Map, } impl GameState { pub fn update(&mut self) { } }
use smash::*; use smash::hash40; use smash::lib::lua_const::*; use smash::lua2cpp::L2CFighterCommon; use acmd::{acmd, acmd_func}; use smash::app::lua_bind::*; use smash::lib::L2CValueType; use smash::phx::Vector3f; use smash::phx::Hash40; #[acmd_func( battle_object_category = BATTLE_OBJECT_CATEGORY_FIGHTER, battle_object_kind = FIGHTER_KIND_KIRBY, animation = "throw_b", animcmd = "game_throwb")] pub fn throwb(fighter: &mut L2CFighterCommon) { let kirbycide_boost: smash::phx::Vector3f = smash::phx::Vector3f {x: 0.0, y: -8.0, z: 0.0}; let mut globals = *fighter.globals_mut(); if let L2CValueType::Void = globals["prev_pos"].val_type { globals["prev_pos"] = 0.0.into(); } if let L2CValueType::Void = globals["pos"].val_type { globals["pos"] = 0.0.into(); } acmd!({ if(is_excute){ ATTACK_ABS(Kind=FIGHTER_ATTACK_ABSOLUTE_KIND_THROW, ID=0, Damage=8.0, Angle=130, KBG=120, FKB=0, BKB=30, Hitlag=0.0, Unk=1.0, FacingRestrict=ATTACK_LR_CHECK_F, Unk=0.0, Unk=true, Effect=hash40("collision_attr_normal"), SFXLevel=ATTACK_SOUND_LEVEL_S, SFXType=COLLISION_SOUND_ATTR_NONE, Type=ATTACK_REGION_THROW) ATTACK_ABS(Kind=FIGHTER_ATTACK_ABSOLUTE_KIND_CATCH, ID=0, Damage=3.0, Angle=361, KBG=100, FKB=0, BKB=60, Hitlag=0.0, Unk=1.0, FacingRestrict=ATTACK_LR_CHECK_F, Unk=0.0, Unk=true, Effect=hash40("collision_attr_normal"), SFXLevel=ATTACK_SOUND_LEVEL_S, SFXType=COLLISION_SOUND_ATTR_NONE, Type=ATTACK_REGION_THROW) } frame(13) if(is_excute) { WorkModule::on_flag(Flag=FIGHTER_STATUS_THROW_FLAG_START_AIR) } frame(28) if(is_excute) { MotionModule::set_rate( 0.05); rust { KineticModule::add_speed(module_accessor, &kirbycide_boost); } } frame (28.1) if(is_excute) { rust { globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); //println!("{}", globals["prev_pos"].get_num()); } } frame (28.15) if(is_excute) { rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); //println!("{}", globals["prev_pos"].get_num()); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 30.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } } frame (28.2) if(is_excute) { rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 30.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } } frame (28.25) if(is_excute) { rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 30.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } } frame (28.3) if(is_excute) { rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 30.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } } frame (28.35) if(is_excute) { rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 30.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } } frame (28.4) if(is_excute) { rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 30.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } } frame (28.45) if(is_excute) { rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 30.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } } frame (28.5) if(is_excute) { rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 30.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } } frame (28.55) if(is_excute) { rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 30.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } } frame (28.6) if(is_excute) { rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 30.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } } frame (28.65) if(is_excute) { rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 30.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } } frame (28.7) if(is_excute) { rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 30.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } } frame (28.75) if(is_excute) { rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 30.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } } frame (28.8) if(is_excute) { rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 30.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } } frame (28.85) if(is_excute) { rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 30.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } } frame (28.9) if(is_excute) { rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 30.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } } frame(30) if(is_excute) { MotionModule::set_rate( 1.0); rust { KineticModule::clear_speed_all(module_accessor); } } frame(41) if(is_excute) { ATK_HIT_ABS(FIGHTER_ATTACK_ABSOLUTE_KIND_THROW, hash40("throw"), WorkModule::get_int64(module_accessor, *FIGHTER_STATUS_THROW_WORK_INT_TARGET_OBJECT), WorkModule::get_int64(module_accessor, *FIGHTER_STATUS_THROW_WORK_INT_TARGET_HIT_GROUP), WorkModule::get_int64(module_accessor, *FIGHTER_STATUS_THROW_WORK_INT_TARGET_HIT_NO)) } frame(61) if(is_excute){ StatusModule::change_status_request(FIGHTER_STATUS_KIND_FALL, false) } }); } #[acmd_func( battle_object_category = BATTLE_OBJECT_CATEGORY_FIGHTER, battle_object_kind = FIGHTER_KIND_KIRBY, animation = "throw_f", animcmd = "game_throwf")] pub fn throwf(fighter: &mut L2CFighterCommon) { let kirbycide_boost: smash::phx::Vector3f = smash::phx::Vector3f {x: 0.0, y: -8.0, z: 0.0}; let mut globals = *fighter.globals_mut(); if let L2CValueType::Void = globals["prev_pos"].val_type { globals["prev_pos"] = 0.0.into(); } if let L2CValueType::Void = globals["pos"].val_type { globals["pos"] = 0.0.into(); } acmd!({ if(is_excute){ ATTACK_ABS(Kind=FIGHTER_ATTACK_ABSOLUTE_KIND_THROW, ID=0, Damage=5.0, Angle=75, KBG=125, FKB=0, BKB=40, Hitlag=0.0, Unk=1.0, FacingRestrict=ATTACK_LR_CHECK_F, Unk=0.0, Unk=true, Effect=hash40("collision_attr_normal"), SFXLevel=ATTACK_SOUND_LEVEL_S, SFXType=COLLISION_SOUND_ATTR_NONE, Type=ATTACK_REGION_THROW) ATTACK_ABS(Kind=FIGHTER_ATTACK_ABSOLUTE_KIND_CATCH, ID=0, Damage=3.0, Angle=361, KBG=100, FKB=0, BKB=60, Hitlag=0.0, Unk=1.0, FacingRestrict=ATTACK_LR_CHECK_F, Unk=0.0, Unk=true, Effect=hash40("collision_attr_normal"), SFXLevel=ATTACK_SOUND_LEVEL_S, SFXType=COLLISION_SOUND_ATTR_NONE, Type=ATTACK_REGION_THROW) } frame(9) if(is_excute) { WorkModule::on_flag(Flag=FIGHTER_STATUS_THROW_FLAG_START_AIR) } frame(32) if(is_excute) { MotionModule::set_rate( 0.05); rust { KineticModule::add_speed(module_accessor, &kirbycide_boost); } } frame (32.1) if(is_excute) { for (19 Iterations) { rust {globals["prev_pos"] = PostureModule::pos_y(module_accessor).into();} wait(0.05) rust { globals["pos"] = PostureModule::pos_y(module_accessor).into(); let pos_dif = globals["prev_pos"].get_num() - globals["pos"].get_num(); if pos_dif.abs() <= 3.0 { MotionModule::set_frame(module_accessor, 34.0, false); } globals["prev_pos"] = PostureModule::pos_y(module_accessor).into(); } wait(0.05) } } frame(34) if(is_excute) { MotionModule::set_rate( 1.0); rust { KineticModule::clear_speed_all(module_accessor); } } frame(45) if(is_excute) { ATK_HIT_ABS(FIGHTER_ATTACK_ABSOLUTE_KIND_THROW, hash40("throw"), WorkModule::get_int64(module_accessor, *FIGHTER_STATUS_THROW_WORK_INT_TARGET_OBJECT), WorkModule::get_int64(module_accessor, *FIGHTER_STATUS_THROW_WORK_INT_TARGET_HIT_GROUP), WorkModule::get_int64(module_accessor, *FIGHTER_STATUS_THROW_WORK_INT_TARGET_HIT_NO)) } }); } pub fn install() { acmd::add_hooks!( throwb, throwf ); }
use super::*; #[test] fn with_small_integer_subtrahend_with_underflow_returns_big_integer() { with_process(|process| { let minuend = process.integer(SmallInteger::MIN_VALUE); let subtrahend = process.integer(SmallInteger::MAX_VALUE); assert!(subtrahend.is_smallint()); let result = result(&process, minuend, subtrahend); assert!(result.is_ok()); let difference = result.unwrap(); assert!(difference.is_boxed_bigint()); }) } #[test] fn with_small_integer_subtrahend_with_overflow_returns_big_integer() { with(|minuend, process| { let subtrahend = process.integer(SmallInteger::MIN_VALUE); assert!(subtrahend.is_smallint()); let result = result(&process, minuend, subtrahend); assert!(result.is_ok()); let difference = result.unwrap(); assert!(difference.is_boxed_bigint()); }) } #[test] fn with_float_subtrahend_with_underflow_returns_min_float() { with(|minuend, process| { let subtrahend = process.float(std::f64::MAX); assert_eq!( result(&process, minuend, subtrahend), Ok(process.float(std::f64::MIN)) ); }) } #[test] fn with_float_subtrahend_with_overflow_returns_max_float() { with(|minuend, process| { let subtrahend = process.float(std::f64::MIN); assert_eq!( result(&process, minuend, subtrahend), Ok(process.float(std::f64::MAX)) ); }) } fn with<F>(f: F) where F: FnOnce(Term, &Process) -> (), { with_process(|process| { let minuend = process.integer(2); f(minuend, &process) }) }
#[macro_use] use super::*; fn walk<F: Fn(&mut Term, usize)>(term: &mut Term, cutoff: usize, f: &F) { match term { Term::Var(_) => { f(term, cutoff); } Term::Abs(t2) => walk(t2, cutoff + 1, f), Term::App(t1, t2) => { walk(t1, cutoff, f); walk(t2, cutoff, f); } } } fn shift(t: &mut Term, s: isize) { walk(t, 0, &|f, c| { if let Term::Var(n) = f { if *n >= c { *n = (*n as isize + s) as usize; } } }) } fn subst(t: &mut Term, mut s: Term) { walk(t, 0, &|f, c| { if let Term::Var(n) = f { if *n == c { let mut sub = s.clone(); shift(&mut sub, c as isize); *f = sub; } } }) } /// Substitute term `s` into term `t` fn subst_top(t: &mut Term, mut s: Term) { shift(&mut s, 1); subst(t, s); shift(t, -1); } fn eval1(tm: Term) -> Result<Term, Term> { match tm { Term::App(e1, e2) => { if !e2.nf() { Ok(Term::App(e1, Box::new(eval1(*e2)?))) } else if !e1.nf() { Ok(Term::App(Box::new(eval1(*e1)?), e2)) } else { match *e1 { Term::Abs(mut e) => { subst_top(&mut e, *e2); Ok(*e) } _ => Err(Term::App(e1, e2)), } } } _ => Err(tm), } } pub fn eval(tm: Term) -> Term { let mut t = tm; loop { match eval1(t) { Ok(e) => t = e, Err(e) => return e, } } } #[cfg(test)] mod test { use super::*; macro_rules! var { ($ex:expr) => { Term::Var($ex) }; } macro_rules! abs { ($ex:expr) => { Term::Abs(Box::new($ex)) }; } macro_rules! app { ($ex:expr, $ex2:expr) => { Term::App(Box::new($ex), Box::new($ex2))}; ($ex1:expr, $($ex:expr),+) => { vec![$(var!($ex)),+].into_iter().fold(var!($ex1), |tm, n| app!(tm, n)) } } #[test] fn eval_id() { let id = abs!(var!(0)); let a = app!(id.clone(), id.clone()); let ev = eval(a); assert_eq!(ev, id); } #[test] fn eval_subst1() { let t = app!(abs!(app!(app!(var!(1), var!(0)), var!(2))), abs!(var!(0))); let res = app!(app!(var!(0), abs!(var!(0))), var!(1)); assert_eq!(eval1(t), Ok(res)); } #[test] fn numerals() { let c0 = abs!(abs!(var!(0))); let succ = abs!(abs!(abs!(app!( app!(var!(2), var!(1)), app!(var!(1), var!(0)) )))); let plus = abs!(abs!(abs!(abs!(app!( app!(var!(3), var!(1)), app!(app!(var!(2), var!(1)), var!(0)) ))))); let c1 = app!(succ.clone(), c0.clone()); let c2 = app!(succ.clone(), c1.clone()); let c3 = app!(succ.clone(), c2.clone()); assert_eq!( eval(app!(succ.clone(), c3)), eval(app!( app!(app!(app!(plus.clone(), c2.clone()), c2.clone()), succ), c0 )) ); } #[test] fn eval_church() { let a = app!(app!(app!(church::test(), church::tru()), var!(5)), var!(7)); let b = app!(app!(app!(church::test(), church::fls()), var!(5)), var!(7)); let c = app!(app!(church::and(), church::fls()), church::tru()); let d = app!(app!(church::and(), church::tru()), church::tru()); assert_eq!(eval(a), var!(5)); assert_eq!(eval(b), var!(7)); assert_eq!(eval(app!(app!(church::tru(), var!(1)), var!(2))), var!(1)); assert_eq!(eval(app!(app!(church::fls(), var!(1)), var!(2))), var!(2)); assert_eq!(eval(c), church::fls()); assert_eq!(eval(d), church::tru()); } }
use std::convert::From; use nabi; #[repr(C)] pub struct AbiResult(u64); impl From<AbiResult> for nabi::Result<u32> { fn from(res: AbiResult) -> nabi::Result<u32> { nabi::Error::demux(res.0) } }
use grass::algorithm::AssumeSorted; grass::grass_query! { let a = open("data/a.bed"); let g = open("data/test.genome"); // The invert operator assume the genome size is INF, thus we need to intersect with // the genome size file, so that we can limit the result not larger than the genome size intersect(a | invert() | assume_sorted(), g) | as_bed3() | show_all(); }
pub mod data; use std::process::{Command, Stdio}; use std::io::{Write}; use itertools::{Itertools}; fn thruster_signal(data: &str, path: &str, phase: i32, signal: i32) -> i32 { let mut result = Command::new(path) .args(&[data]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn().expect("Unable to start child process"); let child_input = result.stdin.as_mut().expect("Unable to capture input"); write!(child_input, "{}\n{}", phase, signal).expect("Unable to write input"); let output = result.wait_with_output().expect("Unable to capture result"); String::from_utf8(output.stdout).unwrap().trim().parse::<i32>() .expect("Unable to parse output signal") } fn main() { let path = "../../05/intcode/target/release/intcode.exe"; let data = data::data(); let amplifier_count = 5; let mut input_signal = 0; let mut max = 0; let mut max_soln = None; for configuration in (0..amplifier_count).permutations(amplifier_count) { for &phase_setting in &configuration { input_signal = thruster_signal(data, path, phase_setting as i32, input_signal); } if input_signal > max { max = input_signal; max_soln = Some(configuration); } input_signal = 0; } if let Some(soln) = max_soln { println!("soln({:?}) = {:?}", max, soln); } }
#[doc = "Reader of register PP"] pub type R = crate::R<u32, super::PP>; #[doc = "EEPROM Size\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u16)] pub enum SIZE_A { #[doc = "0: 64 bytes of EEPROM"] _64 = 0, #[doc = "1: 128 bytes of EEPROM"] _128 = 1, #[doc = "3: 256 bytes of EEPROM"] _256 = 3, #[doc = "7: 512 bytes of EEPROM"] _512 = 7, #[doc = "15: 1 KB of EEPROM"] _1K = 15, #[doc = "31: 2 KB of EEPROM"] _2K = 31, #[doc = "63: 3 KB of EEPROM"] _3K = 63, #[doc = "127: 4 KB of EEPROM"] _4K = 127, #[doc = "255: 5 KB of EEPROM"] _5K = 255, #[doc = "511: 6 KB of EEPROM"] _6K = 511, } impl From<SIZE_A> for u16 { #[inline(always)] fn from(variant: SIZE_A) -> Self { variant as _ } } #[doc = "Reader of field `SIZE`"] pub type SIZE_R = crate::R<u16, SIZE_A>; impl SIZE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u16, SIZE_A> { use crate::Variant::*; match self.bits { 0 => Val(SIZE_A::_64), 1 => Val(SIZE_A::_128), 3 => Val(SIZE_A::_256), 7 => Val(SIZE_A::_512), 15 => Val(SIZE_A::_1K), 31 => Val(SIZE_A::_2K), 63 => Val(SIZE_A::_3K), 127 => Val(SIZE_A::_4K), 255 => Val(SIZE_A::_5K), 511 => Val(SIZE_A::_6K), i => Res(i), } } #[doc = "Checks if the value of the field is `_64`"] #[inline(always)] pub fn is_64(&self) -> bool { *self == SIZE_A::_64 } #[doc = "Checks if the value of the field is `_128`"] #[inline(always)] pub fn is_128(&self) -> bool { *self == SIZE_A::_128 } #[doc = "Checks if the value of the field is `_256`"] #[inline(always)] pub fn is_256(&self) -> bool { *self == SIZE_A::_256 } #[doc = "Checks if the value of the field is `_512`"] #[inline(always)] pub fn is_512(&self) -> bool { *self == SIZE_A::_512 } #[doc = "Checks if the value of the field is `_1K`"] #[inline(always)] pub fn is_1k(&self) -> bool { *self == SIZE_A::_1K } #[doc = "Checks if the value of the field is `_2K`"] #[inline(always)] pub fn is_2k(&self) -> bool { *self == SIZE_A::_2K } #[doc = "Checks if the value of the field is `_3K`"] #[inline(always)] pub fn is_3k(&self) -> bool { *self == SIZE_A::_3K } #[doc = "Checks if the value of the field is `_4K`"] #[inline(always)] pub fn is_4k(&self) -> bool { *self == SIZE_A::_4K } #[doc = "Checks if the value of the field is `_5K`"] #[inline(always)] pub fn is_5k(&self) -> bool { *self == SIZE_A::_5K } #[doc = "Checks if the value of the field is `_6K`"] #[inline(always)] pub fn is_6k(&self) -> bool { *self == SIZE_A::_6K } } impl R { #[doc = "Bits 0:15 - EEPROM Size"] #[inline(always)] pub fn size(&self) -> SIZE_R { SIZE_R::new((self.bits & 0xffff) as u16) } }
extern crate hyper; extern crate multipart; use std::io; use hyper::server::{Handler, Server, Request, Response}; use hyper::status::StatusCode; use hyper::server::response::Response as HyperResponse; use multipart::server::hyper::{Switch, MultipartHandler, HyperRequest}; use multipart::server::{Multipart, Entries, SaveResult}; use multipart::mock::StdoutTee; struct NonMultipart; impl Handler for NonMultipart { fn handle(&self, _: Request, mut res: Response) { *res.status_mut() = StatusCode::ImATeapot; res.send(b"Please send a multipart req :(\n").unwrap(); } } struct EchoMultipart; impl MultipartHandler for EchoMultipart { fn handle_multipart(&self, mut multipart: Multipart<HyperRequest>, res: HyperResponse) { match multipart.save().temp() { SaveResult::Full(entries) => process_entries(res, entries).unwrap(), SaveResult::Partial(entries, error) => { println!("Errors saving multipart:\n{:?}", error); process_entries(res, entries.into()).unwrap(); } SaveResult::Error(error) => { println!("Errors saving multipart:\n{:?}", error); res.send(format!("An error occurred {}", error).as_bytes()).unwrap(); } }; } } fn process_entries(res: HyperResponse, entries: Entries) -> io::Result<()> { let mut res = res.start()?; let stdout = io::stdout(); let out = StdoutTee::new(&mut res, &stdout); entries.write_debug(out) } fn main() { println!("Listening on 0.0.0.0:3333"); Server::http("0.0.0.0:3333").unwrap().handle( Switch::new( NonMultipart, EchoMultipart )).unwrap(); }
//! This module describes the negotiate contexts. //! The SMB2_NEGOTIATE_CONTEXT structure is used by the SMB2 NEGOTIATE Request //! and the SMB2 NEGOTIATE Response to encode additional properties. //! The server MUST support receiving negotiate contexts in any order. use rand::{ distributions::{Distribution, Standard}, Rng, }; use crate::{ format::convert_byte_array_to_int, fuzzer::create_random_byte_array_of_predefined_length, }; pub trait DataSize { fn get_data_length(&self) -> Vec<u8>; } /// ContextType (2 bytes): Specifies the type of context in the Data field. #[derive(Debug, PartialEq, Eq, Clone)] pub enum ContextType { PreauthIntegrityCapabilities(PreauthIntegrityCapabilities), EncryptionCapabilities(EncryptionCapabilities), CompressionCapabilities(CompressionCapabilities), NetnameNegotiateContextId(NetnameNegotiateContextId), TransportCapabilities(TransportCapabilities), RdmaTransformCapabilities(RdmaTransformCapabilities), } impl ContextType { /// Unpacks the byte code for the context type. pub fn unpack_byte_code(&self) -> Vec<u8> { match self { ContextType::PreauthIntegrityCapabilities(_) => b"\x01\x00".to_vec(), ContextType::EncryptionCapabilities(_) => b"\x02\x00".to_vec(), ContextType::CompressionCapabilities(_) => b"\x03\x00".to_vec(), ContextType::NetnameNegotiateContextId(_) => b"\x05\x00".to_vec(), ContextType::TransportCapabilities(_) => b"\x06\x00".to_vec(), ContextType::RdmaTransformCapabilities(_) => b"\x07\x00".to_vec(), } } /// Maps the byte code of an incoming response to the corresponding context type. pub fn map_byte_code_to_context_type(byte_code: Vec<u8>) -> ContextType { if let Some(code) = byte_code.get(0) { match code { 1 => ContextType::PreauthIntegrityCapabilities( PreauthIntegrityCapabilities::default(), ), 2 => ContextType::EncryptionCapabilities(EncryptionCapabilities::default()), 3 => ContextType::CompressionCapabilities(CompressionCapabilities::default()), 5 => ContextType::NetnameNegotiateContextId(NetnameNegotiateContextId::default()), 6 => ContextType::TransportCapabilities(TransportCapabilities::default()), 7 => ContextType::RdmaTransformCapabilities(RdmaTransformCapabilities::default()), _ => panic!("Invalid context type in parsed response."), } } else { panic!("Empty context type in parsed response.") } } /// Calls get data length for the corresponding capability. pub fn get_capability_data_length(&self) -> Vec<u8> { match self { ContextType::PreauthIntegrityCapabilities(preauth) => preauth.get_data_length(), ContextType::EncryptionCapabilities(encrypt) => encrypt.get_data_length(), ContextType::CompressionCapabilities(compress) => compress.get_data_length(), ContextType::NetnameNegotiateContextId(netname) => netname.get_data_length(), ContextType::TransportCapabilities(transport) => transport.get_data_length(), ContextType::RdmaTransformCapabilities(rdma) => rdma.get_data_length(), } } } impl Distribution<ContextType> for Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> ContextType { match rng.gen_range(0..=4) { 0 => ContextType::PreauthIntegrityCapabilities( PreauthIntegrityCapabilities::fuzz_with_predefined_length(), ), 1 => ContextType::EncryptionCapabilities( EncryptionCapabilities::fuzz_with_predefined_length(), ), 2 => ContextType::CompressionCapabilities( CompressionCapabilities::fuzz_with_predefined_length(), ), 3 => ContextType::NetnameNegotiateContextId(NetnameNegotiateContextId::fuzz()), 4 => ContextType::TransportCapabilities( TransportCapabilities::fuzz_with_predefined_length(), ), _ => ContextType::RdmaTransformCapabilities( RdmaTransformCapabilities::fuzz_with_predefined_length(), ), } } } impl std::fmt::Display for ContextType { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { ContextType::PreauthIntegrityCapabilities(preauth) => { write!(f, "{}", preauth) } ContextType::EncryptionCapabilities(encrypt) => { write!(f, "{}", encrypt) } ContextType::CompressionCapabilities(compress) => { write!(f, "{}", compress) } ContextType::NetnameNegotiateContextId(netname) => { write!(f, "{}", netname) } ContextType::TransportCapabilities(transport) => { write!(f, "{}", transport) } ContextType::RdmaTransformCapabilities(rdma) => { write!(f, "{}", rdma) } } } } /// The SMB2_NEGOTIATE_CONTEXT structure is used by the SMB2 NEGOTIATE Request /// and the SMB2 NEGOTIATE Response to encode additional properties. #[derive(Debug, PartialEq, Eq, Clone)] pub struct NegotiateContext { /// ContextType (2 bytes): Specifies the type of context in the Data field. pub context_type: Vec<u8>, /// DataLength (2 bytes): The length, in bytes, of the Data field. pub data_length: Vec<u8>, /// Reserved (4 bytes): This field MUST NOT be used and MUST be reserved. /// This value MUST be set to 0 by the client, and MUST be ignored by the server. pub reserved: Vec<u8>, /// Data (variable): A variable-length field that contains /// the negotiate context specified by the ContextType field. pub data: Option<ContextType>, } impl NegotiateContext { /// Creates a new instance of the Negotiate Context. pub fn default() -> Self { NegotiateContext { context_type: Vec::new(), data_length: Vec::new(), reserved: vec![0; 4], data: None, } } } impl std::fmt::Display for NegotiateContext { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "Negotiate Context: \n\t\tcontext type: {:?}\n\t\tdata length: {:?}\ \n\t\treserved: {:?}\n\t\tdata: {}", self.context_type, self.data_length, self.reserved, self.data.as_ref().unwrap() ) } } pub struct NegVec<'a>(pub &'a Vec<NegotiateContext>); impl<'a> std::fmt::Display for NegVec<'a> { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let mut context_string = String::new(); for context in self.0.iter() { context_string.push_str(format!("{}\n", context).as_str()); } write!(f, "{}", context_string) } } #[derive(Debug, PartialEq, Eq, Clone)] pub enum HashAlgorithms { Sha512, } impl HashAlgorithms { /// Unpacks the byte code for hash algorithms. pub fn unpack_byte_code(&self) -> Vec<u8> { match self { HashAlgorithms::Sha512 => b"\x01\x00".to_vec(), } } } impl Distribution<HashAlgorithms> for Standard { fn sample<R: Rng + ?Sized>(&self, _rng: &mut R) -> HashAlgorithms { HashAlgorithms::Sha512 } } /// The SMB2_PREAUTH_INTEGRITY_CAPABILITIES context is specified in an SMB2 NEGOTIATE /// request by the client to indicate which preauthentication integrity hash algorithms /// the client supports and to optionally supply a preauthentication integrity hash salt value. #[derive(Debug, PartialEq, Eq, Clone)] pub struct PreauthIntegrityCapabilities { /// HashAlgorithmCount (2 bytes): The number of hash algorithms in /// the HashAlgorithms array. This value MUST be greater than zero. pub hash_algorithm_count: Vec<u8>, /// SaltLength (2 bytes): The size, in bytes, of the Salt field. pub salt_length: Vec<u8>, /// HashAlgorithms (variable): An array of HashAlgorithmCount /// 16-bit integer IDs specifying the supported preauthentication integrity hash functions. /// There is currently only SHA-512 available. pub hash_algorithms: Vec<Vec<u8>>, /// Salt (variable): A buffer containing the salt value of the hash. pub salt: Vec<u8>, } impl PreauthIntegrityCapabilities { /// Creates a new PreauthIntegrityCapabilities instance. pub fn default() -> Self { PreauthIntegrityCapabilities { hash_algorithm_count: b"\x01\x00".to_vec(), salt_length: Vec::new(), hash_algorithms: vec![b"\x01\x00".to_vec()], // SHA-512 salt: Vec::new(), } } /// Fuzzes the preauthintegrity capabilities with a predefined length. pub fn fuzz_with_predefined_length() -> Self { let mut random_hashes: Vec<HashAlgorithms> = Vec::new(); for _ in 0..rand::thread_rng().gen_range(0..100) { random_hashes.push(rand::random()); } let salt_length = rand::thread_rng().gen_range(0..32) as u16; PreauthIntegrityCapabilities { hash_algorithm_count: (random_hashes.len() as u16).to_le_bytes().to_vec(), salt_length: salt_length.to_le_bytes().to_vec(), hash_algorithms: random_hashes .into_iter() .map(|hash| hash.unpack_byte_code()) .collect(), salt: create_random_byte_array_of_predefined_length(salt_length as u32), } } } impl DataSize for PreauthIntegrityCapabilities { /// Gets the data length of the preauthintegrity capabilities. fn get_data_length(&self) -> Vec<u8> { let length = self.hash_algorithm_count.len() + self.salt_length.len() + convert_byte_array_to_int(self.hash_algorithm_count.clone(), false) as usize + self.salt.len(); (length as u16).to_le_bytes().to_vec() } } impl std::fmt::Display for PreauthIntegrityCapabilities { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "\n\t\t\tPreauth Integrity Capabilities: \n\t\t\t\thash algorithm count: {:?}\ \n\t\t\t\tsalt length: {:?}\n\t\t\t\thash algorithms: {:?}\n\t\t\t\tsalt: {:?}", self.hash_algorithm_count, self.salt_length, self.hash_algorithms, self.salt ) } } /// An array of CipherCount 16-bit integer IDs specifying the supported encryption algorithms. /// These IDs MUST be in an order such that the most preferred cipher MUST be at the beginning /// of the array and least preferred cipher at the end of the array. The following IDs are defined. #[derive(Debug, PartialEq, Eq, Clone)] pub enum Ciphers { Aes128Ccm, Aes128Gcm, Aes256Ccm, Aes256Gcm, } impl Ciphers { /// Unpacks the byte code of ciphers. pub fn unpack_byte_code(&self) -> Vec<u8> { match self { Ciphers::Aes128Ccm => b"\x01\x00".to_vec(), Ciphers::Aes128Gcm => b"\x02\x00".to_vec(), Ciphers::Aes256Ccm => b"\x03\x00".to_vec(), Ciphers::Aes256Gcm => b"\x04\x00".to_vec(), } } } impl Distribution<Ciphers> for Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Ciphers { match rng.gen_range(0..=3) { 0 => Ciphers::Aes128Ccm, 1 => Ciphers::Aes128Gcm, 2 => Ciphers::Aes256Ccm, _ => Ciphers::Aes256Gcm, } } } /// The SMB2_ENCRYPTION_CAPABILITIES context is specified in an SMB2 NEGOTIATE /// request by the client to indicate which encryption algorithms the client supports. #[derive(Debug, PartialEq, Eq, Clone)] pub struct EncryptionCapabilities { /// CipherCount (2 bytes): The number of ciphers in the Ciphers array. /// This value MUST be greater than zero. pub cipher_count: Vec<u8>, /// Ciphers (variable): An array of CipherCount 16-bit integer IDs /// specifying the supported encryption algorithms. /// These IDs MUST be in an order such that the most preferred cipher /// MUST be at the beginning of the array and least preferred cipher /// at the end of the array. pub ciphers: Vec<Vec<u8>>, } impl EncryptionCapabilities { /// Creates a new EncryptionCapabilities instance. pub fn default() -> Self { EncryptionCapabilities { cipher_count: Vec::new(), ciphers: Vec::new(), } } /// Fuzzes the encryption capabilities with the predefined length. pub fn fuzz_with_predefined_length() -> Self { let mut random_ciphers: Vec<Ciphers> = Vec::new(); for _ in 0..rand::thread_rng().gen_range(0..100) { random_ciphers.push(rand::random()); } EncryptionCapabilities { cipher_count: (random_ciphers.len() as u16).to_le_bytes().to_vec(), ciphers: random_ciphers .into_iter() .map(|cipher| cipher.unpack_byte_code()) .collect(), } } /// Gets the data length of the encrytpion capabilities. pub fn get_data_length(&self) -> Vec<u8> { let length = self.cipher_count.len() + convert_byte_array_to_int(self.cipher_count.clone(), false) as usize; (length as u16).to_le_bytes().to_vec() } } impl DataSize for EncryptionCapabilities { /// Gets the data length of the encrytpion capabilities. fn get_data_length(&self) -> Vec<u8> { let length = self.cipher_count.len() + convert_byte_array_to_int(self.cipher_count.clone(), false) as usize; (length as u16).to_le_bytes().to_vec() } } impl std::fmt::Display for EncryptionCapabilities { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "\n\t\t\tEncryption Capabilities: \n\t\t\t\tcipher count: {:?}\n\t\t\t\tciphers: {:?}", self.cipher_count, self.ciphers ) } } /// *Compression Capabilities Flag None*: /// - Chained compression is not supported. /// /// *Compression Capabilities Flag Chained*: /// - Chained compression is supported on this connection. #[derive(Debug, PartialEq, Eq, Clone)] pub enum Flags { CompressionCapabilitiesFlagNone, CompressionCapabilitiesFlagChained, } impl Flags { /// Unpacks the byte code for compression flags. pub fn unpack_byte_code(&self) -> Vec<u8> { match self { Flags::CompressionCapabilitiesFlagNone => b"\x00\x00\x00\x00".to_vec(), Flags::CompressionCapabilitiesFlagChained => b"\x01\x00\x00\x00".to_vec(), } } } impl Distribution<Flags> for Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Flags { match rng.gen_range(0..=1) { 0 => Flags::CompressionCapabilitiesFlagNone, _ => Flags::CompressionCapabilitiesFlagChained, } } } /// *None*: /// - No compression. /// /// *LZNT1*: /// - LZNT1 compression algorithm. /// /// *LZ77*: /// - LZ77 compression algorithm. /// /// *LZ77 + Huffman*: /// - LZ77+Huffman compression algorithm. /// /// *Pattern_V1*: /// - Pattern scanning algorithm. #[derive(Debug, PartialEq, Eq, Clone)] pub enum CompressionAlgorithms { None, Lznt1, Lz77, Lz77Huffman, PatternV1, } impl CompressionAlgorithms { /// Unpacks the byte code for compression algorithms. pub fn unpack_byte_code(&self) -> Vec<u8> { match self { CompressionAlgorithms::None => b"\x00\x00".to_vec(), CompressionAlgorithms::Lznt1 => b"\x01\x00".to_vec(), CompressionAlgorithms::Lz77 => b"\x02\x00".to_vec(), CompressionAlgorithms::Lz77Huffman => b"\x03\x00".to_vec(), CompressionAlgorithms::PatternV1 => b"\x04\x00".to_vec(), } } } impl Distribution<CompressionAlgorithms> for Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> CompressionAlgorithms { match rng.gen_range(0..=4) { 0 => CompressionAlgorithms::None, 1 => CompressionAlgorithms::Lznt1, 2 => CompressionAlgorithms::Lz77, 3 => CompressionAlgorithms::Lz77Huffman, _ => CompressionAlgorithms::PatternV1, } } } /// The SMB2_COMPRESSION_CAPABILITIES context is specified in an SMB2 NEGOTIATE request /// by the client to indicate which compression algorithms the client supports. #[derive(Debug, PartialEq, Eq, Clone)] pub struct CompressionCapabilities { /// CompressionAlgorithmCount (2 bytes): The number of elements in CompressionAlgorithms array. pub compression_algorithm_count: Vec<u8>, /// Padding (2 bytes): The sender MUST set this to 0, and the receiver MUST ignore it on receipt. pub padding: Vec<u8>, /// Flags (4 bytes) pub flags: Vec<u8>, /// CompressionAlgorithms (variable): An array of 16-bit integer IDs specifying /// the supported compression algorithms. These IDs MUST be in order of preference /// from most to least. The following IDs are defined. pub compression_algorithms: Vec<Vec<u8>>, } impl CompressionCapabilities { /// Creates a new compression capabilities instance. pub fn default() -> Self { CompressionCapabilities { compression_algorithm_count: Vec::new(), padding: b"\x00\x00".to_vec(), flags: Vec::new(), compression_algorithms: Vec::new(), } } /// Fuzzes the compression capabilities with the predefined length. pub fn fuzz_with_predefined_length() -> Self { let mut random_algorithms: Vec<CompressionAlgorithms> = Vec::new(); for _ in 0..rand::thread_rng().gen_range(0..100) { random_algorithms.push(rand::random()); } CompressionCapabilities { compression_algorithm_count: (random_algorithms.len() as u16).to_le_bytes().to_vec(), padding: b"\x00\x00".to_vec(), flags: rand::random::<Flags>().unpack_byte_code(), compression_algorithms: random_algorithms .into_iter() .map(|algo| algo.unpack_byte_code()) .collect(), } } } impl DataSize for CompressionCapabilities { /// Gets the data size of the compression capabilities. fn get_data_length(&self) -> Vec<u8> { let length = self.compression_algorithm_count.len() + self.padding.len() + self.flags.len() + convert_byte_array_to_int(self.compression_algorithm_count.clone(), false) as usize; (length as u16).to_le_bytes().to_vec() } } impl std::fmt::Display for CompressionCapabilities { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "\n\t\t\tCompression Capabilities: \n\t\t\t\talgorithm count: {:?}\ \n\t\t\t\tpadding: {:?}\n\t\t\t\tflags: {:?}\n\t\t\t\talgorithms: {:?}", self.compression_algorithm_count, self.padding, self.flags, self.compression_algorithms ) } } /// The SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context is specified in an SMB2 NEGOTIATE request /// to indicate the server name the client connects to. #[derive(Debug, PartialEq, Eq, Clone)] pub struct NetnameNegotiateContextId { /// NetName (variable): A Unicode string containing the server name and specified /// by the client application. e.g. 'tom' pub net_name: Vec<u8>, } impl NetnameNegotiateContextId { /// Creates a new NetnameNegotiateContextId instance. pub fn default() -> Self { NetnameNegotiateContextId { net_name: Vec::new(), } } /// Fuzzess the netname with random bytes and a random length up to 100 bytes. pub fn fuzz() -> Self { NetnameNegotiateContextId { net_name: create_random_byte_array_of_predefined_length( rand::thread_rng().gen_range(0..100), ), } } } impl DataSize for NetnameNegotiateContextId { /// Gets the data size of the netname context id. fn get_data_length(&self) -> Vec<u8> { (self.net_name.len() as u16).to_le_bytes().to_vec() } } impl std::fmt::Display for NetnameNegotiateContextId { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "\n\t\t\tNetname Context ID: \n\t\t\t\tnetname: {:?}", self.net_name ) } } /// The SMB2_TRANSPORT_CAPABILITIES context is specified in an SMB2 NEGOTIATE request /// to indicate transport capabilities over which the connection is made. /// The server MUST ignore the context on receipt. #[derive(Debug, PartialEq, Eq, Clone)] pub struct TransportCapabilities { /// Reserved (4 bytes): This field SHOULD be set to zero and is ignored on receipt. pub reserved: Vec<u8>, } impl TransportCapabilities { /// Creates a new TransportCapabilities instance. pub fn default() -> Self { TransportCapabilities { reserved: b"\x00\x00\x00\x00".to_vec(), } } /// Fuzzes the transport capabilities with the predefined length. pub fn fuzz_with_predefined_length() -> Self { TransportCapabilities { reserved: create_random_byte_array_of_predefined_length(4), } } /// Fuzzes the transport capabilities with random length and bytes. pub fn fuzz_with_random_length() -> Self { TransportCapabilities { reserved: create_random_byte_array_of_predefined_length( rand::thread_rng().gen_range(0..100), ), } } } impl DataSize for TransportCapabilities { /// Gets the data length of the transport capabilities. fn get_data_length(&self) -> Vec<u8> { (self.reserved.len() as u16).to_le_bytes().to_vec() } } impl std::fmt::Display for TransportCapabilities { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "\n\t\t\tTransport Capabilities: \n\t\t\t\treserved: {:?}", self.reserved ) } } /// *RDMA Transform None*: /// - No transform /// /// *RDMA Transform Encryption*: /// - Encryption of data sent over RMDA. #[derive(Debug, PartialEq, Eq, Clone)] pub enum RdmaTransformIds { RdmaTransformNone, RdmaTransformEncryption, } impl RdmaTransformIds { /// Unpacks the byte code of RDMA transform ids. pub fn unpack_byte_code(&self) -> Vec<u8> { match self { RdmaTransformIds::RdmaTransformNone => b"\x00\x00".to_vec(), RdmaTransformIds::RdmaTransformEncryption => b"\x01\x00".to_vec(), } } } impl Distribution<RdmaTransformIds> for Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> RdmaTransformIds { match rng.gen_range(0..=1) { 0 => RdmaTransformIds::RdmaTransformNone, _ => RdmaTransformIds::RdmaTransformEncryption, } } } /// The RDMA_TRANSFORM_CAPABILITIES context is specified in an /// SMB2 NEGOTIATE request by the client to indicate the transforms /// supported when data is sent over RDMA. #[derive(Debug, PartialEq, Eq, Clone)] pub struct RdmaTransformCapabilities { /// TransformCount (2 bytes): The number of elements in RDMATransformIds array. /// This value MUST be greater than 0. pub transform_count: Vec<u8>, /// Reserved1 (2 bytes): This field MUST NOT be used and MUST be reserved. /// The sender MUST set this to 0, and the receiver MUST ignore it on receipt. pub reserved1: Vec<u8>, /// Reserved2 (4 bytes): This field MUST NOT be used and MUST be reserved. /// The sender MUST set this to 0, and the receiver MUST ignore it on receipt. pub reserved2: Vec<u8>, /// RDMATransformIds (variable): An array of 16-bit integer IDs specifying /// the supported RDMA transforms. The following IDs are defined. pub rdma_transform_ids: Vec<Vec<u8>>, } impl RdmaTransformCapabilities { /// Creates a new RDMATransformCapabilities instance. pub fn default() -> Self { RdmaTransformCapabilities { transform_count: Vec::new(), reserved1: b"\x00\x00".to_vec(), reserved2: b"\x00\x00\x00\x00".to_vec(), rdma_transform_ids: Vec::new(), } } /// Fuzzes the rdma transform capabilities with the predefined length. /// and semi-valid values. pub fn fuzz_with_predefined_length() -> Self { let mut random_ids: Vec<RdmaTransformIds> = Vec::new(); for _ in 0..rand::thread_rng().gen_range(0..100) { random_ids.push(rand::random()); } RdmaTransformCapabilities { transform_count: (random_ids.len() as u16).to_le_bytes().to_vec(), reserved1: b"\x00\x00".to_vec(), reserved2: b"\x00\x00\x00\x00".to_vec(), rdma_transform_ids: random_ids .into_iter() .map(|id| id.unpack_byte_code()) .collect(), } } } impl DataSize for RdmaTransformCapabilities { /// Gets the data length of the rdma transform capabilities. fn get_data_length(&self) -> Vec<u8> { let length = self.transform_count.len() + self.reserved1.len() + self.reserved2.len() + convert_byte_array_to_int(self.transform_count.clone(), false) as usize; (length as u16).to_le_bytes().to_vec() } } impl std::fmt::Display for RdmaTransformCapabilities { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "\n\t\t\tRDMA Transform Capabilities: \n\t\t\t\ttransform count: {:?}\ \n\t\t\t\treserved1: {:?}\n\t\t\t\treserved2: {:?}\n\t\t\t\tids: {:?}", self.transform_count, self.reserved1, self.reserved2, self.rdma_transform_ids ) } }
//! Example program drawing circles on a page. #[macro_use] extern crate simple_pdf; use simple_pdf::graphicsstate::Color; use simple_pdf::units::{Points, UserSpace}; use simple_pdf::Pdf; use std::f32::consts::PI; use std::io; /// Create a `circles.pdf` file, with a single page containg a circle /// stroked in black, overwritten with a circle in a finer yellow /// stroke. /// The black circle is drawn using the `Canvas.circle` method, /// which approximates a circle with four bezier curves. /// The yellow circle is drawn as a 200-sided polygon. fn main() -> io::Result<()> { // Open our pdf document. let mut document = Pdf::create("circles.pdf").expect("Could not create file."); // Add a 400x400 pt page. // Render-page writes the pdf file structure for a page and // creates a Canvas which is sent to the function that is the last // argument of the render_page method. // That function then puts content on the page by calling methods // on the canvas. document.render_page(pt!(400), pt!(400), |c| { let (x, y) = (pt!(200), pt!(200)); let r = pt!(190); // Set a wide black pen and stroke a circle c.set_stroke_color(Color::rgb(0, 0, 0))?; c.set_line_width(pt!(2))?; c.circle(x, y, r)?; c.stroke()?; // Set a finer yellow pen and stroke a 200-sided polygon c.set_stroke_color(Color::rgb(255, 230, 150))?; c.set_line_width(pt!(1))?; c.move_to(x + r, y)?; let sides: u8 = 200; for n in 1..sides { let phi = f32::from(n) * 2.0 * PI / f32::from(sides); c.line_to(x + r * phi.cos(), y + r * phi.sin())?; } c.close_and_stroke() })?; document.finish() }
mod game; pub use self::game::Suit; pub use self::game::Card; pub use self::game::PokerPlayer; pub use self::game::PokerGame; pub fn parse(raw_games: &str) -> Vec<PokerGame> { raw_games .lines() .map(str::trim) .filter(|line| !line.is_empty()) .map(game::parse) .collect() } #[cfg(test)] mod tests { use super::*; #[test] fn it_parsers_string_into_poker_game() { let raw_games = " Player1: 2H 3D 5S 9C KD Player2: 2C 3H 4S 8C AH Player1: 2H 3D 5S 9C AD Player2: 2C 3H 4S 8C KH "; assert_eq!(parse(raw_games), vec![ PokerGame { players: vec![ PokerPlayer { id: "Player1".to_string(), cards: vec![ Card { number: 2, suit: Suit::Hearts }, Card { number: 3, suit: Suit::Dimonds }, Card { number: 5, suit: Suit::Spades }, Card { number: 9, suit: Suit::Clubs }, Card { number: 13, suit: Suit::Dimonds } ] }, PokerPlayer { id: "Player2".to_string(), cards: vec![ Card { number: 2, suit: Suit::Clubs }, Card { number: 3, suit: Suit::Hearts }, Card { number: 4, suit: Suit::Spades }, Card { number: 8, suit: Suit::Clubs }, Card { number: 14, suit: Suit::Hearts } ] } ] }, PokerGame { players: vec![ PokerPlayer { id: "Player1".to_string(), cards: vec![ Card { number: 2, suit: Suit::Hearts }, Card { number: 3, suit: Suit::Dimonds }, Card { number: 5, suit: Suit::Spades }, Card { number: 9, suit: Suit::Clubs }, Card { number: 14, suit: Suit::Dimonds } ] }, PokerPlayer { id: "Player2".to_string(), cards: vec![ Card { number: 2, suit: Suit::Clubs }, Card { number: 3, suit: Suit::Hearts }, Card { number: 4, suit: Suit::Spades }, Card { number: 8, suit: Suit::Clubs }, Card { number: 13, suit: Suit::Hearts } ] } ] } ]) } }
use crate::datastructure::DataStructure; use crate::shader::shaders::{emittance, map_uv}; use crate::shader::Shader; use crate::util::ray::Ray; use crate::util::rng::get_rng; use crate::util::vector::Vector; use rand::Rng; use std::f64; #[derive(Debug)] pub struct VMcShader { air_density: f64, particle_reflectivity: f64, } impl VMcShader { pub fn new(air_density: f64, particle_reflectivity: f64) -> Self { Self { air_density, particle_reflectivity, } } pub fn shade_internal<'a>( &self, ray: &Ray, depth: usize, datastructure: &'a (dyn DataStructure + 'a), ) -> Vector { let intersection = if let Some(intersection) = datastructure.intersects(&ray) { intersection } else { return if depth > 0 { let reflec_type = get_rng(|mut r| r.gen::<f64>()); if self.particle_reflectivity > reflec_type { let breakdist = -get_rng(|mut r| r.gen::<f64>()).ln() / self.air_density; let hit_point = ray.origin + ray.direction * breakdist; let scatter_ray = Ray::new(hit_point, Vector::point_on_sphere()); self.shade_internal(&scatter_ray, depth - 1, datastructure) } else { Vector::repeated(0f64) } } else { Vector::repeated(0f64) }; }; let hit_pos = intersection.hit_pos(); let dist = (ray.origin - hit_pos).length(); let breakdist = -get_rng(|mut r| r.gen::<f64>()).ln() / self.air_density; if breakdist < dist { let reflec_type = get_rng(|mut r| r.gen::<f64>()); if self.particle_reflectivity > reflec_type { let hit_point = ray.origin + ray.direction * breakdist; let scatter_ray = Ray::new(hit_point, Vector::point_on_sphere()); if depth > 0 { return self.shade_internal(&scatter_ray, depth - 1, datastructure); } else { return Vector::repeated(0f64); } } else { return Vector::repeated(0f64); } } // // let part_amb = ambient(&intersection.face, self.scene) * Vector::repeated(0.1); let part_emi = emittance(&intersection); // let part_diff = diffuse(&intersection.face, self.scene, hit_pos, pointlight) * brightness; // let part_spec = specular(&intersection.face, self.scene, hit_pos, pointlight, intersection.ray.origin) * brightness; // // // let direct = part_amb + part_emi + part_diff + part_spec; let indirect = if depth > 0 { let reflec_type = get_rng(|mut r| r.gen::<f64>()); let diffuse_max = intersection.triangle.material().diffuse.max_item(); if diffuse_max > reflec_type { let fliped_normal = if intersection.triangle.normal().dot(ray.direction) < 0. { intersection.triangle.normal() } else { intersection.triangle.normal() * -1. }; let bounce_direction = Vector::point_on_diffuse_hemisphere().rotated(fliped_normal); let bounce_ray = Ray::new(hit_pos, bounce_direction); let indirect_light = self.shade_internal(&bounce_ray, depth - 1, datastructure); let texture = if let Some(texture) = intersection.triangle.mesh.material.diffuse_texture { let coord = map_uv(&intersection); texture.at(coord) } else { Vector::new(1., 1., 1.) }; indirect_light * intersection.triangle.material().diffuse / diffuse_max * texture } else { Vector::repeated(0f64) } } else { Vector::repeated(0f64) }; indirect + part_emi } } impl Shader for VMcShader { fn shade<'s>(&self, ray: &Ray, datastructure: &'s (dyn DataStructure + 's)) -> Vector { self.shade_internal(ray, 6, datastructure) } }