hexsha
stringlengths
40
40
size
int64
2
1.05M
content
stringlengths
2
1.05M
avg_line_length
float64
1.33
100
max_line_length
int64
1
1k
alphanum_fraction
float64
0.25
1
1eb16e52414d9a187b651bf8205e8e32b7d93ae1
3,953
//! # Integrating x11rb with an Event Loop //! //! To integrate x11rb with an event loop, //! [`std::os::unix::io::AsRawFd`](https://doc.rust-lang.org/std/os/unix/io/trait.AsRawFd.html) is //! implemented by [`RustConnection`](../rust_connection/struct.RustConnection.html)'s //! [`DefaultStream`](../rust_connection/struct.DefaultStream.html#impl-AsRawFd) and //! [`XCBConnection`](../xcb_ffi/struct.XCBConnection.html#impl-AsRawFd). This allows to integrate //! with an event loop that also handles timeouts or network I/O. See //! [`xclock_utc`](https://github.com/psychon/x11rb/blob/master/examples/xclock_utc.rs) for an //! example. //! //! The general form of such an integration could be as follows: //! ```no_run //! #[cfg(unix)] //! use std::os::unix::io::{AsRawFd, RawFd}; //! #[cfg(windows)] //! use std::os::windows::io::{AsRawSocket, RawSocket}; //! use x11rb::connection::Connection; //! use x11rb::rust_connection::RustConnection; //! use x11rb::errors::ConnectionError; //! //! fn main_loop(conn: &RustConnection) -> Result<(), ConnectionError> { //! #[cfg(unix)] //! let raw_handle = conn.stream().as_raw_fd(); //! #[cfg(windows)] //! let raw_handle = conn.stream().as_raw_socket(); //! loop { //! while let Some(event) = conn.poll_for_event()? { //! handle_event(event); //! } //! //! poll_for_readable(raw_handle); //! //! // Do other work here. //! } //! } //! # fn handle_event<T>(event: T) {} //! # fn poll_for_readable<T>(event: T) {} //! ``` //! The function `poll_for_readable` could wait for any number of I/O streams (besides the one from //! x11rb) to become readable. It can also implement timeouts, as seen in the //! [`xclock_utc` example](https://github.com/psychon/x11rb/blob/master/examples/xclock_utc.rs). //! //! //! ## Threads and Races //! //! Both [`RustConnection`](../rust_connection/struct.RustConnection.html) and //! [`XCBConnection`](../xcb_ffi/struct.XCBConnection.html) are `Sync+Send`. However, it is still //! possible to see races in the presence of threads and an event loop. //! //! The underlying problem is that the following two points are not equivalent: //! //! 1. A new event is available and can be returned from `conn.poll_for_event()`. //! 2. The underlying I/O stream is readable. //! //! The reason for this is an internal buffer that is required: When an event is received from the //! X11 server, but we are currently not in `conn.poll_for_event()`, then this event is added to an //! internal buffer. Thus, it can happen that there is an event available, but the stream is not //! readable. //! //! An example for such an other function is `conn.get_input_focus()?.reply()?`: The //! `GetInputFocus` request is sent to the server and then `reply()` waits for the reply. It does //! so by reading X11 packets from the X11 server until the right reply arrives. Any events that //! are read during this are buffered internally in the `Connection`. //! //! If this race occurs, the main loop would sit in `poll_for_readable` and wait, while the already //! buffered event is available. When something else wakes up the main loop and //! `conn.poll_for_event()` is called the next time, the event is finally processed. //! //! There are two ways around this: //! //! 1. Only interact with x11rb from one thread. //! 2. Use a dedicated thread for waiting for event. //! //! In case (1), one can call `conn.poll_for_event()` before waiting for the underlying I/O stream //! to be readable. Since there are no other threads, nothing can read a new event from the stream //! after `conn.poll_for_event()` returned `None`. //! //! Option (2) is to start a thread that calls `conn.wait_for_event()` in a loop. This is basically //! a dedicated event loop for fetching events from the X11 server. All other threads can now //! freely use the X11 connection without events possibly getting stuck and only being processed //! later.
47.626506
99
0.691627
bb81cf55c24764df0d3058b25959f4f13b1e1f67
18,890
// Copyright 2017 PingCAP, Inc. // // 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, // See the License for the specific language governing permissions and // limitations under the License. use std::fs::File; use std::io::Read; use std::path::PathBuf; use rocksdb::{CompactionPriority, DBCompactionStyle, DBCompressionType, DBRecoveryMode}; use slog::Level; use tikv::config::*; use tikv::import::Config as ImportConfig; use tikv::pd::Config as PdConfig; use tikv::raftstore::coprocessor::Config as CopConfig; use tikv::raftstore::store::Config as RaftstoreConfig; use tikv::server::Config as ServerConfig; use tikv::server::config::GrpcCompressionType; use tikv::storage::Config as StorageConfig; use tikv::util::config::{ReadableDuration, ReadableSize}; use tikv::util::security::SecurityConfig; use toml; #[test] fn test_toml_serde() { let value = TiKvConfig::default(); let dump = toml::to_string_pretty(&value).unwrap(); let load = toml::from_str(&dump).unwrap(); assert_eq!(value, load); } // Read a file in project directory. It is similar to `include_str!`, // but `include_str!` a large string literal increases compile time. // See more: https://github.com/rust-lang/rust/issues/39352 fn read_file_in_project_dir(path: &str) -> String { let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR")); p.push(path); let mut f = File::open(p).unwrap(); let mut buffer = String::new(); f.read_to_string(&mut buffer).unwrap(); buffer } #[test] fn test_serde_custom_tikv_config() { let mut value = TiKvConfig::default(); value.log_level = Level::Debug; value.log_file = "foo".to_owned(); value.server = ServerConfig { cluster_id: 0, // KEEP IT ZERO, it is skipped by serde. addr: "example.com:443".to_owned(), labels: map!{ "a".to_owned() => "b".to_owned() }, advertise_addr: "example.com:443".to_owned(), notify_capacity: 12_345, messages_per_tick: 123, concurrent_send_snap_limit: 4, concurrent_recv_snap_limit: 4, grpc_compression_type: GrpcCompressionType::Gzip, grpc_concurrency: 123, grpc_concurrent_stream: 1_234, grpc_raft_conn_num: 123, grpc_stream_initial_window_size: ReadableSize(12_345), grpc_keepalive_time: ReadableDuration::secs(3), grpc_keepalive_timeout: ReadableDuration::secs(60), end_point_concurrency: None, end_point_max_tasks: 12, end_point_stack_size: None, end_point_recursion_limit: 100, end_point_stream_channel_size: 16, end_point_batch_row_limit: 64, end_point_stream_batch_row_limit: 4096, end_point_request_max_handle_duration: ReadableDuration::secs(12), snap_max_write_bytes_per_sec: ReadableSize::mb(10), snap_max_total_size: ReadableSize::gb(10), }; value.readpool = ReadPoolConfig { storage: StorageReadPoolConfig { high_concurrency: 1, normal_concurrency: 3, low_concurrency: 7, max_tasks_high: 10000, max_tasks_normal: 20000, max_tasks_low: 30000, stack_size: ReadableSize::mb(20), }, coprocessor: CoprocessorReadPoolConfig { high_concurrency: 2, normal_concurrency: 4, low_concurrency: 6, max_tasks_high: 20000, max_tasks_normal: 30000, max_tasks_low: 40000, stack_size: ReadableSize::mb(12), }, }; value.metric = MetricConfig { interval: ReadableDuration::secs(12), address: "example.com:443".to_owned(), job: "tikv_1".to_owned(), }; value.raft_store = RaftstoreConfig { sync_log: false, raftdb_path: "/var".to_owned(), capacity: ReadableSize(123), raft_base_tick_interval: ReadableDuration::secs(12), raft_heartbeat_ticks: 1, raft_election_timeout_ticks: 12, raft_min_election_timeout_ticks: 14, raft_max_election_timeout_ticks: 20, raft_max_size_per_msg: ReadableSize::mb(12), raft_max_inflight_msgs: 123, raft_entry_max_size: ReadableSize::mb(12), raft_log_gc_tick_interval: ReadableDuration::secs(12), raft_log_gc_threshold: 12, raft_log_gc_count_limit: 12, raft_log_gc_size_limit: ReadableSize::kb(1), split_region_check_tick_interval: ReadableDuration::secs(12), region_split_check_diff: ReadableSize::mb(6), region_compact_check_interval: ReadableDuration::secs(12), clean_stale_peer_delay: ReadableDuration::secs(13), region_compact_check_step: 1_234, region_compact_min_tombstones: 999, pd_heartbeat_tick_interval: ReadableDuration::minutes(12), pd_store_heartbeat_tick_interval: ReadableDuration::secs(12), notify_capacity: 12_345, snap_mgr_gc_tick_interval: ReadableDuration::minutes(12), snap_gc_timeout: ReadableDuration::hours(12), messages_per_tick: 12_345, max_peer_down_duration: ReadableDuration::minutes(12), max_leader_missing_duration: ReadableDuration::hours(12), abnormal_leader_missing_duration: ReadableDuration::hours(6), peer_stale_state_check_interval: ReadableDuration::hours(2), snap_apply_batch_size: ReadableSize::mb(12), lock_cf_compact_interval: ReadableDuration::minutes(12), lock_cf_compact_bytes_threshold: ReadableSize::mb(123), consistency_check_interval: ReadableDuration::secs(12), report_region_flow_interval: ReadableDuration::minutes(12), raft_store_max_leader_lease: ReadableDuration::secs(12), right_derive_when_split: false, allow_remove_leader: true, merge_max_log_gap: 3, merge_check_tick_interval: ReadableDuration::secs(11), use_delete_range: true, cleanup_import_sst_interval: ReadableDuration::minutes(12), region_max_size: ReadableSize(0), region_split_size: ReadableSize(0), }; value.pd = PdConfig { endpoints: vec!["example.com:443".to_owned()], }; value.rocksdb = DbConfig { wal_recovery_mode: DBRecoveryMode::AbsoluteConsistency, wal_dir: "/var".to_owned(), wal_ttl_seconds: 1, wal_size_limit: ReadableSize::kb(1), max_total_wal_size: ReadableSize::gb(1), max_background_jobs: 12, max_manifest_file_size: ReadableSize::mb(12), create_if_missing: false, max_open_files: 12_345, enable_statistics: false, stats_dump_period: ReadableDuration::minutes(12), compaction_readahead_size: ReadableSize::kb(1), info_log_max_size: ReadableSize::kb(1), info_log_roll_time: ReadableDuration::secs(12), info_log_dir: "/var".to_owned(), rate_bytes_per_sec: ReadableSize::kb(1), bytes_per_sync: ReadableSize::mb(1), wal_bytes_per_sync: ReadableSize::kb(32), max_sub_compactions: 12, writable_file_max_buffer_size: ReadableSize::mb(12), use_direct_io_for_flush_and_compaction: true, enable_pipelined_write: false, defaultcf: DefaultCfConfig { block_size: ReadableSize::kb(12), block_cache_size: ReadableSize::gb(12), disable_block_cache: false, cache_index_and_filter_blocks: false, pin_l0_filter_and_index_blocks: false, use_bloom_filter: false, whole_key_filtering: true, bloom_filter_bits_per_key: 123, block_based_bloom_filter: true, read_amp_bytes_per_bit: 0, compression_per_level: [ DBCompressionType::No, DBCompressionType::No, DBCompressionType::Zstd, DBCompressionType::Zstd, DBCompressionType::No, DBCompressionType::Zstd, DBCompressionType::Lz4, ], write_buffer_size: ReadableSize::mb(1), max_write_buffer_number: 12, min_write_buffer_number_to_merge: 12, max_bytes_for_level_base: ReadableSize::kb(12), target_file_size_base: ReadableSize::kb(123), level0_file_num_compaction_trigger: 123, level0_slowdown_writes_trigger: 123, level0_stop_writes_trigger: 123, max_compaction_bytes: ReadableSize::gb(1), compaction_pri: CompactionPriority::MinOverlappingRatio, dynamic_level_bytes: true, num_levels: 4, max_bytes_for_level_multiplier: 8, compaction_style: DBCompactionStyle::Universal, disable_auto_compactions: true, soft_pending_compaction_bytes_limit: ReadableSize::gb(12), hard_pending_compaction_bytes_limit: ReadableSize::gb(12), }, writecf: WriteCfConfig { block_size: ReadableSize::kb(12), block_cache_size: ReadableSize::gb(12), disable_block_cache: false, cache_index_and_filter_blocks: false, pin_l0_filter_and_index_blocks: false, use_bloom_filter: false, whole_key_filtering: true, bloom_filter_bits_per_key: 123, block_based_bloom_filter: true, read_amp_bytes_per_bit: 0, compression_per_level: [ DBCompressionType::No, DBCompressionType::No, DBCompressionType::Zstd, DBCompressionType::Zstd, DBCompressionType::No, DBCompressionType::Zstd, DBCompressionType::Lz4, ], write_buffer_size: ReadableSize::mb(1), max_write_buffer_number: 12, min_write_buffer_number_to_merge: 12, max_bytes_for_level_base: ReadableSize::kb(12), target_file_size_base: ReadableSize::kb(123), level0_file_num_compaction_trigger: 123, level0_slowdown_writes_trigger: 123, level0_stop_writes_trigger: 123, max_compaction_bytes: ReadableSize::gb(1), compaction_pri: CompactionPriority::MinOverlappingRatio, dynamic_level_bytes: true, num_levels: 4, max_bytes_for_level_multiplier: 8, compaction_style: DBCompactionStyle::Universal, disable_auto_compactions: true, soft_pending_compaction_bytes_limit: ReadableSize::gb(12), hard_pending_compaction_bytes_limit: ReadableSize::gb(12), }, lockcf: LockCfConfig { block_size: ReadableSize::kb(12), block_cache_size: ReadableSize::gb(12), disable_block_cache: false, cache_index_and_filter_blocks: false, pin_l0_filter_and_index_blocks: false, use_bloom_filter: false, whole_key_filtering: true, bloom_filter_bits_per_key: 123, block_based_bloom_filter: true, read_amp_bytes_per_bit: 0, compression_per_level: [ DBCompressionType::No, DBCompressionType::No, DBCompressionType::Zstd, DBCompressionType::Zstd, DBCompressionType::No, DBCompressionType::Zstd, DBCompressionType::Lz4, ], write_buffer_size: ReadableSize::mb(1), max_write_buffer_number: 12, min_write_buffer_number_to_merge: 12, max_bytes_for_level_base: ReadableSize::kb(12), target_file_size_base: ReadableSize::kb(123), level0_file_num_compaction_trigger: 123, level0_slowdown_writes_trigger: 123, level0_stop_writes_trigger: 123, max_compaction_bytes: ReadableSize::gb(1), compaction_pri: CompactionPriority::MinOverlappingRatio, dynamic_level_bytes: true, num_levels: 4, max_bytes_for_level_multiplier: 8, compaction_style: DBCompactionStyle::Universal, disable_auto_compactions: true, soft_pending_compaction_bytes_limit: ReadableSize::gb(12), hard_pending_compaction_bytes_limit: ReadableSize::gb(12), }, raftcf: RaftCfConfig { block_size: ReadableSize::kb(12), block_cache_size: ReadableSize::gb(12), disable_block_cache: false, cache_index_and_filter_blocks: false, pin_l0_filter_and_index_blocks: false, use_bloom_filter: false, whole_key_filtering: true, bloom_filter_bits_per_key: 123, block_based_bloom_filter: true, read_amp_bytes_per_bit: 0, compression_per_level: [ DBCompressionType::No, DBCompressionType::No, DBCompressionType::Zstd, DBCompressionType::Zstd, DBCompressionType::No, DBCompressionType::Zstd, DBCompressionType::Lz4, ], write_buffer_size: ReadableSize::mb(1), max_write_buffer_number: 12, min_write_buffer_number_to_merge: 12, max_bytes_for_level_base: ReadableSize::kb(12), target_file_size_base: ReadableSize::kb(123), level0_file_num_compaction_trigger: 123, level0_slowdown_writes_trigger: 123, level0_stop_writes_trigger: 123, max_compaction_bytes: ReadableSize::gb(1), compaction_pri: CompactionPriority::MinOverlappingRatio, dynamic_level_bytes: true, num_levels: 4, max_bytes_for_level_multiplier: 8, compaction_style: DBCompactionStyle::Universal, disable_auto_compactions: true, soft_pending_compaction_bytes_limit: ReadableSize::gb(12), hard_pending_compaction_bytes_limit: ReadableSize::gb(12), }, }; value.raftdb = RaftDbConfig { wal_recovery_mode: DBRecoveryMode::SkipAnyCorruptedRecords, wal_dir: "/var".to_owned(), wal_ttl_seconds: 1, wal_size_limit: ReadableSize::kb(12), max_total_wal_size: ReadableSize::gb(1), max_manifest_file_size: ReadableSize::mb(12), create_if_missing: false, max_open_files: 12_345, enable_statistics: false, stats_dump_period: ReadableDuration::minutes(12), compaction_readahead_size: ReadableSize::kb(1), info_log_max_size: ReadableSize::kb(1), info_log_roll_time: ReadableDuration::secs(1), info_log_dir: "/var".to_owned(), max_sub_compactions: 12, writable_file_max_buffer_size: ReadableSize::mb(12), use_direct_io_for_flush_and_compaction: true, enable_pipelined_write: false, allow_concurrent_memtable_write: true, bytes_per_sync: ReadableSize::mb(1), wal_bytes_per_sync: ReadableSize::kb(32), defaultcf: RaftDefaultCfConfig { block_size: ReadableSize::kb(12), block_cache_size: ReadableSize::gb(12), disable_block_cache: false, cache_index_and_filter_blocks: false, pin_l0_filter_and_index_blocks: false, use_bloom_filter: false, whole_key_filtering: true, bloom_filter_bits_per_key: 123, block_based_bloom_filter: true, read_amp_bytes_per_bit: 0, compression_per_level: [ DBCompressionType::No, DBCompressionType::No, DBCompressionType::Zstd, DBCompressionType::Zstd, DBCompressionType::No, DBCompressionType::Zstd, DBCompressionType::Lz4, ], write_buffer_size: ReadableSize::mb(1), max_write_buffer_number: 12, min_write_buffer_number_to_merge: 12, max_bytes_for_level_base: ReadableSize::kb(12), target_file_size_base: ReadableSize::kb(123), level0_file_num_compaction_trigger: 123, level0_slowdown_writes_trigger: 123, level0_stop_writes_trigger: 123, max_compaction_bytes: ReadableSize::gb(1), compaction_pri: CompactionPriority::MinOverlappingRatio, dynamic_level_bytes: true, num_levels: 4, max_bytes_for_level_multiplier: 8, compaction_style: DBCompactionStyle::Universal, disable_auto_compactions: true, soft_pending_compaction_bytes_limit: ReadableSize::gb(12), hard_pending_compaction_bytes_limit: ReadableSize::gb(12), }, }; value.storage = StorageConfig { data_dir: "/var".to_owned(), gc_ratio_threshold: 1.2, max_key_size: 8192, scheduler_notify_capacity: 123, scheduler_messages_per_tick: 123, scheduler_concurrency: 123, scheduler_worker_pool_size: 1, scheduler_pending_write_threshold: ReadableSize::kb(123), }; value.coprocessor = CopConfig { split_region_on_table: true, region_max_size: ReadableSize::mb(12), region_split_size: ReadableSize::mb(12), }; value.security = SecurityConfig { ca_path: "invalid path".to_owned(), cert_path: "invalid path".to_owned(), key_path: "invalid path".to_owned(), override_ssl_target: "".to_owned(), }; value.import = ImportConfig { import_dir: "/abc".to_owned(), num_threads: 123, stream_channel_window: 123, }; let custom = read_file_in_project_dir("tests/config/test-custom.toml"); let load = toml::from_str(&custom).unwrap(); assert_eq!(value, load); let dump = toml::to_string_pretty(&load).unwrap(); assert_eq!(dump, custom); } #[test] fn test_serde_default_config() { let cfg: TiKvConfig = toml::from_str("").unwrap(); assert_eq!(cfg, TiKvConfig::default()); let content = read_file_in_project_dir("tests/config/test-default.toml"); let cfg: TiKvConfig = toml::from_str(&content).unwrap(); assert_eq!(cfg, TiKvConfig::default()); } #[test] fn test_readpool_default_config() { let content = r#" [readpool.storage] high-concurrency = 1 "#; let cfg: TiKvConfig = toml::from_str(content).unwrap(); let mut expected = TiKvConfig::default(); expected.readpool.storage.high_concurrency = 1; // Note: max_tasks is unchanged! assert_eq!(cfg, expected); }
41.60793
88
0.648332
8f9aa084669ccf3b1ef47abe7974a96cacb69f68
1,025
pub fn combine(n: i32, k: i32) -> Vec<Vec<i32>> { debug_assert!(n > 0 && k > 0 && n >= k); let n = n as usize; let k = k as usize; let mut results = Vec::new(); let mut stack = Vec::with_capacity(k); backtrack(1, n, k, &mut stack, &mut results); results } fn backtrack( start: usize, end: usize, k: usize, stack: &mut Vec<i32>, results: &mut Vec<Vec<i32>>, ) { if stack.len() < k { for num in start..=end { stack.push(num as i32); backtrack(num + 1, end, k, stack, results); stack.pop(); } } else { results.push(stack.clone()); } } #[test] fn test() { use utils::assert_same_set; let cases = vec![( 4, 2, vec![ vec![2, 4], vec![3, 4], vec![2, 3], vec![1, 2], vec![1, 3], vec![1, 4], ], )]; for (n, k, expected) in cases { assert_same_set(combine(n, k), expected); } }
20.098039
55
0.44878
3907c77bb5e19bba1fee3931a3acfeb8214a221b
1,087
use crate::internal::*; #[derive(Debug, Clone, new, Hash)] pub struct Shape { pub dt: DatumType, } tract_linalg::impl_dyn_hash!(Shape); impl Op for Shape { fn name(&self) -> Cow<str> { "Shape".into() } op_core_mir!(); op_as_typed_op!(); not_a_pulsed_op!(); } impl StatelessOp for Shape { /// Evaluates the operation given the input tensors. fn eval(&self, inputs: TVec<Arc<Tensor>>) -> TractResult<TVec<Arc<Tensor>>> { let shape = rctensor1(&inputs[0].shape().iter().map(|&d| d as i64).collect::<Vec<_>>()); let shape = shape.cast_to_dt(self.dt)?.into_owned(); Ok(tvec![shape.into_arc_tensor()]) } } impl TypedOp for Shape { fn output_facts(&self, inputs: &[&TypedFact]) -> TractResult<TVec<TypedFact>> { let shape = inputs[0].shape.iter().collect::<TVec<_>>(); let mut tensor = tensor1(&*shape); if shape.iter().all(|d| d.to_integer().is_ok()) { tensor = tensor.cast_to_dt(self.dt)?.into_owned(); } Ok(tvec!(TypedFact::from(tensor))) } as_op!(); }
27.175
96
0.595216
23ec08eaa51af34d27a8ee5d7d5b19debb6278d6
111,018
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // TODO: Edit this doc comment (it's copy+pasted from the Netstack3 core) //! Internet Protocol (IP) types. //! //! This module provides support for various types and traits relating to IPv4 //! and IPv6, including a number of mechanisms for abstracting over details //! which are shared between IPv4 and IPv6. //! //! # `Ip` and `IpAddress` //! //! The most important traits are [`Ip`] and [`IpAddress`]. //! //! `Ip` represents a version of the IP protocol - either IPv4 or IPv6 - and is //! implemented by [`Ipv4`] and [`Ipv6`]. These types exist only at the type //! level - they cannot be constructed at runtime. They provide a place to put //! constants and functionality which are not associated with a particular type, //! and they allow code to be written which is generic over the version of the //! IP protocol. For example: //! //! ```rust //! # use net_types::ip::{Ip, IpAddress, Subnet}; //! struct Entry<A: IpAddress> { //! subnet: Subnet<A>, //! dest: Destination<A>, //! } //! //! enum Destination<A: IpAddress> { //! Local { device_id: usize }, //! Remote { dst: A }, //! } //! //! struct ForwardingTable<I: Ip> { //! entries: Vec<Entry<I::Addr>>, //! } //! ``` //! //! See also [`IpVersionMarker`]. //! //! The `IpAddress` trait is implemented by the concrete [`Ipv4Addr`] and //! [`Ipv6Addr`] types. //! //! # Runtime types //! //! Sometimes, it is not known at compile time which version of a given type - //! IPv4 or IPv6 - is present. For these cases, enums are provided with variants //! for both IPv4 and IPv6. These are [`IpAddr`], [`SubnetEither`], and //! [`AddrSubnetEither`]. //! //! # Composite types //! //! This modules also provides composite types such as [`Subnet`] and //! [`AddrSubnet`]. use core::convert::TryFrom; use core::fmt::{self, Debug, Display, Formatter}; use core::hash::Hash; use core::mem; use core::ops::Deref; #[cfg(feature = "std")] use std::net; use zerocopy::{AsBytes, FromBytes, Unaligned}; use crate::{ sealed, LinkLocalAddr, LinkLocalAddress, LinkLocalMulticastAddr, LinkLocalUnicastAddr, MulticastAddr, MulticastAddress, Scope, ScopeableAddress, SpecifiedAddr, SpecifiedAddress, UnicastAddr, UnicastAddress, Witness, }; // NOTE on passing by reference vs by value: Clippy advises us to pass IPv4 // addresses by value, and IPv6 addresses by reference. For concrete types, we // do the right thing. For the IpAddress trait, we use references in order to // optimize (albeit very slightly) for IPv6 performance. /// An IP protocol version. #[allow(missing_docs)] #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub enum IpVersion { V4, V6, } /// A zero-sized type that carries IP version information. /// /// `IpVersionMarker` is typically used by types that are generic over IP /// version, but without any other associated data. In this sense, /// `IpVersionMarker` behaves similarly to [`PhantomData`]. /// /// [`PhantomData`]: core::marker::PhantomData #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct IpVersionMarker<I: Ip> { _marker: core::marker::PhantomData<I>, } impl<I: Ip> Default for IpVersionMarker<I> { fn default() -> Self { Self { _marker: core::marker::PhantomData } } } impl<I: Ip> Debug for IpVersionMarker<I> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "IpVersionMarker<{}>", I::NAME) } } /// An IP address. /// /// By default, the contained address types are [`Ipv4Addr`] and [`Ipv6Addr`]. /// However, any types can be provided. This is intended to support types like /// `IpAddr<SpecifiedAddr<Ipv4Addr>, SpecifiedAddr<Ipv6Addr>>`. `From` is /// implemented to support conversions in both directions between /// `IpAddr<SpecifiedAddr<Ipv4Addr>, SpecifiedAddr<Ipv6Addr>>` and /// `SpecifiedAddr<IpAddr>`, and similarly for other witness types. #[allow(missing_docs)] #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub enum IpAddr<V4 = Ipv4Addr, V6 = Ipv6Addr> { V4(V4), V6(V6), } impl<V4, V6> IpAddr<V4, V6> { /// Transposes an `IpAddr` of a witness type to a witness type of an /// `IpAddr`. /// /// For example, `transpose` can be used to convert an /// `IpAddr<SpecifiedAddr<Ipv4Addr>, SpecifiedAddr<Ipv6Addr>>` into a /// `SpecifiedAddr<IpAddr<Ipv4Addr, Ipv6Addr>>`. pub fn transpose<W: IpAddrWitness<V4 = V4, V6 = V6>>(self) -> W { match self { IpAddr::V4(addr) => W::from_v4(addr), IpAddr::V6(addr) => W::from_v6(addr), } } } impl<A: IpAddress> From<A> for IpAddr { #[inline] fn from(addr: A) -> IpAddr { addr.to_ip_addr() } } #[cfg(feature = "std")] impl From<net::IpAddr> for IpAddr { #[inline] fn from(addr: net::IpAddr) -> IpAddr { match addr { net::IpAddr::V4(addr) => IpAddr::V4(addr.into()), net::IpAddr::V6(addr) => IpAddr::V6(addr.into()), } } } #[cfg(feature = "std")] impl From<IpAddr> for net::IpAddr { fn from(addr: IpAddr) -> net::IpAddr { match addr { IpAddr::V4(addr) => net::IpAddr::V4(addr.into()), IpAddr::V6(addr) => net::IpAddr::V6(addr.into()), } } } impl IpVersion { /// The number for this IP protocol version. /// /// 4 for `V4` and 6 for `V6`. #[inline] pub fn version_number(self) -> u8 { match self { IpVersion::V4 => 4, IpVersion::V6 => 6, } } /// Is this IPv4? #[inline] pub fn is_v4(self) -> bool { self == IpVersion::V4 } /// Is this IPv6? #[inline] pub fn is_v6(self) -> bool { self == IpVersion::V6 } } /// A trait for IP protocol versions. /// /// `Ip` encapsulates the details of a version of the IP protocol. It includes a /// runtime representation of the protocol version ([`VERSION`]), the type of /// addresses for this version ([`Addr`]), and a number of constants which exist /// in both protocol versions. This trait is sealed, and there are guaranteed to /// be no other implementors besides these. Code - including unsafe code - may /// rely on this assumption for its correctness and soundness. /// /// Note that the implementors of this trait cannot be instantiated; they only /// exist at the type level. /// /// [`VERSION`]: Ip::VERSION /// [`Addr`]: Ip::Addr pub trait Ip: Sized + Clone + Copy + Debug + Default + Eq + Hash + Ord + PartialEq + PartialOrd + Send + Sync + sealed::Sealed + 'static { /// The IP version. /// /// `V4` for IPv4 and `V6` for IPv6. const VERSION: IpVersion; /// The unspecified address. /// /// This is 0.0.0.0 for IPv4 and :: for IPv6. const UNSPECIFIED_ADDRESS: Self::Addr; /// The default loopback address. /// /// When sending packets to a loopback interface, this address is used as /// the source address. It is an address in the [`LOOPBACK_SUBNET`]. /// /// [`LOOPBACK_SUBNET`]: Ip::LOOPBACK_SUBNET const LOOPBACK_ADDRESS: SpecifiedAddr<Self::Addr>; /// The subnet of loopback addresses. /// /// Addresses in this subnet must not appear outside a host, and may only be /// used for loopback interfaces. const LOOPBACK_SUBNET: Subnet<Self::Addr>; /// The subnet of multicast addresses. const MULTICAST_SUBNET: Subnet<Self::Addr>; /// The subnet of link-local unicast addresses. /// /// Note that some multicast addresses are also link-local. In IPv4, these /// are contained in the [link-local multicast subnet]. In IPv6, the /// link-local multicast addresses are not organized into a single subnet; /// instead, whether a multicast IPv6 address is link-local is a function of /// its scope. /// /// [link-local multicast subnet]: Ipv4::LINK_LOCAL_MULTICAST_SUBNET const LINK_LOCAL_UNICAST_SUBNET: Subnet<Self::Addr>; /// "IPv4" or "IPv6". const NAME: &'static str; /// The minimum link MTU for this version. /// /// Every internet link supporting this IP version must have a maximum /// transmission unit (MTU) of at least this many bytes. This MTU applies to /// the size of an IP packet, and does not include any extra bytes used by /// encapsulating packets (Ethernet frames, GRE packets, etc). const MINIMUM_LINK_MTU: u16; /// The address type for this IP version. /// /// [`Ipv4Addr`] for IPv4 and [`Ipv6Addr`] for IPv6. type Addr: IpAddress<Version = Self>; } /// IPv4. /// /// `Ipv4` implements [`Ip`] for IPv4. /// /// Note that this type has no value constructor. It is used purely at the type /// level. Attempting to construct it by calling `Default::default` will panic. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum Ipv4 {} impl Default for Ipv4 { fn default() -> Ipv4 { panic!("Ipv4 default") } } impl sealed::Sealed for Ipv4 {} impl Ip for Ipv4 { const VERSION: IpVersion = IpVersion::V4; // TODO(https://fxbug.dev/83331): Document the standard in which this // constant is defined. const UNSPECIFIED_ADDRESS: Ipv4Addr = Ipv4Addr::new([0, 0, 0, 0]); /// The default IPv4 address used for loopback, defined in [RFC 5735 Section /// 3]. /// /// Note that while this address is the most commonly used address for /// loopback traffic, any address in the [`LOOPBACK_SUBNET`] may be used. /// /// [RFC 5735 Section 3]: https://datatracker.ietf.org/doc/html/rfc5735#section-3 /// [`LOOPBACK_SUBNET`]: Ipv4::LOOPBACK_SUBNET const LOOPBACK_ADDRESS: SpecifiedAddr<Ipv4Addr> = unsafe { SpecifiedAddr::new_unchecked(Ipv4Addr::new([127, 0, 0, 1])) }; /// The IPv4 loopback subnet, defined in [RFC 1122 Section 3.2.1.3]. /// /// [RFC 1122 Section 3.2.1.3]: https://www.rfc-editor.org/rfc/rfc1122.html#section-3.2.1.3 const LOOPBACK_SUBNET: Subnet<Ipv4Addr> = Subnet { network: Ipv4Addr::new([127, 0, 0, 0]), prefix: 8 }; // TODO(https://fxbug.dev/83331): Document the standard in which this // constant is defined. const MULTICAST_SUBNET: Subnet<Ipv4Addr> = Subnet { network: Ipv4Addr::new([224, 0, 0, 0]), prefix: 4 }; /// The subnet of link-local unicast IPv4 addresses, outlined in [RFC 3927 /// Section 2.1]. /// /// [RFC 3927 Section 2.1]: https://tools.ietf.org/html/rfc3927#section-2.1 const LINK_LOCAL_UNICAST_SUBNET: Subnet<Ipv4Addr> = Subnet { network: Ipv4Addr::new([169, 254, 0, 0]), prefix: 16 }; const NAME: &'static str = "IPv4"; /// The IPv4 minimum link MTU. /// /// Per [RFC 791 Section 3.2], "[\e\]very internet module must be able to /// forward a datagram of 68 octets without further fragmentation." /// /// [RFC 791 Section 3.2]: https://tools.ietf.org/html/rfc791#section-3.2 const MINIMUM_LINK_MTU: u16 = 68; type Addr = Ipv4Addr; } impl Ipv4 { /// The limited broadcast address. /// /// The limited broadcast address is considered to be a broadcast address on /// all networks regardless of subnet address. This is distinct from the /// subnet-specific broadcast address (e.g., 192.168.255.255 on the subnet /// 192.168.0.0/16). It is defined in the [IANA IPv4 Special-Purpose Address /// Registry]. /// /// [IANA IPv4 Special-Purpose Address Registry]: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml pub const LIMITED_BROADCAST_ADDRESS: SpecifiedAddr<Ipv4Addr> = unsafe { SpecifiedAddr::new_unchecked(Ipv4Addr::new([255, 255, 255, 255])) }; /// The Class E subnet. /// /// The Class E subnet is meant for experimental purposes, and should not be /// used on the general internet. [RFC 1812 Section 5.3.7] suggests that /// routers SHOULD discard packets with a source address in the Class E /// subnet. The Class E subnet is defined in [RFC 1112 Section 4]. /// /// [RFC 1812 Section 5.3.7]: https://tools.ietf.org/html/rfc1812#section-5.3.7 /// [RFC 1112 Section 4]: https://datatracker.ietf.org/doc/html/rfc1112#section-4 pub const CLASS_E_SUBNET: Subnet<Ipv4Addr> = Subnet { network: Ipv4Addr::new([240, 0, 0, 0]), prefix: 4 }; /// The subnet of link-local multicast addresses, outlined in [RFC 5771 /// Section 4]. /// /// [RFC 5771 Section 4]: https://tools.ietf.org/html/rfc5771#section-4 pub const LINK_LOCAL_MULTICAST_SUBNET: Subnet<Ipv4Addr> = Subnet { network: Ipv4Addr::new([169, 254, 0, 0]), prefix: 16 }; /// The multicast address subscribed to by all routers on the local network, /// defined in the [IPv4 Multicast Address Space Registry]. /// /// [IPv4 Multicast Address Space Registry]: https://www.iana.org/assignments/multicast-addresses/multicast-addresses.xhtml pub const ALL_ROUTERS_MULTICAST_ADDRESS: MulticastAddr<Ipv4Addr> = unsafe { MulticastAddr::new_unchecked(Ipv4Addr::new([224, 0, 0, 2])) }; } /// IPv6. /// /// `Ipv6` implements [`Ip`] for IPv6. /// /// Note that this type has no value constructor. It is used purely at the type /// level. Attempting to construct it by calling `Default::default` will panic. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum Ipv6 {} impl Default for Ipv6 { fn default() -> Ipv6 { panic!("Ipv6 default") } } impl sealed::Sealed for Ipv6 {} impl Ip for Ipv6 { const VERSION: IpVersion = IpVersion::V6; /// The unspecified IPv6 address, defined in [RFC 4291 Section 2.5.2]. /// /// Per RFC 4291: /// /// > The address 0:0:0:0:0:0:0:0 is called the unspecified address. It /// > must never be assigned to any node. It indicates the absence of an /// > address. One example of its use is in the Source Address field of any /// > IPv6 packets sent by an initializing host before it has learned its /// > own address. /// > /// > The unspecified address must not be used as the destination address of /// > IPv6 packets or in IPv6 Routing headers. An IPv6 packet with a source /// > address of unspecified must never be forwarded by an IPv6 router. /// /// [RFC 4291 Section 2.5.2]: https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.2 const UNSPECIFIED_ADDRESS: Ipv6Addr = Ipv6Addr::new([0; 8]); /// The loopback IPv6 address, defined in [RFC 4291 Section 2.5.3]. /// /// Per RFC 4291: /// /// > The unicast address 0:0:0:0:0:0:0:1 is called the loopback address. /// > It may be used by a node to send an IPv6 packet to itself. It must /// > not be assigned to any physical interface. It is treated as having /// > Link-Local scope, and may be thought of as the Link-Local unicast /// > address of a virtual interface (typically called the "loopback /// > interface") to an imaginary link that goes nowhere. /// > /// > The loopback address must not be used as the source address in IPv6 /// > packets that are sent outside of a single node. An IPv6 packet with /// > a destination address of loopback must never be sent outside of a /// > single node and must never be forwarded by an IPv6 router. A packet /// > received on an interface with a destination address of loopback must /// > be dropped. /// /// [RFC 4291 Section 2.5.3]: https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.3 const LOOPBACK_ADDRESS: SpecifiedAddr<Ipv6Addr> = unsafe { SpecifiedAddr::new_unchecked(Ipv6Addr::new([0, 0, 0, 0, 0, 0, 0, 1])) }; /// The subnet of loopback IPv6 addresses, defined in [RFC 4291 Section 2.4]. /// /// Note that the IPv6 loopback subnet is a /128, meaning that it contains /// only one address - the [`LOOPBACK_ADDRESS`]. /// /// [RFC 4291 Section 2.4]: https://datatracker.ietf.org/doc/html/rfc4291#section-2.4 /// [`LOOPBACK_ADDRESS`]: Ipv6::LOOPBACK_ADDRESS const LOOPBACK_SUBNET: Subnet<Ipv6Addr> = Subnet { network: Ipv6Addr::new([0, 0, 0, 0, 0, 0, 0, 1]), prefix: 128 }; /// The subnet of multicast IPv6 addresses, defined in [RFC 4291 Section /// 2.7]. /// /// [RFC 4291 Section 2.7]: https://datatracker.ietf.org/doc/html/rfc4291#section-2.7 const MULTICAST_SUBNET: Subnet<Ipv6Addr> = Subnet { network: Ipv6Addr::new([0xff00, 0, 0, 0, 0, 0, 0, 0]), prefix: 8 }; /// The subnet of link-local unicast addresses, defined in [RFC 4291 Section /// 2.4]. /// /// Note that multicast addresses can also be link-local. However, there is /// no single subnet of link-local multicast addresses. For more details on /// link-local multicast addresses, see [RFC 4291 Section 2.7]. /// /// [RFC 4291 Section 2.4]: https://tools.ietf.org/html/rfc4291#section-2.4 /// [RFC 4291 Section 2.7]: https://tools.ietf.org/html/rfc4291#section-2.7 const LINK_LOCAL_UNICAST_SUBNET: Subnet<Ipv6Addr> = Subnet { network: Ipv6Addr::new([0xfe80, 0, 0, 0, 0, 0, 0, 0]), prefix: 10 }; const NAME: &'static str = "IPv6"; /// The IPv6 minimum link MTU, defined in [RFC 8200 Section 5]. /// /// Per RFC 8200: /// /// > IPv6 requires that every link in the Internet have an MTU of 1280 /// > octets or greater. This is known as the IPv6 minimum link MTU. On any /// > link that cannot convey a 1280-octet packet in one piece, link- /// > specific fragmentation and reassembly must be provided at a layer /// > below IPv6. /// /// [RFC 8200 Section 5]: https://tools.ietf.org/html/rfc8200#section-5 const MINIMUM_LINK_MTU: u16 = 1280; type Addr = Ipv6Addr; } impl Ipv6 { /// The loopback address represented as a [`UnicastAddr`]. /// /// This is equivalent to [`LOOPBACK_ADDRESS`], except that it is a /// [`UnicastAddr`] witness type. /// /// [`LOOPBACK_ADDRESS`]: Ipv6::LOOPBACK_ADDRESS pub const LOOPBACK_IPV6_ADDRESS: UnicastAddr<Ipv6Addr> = unsafe { UnicastAddr::new_unchecked(Ipv6::LOOPBACK_ADDRESS.0) }; /// The IPv6 All Nodes multicast address in link-local scope, defined in /// [RFC 4291 Section 2.7.1]. /// /// [RFC 4291 Section 2.7.1]: https://tools.ietf.org/html/rfc4291#section-2.7.1 pub const ALL_NODES_LINK_LOCAL_MULTICAST_ADDRESS: MulticastAddr<Ipv6Addr> = unsafe { MulticastAddr::new_unchecked(Ipv6Addr::new([0xff02, 0, 0, 0, 0, 0, 0, 1])) }; /// The IPv6 All Routers multicast address in link-local scope, defined in /// [RFC 4291 Section 2.7.1]. /// /// [RFC 4291 Section 2.7.1]: https://tools.ietf.org/html/rfc4291#section-2.7.1 pub const ALL_ROUTERS_LINK_LOCAL_MULTICAST_ADDRESS: MulticastAddr<Ipv6Addr> = unsafe { MulticastAddr::new_unchecked(Ipv6Addr::new([0xff02, 0, 0, 0, 0, 0, 0, 2])) }; /// The (deprecated) subnet of site-local unicast addresses, defined in [RFC /// 3513 Section 2.5.6]. /// /// The site-local unicast subnet was deprecated in [RFC 3879]: /// /// > The special behavior of this prefix MUST no longer be supported in new /// > implementations. The prefix MUST NOT be reassigned for other use /// > except by a future IETF standards action... However, router /// > implementations SHOULD be configured to prevent routing of this prefix /// > by default. /// /// [RFC 3513 Section 2.5.6]: https://tools.ietf.org/html/rfc3513#section-2.5.6 /// [RFC 3879]: https://tools.ietf.org/html/rfc3879 pub const SITE_LOCAL_UNICAST_SUBNET: Subnet<Ipv6Addr> = Subnet { network: Ipv6Addr::new([0xfec0, 0, 0, 0, 0, 0, 0, 0]), prefix: 10 }; /// The length, in bits, of the interface identifier portion of unicast IPv6 /// addresses *except* for addresses which start with the binary value 000. /// /// According to [RFC 4291 Section 2.5.1], "\[f\]or all unicast addresses, /// except those that start with the binary value 000, Interface IDs are /// required to be 64 bits." /// /// Note that, per [RFC 4862 Section 5.5.3]: /// /// > a future revision of the address architecture \[RFC4291\] and a future /// > link-type-specific document, which will still be consistent with each /// > other, could potentially allow for an interface identifier of length /// > other than the value defined in the current documents. Thus, an /// > implementation should not assume a particular constant. Rather, it /// > should expect any lengths of interface identifiers. /// /// In other words, this constant may be used to generate addresses or /// subnet prefix lengths, but should *not* be used to validate addresses or /// subnet prefix lengths generated by other software or other machines, as /// it might be valid for other software or other machines to use an /// interface identifier length different from this one. /// /// [RFC 4291 Section 2.5.1]: https://tools.ietf.org/html/rfc4291#section-2.5.1 /// [RFC 4862 Section 5.5.3]: https://tools.ietf.org/html/rfc4862#section-5.5.3 pub const UNICAST_INTERFACE_IDENTIFIER_BITS: u8 = 64; /// The length, in bits, of an IPv6 flow label, defined in [RFC 6437 Section 2]. /// /// [RFC 6437 Section 2]: https://tools.ietf.org/html/rfc6437#section-2 pub const FLOW_LABEL_BITS: u8 = 20; } /// An IPv4 or IPv6 address. /// /// `IpAddress` is implemented by [`Ipv4Addr`] and [`Ipv6Addr`]. It is sealed, /// and there are guaranteed to be no other implementors besides these. Code - /// including unsafe code - may rely on this assumption for its correctness and /// soundness. pub trait IpAddress: Sized + Eq + PartialEq + Hash + Copy + Display + Debug + Default + Sync + Send + LinkLocalAddress + ScopeableAddress + sealed::Sealed + 'static { /// The number of bytes in an address of this type. /// /// 4 for IPv4 and 16 for IPv6. const BYTES: u8; /// The IP version type of this address. /// /// [`Ipv4`] for [`Ipv4Addr`] and [`Ipv6`] for [`Ipv6Addr`]. type Version: Ip<Addr = Self>; /// Gets the underlying bytes of the address. fn bytes(&self) -> &[u8]; /// Masks off the top bits of the address. /// /// Returns a copy of `self` where all but the top `bits` bits are set to /// 0. /// /// # Panics /// /// `mask` panics if `bits` is out of range - if it is greater than 32 for /// IPv4 or greater than 128 for IPv6. fn mask(&self, bits: u8) -> Self; /// Converts a statically-typed IP address into a dynamically-typed one. fn to_ip_addr(&self) -> IpAddr; /// Is this a loopback address? /// /// `is_loopback` returns `true` if this address is a member of the /// [`LOOPBACK_SUBNET`]. /// /// [`LOOPBACK_SUBNET`]: Ip::LOOPBACK_SUBNET #[inline] fn is_loopback(&self) -> bool { Self::Version::LOOPBACK_SUBNET.contains(self) } /// Calculates the common prefix length between this address and `other`. fn common_prefix_len(&self, other: &Self) -> u8; /// Is this a unicast address contained in the given subnet? /// /// `is_unicast_in_subnet` returns `true` if the given subnet contains this /// address and the address is none of: /// - a multicast address /// - the IPv4 limited broadcast address /// - the IPv4 subnet-specific broadcast address for the given subnet /// - an IPv4 address whose host bits (those bits following the network /// prefix) are all 0 /// - the unspecified address /// - an IPv4 Class E address /// /// Note two exceptions to these rules: If `subnet` is an IPv4 /32, then the /// single unicast address in the subnet is also technically the subnet /// broadcast address. If `subnet` is an IPv4 /31, then both addresses in /// that subnet are broadcast addresses. In either case, the "no /// subnet-specific broadcast" and "no address with a host part of all /// zeroes" rules don't apply. Note further that this exception *doesn't* /// apply to the unspecified address, which is never considered a unicast /// address regardless of what subnet it's in. /// /// # RFC Deep Dive /// /// ## IPv4 addresses ending in zeroes /// /// In this section, we justify the rule that IPv4 addresses whose host bits /// are all 0 are not considered unicast addresses. /// /// In earlier standards, an IPv4 address whose bits were all 0 after the /// network prefix (e.g., 192.168.0.0 in the subnet 192.168.0.0/16) were a /// form of "network-prefix-directed" broadcast addresses. Similarly, /// 0.0.0.0 was considered a form of "limited broadcast address" (equivalent /// to 255.255.255.255). These have since been deprecated (in the case of /// 0.0.0.0, it is now considered the "unspecified" address). /// /// As evidence that this deprecation is official, consider [RFC 1812 /// Section 5.3.5]. In reference to these types of addresses, it states that /// "packets addressed to any of these addresses SHOULD be silently /// discarded \[by routers\]". This not only deprecates them as broadcast /// addresses, but also as unicast addresses (after all, unicast addresses /// are not particularly useful if packets destined to them are discarded by /// routers). /// /// ## IPv4 /31 and /32 exceptions /// /// In this section, we justify the exceptions that all addresses in IPv4 /// /31 and /32 subnets are considered unicast. /// /// For /31 subnets, the case is easy. [RFC 3021 Section 2.1] states that /// both addresses in a /31 subnet "MUST be interpreted as host addresses." /// /// For /32, the case is a bit more vague. RFC 3021 makes no mention of /32 /// subnets. However, the same reasoning applies - if an exception is not /// made, then there do not exist any host addresses in a /32 subnet. [RFC /// 4632 Section 3.1] also vaguely implies this interpretation by referring /// to addresses in /32 subnets as "host routes." /// /// [RFC 1812 Section 5.3.5]: https://tools.ietf.org/html/rfc1812#page-92 /// [RFC 4632 Section 3.1]: https://tools.ietf.org/html/rfc4632#section-3.1 fn is_unicast_in_subnet(&self, subnet: &Subnet<Self>) -> bool; // Functions used to implement internal types. These functions aren't // particularly useful to users, but allow us to implement certain // specialization-like behavior without actually relying on the unstable // `specialization` feature. #[doc(hidden)] fn subnet_into_either(subnet: Subnet<Self>) -> SubnetEither; } impl<A: IpAddress> SpecifiedAddress for A { /// Is this an address other than the unspecified address? /// /// `is_specified` returns true if `self` is not equal to /// [`A::Version::UNSPECIFIED_ADDRESS`]. /// /// [`A::Version::UNSPECIFIED_ADDRESS`]: Ip::UNSPECIFIED_ADDRESS #[inline] fn is_specified(&self) -> bool { self != &A::Version::UNSPECIFIED_ADDRESS } } /// Maps a method over an `IpAddr`, calling it after matching on the type of IP /// address. macro_rules! map_ip_addr { ($val:expr, $method:ident) => { match $val { IpAddr::V4(a) => a.$method(), IpAddr::V6(a) => a.$method(), } }; } impl SpecifiedAddress for IpAddr { /// Is this an address other than the unspecified address? /// /// `is_specified` returns true if `self` is not equal to /// [`Ip::UNSPECIFIED_ADDRESS`] for the IP version of this address. #[inline] fn is_specified(&self) -> bool { map_ip_addr!(self, is_specified) } } impl<A: IpAddress> MulticastAddress for A { /// Is this address in the multicast subnet? /// /// `is_multicast` returns true if `self` is in /// [`A::Version::MULTICAST_SUBNET`]. /// /// [`A::Version::MULTICAST_SUBNET`]: Ip::MULTICAST_SUBNET #[inline] fn is_multicast(&self) -> bool { <A as IpAddress>::Version::MULTICAST_SUBNET.contains(self) } } impl MulticastAddress for IpAddr { /// Is this an address in the multicast subnet? /// /// `is_multicast` returns true if `self` is in [`Ip::MULTICAST_SUBNET`] for /// the IP version of this address. #[inline] fn is_multicast(&self) -> bool { map_ip_addr!(self, is_multicast) } } impl LinkLocalAddress for Ipv4Addr { /// Is this address in the link-local subnet? /// /// `is_link_local` returns true if `self` is in /// [`Ipv4::LINK_LOCAL_UNICAST_SUBNET`] or /// [`Ipv4::LINK_LOCAL_MULTICAST_SUBNET`]. #[inline] fn is_link_local(&self) -> bool { Ipv4::LINK_LOCAL_UNICAST_SUBNET.contains(self) || Ipv4::LINK_LOCAL_MULTICAST_SUBNET.contains(self) } } impl LinkLocalAddress for Ipv6Addr { /// Is this address in the link-local subnet? /// /// `is_link_local` returns true if `self` is in /// [`Ipv6::LINK_LOCAL_UNICAST_SUBNET`], is a multicast address whose scope /// is link-local, or is the address [`Ipv6::LOOPBACK_ADDRESS`] (per [RFC /// 4291 Section 2.5.3], the loopback address is considered to have /// link-local scope). /// /// [RFC 4291 Section 2.5.3]: https://tools.ietf.org/html/rfc4291#section-2.5.3 #[inline] fn is_link_local(&self) -> bool { Ipv6::LINK_LOCAL_UNICAST_SUBNET.contains(self) || (self.is_multicast() && self.scope() == Ipv6Scope::LinkLocal) || self == Ipv6::LOOPBACK_ADDRESS.deref() } } impl LinkLocalAddress for IpAddr { /// Is this address link-local? #[inline] fn is_link_local(&self) -> bool { map_ip_addr!(self, is_link_local) } } impl ScopeableAddress for Ipv4Addr { type Scope = (); /// The scope of this address. /// /// Although IPv4 defines a link local subnet, IPv4 addresses are always /// considered to be in the global scope. fn scope(&self) {} } /// The list of IPv6 scopes. /// /// These scopes are defined by [RFC 4291 Section 2.7]. /// /// [RFC 4291 Section 2.7]: https://tools.ietf.org/html/rfc4291#section-2.7 #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Ipv6Scope { /// The interface-local scope. InterfaceLocal, /// The link-local scope. LinkLocal, /// The admin-local scope. AdminLocal, /// The (deprecated) site-local scope. /// /// The site-local scope was deprecated in [RFC 3879]. While this scope /// is returned for both site-local unicast and site-local multicast /// addresses, RFC 3879 says the following about site-local unicast addresses /// in particular ("this prefix" refers to the [site-local unicast subnet]): /// /// > The special behavior of this prefix MUST no longer be supported in new /// > implementations. The prefix MUST NOT be reassigned for other use /// > except by a future IETF standards action... However, router /// > implementations SHOULD be configured to prevent routing of this prefix /// > by default. /// /// [RFC 3879]: https://tools.ietf.org/html/rfc3879 /// [site-local unicast subnet]: Ipv6::SITE_LOCAL_UNICAST_SUBNET SiteLocal, /// The organization-local scope. OrganizationLocal, /// The global scope. Global, /// Scopes which are reserved for future use by [RFC 4291 Section 2.7]. /// /// [RFC 4291 Section 2.7]: https://tools.ietf.org/html/rfc4291#section-2.7 Reserved(Ipv6ReservedScope), /// Scopes which are available for local definition by administrators. Unassigned(Ipv6UnassignedScope), } /// The list of IPv6 scopes which are reserved for future use by [RFC 4291 /// Section 2.7]. /// /// [RFC 4291 Section 2.7]: https://tools.ietf.org/html/rfc4291#section-2.7 #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Ipv6ReservedScope { /// The scope with numerical value 0. Scope0 = 0, /// The scope with numerical value 3. Scope3 = 3, /// The scope with numerical value 0xF. ScopeF = 0xF, } /// The list of IPv6 scopes which are available for local definition by /// administrators. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Ipv6UnassignedScope { /// The scope with numerical value 6. Scope6 = 6, /// The scope with numerical value 7. Scope7 = 7, /// The scope with numerical value 9. Scope9 = 9, /// The scope with numerical value 0xA. ScopeA = 0xA, /// The scope with numerical value 0xB. ScopeB = 0xB, /// The scope with numerical value 0xC. ScopeC = 0xC, /// The scope with numerical value 0xD. ScopeD = 0xD, } impl Scope for Ipv6Scope { #[inline] fn can_have_zone(&self) -> bool { // Per RFC 6874 Section 4: // // > [I]mplementations MUST NOT allow use of this format except for // > well-defined usages, such as sending to link-local addresses under // > prefix fe80::/10. At the time of writing, this is the only // > well-defined usage known. // // While this directive applies particularly to the human-readable // string representation of IPv6 addresses and zone identifiers, it // seems reasonable to limit the in-memory representation in the same // way. // // Note that, if interpreted literally, this quote would bar the use of // zone identifiers on link-local multicast addresses (they are not // under the prefix fe80::/10). However, it seems clear that this is not // the interpretation that was intended. Link-local multicast addresses // have the same need for a zone identifier as link-local unicast // addresses, and indeed, real systems like Linux allow link-local // multicast addresses to be accompanied by zone identifiers. matches!(self, Ipv6Scope::LinkLocal) } } impl Ipv6Scope { /// The multicast scope ID of an interface-local address, defined in [RFC /// 4291 Section 2.7]. /// /// [RFC 4291 Section 2.7]: https://tools.ietf.org/html/rfc4291#section-2.7 pub const MULTICAST_SCOPE_ID_INTERFACE_LOCAL: u8 = 1; /// The multicast scope ID of a link-local address, defined in [RFC 4291 /// Section 2.7]. /// /// [RFC 4291 Section 2.7]: https://tools.ietf.org/html/rfc4291#section-2.7 pub const MULTICAST_SCOPE_ID_LINK_LOCAL: u8 = 2; /// The multicast scope ID of an admin-local address, defined in [RFC 4291 /// Section 2.7]. /// /// [RFC 4291 Section 2.7]: https://tools.ietf.org/html/rfc4291#section-2.7 pub const MULTICAST_SCOPE_ID_ADMIN_LOCAL: u8 = 4; /// The multicast scope ID of a (deprecated) site-local address, defined in /// [RFC 4291 Section 2.7]. /// /// Note that site-local addresses are deprecated. /// /// [RFC 4291 Section 2.7]: https://tools.ietf.org/html/rfc4291#section-2.7 pub const MULTICAST_SCOPE_ID_SITE_LOCAL: u8 = 5; /// The multicast scope ID of an organization-local address, defined in [RFC /// 4291 Section 2.7]. /// /// [RFC 4291 Section 2.7]: https://tools.ietf.org/html/rfc4291#section-2.7 pub const MULTICAST_SCOPE_ID_ORG_LOCAL: u8 = 8; /// The multicast scope ID of global address, defined in [RFC 4291 Section /// 2.7]. /// /// [RFC 4291 Section 2.7]: https://tools.ietf.org/html/rfc4291#section-2.7 pub const MULTICAST_SCOPE_ID_GLOBAL: u8 = 0xE; /// The ID used to indicate this scope in a multicast IPv6 address. /// /// Per [RFC 4291 Section 2.7], the bits of a multicast IPv6 address are /// laid out as follows: /// /// ```text /// | 8 | 4 | 4 | 112 bits | /// +------ -+----+----+---------------------------------------------+ /// |11111111|flgs|scop| group ID | /// +--------+----+----+---------------------------------------------+ /// ``` /// /// The 4-bit scop field encodes the scope of the address. /// `multicast_scope_id` returns the numerical value used to encode this /// scope in the scop field of a multicast address. /// /// [RFC 4291 Section 2.7]: https://tools.ietf.org/html/rfc4291#section-2.7 pub fn multicast_scope_id(&self) -> u8 { match self { Ipv6Scope::Reserved(Ipv6ReservedScope::Scope0) => 0, Ipv6Scope::InterfaceLocal => Self::MULTICAST_SCOPE_ID_INTERFACE_LOCAL, Ipv6Scope::LinkLocal => Self::MULTICAST_SCOPE_ID_LINK_LOCAL, Ipv6Scope::Reserved(Ipv6ReservedScope::Scope3) => 3, Ipv6Scope::AdminLocal => Self::MULTICAST_SCOPE_ID_ADMIN_LOCAL, Ipv6Scope::SiteLocal => Self::MULTICAST_SCOPE_ID_SITE_LOCAL, Ipv6Scope::Unassigned(Ipv6UnassignedScope::Scope6) => 6, Ipv6Scope::Unassigned(Ipv6UnassignedScope::Scope7) => 7, Ipv6Scope::OrganizationLocal => Self::MULTICAST_SCOPE_ID_ORG_LOCAL, Ipv6Scope::Unassigned(Ipv6UnassignedScope::Scope9) => 9, Ipv6Scope::Unassigned(Ipv6UnassignedScope::ScopeA) => 0xA, Ipv6Scope::Unassigned(Ipv6UnassignedScope::ScopeB) => 0xB, Ipv6Scope::Unassigned(Ipv6UnassignedScope::ScopeC) => 0xC, Ipv6Scope::Unassigned(Ipv6UnassignedScope::ScopeD) => 0xD, Ipv6Scope::Global => Self::MULTICAST_SCOPE_ID_GLOBAL, Ipv6Scope::Reserved(Ipv6ReservedScope::ScopeF) => 0xF, } } } impl ScopeableAddress for Ipv6Addr { type Scope = Ipv6Scope; /// The scope of this address. #[inline] fn scope(&self) -> Ipv6Scope { if self.is_multicast() { use Ipv6ReservedScope::*; use Ipv6Scope::*; use Ipv6UnassignedScope::*; // The "scop" field of a multicast address is the last 4 bits of the // second byte of the address (see // https://tools.ietf.org/html/rfc4291#section-2.7). match self.0[1] & 0xF { 0 => Reserved(Scope0), Ipv6Scope::MULTICAST_SCOPE_ID_INTERFACE_LOCAL => InterfaceLocal, Ipv6Scope::MULTICAST_SCOPE_ID_LINK_LOCAL => LinkLocal, 3 => Reserved(Scope3), Ipv6Scope::MULTICAST_SCOPE_ID_ADMIN_LOCAL => AdminLocal, Ipv6Scope::MULTICAST_SCOPE_ID_SITE_LOCAL => SiteLocal, 6 => Unassigned(Scope6), 7 => Unassigned(Scope7), Ipv6Scope::MULTICAST_SCOPE_ID_ORG_LOCAL => OrganizationLocal, 9 => Unassigned(Scope9), 0xA => Unassigned(ScopeA), 0xB => Unassigned(ScopeB), 0xC => Unassigned(ScopeC), 0xD => Unassigned(ScopeD), Ipv6Scope::MULTICAST_SCOPE_ID_GLOBAL => Global, 0xF => Reserved(ScopeF), _ => unreachable!(), } } else if self.is_link_local() { Ipv6Scope::LinkLocal } else if self.is_site_local() { Ipv6Scope::SiteLocal } else { Ipv6Scope::Global } } } impl Scope for IpAddr<(), Ipv6Scope> { #[inline] fn can_have_zone(&self) -> bool { match self { IpAddr::V4(scope) => scope.can_have_zone(), IpAddr::V6(scope) => scope.can_have_zone(), } } } impl ScopeableAddress for IpAddr { type Scope = IpAddr<(), Ipv6Scope>; #[inline] fn scope(&self) -> IpAddr<(), Ipv6Scope> { match self { IpAddr::V4(_) => IpAddr::V4(()), IpAddr::V6(addr) => IpAddr::V6(addr.scope()), } } } // The definition of each trait for `IpAddr` is equal to the definition of that // trait for whichever of `Ipv4Addr` and `Ipv6Addr` is actually present in the // enum. Thus, we can convert between `$witness<IpvXAddr>`, `$witness<IpAddr>`, // and `IpAddr<$witness<Ipv4Addr>, $witness<Ipv6Addr>>` arbitrarily. /// Provides various useful `From` impls for an IP address witness type. /// /// `impl_from_witness!($witness)` implements: /// - `From<IpAddr<$witness<Ipv4Addr>, $witness<Ipv6Addr>>> for /// $witness<IpAddr>` /// - `From<$witness<IpAddr>> for IpAddr<$witness<Ipv4Addr>, /// $witness<Ipv6Addr>>` /// - `From<$witness<Ipv4Addr>> for $witness<IpAddr>` /// - `From<$witness<Ipv6Addr>> for $witness<IpAddr>` /// - `From<$witness<Ipv4Addr>> for IpAddr` /// - `From<$witness<Ipv6Addr>> for IpAddr` /// - `TryFrom<Ipv4Addr> for $witness<Ipv4Addr>` /// - `TryFrom<Ipv6Addr> for $witness<Ipv6Addr>` /// /// `impl_from_witness!($witness, $ipaddr, $new_unchecked)` implements: /// - `From<$witness<$ipaddr>> for $witness<IpAddr>` /// - `From<$witness<$ipaddr>> for $ipaddr` /// - `TryFrom<$ipaddr> for $witness<$ipaddr>` macro_rules! impl_from_witness { ($witness:ident) => { impl_from_witness!($witness, Ipv4Addr, Witness::new_unchecked); impl_from_witness!($witness, Ipv6Addr, Witness::new_unchecked); impl From<IpAddr<$witness<Ipv4Addr>, $witness<Ipv6Addr>>> for $witness<IpAddr> { fn from(addr: IpAddr<$witness<Ipv4Addr>, $witness<Ipv6Addr>>) -> $witness<IpAddr> { unsafe { Witness::new_unchecked(match addr { IpAddr::V4(addr) => IpAddr::V4(addr.get()), IpAddr::V6(addr) => IpAddr::V6(addr.get()), }) } } } impl From<$witness<IpAddr>> for IpAddr<$witness<Ipv4Addr>, $witness<Ipv6Addr>> { fn from(addr: $witness<IpAddr>) -> IpAddr<$witness<Ipv4Addr>, $witness<Ipv6Addr>> { unsafe { match addr.get() { IpAddr::V4(addr) => IpAddr::V4(Witness::new_unchecked(addr)), IpAddr::V6(addr) => IpAddr::V6(Witness::new_unchecked(addr)), } } } } }; ($witness:ident, $ipaddr:ident, $new_unchecked:expr) => { impl From<$witness<$ipaddr>> for $witness<IpAddr> { fn from(addr: $witness<$ipaddr>) -> $witness<IpAddr> { let addr: $ipaddr = addr.get(); let addr: IpAddr = addr.into(); #[allow(unused_unsafe)] // For when a closure is passed unsafe { $new_unchecked(addr) } } } impl From<$witness<$ipaddr>> for $ipaddr { fn from(addr: $witness<$ipaddr>) -> $ipaddr { addr.get() } } impl TryFrom<$ipaddr> for $witness<$ipaddr> { type Error = (); fn try_from(addr: $ipaddr) -> Result<$witness<$ipaddr>, ()> { Witness::new(addr).ok_or(()) } } }; } impl_from_witness!(SpecifiedAddr); impl_from_witness!(MulticastAddr); impl_from_witness!(LinkLocalAddr); impl_from_witness!(LinkLocalMulticastAddr); impl_from_witness!(UnicastAddr, Ipv6Addr, UnicastAddr::new_unchecked); impl_from_witness!(LinkLocalUnicastAddr, Ipv6Addr, |addr| LinkLocalAddr(UnicastAddr(addr))); /// An IPv4 address. /// /// # Layout /// /// `Ipv4Addr` has the same layout as `[u8; 4]`, which is the layout that most /// protocols use to represent an IPv4 address in their packet formats. This can /// be useful when parsing an IPv4 address from a packet. For example: /// /// ```rust /// # use net_types::ip::Ipv4Addr; /// /// An ICMPv4 Redirect Message header. /// /// /// /// `Icmpv4RedirectHeader` has the same layout as the header of an ICMPv4 /// /// Redirect Message. /// #[repr(C)] /// struct Icmpv4RedirectHeader { /// typ: u8, /// code: u8, /// checksum: [u8; 2], /// gateway: Ipv4Addr, /// } /// ``` #[derive(Copy, Clone, Default, PartialEq, Eq, Hash, FromBytes, AsBytes, Unaligned)] #[repr(transparent)] pub struct Ipv4Addr([u8; 4]); impl Ipv4Addr { /// Creates a new IPv4 address. #[inline] pub const fn new(bytes: [u8; 4]) -> Self { Ipv4Addr(bytes) } /// Gets the bytes of the IPv4 address. #[inline] pub const fn ipv4_bytes(self) -> [u8; 4] { self.0 } /// Is this the limited broadcast address? /// /// `is_limited_broadcast` is a shorthand for comparing against /// [`Ipv4::LIMITED_BROADCAST_ADDRESS`]. #[inline] pub fn is_limited_broadcast(self) -> bool { self == Ipv4::LIMITED_BROADCAST_ADDRESS.get() } /// Is this a Class E address? /// /// `is_class_e` is a shorthand for checking membership in /// [`Ipv4::CLASS_E_SUBNET`]. #[inline] pub fn is_class_e(self) -> bool { Ipv4::CLASS_E_SUBNET.contains(&self) } /// Converts the address to an IPv4-compatible IPv6 address according to /// [RFC 4291 Section 2.5.5.1]. /// /// IPv4-compatible IPv6 addresses were defined to assist in the IPv6 /// transition, and are now specified in [RFC 4291 Section 2.5.5.1]. The /// lowest-order 32 bits carry an IPv4 address, while the highest-order 96 /// bits are all set to 0 as in this diagram from the RFC: /// /// ```text /// | 80 bits | 16 | 32 bits | /// +--------------------------------------+--------------------------+ /// |0000..............................0000|0000| IPv4 address | /// +--------------------------------------+----+---------------------+ /// ``` /// /// Per RFC 4291: /// /// > The 'IPv4-Compatible IPv6 address' is now deprecated because the /// > current IPv6 transition mechanisms no longer use these addresses. New /// > or updated implementations are not required to support this address /// > type. /// /// The more modern embedding format is IPv4-mapped IPv6 addressing - see /// [`to_ipv6_mapped`]. /// /// [RFC 4291 Section 2.5.5.1]: https://tools.ietf.org/html/rfc4291#section-2.5.5.1 /// [`to_ipv6_mapped`]: Ipv4Addr::to_ipv6_mapped #[inline] pub fn to_ipv6_compatible(self) -> Ipv6Addr { let Self([a, b, c, d]) = self; Ipv6Addr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a, b, c, d]) } /// Converts the address to an IPv4-mapped IPv6 address according to [RFC /// 4291 Section 2.5.5.2]. /// /// IPv4-mapped IPv6 addresses are used to represent the addresses of IPv4 /// nodes as IPv6 addresses, and are defined in [RFC 4291 Section 2.5.5.2]. /// The lowest-order 32 bits carry an IPv4 address, the middle order 16 bits /// carry the literal 0xFFFF, and the highest order 80 bits are set to 0 as /// in this diagram from the RFC: /// /// ```text /// | 80 bits | 16 | 32 bits | /// +--------------------------------------+--------------------------+ /// |0000..............................0000|FFFF| IPv4 address | /// +--------------------------------------+----+---------------------+ /// ``` /// /// [RFC 4291 Section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2 #[inline] pub fn to_ipv6_mapped(self) -> Ipv6Addr { let Self([a, b, c, d]) = self; Ipv6Addr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, a, b, c, d]) } } impl sealed::Sealed for Ipv4Addr {} impl IpAddress for Ipv4Addr { const BYTES: u8 = 4; type Version = Ipv4; #[inline] fn mask(&self, bits: u8) -> Self { assert!(bits <= 32); if bits == 0 { // shifting left by the size of the value is undefined Ipv4Addr([0; 4]) } else { let mask = <u32>::max_value() << (32 - bits); Self::new((u32::from_be_bytes(self.0) & mask).to_be_bytes()) } } #[inline] fn bytes(&self) -> &[u8] { &self.0 } #[inline] fn to_ip_addr(&self) -> IpAddr { IpAddr::V4(*self) } #[inline] fn common_prefix_len(&self, other: &Ipv4Addr) -> u8 { let me = u32::from_be_bytes(self.0); let other = u32::from_be_bytes(other.0); // `same_bits` has a 0 wherever `me` and `other` have the same bit in a // given position, and a 1 wherever they have opposite bits. let same_bits = me ^ other; same_bits.leading_zeros() as u8 } #[inline] fn is_unicast_in_subnet(&self, subnet: &Subnet<Self>) -> bool { !self.is_multicast() && !self.is_limited_broadcast() // This clause implements the rules that (the subnet broadcast is // not unicast AND the address with an all-zeroes host part is not // unicast) UNLESS the prefix length is 31 or 32. && (subnet.prefix() == 32 || subnet.prefix() == 31 || (*self != subnet.broadcast() && *self != subnet.network())) && self.is_specified() && !self.is_class_e() && subnet.contains(self) } fn subnet_into_either(subnet: Subnet<Ipv4Addr>) -> SubnetEither { SubnetEither::V4(subnet) } } impl From<[u8; 4]> for Ipv4Addr { #[inline] fn from(bytes: [u8; 4]) -> Ipv4Addr { Ipv4Addr(bytes) } } #[cfg(feature = "std")] impl From<net::Ipv4Addr> for Ipv4Addr { #[inline] fn from(ip: net::Ipv4Addr) -> Ipv4Addr { Ipv4Addr::new(ip.octets()) } } #[cfg(feature = "std")] impl From<Ipv4Addr> for net::Ipv4Addr { #[inline] fn from(ip: Ipv4Addr) -> net::Ipv4Addr { net::Ipv4Addr::from(ip.0) } } impl Display for Ipv4Addr { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { write!(f, "{}.{}.{}.{}", self.0[0], self.0[1], self.0[2], self.0[3]) } } impl Debug for Ipv4Addr { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { Display::fmt(self, f) } } /// An IPv6 address. /// /// # Layout /// /// `Ipv6Addr` has the same layout as `[u8; 16]`, which is the layout that most /// protocols use to represent an IPv6 address in their packet formats. This can /// be useful when parsing an IPv6 address from a packet. For example: /// /// ```rust /// # use net_types::ip::Ipv6Addr; /// /// The fixed part of an IPv6 packet header. /// /// /// /// `FixedHeader` has the same layout as the fixed part of an IPv6 packet /// /// header. /// #[repr(C)] /// pub struct FixedHeader { /// version_tc_flowlabel: [u8; 4], /// payload_len: [u8; 2], /// next_hdr: u8, /// hop_limit: u8, /// src_ip: Ipv6Addr, /// dst_ip: Ipv6Addr, /// } /// ``` /// /// # `Display` /// /// The [`Display`] impl for `Ipv6Addr` formats according to [RFC 5952]. /// /// Where RFC 5952 leaves decisions up to the implementation, `Ipv6Addr` matches /// the behavior of [`std::net::Ipv6Addr`] - all IPv6 addresses are formatted /// the same by `Ipv6Addr` as by `<std::net::Ipv6Addr as Display>::fmt`. /// /// [RFC 5952]: https://datatracker.ietf.org/doc/html/rfc5952 #[derive(Copy, Clone, Default, PartialEq, Eq, Hash, FromBytes, AsBytes, Unaligned)] #[repr(transparent)] pub struct Ipv6Addr([u8; 16]); impl Ipv6Addr { /// Creates a new IPv6 address from 16-bit segments. #[inline] pub const fn new(segments: [u16; 8]) -> Ipv6Addr { #![allow(clippy::many_single_char_names)] let [a, b, c, d, e, f, g, h] = segments; let [aa, ab] = a.to_be_bytes(); let [ba, bb] = b.to_be_bytes(); let [ca, cb] = c.to_be_bytes(); let [da, db] = d.to_be_bytes(); let [ea, eb] = e.to_be_bytes(); let [fa, fb] = f.to_be_bytes(); let [ga, gb] = g.to_be_bytes(); let [ha, hb] = h.to_be_bytes(); Ipv6Addr([aa, ab, ba, bb, ca, cb, da, db, ea, eb, fa, fb, ga, gb, ha, hb]) } /// Creates a new IPv6 address from bytes. #[inline] pub const fn from_bytes(bytes: [u8; 16]) -> Ipv6Addr { Ipv6Addr(bytes) } /// Gets the bytes of the IPv6 address. #[inline] pub const fn ipv6_bytes(&self) -> [u8; 16] { self.0 } /// Gets the 16-bit segments of the IPv6 address. #[inline] pub fn segments(&self) -> [u16; 8] { #![allow(clippy::many_single_char_names)] let [a, b, c, d, e, f, g, h]: [zerocopy::U16<zerocopy::NetworkEndian>; 8] = zerocopy::transmute!(self.ipv6_bytes()); [a.into(), b.into(), c.into(), d.into(), e.into(), f.into(), g.into(), h.into()] } /// Converts this `Ipv6Addr` to the IPv6 Solicited-Node Address, used in /// Neighbor Discovery, defined in [RFC 4291 Section 2.7.1]. /// /// [RFC 4291 Section 2.7.1]: https://tools.ietf.org/html/rfc4291#section-2.7.1 #[inline] pub const fn to_solicited_node_address(&self) -> MulticastAddr<Ipv6Addr> { // TODO(brunodalbo) benchmark this generation and evaluate if using // bit operations with u128 could be faster. This is very likely // going to be on a hot path. // We know we are not breaking the guarantee that `MulticastAddr` provides // when calling `new_unchecked` because the address we provide it is // a multicast address as defined by RFC 4291 section 2.7.1. unsafe { MulticastAddr::new_unchecked(Ipv6Addr::from_bytes([ 0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01, 0xff, self.0[13], self.0[14], self.0[15], ])) } } /// Is this a valid unicast address? /// /// A valid unicast address is any unicast address that can be bound to an /// interface (not the unspecified or loopback addresses). /// `addr.is_valid_unicast()` is equivalent to `!(addr.is_loopback() || /// !addr.is_specified() || addr.is_multicast())`. #[inline] pub fn is_valid_unicast(&self) -> bool { !(self.is_loopback() || !self.is_specified() || self.is_multicast()) } /// Is this address in the (deprecated) site-local unicast subnet? /// /// `is_site_local` returns true if `self` is in the (deprecated) /// [`Ipv6::SITE_LOCAL_UNICAST_SUBNET`]. See that constant's documentation /// for more details on deprecation and how the subnet should be used in /// light of deprecation. #[inline] pub fn is_site_local(&self) -> bool { Ipv6::SITE_LOCAL_UNICAST_SUBNET.contains(self) } /// Is this a unicast link-local address? /// /// `addr.is_unicast_link_local()` is equivalent to /// `addr.is_unicast_in_subnet(&Ipv6::LINK_LOCAL_UNICAST_SUBNET)`. #[inline] pub fn is_unicast_link_local(&self) -> bool { self.is_unicast_in_subnet(&Ipv6::LINK_LOCAL_UNICAST_SUBNET) } /// Tries to extract the IPv4 address from an IPv4-compatible IPv6 address. /// /// IPv4-compatible IPv6 addresses were defined to assist in the IPv6 /// transition, and are now specified in [RFC 4291 Section 2.5.5.1]. The /// lowest-order 32 bits carry an IPv4 address, while the highest-order 96 /// bits are all set to 0 as in this diagram from the RFC: /// /// ```text /// | 80 bits | 16 | 32 bits | /// +--------------------------------------+--------------------------+ /// |0000..............................0000|0000| IPv4 address | /// +--------------------------------------+----+---------------------+ /// ``` /// /// `to_ipv4_compatible` checks to see if `self` is an IPv4-compatible /// IPv6 address. If it is, the IPv4 address is extracted and returned. /// /// Per RFC 4291: /// /// > The 'IPv4-Compatible IPv6 address' is now deprecated because the /// > current IPv6 transition mechanisms no longer use these addresses. New /// > or updated implementations are not required to support this address /// > type. /// /// The more modern embedding format is IPv4-mapped IPv6 addressing - see /// [`to_ipv4_mapped`]. /// /// [RFC 4291 Section 2.5.5.1]: https://tools.ietf.org/html/rfc4291#section-2.5.5.1 /// [`to_ipv4_mapped`]: Ipv6Addr::to_ipv4_mapped pub fn to_ipv4_compatible(&self) -> Option<Ipv4Addr> { if let [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a, b, c, d] = self.0 { Some(Ipv4Addr::new([a, b, c, d])) } else { None } } /// Tries to extract the IPv4 address from an IPv4-mapped IPv6 address. /// /// IPv4-mapped IPv6 addresses are used to represent the addresses of IPv4 /// nodes as IPv6 addresses, and are defined in [RFC 4291 Section 2.5.5.2]. /// The lowest-order 32 bits carry an IPv4 address, the middle order 16 bits /// carry the literal 0xFFFF, and the highest order 80 bits are set to 0 as /// in this diagram from the RFC: /// /// ```text /// | 80 bits | 16 | 32 bits | /// +--------------------------------------+--------------------------+ /// |0000..............................0000|FFFF| IPv4 address | /// +--------------------------------------+----+---------------------+ /// ``` /// /// `to_ipv4_mapped` checks to see if `self` is an IPv4-mapped /// IPv6 address. If it is, the IPv4 address is extracted and returned. /// /// [RFC 4291 Section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2 pub fn to_ipv4_mapped(&self) -> Option<Ipv4Addr> { if let [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, a, b, c, d] = self.0 { Some(Ipv4Addr::new([a, b, c, d])) } else { None } } } impl sealed::Sealed for Ipv6Addr {} /// [`Ipv4Addr`] is convertible into [`Ipv6Addr`] through /// [`Ipv4Addr::to_ipv6_mapped`]. impl From<Ipv4Addr> for Ipv6Addr { fn from(addr: Ipv4Addr) -> Ipv6Addr { addr.to_ipv6_mapped() } } impl IpAddress for Ipv6Addr { const BYTES: u8 = 16; type Version = Ipv6; #[inline] fn mask(&self, bits: u8) -> Ipv6Addr { assert!(bits <= 128); if bits == 0 { // shifting left by the size of the value is undefined Ipv6Addr([0; 16]) } else { let mask = <u128>::max_value() << (128 - bits); Ipv6Addr::from((u128::from_be_bytes(self.0) & mask).to_be_bytes()) } } #[inline] fn bytes(&self) -> &[u8] { &self.0 } #[inline] fn to_ip_addr(&self) -> IpAddr { IpAddr::V6(*self) } #[inline] fn common_prefix_len(&self, other: &Ipv6Addr) -> u8 { let me = u128::from_be_bytes(self.0); let other = u128::from_be_bytes(other.0); // `same_bits` has a 0 wherever `me` and `other` have the same bit in a // given position, and a 1 wherever they have opposite bits. let same_bits = me ^ other; same_bits.leading_zeros() as u8 } #[inline] fn is_unicast_in_subnet(&self, subnet: &Subnet<Self>) -> bool { !self.is_multicast() && self.is_specified() && subnet.contains(self) } fn subnet_into_either(subnet: Subnet<Ipv6Addr>) -> SubnetEither { SubnetEither::V6(subnet) } } impl UnicastAddress for Ipv6Addr { /// Is this a unicast address? /// /// `addr.is_unicast()` is equivalent to `!addr.is_multicast() && /// addr.is_specified()`. #[inline] fn is_unicast(&self) -> bool { !self.is_multicast() && self.is_specified() } } impl From<[u8; 16]> for Ipv6Addr { #[inline] fn from(bytes: [u8; 16]) -> Ipv6Addr { Ipv6Addr::from_bytes(bytes) } } #[cfg(feature = "std")] impl From<net::Ipv6Addr> for Ipv6Addr { #[inline] fn from(addr: net::Ipv6Addr) -> Ipv6Addr { Ipv6Addr::from_bytes(addr.octets()) } } #[cfg(feature = "std")] impl From<Ipv6Addr> for net::Ipv6Addr { #[inline] fn from(addr: Ipv6Addr) -> net::Ipv6Addr { net::Ipv6Addr::from(addr.ipv6_bytes()) } } impl Display for Ipv6Addr { /// Formats an IPv6 address according to [RFC 5952]. /// /// Where RFC 5952 leaves decisions up to the implementation, this function /// matches the behavior of [`std::net::Ipv6Addr`] - all IPv6 addresses are /// formatted the same by this function as by `<std::net::Ipv6Addr as /// Display>::fmt`. /// /// [RFC 5952]: https://datatracker.ietf.org/doc/html/rfc5952 #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { // `fmt_inner` implements the core of the formatting algorithm, but does // not handle precision or width requirements. Those are handled below // by creating a scratch buffer, calling `fmt_inner` on that scratch // buffer, and then satisfying those requirements. fn fmt_inner<W: fmt::Write>(addr: &Ipv6Addr, w: &mut W) -> Result<(), fmt::Error> { // We special-case the unspecified and localhost addresses because // both addresses are valid IPv4-compatible addresses, and so if we // don't special case them, they'll get printed as IPv4-compatible // addresses ("::0.0.0.0" and "::0.0.0.1") respectively. if !addr.is_specified() { write!(w, "::") } else if addr.is_loopback() { write!(w, "::1") } else if let Some(v4) = addr.to_ipv4_compatible() { write!(w, "::{}", v4) } else if let Some(v4) = addr.to_ipv4_mapped() { write!(w, "::ffff:{}", v4) } else { let segments = addr.segments(); let longest_zero_span = { let mut longest_zero_span = 0..0; let mut current_zero_span = 0..0; for (i, seg) in segments.iter().enumerate() { if *seg == 0 { current_zero_span.end = i + 1; if current_zero_span.len() > longest_zero_span.len() { longest_zero_span = current_zero_span.clone(); } } else { let next_idx = i + 1; current_zero_span = next_idx..next_idx; } } longest_zero_span }; let write_slice = |w: &mut W, slice: &[u16]| { if let [head, tail @ ..] = slice { write!(w, "{:x}", head)?; for seg in tail { write!(w, ":{:x}", seg)?; } } Ok(()) }; // Note that RFC 5952 gives us a choice of when to compress a // run of zeroes: // // It is possible to select whether or not to omit just one // 16-bit 0 field. // // Given this choice, we opt to match the stdlib's behavior. // This makes it easier to write tests (we can simply check to // see whether our behavior matches `std`'s behavior on a range // of inputs), and makes it so that our `Ipv6Addr` type is, // behaviorally, more of a drop-in for `std::net::Ipv6Addr` than // it would be if we were to diverge on formatting. This makes // replacing `std::net::Ipv6Addr` with our `Ipv6Addr` easier for // clients, and also makes it an easier choice since they don't // have to weigh whether the difference in behavior is // acceptable for them. if longest_zero_span.len() > 1 { write_slice(w, &segments[..longest_zero_span.start])?; w.write_str("::")?; write_slice(w, &segments[longest_zero_span.end..]) } else { write_slice(w, &segments) } } } if f.precision().is_none() && f.width().is_none() { // Fast path: No precision or width requirements, so write directly // to `f`. fmt_inner(self, f) } else { // Slow path: Precision or width requirement(s), so construct a // scratch buffer, use the `fmt_inner` to fill it, then use `f.pad` // to satisfy precision/width requirement(s). // `[u8]` does not implement `core::fmt::Write`, so we provide our // own wrapper which does. struct ByteSlice<'a>(&'a mut [u8]); impl<'a> fmt::Write for ByteSlice<'a> { fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { let from = s.as_bytes(); if from.len() > self.0.len() { return Err(fmt::Error); } // Temporarily replace `self.0` with an empty slice and move // the old value of `self.0` into our scope so that we can // operate on it by value. This allows us to split it in two // (`to` and `remaining`) and then overwrite `self.0` with // `remaining`. let to = mem::replace(&mut self.0, &mut [][..]); let (to, remaining) = to.split_at_mut(from.len()); to.copy_from_slice(from); self.0 = remaining; Ok(()) } } // The maximum length for an IPv6 address displays all 8 pairs of // bytes in hexadecimal representation (4 characters per two bytes // of IPv6 address), each separated with colons (7 colons total). const MAX_DISPLAY_LEN: usize = (4 * 8) + 7; let mut scratch = [0u8; MAX_DISPLAY_LEN]; let mut scratch_slice = ByteSlice(&mut scratch[..]); // `fmt_inner` only returns an error if a method on `w` returns an // error. Since, in this call to `fmt_inner`, `w` is // `scratch_slice`, the only error that could happen would be if we // run out of space, but we know we won't because `scratch_slice` // has `MAX_DISPLAY_LEN` bytes, which is enough to hold any // formatted IPv6 address. fmt_inner(self, &mut scratch_slice) .expect("<Ipv6Addr as Display>::fmt: fmt_inner should have succeeded because the scratch buffer was long enough"); let unwritten = scratch_slice.0.len(); let len = MAX_DISPLAY_LEN - unwritten; // `fmt_inner` only writes valid UTF-8. let str = core::str::from_utf8(&scratch[..len]) .expect("<Ipv6Addr as Display>::fmt: scratch buffer should contain valid UTF-8"); f.pad(str) } } } impl Debug for Ipv6Addr { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { Display::fmt(self, f) } } /// The source address from an IPv6 packet. /// /// An `Ipv6SourceAddr` represents the source address from an IPv6 packet, which /// may only be either unicast or unspecified. #[allow(missing_docs)] #[derive(Copy, Clone, Eq, PartialEq)] pub enum Ipv6SourceAddr { Unicast(UnicastAddr<Ipv6Addr>), Unspecified, } impl crate::sealed::Sealed for Ipv6SourceAddr {} impl Ipv6SourceAddr { /// Constructs a new `Ipv6SourceAddr`. /// /// Returns `None` if `addr` is neither unicast nor unspecified. #[inline] pub fn new(addr: Ipv6Addr) -> Option<Ipv6SourceAddr> { if let Some(addr) = UnicastAddr::new(addr) { Some(Ipv6SourceAddr::Unicast(addr)) } else if !addr.is_specified() { Some(Ipv6SourceAddr::Unspecified) } else { None } } } impl Witness<Ipv6Addr> for Ipv6SourceAddr { #[inline] fn new(addr: Ipv6Addr) -> Option<Ipv6SourceAddr> { Ipv6SourceAddr::new(addr) } #[inline] unsafe fn new_unchecked(addr: Ipv6Addr) -> Ipv6SourceAddr { Ipv6SourceAddr::new(addr).unwrap() } #[inline] fn into_addr(self) -> Ipv6Addr { match self { Ipv6SourceAddr::Unicast(addr) => addr.get(), Ipv6SourceAddr::Unspecified => Ipv6::UNSPECIFIED_ADDRESS, } } } impl SpecifiedAddress for Ipv6SourceAddr { fn is_specified(&self) -> bool { self != &Ipv6SourceAddr::Unspecified } } impl UnicastAddress for Ipv6SourceAddr { fn is_unicast(&self) -> bool { matches!(self, Ipv6SourceAddr::Unicast(_)) } } impl LinkLocalAddress for Ipv6SourceAddr { fn is_link_local(&self) -> bool { let addr: Ipv6Addr = self.into(); addr.is_link_local() } } impl From<Ipv6SourceAddr> for Ipv6Addr { fn from(addr: Ipv6SourceAddr) -> Ipv6Addr { addr.get() } } impl From<&'_ Ipv6SourceAddr> for Ipv6Addr { fn from(addr: &Ipv6SourceAddr) -> Ipv6Addr { match addr { Ipv6SourceAddr::Unicast(addr) => addr.get(), Ipv6SourceAddr::Unspecified => Ipv6::UNSPECIFIED_ADDRESS, } } } impl From<UnicastAddr<Ipv6Addr>> for Ipv6SourceAddr { fn from(addr: UnicastAddr<Ipv6Addr>) -> Ipv6SourceAddr { Ipv6SourceAddr::Unicast(addr) } } impl TryFrom<Ipv6Addr> for Ipv6SourceAddr { type Error = (); fn try_from(addr: Ipv6Addr) -> Result<Ipv6SourceAddr, ()> { Ipv6SourceAddr::new(addr).ok_or(()) } } impl AsRef<Ipv6Addr> for Ipv6SourceAddr { fn as_ref(&self) -> &Ipv6Addr { match self { Ipv6SourceAddr::Unicast(addr) => addr, Ipv6SourceAddr::Unspecified => &Ipv6::UNSPECIFIED_ADDRESS, } } } impl Deref for Ipv6SourceAddr { type Target = Ipv6Addr; fn deref(&self) -> &Ipv6Addr { self.as_ref() } } impl Display for Ipv6SourceAddr { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { match self { Ipv6SourceAddr::Unicast(addr) => write!(f, "{}", addr), Ipv6SourceAddr::Unspecified => write!(f, "::"), } } } impl Debug for Ipv6SourceAddr { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { Display::fmt(self, f) } } /// An IPv6 address stored as a unicast or multicast witness type. /// /// `UnicastOrMulticastIpv6Addr` is either a [`UnicastAddr`] or a /// [`MulticastAddr`]. It allows the user to match on the unicast-ness or /// multicast-ness of an IPv6 address and obtain a statically-typed witness in /// each case. This is useful if the user needs to call different functions /// which each take a witness type. #[allow(missing_docs)] #[derive(Copy, Clone, Eq, PartialEq)] pub enum UnicastOrMulticastIpv6Addr { Unicast(UnicastAddr<Ipv6Addr>), Multicast(MulticastAddr<Ipv6Addr>), } impl UnicastOrMulticastIpv6Addr { /// Constructs a new `UnicastOrMulticastIpv6Addr`. /// /// Returns `None` if `addr` is the unspecified address. pub fn new(addr: Ipv6Addr) -> Option<UnicastOrMulticastIpv6Addr> { SpecifiedAddr::new(addr).map(UnicastOrMulticastIpv6Addr::from_specified) } /// Constructs a new `UnicastOrMulticastIpv6Addr` from a specified address. pub fn from_specified(addr: SpecifiedAddr<Ipv6Addr>) -> UnicastOrMulticastIpv6Addr { if addr.is_unicast() { UnicastOrMulticastIpv6Addr::Unicast(UnicastAddr(addr.get())) } else { UnicastOrMulticastIpv6Addr::Multicast(MulticastAddr(addr.get())) } } } impl crate::sealed::Sealed for UnicastOrMulticastIpv6Addr {} impl Witness<Ipv6Addr> for UnicastOrMulticastIpv6Addr { #[inline] fn new(addr: Ipv6Addr) -> Option<UnicastOrMulticastIpv6Addr> { UnicastOrMulticastIpv6Addr::new(addr) } #[inline] unsafe fn new_unchecked(addr: Ipv6Addr) -> UnicastOrMulticastIpv6Addr { UnicastOrMulticastIpv6Addr::new(addr).unwrap() } #[inline] fn into_addr(self) -> Ipv6Addr { match self { UnicastOrMulticastIpv6Addr::Unicast(addr) => addr.get(), UnicastOrMulticastIpv6Addr::Multicast(addr) => addr.get(), } } } impl UnicastAddress for UnicastOrMulticastIpv6Addr { fn is_unicast(&self) -> bool { matches!(self, UnicastOrMulticastIpv6Addr::Unicast(_)) } } impl MulticastAddress for UnicastOrMulticastIpv6Addr { fn is_multicast(&self) -> bool { matches!(self, UnicastOrMulticastIpv6Addr::Multicast(_)) } } impl LinkLocalAddress for UnicastOrMulticastIpv6Addr { fn is_link_local(&self) -> bool { match self { UnicastOrMulticastIpv6Addr::Unicast(addr) => addr.is_link_local(), UnicastOrMulticastIpv6Addr::Multicast(addr) => addr.is_link_local(), } } } impl From<UnicastOrMulticastIpv6Addr> for Ipv6Addr { fn from(addr: UnicastOrMulticastIpv6Addr) -> Ipv6Addr { addr.get() } } impl From<&'_ UnicastOrMulticastIpv6Addr> for Ipv6Addr { fn from(addr: &UnicastOrMulticastIpv6Addr) -> Ipv6Addr { addr.get() } } impl From<UnicastAddr<Ipv6Addr>> for UnicastOrMulticastIpv6Addr { fn from(addr: UnicastAddr<Ipv6Addr>) -> UnicastOrMulticastIpv6Addr { UnicastOrMulticastIpv6Addr::Unicast(addr) } } impl From<MulticastAddr<Ipv6Addr>> for UnicastOrMulticastIpv6Addr { fn from(addr: MulticastAddr<Ipv6Addr>) -> UnicastOrMulticastIpv6Addr { UnicastOrMulticastIpv6Addr::Multicast(addr) } } impl TryFrom<Ipv6Addr> for UnicastOrMulticastIpv6Addr { type Error = (); fn try_from(addr: Ipv6Addr) -> Result<UnicastOrMulticastIpv6Addr, ()> { UnicastOrMulticastIpv6Addr::new(addr).ok_or(()) } } impl AsRef<Ipv6Addr> for UnicastOrMulticastIpv6Addr { fn as_ref(&self) -> &Ipv6Addr { match self { UnicastOrMulticastIpv6Addr::Unicast(addr) => addr, UnicastOrMulticastIpv6Addr::Multicast(addr) => addr, } } } impl Deref for UnicastOrMulticastIpv6Addr { type Target = Ipv6Addr; fn deref(&self) -> &Ipv6Addr { self.as_ref() } } impl Display for UnicastOrMulticastIpv6Addr { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { match self { UnicastOrMulticastIpv6Addr::Unicast(addr) => write!(f, "{}", addr), UnicastOrMulticastIpv6Addr::Multicast(addr) => write!(f, "{}", addr), } } } impl Debug for UnicastOrMulticastIpv6Addr { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { Display::fmt(self, f) } } /// The error returned from [`Subnet::new`] and [`SubnetEither::new`]. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum SubnetError { /// The network prefix is longer than the number of bits in the address (32 /// for IPv4/128 for IPv6). PrefixTooLong, /// The network address has some bits in the host part (past the network /// prefix) set to one. HostBitsSet, } /// An IP subnet. /// /// `Subnet` is a combination of an IP network address and a prefix length. #[derive(Copy, Clone, Eq, PartialEq, Hash)] pub struct Subnet<A> { // invariant: only contains prefix bits network: A, prefix: u8, } impl<A> Subnet<A> { /// Creates a new subnet without enforcing correctness. /// /// # Safety /// /// Unlike `new`, `new_unchecked` does not validate that `prefix` is in the /// proper range, and does not check that `network` has only the top /// `prefix` bits set. It is up to the caller to guarantee that `prefix` is /// in the proper range, and that none of the bits of `network` beyond the /// prefix are set. #[inline] pub const unsafe fn new_unchecked(network: A, prefix: u8) -> Subnet<A> { Subnet { network, prefix } } } impl<A: IpAddress> Subnet<A> { /// Creates a new subnet. /// /// `new` creates a new subnet with the given network address and prefix /// length. It returns `Err` if `prefix` is longer than the number of bits /// in this type of IP address (32 for IPv4 and 128 for IPv6) or if any of /// the host bits (beyond the first `prefix` bits) are set in `network`. #[inline] pub fn new(network: A, prefix: u8) -> Result<Subnet<A>, SubnetError> { if prefix > A::BYTES * 8 { return Err(SubnetError::PrefixTooLong); } // TODO(joshlf): Is there a more efficient way we can perform this // check? if network != network.mask(prefix) { return Err(SubnetError::HostBitsSet); } Ok(Subnet { network, prefix }) } /// Gets the network address component of this subnet. /// /// Any bits beyond the prefix will be zero. #[inline] pub fn network(&self) -> A { self.network } /// Gets the prefix length component of this subnet. #[inline] pub fn prefix(&self) -> u8 { self.prefix } /// Tests whether an address is in this subnet. /// /// Tests whether `addr` is in this subnet by testing whether the prefix /// bits match the prefix bits of the subnet's network address. This is /// equivalent to `sub.network() == addr.mask(sub.prefix())`. #[inline] pub fn contains(&self, addr: &A) -> bool { self.network == addr.mask(self.prefix) } } impl Subnet<Ipv4Addr> { // TODO(joshlf): If we introduce a separate type for an address in a subnet // (with fewer requirements than `AddrSubnet` has now so that a broadcast // address is representable), then that type could implement // `BroadcastAddress`, and `broadcast` could return // `BroadcastAddr<Foo<Ipv4Addr>>`. /// Gets the broadcast address in this IPv4 subnet. #[inline] pub fn broadcast(self) -> Ipv4Addr { if self.prefix == 32 { // shifting right by the size of the value is undefined self.network } else { let mask = <u32>::max_value() >> self.prefix; Ipv4Addr::new((u32::from_be_bytes(self.network.0) | mask).to_be_bytes()) } } } impl<A: IpAddress> Display for Subnet<A> { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { write!(f, "{}/{}", self.network, self.prefix) } } impl<A: IpAddress> Debug for Subnet<A> { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { write!(f, "{}/{}", self.network, self.prefix) } } /// An IPv4 subnet or an IPv6 subnet. /// /// `SubnetEither` is an enum of [`Subnet<Ipv4Addr>`] and `Subnet<Ipv6Addr>`. /// /// [`Subnet<Ipv4Addr>`]: Subnet #[allow(missing_docs)] #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub enum SubnetEither { V4(Subnet<Ipv4Addr>), V6(Subnet<Ipv6Addr>), } impl SubnetEither { /// Creates a new subnet. /// /// `new` creates a new subnet with the given network address and prefix /// length. It returns `Err` if `prefix` is longer than the number of bits /// in this type of IP address (32 for IPv4 and 128 for IPv6) or if any of /// the host bits (beyond the first `prefix` bits) are set in `network`. #[inline] pub fn new(network: IpAddr, prefix: u8) -> Result<SubnetEither, SubnetError> { Ok(match network { IpAddr::V4(network) => SubnetEither::V4(Subnet::new(network, prefix)?), IpAddr::V6(network) => SubnetEither::V6(Subnet::new(network, prefix)?), }) } /// Gets the network and prefix. #[inline] pub fn net_prefix(&self) -> (IpAddr, u8) { match self { SubnetEither::V4(v4) => (v4.network.into(), v4.prefix), SubnetEither::V6(v6) => (v6.network.into(), v6.prefix), } } } impl<A: IpAddress> From<Subnet<A>> for SubnetEither { fn from(subnet: Subnet<A>) -> SubnetEither { A::subnet_into_either(subnet) } } /// The error returned from [`AddrSubnet::new`] and [`AddrSubnetEither::new`]. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum AddrSubnetError { /// The network prefix is longer than the number of bits in the address (32 /// for IPv4/128 for IPv6). PrefixTooLong, /// The address is not a unicast address in the given subnet (see /// [`IpAddress::is_unicast_in_subnet`]). NotUnicastInSubnet, /// The address does not satisfy the requirements of the witness type. InvalidWitness, } // TODO(joshlf): Is the unicast restriction always necessary, or will some users // want the AddrSubnet functionality without that restriction? /// An address and that address's subnet. /// /// An `AddrSubnet` is a pair of an address and a subnet which maintains the /// invariant that the address is guaranteed to be a unicast address in the /// subnet. `S` is the type of address ([`Ipv4Addr`] or [`Ipv6Addr`]), and `A` /// is the type of the address in the subnet, which is always a witness wrapper /// around `S`. By default, it is `SpecifiedAddr<S>`. #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub struct AddrSubnet<S: IpAddress, A: Witness<S> + Copy = SpecifiedAddr<S>> { // TODO(joshlf): Would it be more performant to store these as just an // address and subnet mask? It would make the object smaller and so cheaper // to pass around, but it would make certain operations more expensive. addr: A, subnet: Subnet<S>, } impl<S: IpAddress, A: Witness<S> + Copy> AddrSubnet<S, A> { /// Creates a new `AddrSubnet`. /// /// `new` is like [`from_witness`], except that it also converts `addr` into /// the appropriate witness type, returning /// [`AddrSubnetError::InvalidWitness`] if the conversion fails. /// /// [`from_witness`]: Witness::from_witness #[inline] pub fn new(addr: S, prefix: u8) -> Result<AddrSubnet<S, A>, AddrSubnetError> { AddrSubnet::from_witness(A::new(addr).ok_or(AddrSubnetError::InvalidWitness)?, prefix) } /// Creates a new `AddrSubnet` from an existing witness. /// /// `from_witness` creates a new `AddrSubnet` with the given address and /// prefix length. The network address of the subnet is taken to be the /// first `prefix` bits of the address. It returns `Err` if `prefix` is /// longer than the number of bits in this type of IP address (32 for IPv4 /// and 128 for IPv6) or if `addr` is not a unicast address in the resulting /// subnet (see [`IpAddress::is_unicast_in_subnet`]). pub fn from_witness(addr: A, prefix: u8) -> Result<AddrSubnet<S, A>, AddrSubnetError> { if prefix > S::BYTES * 8 { return Err(AddrSubnetError::PrefixTooLong); } let subnet = Subnet { network: addr.as_ref().mask(prefix), prefix }; if !addr.as_ref().is_unicast_in_subnet(&subnet) { return Err(AddrSubnetError::NotUnicastInSubnet); } Ok(AddrSubnet { addr, subnet }) } /// Gets the subnet. #[inline] pub fn subnet(&self) -> Subnet<S> { self.subnet } /// Gets the address. #[inline] pub fn addr(&self) -> A { self.addr } /// Gets the address and subnet. #[inline] pub fn addr_subnet(self) -> (A, Subnet<S>) { (self.addr, self.subnet) } /// Constructs a new `AddrSubnet` of a different witness type. #[inline] pub fn to_witness<B: Witness<S> + Copy>(&self) -> AddrSubnet<S, B> where A: Into<B>, { AddrSubnet { addr: self.addr.into(), subnet: self.subnet } } } impl<A: Witness<Ipv6Addr> + Copy> AddrSubnet<Ipv6Addr, A> { /// Gets the address as a [`UnicastAddr`] witness. /// /// Since one of the invariants on an `AddrSubnet` is that its contained /// address is unicast in its subnet, `ipv6_unicast_addr` can infallibly /// convert its stored address to a `UnicastAddr`. pub fn ipv6_unicast_addr(&self) -> UnicastAddr<Ipv6Addr> { unsafe { UnicastAddr::new_unchecked(self.addr.get()) } } /// Constructs a new `AddrSubnet` which stores a [`UnicastAddr`] witness. /// /// Since one of the invariants on an `AddrSubnet` is that its contained /// address is unicast in its subnet, `to_unicast` can infallibly convert /// its stored address to a `UnicastAddr`. pub fn to_unicast(&self) -> AddrSubnet<Ipv6Addr, UnicastAddr<Ipv6Addr>> { let AddrSubnet { addr, subnet } = *self; let addr = unsafe { UnicastAddr::new_unchecked(addr.get()) }; AddrSubnet { addr, subnet } } } /// A type which is a witness to some property about an [`IpAddress`]. /// /// `IpAddrWitness` extends [`Witness`] of [`IpAddr`] by adding associated types /// for the IPv4- and IPv6-specific versions of the same witness type. For /// example, the following implementation is provided for /// `SpecifiedAddr<IpAddr>`: /// /// ```rust,ignore /// impl IpAddrWitness for SpecifiedAddr<IpAddr> { /// type V4 = SpecifiedAddr<Ipv4Addr>; /// type V6 = SpecifiedAddr<Ipv6Addr>; /// } /// ``` pub trait IpAddrWitness: Witness<IpAddr> + Copy { /// The IPv4-specific version of `Self`. /// /// For example, `SpecifiedAddr<IpAddr>: IpAddrWitness<V4 = /// SpecifiedAddr<Ipv4Addr>>`. type V4: Witness<Ipv4Addr> + Into<Self> + Copy; /// The IPv6-specific version of `Self`. /// /// For example, `SpecifiedAddr<IpAddr>: IpAddrWitness<V6 = /// SpecifiedAddr<Ipv6Addr>>`. type V6: Witness<Ipv6Addr> + Into<Self> + Copy; // TODO(https://github.com/rust-lang/rust/issues/44491): Remove these // functions once implied where bounds make them unnecessary. /// Converts an IPv4-specific witness into a general witness. fn from_v4(addr: Self::V4) -> Self { addr.into() } /// Converts an IPv6-specific witness into a general witness. fn from_v6(addr: Self::V6) -> Self { addr.into() } } macro_rules! impl_ip_addr_witness { ($witness:ident) => { impl IpAddrWitness for $witness<IpAddr> { type V4 = $witness<Ipv4Addr>; type V6 = $witness<Ipv6Addr>; } }; } impl_ip_addr_witness!(SpecifiedAddr); impl_ip_addr_witness!(MulticastAddr); impl_ip_addr_witness!(LinkLocalAddr); /// An address and that address's subnet, either IPv4 or IPv6. /// /// `AddrSubnetEither` is an enum of [`AddrSubnet<Ipv4Addr>`] and /// `AddrSubnet<Ipv6Addr>`. /// /// [`AddrSubnet<Ipv4Addr>`]: AddrSubnet #[allow(missing_docs)] #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub enum AddrSubnetEither<A: IpAddrWitness = SpecifiedAddr<IpAddr>> { V4(AddrSubnet<Ipv4Addr, A::V4>), V6(AddrSubnet<Ipv6Addr, A::V6>), } impl<A: IpAddrWitness> AddrSubnetEither<A> { /// Creates a new `AddrSubnetEither`. /// /// `new` creates a new `AddrSubnetEither` with the given address and prefix /// length. It returns `Err` under the same conditions as /// [`AddrSubnet::new`]. #[inline] pub fn new(addr: IpAddr, prefix: u8) -> Result<AddrSubnetEither<A>, AddrSubnetError> { Ok(match addr { IpAddr::V4(addr) => AddrSubnetEither::V4(AddrSubnet::new(addr, prefix)?), IpAddr::V6(addr) => AddrSubnetEither::V6(AddrSubnet::new(addr, prefix)?), }) } /// Gets the IP address and prefix. #[inline] pub fn addr_prefix(&self) -> (A, u8) { match self { AddrSubnetEither::V4(v4) => (v4.addr.into(), v4.subnet.prefix), AddrSubnetEither::V6(v6) => (v6.addr.into(), v6.subnet.prefix), } } /// Gets the IP address and subnet. #[inline] pub fn addr_subnet(&self) -> (A, SubnetEither) { match self { AddrSubnetEither::V4(v4) => (v4.addr.into(), SubnetEither::V4(v4.subnet)), AddrSubnetEither::V6(v6) => (v6.addr.into(), SubnetEither::V6(v6.subnet)), } } } #[cfg(test)] mod tests { use core::convert::TryInto; use super::*; #[test] fn test_loopback_unicast() { // The loopback addresses are constructed as `SpecifiedAddr`s directly, // bypassing the actual check against `is_specified`. Test that that's // actually valid. assert!(Ipv4::LOOPBACK_ADDRESS.0.is_specified()); assert!(Ipv6::LOOPBACK_ADDRESS.0.is_specified()); } #[test] fn test_specified() { // For types that implement SpecifiedAddress, // UnicastAddress::is_unicast, MulticastAddress::is_multicast, and // LinkLocalAddress::is_link_local all imply // SpecifiedAddress::is_specified. Test that that's true for both IPv4 // and IPv6. assert!(!Ipv6::UNSPECIFIED_ADDRESS.is_specified()); assert!(!Ipv4::UNSPECIFIED_ADDRESS.is_specified()); // Unicast assert!(!Ipv6::UNSPECIFIED_ADDRESS.is_unicast()); let unicast = Ipv6Addr([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]); assert!(unicast.is_unicast()); assert!(unicast.is_specified()); // Multicast assert!(!Ipv4::UNSPECIFIED_ADDRESS.is_multicast()); assert!(!Ipv6::UNSPECIFIED_ADDRESS.is_multicast()); let multicast = Ipv4::MULTICAST_SUBNET.network; assert!(multicast.is_multicast()); assert!(multicast.is_specified()); let multicast = Ipv6::MULTICAST_SUBNET.network; assert!(multicast.is_multicast()); assert!(multicast.is_specified()); // Link-local assert!(!Ipv4::UNSPECIFIED_ADDRESS.is_link_local()); assert!(!Ipv6::UNSPECIFIED_ADDRESS.is_link_local()); let link_local = Ipv4::LINK_LOCAL_UNICAST_SUBNET.network; assert!(link_local.is_link_local()); assert!(link_local.is_specified()); let link_local = Ipv4::LINK_LOCAL_MULTICAST_SUBNET.network; assert!(link_local.is_link_local()); assert!(link_local.is_specified()); let link_local = Ipv6::LINK_LOCAL_UNICAST_SUBNET.network; assert!(link_local.is_link_local()); assert!(link_local.is_specified()); let mut link_local = Ipv6::MULTICAST_SUBNET.network; link_local.0[1] = 0x02; assert!(link_local.is_link_local()); assert!(link_local.is_specified()); assert!(Ipv6::LOOPBACK_ADDRESS.is_link_local()); } #[test] fn test_link_local() { // IPv4 assert!(Ipv4::LINK_LOCAL_UNICAST_SUBNET.network.is_link_local()); assert!(Ipv4::LINK_LOCAL_MULTICAST_SUBNET.network.is_link_local()); // IPv6 assert!(Ipv6::LINK_LOCAL_UNICAST_SUBNET.network.is_link_local()); assert!(Ipv6::LINK_LOCAL_UNICAST_SUBNET.network.is_unicast_link_local()); let mut addr = Ipv6::MULTICAST_SUBNET.network; for flags in 0..=0x0F { // Set the scope to link-local and the flags to `flags`. addr.0[1] = (flags << 4) | 0x02; // Test that a link-local multicast address is always considered // link-local regardless of which flags are set. assert!(addr.is_link_local()); assert!(!addr.is_unicast_link_local()); } // Test that a non-multicast address (outside of the link-local subnet) // is never considered link-local even if the bits are set that, in a // multicast address, would put it in the link-local scope. let mut addr = Ipv6::LOOPBACK_ADDRESS.get(); // Explicitly set the scope to link-local. addr.0[1] = 0x02; assert!(!addr.is_link_local()); } #[test] fn test_subnet_new() { assert_eq!( Subnet::new(Ipv4Addr::new([255, 255, 255, 255]), 32).unwrap(), Subnet { network: Ipv4Addr::new([255, 255, 255, 255]), prefix: 32 }, ); // Prefix exceeds 32 bits assert_eq!( Subnet::new(Ipv4Addr::new([255, 255, 0, 0]), 33), Err(SubnetError::PrefixTooLong) ); // Network address has more than top 8 bits set assert_eq!(Subnet::new(Ipv4Addr::new([255, 255, 0, 0]), 8), Err(SubnetError::HostBitsSet)); assert_eq!( AddrSubnet::<_, SpecifiedAddr<_>>::new(Ipv4Addr::new([1, 2, 3, 4]), 32).unwrap(), AddrSubnet { addr: SpecifiedAddr(Ipv4Addr::new([1, 2, 3, 4])), subnet: Subnet { network: Ipv4Addr::new([1, 2, 3, 4]), prefix: 32 } } ); // The unspecified address will always fail because it is not valid for // the `SpecifiedAddr` witness (use assert, not assert_eq, because // AddrSubnet doesn't impl Debug). assert!( AddrSubnet::<_, SpecifiedAddr<_>>::new(Ipv4::UNSPECIFIED_ADDRESS, 16) == Err(AddrSubnetError::InvalidWitness) ); assert!( AddrSubnet::<_, SpecifiedAddr<_>>::new(Ipv6::UNSPECIFIED_ADDRESS, 64) == Err(AddrSubnetError::InvalidWitness) ); // Prefix exceeds 32/128 bits assert!( AddrSubnet::<_, SpecifiedAddr<_>>::new(Ipv4Addr::new([1, 2, 3, 4]), 33) == Err(AddrSubnetError::PrefixTooLong) ); assert!( AddrSubnet::<_, SpecifiedAddr<_>>::new( Ipv6Addr::from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]), 129, ) == Err(AddrSubnetError::PrefixTooLong) ); // Limited broadcast assert!( AddrSubnet::<_, SpecifiedAddr<_>>::new(Ipv4::LIMITED_BROADCAST_ADDRESS.get(), 16) == Err(AddrSubnetError::NotUnicastInSubnet) ); // Subnet broadcast assert!( AddrSubnet::<_, SpecifiedAddr<_>>::new(Ipv4Addr::new([192, 168, 255, 255]), 16) == Err(AddrSubnetError::NotUnicastInSubnet) ); // Multicast assert!( AddrSubnet::<_, SpecifiedAddr<_>>::new(Ipv4Addr::new([224, 0, 0, 1]), 16) == Err(AddrSubnetError::NotUnicastInSubnet) ); assert!( AddrSubnet::<_, SpecifiedAddr<_>>::new( Ipv6Addr::from([0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]), 64, ) == Err(AddrSubnetError::NotUnicastInSubnet) ); // If we use the `LinkLocalAddr` witness type, then non link-local // addresses are rejected. Note that this address was accepted above // when `SpecifiedAddr` was used. assert!( AddrSubnet::<_, LinkLocalAddr<Ipv4Addr>>::new(Ipv4Addr::new([1, 2, 3, 4]), 32) == Err(AddrSubnetError::InvalidWitness) ); } #[test] fn test_is_unicast_in_subnet() { // Valid unicast in subnet let subnet = Subnet::new(Ipv4Addr::new([1, 2, 0, 0]), 16).expect("1.2.0.0/16 is a valid subnet"); assert!(Ipv4Addr::new([1, 2, 3, 4]).is_unicast_in_subnet(&subnet)); assert!(!Ipv4Addr::new([2, 2, 3, 4]).is_unicast_in_subnet(&subnet)); let subnet = Subnet::new(Ipv6Addr::from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), 64) .expect("1::/64 is a valid subnet"); assert!(Ipv6Addr::from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) .is_unicast_in_subnet(&subnet)); assert!(!Ipv6Addr::from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) .is_unicast_in_subnet(&subnet)); // Unspecified address assert!(!Ipv4::UNSPECIFIED_ADDRESS .is_unicast_in_subnet(&Subnet::new(Ipv4::UNSPECIFIED_ADDRESS, 16).unwrap())); assert!(!Ipv6::UNSPECIFIED_ADDRESS .is_unicast_in_subnet(&Subnet::new(Ipv6::UNSPECIFIED_ADDRESS, 64).unwrap())); // The "31- or 32-bit prefix" exception doesn't apply to the unspecified // address (IPv4 only). assert!(!Ipv4::UNSPECIFIED_ADDRESS .is_unicast_in_subnet(&Subnet::new(Ipv4::UNSPECIFIED_ADDRESS, 31).unwrap())); assert!(!Ipv4::UNSPECIFIED_ADDRESS .is_unicast_in_subnet(&Subnet::new(Ipv4::UNSPECIFIED_ADDRESS, 32).unwrap())); // All-zeroes host part (IPv4 only) assert!(!Ipv4Addr::new([1, 2, 0, 0]) .is_unicast_in_subnet(&Subnet::new(Ipv4Addr::new([1, 2, 0, 0]), 16).unwrap())); // Exception: 31- or 32-bit prefix (IPv4 only) assert!(Ipv4Addr::new([1, 2, 3, 0]) .is_unicast_in_subnet(&Subnet::new(Ipv4Addr::new([1, 2, 3, 0]), 31).unwrap())); assert!(Ipv4Addr::new([1, 2, 3, 0]) .is_unicast_in_subnet(&Subnet::new(Ipv4Addr::new([1, 2, 3, 0]), 32).unwrap())); // Limited broadcast (IPv4 only) assert!(!Ipv4::LIMITED_BROADCAST_ADDRESS .get() .is_unicast_in_subnet(&Subnet::new(Ipv4Addr::new([128, 0, 0, 0]), 1).unwrap())); // Subnet broadcast (IPv4 only) assert!(!Ipv4Addr::new([1, 2, 255, 255]) .is_unicast_in_subnet(&Subnet::new(Ipv4Addr::new([1, 2, 0, 0]), 16).unwrap())); // Exception: 31- or 32-bit prefix (IPv4 only) assert!(Ipv4Addr::new([1, 2, 255, 255]) .is_unicast_in_subnet(&Subnet::new(Ipv4Addr::new([1, 2, 255, 254]), 31).unwrap())); assert!(Ipv4Addr::new([1, 2, 255, 255]) .is_unicast_in_subnet(&Subnet::new(Ipv4Addr::new([1, 2, 255, 255]), 32).unwrap())); // Multicast assert!(!Ipv4Addr::new([224, 0, 0, 1]).is_unicast_in_subnet(&Ipv4::MULTICAST_SUBNET)); assert!(!Ipv6Addr::from([0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) .is_unicast_in_subnet(&Ipv6::MULTICAST_SUBNET)); // Class E (IPv4 only) assert!(!Ipv4Addr::new([240, 0, 0, 1]).is_unicast_in_subnet(&Ipv4::CLASS_E_SUBNET)); } macro_rules! add_mask_test { ($name:ident, $addr:ident, $from_ip:expr => { $($mask:expr => $to_ip:expr),* }) => { #[test] fn $name() { let from = $addr::from($from_ip); $(assert_eq!(from.mask($mask), $addr::from($to_ip), "(`{}`.mask({}))", from, $mask);)* } }; ($name:ident, $addr:ident, $from_ip:expr => { $($mask:expr => $to_ip:expr),*, }) => { add_mask_test!($name, $addr, $from_ip => { $($mask => $to_ip),* }); }; } add_mask_test!(v4_full_mask, Ipv4Addr, [255, 254, 253, 252] => { 32 => [255, 254, 253, 252], 28 => [255, 254, 253, 240], 24 => [255, 254, 253, 0], 20 => [255, 254, 240, 0], 16 => [255, 254, 0, 0], 12 => [255, 240, 0, 0], 8 => [255, 0, 0, 0], 4 => [240, 0, 0, 0], 0 => [0, 0, 0, 0], }); add_mask_test!(v6_full_mask, Ipv6Addr, [0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6, 0xF5, 0xF4, 0xF3, 0xF2, 0xF1, 0xF0] => { 128 => [0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6, 0xF5, 0xF4, 0xF3, 0xF2, 0xF1, 0xF0], 112 => [0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6, 0xF5, 0xF4, 0xF3, 0xF2, 0x00, 0x00], 96 => [0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6, 0xF5, 0xF4, 0x00, 0x00, 0x00, 0x00], 80 => [0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 64 => [0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 48 => [0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 32 => [0xFF, 0xFE, 0xFD, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 16 => [0xFF, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 8 => [0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 0 => [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], } ); #[test] fn test_ipv6_solicited_node() { let addr = Ipv6Addr::new([0xfe80, 0, 0, 0, 0x52e5, 0x49ff, 0xfeb5, 0x5aa0]); let solicited = Ipv6Addr::new([0xff02, 0, 0, 0, 0, 0x01, 0xffb5, 0x5aa0]); assert_eq!(addr.to_solicited_node_address().get(), solicited); } #[test] fn test_ipv6_address_types() { assert!(!Ipv6Addr::from([0; 16]).is_specified()); assert!(Ipv6Addr::new([0, 0, 0, 0, 0, 0, 0, 1]).is_loopback()); let link_local = Ipv6Addr::new([0xfe80, 0, 0, 0, 0x52e5, 0x49ff, 0xfeb5, 0x5aa0]); assert!(link_local.is_link_local()); assert!(link_local.is_valid_unicast()); assert!(link_local.to_solicited_node_address().is_multicast()); let global_unicast = Ipv6Addr::new([0x80, 0, 0, 0, 0x52e5, 0x49ff, 0xfeb5, 0x5aa0]); assert!(global_unicast.is_valid_unicast()); assert!(global_unicast.to_solicited_node_address().is_multicast()); let multi = Ipv6Addr::new([0xff02, 0, 0, 0, 0, 0x01, 0xffb5, 0x5aa0]); assert!(multi.is_multicast()); assert!(!multi.is_valid_unicast()); } #[test] fn test_const_witness() { // Test that all of the addresses that we initialize at compile time // using `new_unchecked` constructors are valid for their witness types. assert!(Ipv4::LOOPBACK_ADDRESS.0.is_specified()); assert!(Ipv6::LOOPBACK_ADDRESS.0.is_specified()); assert!(Ipv4::LIMITED_BROADCAST_ADDRESS.0.is_specified()); assert!(Ipv4::ALL_ROUTERS_MULTICAST_ADDRESS.0.is_multicast()); assert!(Ipv6::ALL_NODES_LINK_LOCAL_MULTICAST_ADDRESS.0.is_multicast()); assert!(Ipv6::ALL_ROUTERS_LINK_LOCAL_MULTICAST_ADDRESS.0.is_multicast()); } #[test] fn test_ipv6_scope() { use Ipv6ReservedScope::*; use Ipv6Scope::*; use Ipv6UnassignedScope::*; // Test unicast scopes. assert_eq!(Ipv6::SITE_LOCAL_UNICAST_SUBNET.network.scope(), SiteLocal); assert_eq!(Ipv6::LINK_LOCAL_UNICAST_SUBNET.network.scope(), LinkLocal); assert_eq!(Ipv6::UNSPECIFIED_ADDRESS.scope(), Global); // Test multicast scopes. let assert_scope = |value, scope| { let mut addr = Ipv6::MULTICAST_SUBNET.network; // Set the "scop" field manually. addr.0[1] |= value; assert_eq!(addr.scope(), scope); }; assert_scope(0, Reserved(Scope0)); assert_scope(1, InterfaceLocal); assert_scope(2, LinkLocal); assert_scope(3, Reserved(Scope3)); assert_scope(4, AdminLocal); assert_scope(5, SiteLocal); assert_scope(6, Unassigned(Scope6)); assert_scope(7, Unassigned(Scope7)); assert_scope(8, OrganizationLocal); assert_scope(9, Unassigned(Scope9)); assert_scope(0xA, Unassigned(ScopeA)); assert_scope(0xB, Unassigned(ScopeB)); assert_scope(0xC, Unassigned(ScopeC)); assert_scope(0xD, Unassigned(ScopeD)); assert_scope(0xE, Global); assert_scope(0xF, Reserved(ScopeF)); } #[test] fn test_ipv6_multicast_scope_id() { const ALL_SCOPES: &[Ipv6Scope] = &[ Ipv6Scope::Reserved(Ipv6ReservedScope::Scope0), Ipv6Scope::InterfaceLocal, Ipv6Scope::LinkLocal, Ipv6Scope::Reserved(Ipv6ReservedScope::Scope3), Ipv6Scope::AdminLocal, Ipv6Scope::SiteLocal, Ipv6Scope::Unassigned(Ipv6UnassignedScope::Scope6), Ipv6Scope::Unassigned(Ipv6UnassignedScope::Scope7), Ipv6Scope::OrganizationLocal, Ipv6Scope::Unassigned(Ipv6UnassignedScope::Scope9), Ipv6Scope::Unassigned(Ipv6UnassignedScope::ScopeA), Ipv6Scope::Unassigned(Ipv6UnassignedScope::ScopeB), Ipv6Scope::Unassigned(Ipv6UnassignedScope::ScopeC), Ipv6Scope::Unassigned(Ipv6UnassignedScope::ScopeD), Ipv6Scope::Global, Ipv6Scope::Reserved(Ipv6ReservedScope::ScopeF), ]; for (i, a) in ALL_SCOPES.iter().enumerate() { assert_eq!(a.multicast_scope_id(), i.try_into().unwrap()); } } #[test] fn test_ipv4_embedded() { // Test Ipv4Addr's to_ipv6_compatible and to_ipv6_mapped methods. assert_eq!( Ipv4Addr::new([1, 2, 3, 4]).to_ipv6_compatible(), Ipv6Addr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4]) ); assert_eq!( Ipv4Addr::new([1, 2, 3, 4]).to_ipv6_mapped(), Ipv6Addr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 1, 2, 3, 4]), ); // Test Ipv6Addr's to_ipv4_compatible and to_ipv4_mapped methods. let compatible = Ipv6Addr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4]); let mapped = Ipv6Addr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 1, 2, 3, 4]); let not_embedded = Ipv6Addr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 1, 2, 3, 4]); let v4 = Ipv4Addr::new([1, 2, 3, 4]); assert_eq!(compatible.to_ipv4_compatible(), Some(v4)); assert_eq!(compatible.to_ipv4_mapped(), None); assert_eq!(mapped.to_ipv4_compatible(), None); assert_eq!(mapped.to_ipv4_mapped(), Some(v4)); assert_eq!(not_embedded.to_ipv4_compatible(), None); assert_eq!(not_embedded.to_ipv4_mapped(), None); } #[test] fn test_common_prefix_len_ipv6() { let ip1 = Ipv6Addr::from([0xFF, 0xFF, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); let ip2 = Ipv6Addr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); let ip3 = Ipv6Addr::from([0xFF, 0xFF, 0x80, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); let ip4 = Ipv6Addr::from([0xFF, 0xFF, 0xC0, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); let compare_with_ip1 = |target, expect| { assert_eq!(ip1.common_prefix_len(&target), expect, "{} <=> {}", ip1, target); }; compare_with_ip1(ip1, 128); compare_with_ip1(ip2, 0); compare_with_ip1(ip3, 24); compare_with_ip1(ip4, 17); } #[test] fn test_common_prefix_len_ipv4() { let ip1 = Ipv4Addr::new([0xFF, 0xFF, 0x80, 0]); let ip2 = Ipv4Addr::new([0, 0, 0, 0]); let ip3 = Ipv4Addr::new([0xFF, 0xFF, 0x80, 0xFF]); let ip4 = Ipv4Addr::new([0xFF, 0xFF, 0xC0, 0x20]); let compare_with_ip1 = |target, expect| { assert_eq!(ip1.common_prefix_len(&target), expect, "{} <=> {}", ip1, target); }; compare_with_ip1(ip1, 32); compare_with_ip1(ip2, 0); compare_with_ip1(ip3, 24); compare_with_ip1(ip4, 17); } #[test] fn test_ipv6_display() { // Test that `addr` is formatted the same by our `Display` impl as by // the standard library's `Display` impl. Optionally test that it // matches a particular expected string. fn test_one(addr: Ipv6Addr, expect: Option<&str>) { let formatted = format!("{}", addr); if let Some(expect) = expect { assert_eq!(formatted, expect); } // NOTE: We use `std` here even though we're not inside of the // `std_tests` module because we're using `std` to test // functionality that is present even when the `std` Cargo feature // is not used. // // Note that we use `std::net::Ipv6Addr::from(addr.segments())` // rather than `std::net::Ipv6Addr::from(addr)` because, when the // `std` Cargo feature is disabled, the `From<Ipv6Addr> for // std::net::Ipv6Addr` impl is not emitted. let formatted_std = format!("{}", std::net::Ipv6Addr::from(addr.segments())); assert_eq!(formatted, formatted_std); } test_one(Ipv6::UNSPECIFIED_ADDRESS, Some("::")); test_one(*Ipv6::LOOPBACK_ADDRESS, Some("::1")); test_one(Ipv6::MULTICAST_SUBNET.network, Some("ff00::")); test_one(Ipv6::LINK_LOCAL_UNICAST_SUBNET.network, Some("fe80::")); test_one(*Ipv6::ALL_NODES_LINK_LOCAL_MULTICAST_ADDRESS, Some("ff02::1")); test_one(*Ipv6::ALL_NODES_LINK_LOCAL_MULTICAST_ADDRESS, Some("ff02::1")); test_one(*Ipv6::ALL_ROUTERS_LINK_LOCAL_MULTICAST_ADDRESS, Some("ff02::2")); test_one(Ipv6::SITE_LOCAL_UNICAST_SUBNET.network, Some("fec0::")); test_one(Ipv6Addr::new([1, 0, 0, 0, 0, 0, 0, 0]), Some("1::")); test_one(Ipv6Addr::new([0, 0, 0, 1, 2, 3, 4, 5]), Some("::1:2:3:4:5")); // Treating each pair of bytes as a bit (either 0x0000 or 0x0001), cycle // through every possible IPv6 address. Since the formatting algorithm // is only sensitive to zero vs nonzero for any given byte pair, this // gives us effectively complete coverage of the input space. for byte in 0u8..=255 { test_one( Ipv6Addr::new([ u16::from(byte & 0b1), u16::from((byte & 0b10) >> 1), u16::from((byte & 0b100) >> 2), u16::from((byte & 0b1000) >> 3), u16::from((byte & 0b10000) >> 4), u16::from((byte & 0b100000) >> 5), u16::from((byte & 0b1000000) >> 6), u16::from((byte & 0b10000000) >> 7), ]), None, ); } } #[cfg(feature = "std")] mod std_tests { use std::net; use super::*; #[test] fn test_conversions() { let v4 = Ipv4Addr::new([127, 0, 0, 1]); let v6 = Ipv6Addr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]); let std_v4 = net::Ipv4Addr::new(127, 0, 0, 1); let std_v6 = net::Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); let converted: IpAddr = net::IpAddr::V4(std_v4).into(); assert_eq!(converted, IpAddr::V4(v4)); let converted: IpAddr = net::IpAddr::V6(std_v6).into(); assert_eq!(converted, IpAddr::V6(v6)); let converted: net::IpAddr = IpAddr::V4(v4).into(); assert_eq!(converted, net::IpAddr::V4(std_v4)); let converted: net::IpAddr = IpAddr::V6(v6).into(); assert_eq!(converted, net::IpAddr::V6(std_v6)); let converted: Ipv4Addr = std_v4.into(); assert_eq!(converted, v4); let converted: Ipv6Addr = std_v6.into(); assert_eq!(converted, v6); let converted: net::Ipv4Addr = v4.into(); assert_eq!(converted, std_v4); let converted: net::Ipv6Addr = v6.into(); assert_eq!(converted, std_v6); } } }
38.072016
146
0.598029
675a7e8b081de7dc44a527dd5a361777e6d5965a
31,370
use super::prelude::*; use crate::protocol::commands::ext::Base; use crate::arch::{Arch, Registers}; use crate::protocol::{IdKind, SpecificIdKind, SpecificThreadId}; use crate::target::ext::base::multithread::ThreadStopReason; use crate::target::ext::base::{BaseOps, GdbInterrupt, ReplayLogPosition, ResumeAction}; use crate::{FAKE_PID, SINGLE_THREAD_TID}; impl<T: Target, C: Connection> GdbStubImpl<T, C> { #[inline(always)] fn get_sane_any_tid(&mut self, target: &mut T) -> Result<Tid, Error<T::Error, C::Error>> { let tid = match target.base_ops() { BaseOps::SingleThread(_) => SINGLE_THREAD_TID, BaseOps::MultiThread(ops) => { let mut first_tid = None; ops.list_active_threads(&mut |tid| { if first_tid.is_none() { first_tid = Some(tid); } }) .map_err(Error::TargetError)?; // Note that `Error::NoActiveThreads` shouldn't ever occur, since this method is // called from the `H` packet handler, which AFAIK is only sent after the GDB // client has confirmed that a thread / process exists. // // If it does, that really sucks, and will require rethinking how to handle "any // thread" messages. first_tid.ok_or(Error::NoActiveThreads)? } }; Ok(tid) } pub(crate) fn handle_base<'a>( &mut self, res: &mut ResponseWriter<C>, target: &mut T, command: Base<'a>, ) -> Result<HandlerStatus, Error<T::Error, C::Error>> { let handler_status = match command { // ------------------ Handshaking and Queries ------------------- // Base::qSupported(cmd) => { // XXX: actually read what the client supports, and enable/disable features // appropriately let _features = cmd.features.into_iter(); res.write_str("PacketSize=")?; res.write_num(cmd.packet_buffer_len)?; res.write_str(";vContSupported+")?; res.write_str(";multiprocess+")?; res.write_str(";QStartNoAckMode+")?; let (reverse_cont, reverse_step) = match target.base_ops() { BaseOps::MultiThread(ops) => ( ops.support_reverse_cont().is_some(), ops.support_reverse_step().is_some(), ), BaseOps::SingleThread(ops) => ( ops.support_reverse_cont().is_some(), ops.support_reverse_step().is_some(), ), }; if reverse_cont { res.write_str(";ReverseContinue+")?; } if reverse_step { res.write_str(";ReverseStep+")?; } if let Some(ops) = target.extended_mode() { if ops.configure_aslr().is_some() { res.write_str(";QDisableRandomization+")?; } if ops.configure_env().is_some() { res.write_str(";QEnvironmentHexEncoded+")?; res.write_str(";QEnvironmentUnset+")?; res.write_str(";QEnvironmentReset+")?; } if ops.configure_startup_shell().is_some() { res.write_str(";QStartupWithShell+")?; } if ops.configure_working_dir().is_some() { res.write_str(";QSetWorkingDir+")?; } } if let Some(ops) = target.breakpoints() { if ops.sw_breakpoint().is_some() { res.write_str(";swbreak+")?; } if ops.hw_breakpoint().is_some() || ops.hw_watchpoint().is_some() { res.write_str(";hwbreak+")?; } } if T::Arch::target_description_xml().is_some() || target.target_description_xml_override().is_some() { res.write_str(";qXfer:features:read+")?; } if target.memory_map().is_some() { res.write_str(";qXfer:memory-map:read+")?; } HandlerStatus::Handled } Base::QStartNoAckMode(_) => { self.no_ack_mode = true; HandlerStatus::NeedsOk } Base::qXferFeaturesRead(cmd) => { #[allow(clippy::redundant_closure)] let xml = target .target_description_xml_override() .map(|ops| ops.target_description_xml()) .or_else(|| T::Arch::target_description_xml()); match xml { Some(xml) => { let xml = xml.trim(); if cmd.offset >= xml.len() { // no more data res.write_str("l")?; } else if cmd.offset + cmd.len >= xml.len() { // last little bit of data res.write_str("l")?; res.write_binary(&xml.as_bytes()[cmd.offset..])? } else { // still more data res.write_str("m")?; res.write_binary(&xml.as_bytes()[cmd.offset..(cmd.offset + cmd.len)])? } } // If the target hasn't provided their own XML, then the initial response to // "qSupported" wouldn't have included "qXfer:features:read", and gdb wouldn't // send this packet unless it was explicitly marked as supported. None => return Err(Error::PacketUnexpected), } HandlerStatus::Handled } // -------------------- "Core" Functionality -------------------- // // TODO: Improve the '?' response based on last-sent stop reason. // this will be particularly relevant when working on non-stop mode. Base::QuestionMark(_) => { res.write_str("S05")?; HandlerStatus::Handled } Base::qAttached(cmd) => { let is_attached = match target.extended_mode() { // when _not_ running in extended mode, just report that we're attaching to an // existing process. None => true, // assume attached to an existing process // When running in extended mode, we must defer to the target Some(ops) => { let pid: Pid = cmd.pid.ok_or(Error::PacketUnexpected)?; ops.query_if_attached(pid).handle_error()?.was_attached() } }; res.write_str(if is_attached { "1" } else { "0" })?; HandlerStatus::Handled } Base::g(_) => { let mut regs: <T::Arch as Arch>::Registers = Default::default(); match target.base_ops() { BaseOps::SingleThread(ops) => ops.read_registers(&mut regs), BaseOps::MultiThread(ops) => { ops.read_registers(&mut regs, self.current_mem_tid) } } .handle_error()?; let mut err = Ok(()); regs.gdb_serialize(|val| { let res = match val { Some(b) => res.write_hex_buf(&[b]), None => res.write_str("xx"), }; if let Err(e) = res { err = Err(e); } }); err?; HandlerStatus::Handled } Base::G(cmd) => { let mut regs: <T::Arch as Arch>::Registers = Default::default(); regs.gdb_deserialize(cmd.vals) .map_err(|_| Error::TargetMismatch)?; match target.base_ops() { BaseOps::SingleThread(ops) => ops.write_registers(&regs), BaseOps::MultiThread(ops) => ops.write_registers(&regs, self.current_mem_tid), } .handle_error()?; HandlerStatus::NeedsOk } Base::m(cmd) => { let buf = cmd.buf; let addr = <T::Arch as Arch>::Usize::from_be_bytes(cmd.addr) .ok_or(Error::TargetMismatch)?; let mut i = 0; let mut n = cmd.len; while n != 0 { let chunk_size = n.min(buf.len()); use num_traits::NumCast; let addr = addr + NumCast::from(i).ok_or(Error::TargetMismatch)?; let data = &mut buf[..chunk_size]; match target.base_ops() { BaseOps::SingleThread(ops) => ops.read_addrs(addr, data), BaseOps::MultiThread(ops) => { ops.read_addrs(addr, data, self.current_mem_tid) } } .handle_error()?; n -= chunk_size; i += chunk_size; res.write_hex_buf(data)?; } HandlerStatus::Handled } Base::M(cmd) => { let addr = <T::Arch as Arch>::Usize::from_be_bytes(cmd.addr) .ok_or(Error::TargetMismatch)?; match target.base_ops() { BaseOps::SingleThread(ops) => ops.write_addrs(addr, cmd.val), BaseOps::MultiThread(ops) => { ops.write_addrs(addr, cmd.val, self.current_mem_tid) } } .handle_error()?; HandlerStatus::NeedsOk } Base::k(_) | Base::vKill(_) => { match target.extended_mode() { // When not running in extended mode, stop the `GdbStub` and disconnect. None => HandlerStatus::Disconnect(DisconnectReason::Kill), // When running in extended mode, a kill command does not necessarily result in // a disconnect... Some(ops) => { let pid = match command { Base::vKill(cmd) => Some(cmd.pid), _ => None, }; let should_terminate = ops.kill(pid).handle_error()?; if should_terminate.into_bool() { // manually write OK, since we need to return a DisconnectReason res.write_str("OK")?; HandlerStatus::Disconnect(DisconnectReason::Kill) } else { HandlerStatus::NeedsOk } } } } Base::D(_) => { // TODO: plumb-through Pid when exposing full multiprocess + extended mode res.write_str("OK")?; // manually write OK, since we need to return a DisconnectReason HandlerStatus::Disconnect(DisconnectReason::Disconnect) } Base::vCont(cmd) => { use crate::protocol::commands::_vCont::vCont; match cmd { vCont::Query => { res.write_str("vCont;c;C;s;S")?; if match target.base_ops() { BaseOps::SingleThread(ops) => ops.support_resume_range_step().is_some(), BaseOps::MultiThread(ops) => ops.support_range_step().is_some(), } { res.write_str(";r")?; } HandlerStatus::Handled } vCont::Actions(actions) => self.do_vcont(res, target, actions)?, } } // TODO?: support custom resume addr in 'c' and 's' // // unfortunately, this wouldn't be a particularly easy thing to implement, since the // vCont packet doesn't natively support custom resume addresses. This leaves a few // options for the implementation: // // 1. Adding new ResumeActions (i.e: ContinueWithAddr(U) and StepWithAddr(U)) // 2. Automatically calling `read_registers`, updating the `pc`, and calling // `write_registers` prior to resuming. // - will require adding some sort of `get_pc_mut` method to the `Registers` trait. // // Option 1 is easier to implement, but puts more burden on the implementor. Option 2 // will require more effort to implement (and will be less performant), but it will hide // this protocol wart from the end user. // // Oh, one more thought - there's a subtle pitfall to watch out for if implementing // Option 1: if the target is using conditional breakpoints, `do_vcont` has to be // modified to only pass the resume with address variants on the _first_ iteration // through the loop. Base::c(_) => { use crate::protocol::commands::_vCont::Actions; self.do_vcont( res, target, Actions::new_continue(SpecificThreadId { pid: None, tid: self.current_resume_tid, }), )? } Base::s(_) => { use crate::protocol::commands::_vCont::Actions; self.do_vcont( res, target, Actions::new_step(SpecificThreadId { pid: None, tid: self.current_resume_tid, }), )? } // ------------------- Multi-threading Support ------------------ // Base::H(cmd) => { use crate::protocol::commands::_h_upcase::Op; match cmd.kind { Op::Other => match cmd.thread.tid { IdKind::Any => self.current_mem_tid = self.get_sane_any_tid(target)?, // "All" threads doesn't make sense for memory accesses IdKind::All => return Err(Error::PacketUnexpected), IdKind::WithId(tid) => self.current_mem_tid = tid, }, // technically, this variant is deprecated in favor of vCont... Op::StepContinue => match cmd.thread.tid { IdKind::Any => { self.current_resume_tid = SpecificIdKind::WithId(self.get_sane_any_tid(target)?) } IdKind::All => self.current_resume_tid = SpecificIdKind::All, IdKind::WithId(tid) => { self.current_resume_tid = SpecificIdKind::WithId(tid) } }, } HandlerStatus::NeedsOk } Base::qfThreadInfo(_) => { res.write_str("m")?; match target.base_ops() { BaseOps::SingleThread(_) => res.write_specific_thread_id(SpecificThreadId { pid: Some(SpecificIdKind::WithId(FAKE_PID)), tid: SpecificIdKind::WithId(SINGLE_THREAD_TID), })?, BaseOps::MultiThread(ops) => { let mut err: Result<_, Error<T::Error, C::Error>> = Ok(()); let mut first = true; ops.list_active_threads(&mut |tid| { // TODO: replace this with a try block (once stabilized) let e = (|| { if !first { res.write_str(",")? } first = false; res.write_specific_thread_id(SpecificThreadId { pid: Some(SpecificIdKind::WithId(FAKE_PID)), tid: SpecificIdKind::WithId(tid), })?; Ok(()) })(); if let Err(e) = e { err = Err(e) } }) .map_err(Error::TargetError)?; err?; } } HandlerStatus::Handled } Base::qsThreadInfo(_) => { res.write_str("l")?; HandlerStatus::Handled } Base::T(cmd) => { let alive = match cmd.thread.tid { IdKind::WithId(tid) => match target.base_ops() { BaseOps::SingleThread(_) => tid == SINGLE_THREAD_TID, BaseOps::MultiThread(ops) => { ops.is_thread_alive(tid).map_err(Error::TargetError)? } }, // TODO: double-check if GDB ever sends other variants // Even after ample testing, this arm has never been hit... _ => return Err(Error::PacketUnexpected), }; if alive { HandlerStatus::NeedsOk } else { // any error code will do return Err(Error::NonFatalError(1)); } } }; Ok(handler_status) } #[allow(clippy::type_complexity)] fn do_vcont_single_thread( ops: &mut dyn crate::target::ext::base::singlethread::SingleThreadOps< Arch = T::Arch, Error = T::Error, >, res: &mut ResponseWriter<C>, actions: &crate::protocol::commands::_vCont::Actions, ) -> Result<ThreadStopReason<<T::Arch as Arch>::Usize>, Error<T::Error, C::Error>> { use crate::protocol::commands::_vCont::VContKind; let mut err = Ok(()); let mut check_gdb_interrupt = || match res.as_conn().peek() { Ok(Some(0x03)) => true, // 0x03 is the interrupt byte Ok(Some(_)) => false, // it's nothing that can't wait... Ok(None) => false, Err(e) => { err = Err(Error::ConnectionRead(e)); true // break ASAP if a connection error occurred } }; let mut actions = actions.iter(); let first_action = actions .next() .ok_or(Error::PacketParse( crate::protocol::PacketParseError::MalformedCommand, ))? .ok_or(Error::PacketParse( crate::protocol::PacketParseError::MalformedCommand, ))?; let invalid_second_action = match actions.next() { None => false, Some(act) => match act { None => { return Err(Error::PacketParse( crate::protocol::PacketParseError::MalformedCommand, )) } Some(act) => !matches!(act.kind, VContKind::Continue), }, }; if invalid_second_action || actions.next().is_some() { return Err(Error::PacketUnexpected); } let action = match first_action.kind { VContKind::Step => ResumeAction::Step, VContKind::Continue => ResumeAction::Continue, VContKind::StepWithSig(sig) => ResumeAction::StepWithSignal(sig), VContKind::ContinueWithSig(sig) => ResumeAction::ContinueWithSignal(sig), VContKind::RangeStep(start, end) => { if let Some(ops) = ops.support_resume_range_step() { let start = start.decode().map_err(|_| Error::TargetMismatch)?; let end = end.decode().map_err(|_| Error::TargetMismatch)?; let ret = ops .resume_range_step(start, end, GdbInterrupt::new(&mut check_gdb_interrupt)) .map_err(Error::TargetError)? .into(); err?; return Ok(ret); } else { return Err(Error::PacketUnexpected); } } // TODO: update this case when non-stop mode is implemented VContKind::Stop => return Err(Error::PacketUnexpected), }; let ret = ops .resume(action, GdbInterrupt::new(&mut check_gdb_interrupt)) .map_err(Error::TargetError)? .into(); err?; Ok(ret) } #[allow(clippy::type_complexity)] fn do_vcont_multi_thread( ops: &mut dyn crate::target::ext::base::multithread::MultiThreadOps< Arch = T::Arch, Error = T::Error, >, res: &mut ResponseWriter<C>, actions: &crate::protocol::commands::_vCont::Actions, ) -> Result<ThreadStopReason<<T::Arch as Arch>::Usize>, Error<T::Error, C::Error>> { // this is a pretty arbitrary choice, but it seems reasonable for most cases. let mut default_resume_action = ResumeAction::Continue; ops.clear_resume_actions().map_err(Error::TargetError)?; for action in actions.iter() { use crate::protocol::commands::_vCont::VContKind; let action = action.ok_or(Error::PacketParse( crate::protocol::PacketParseError::MalformedCommand, ))?; let resume_action = match action.kind { VContKind::Step => ResumeAction::Step, VContKind::Continue => ResumeAction::Continue, // there seems to be a GDB bug where it doesn't use `vCont` unless // `vCont?` returns support for resuming with a signal. VContKind::StepWithSig(sig) => ResumeAction::StepWithSignal(sig), VContKind::ContinueWithSig(sig) => ResumeAction::ContinueWithSignal(sig), VContKind::RangeStep(start, end) => { if let Some(ops) = ops.support_range_step() { match action.thread.map(|thread| thread.tid) { // An action with no thread-id matches all threads None | Some(SpecificIdKind::All) => { return Err(Error::PacketUnexpected) } Some(SpecificIdKind::WithId(tid)) => { let start = start.decode().map_err(|_| Error::TargetMismatch)?; let end = end.decode().map_err(|_| Error::TargetMismatch)?; ops.set_resume_action_range_step(tid, start, end) .map_err(Error::TargetError)?; continue; } }; } else { return Err(Error::PacketUnexpected); } } // TODO: update this case when non-stop mode is implemented VContKind::Stop => return Err(Error::PacketUnexpected), }; match action.thread.map(|thread| thread.tid) { // An action with no thread-id matches all threads None | Some(SpecificIdKind::All) => default_resume_action = resume_action, Some(SpecificIdKind::WithId(tid)) => ops .set_resume_action(tid, resume_action) .map_err(Error::TargetError)?, }; } let mut err = Ok(()); let mut check_gdb_interrupt = || match res.as_conn().peek() { Ok(Some(0x03)) => true, // 0x03 is the interrupt byte Ok(Some(_)) => false, // it's nothing that can't wait... Ok(None) => false, Err(e) => { err = Err(Error::ConnectionRead(e)); true // break ASAP if a connection error occurred } }; let ret = ops .resume( default_resume_action, GdbInterrupt::new(&mut check_gdb_interrupt), ) .map_err(Error::TargetError)?; err?; Ok(ret) } fn do_vcont( &mut self, res: &mut ResponseWriter<C>, target: &mut T, actions: crate::protocol::commands::_vCont::Actions, ) -> Result<HandlerStatus, Error<T::Error, C::Error>> { loop { let stop_reason = match target.base_ops() { BaseOps::SingleThread(ops) => Self::do_vcont_single_thread(ops, res, &actions)?, BaseOps::MultiThread(ops) => Self::do_vcont_multi_thread(ops, res, &actions)?, }; match self.finish_exec(res, target, stop_reason)? { Some(status) => break Ok(status), None => continue, } } } fn write_break_common( &mut self, res: &mut ResponseWriter<C>, tid: Tid, ) -> Result<(), Error<T::Error, C::Error>> { self.current_mem_tid = tid; self.current_resume_tid = SpecificIdKind::WithId(tid); res.write_str("T05")?; res.write_str("thread:")?; res.write_specific_thread_id(SpecificThreadId { pid: Some(SpecificIdKind::WithId(FAKE_PID)), tid: SpecificIdKind::WithId(tid), })?; res.write_str(";")?; Ok(()) } pub(super) fn finish_exec( &mut self, res: &mut ResponseWriter<C>, target: &mut T, stop_reason: ThreadStopReason<<T::Arch as Arch>::Usize>, ) -> Result<Option<HandlerStatus>, Error<T::Error, C::Error>> { macro_rules! guard_reverse_exec { () => {{ let (reverse_cont, reverse_step) = match target.base_ops() { BaseOps::MultiThread(ops) => ( ops.support_reverse_cont().is_some(), ops.support_reverse_step().is_some(), ), BaseOps::SingleThread(ops) => ( ops.support_reverse_cont().is_some(), ops.support_reverse_step().is_some(), ), }; reverse_cont || reverse_step }}; } macro_rules! guard_break { ($op:ident) => { target.breakpoints().and_then(|ops| ops.$op()).is_some() }; } let status = match stop_reason { ThreadStopReason::DoneStep | ThreadStopReason::GdbInterrupt => { res.write_str("S05")?; HandlerStatus::Handled } ThreadStopReason::Signal(sig) => { res.write_str("S")?; res.write_num(sig)?; HandlerStatus::Handled } ThreadStopReason::Exited(code) => { res.write_str("W")?; res.write_num(code)?; HandlerStatus::Disconnect(DisconnectReason::TargetExited(code)) } ThreadStopReason::Terminated(sig) => { res.write_str("X")?; res.write_num(sig)?; HandlerStatus::Disconnect(DisconnectReason::TargetTerminated(sig)) } ThreadStopReason::SwBreak(tid) if guard_break!(sw_breakpoint) => { crate::__dead_code_marker!("sw_breakpoint", "stop_reason"); self.write_break_common(res, tid)?; res.write_str("swbreak:;")?; HandlerStatus::Handled } ThreadStopReason::HwBreak(tid) if guard_break!(hw_breakpoint) => { crate::__dead_code_marker!("hw_breakpoint", "stop_reason"); self.write_break_common(res, tid)?; res.write_str("hwbreak:;")?; HandlerStatus::Handled } ThreadStopReason::Watch { tid, kind, addr } if guard_break!(hw_watchpoint) => { crate::__dead_code_marker!("hw_watchpoint", "stop_reason"); self.write_break_common(res, tid)?; use crate::target::ext::breakpoints::WatchKind; match kind { WatchKind::Write => res.write_str("watch:")?, WatchKind::Read => res.write_str("rwatch:")?, WatchKind::ReadWrite => res.write_str("awatch:")?, } res.write_num(addr)?; res.write_str(";")?; HandlerStatus::Handled } ThreadStopReason::ReplayLog(pos) if guard_reverse_exec!() => { crate::__dead_code_marker!("reverse_exec", "stop_reason"); res.write_str("T05")?; res.write_str("replaylog:")?; res.write_str(match pos { ReplayLogPosition::Begin => "begin", ReplayLogPosition::End => "end", })?; res.write_str(";")?; HandlerStatus::Handled } _ => return Err(Error::UnsupportedStopReason), }; Ok(Some(status)) } } use crate::target::ext::base::singlethread::StopReason; impl<U> From<StopReason<U>> for ThreadStopReason<U> { fn from(st_stop_reason: StopReason<U>) -> ThreadStopReason<U> { match st_stop_reason { StopReason::DoneStep => ThreadStopReason::DoneStep, StopReason::GdbInterrupt => ThreadStopReason::GdbInterrupt, StopReason::Exited(code) => ThreadStopReason::Exited(code), StopReason::Terminated(sig) => ThreadStopReason::Terminated(sig), StopReason::SwBreak => ThreadStopReason::SwBreak(SINGLE_THREAD_TID), StopReason::HwBreak => ThreadStopReason::HwBreak(SINGLE_THREAD_TID), StopReason::Watch { kind, addr } => ThreadStopReason::Watch { tid: SINGLE_THREAD_TID, kind, addr, }, StopReason::Signal(sig) => ThreadStopReason::Signal(sig), StopReason::ReplayLog(pos) => ThreadStopReason::ReplayLog(pos), } } }
41.938503
102
0.468601
332b06d3da7881ae8674cca44cb93f62d984c2bc
880
// DLEQ proof through g^a use crypto::*; type Challenge = Scalar; #[derive(Clone)] pub struct DLEQ { pub g1: Point, pub h1: Point, pub g2: Point, pub h2: Point, } #[derive(Clone, Serialize, Deserialize, PartialEq)] pub struct Proof { c: Challenge, z: Scalar, } impl Proof { pub fn create(w: Scalar, a: Scalar, dleq: DLEQ) -> Proof { let a1 = dleq.g1.mul(&w); let a2 = dleq.g2.mul(&w); let c = Scalar::hash_points(vec![dleq.h1, dleq.h2, a1, a2]); let r = w + a * c.clone(); return Proof { c: c, z: r }; } pub fn verify(&self, dleq: DLEQ) -> bool { let r1 = dleq.g1.mul(&self.z); let r2 = dleq.g2.mul(&self.z); let a1 = r1 - dleq.h1.mul(&self.c); let a2 = r2 - dleq.h2.mul(&self.c); return self.c == Scalar::hash_points(vec![dleq.h1, dleq.h2, a1, a2]); } }
23.783784
77
0.544318
e4533071eb549a17ea29de57ed7f2eebd2592c2b
21,059
use std::{collections::HashMap, num::NonZeroUsize}; use bytes::{Bytes, BytesMut}; use futures::{stream::BoxStream, StreamExt}; use once_cell::sync::Lazy; use regex::Regex; use snafu::Snafu; use tokio_util::codec::Encoder as _; use vector_core::{ buffers::Acker, event::{self, Event, EventFinalizers, Finalizable, Value}, partition::Partitioner, sink::StreamSink, stream::BatcherSettings, ByteSizeOf, }; use super::{ config::{LokiConfig, OutOfOrderAction}, event::{LokiBatchEncoder, LokiEvent, LokiRecord, PartitionKey}, service::{LokiRequest, LokiRetryLogic, LokiService}, }; use crate::{ codecs::Encoder, config::{log_schema, SinkContext}, http::HttpClient, internal_events::{ LokiEventUnlabeled, LokiOutOfOrderEventDropped, LokiOutOfOrderEventRewritten, TemplateRenderingError, }, sinks::util::{ builder::SinkBuilderExt, encoding::Transformer, request_builder::EncodeResult, service::{ServiceBuilderExt, Svc}, Compression, RequestBuilder, }, template::Template, }; #[derive(Clone)] pub struct KeyPartitioner(Option<Template>); impl KeyPartitioner { pub const fn new(template: Option<Template>) -> Self { Self(template) } } impl Partitioner for KeyPartitioner { type Item = Event; type Key = Option<String>; fn partition(&self, item: &Self::Item) -> Self::Key { self.0.as_ref().and_then(|t| { t.render_string(item) .map_err(|error| { emit!(TemplateRenderingError { error, field: Some("tenant_id"), drop_event: false, }) }) .ok() }) } } #[derive(Default)] struct RecordPartitioner; impl Partitioner for RecordPartitioner { type Item = Option<FilteredRecord>; type Key = Option<PartitionKey>; fn partition(&self, item: &Self::Item) -> Self::Key { item.as_ref().map(|inner| inner.partition()) } } #[derive(Clone)] pub struct LokiRequestBuilder { compression: Compression, encoder: LokiBatchEncoder, } #[derive(Debug, Snafu)] pub enum RequestBuildError { #[snafu(display("Encoded payload is greater than the max limit."))] PayloadTooBig, #[snafu(display("Failed to build payload with error: {}", error))] Io { error: std::io::Error }, } impl From<std::io::Error> for RequestBuildError { fn from(error: std::io::Error) -> RequestBuildError { RequestBuildError::Io { error } } } impl RequestBuilder<(PartitionKey, Vec<LokiRecord>)> for LokiRequestBuilder { type Metadata = (Option<String>, usize, EventFinalizers, usize); type Events = Vec<LokiRecord>; type Encoder = LokiBatchEncoder; type Payload = Bytes; type Request = LokiRequest; type Error = RequestBuildError; fn compression(&self) -> Compression { self.compression } fn encoder(&self) -> &Self::Encoder { &self.encoder } fn split_input( &self, input: (PartitionKey, Vec<LokiRecord>), ) -> (Self::Metadata, Self::Events) { let (key, mut events) = input; let batch_size = events.len(); let events_byte_size = events.size_of(); let finalizers = events .iter_mut() .fold(EventFinalizers::default(), |mut acc, x| { acc.merge(x.take_finalizers()); acc }); ( (key.tenant_id, batch_size, finalizers, events_byte_size), events, ) } fn build_request( &self, metadata: Self::Metadata, payload: EncodeResult<Self::Payload>, ) -> Self::Request { let (tenant_id, batch_size, finalizers, events_byte_size) = metadata; let compression = self.compression(); LokiRequest { compression, batch_size, finalizers, payload: payload.into_payload(), tenant_id, events_byte_size, } } } #[derive(Clone)] pub(super) struct EventEncoder { key_partitioner: KeyPartitioner, transformer: Transformer, encoder: Encoder<()>, labels: HashMap<Template, Template>, remove_label_fields: bool, remove_timestamp: bool, } impl EventEncoder { fn build_labels(&self, event: &Event) -> Vec<(String, String)> { let mut vec: Vec<(String, String)> = Vec::new(); for (key_template, value_template) in self.labels.iter() { if let (Ok(key), Ok(value)) = ( key_template.render_string(event), value_template.render_string(event), ) { if let Some(opening_prefix) = key.strip_suffix('*') { let output: Result<serde_json::map::Map<String, serde_json::Value>, _> = serde_json::from_str(value.as_str()); if let Ok(output) = output { // key_* -> key_one, key_two, key_three for (k, v) in output { vec.push(( slugify_text(format!("{}{}", opening_prefix, k)), Value::from(v).to_string_lossy(), )) } } } else { vec.push((key, value)); } } } vec } fn remove_label_fields(&self, event: &mut Event) { if self.remove_label_fields { for template in self.labels.values() { if let Some(fields) = template.get_fields() { for field in fields { event.as_mut_log().remove(field.as_str()); } } } } } pub(super) fn encode_event(&mut self, mut event: Event) -> Option<LokiRecord> { let tenant_id = self.key_partitioner.partition(&event); let finalizers = event.take_finalizers(); let mut labels = self.build_labels(&event); self.remove_label_fields(&mut event); let schema = log_schema(); let timestamp_key = schema.timestamp_key(); let timestamp = match event.as_log().get(timestamp_key) { Some(event::Value::Timestamp(ts)) => ts.timestamp_nanos(), _ => chrono::Utc::now().timestamp_nanos(), }; if self.remove_timestamp { event.as_mut_log().remove(timestamp_key); } self.transformer.transform(&mut event); let mut bytes = BytesMut::new(); self.encoder.encode(event, &mut bytes).ok(); // If no labels are provided we set our own default // `{agent="vector"}` label. This can happen if the only // label is a templatable one but the event doesn't match. if labels.is_empty() { emit!(LokiEventUnlabeled); labels = vec![("agent".to_string(), "vector".to_string())] } let partition = PartitionKey::new(tenant_id, &mut labels); Some(LokiRecord { labels, event: LokiEvent { timestamp, event: bytes.freeze(), }, partition, finalizers, }) } } struct FilteredRecord { pub rewritten: bool, pub inner: LokiRecord, } impl FilteredRecord { pub const fn rewritten(inner: LokiRecord) -> Self { Self { rewritten: true, inner, } } pub const fn valid(inner: LokiRecord) -> Self { Self { rewritten: false, inner, } } pub fn partition(&self) -> PartitionKey { self.inner.partition.clone() } } impl ByteSizeOf for FilteredRecord { fn allocated_bytes(&self) -> usize { self.inner.allocated_bytes() } fn size_of(&self) -> usize { self.inner.size_of() } } struct RecordFilter { timestamps: HashMap<PartitionKey, i64>, out_of_order_action: OutOfOrderAction, } impl RecordFilter { fn new(out_of_order_action: OutOfOrderAction) -> Self { Self { timestamps: HashMap::new(), out_of_order_action, } } } impl RecordFilter { pub fn filter_record(&mut self, mut record: LokiRecord) -> Option<FilteredRecord> { if let Some(latest) = self.timestamps.get_mut(&record.partition) { if record.event.timestamp < *latest { match self.out_of_order_action { OutOfOrderAction::Drop => None, OutOfOrderAction::RewriteTimestamp => { record.event.timestamp = *latest; Some(FilteredRecord::rewritten(record)) } OutOfOrderAction::Accept => Some(FilteredRecord::valid(record)), } } else { *latest = record.event.timestamp; Some(FilteredRecord::valid(record)) } } else { self.timestamps .insert(record.partition.clone(), record.event.timestamp); Some(FilteredRecord::valid(record)) } } } pub struct LokiSink { acker: Acker, request_builder: LokiRequestBuilder, pub(super) encoder: EventEncoder, batch_settings: BatcherSettings, out_of_order_action: OutOfOrderAction, service: Svc<LokiService, LokiRetryLogic>, } impl LokiSink { #[allow(clippy::missing_const_for_fn)] // const cannot run destructor pub fn new(config: LokiConfig, client: HttpClient, cx: SinkContext) -> crate::Result<Self> { let compression = config.compression; // if Vector is configured to allow events with out of order timestamps, then then we can // safely enable concurrency settings. // // For rewritten timestamps, we use a static concurrency of 1 to avoid out-of-order // timestamps across requests. We used to support concurrency across partitions (Loki // streams) but this was lost in #9506. Rather than try to re-add it, since Loki no longer // requires in-order processing for version >= 2.4, instead we just keep the static limit // of 1 for now. let request_limits = match config.out_of_order_action { OutOfOrderAction::Accept => config.request.unwrap_with(&Default::default()), OutOfOrderAction::Drop | OutOfOrderAction::RewriteTimestamp => { let mut settings = config.request.unwrap_with(&Default::default()); settings.concurrency = Some(1); settings } }; let service = tower::ServiceBuilder::new() .settings(request_limits, LokiRetryLogic) .service(LokiService::new(client, config.endpoint, config.auth)?); let transformer = config.encoding.transformer(); let serializer = config.encoding.encoding(); let encoder = Encoder::<()>::new(serializer); Ok(Self { acker: cx.acker(), request_builder: LokiRequestBuilder { compression, encoder: Default::default(), }, encoder: EventEncoder { key_partitioner: KeyPartitioner::new(config.tenant_id), transformer, encoder, labels: config.labels, remove_label_fields: config.remove_label_fields, remove_timestamp: config.remove_timestamp, }, batch_settings: config.batch.into_batcher_settings()?, out_of_order_action: config.out_of_order_action, service, }) } async fn run_inner(self: Box<Self>, input: BoxStream<'_, Event>) -> Result<(), ()> { let mut encoder = self.encoder.clone(); let mut filter = RecordFilter::new(self.out_of_order_action); // out_of_order_action's that require a complete ordering are limited to building 1 request // at a time let request_builder_concurrency = match self.out_of_order_action { OutOfOrderAction::Accept => NonZeroUsize::new(50).expect("static"), OutOfOrderAction::Drop | OutOfOrderAction::RewriteTimestamp => { NonZeroUsize::new(1).expect("static") } }; let sink = input .map(|event| encoder.encode_event(event)) .filter_map(|event| async { event }) .map(|record| filter.filter_record(record)) .batched_partitioned(RecordPartitioner::default(), self.batch_settings) .filter_map(|(partition, batch)| async { if let Some(partition) = partition { let mut count: usize = 0; let result = batch .into_iter() .flatten() .map(|event| { if event.rewritten { count += 1; } event.inner }) .collect::<Vec<_>>(); if count > 0 { emit!(LokiOutOfOrderEventRewritten { count }); } Some((partition, result)) } else { emit!(LokiOutOfOrderEventDropped { count: batch.len() }); None } }) .request_builder(Some(request_builder_concurrency), self.request_builder) .filter_map(|request| async move { match request { Err(e) => { error!("Failed to build Loki request: {:?}.", e); None } Ok(req) => Some(req), } }) .into_driver(self.service, self.acker); sink.run().await } } #[async_trait::async_trait] impl StreamSink<Event> for LokiSink { async fn run(mut self: Box<Self>, input: BoxStream<'_, Event>) -> Result<(), ()> { self.run_inner(input).await } } static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"[^0-9A-Za-z_]").unwrap()); fn slugify_text(input: String) -> String { let result = RE.replace_all(&input, "_"); result.to_lowercase() } #[cfg(test)] mod tests { use std::{ collections::{BTreeMap, HashMap}, convert::TryFrom, }; use codecs::JsonSerializer; use futures::stream::StreamExt; use vector_core::event::{Event, Value}; use super::{EventEncoder, KeyPartitioner, RecordFilter}; use crate::{ codecs::Encoder, config::log_schema, sinks::loki::config::OutOfOrderAction, template::Template, test_util::random_lines, }; #[test] fn encoder_no_labels() { let mut encoder = EventEncoder { key_partitioner: KeyPartitioner::new(None), transformer: Default::default(), encoder: Encoder::<()>::new(JsonSerializer::new().into()), labels: HashMap::default(), remove_label_fields: false, remove_timestamp: false, }; let mut event = Event::from("hello world"); let log = event.as_mut_log(); log.insert(log_schema().timestamp_key(), chrono::Utc::now()); let record = encoder.encode_event(event).unwrap(); assert!(String::from_utf8_lossy(&record.event.event).contains(log_schema().timestamp_key())); assert_eq!(record.labels.len(), 1); assert_eq!( record.labels[0], ("agent".to_string(), "vector".to_string()) ); } #[test] fn encoder_with_labels() { let mut labels = HashMap::default(); labels.insert( Template::try_from("static").unwrap(), Template::try_from("value").unwrap(), ); labels.insert( Template::try_from("{{ name }}").unwrap(), Template::try_from("{{ value }}").unwrap(), ); labels.insert( Template::try_from("test_key_*").unwrap(), Template::try_from("{{ dict }}").unwrap(), ); labels.insert( Template::try_from("going_to_fail_*").unwrap(), Template::try_from("{{ value }}").unwrap(), ); let mut encoder = EventEncoder { key_partitioner: KeyPartitioner::new(None), transformer: Default::default(), encoder: Encoder::<()>::new(JsonSerializer::new().into()), labels, remove_label_fields: false, remove_timestamp: false, }; let mut event = Event::from("hello world"); let log = event.as_mut_log(); log.insert(log_schema().timestamp_key(), chrono::Utc::now()); log.insert("name", "foo"); log.insert("value", "bar"); let mut test_dict = BTreeMap::default(); test_dict.insert("one".to_string(), Value::from("foo")); test_dict.insert("two".to_string(), Value::from("baz")); log.insert("dict", Value::from(test_dict)); let record = encoder.encode_event(event).unwrap(); assert!(String::from_utf8_lossy(&record.event.event).contains(log_schema().timestamp_key())); assert_eq!(record.labels.len(), 4); let labels: HashMap<String, String> = record.labels.into_iter().collect(); assert_eq!(labels["static"], "value".to_string()); assert_eq!(labels["foo"], "bar".to_string()); assert_eq!(labels["test_key_one"], "foo".to_string()); assert_eq!(labels["test_key_two"], "baz".to_string()); } #[test] fn encoder_no_ts() { let mut encoder = EventEncoder { key_partitioner: KeyPartitioner::new(None), transformer: Default::default(), encoder: Encoder::<()>::new(JsonSerializer::new().into()), labels: HashMap::default(), remove_label_fields: false, remove_timestamp: true, }; let mut event = Event::from("hello world"); let log = event.as_mut_log(); log.insert(log_schema().timestamp_key(), chrono::Utc::now()); let record = encoder.encode_event(event).unwrap(); assert!( !String::from_utf8_lossy(&record.event.event).contains(log_schema().timestamp_key()) ); } #[test] fn encoder_no_record_labels() { let mut labels = HashMap::default(); labels.insert( Template::try_from("static").unwrap(), Template::try_from("value").unwrap(), ); labels.insert( Template::try_from("{{ name }}").unwrap(), Template::try_from("{{ value }}").unwrap(), ); let mut encoder = EventEncoder { key_partitioner: KeyPartitioner::new(None), transformer: Default::default(), encoder: Encoder::<()>::new(JsonSerializer::new().into()), labels, remove_label_fields: true, remove_timestamp: false, }; let mut event = Event::from("hello world"); let log = event.as_mut_log(); log.insert(log_schema().timestamp_key(), chrono::Utc::now()); log.insert("name", "foo"); log.insert("value", "bar"); let record = encoder.encode_event(event).unwrap(); assert!(!String::from_utf8_lossy(&record.event.event).contains("value")); } #[tokio::test] async fn filter_encoder_drop() { let mut encoder = EventEncoder { key_partitioner: KeyPartitioner::new(None), transformer: Default::default(), encoder: Encoder::<()>::new(JsonSerializer::new().into()), labels: HashMap::default(), remove_label_fields: false, remove_timestamp: false, }; let base = chrono::Utc::now(); let events = random_lines(100) .take(20) .map(Event::from) .enumerate() .map(|(i, mut event)| { let log = event.as_mut_log(); let ts = if i % 5 == 1 { base } else { base + chrono::Duration::seconds(i as i64) }; log.insert(log_schema().timestamp_key(), ts); event }) .collect::<Vec<_>>(); let mut filter = RecordFilter::new(OutOfOrderAction::Drop); let stream = futures::stream::iter(events) .map(|event| encoder.encode_event(event)) .filter_map(|event| async { event }) .filter_map(|event| { let res = filter.filter_record(event); async { res } }); tokio::pin!(stream); let mut result = Vec::new(); while let Some(item) = stream.next().await { result.push(item); } assert_eq!(result.len(), 17); } }
33.426984
101
0.551878
284f1c6d4e9e334090543feb02f2788ab42dd2a8
19,900
#[macro_use] extern crate nom; use nom::{IResult,digit,alphanumeric,anychar,is_alphanumeric}; use std::str; use std::str::FromStr; #[derive(Debug)] #[derive(PartialEq)] #[derive(Clone)] pub struct Equation { pub left: Operand, pub right: Operand, } #[derive(Debug)] #[derive(PartialEq)] #[derive(Clone)] pub struct Function { pub function: String, pub params: Vec<Operand>, } #[derive(Debug)] #[derive(PartialEq)] #[derive(Clone)] pub enum Operand { Column(String), Function(Function), Number(f64), Boolean(bool), Value(String), } #[derive(Debug)] #[derive(PartialEq)] #[derive(Clone)] pub enum Connector { AND, OR, } #[derive(Debug)] #[derive(PartialEq)] #[derive(Clone)] pub enum Direction { ASC, DESC, } #[derive(Debug)] #[derive(PartialEq)] #[derive(Clone)] pub enum NullsWhere { FIRST, LAST, } #[derive(Debug)] #[derive(PartialEq)] #[derive(Clone)] pub struct Order { pub operand: Operand, pub direction: Option<Direction>, pub nulls_where: Option<NullsWhere>, } #[derive(Debug)] #[derive(PartialEq)] #[derive(Clone)] pub enum Equality { EQ, // = , eq NEQ, // != , neq LT, // <, lt LTE, // <=, lte GT, // >, gt GTE, // >=, gte IN, // IN, in NOT_IN, // NOT IN, not_in IS, // IS, is IS_NOT, // IS NOT, is_not LIKE, // LIKE, like ILIKE, // ILIKE case insensitive like, postgresql specific ST // Starts with, which will become ILIKE 'value%' } #[derive(Debug)] #[derive(PartialEq)] #[derive(Clone)] pub struct Condition { pub left: Operand, pub equality: Equality, pub right: Operand, } #[derive(Debug)] #[derive(PartialEq)] #[derive(Clone)] enum Param{ Condition(Condition), Equation(Equation) } #[derive(Debug)] #[derive(PartialEq)] #[derive(Clone)] pub struct Filter { pub condition: Condition, /// the filter's condition will use this connector to connect to the rest of the filters (sub_filters) pub connector: Option<Connector>, pub sub_filters: Vec<Filter>, } #[derive(Debug)] #[derive(PartialEq)] #[derive(Default)] #[derive(Clone)] pub struct Query { pub from: Vec<Operand>, pub join: Vec<Join>, pub filters: Vec<Filter>, pub group_by: Vec<Operand>, pub having: Vec<Filter>, pub order_by: Vec<Order>, pub range: Option<Range>, pub equations: Vec<Equation>, } #[derive(Debug)] #[derive(PartialEq)] #[derive(Default)] #[derive(Clone)] pub struct Page { pub page: i64, pub page_size: i64, } #[derive(Debug)] #[derive(PartialEq)] #[derive(Default)] #[derive(Clone)] pub struct Limit { pub limit: i64, pub offset: Option<i64>, } #[derive(Debug)] #[derive(PartialEq)] #[derive(Clone)] pub enum Range { Page(Page), Limit(Limit), } #[derive(Debug)] #[derive(PartialEq)] #[derive(Clone)] pub enum JoinType { CROSS, INNER, OUTER, NATURAL, } #[derive(Debug)] #[derive(PartialEq)] #[derive(Clone)] pub enum Modifier { LEFT, RIGHT, FULL, } #[derive(Debug)] #[derive(PartialEq)] #[derive(Clone)] pub struct Join { pub modifier: Option<Modifier>, pub join_type: Option<JoinType>, pub table: Operand, pub column1: Vec<String>, pub column2: Vec<String>, } fn main() { println!("Hello, world!"); } named!(value<&str>, map_res!(complete!(recognize!(many1!(is_not_s!(")")))) ,str::from_utf8 ) ); named!(column<&str>, map_res!(recognize!(many1!(one_of!("abcdefghijklmnopqrstuvwxyz0123456789_"))) ,str::from_utf8 ) ); /* named!(column <&str>, map_res!( complete!(alphanumeric), str::from_utf8 ) ); */ named!(boolean <bool>, alt!(tag!("true") => {|_| true} | tag!("false") => {|_| false} ) ); named!(number<i64>, map_res!( map_res!( ws!(digit), str::from_utf8 ), FromStr::from_str ) ); named!(operand <Operand>, alt_complete!( float => {|f| Operand::Number(f as f64)} | boolean => {|b| Operand::Boolean(b) } | //column => {|c:&str| Operand::Column(c.to_string())} | //NOTE: assume the right value to be value, and the left to be always column value => {|v:&str| Operand::Value(v.to_string())} ) ); named!(equality<Equality>, alt!(tag!("eq") => {|_| Equality::EQ} | tag!("neq") => {|_| Equality::NEQ} | tag!("lt") => {|_| Equality::LT} | tag!("lte") => {|_| Equality::LTE} | tag!("gt") => {|_| Equality::GT} | tag!("gte") => {|_| Equality::GTE} | tag!("in") => {|_| Equality::IN} | tag!("not_in") => {|_| Equality::NOT_IN} | tag!("is") => {|_| Equality::IS} | tag!("is_not") => {|_| Equality::IS_NOT} | tag!("like") => {|_| Equality::LIKE} | tag!("ilike") => {|_| Equality::ILIKE} | tag!("st") => {|_| Equality::ST} ) ); named!(connector <Connector>, alt!(tag!("&") => {|_| Connector::AND} | tag!("|") => {|_| Connector::OR} ) ); named!(param <Param>, alt!(condition => {|c| Param::Condition(c)}| equation => {|e| Param::Equation(e)} ) ); fn fold_conditions(initial: Condition, remainder: Vec<(Connector, Condition)>) -> Filter{ let mut sub_filters = vec![]; for (conn, cond) in remainder{ let sub_filter = Filter{ connector: Some(conn), condition: cond, sub_filters: vec![] }; sub_filters.push(sub_filter); } Filter{ connector: None, condition: initial, sub_filters: sub_filters } } named!(filter <Filter>, do_parse!( initial: condition_expr >> remainder: many0!( do_parse!(conn: connector >> cond: condition_expr >> (conn, cond) ) ) >> (fold_conditions(initial, remainder)) ) ); named!(filter_expr <Filter>, alt_complete!(filter | delimited!(tag!("("), filter_expr, tag!(")"))) ); named!(params < Vec<Param> >, separated_list!(tag!("&"), param) ); named!(equation <Equation>, map!(separated_pair!(column, tag!("="), operand ), |(col,op):(&str,Operand)|{ Equation{ left: Operand::Column(col.to_string()), right: op } } ) ); named!(condition <Condition>, map!(tuple!( column, tag!("="), equality, tag!("."), operand ), |(col,_,eq,_,op):(&str,_,Equality,_,Operand)|{ Condition{ left: Operand::Column(col.to_string()), equality: eq, right: op } } ) ); named!(condition_expr <Condition>, alt_complete!(condition | complete!(delimited!(tag!("("), condition_expr, tag!(")")))) ); named!(unsigned_float <f64>, map_res!( map_res!( recognize!( alt_complete!( delimited!(digit, tag!("."), opt!(complete!(digit))) | delimited!(opt!(digit), tag!("."), complete!(digit)) | complete!(digit) ) ), str::from_utf8 ), FromStr::from_str )); named!(float <f64>, map!( pair!( opt!(alt!(tag!("+") | tag!("-"))), unsigned_float ), |(sign, value): (Option<&[u8]>, f64)| { sign.and_then(|s| if s[0] == ('-' as u8) { Some(-1f64) } else { None }).unwrap_or(1f64) * value } )); #[test] fn test_identifier(){ assert_eq!(column("ahello".as_bytes()), IResult::Done(&b""[..],"ahello")); assert_eq!(column("hello_".as_bytes()), IResult::Done(&b""[..],"hello_")); assert_eq!(column("hello1".as_bytes()), IResult::Done(&b""[..],"hello1")); } #[test] fn test_value(){ assert_eq!(value("hello world!".as_bytes()), IResult::Done(&b""[..],"hello world!")); assert_eq!(value("技術通報".as_bytes()), IResult::Done(&b""[..],"技術通報")); } #[test] fn test_param(){ assert_eq!(param(&b"product=eq.134"[..]), IResult::Done(&b""[..], Param::Condition(Condition{ left: Operand::Column("product".to_string()), equality: Equality::EQ, right: Operand::Number(134f64) } ))); assert_eq!(param(&b"product=134"[..]), IResult::Done(&b""[..], Param::Equation(Equation{ left: Operand::Column("product".to_string()), right: Operand::Number(134f64) } ))); } #[test] fn test_params(){ assert_eq!(params(&b"product=eq.134"[..]), IResult::Done(&b""[..], vec![Param::Condition(Condition{ left: Operand::Column("product".to_string()), equality: Equality::EQ, right: Operand::Number(134f64) })] )); assert_eq!(params(&b"product=eq.134&page=2"[..]), IResult::Done(&b""[..], vec![Param::Condition(Condition{ left: Operand::Column("product".to_string()), equality: Equality::EQ, right: Operand::Number(134f64) }), Param::Equation(Equation{ left: Operand::Column("page".to_string()), right: Operand::Number(2f64) }) ] )); } // (filter)&condition wont match #[test] fn test_filter_issue1(){ assert_eq!(filter(&b"age=lt.20&product=eq.134&price=lt.100.0"[..]), IResult::Done(&b""[..], Filter{ connector: None, condition: Condition{ left: Operand::Column("age".to_string()), equality: Equality::LT, right: Operand::Number(20f64) }, sub_filters:vec![ Filter{ condition:Condition{ left: Operand::Column("product".to_string()), equality: Equality::EQ, right: Operand::Number(134f64) }, connector: Some(Connector::AND), sub_filters: vec![ ] }, Filter{ connector: Some(Connector::AND), condition: Condition{ left: Operand::Column("price".to_string()), equality: Equality::LT, right: Operand::Number(100.0) }, sub_filters: vec![] } ] } )); } // (filter)&(filter) wont match //#[test] fn test_filter_issue2(){ } #[test] fn test_filters(){ assert_eq!(filter(&b"product=eq.134"[..]), IResult::Done(&b""[..], Filter{ connector: None, condition:Condition{ left: Operand::Column("product".to_string()), equality: Equality::EQ, right: Operand::Number(134f64) }, sub_filters: vec![] } )); assert_eq!(filter(&b"product=eq.134&price=lt.100.0"[..]), IResult::Done(&b""[..], Filter{ condition:Condition{ left: Operand::Column("product".to_string()), equality: Equality::EQ, right: Operand::Number(134f64) }, connector: None, sub_filters: vec![ Filter{ connector: Some(Connector::AND), condition: Condition{ left: Operand::Column("price".to_string()), equality: Equality::LT, right: Operand::Number(100.0) }, sub_filters: vec![] } ] } )); assert_eq!(filter(&b"product=eq.134|price=lt.100.0"[..]), IResult::Done(&b""[..], Filter{ condition:Condition{ left: Operand::Column("product".to_string()), equality: Equality::EQ, right: Operand::Number(134f64) }, connector: None, sub_filters: vec![ Filter{ connector: Some(Connector::OR), condition: Condition{ left: Operand::Column("price".to_string()), equality: Equality::LT, right: Operand::Number(100.0) }, sub_filters: vec![] } ] } )); assert_eq!(filter_expr(&b"(product=eq.134|price=lt.100.0)"[..]), IResult::Done(&b""[..], Filter{ condition:Condition{ left: Operand::Column("product".to_string()), equality: Equality::EQ, right: Operand::Number(134f64) }, connector: None, sub_filters: vec![ Filter{ connector: Some(Connector::OR), condition: Condition{ left: Operand::Column("price".to_string()), equality: Equality::LT, right: Operand::Number(100.0) }, sub_filters: vec![] } ] } )); } #[test] fn test_paren_filter_exprs(){ assert_eq!(filter_expr(&b"(product=eq.134)|(price=lt.100.0)"[..]), IResult::Done(&b""[..], Filter{ condition:Condition{ left: Operand::Column("product".to_string()), equality: Equality::EQ, right: Operand::Number(134f64) }, connector: None, sub_filters: vec![ Filter{ condition: Condition{ left: Operand::Column("price".to_string()), equality: Equality::LT, right: Operand::Number(100.0) }, connector: Some(Connector::OR), sub_filters: vec![] } ] } )); assert_eq!(filter_expr(&b"age=lt.20&(product=eq.134|price=lt.100.0)"[..]), IResult::Done(&b""[..], Filter{ condition: Condition{ left: Operand::Column("age".to_string()), equality: Equality::LT, right: Operand::Number(20f64) }, connector: None, sub_filters:vec![ Filter{ condition:Condition{ left: Operand::Column("product".to_string()), equality: Equality::EQ, right: Operand::Number(134f64) }, connector: Some(Connector::OR), sub_filters: vec![ Filter{ connector: None, condition: Condition{ left: Operand::Column("price".to_string()), equality: Equality::LT, right: Operand::Number(100.0) }, sub_filters: vec![] } ] } ] } )); } #[test] fn test_boolean(){ assert_eq!(boolean(&b"true"[..]), IResult::Done(&b""[..], true)); assert_eq!(boolean(&b"false"[..]), IResult::Done(&b""[..], false)); } #[test] fn test_cond(){ assert_eq!(condition(&b"product=eq.134"[..]), IResult::Done(&b""[..], Condition{ left: Operand::Column("product".to_string()), equality: Equality::EQ, right: Operand::Number(134f64) } )); assert_eq!(condition(&b"active=eq.true"[..]), IResult::Done(&b""[..], Condition{ left: Operand::Column("active".to_string()), equality: Equality::EQ, right: Operand::Boolean(true) } )); assert_eq!(condition(&b"price=lt.-0.3"[..]), IResult::Done(&b""[..], Condition{ left: Operand::Column("price".to_string()), equality: Equality::LT, right: Operand::Number(-0.3) } )); assert_eq!(condition(&b"name=st.John"[..]), IResult::Done(&b""[..], Condition{ left: Operand::Column("name".to_string()), equality: Equality::ST, right: Operand::Value("John".to_string()) } )); assert_eq!(condition(&b"name=st.John Cena"[..]), IResult::Done(&b""[..], Condition{ left: Operand::Column("name".to_string()), equality: Equality::ST, right: Operand::Value("John Cena".to_string()) } )); assert_eq!(condition_expr(&b"(name=st.John)"[..]), IResult::Done(&b""[..], Condition{ left: Operand::Column("name".to_string()), equality: Equality::ST, right: Operand::Value("John".to_string()) } )); assert_eq!(condition_expr(&b"((name=st.John))"[..]), IResult::Done(&b""[..], Condition{ left: Operand::Column("name".to_string()), equality: Equality::ST, right: Operand::Value("John".to_string()) } )); assert_eq!(condition("name=st.技術通".as_bytes()), IResult::Done(&b""[..], Condition{ left: Operand::Column("name".to_string()), equality: Equality::ST, right: Operand::Value("技術通".to_string()) } )); assert_eq!(condition("name=ilike.*° ͜ʖ ͡°*".as_bytes()), IResult::Done(&b""[..], Condition{ left: Operand::Column("name".to_string()), equality: Equality::ILIKE, right: Operand::Value("*° ͜ʖ ͡°*".to_string()) } )); } #[test] fn test_equality(){ assert_eq!(equality(&b"eq"[..]), IResult::Done(&b""[..], Equality::EQ)); assert_eq!(equality(&b"neq"[..]), IResult::Done(&b""[..], Equality::NEQ)); assert_eq!(equality(&b"st"[..]), IResult::Done(&b""[..], Equality::ST)); assert_eq!(equality(&b"ilike"[..]), IResult::Done(&b""[..], Equality::ILIKE)); } #[test] fn test_operand() { assert_eq!(operand(&b"product"[..]), IResult::Done(&b""[..],Operand::Value("product".to_string()))); assert_eq!(operand(&b"1234"[..]), IResult::Done(&b""[..],Operand::Number(1234f64))); assert_eq!(operand(&b"true"[..]), IResult::Done(&b""[..],Operand::Boolean(true))); assert_eq!(operand(&b"false"[..]), IResult::Done(&b""[..],Operand::Boolean(false))); // half match? //assert_eq!(operand(&b"true false"[..]), // IResult::Done(&b""[..],Operand::Column("true false".to_string()))); assert_eq!(operand(&b"Hello world!"[..]), IResult::Done(&b""[..],Operand::Value("Hello world!".to_string()))); assert_eq!(operand(&b"hello world!"[..]), IResult::Done(&b""[..],Operand::Value("hello world!".to_string()))); } #[test] fn test_column() { assert_eq!(column(&b"product"[..]), IResult::Done(&b""[..], "product")); //assert_eq!(column(&b"product_id"[..]), IResult::Done(&b""[..], "product_id")); } #[test] fn unsigned_float_test() { assert_eq!(unsigned_float(&b"123.456"[..]), IResult::Done(&b""[..], 123.456)); assert_eq!(unsigned_float(&b"0.123"[..]), IResult::Done(&b""[..], 0.123)); assert_eq!(unsigned_float(&b"123.0"[..]), IResult::Done(&b""[..], 123.0)); assert_eq!(unsigned_float(&b"123."[..]), IResult::Done(&b""[..], 123.0)); assert_eq!(unsigned_float(&b".123"[..]), IResult::Done(&b""[..], 0.123)); assert_eq!(unsigned_float(&b"123456"[..]), IResult::Done(&b""[..], 123456f64)); } #[test] fn float_test() { assert_eq!(float(&b"123.456"[..]), IResult::Done(&b""[..], 123.456)); assert_eq!(float(&b"+123.456"[..]), IResult::Done(&b""[..], 123.456)); assert_eq!(float(&b"-123.456"[..]), IResult::Done(&b""[..], -123.456)); }
26.819407
140
0.499497
18ac720007b3676043e2206c4de173cfad3261a1
5,951
// Copyright 2020 Manuel Landesfeind, Evotec International GmbH // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! //! Module for working with faidx-indexed FASTA files. //! use std::ffi; use std::path::Path; use url::Url; use crate::htslib; use crate::errors::{Error, Result}; use crate::utils::path_as_bytes; /// A Fasta reader. #[derive(Debug)] pub struct Reader { inner: *mut htslib::faidx_t, } impl Reader { /// Create a new Reader from a path. /// /// # Arguments /// /// * `path` - the path to open. pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self, Error> { Self::new(&path_as_bytes(path, true)?) } /// Create a new Reader from an URL. /// /// # Arguments /// /// * `url` - the url to open pub fn from_url(url: &Url) -> Result<Self, Error> { Self::new(url.as_str().as_bytes()) } /// Internal function to create a Reader from some sort of path (could be file path but also URL). /// The path or URL will be handled by the c-implementation transparently. /// /// # Arguments /// /// * `path` - the path or URL to open fn new(path: &[u8]) -> Result<Self, Error> { let cpath = ffi::CString::new(path).unwrap(); let inner = unsafe { htslib::fai_load(cpath.as_ptr()) }; Ok(Self { inner }) } /// Fetch the sequence as a byte array. /// /// # Arguments /// /// * `name` - the name of the template sequence (e.g., "chr1") /// * `begin` - the offset within the template sequence (starting with 0) /// * `end` - the end position to return (if smaller than `begin`, the behavior is undefined). pub fn fetch_seq<N: AsRef<str>>(&self, name: N, begin: usize, end: usize) -> Result<&[u8]> { if begin > std::i64::MAX as usize { return Err(Error::FaidxPositionTooLarge); } if end > std::i64::MAX as usize { return Err(Error::FaidxPositionTooLarge); } let cname = ffi::CString::new(name.as_ref().as_bytes()).unwrap(); let len_out: i64 = 0; let cseq = unsafe { let ptr = htslib::faidx_fetch_seq64( self.inner, //*const faidx_t, cname.as_ptr(), // c_name begin as htslib::hts_pos_t, // p_beg_i end as htslib::hts_pos_t, // p_end_i &mut (len_out as htslib::hts_pos_t), //len ); ffi::CStr::from_ptr(ptr) }; Ok(cseq.to_bytes()) } /// Fetches the sequence and returns it as string. /// /// # Arguments /// /// * `name` - the name of the template sequence (e.g., "chr1") /// * `begin` - the offset within the template sequence (starting with 0) /// * `end` - the end position to return (if smaller than `begin`, the behavior is undefined). pub fn fetch_seq_string<N: AsRef<str>>( &self, name: N, begin: usize, end: usize, ) -> Result<String> { let bytes = self.fetch_seq(name, begin, end)?; Ok(std::str::from_utf8(bytes).unwrap().to_owned()) } } #[cfg(test)] mod tests { use super::*; fn open_reader() -> Reader { Reader::from_path(format!("{}/test/test_cram.fa", env!("CARGO_MANIFEST_DIR"))) .ok() .unwrap() } #[test] fn faidx_open() { open_reader(); } #[test] fn faidx_read_chr_first_base() { let r = open_reader(); let bseq = r.fetch_seq("chr1", 0, 0).unwrap(); assert_eq!(bseq.len(), 1); assert_eq!(bseq, b"G"); let seq = r.fetch_seq_string("chr1", 0, 0).unwrap(); assert_eq!(seq.len(), 1); assert_eq!(seq, "G"); } #[test] fn faidx_read_chr_start() { let r = open_reader(); let bseq = r.fetch_seq("chr1", 0, 9).unwrap(); assert_eq!(bseq.len(), 10); assert_eq!(bseq, b"GGGCACAGCC"); let seq = r.fetch_seq_string("chr1", 0, 9).unwrap(); assert_eq!(seq.len(), 10); assert_eq!(seq, "GGGCACAGCC"); } #[test] fn faidx_read_chr_between() { let r = open_reader(); let bseq = r.fetch_seq("chr1", 4, 14).unwrap(); assert_eq!(bseq.len(), 11); assert_eq!(bseq, b"ACAGCCTCACC"); let seq = r.fetch_seq_string("chr1", 4, 14).unwrap(); assert_eq!(seq.len(), 11); assert_eq!(seq, "ACAGCCTCACC"); } #[test] fn faidx_read_chr_end() { let r = open_reader(); let bseq = r.fetch_seq("chr1", 110, 120).unwrap(); assert_eq!(bseq.len(), 10); assert_eq!(bseq, b"CCCCTCCGTG"); let seq = r.fetch_seq_string("chr1", 110, 120).unwrap(); assert_eq!(seq.len(), 10); assert_eq!(seq, "CCCCTCCGTG"); } #[test] fn faidx_read_twice_string() { let r = open_reader(); let seq = r.fetch_seq_string("chr1", 110, 120).unwrap(); assert_eq!(seq.len(), 10); assert_eq!(seq, "CCCCTCCGTG"); let seq = r.fetch_seq_string("chr1", 5, 9).unwrap(); assert_eq!(seq.len(), 5); assert_eq!(seq, "CAGCC"); } #[test] fn faidx_read_twice_bytes() { let r = open_reader(); let seq = r.fetch_seq("chr1", 110, 120).unwrap(); assert_eq!(seq.len(), 10); assert_eq!(seq, b"CCCCTCCGTG"); let seq = r.fetch_seq("chr1", 5, 9).unwrap(); assert_eq!(seq.len(), 5); assert_eq!(seq, b"CAGCC"); } #[test] fn faidx_position_too_large() { let r = open_reader(); let position_too_large = i64::MAX as usize; let res = r.fetch_seq("chr1", position_too_large, position_too_large + 1); assert_eq!(res, Err(Error::FaidxPositionTooLarge)); } }
29.460396
102
0.548647
22e27202db90d2137edd6969e7ec9b03549bf0df
15,426
use crate::config::dfinity::CONFIG_FILE_NAME; use crate::lib::environment::Environment; use crate::lib::error::{DfxError, DfxResult}; use crate::lib::manifest::{get_latest_version, is_upgrade_necessary}; use crate::util::assets; use crate::util::clap::validators::project_name_validator; use anyhow::{anyhow, bail, Context}; use clap::Clap; use console::{style, Style}; use indicatif::HumanBytes; use lazy_static::lazy_static; use semver::Version; use serde_json::Value; use slog::{info, warn, Logger}; use std::collections::BTreeMap; use std::io::Read; use std::path::{Path, PathBuf}; use std::process::Stdio; use std::time::Duration; use tar::Archive; // const DRY_RUN: &str = "dry_run"; // const PROJECT_NAME: &str = "project_name"; const RELEASE_ROOT: &str = "https://sdk.dfinity.org"; // The dist-tag to use when getting the version from NPM. const AGENT_JS_DEFAULT_INSTALL_DIST_TAG: &str = "latest"; lazy_static! { // Tested on a phone tethering connection. This should be fine with // little impact to the user, given that "new" is supposedly a // heavy-weight operation. Thus, worst case we are utilizing the user // expectation for the duration to have a more expensive version // check. static ref CHECK_VERSION_TIMEOUT: Duration = Duration::from_secs(2); } /// Creates a new project. #[derive(Clap)] pub struct NewOpts { /// Specifies the name of the project to create. #[clap(validator(project_name_validator))] project_name: String, /// Provides a preview the directories and files to be created without adding them to the file system. #[clap(long)] dry_run: bool, /// Installs the frontend code example for the default canister. This defaults to true if Node is installed, or false if it isn't. #[clap(long)] frontend: bool, #[clap(long, conflicts_with = "frontend")] no_frontend: bool, /// Overrides which version of the JavaScript Agent to install. By default, will contact /// NPM to decide. #[clap(long, requires("frontend"))] agent_version: Option<String>, } enum Status<'a> { Create(&'a Path, usize), CreateDir(&'a Path), } impl std::fmt::Display for Status<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { match self { Status::Create(path, size) => write!( f, "{:<12} {} ({})...", style("CREATE").green().bold(), path.to_str().unwrap_or("<unknown>"), HumanBytes(*size as u64), )?, Status::CreateDir(path) => write!( f, "{:<12} {}...", style("CREATE_DIR").blue().bold(), path.to_str().unwrap_or("<unknown>"), )?, }; Ok(()) } } pub fn create_file(log: &Logger, path: &Path, content: &[u8], dry_run: bool) -> DfxResult { if !dry_run { if let Some(p) = path.parent() { std::fs::create_dir_all(p)?; } std::fs::write(&path, content)?; } info!(log, "{}", Status::Create(path, content.len())); Ok(()) } #[allow(dead_code)] pub fn create_dir<P: AsRef<Path>>(log: &Logger, path: P, dry_run: bool) -> DfxResult { let path = path.as_ref(); if path.is_dir() { return Ok(()); } if !dry_run { std::fs::create_dir_all(&path)?; } info!(log, "{}", Status::CreateDir(path)); Ok(()) } pub fn init_git(log: &Logger, project_name: &Path) -> DfxResult { let init_status = std::process::Command::new("git") .arg("init") .current_dir(project_name) .stderr(Stdio::null()) .stdout(Stdio::null()) .status(); if init_status.is_ok() && init_status.unwrap().success() { info!(log, "Creating git repository..."); std::process::Command::new("git") .arg("add") .current_dir(project_name) .arg(".") .output()?; std::process::Command::new("git") .arg("commit") .current_dir(project_name) .arg("-a") .arg("--message=Initial commit.") .output()?; } Ok(()) } fn write_files_from_entries<R: Sized + Read>( log: &Logger, archive: &mut Archive<R>, root: &Path, dry_run: bool, variables: &BTreeMap<String, String>, ) -> DfxResult { for entry in archive.entries()? { let mut file = entry?; if file.header().entry_type().is_dir() { continue; } let mut v = Vec::new(); file.read_to_end(&mut v).map_err(DfxError::from)?; let v = match String::from_utf8(v) { Err(err) => err.into_bytes(), Ok(mut s) => { // Perform replacements. variables.iter().for_each(|(name, value)| { let pattern = "{".to_owned() + name + "}"; s = s.replace(pattern.as_str(), value); }); s.into_bytes() } }; // Perform path replacements. let mut p = root .join(file.header().path()?) .to_str() .expect("Non unicode project name path.") .to_string(); variables.iter().for_each(|(name, value)| { let pattern = "__".to_owned() + name + "__"; p = p.replace(pattern.as_str(), value); }); let p = PathBuf::from(p); create_file(log, p.as_path(), &v, dry_run)?; } Ok(()) } fn npm_install(location: &Path) -> DfxResult<std::process::Child> { std::process::Command::new("npm") .arg("install") .arg("--quiet") .arg("--no-progress") .stdout(std::process::Stdio::inherit()) .stderr(std::process::Stdio::inherit()) .current_dir(location) .spawn() .map_err(DfxError::from) } fn scaffold_frontend_code( env: &dyn Environment, dry_run: bool, project_name: &Path, arg_no_frontend: bool, arg_frontend: bool, agent_version: &Option<String>, variables: &BTreeMap<String, String>, ) -> DfxResult { let log = env.get_logger(); let node_installed = std::process::Command::new("node") .arg("--version") .output() .is_ok(); let project_name_str = project_name .to_str() .ok_or_else(|| anyhow!("Invalid argument: project_name"))?; if (node_installed && !arg_no_frontend) || arg_frontend { // Check if node is available, and if it is create the files for the frontend build. let js_agent_version = if let Some(v) = agent_version { v.clone() } else { get_agent_js_version_from_npm(&AGENT_JS_DEFAULT_INSTALL_DIST_TAG) .map_err(|err| anyhow!("Cannot execute npm: {}", err))? }; let mut variables = variables.clone(); variables.insert("js_agent_version".to_string(), js_agent_version); variables.insert( "project_name_uppercase".to_string(), project_name_str.to_uppercase(), ); let mut new_project_node_files = assets::new_project_node_files()?; write_files_from_entries( log, &mut new_project_node_files, project_name, dry_run, &variables, )?; let dfx_path = project_name.join(CONFIG_FILE_NAME); let content = std::fs::read(&dfx_path)?; let mut config_json: Value = serde_json::from_slice(&content).map_err(std::io::Error::from)?; let frontend_value: serde_json::Map<String, Value> = [( "entrypoint".to_string(), ("src/".to_owned() + project_name_str + "_assets/src/index.html").into(), )] .iter() .cloned() .collect(); // Only update the dfx.json and install node dependencies if we're not running in dry run. if !dry_run { let assets_canister_json = config_json .pointer_mut(("/canisters/".to_owned() + project_name_str + "_assets").as_str()) .unwrap(); assets_canister_json .as_object_mut() .unwrap() .insert("frontend".to_string(), Value::from(frontend_value)); assets_canister_json .as_object_mut() .unwrap() .get_mut("source") .unwrap() .as_array_mut() .unwrap() .push(Value::from( "dist/".to_owned() + project_name_str + "_assets/", )); let pretty = serde_json::to_string_pretty(&config_json) .context("Invalid data: Cannot serialize configuration file.")?; std::fs::write(&dfx_path, pretty)?; // Install node modules. Error is not blocking, we just show a message instead. if node_installed { let b = env.new_spinner("Installing node dependencies..."); if npm_install(project_name)?.wait().is_ok() { b.finish_with_message("Done."); } else { b.finish_with_message( "An error occurred. See the messages above for more details.", ); } } } } else if !arg_frontend && !node_installed { warn!( log, "Node could not be found. Skipping installing the frontend example code." ); warn!( log, "You can bypass this check by using the --frontend flag." ); } Ok(()) } fn get_agent_js_version_from_npm(dist_tag: &str) -> DfxResult<String> { std::process::Command::new("npm") .arg("show") .arg("@dfinity/agent") .arg(&format!("dist-tags.{}", dist_tag)) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::inherit()) .spawn() .map_err(DfxError::from) .and_then(|child| { let mut result = String::new(); child .stdout .expect("Could not get the output of subprocess 'npm'.") .read_to_string(&mut result)?; Ok(result.trim().to_string()) }) } pub fn exec(env: &dyn Environment, opts: NewOpts) -> DfxResult { let log = env.get_logger(); let dry_run = opts.dry_run; let project_name = Path::new(opts.project_name.as_str()); if project_name.exists() { bail!("Cannot create a new project because the directory already exists."); } let current_version = env.get_version(); let version_str = format!("{}", current_version); // It is fine for the following command to timeout or fail. We // drop the error. let latest_version = get_latest_version(RELEASE_ROOT, Some(*CHECK_VERSION_TIMEOUT)).ok(); if is_upgrade_necessary(latest_version.as_ref(), current_version) { warn_upgrade(log, latest_version.as_ref(), current_version); } if !env.get_cache().is_installed()? { env.get_cache().install()?; } info!( log, r#"Creating new project "{}"..."#, project_name.display() ); if dry_run { warn!( log, r#"Running in dry mode. Nothing will be committed to disk."# ); } let project_name_str = project_name .to_str() .ok_or_else(|| anyhow!("Invalid argument: project_name"))?; let variables: BTreeMap<String, String> = [ ("project_name".to_string(), project_name_str.to_string()), ("dfx_version".to_string(), version_str.clone()), ("dot".to_string(), ".".to_string()), ] .iter() .cloned() .collect(); let mut new_project_files = assets::new_project_files()?; write_files_from_entries( log, &mut new_project_files, project_name, dry_run, &variables, )?; scaffold_frontend_code( env, dry_run, project_name, opts.no_frontend, opts.frontend, &opts.agent_version, &variables, )?; if !dry_run { // If on mac, we should validate that XCode toolchain was installed. #[cfg(target_os = "macos")] { let mut should_git = true; if let Ok(code) = std::process::Command::new("xcode-select") .arg("-p") .stderr(Stdio::null()) .stdout(Stdio::null()) .status() { if !code.success() { // git is not installed. should_git = false; } } else { // Could not find XCode Toolchain on Mac, that's weird. should_git = false; } if should_git { init_git(log, &project_name)?; } } #[cfg(not(target_os = "macos"))] { init_git(log, &project_name)?; } } // Print welcome message. info!( log, // This needs to be included here because we cannot use the result of a function for // the format!() rule (and so it cannot be moved in the util::assets module). include_str!("../../assets/welcome.txt"), version_str, assets::dfinity_logo(), project_name_str ); Ok(()) } fn warn_upgrade(log: &Logger, latest_version: Option<&Version>, current_version: &Version) { warn!(log, "You seem to be running an outdated version of dfx."); let red = Style::new().red(); let green = Style::new().green(); let yellow = Style::new().yellow(); let mut version_comparison = format!("Current version: {}", red.apply_to(current_version.clone())); if let Some(v) = latest_version { version_comparison += format!( "{} latest version: {}", yellow.apply_to(" → "), green.apply_to(v) ) .as_str(); } warn!( log, "\nYou are strongly encouraged to upgrade by running 'dfx upgrade'!" ); } #[cfg(test)] mod tests { use super::*; #[test] fn project_name_is_valid() { assert!(project_name_validator("a").is_ok()); assert!(project_name_validator("a_").is_ok()); assert!(project_name_validator("a_1").is_ok()); assert!(project_name_validator("A").is_ok()); assert!(project_name_validator("A1").is_ok()); assert!(project_name_validator("a_good_name_").is_ok()); assert!(project_name_validator("a_good_name").is_ok()); } #[test] fn project_name_is_invalid() { assert!(project_name_validator("_a_good_name_").is_err()); assert!(project_name_validator("__also_good").is_err()); assert!(project_name_validator("_1").is_err()); assert!(project_name_validator("_a").is_err()); assert!(project_name_validator("1").is_err()); assert!(project_name_validator("1_").is_err()); assert!(project_name_validator("-").is_err()); assert!(project_name_validator("_").is_err()); assert!(project_name_validator("a-b-c").is_err()); assert!(project_name_validator("🕹").is_err()); assert!(project_name_validator("不好").is_err()); assert!(project_name_validator("a:b").is_err()); } }
30.852
134
0.558343
23dfcd826c162bc622019fc0bb2984357d8c6ac2
2,884
//! Data structures to provide transformation of the source // addresses of a WebAssembly module into the native code. use serde::{Deserialize, Serialize}; /// Single source location to generated address mapping. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct InstructionAddressMap { /// Where in the source wasm binary this instruction comes from, specified /// in an offset of bytes from the front of the file. pub srcloc: FilePos, /// Offset from the start of the function's compiled code to where this /// instruction is located, or the region where it starts. pub code_offset: u32, } /// Function and its instructions addresses mappings. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)] pub struct FunctionAddressMap { /// An array of data for the instructions in this function, indicating where /// each instruction maps back to in the original function. /// /// This array is sorted least-to-greatest by the `code_offset` field. /// Additionally the span of each `InstructionAddressMap` is implicitly the /// gap between it and the next item in the array. pub instructions: Box<[InstructionAddressMap]>, /// Function's initial offset in the source file, specified in bytes from /// the front of the file. pub start_srcloc: FilePos, /// Function's end offset in the source file, specified in bytes from /// the front of the file. pub end_srcloc: FilePos, /// Generated function body offset if applicable, otherwise 0. pub body_offset: usize, /// Generated function body length. pub body_len: u32, } /// A position within an original source file, /// /// This structure is used as a newtype wrapper around a 32-bit integer which /// represents an offset within a file where a wasm instruction or function is /// to be originally found. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct FilePos(u32); impl FilePos { /// Create a new file position with the given offset. pub fn new(pos: u32) -> FilePos { assert!(pos != u32::MAX); FilePos(pos) } /// Returns the offset that this offset was created with. /// /// Note that the `Default` implementation will return `None` here, whereas /// positions created with `FilePos::new` will return `Some`. pub fn file_offset(self) -> Option<u32> { if self.0 == u32::MAX { None } else { Some(self.0) } } } impl Default for FilePos { fn default() -> FilePos { FilePos(u32::MAX) } } /// Memory definition offset in the VMContext structure. #[derive(Debug, Clone)] pub enum ModuleMemoryOffset { /// Not available. None, /// Offset to the defined memory. Defined(u32), /// Offset to the imported memory. Imported(u32), }
32.772727
80
0.678225
edea5c631668c9c7be339443cd6e8572c338a4a7
3,123
use rulinalg::matrix::{BaseMatrix, BaseMatrixMut, Matrix}; /// Continuous Time Recurrent Neural Network implementation, which the /// `NeuralNetwork` genome encodes for. #[allow(missing_docs)] #[derive(Debug, Clone)] pub struct Ctrnn { theta: Matrix<f64>, // bias delta_t_tau: Matrix<f64>, wij: Matrix<f64>, // weights steps: usize, } impl Ctrnn { /// Create a new CTRNN pub fn new(theta: Vec<f64>, tau: Vec<f64>, wij: Vec<f64>, delta_t: f64, steps: usize) -> Ctrnn { let tau = Ctrnn::vector_to_column_matrix(tau); Ctrnn { theta: Ctrnn::vector_to_column_matrix(theta), wij: Ctrnn::vector_to_matrix(wij), delta_t_tau: tau.apply(&(|x| 1.0 / x)) * delta_t, steps, } } /// Activate the neural network. The output is written to `output`, the /// amount depending on the length of `output`. pub fn activate(&self, mut input: Vec<f64>, output: &mut [f64]) { let n_inputs = input.len(); let n_neurons = self.theta.rows(); if n_neurons < n_inputs { input.truncate(n_neurons); } else { input = [input, vec![0.0; n_neurons - n_inputs]].concat(); } let input = Ctrnn::vector_to_column_matrix(input); let mut y = input.clone(); // TODO: correct? Or zero-vector? for _ in 0..self.steps { let activations = (&y + &self.theta).apply(&Ctrnn::sigmoid); y = &y + self .delta_t_tau .elemul(&((&self.wij * activations) - &y + &input)); } let y = y.into_vec(); if n_inputs < n_neurons { let outputs_activations = y.split_at(n_inputs).1.to_vec(); let len = std::cmp::min(outputs_activations.len(), output.len()); output[..len].clone_from_slice(&outputs_activations[..len]) } } fn sigmoid(y: f64) -> f64 { // Inspired from neat-python let y = y * 5.0; let y = if y < -60.0 { -60.0 } else if y > 60.0 { 60.0 } else { y }; 1.0 / (1.0 + (-y).exp()) } fn vector_to_column_matrix(vector: Vec<f64>) -> Matrix<f64> { Matrix::new(vector.len(), 1, vector) } fn vector_to_matrix(vector: Vec<f64>) -> Matrix<f64> { let width = (vector.len() as f64).sqrt() as usize; Matrix::new(width, width, vector) } } #[cfg(test)] mod tests { macro_rules! assert_delta_vector { ($x:expr, $y:expr, $d:expr) => { for pos in 0..$x.len() { if !(($x[pos] - $y[pos]).abs() <= $d) { panic!( "Element at position {:?} -> {:?} \ is not equal to {:?}", pos, $x[pos], $y[pos] ); } } }; } #[test] fn neural_network_activation_stability() { // TODO // This test should just ensure that a stable neural network implementation // doesn't change } }
30.028846
100
0.509446
39bf899a023f14fce9ea3d20293b7cf52c7385bb
644
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test bounds checking for DST raw slices // error-pattern:index out of bounds fn main() { let a: *const [_] = &[1i, 2, 3]; unsafe { let _b = (*a)[3]; } }
32.2
68
0.686335
380c684e00b69d51a7e9f8e92516accd8f08cd88
8,829
use crate::error::{Error, Result}; use crate::join::estimate::Estimate; use crate::join::graph::{Edge, EdgeID, Graph, VertexSet}; use crate::join::reorder::{JoinEdge, Reorder, Tree}; use crate::join::{JoinKind, JoinOp}; use crate::op::Op; use std::borrow::Cow; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::mem; /// DPsize is a classic DP algorithm for join reorder. /// Suppose there are N tables to be joined. /// DPsize initialize each table as a single join set. /// Then iterate the size from 2 to N, to compute all best plans /// of given size, based on previous results. /// At the end of the iteration, we get the best plan of size N. /// /// Note: DP algorithm requires cost model to pick best plan on /// same join set. Here we use simplest cost function that just /// sums row counts of intermediate result sets, which can be /// considered as "logical" cost. pub struct DPsize<E>(E); impl<E: Estimate> DPsize<E> { #[inline] pub fn new(est: E) -> Self { DPsize(est) } } impl<E: Estimate> Reorder for DPsize<E> { #[inline] fn reorder(mut self, graph: &Graph) -> Result<Op> { // we store n+1 sizes, and leave size=0 empty. let n_vertexes = graph.n_vertexes(); let mut best_plans = vec![HashMap::new(); n_vertexes + 1]; // initialize each single table for vid in graph.vids() { let vset = VertexSet::from(vid); let rows = self.0.estimate_qry_rows(vset)?; // In current version, we made simple cost function: cost is same as number // of processed rows. // So cost of a table scan is just row count of this table. // Cost of a binary join is the input rows of both children and its output rows. best_plans[1].insert(vset, Tree::Single { rows, cost: rows }); } // initialize edges as pairs of id and ref. let edges: Vec<(EdgeID, &Edge)> = graph.eids().map(|eid| (eid, graph.edge(eid))).collect(); // main loop to compute join size from 2 to N let mut target_plan = HashMap::new(); // target_plan is what we update in the iteration for join_size in 2..=n_vertexes { for l_size in 1..=n_vertexes / 2 { let r_size = join_size - l_size; // here we use a trick to swap the plan of target size with empty map, // so that we can perform update on it while looking up plans of smaller size. mem::swap(&mut target_plan, &mut best_plans[join_size]); // we only need to iterate over joined plans for (vi, ti) in &best_plans[l_size] { for (vj, tj) in &best_plans[r_size] { // If size is identical, we only iterate over small-large pairs. // And we skip plans that has intersection. if (l_size == r_size && vi >= vj) || vi.intersects(*vj) { continue; } let vset = *vi | *vj; for (eid, new_edge) in &edges { // Provided sets must include entire eligibility set. // But either side should not include eligiblity set, that means it is already joined. if vset.includes(new_edge.e_vset) && !vi.includes(new_edge.e_vset) && !vj.includes(new_edge.e_vset) { // then identify left and right let (l_vset, r_vset) = { let l = new_edge.e_vset & new_edge.l_vset; let r = new_edge.e_vset & new_edge.r_vset; if vi.includes(l) && vj.includes(r) { (*vi, *vj) } else if vi.includes(r) && vj.includes(l) { (*vj, *vi) } else { return Err(Error::InvalidJoinTransformation); } }; let mut edge = Cow::Borrowed(*new_edge); // Addtional check must be performed on inner join, to ensure all // available edges are merged together before the estimation. if edge.kind == JoinKind::Inner { for (merge_eid, merge_edge) in &edges { if merge_edge.kind == JoinKind::Inner && merge_eid != eid && vset.includes(merge_edge.e_vset) && !vi.includes(merge_edge.e_vset) && !vj.includes(merge_edge.e_vset) { let edge = edge.to_mut(); edge.cond.extend_from_slice(&merge_edge.cond); edge.e_vset |= merge_edge.e_vset; } } } // now estimate rows let rows = self.0.estimate_join_rows(graph, l_vset, r_vset, &edge)?; // check if it's better than existing one and update match target_plan.entry(*vi | *vj) { Entry::Vacant(vac) => { let join_edge = JoinEdge { l_vset, r_vset, edge, rows, cost: ti.cost() + tj.cost() + rows, }; vac.insert(Tree::Join(join_edge)); } Entry::Occupied(mut occ) => { let new_cost = ti.cost() + tj.cost() + rows; if occ.get().cost() > new_cost { let join_edge = JoinEdge { l_vset, r_vset, edge, rows, cost: new_cost, }; *occ.get_mut() = Tree::Join(join_edge); } } } } } } } // swap target plan back mem::swap(&mut target_plan, &mut best_plans[join_size]); } } if best_plans[n_vertexes].len() != 1 { return Err(Error::InvalidJoinTransformation); } let (vset, tree) = best_plans[n_vertexes].iter().next().unwrap(); build_join_tree(graph, &best_plans, *vset, tree) } } fn build_join_tree( graph: &Graph, best_plans: &[HashMap<VertexSet, Tree>], vset: VertexSet, tree: &Tree, ) -> Result<Op> { match tree { Tree::Single { .. } => { let vid = vset.single().unwrap(); let qid = graph.vid_to_qid(vid)?; Ok(Op::Query(qid)) } Tree::Join(JoinEdge { l_vset, r_vset, edge, .. }) => { let l_tree = &best_plans[l_vset.len()][l_vset]; let left = build_join_tree(graph, best_plans, *l_vset, l_tree)?; let r_tree = &best_plans[r_vset.len()][r_vset]; let right = build_join_tree(graph, best_plans, *r_vset, r_tree)?; let cond: Vec<_> = graph.preds(edge.cond.clone()).cloned().collect(); let filt: Vec<_> = graph.preds(edge.filt.clone()).cloned().collect(); let op = Op::qualified_join( edge.kind, JoinOp::try_from(left)?, JoinOp::try_from(right)?, cond, filt, ); Ok(op) } } }
48.245902
114
0.425756
2171240c4942b0f41fc7e1e12966706c56c29175
7,954
mod compression; mod crc32; pub mod de; pub mod error; pub mod ser; pub use crate::codec::compression::Compression; pub use crate::codec::de::{decode_resp, Deserializer}; pub use crate::codec::error::{Error, Result}; pub use crate::codec::ser::{encode_req, Serializer}; #[cfg(test)] mod tests { use serde::{Deserialize, Serialize}; use std::io::Cursor; use matches::assert_matches; use super::*; use crate::codec::{de::zag_i32, ser::zig_i32}; use crate::model::*; use crate::types::*; fn encode_single<T: Serialize>(val: &T) -> Result<Vec<u8>> { let mut serializer = Serializer::new(); val.serialize(&mut serializer)?; Ok(serializer.buf) } fn decode_single<'a, T>(input: &'a [u8], version: Option<usize>) -> Result<T> where T: Deserialize<'a>, { let mut deserializer = Deserializer::from_bytes(input, version.unwrap_or_else(|| 0)); let resp = T::deserialize(&mut deserializer)?; if deserializer.len() == 0 { Ok(resp) } else { Err(serde::de::Error::custom(format!("bytes remaining",))) } } pub fn read_resp<R, T>(rdr: &mut R, version: usize) -> Result<(HeaderResponse, T)> where R: std::io::Read, T: serde::de::DeserializeOwned, { let mut buf = [0u8; 4]; rdr.read_exact(&mut buf)?; let size = i32::from_be_bytes(buf); let mut bytes = vec![0; size as usize]; rdr.read_exact(&mut bytes)?; decode_resp::<T>(&bytes, version) } #[test] fn serde_bool() { let v1 = true; let bytes = encode_single(&v1).unwrap(); let v2 = decode_single::<bool>(&bytes, None).unwrap(); assert_eq!(v1, v2); } #[test] fn serde_integers() { let v1 = 13 as i8; let bytes = encode_single(&v1).unwrap(); let v2 = decode_single::<i8>(&bytes, None).unwrap(); assert_eq!(v1, v2); let v1 = 13 as i16; let bytes = encode_single(&v1).unwrap(); let v2 = decode_single::<i16>(&bytes, None).unwrap(); assert_eq!(v1, v2); let v1 = 13 as i32; let bytes = encode_single(&v1).unwrap(); let v2 = decode_single::<i32>(&bytes, None).unwrap(); assert_eq!(v1, v2); let v1 = 13 as i64; let bytes = encode_single(&v1).unwrap(); let v2 = decode_single::<i64>(&bytes, None).unwrap(); assert_eq!(v1, v2); let v1 = 13 as u32; let bytes = encode_single(&v1).unwrap(); let v2 = decode_single::<u32>(&bytes, None).unwrap(); assert_eq!(v1, v2); } #[test] fn serde_varint_varlong() { let i: i32 = 3; let mut bytes = vec![]; zig_i32(i, &mut bytes).unwrap(); let mut rdr = Cursor::new(bytes); let (j, varint_size) = zag_i32(&mut rdr).unwrap(); assert_eq!(i, j); assert_eq!(1, varint_size); let i = Varint(3); let bytes = encode_single(&i).unwrap(); let j = decode_single::<Varint>(&bytes, None).unwrap(); assert_eq!(i, j); let i = Varlong(-3); let bytes = encode_single(&i).unwrap(); let j = decode_single::<Varlong>(&bytes, None).unwrap(); assert_eq!(i, j); let i = Varint::size_of(12121662); let j = encode_single(&Varint(12121662)).unwrap(); assert_eq!(i, j.len()); } #[test] fn serde_strings() { let s1 = String::from("yes"); let bytes = encode_single(&s1).unwrap(); let s2 = decode_single::<String>(&bytes, None).unwrap(); assert_eq!(s1, s2); let s1 = NullableString::from("yes"); let bytes = encode_single(&s1).unwrap(); let s2 = decode_single::<NullableString>(&bytes, None).unwrap(); assert_eq!(s1, s2); let s1 = NullableString(None); let bytes = encode_single(&s1).unwrap(); let s2 = decode_single::<NullableString>(&bytes, None).unwrap(); assert_eq!(s1, s2); } #[test] fn serde_bytes() { let b1 = Bytes(vec![1, 2, 3]); let bytes = encode_single(&b1).unwrap(); let b2 = decode_single::<Bytes>(&bytes, None).unwrap(); assert_eq!(b1, b2); let b1 = NullableBytes::from(vec![1, 2, 3]); let bytes = encode_single(&b1).unwrap(); let b2 = decode_single::<NullableBytes>(&bytes, None).unwrap(); assert_eq!(b1, b2); let b1 = NullableBytes(None); let bytes = encode_single(&b1).unwrap(); let b2 = decode_single::<NullableBytes>(&bytes, None).unwrap(); assert_eq!(b1, b2); } #[test] fn versions_req_ser() { let header = HeaderRequest { api_key: ApiKey::ApiVersions, api_version: 0, correlation_id: 42, client_id: NullableString(None), }; let bytes = encode_req(&header, &ApiVersionsRequest::V0 {}).unwrap(); assert_eq!(vec![0, 0, 0, 10, 0, 18, 0, 0, 0, 0, 0, 42, 255, 255], bytes); } #[test] fn versions_resp_de() { let mut bytes = Cursor::new(vec![ 0, 0, 1, 12, 0, 0, 0, 42, 0, 0, 0, 0, 0, 43, 0, 0, 0, 0, 0, 7, 0, 1, 0, 0, 0, 10, 0, 2, 0, 0, 0, 4, 0, 3, 0, 0, 0, 7, 0, 4, 0, 0, 0, 1, 0, 5, 0, 0, 0, 0, 0, 6, 0, 0, 0, 4, 0, 7, 0, 0, 0, 1, 0, 8, 0, 0, 0, 6, 0, 9, 0, 0, 0, 5, 0, 10, 0, 0, 0, 2, 0, 11, 0, 0, 0, 3, 0, 12, 0, 0, 0, 2, 0, 13, 0, 0, 0, 2, 0, 14, 0, 0, 0, 2, 0, 15, 0, 0, 0, 2, 0, 16, 0, 0, 0, 2, 0, 17, 0, 0, 0, 1, 0, 18, 0, 0, 0, 2, 0, 19, 0, 0, 0, 3, 0, 20, 0, 0, 0, 3, 0, 21, 0, 0, 0, 1, 0, 22, 0, 0, 0, 1, 0, 23, 0, 0, 0, 2, 0, 24, 0, 0, 0, 1, 0, 25, 0, 0, 0, 1, 0, 26, 0, 0, 0, 1, 0, 27, 0, 0, 0, 0, 0, 28, 0, 0, 0, 2, 0, 29, 0, 0, 0, 1, 0, 30, 0, 0, 0, 1, 0, 31, 0, 0, 0, 1, 0, 32, 0, 0, 0, 2, 0, 33, 0, 0, 0, 1, 0, 34, 0, 0, 0, 1, 0, 35, 0, 0, 0, 1, 0, 36, 0, 0, 0, 0, 0, 37, 0, 0, 0, 1, 0, 38, 0, 0, 0, 1, 0, 39, 0, 0, 0, 1, 0, 40, 0, 0, 0, 1, 0, 41, 0, 0, 0, 1, 0, 42, 0, 0, 0, 1, ]); let (header, resp) = read_resp::<_, ApiVersionsResponse>(&mut bytes, 0).unwrap(); assert_eq!(42, header.correlation); assert_matches!(resp, ApiVersionsResponse::V0 { error_code,ref api_versions } if error_code == 0 && api_versions.len() == 43); } #[test] fn topics_req_resp_serde() { let val1 = CreateTopicsRequest::V0 { topics: vec![create_topics_request::v0::Topics { name: "topic".to_owned(), num_partitions: 32, replication_factor: 16, assignments: vec![create_topics_request::v0::Assignments { partition_index: 12, broker_ids: vec![1], }], configs: vec![create_topics_request::v0::Configs { name: "default".to_owned(), value: NullableString(None), }], }], timeout_ms: 0, }; let bytes = encode_single(&val1).unwrap(); let val2 = decode_single::<CreateTopicsRequest>(&bytes, Some(0)).unwrap(); assert_eq!(val1, val2); } #[test] fn fetch_resp_de() { let mut bytes = vec![ 0, 0, 0, 42, 0, 0, 0, 1, 0, 4, 116, 101, 115, 116, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 74, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 224, 87, 178, 51, 0, 0, 255, 255, 255, 255, 0, 0, 0, 6, 99, 111, 117, 99, 111, 117, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 61, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; let (header, resp) = decode_resp::<FetchResponse>(&mut bytes, 0).unwrap(); println!("{:?}", header); println!("{:?}", resp); } }
34.885965
99
0.505783
7a3eaced9d8ea11c02a8c6380ed770617461dacd
3,349
use stm32f4xx_hal as p_hal; use p_hal::stm32 as pac; use p_hal::stm32::I2C1; use p_hal::gpio::GpioExt; use p_hal::rcc::RccExt; use p_hal::time::U32Ext; pub fn setup_peripherals() -> ( // LED output pin UserLed1Type, DelaySourceType, I2c1PortType, Spi1PortType, ChipSelectPinType, ) { let dp = pac::Peripherals::take().unwrap(); let cp = cortex_m::Peripherals::take().unwrap(); // Set up the system clock let rcc = dp.RCC.constrain(); let clocks = rcc .cfgr .use_hse(25.mhz()) //f401cb board has 25 MHz crystal for HSE .sysclk(84.mhz()) // f401cb supports 84 MHz sysclk max .pclk1(48.mhz()) .pclk2(48.mhz()) .freeze(); let delay_source = p_hal::delay::Delay::new(cp.SYST, clocks); // let hclk = clocks.hclk(); // let rng_clk = clocks.pll48clk().unwrap_or(0u32.hz()); // let pclk1 = clocks.pclk1(); // d_println!(get_debug_log(), "hclk: {} /16: {} pclk1: {} rng_clk: {}", hclk.0, hclk.0 / 16, pclk1.0, rng_clk.0); let gpioa = dp.GPIOA.split(); let gpiob = dp.GPIOB.split(); let gpioc = dp.GPIOC.split(); // let gpiod = dp.GPIOD.split(); let user_led1 = gpioc.pc13.into_push_pull_output(); //f401CxUx // let user_led1 = gpiod.pd12.into_push_pull_output(); //f4discovery // setup i2c1 // NOTE: stm32f401CxUx board lacks external pull-ups on i2c pins // NOTE: eg f407 discovery board already has external pull-ups // NOTE: sensor breakout boards may have their own pull-ups: check carefully let i2c1_port = { let scl = gpiob .pb8 .into_alternate_af4() .internal_pull_up(true) .set_open_drain(); let sda = gpiob .pb9 .into_alternate_af4() .internal_pull_up(true) .set_open_drain(); p_hal::i2c::I2c::i2c1(dp.I2C1, (scl, sda), 400.khz(), clocks) }; let spi1_port = { // SPI1 port setup let sck = gpioa.pa5.into_alternate_af5(); let miso = gpioa.pa6.into_alternate_af5(); let mosi = gpioa.pa7.into_alternate_af5(); p_hal::spi::Spi::spi1( dp.SPI1, (sck, miso, mosi), embedded_hal::spi::MODE_0, 3_000_000.hz(), clocks, ) }; // SPI chip select CS let spi_csn = gpioa.pa15.into_open_drain_output(); // HINTN interrupt pin // let hintn = gpiob.pb0.into_pull_up_input(); (user_led1, delay_source, i2c1_port, spi1_port, spi_csn) } pub type I2c1PortType = p_hal::i2c::I2c< I2C1, ( p_hal::gpio::gpiob::PB8<p_hal::gpio::AlternateOD<p_hal::gpio::AF4>>, p_hal::gpio::gpiob::PB9<p_hal::gpio::AlternateOD<p_hal::gpio::AF4>>, ), >; pub type Spi1PortType = p_hal::spi::Spi< pac::SPI1, ( p_hal::gpio::gpioa::PA5<p_hal::gpio::Alternate<p_hal::gpio::AF5>>, //SCLK p_hal::gpio::gpioa::PA6<p_hal::gpio::Alternate<p_hal::gpio::AF5>>, //MISO p_hal::gpio::gpioa::PA7<p_hal::gpio::Alternate<p_hal::gpio::AF5>>, //MOSI ), >; pub type ChipSelectPinType = p_hal::gpio::gpioa::PA15<p_hal::gpio::Output<p_hal::gpio::OpenDrain>>; //CSN pub type UserLed1Type = p_hal::gpio::gpioc::PC13<p_hal::gpio::Output<p_hal::gpio::PushPull>>; pub type DelaySourceType = p_hal::delay::Delay;
29.121739
118
0.601374
69e240f30bcf026af4a40d3e98a85f800ac6f815
6,368
// Copyright 2013 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. use container::Container; use fmt; use from_str::FromStr; use io::IoResult; use iter::Iterator; use libc; use option::{Some, None, Option}; use os; use result::Ok; use str::StrSlice; use unstable::running_on_valgrind; use vec::ImmutableVector; // Indicates whether we should perform expensive sanity checks, including rtassert! // FIXME: Once the runtime matures remove the `true` below to turn off rtassert, etc. pub static ENFORCE_SANITY: bool = true || !cfg!(rtopt) || cfg!(rtdebug) || cfg!(rtassert); /// Get the number of cores available pub fn num_cpus() -> uint { unsafe { return rust_get_num_cpus(); } extern { fn rust_get_num_cpus() -> libc::uintptr_t; } } /// Valgrind has a fixed-sized array (size around 2000) of segment descriptors /// wired into it; this is a hard limit and requires rebuilding valgrind if you /// want to go beyond it. Normally this is not a problem, but in some tests, we /// produce a lot of threads casually. Making lots of threads alone might not /// be a problem _either_, except on OSX, the segments produced for new threads /// _take a while_ to get reclaimed by the OS. Combined with the fact that libuv /// schedulers fork off a separate thread for polling fsevents on OSX, we get a /// perfect storm of creating "too many mappings" for valgrind to handle when /// running certain stress tests in the runtime. pub fn limit_thread_creation_due_to_osx_and_valgrind() -> bool { (cfg!(target_os="macos")) && running_on_valgrind() } /// Get's the number of scheduler threads requested by the environment /// either `RUST_THREADS` or `num_cpus`. pub fn default_sched_threads() -> uint { match os::getenv("RUST_THREADS") { Some(nstr) => { let opt_n: Option<uint> = FromStr::from_str(nstr); match opt_n { Some(n) if n > 0 => n, _ => rtabort!("`RUST_THREADS` is `{}`, should be a positive integer", nstr) } } None => { if limit_thread_creation_due_to_osx_and_valgrind() { 1 } else { num_cpus() } } } } pub fn dumb_println(args: &fmt::Arguments) { use io; struct Stderr; impl io::Writer for Stderr { fn write(&mut self, data: &[u8]) -> IoResult<()> { unsafe { libc::write(libc::STDERR_FILENO, data.as_ptr() as *libc::c_void, data.len() as libc::size_t); } Ok(()) // yes, we're lying } } let mut w = Stderr; let _ = fmt::writeln(&mut w as &mut io::Writer, args); } pub fn abort(msg: &str) -> ! { let msg = if !msg.is_empty() { msg } else { "aborted" }; let hash = msg.chars().fold(0, |accum, val| accum + (val as uint) ); let quote = match hash % 10 { 0 => " It was from the artists and poets that the pertinent answers came, and I know that panic would have broken loose had they been able to compare notes. As it was, lacking their original letters, I half suspected the compiler of having asked leading questions, or of having edited the correspondence in corroboration of what he had latently resolved to see.", 1 => " There are not many persons who know what wonders are opened to them in the stories and visions of their youth; for when as children we listen and dream, we think but half-formed thoughts, and when as men we try to remember, we are dulled and prosaic with the poison of life. But some of us awake in the night with strange phantasms of enchanted hills and gardens, of fountains that sing in the sun, of golden cliffs overhanging murmuring seas, of plains that stretch down to sleeping cities of bronze and stone, and of shadowy companies of heroes that ride caparisoned white horses along the edges of thick forests; and then we know that we have looked back through the ivory gates into that world of wonder which was ours before we were wise and unhappy.", 2 => " Instead of the poems I had hoped for, there came only a shuddering blackness and ineffable loneliness; and I saw at last a fearful truth which no one had ever dared to breathe before — the unwhisperable secret of secrets — The fact that this city of stone and stridor is not a sentient perpetuation of Old New York as London is of Old London and Paris of Old Paris, but that it is in fact quite dead, its sprawling body imperfectly embalmed and infested with queer animate things which have nothing to do with it as it was in life.", 3 => " The ocean ate the last of the land and poured into the smoking gulf, thereby giving up all it had ever conquered. From the new-flooded lands it flowed again, uncovering death and decay; and from its ancient and immemorial bed it trickled loathsomely, uncovering nighted secrets of the years when Time was young and the gods unborn. Above the waves rose weedy remembered spires. The moon laid pale lilies of light on dead London, and Paris stood up from its damp grave to be sanctified with star-dust. Then rose spires and monoliths that were weedy but not remembered; terrible spires and monoliths of lands that men never knew were lands...", 4 => " There was a night when winds from unknown spaces whirled us irresistibly into limitless vacuum beyond all thought and entity. Perceptions of the most maddeningly untransmissible sort thronged upon us; perceptions of infinity which at the time convulsed us with joy, yet which are now partly lost to my memory and partly incapable of presentation to others.", _ => "You've met with a terrible fate, haven't you?" }; rterrln!("{}", ""); rterrln!("{}", quote); rterrln!("{}", ""); rterrln!("fatal runtime error: {}", msg); abort(); fn abort() -> ! { use std::unstable::intrinsics; unsafe { intrinsics::abort() } } }
42.453333
91
0.689227
870722748e878dd704d21c019b5015708dd5c991
3,403
use super::super::super::EnumTrait; use std::str::FromStr; #[derive(Clone, Debug)] pub enum LightRigValues { Balanced, BrightRoom, Chilly, Contrasting, Flat, Flood, Freezing, Glow, Harsh, LegacyFlat1, LegacyFlat2, LegacyFlat3, LegacyFlat4, LegacyHarsh1, LegacyHarsh2, LegacyHarsh3, LegacyHarsh4, LegacyNormal1, LegacyNormal2, LegacyNormal3, LegacyNormal4, Morning, Soft, Sunrise, Sunset, ThreePoints, TwoPoints, } impl Default for LightRigValues { fn default() -> Self { Self::LegacyFlat1 } } impl EnumTrait for LightRigValues { fn get_value_string(&self) -> &str { match &self { Self::Balanced => "balanced", Self::BrightRoom => "brightRoom", Self::Chilly => "chilly", Self::Contrasting => "contrasting", Self::Flat => "flat", Self::Flood => "flood", Self::Freezing => "freezing", Self::Glow => "glow", Self::Harsh => "harsh", Self::LegacyFlat1 => "legacyFlat1", Self::LegacyFlat2 => "legacyFlat2", Self::LegacyFlat3 => "legacyFlat3", Self::LegacyFlat4 => "legacyFlat4", Self::LegacyHarsh1 => "legacyHarsh1", Self::LegacyHarsh2 => "legacyHarsh2", Self::LegacyHarsh3 => "legacyHarsh3", Self::LegacyHarsh4 => "legacyHarsh4", Self::LegacyNormal1 => "legacyNormal1", Self::LegacyNormal2 => "legacyNormal2", Self::LegacyNormal3 => "legacyNormal3", Self::LegacyNormal4 => "legacyNormal4", Self::Morning => "morning", Self::Soft => "soft", Self::Sunrise => "sunrise", Self::Sunset => "sunset", Self::ThreePoints => "threePt", Self::TwoPoints => "twoPt", } } } impl FromStr for LightRigValues { type Err = (); fn from_str(input: &str) -> Result<Self, Self::Err> { match input { "balanced" => Ok(Self::Balanced), "brightRoom" => Ok(Self::BrightRoom), "chilly" => Ok(Self::Chilly), "contrasting" => Ok(Self::Contrasting), "flat" => Ok(Self::Flat), "flood" => Ok(Self::Flood), "freezing" => Ok(Self::Freezing), "glow" => Ok(Self::Glow), "harsh" => Ok(Self::Harsh), "legacyFlat1" => Ok(Self::LegacyFlat1), "legacyFlat2" => Ok(Self::LegacyFlat2), "legacyFlat3" => Ok(Self::LegacyFlat3), "legacyFlat4" => Ok(Self::LegacyFlat4), "legacyHarsh1" => Ok(Self::LegacyHarsh1), "legacyHarsh2" => Ok(Self::LegacyHarsh2), "legacyHarsh3" => Ok(Self::LegacyHarsh3), "legacyHarsh4" => Ok(Self::LegacyHarsh4), "legacyNormal1" => Ok(Self::LegacyNormal1), "legacyNormal2" => Ok(Self::LegacyNormal2), "legacyNormal3" => Ok(Self::LegacyNormal3), "legacyNormal4" => Ok(Self::LegacyNormal4), "morning" => Ok(Self::Morning), "soft" => Ok(Self::Soft), "sunrise" => Ok(Self::Sunrise), "sunset" => Ok(Self::Sunset), "threePt" => Ok(Self::ThreePoints), "twoPt" => Ok(Self::TwoPoints), _ => Err(()), } } }
32.103774
57
0.523949
d73b49e36455c13fb67505b0c8ca6030ddb78886
1,728
use crate::math::{Isometry, Vector}; use crate::query::algorithms::VoronoiSimplex; use crate::query::algorithms::{gjk, gjk::GJKResult, CSOPoint}; use crate::shape::SupportMap; use na::{self, RealField, Unit}; /// Distance between support-mapped shapes. pub fn distance_support_map_support_map<N, G1: ?Sized, G2: ?Sized>( m1: &Isometry<N>, g1: &G1, m2: &Isometry<N>, g2: &G2, ) -> N where N: RealField + Copy, G1: SupportMap<N>, G2: SupportMap<N>, { distance_support_map_support_map_with_params(m1, g1, m2, g2, &mut VoronoiSimplex::new(), None) } /// Distance between support-mapped shapes. /// /// This allows a more fine grained control other the underlying GJK algorigtm. pub fn distance_support_map_support_map_with_params<N, G1: ?Sized, G2: ?Sized>( m1: &Isometry<N>, g1: &G1, m2: &Isometry<N>, g2: &G2, simplex: &mut VoronoiSimplex<N>, init_dir: Option<Vector<N>>, ) -> N where N: RealField + Copy, G1: SupportMap<N>, G2: SupportMap<N>, { // FIXME: or m2.translation - m1.translation ? let dir = init_dir.unwrap_or_else(|| m1.translation.vector - m2.translation.vector); if let Some(dir) = Unit::try_new(dir, N::default_epsilon()) { simplex.reset(CSOPoint::from_shapes(m1, g1, m2, g2, &dir)); } else { simplex.reset(CSOPoint::from_shapes(m1, g1, m2, g2, &Vector::x_axis())); } match gjk::closest_points(m1, g1, m2, g2, N::max_value(), true, simplex) { GJKResult::Intersection => N::zero(), GJKResult::ClosestPoints(p1, p2, _) => na::distance(&p1, &p2), GJKResult::Proximity(_) => unreachable!(), GJKResult::NoIntersection(_) => N::zero(), // FIXME: GJK did not converge. } }
32
98
0.643519
3ae52ae3136d26677685ef5efd4d632e84b7fc55
13,984
//! Raw executor. //! //! This module exposes "raw" Executor and Task structs for more low level control. //! //! ## WARNING: here be dragons! //! //! Using this module requires respecting subtle safety contracts. If you can, prefer using the safe //! executor wrappers in [`crate::executor`] and the [`crate::task`] macro, which are fully safe. mod run_queue; #[cfg(feature = "time")] mod timer_queue; pub(crate) mod util; mod waker; use atomic_polyfill::{AtomicU32, Ordering}; use core::cell::Cell; use core::future::Future; use core::pin::Pin; use core::ptr::NonNull; use core::task::{Context, Poll}; use core::{mem, ptr}; use critical_section::CriticalSection; use self::run_queue::{RunQueue, RunQueueItem}; use self::util::UninitCell; use super::SpawnToken; #[cfg(feature = "time")] use crate::time::driver::{self, AlarmHandle}; #[cfg(feature = "time")] use crate::time::Instant; pub use self::waker::task_from_waker; /// Task is spawned (has a future) pub(crate) const STATE_SPAWNED: u32 = 1 << 0; /// Task is in the executor run queue pub(crate) const STATE_RUN_QUEUED: u32 = 1 << 1; /// Task is in the executor timer queue #[cfg(feature = "time")] pub(crate) const STATE_TIMER_QUEUED: u32 = 1 << 2; /// Raw task header for use in task pointers. /// /// This is an opaque struct, used for raw pointers to tasks, for use /// with funtions like [`wake_task`] and [`task_from_waker`]. pub struct TaskHeader { pub(crate) state: AtomicU32, pub(crate) run_queue_item: RunQueueItem, pub(crate) executor: Cell<*const Executor>, // Valid if state != 0 pub(crate) poll_fn: UninitCell<unsafe fn(NonNull<TaskHeader>)>, // Valid if STATE_SPAWNED #[cfg(feature = "time")] pub(crate) expires_at: Cell<Instant>, #[cfg(feature = "time")] pub(crate) timer_queue_item: timer_queue::TimerQueueItem, } impl TaskHeader { #[cfg(feature = "nightly")] pub(crate) const fn new() -> Self { Self { state: AtomicU32::new(0), run_queue_item: RunQueueItem::new(), executor: Cell::new(ptr::null()), poll_fn: UninitCell::uninit(), #[cfg(feature = "time")] expires_at: Cell::new(Instant::from_ticks(0)), #[cfg(feature = "time")] timer_queue_item: timer_queue::TimerQueueItem::new(), } } #[cfg(not(feature = "nightly"))] pub(crate) fn new() -> Self { Self { state: AtomicU32::new(0), run_queue_item: RunQueueItem::new(), executor: Cell::new(ptr::null()), poll_fn: UninitCell::uninit(), #[cfg(feature = "time")] expires_at: Cell::new(Instant::from_ticks(0)), #[cfg(feature = "time")] timer_queue_item: timer_queue::TimerQueueItem::new(), } } pub(crate) unsafe fn enqueue(&self) { critical_section::with(|cs| { let state = self.state.load(Ordering::Relaxed); // If already scheduled, or if not started, if (state & STATE_RUN_QUEUED != 0) || (state & STATE_SPAWNED == 0) { return; } // Mark it as scheduled self.state .store(state | STATE_RUN_QUEUED, Ordering::Relaxed); // We have just marked the task as scheduled, so enqueue it. let executor = &*self.executor.get(); executor.enqueue(cs, self as *const TaskHeader as *mut TaskHeader); }) } } /// Raw storage in which a task can be spawned. /// /// This struct holds the necessary memory to spawn one task whose future is `F`. /// At a given time, the `Task` may be in spawned or not-spawned state. You may spawn it /// with [`Task::spawn()`], which will fail if it is already spawned. /// /// A `TaskStorage` must live forever, it may not be deallocated even after the task has finished /// running. Hence the relevant methods require `&'static self`. It may be reused, however. /// /// Internally, the [embassy::task](crate::task) macro allocates an array of `TaskStorage`s /// in a `static`. The most common reason to use the raw `Task` is to have control of where /// the memory for the task is allocated: on the stack, or on the heap with e.g. `Box::leak`, etc. // repr(C) is needed to guarantee that the Task is located at offset 0 // This makes it safe to cast between Task and Task pointers. #[repr(C)] pub struct TaskStorage<F: Future + 'static> { raw: TaskHeader, future: UninitCell<F>, // Valid if STATE_SPAWNED } impl<F: Future + 'static> TaskStorage<F> { /// Create a new TaskStorage, in not-spawned state. #[cfg(feature = "nightly")] pub const fn new() -> Self { Self { raw: TaskHeader::new(), future: UninitCell::uninit(), } } /// Create a new TaskStorage, in not-spawned state. #[cfg(not(feature = "nightly"))] pub fn new() -> Self { Self { raw: TaskHeader::new(), future: UninitCell::uninit(), } } /// Try to spawn a task in a pool. /// /// See [`Self::spawn()`] for details. /// /// This will loop over the pool and spawn the task in the first storage that /// is currently free. If none is free, pub fn spawn_pool(pool: &'static [Self], future: impl FnOnce() -> F) -> SpawnToken<F> { for task in pool { if task.spawn_allocate() { return unsafe { task.spawn_initialize(future) }; } } SpawnToken::new_failed() } /// Try to spawn the task. /// /// The `future` closure constructs the future. It's only called if spawning is /// actually possible. It is a closure instead of a simple `future: F` param to ensure /// the future is constructed in-place, avoiding a temporary copy in the stack thanks to /// NRVO optimizations. /// /// This function will fail if the task is already spawned and has not finished running. /// In this case, the error is delayed: a "poisoned" SpawnToken is returned, which will /// cause [`Executor::spawn()`] to return the error. /// /// Once the task has finished running, you may spawn it again. It is allowed to spawn it /// on a different executor. pub fn spawn(&'static self, future: impl FnOnce() -> F) -> SpawnToken<F> { if self.spawn_allocate() { unsafe { self.spawn_initialize(future) } } else { SpawnToken::new_failed() } } fn spawn_allocate(&'static self) -> bool { let state = STATE_SPAWNED | STATE_RUN_QUEUED; self.raw .state .compare_exchange(0, state, Ordering::AcqRel, Ordering::Acquire) .is_ok() } unsafe fn spawn_initialize(&'static self, future: impl FnOnce() -> F) -> SpawnToken<F> { // Initialize the task self.raw.poll_fn.write(Self::poll); self.future.write(future()); SpawnToken::new(NonNull::new_unchecked(&self.raw as *const TaskHeader as _)) } unsafe fn poll(p: NonNull<TaskHeader>) { let this = &*(p.as_ptr() as *const TaskStorage<F>); let future = Pin::new_unchecked(this.future.as_mut()); let waker = waker::from_task(p); let mut cx = Context::from_waker(&waker); match future.poll(&mut cx) { Poll::Ready(_) => { this.future.drop_in_place(); this.raw.state.fetch_and(!STATE_SPAWNED, Ordering::AcqRel); } Poll::Pending => {} } // the compiler is emitting a virtual call for waker drop, but we know // it's a noop for our waker. mem::forget(waker); } } unsafe impl<F: Future + 'static> Sync for TaskStorage<F> {} /// Raw executor. /// /// This is the core of the Embassy executor. It is low-level, requiring manual /// handling of wakeups and task polling. If you can, prefer using one of the /// higher level executors in [`crate::executor`]. /// /// The raw executor leaves it up to you to handle wakeups and scheduling: /// /// - To get the executor to do work, call `poll()`. This will poll all queued tasks (all tasks /// that "want to run"). /// - You must supply a `signal_fn`. The executor will call it to notify you it has work /// to do. You must arrange for `poll()` to be called as soon as possible. /// /// `signal_fn` can be called from *any* context: any thread, any interrupt priority /// level, etc. It may be called synchronously from any `Executor` method call as well. /// You must deal with this correctly. /// /// In particular, you must NOT call `poll` directly from `signal_fn`, as this violates /// the requirement for `poll` to not be called reentrantly. pub struct Executor { run_queue: RunQueue, signal_fn: fn(*mut ()), signal_ctx: *mut (), #[cfg(feature = "time")] pub(crate) timer_queue: timer_queue::TimerQueue, #[cfg(feature = "time")] alarm: AlarmHandle, } impl Executor { /// Create a new executor. /// /// When the executor has work to do, it will call `signal_fn` with /// `signal_ctx` as argument. /// /// See [`Executor`] docs for details on `signal_fn`. pub fn new(signal_fn: fn(*mut ()), signal_ctx: *mut ()) -> Self { #[cfg(feature = "time")] let alarm = unsafe { unwrap!(driver::allocate_alarm()) }; #[cfg(feature = "time")] driver::set_alarm_callback(alarm, signal_fn, signal_ctx); Self { run_queue: RunQueue::new(), signal_fn, signal_ctx, #[cfg(feature = "time")] timer_queue: timer_queue::TimerQueue::new(), #[cfg(feature = "time")] alarm, } } /// Enqueue a task in the task queue /// /// # Safety /// - `task` must be a valid pointer to a spawned task. /// - `task` must be set up to run in this executor. /// - `task` must NOT be already enqueued (in this executor or another one). #[inline(always)] unsafe fn enqueue(&self, cs: CriticalSection, task: *mut TaskHeader) { if self.run_queue.enqueue(cs, task) { (self.signal_fn)(self.signal_ctx) } } /// Spawn a task in this executor. /// /// # Safety /// /// `task` must be a valid pointer to an initialized but not-already-spawned task. /// /// It is OK to use `unsafe` to call this from a thread that's not the executor thread. /// In this case, the task's Future must be Send. This is because this is effectively /// sending the task to the executor thread. pub(super) unsafe fn spawn(&'static self, task: NonNull<TaskHeader>) { let task = task.as_ref(); task.executor.set(self); critical_section::with(|cs| { self.enqueue(cs, task as *const _ as _); }) } /// Poll all queued tasks in this executor. /// /// This loops over all tasks that are queued to be polled (i.e. they're /// freshly spawned or they've been woken). Other tasks are not polled. /// /// You must call `poll` after receiving a call to `signal_fn`. It is OK /// to call `poll` even when not requested by `signal_fn`, but it wastes /// energy. /// /// # Safety /// /// You must NOT call `poll` reentrantly on the same executor. /// /// In particular, note that `poll` may call `signal_fn` synchronously. Therefore, you /// must NOT directly call `poll()` from your `signal_fn`. Instead, `signal_fn` has to /// somehow schedule for `poll()` to be called later, at a time you know for sure there's /// no `poll()` already running. pub unsafe fn poll(&'static self) { #[cfg(feature = "time")] self.timer_queue.dequeue_expired(Instant::now(), |p| { p.as_ref().enqueue(); }); self.run_queue.dequeue_all(|p| { let task = p.as_ref(); #[cfg(feature = "time")] task.expires_at.set(Instant::MAX); let state = task.state.fetch_and(!STATE_RUN_QUEUED, Ordering::AcqRel); if state & STATE_SPAWNED == 0 { // If task is not running, ignore it. This can happen in the following scenario: // - Task gets dequeued, poll starts // - While task is being polled, it gets woken. It gets placed in the queue. // - Task poll finishes, returning done=true // - RUNNING bit is cleared, but the task is already in the queue. return; } // Run the task task.poll_fn.read()(p as _); // Enqueue or update into timer_queue #[cfg(feature = "time")] self.timer_queue.update(p); }); #[cfg(feature = "time")] { // If this is already in the past, set_alarm will immediately trigger the alarm. // This will cause `signal_fn` to be called, which will cause `poll()` to be called again, // so we immediately do another poll loop iteration. let next_expiration = self.timer_queue.next_expiration(); driver::set_alarm(self.alarm, next_expiration.as_ticks()); } } /// Get a spawner that spawns tasks in this executor. /// /// It is OK to call this method multiple times to obtain multiple /// `Spawner`s. You may also copy `Spawner`s. pub fn spawner(&'static self) -> super::Spawner { super::Spawner::new(self) } } /// Wake a task by raw pointer. /// /// You can obtain task pointers from `Waker`s using [`task_from_waker`]. pub unsafe fn wake_task(task: NonNull<TaskHeader>) { task.as_ref().enqueue(); } #[cfg(feature = "time")] pub(crate) unsafe fn register_timer(at: Instant, waker: &core::task::Waker) { let task = waker::task_from_waker(waker); let task = task.as_ref(); let expires_at = task.expires_at.get(); task.expires_at.set(expires_at.min(at)); }
35.764706
102
0.605478
33c8605066686f028d971a22de2e1e63562cee45
2,306
// compile-flags: -C no-prepopulate-passes #![crate_type = "lib"] #![feature(repr_simd, platform_intrinsics)] #![allow(non_camel_case_types)] #[repr(simd)] #[derive(Copy, Clone, PartialEq, Debug)] pub struct f32x2(pub f32, pub f32); #[repr(simd)] #[derive(Copy, Clone, PartialEq, Debug)] pub struct f32x4(pub f32, pub f32, pub f32, pub f32); #[repr(simd)] #[derive(Copy, Clone, PartialEq, Debug)] pub struct f32x8(pub f32, pub f32, pub f32, pub f32, pub f32, pub f32, pub f32, pub f32); #[repr(simd)] #[derive(Copy, Clone, PartialEq, Debug)] pub struct f32x16(pub f32, pub f32, pub f32, pub f32, pub f32, pub f32, pub f32, pub f32, pub f32, pub f32, pub f32, pub f32, pub f32, pub f32, pub f32, pub f32); extern "platform-intrinsic" { fn simd_fexp<T>(x: T) -> T; } // CHECK-LABEL: @exp_32x2 #[no_mangle] pub unsafe fn exp_32x2(a: f32x2) -> f32x2 { // CHECK: call fast <2 x float> @llvm.exp.v2f32 simd_fexp(a) } // CHECK-LABEL: @exp_32x4 #[no_mangle] pub unsafe fn exp_32x4(a: f32x4) -> f32x4 { // CHECK: call fast <4 x float> @llvm.exp.v4f32 simd_fexp(a) } // CHECK-LABEL: @exp_32x8 #[no_mangle] pub unsafe fn exp_32x8(a: f32x8) -> f32x8 { // CHECK: call fast <8 x float> @llvm.exp.v8f32 simd_fexp(a) } // CHECK-LABEL: @exp_32x16 #[no_mangle] pub unsafe fn exp_32x16(a: f32x16) -> f32x16 { // CHECK: call fast <16 x float> @llvm.exp.v16f32 simd_fexp(a) } #[repr(simd)] #[derive(Copy, Clone, PartialEq, Debug)] pub struct f64x2(pub f64, pub f64); #[repr(simd)] #[derive(Copy, Clone, PartialEq, Debug)] pub struct f64x4(pub f64, pub f64, pub f64, pub f64); #[repr(simd)] #[derive(Copy, Clone, PartialEq, Debug)] pub struct f64x8(pub f64, pub f64, pub f64, pub f64, pub f64, pub f64, pub f64, pub f64); // CHECK-LABEL: @exp_64x4 #[no_mangle] pub unsafe fn exp_64x4(a: f64x4) -> f64x4 { // CHECK: call fast <4 x double> @llvm.exp.v4f64 simd_fexp(a) } // CHECK-LABEL: @exp_64x2 #[no_mangle] pub unsafe fn exp_64x2(a: f64x2) -> f64x2 { // CHECK: call fast <2 x double> @llvm.exp.v2f64 simd_fexp(a) } // CHECK-LABEL: @exp_64x8 #[no_mangle] pub unsafe fn exp_64x8(a: f64x8) -> f64x8 { // CHECK: call fast <8 x double> @llvm.exp.v8f64 simd_fexp(a) }
24.795699
54
0.636167
08c527d21a28cef6530c7e7833736ef23ae6457c
29,471
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. // TODO: remove it after all code been merged. #![allow(unused_variables)] #![allow(dead_code)] use std::cmp; use std::fmt; use std::sync::atomic::*; use std::sync::*; use std::time::*; use engine::DB; use external_storage::*; use futures::sync::mpsc::*; use futures::{lazy, Future}; use kvproto::backup::*; use kvproto::kvrpcpb::{Context, IsolationLevel}; use kvproto::metapb::*; use raft::StateRole; use tikv::raftstore::coprocessor::RegionInfoAccessor; use tikv::raftstore::store::util::find_peer; use tikv::server::transport::ServerRaftStoreRouter; use tikv::storage::kv::{ Engine, Error as EngineError, RegionInfoProvider, ScanMode, StatisticsSummary, }; use tikv::storage::txn::{ EntryBatch, Error as TxnError, Msg, Scanner, SnapshotStore, Store, TxnEntryScanner, TxnEntryStore, }; use tikv::storage::{Key, Statistics}; use tikv_util::worker::{Runnable, RunnableWithTimer}; use tokio_threadpool::{Builder as ThreadPoolBuilder, ThreadPool}; use crate::metrics::*; use crate::*; /// Backup task. pub struct Task { start_key: Vec<u8>, end_key: Vec<u8>, start_ts: u64, end_ts: u64, storage: Arc<dyn ExternalStorage>, pub(crate) resp: UnboundedSender<BackupResponse>, cancel: Arc<AtomicBool>, } impl fmt::Display for Task { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self) } } impl fmt::Debug for Task { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("BackupTask") .field("start_ts", &self.start_ts) .field("end_ts", &self.end_ts) .field("start_key", &hex::encode_upper(&self.start_key)) .field("end_key", &hex::encode_upper(&self.end_key)) .finish() } } impl Task { /// Create a backup task based on the given backup request. pub fn new( req: BackupRequest, resp: UnboundedSender<BackupResponse>, ) -> Result<(Task, Arc<AtomicBool>)> { let start_key = req.get_start_key().to_owned(); let end_key = req.get_end_key().to_owned(); let start_ts = req.get_start_version(); let end_ts = req.get_end_version(); let storage = create_storage(req.get_path())?; let cancel = Arc::new(AtomicBool::new(false)); Ok(( Task { start_key, end_key, start_ts, end_ts, resp, storage, cancel: cancel.clone(), }, cancel, )) } /// Check whether the task is canceled. pub fn has_canceled(&self) -> bool { self.cancel.load(Ordering::SeqCst) } } #[derive(Debug)] pub struct BackupRange { start_key: Option<Key>, end_key: Option<Key>, region: Region, leader: Peer, cancel: Arc<AtomicBool>, } impl BackupRange { fn has_canceled(&self) -> bool { self.cancel.load(Ordering::SeqCst) } } type BackupRes = (Vec<File>, Statistics); /// The endpoint of backup. /// /// It coordinates backup tasks and dispatches them to different workers. pub struct Endpoint<E: Engine, R: RegionInfoProvider> { store_id: u64, workers: ThreadPool, db: Arc<DB>, pub(crate) engine: E, pub(crate) region_info: R, } impl<E: Engine, R: RegionInfoProvider> Endpoint<E, R> { pub fn new(store_id: u64, engine: E, region_info: R, db: Arc<DB>) -> Endpoint<E, R> { let workers = ThreadPoolBuilder::new().name_prefix("backworker").build(); Endpoint { store_id, engine, region_info, // TODO: support more config. workers, db, } } fn seek_backup_range( &self, start_key: Option<Key>, end_key: Option<Key>, cancel: Arc<AtomicBool>, ) -> mpsc::Receiver<BackupRange> { let store_id = self.store_id; let (tx, rx) = mpsc::channel(); let start_key_ = start_key .clone() .map_or_else(Vec::new, |k| k.into_encoded()); let res = self.region_info.seek_region( &start_key_, Box::new(move |iter| { for info in iter { let region = &info.region; if end_key.is_some() { let end_slice = end_key.as_ref().unwrap().as_encoded().as_slice(); if end_slice <= region.get_start_key() { // We have reached the end. // The range is defined as [start, end) so break if // region start key is greater or equal to end key. break; } } if info.role == StateRole::Leader { let ekey = get_min_end_key(end_key.as_ref(), &region); let skey = get_max_start_key(start_key.as_ref(), &region); assert!(!(skey == ekey && ekey.is_some()), "{:?} {:?}", skey, ekey); let leader = find_peer(region, store_id).unwrap().to_owned(); let backup_range = BackupRange { start_key: skey, end_key: ekey, region: region.clone(), leader, cancel: cancel.clone(), }; tx.send(backup_range).unwrap(); } } }), ); if let Err(e) = res { // TODO: handle error. error!("backup seek region failed"; "error" => ?e); } rx } fn dispatch_backup_range( &self, brange: BackupRange, start_ts: u64, end_ts: u64, storage: Arc<dyn ExternalStorage>, tx: mpsc::Sender<(BackupRange, Result<BackupRes>)>, ) { // TODO: support incremental backup let _ = start_ts; let backup_ts = end_ts; let mut ctx = Context::new(); ctx.set_region_id(brange.region.get_id()); ctx.set_region_epoch(brange.region.get_region_epoch().to_owned()); ctx.set_peer(brange.leader.clone()); // TODO: make it async. let snapshot = match self.engine.snapshot(&ctx) { Ok(s) => s, Err(e) => { error!("backup snapshot failed"; "error" => ?e); return tx.send((brange, Err(e.into()))).unwrap(); } }; let db = self.db.clone(); let store_id = self.store_id; self.workers.spawn(lazy(move || { if brange.has_canceled() { warn!("backup task has canceled"; "range" => ?brange); return Ok(()); } let snap_store = SnapshotStore::new( snapshot, backup_ts, IsolationLevel::Si, false, /* fill_cache */ ); let start_key = brange.start_key.clone(); let end_key = brange.end_key.clone(); let mut scanner = snap_store .entry_scanner(start_key.clone(), end_key.clone()) .unwrap(); let mut batch = EntryBatch::with_capacity(1024); let name = backup_file_name(store_id, &brange.region); let mut writer = match BackupWriter::new(db, &name) { Ok(w) => w, Err(e) => { error!("backup writer failed"; "error" => ?e); return tx.send((brange, Err(e))).map_err(|_| ()); } }; let start = Instant::now(); loop { if let Err(e) = scanner.scan_entries(&mut batch) { error!("backup scan entries failed"; "error" => ?e); return tx.send((brange, Err(e.into()))).map_err(|_| ()); }; if batch.is_empty() { break; } debug!("backup scan entries"; "len" => batch.len()); // Build sst files. if let Err(e) = writer.write(batch.drain()) { error!("backup build sst failed"; "error" => ?e); return tx.send((brange, Err(e))).map_err(|_| ()); } } BACKUP_RANGE_HISTOGRAM_VEC .with_label_values(&["scan"]) .observe(start.elapsed().as_secs_f64()); // Save sst files to storage. let files = match writer.save(&storage) { Ok(files) => files, Err(e) => { error!("backup save file failed"; "error" => ?e); return tx.send((brange, Err(e))).map_err(|_| ()); } }; let stat = scanner.take_statistics(); tx.send((brange, Ok((files, stat)))).map_err(|_| ()) })); } pub fn handle_backup_task(&self, task: Task) { let start = Instant::now(); let start_key = if task.start_key.is_empty() { None } else { Some(Key::from_raw(&task.start_key)) }; let end_key = if task.end_key.is_empty() { None } else { Some(Key::from_raw(&task.end_key)) }; let rx = self.seek_backup_range(start_key, end_key, task.cancel); let (res_tx, res_rx) = mpsc::channel(); for brange in rx { let tx = res_tx.clone(); self.dispatch_backup_range( brange, task.start_ts, task.end_ts, task.storage.clone(), tx, ); } // Drop the extra sender so that for loop does not hang up. drop(res_tx); let mut summary = Statistics::default(); let resp = task.resp; for (brange, res) in res_rx { let start_key = brange .start_key .map_or_else(|| vec![], |k| k.into_raw().unwrap()); let end_key = brange .end_key .map_or_else(|| vec![], |k| k.into_raw().unwrap()); let mut response = BackupResponse::new(); response.set_start_key(start_key.clone()); response.set_end_key(end_key.clone()); match res { Ok((mut files, stat)) => { info!("backup region finish"; "region" => ?brange.region, "start_key" => hex::encode_upper(&start_key), "end_key" => hex::encode_upper(&end_key), "details" => ?stat); summary.add(&stat); // Fill key range and ts. for file in files.iter_mut() { file.set_start_key(start_key.clone()); file.set_end_key(end_key.clone()); file.set_start_version(task.start_ts); file.set_end_version(task.end_ts); } response.set_files(files.into()); } Err(e) => { error!("backup region failed"; "region" => ?brange.region, "start_key" => hex::encode_upper(response.get_start_key()), "end_key" => hex::encode_upper(response.get_end_key()), "error" => ?e); response.set_error(e.into()); } } if let Err(e) = resp.unbounded_send(response) { error!("backup failed to send response"; "error" => ?e); break; } } let duration = start.elapsed(); BACKUP_REQUEST_HISTOGRAM.observe(duration.as_secs_f64()); info!("backup finished"; "take" => ?duration, "summary" => ?summary); } } impl<E: Engine, R: RegionInfoProvider> Runnable<Task> for Endpoint<E, R> { fn run(&mut self, task: Task) { if task.has_canceled() { warn!("backup task has canceled"; "task" => %task); return; } info!("run backup task"; "task" => %task); if task.start_ts == task.end_ts { self.handle_backup_task(task); } else { // TODO: support incremental backup BACKUP_RANGE_ERROR_VEC .with_label_values(&["incremental"]) .inc(); error!("incremental backup is not supported yet"); } } } /// Get the min end key from the given `end_key` and `Region`'s end key. fn get_min_end_key(end_key: Option<&Key>, region: &Region) -> Option<Key> { let region_end = if region.get_end_key().is_empty() { None } else { Some(Key::from_encoded_slice(region.get_end_key())) }; if region.get_end_key().is_empty() { end_key.cloned() } else if end_key.is_none() { region_end } else { let end_slice = end_key.as_ref().unwrap().as_encoded().as_slice(); if end_slice < region.get_end_key() { end_key.cloned() } else { region_end } } } /// Get the max start key from the given `start_key` and `Region`'s start key. fn get_max_start_key(start_key: Option<&Key>, region: &Region) -> Option<Key> { let region_start = if region.get_start_key().is_empty() { None } else { Some(Key::from_encoded_slice(region.get_start_key())) }; if start_key.is_none() { region_start } else { let start_slice = start_key.as_ref().unwrap().as_encoded().as_slice(); if start_slice < region.get_start_key() { region_start } else { start_key.cloned() } } } /// Construct an backup file name based on the given store id and region. /// A name consists with three parts: store id, region_id and a epoch version. fn backup_file_name(store_id: u64, region: &Region) -> String { format!( "{}_{}_{}", store_id, region.get_id(), region.get_region_epoch().get_version() ) } #[cfg(test)] pub mod tests { use super::*; use external_storage::LocalStorage; use futures::{Future, Stream}; use kvproto::metapb; use std::collections::BTreeMap; use std::sync::mpsc::{channel, Receiver, Sender}; use tempfile::TempDir; use tikv::raftstore::coprocessor::RegionCollector; use tikv::raftstore::coprocessor::{RegionInfo, SeekRegionCallback}; use tikv::raftstore::store::util::new_peer; use tikv::storage::kv::Result as EngineResult; use tikv::storage::mvcc::tests::*; use tikv::storage::SHORT_VALUE_MAX_LEN; use tikv::storage::{ Mutation, Options, RocksEngine, Storage, TestEngineBuilder, TestStorageBuilder, }; #[derive(Clone)] pub struct MockRegionInfoProvider { regions: Arc<Mutex<RegionCollector>>, cancel: Option<Arc<AtomicBool>>, } impl MockRegionInfoProvider { pub fn new() -> Self { MockRegionInfoProvider { regions: Arc::new(Mutex::new(RegionCollector::new())), cancel: None, } } pub fn set_regions(&self, regions: Vec<(Vec<u8>, Vec<u8>, u64)>) { let mut map = self.regions.lock().unwrap(); for (mut start_key, mut end_key, id) in regions { if !start_key.is_empty() { start_key = Key::from_raw(&start_key).into_encoded(); } if !end_key.is_empty() { end_key = Key::from_raw(&end_key).into_encoded(); } let mut r = metapb::Region::default(); r.set_id(id); r.set_start_key(start_key.clone()); r.set_end_key(end_key); r.mut_peers().push(new_peer(1, 1)); map.create_region(r, StateRole::Leader); } } fn canecl_on_seek(&mut self, cancel: Arc<AtomicBool>) { self.cancel = Some(cancel); } } impl RegionInfoProvider for MockRegionInfoProvider { fn seek_region(&self, from: &[u8], callback: SeekRegionCallback) -> EngineResult<()> { let from = from.to_vec(); let regions = self.regions.lock().unwrap(); if let Some(c) = self.cancel.as_ref() { c.store(true, Ordering::SeqCst); } regions.handle_seek_region(from, callback); Ok(()) } } pub fn new_endpoint() -> (TempDir, Endpoint<RocksEngine, MockRegionInfoProvider>) { let temp = TempDir::new().unwrap(); let rocks = TestEngineBuilder::new() .path(temp.path()) .cfs(&[engine::CF_DEFAULT, engine::CF_LOCK, engine::CF_WRITE]) .build() .unwrap(); let db = rocks.get_rocksdb(); ( temp, Endpoint::new(1, rocks, MockRegionInfoProvider::new(), db), ) } pub fn check_response<F>(rx: UnboundedReceiver<BackupResponse>, check: F) where F: FnOnce(Option<BackupResponse>), { let (resp, rx) = rx.into_future().wait().unwrap(); check(resp); let (none, _rx) = rx.into_future().wait().unwrap(); assert!(none.is_none(), "{:?}", none); } #[test] fn test_seek_range() { let (_tmp, endpoint) = new_endpoint(); endpoint.region_info.set_regions(vec![ (b"".to_vec(), b"1".to_vec(), 1), (b"1".to_vec(), b"2".to_vec(), 2), (b"3".to_vec(), b"4".to_vec(), 3), (b"7".to_vec(), b"9".to_vec(), 4), (b"9".to_vec(), b"".to_vec(), 5), ]); // Test seek backup range. let test_seek_backup_range = |start_key: &[u8], end_key: &[u8], expect: Vec<(&[u8], &[u8])>| { let start_key = if start_key.is_empty() { None } else { Some(Key::from_raw(start_key)) }; let end_key = if end_key.is_empty() { None } else { Some(Key::from_raw(end_key)) }; let rx = endpoint.seek_backup_range(start_key, end_key, Arc::default()); let ranges: Vec<BackupRange> = rx.into_iter().collect(); assert_eq!( ranges.len(), expect.len(), "got {:?}, expect {:?}", ranges, expect ); for (a, b) in ranges.into_iter().zip(expect) { assert_eq!( a.start_key.map_or_else(Vec::new, |k| k.into_raw().unwrap()), b.0 ); assert_eq!( a.end_key.map_or_else(Vec::new, |k| k.into_raw().unwrap()), b.1 ); } }; // Test whether responses contain correct range. #[allow(clippy::block_in_if_condition_stmt)] let test_handle_backup_task_range = |start_key: &[u8], end_key: &[u8], expect: Vec<(&[u8], &[u8])>| { let tmp = TempDir::new().unwrap(); let ls = LocalStorage::new(tmp.path()).unwrap(); let (tx, rx) = unbounded(); let task = Task { start_key: start_key.to_vec(), end_key: end_key.to_vec(), start_ts: 1, end_ts: 1, resp: tx, storage: Arc::new(ls), cancel: Arc::default(), }; endpoint.handle_backup_task(task); let resps: Vec<_> = rx.collect().wait().unwrap(); for a in &resps { assert!( expect .iter() .any(|b| { a.get_start_key() == b.0 && a.get_end_key() == b.1 }), "{:?} {:?}", resps, expect ); } assert_eq!(resps.len(), expect.len()); }; // Backup range from case.0 to case.1, // the case.2 is the expected results. type Case<'a> = (&'a [u8], &'a [u8], Vec<(&'a [u8], &'a [u8])>); let case: Vec<Case> = vec![ (b"", b"1", vec![(b"", b"1")]), (b"", b"2", vec![(b"", b"1"), (b"1", b"2")]), (b"1", b"2", vec![(b"1", b"2")]), (b"1", b"3", vec![(b"1", b"2")]), (b"1", b"4", vec![(b"1", b"2"), (b"3", b"4")]), (b"4", b"6", vec![]), (b"4", b"5", vec![]), (b"2", b"7", vec![(b"3", b"4")]), (b"3", b"", vec![(b"3", b"4"), (b"7", b"9"), (b"9", b"")]), (b"5", b"", vec![(b"7", b"9"), (b"9", b"")]), (b"7", b"", vec![(b"7", b"9"), (b"9", b"")]), (b"8", b"91", vec![(b"8", b"9"), (b"9", b"91")]), (b"8", b"", vec![(b"8", b"9"), (b"9", b"")]), ( b"", b"", vec![ (b"", b"1"), (b"1", b"2"), (b"3", b"4"), (b"7", b"9"), (b"9", b""), ], ), ]; for (start_key, end_key, ranges) in case { test_seek_backup_range(start_key, end_key, ranges.clone()); test_handle_backup_task_range(start_key, end_key, ranges); } } #[test] fn test_handle_backup_task() { let (tmp, endpoint) = new_endpoint(); let engine = endpoint.engine.clone(); endpoint .region_info .set_regions(vec![(b"".to_vec(), b"5".to_vec(), 1)]); let mut ts = 1; let mut alloc_ts = || { ts += 1; ts }; let mut backup_tss = vec![]; // Multi-versions for key 0..9. for len in &[SHORT_VALUE_MAX_LEN - 1, SHORT_VALUE_MAX_LEN * 2] { for i in 0..10u8 { let start = alloc_ts(); let commit = alloc_ts(); let key = format!("{}", i); must_prewrite_put( &engine, key.as_bytes(), &vec![i; *len], key.as_bytes(), start, ); must_commit(&engine, key.as_bytes(), start, commit); backup_tss.push((alloc_ts(), len)); } } // TODO: check key number for each snapshot. for (ts, len) in backup_tss { let mut req = BackupRequest::new(); req.set_start_key(vec![]); req.set_end_key(vec![b'5']); req.set_start_version(ts); req.set_end_version(ts); let (tx, rx) = unbounded(); // Empty path should return an error. Task::new(req.clone(), tx.clone()).unwrap_err(); // Set an unique path to avoid AlreadyExists error. req.set_path(format!( "local://{}", tmp.path().join(format!("{}", ts)).display() )); let (task, _) = Task::new(req, tx).unwrap(); endpoint.handle_backup_task(task); let (resp, rx) = rx.into_future().wait().unwrap(); let resp = resp.unwrap(); assert!(!resp.has_error(), "{:?}", resp); let file_len = if *len <= SHORT_VALUE_MAX_LEN { 1 } else { 2 }; assert_eq!( resp.get_files().len(), file_len, /* default and write */ "{:?}", resp ); let (none, _rx) = rx.into_future().wait().unwrap(); assert!(none.is_none(), "{:?}", none); } } #[test] fn test_scan_error() { let (tmp, endpoint) = new_endpoint(); let engine = endpoint.engine.clone(); endpoint .region_info .set_regions(vec![(b"".to_vec(), b"5".to_vec(), 1)]); let mut ts = 1; let mut alloc_ts = || { ts += 1; ts }; let start = alloc_ts(); let key = format!("{}", start); must_prewrite_put( &engine, key.as_bytes(), key.as_bytes(), key.as_bytes(), start, ); let now = alloc_ts(); let mut req = BackupRequest::new(); req.set_start_key(vec![]); req.set_end_key(vec![b'5']); req.set_start_version(now); req.set_end_version(now); // Set an unique path to avoid AlreadyExists error. req.set_path(format!( "local://{}", tmp.path().join(format!("{}", now)).display() )); let (tx, rx) = unbounded(); let (task, _) = Task::new(req.clone(), tx).unwrap(); endpoint.handle_backup_task(task); check_response(rx, |resp| { let resp = resp.unwrap(); assert!(resp.get_error().has_kv_error(), "{:?}", resp); assert!(resp.get_error().get_kv_error().has_locked(), "{:?}", resp); assert_eq!(resp.get_files().len(), 0, "{:?}", resp); }); // Commit the perwrite. let commit = alloc_ts(); must_commit(&engine, key.as_bytes(), start, commit); // Test whether it can correctly convert not leader to regoin error. engine.trigger_not_leader(); let now = alloc_ts(); req.set_start_version(now); req.set_end_version(now); // Set an unique path to avoid AlreadyExists error. req.set_path(format!( "local://{}", tmp.path().join(format!("{}", now)).display() )); let (tx, rx) = unbounded(); let (task, _) = Task::new(req.clone(), tx).unwrap(); endpoint.handle_backup_task(task); check_response(rx, |resp| { let resp = resp.unwrap(); assert!(resp.get_error().has_region_error(), "{:?}", resp); assert!( resp.get_error().get_region_error().has_not_leader(), "{:?}", resp ); }); } #[test] fn test_cancel() { let (temp, mut endpoint) = new_endpoint(); let engine = endpoint.engine.clone(); endpoint .region_info .set_regions(vec![(b"".to_vec(), b"5".to_vec(), 1)]); let mut ts = 1; let mut alloc_ts = || { ts += 1; ts }; let start = alloc_ts(); let key = format!("{}", start); must_prewrite_put( &engine, key.as_bytes(), key.as_bytes(), key.as_bytes(), start, ); // Commit the perwrite. let commit = alloc_ts(); must_commit(&engine, key.as_bytes(), start, commit); let now = alloc_ts(); let mut req = BackupRequest::new(); req.set_start_key(vec![]); req.set_end_key(vec![]); req.set_start_version(now); req.set_end_version(now); req.set_path(format!("local://{}", temp.path().display())); // Cancel the task before starting the task. let (tx, rx) = unbounded(); let (task, cancel) = Task::new(req.clone(), tx).unwrap(); // Cancel the task. cancel.store(true, Ordering::SeqCst); endpoint.handle_backup_task(task); check_response(rx, |resp| { assert!(resp.is_none()); }); // Cancel the task during backup. let (tx, rx) = unbounded(); let (task, cancel) = Task::new(req.clone(), tx).unwrap(); endpoint.region_info.canecl_on_seek(cancel); endpoint.handle_backup_task(task); check_response(rx, |resp| { assert!(resp.is_none()); }); } #[test] fn test_busy() { let (_tmp, endpoint) = new_endpoint(); let engine = endpoint.engine.clone(); endpoint .region_info .set_regions(vec![(b"".to_vec(), b"5".to_vec(), 1)]); let mut req = BackupRequest::new(); req.set_start_key(vec![]); req.set_end_key(vec![]); req.set_start_version(1); req.set_end_version(1); req.set_path("noop://foo".to_owned()); let (tx, rx) = unbounded(); let (task, _) = Task::new(req.clone(), tx).unwrap(); // Pause the engine 6 seconds to trigger Timeout error. // The Timeout error is translated to server is busy. engine.pause(Duration::from_secs(6)); endpoint.handle_backup_task(task); check_response(rx, |resp| { let resp = resp.unwrap(); assert!(resp.get_error().has_region_error(), "{:?}", resp); assert!( resp.get_error().get_region_error().has_server_is_busy(), "{:?}", resp ); }); } // TODO: region err in txn(engine(request)) }
34.590376
94
0.485257
1cbb5387d6416201ea1cc237532ad7b5b23f442a
5,724
// Copyright 2017-2019 Parity Technologies (UK) Ltd. // This file is part of Substrate. // Substrate is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Substrate is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Substrate. If not, see <http://www.gnu.org/licenses/>. //! On-demand requests service. use crate::protocol::on_demand::RequestData; use std::sync::Arc; use futures::{prelude::*, sync::mpsc, sync::oneshot}; use futures03::compat::{Compat01As03, Future01CompatExt as _}; use parking_lot::Mutex; use client::error::Error as ClientError; use client::light::fetcher::{Fetcher, FetchChecker, RemoteHeaderRequest, RemoteCallRequest, RemoteReadRequest, RemoteChangesRequest, RemoteReadChildRequest, RemoteBodyRequest}; use sr_primitives::traits::{Block as BlockT, Header as HeaderT, NumberFor}; /// Implements the `Fetcher` trait of the client. Makes it possible for the light client to perform /// network requests for some state. /// /// This implementation stores all the requests in a queue. The network, in parallel, is then /// responsible for pulling elements out of that queue and fulfilling them. pub struct OnDemand<B: BlockT> { /// Objects that checks whether what has been retrieved is correct. checker: Arc<dyn FetchChecker<B>>, /// Queue of requests. Set to `Some` at initialization, then extracted by the network. /// /// Note that a better alternative would be to use a MPMC queue here, and add a `poll` method /// from the `OnDemand`. However there exists no popular implementation of MPMC channels in /// asynchronous Rust at the moment requests_queue: Mutex<Option<mpsc::UnboundedReceiver<RequestData<B>>>>, /// Sending side of `requests_queue`. requests_send: mpsc::UnboundedSender<RequestData<B>>, } impl<B: BlockT> OnDemand<B> where B::Header: HeaderT, { /// Creates new on-demand service. pub fn new(checker: Arc<dyn FetchChecker<B>>) -> Self { let (requests_send, requests_queue) = mpsc::unbounded(); let requests_queue = Mutex::new(Some(requests_queue)); OnDemand { checker, requests_queue, requests_send, } } /// Get checker reference. pub fn checker(&self) -> &Arc<dyn FetchChecker<B>> { &self.checker } /// Extracts the queue of requests. /// /// Whenever one of the methods of the `Fetcher` trait is called, an element is pushed on this /// channel. /// /// If this function returns `None`, that means that the receiver has already been extracted in /// the past, and therefore that something already handles the requests. pub(crate) fn extract_receiver(&self) -> Option<mpsc::UnboundedReceiver<RequestData<B>>> { self.requests_queue.lock().take() } } impl<B> Fetcher<B> for OnDemand<B> where B: BlockT, B::Header: HeaderT, { type RemoteHeaderResult = Compat01As03<RemoteResponse<B::Header>>; type RemoteReadResult = Compat01As03<RemoteResponse<Option<Vec<u8>>>>; type RemoteCallResult = Compat01As03<RemoteResponse<Vec<u8>>>; type RemoteChangesResult = Compat01As03<RemoteResponse<Vec<(NumberFor<B>, u32)>>>; type RemoteBodyResult = Compat01As03<RemoteResponse<Vec<B::Extrinsic>>>; fn remote_header(&self, request: RemoteHeaderRequest<B::Header>) -> Self::RemoteHeaderResult { let (sender, receiver) = oneshot::channel(); let _ = self.requests_send.unbounded_send(RequestData::RemoteHeader(request, sender)); RemoteResponse { receiver }.compat() } fn remote_read(&self, request: RemoteReadRequest<B::Header>) -> Self::RemoteReadResult { let (sender, receiver) = oneshot::channel(); let _ = self.requests_send.unbounded_send(RequestData::RemoteRead(request, sender)); RemoteResponse { receiver }.compat() } fn remote_read_child( &self, request: RemoteReadChildRequest<B::Header> ) -> Self::RemoteReadResult { let (sender, receiver) = oneshot::channel(); let _ = self.requests_send.unbounded_send(RequestData::RemoteReadChild(request, sender)); RemoteResponse { receiver }.compat() } fn remote_call(&self, request: RemoteCallRequest<B::Header>) -> Self::RemoteCallResult { let (sender, receiver) = oneshot::channel(); let _ = self.requests_send.unbounded_send(RequestData::RemoteCall(request, sender)); RemoteResponse { receiver }.compat() } fn remote_changes(&self, request: RemoteChangesRequest<B::Header>) -> Self::RemoteChangesResult { let (sender, receiver) = oneshot::channel(); let _ = self.requests_send.unbounded_send(RequestData::RemoteChanges(request, sender)); RemoteResponse { receiver }.compat() } fn remote_body(&self, request: RemoteBodyRequest<B::Header>) -> Self::RemoteBodyResult { let (sender, receiver) = oneshot::channel(); let _ = self.requests_send.unbounded_send(RequestData::RemoteBody(request, sender)); RemoteResponse { receiver }.compat() } } /// Future for an on-demand remote call response. pub struct RemoteResponse<T> { receiver: oneshot::Receiver<Result<T, ClientError>>, } impl<T> Future for RemoteResponse<T> { type Item = T; type Error = ClientError; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { self.receiver.poll() .map_err(|_| ClientError::RemoteFetchCancelled.into()) .and_then(|r| match r { Async::Ready(Ok(ready)) => Ok(Async::Ready(ready)), Async::Ready(Err(error)) => Err(error), Async::NotReady => Ok(Async::NotReady), }) } }
37.907285
99
0.733229
7605c756d7feca9f7b10ffced71fd0167dd432dd
11,557
use crate::constraint_graph::ConstraintGraph; use crate::types::{Constructable, ContextSensitiveVariant, PreliminaryTypeTable, TypeTable, Variant}; use crate::{ keys::{Constraint, TcKey}, types::Preliminary, }; use std::collections::HashMap; use std::fmt::Debug; use std::hash::Hash; /// Represents a re-usable variable in the type checking procedure. /// /// [TcKey]s for variables will be managed by the [TypeChecker]. pub trait TcVar: Debug + Eq + Hash + Clone {} /// The [TypeChecker] is the main interaction point for the type checking procedure. /// /// The [TypeChecker] is the main interaction point for the type checking procedure. /// It provides functionality to obtain [TcKey]s, manage variables, impose constraints, and generate a type table. /// /// # Related Data Structures /// * [TcKey] represent different entities during the type checking procedure such as variables or terms. /// * [TcVar] represent variables in the external structure, e.g. in the AST that is type checked. /// A variable has exactly one associated key, even if it occurs several times in the external data structure. /// The type checker manages keys for variables. /// * `Constraint`s represent dependencies between keys and types. They can only be created using [TcKey]s. /// * [Variant] is an external data type that constitutes a potentially unresolved type. /// * [TcErr] is a wrapper for [Variant::Err] that contains additional information on what went wrong. /// * [TypeTable] maps keys to [Constructable::Type] if [Variant] implements [Constructable]. /// * [PreliminaryTypeTable] maps keys to [Preliminary]. This is only useful if [Variant] does not implement [Constructable] /// /// # Process /// In the first step after creation, the [TypeChecker] generates keys and collects information. It may already resolve some constraints /// and reveal contradictions. This prompts it to return a negative result with a [TcErr]. /// When all information is collected, it resolves them and generates a type table that contains the least restrictive Variant type for /// each registered key. /// /// ## Note: /// The absence of errors does not entail that a constraint can be satisfied. Only the successful generation of a /// type table indicates that all constraints can be satisfied. /// /// # Example /// See [`crate documentation`](index.html). #[derive(Debug, Clone)] pub struct TypeChecker<V: ContextSensitiveVariant, Var: TcVar> { variables: HashMap<Var, TcKey>, graph: ConstraintGraph<V>, context: V::Context, } impl<V: Variant, Var: TcVar> Default for TypeChecker<V, Var> { fn default() -> Self { TypeChecker::new() } } /// A convenience struct representing non-existant variables during a type check precedure. Can and should not be accessed, modified, or created. #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] pub struct NoVars { unit: (), // Prevents external creation. } impl TcVar for NoVars {} /// A [TypeChecker] instance in case no variables are required. pub type VarlessTypeChecker<V> = TypeChecker<V, NoVars>; impl<V: Variant> TypeChecker<V, NoVars> { /// Instantiates a new, empty type checker that does not require variables. pub fn without_vars() -> VarlessTypeChecker<V> { TypeChecker::new() } } // %%%%%%%%%%% PUBLIC INTERFACE %%%%%%%%%%% impl<V: Variant, Var: TcVar> TypeChecker<V, Var> { /// Creates a new, empty type checker. pub fn new() -> Self { Self::with_context(()) } } impl<V: ContextSensitiveVariant, Var: TcVar> TypeChecker<V, Var> { /// Creates a new, empty type checker with the given context. pub fn with_context(context: V::Context) -> Self { TypeChecker { variables: HashMap::new(), graph: ConstraintGraph::new(), context } } /// Generates a new key representing a term. pub fn new_term_key(&mut self) -> TcKey { self.graph.create_vertex() } /// Manages keys for variables. It checks if `var` already has an associated key. /// If so, it returns the key. Otherwise, it generates a new one. pub fn get_var_key(&mut self, var: &Var) -> TcKey { // Avoid cloning `var` by forgoing the `entry` function if possible. if let Some(tck) = self.variables.get(var) { *tck } else { let key = self.new_term_key(); let _ = self.variables.insert(var.clone(), key); key } } /// Provides a key to the `nth` child of the type behind `parent`. /// This imposes the restriction that `parent` resolves to a type that has at least an arity of `nth`. /// If this imposition immediately leads to a contradiction, a [TcErr] is returned. /// Contradictions due to this constraint may only occur later when resolving further constraints. /// Calling this function several times on a parent with the same `nth` results in the same key. pub fn get_child_key(&mut self, parent: TcKey, nth: usize) -> Result<TcKey, TcErr<V>> { let TypeChecker { graph, variables: _, context } = self; let key = graph.nth_child(parent, nth, &context)?; // *self = TypeChecker { graph, variables, context }; Ok(key) } /// Imposes a constraint on keys. They can be obtained by using the associated functions of [TcKey]. /// Returns a [TcErr] if the constraint immediately reveals a contradiction. pub fn impose(&mut self, constr: Constraint<V>) -> Result<(), TcErr<V>> { match constr { Constraint::Conjunction(cs) => cs.into_iter().try_for_each(|c| self.impose(c))?, Constraint::Equal(a, b) => { let TypeChecker { graph, variables: _, context } = self; graph.equate(a, b, &context)?; } Constraint::MoreConc { target, bound } => self.graph.add_upper_bound(target, bound), Constraint::MoreConcExplicit(target, bound) => { let TypeChecker { graph, variables: _, context } = self; graph.explicit_bound(target, bound, &context)?; } } Ok(()) } /// Lifts a collection of keys as children into a certain recursive variant. pub fn lift_into(&mut self, variant: V, mut sub_types: Vec<TcKey>) -> TcKey { self.lift_partially(variant, sub_types.drain(..).map(Some).collect()) } /// Lifts a collection of keys as subset of children into a certain recursive variant. pub fn lift_partially(&mut self, variant: V, sub_types: Vec<Option<TcKey>>) -> TcKey { self.graph.lift(variant, sub_types) } /// Returns an iterator over all keys currently present in the type checking procedure. pub fn all_keys(&self) -> impl Iterator<Item = TcKey> + '_ { self.graph.all_keys() } /// Updates the current context. /// /// Applies the `update` function to the context of the current typechecker. /// The function may mutate the context. /// /// # Warning /// This will not change any call retroactively, i.e. it only applies to future /// meet and equate calls. Proceed with caution. pub fn update_context<F>(&mut self, update: F) where F: FnOnce(&mut V::Context), { update(&mut self.context); } /// Finalizes the type check procedure without constructing a full type table. Refer to [TypeChecker::type_check] if [Variant] implements [Constructable]. /// Calling this function indicates that all relevant information was passed on to the type checker. /// It will attempt to resolve all constraints and return a type table mapping each registered key to its minimally constrained [Variant]s. /// For recursive types, the respective [Preliminary] provides access to [crate::TcKey]s refering to their children. /// If any constrained caused a contradiction, it will return a [TcErr] containing information about it. pub fn type_check_preliminary(self) -> Result<PreliminaryTypeTable<V>, TcErr<V>> { let TypeChecker { graph, variables: _, context } = self; graph.solve_preliminary(context) } } impl<V, Var: TcVar> TypeChecker<V, Var> where V: Constructable, { /// Finalizes the type check procedure. /// Calling this function indicates that all relevant information was passed on to the type checker. /// It will attempt to resolve all constraints and return a type table mapping each registered key to its /// minimally constrained, constructed type, i.e. [Constructable::Type]. Refer to [TypeChecker::type_check_preliminary()] if [Variant] does not implement [Constructable]. /// If any constrained caused a contradiction, it will return a [TcErr] containing information about it. pub fn type_check(self) -> Result<TypeTable<V>, TcErr<V>> { let TypeChecker { graph, variables: _, context } = self; graph.solve(context) } } /// Represents an error during the type check procedure. #[derive(Debug, Clone)] pub enum TcErr<V: ContextSensitiveVariant> { /// Two keys were attempted to be equated and their underlying types turned out to be incompatible. /// Contains the two keys and the error that occurred when attempting to meet their [ContextSensitiveVariant] types. KeyEquation(TcKey, TcKey, V::Err), /// An explicit type bound imposed on a key turned out to be incompatible with the type inferred based on /// remaining information on the key. Contains the key and the error that occurred when meeting the explicit /// bound with the inferred type variant. Bound(TcKey, Option<TcKey>, V::Err), /// This error occurs when a constraint accesses the `n`th child of a type and its variant turns out to only /// have `k < n` sub-types. /// Contains the affected key, its inferred or explicitly assigned variant, and the index of the child that /// was attempted to be accessed. ChildAccessOutOfBound(TcKey, V, usize), /// This error occurs if the type checker inferred a specific arity but the variant reports a fixed arity that is lower than the inferred one. ArityMismatch { /// The key for which the mismatch was detected. key: TcKey, /// The variant with fixed arity. variant: V, /// The least required arity according to the type check procedure. inferred_arity: usize, /// The arity required according to the meet operation that created the variant. reported_arity: usize, }, /// An error reporting a failed type construction. Contains the affected key, the preliminary result for which the construction failed, and the /// error reported by the construction. Construction(TcKey, Preliminary<V>, V::Err), /// This error indicates that a variant requires children, for one of which the construction failed. /// Note that this can occur seemingly-spuriously, e.g., if a child needs to be present but there were no restrictions on said child. /// In this case, the construction attempts and might fail to construct a child out of a [ContextSensitiveVariant::top()]. /// The error contains the affected key, the index of the child, the preliminary result of which a child construction failed, and the error /// reported by the construction of the child. ChildConstruction(TcKey, usize, Preliminary<V>, V::Err), /// This error reports cyclic non-equality dependencies in the constraint graph. /// Example: Key 1 is more concrete than Key 2, which is more concrete than Key 3, which is more concrete than Key 1. CyclicGraph, }
50.467249
175
0.686856
f9e4710fabcf21771bcb643826b30983fc4f3744
4,311
pub use crate::models::client::{ApiClient, Params, Response}; use reqwest::{ header::{HeaderMap, HeaderName, HeaderValue, AUTHORIZATION, CONTENT_TYPE, USER_AGENT}, Client, }; const DEFAULT_API_USER_AGENT: &str = "provide-rust client library"; impl ApiClient { pub fn new(scheme: &str, host: &str, path: &str, token: &str) -> Self { let client = Client::new(); let base_url = format!("{}://{}/{}", scheme, host, path); Self { client, base_url, token: token.to_string(), } } pub fn get( &self, uri: &str, params: Params, additional_headers: Option<Vec<(String, String)>>, query_params: Option<Vec<(String, String)>>, ) -> impl std::future::Future<Output = Response> { let url = format!("{}/{}", self.base_url, uri); self.client .get(url) .headers(self.construct_headers(additional_headers.unwrap_or(vec![]), "GET")) .query(&query_params.unwrap_or(vec![])) .json(&params) .send() } pub fn patch( &self, uri: &str, params: Params, additional_headers: Option<Vec<(String, String)>>, ) -> impl std::future::Future<Output = Response> { let url = format!("{}/{}", self.base_url, uri); self.client .patch(url) .headers(self.construct_headers(additional_headers.unwrap_or(vec![]), "PATCH")) .json(&params) .send() } pub fn put( &self, uri: &str, params: Params, additional_headers: Option<Vec<(String, String)>>, ) -> impl std::future::Future<Output = Response> { let url = format!("{}/{}", self.base_url, uri); self.client .put(url) .headers(self.construct_headers(additional_headers.unwrap_or(vec![]), "PUT")) .json(&params) .send() } pub fn post( &self, uri: &str, params: Params, additional_headers: Option<Vec<(String, String)>>, ) -> impl std::future::Future<Output = Response> { let url = format!("{}/{}", self.base_url, uri); self.client .post(url) .headers(self.construct_headers(additional_headers.unwrap_or(vec![]), "POST")) .json(&params) .send() } pub fn delete( &self, uri: &str, params: Params, additional_headers: Option<Vec<(String, String)>>, ) -> impl std::future::Future<Output = Response> { let url = format!("{}/{}", self.base_url, uri); self.client .delete(url) .headers(self.construct_headers(additional_headers.unwrap_or(vec![]), "DELETE")) .json(&params) .send() } pub fn set_bearer_token(&mut self, token: &str) { // could simply have general prop setter method instead of seperate bearer and baseurl self.token = token.to_string(); } pub fn set_base_url(&mut self, base_url: &str) { // TODO: this should not be necessary self.base_url = base_url.to_string(); } fn construct_headers( &self, additional_headers: Vec<(String, String)>, method: &str, ) -> HeaderMap { let mut headers = HeaderMap::new(); if method == "POST" || method == "PUT" || method == "PATCH" { headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); } headers.insert( USER_AGENT, HeaderValue::from_str( &std::env::var("USER_AGENT").unwrap_or(String::from(DEFAULT_API_USER_AGENT)), ) .expect("user agent"), ); if self.token != "" { let auth = format!("bearer {}", self.token); headers.insert(AUTHORIZATION, HeaderValue::from_str(&auth).expect("token")); } for (key, value) in additional_headers { let header_name = HeaderName::from_bytes(key.as_bytes()).expect("header name"); let header_value = HeaderValue::from_str(&value).expect("header value"); headers.insert(header_name, header_value); } headers } } // TODO-- GET pagination capabilities
31.23913
94
0.547437
de5507be8fbae322dbd61f7b91745c668b676d82
78,010
//! Deserialize JSON data to a Rust data structure. use crate::error::{Error, ErrorCode, Result}; use crate::lib::str::FromStr; use crate::lib::*; use crate::number::Number; use crate::read::{self, Reference}; use serde::de::{self, Expected, Unexpected}; use serde::{forward_to_deserialize_any, serde_if_integer128}; #[cfg(feature = "arbitrary_precision")] use crate::number::NumberDeserializer; pub use crate::read::{Read, SliceRead, StrRead}; #[cfg(feature = "std")] pub use crate::read::IoRead; ////////////////////////////////////////////////////////////////////////////// /// A structure that deserializes JSON into Rust values. pub struct Deserializer<R> { read: R, scratch: Vec<u8>, remaining_depth: u8, #[cfg(feature = "unbounded_depth")] disable_recursion_limit: bool, } impl<'de, R> Deserializer<R> where R: read::Read<'de>, { /// Create a JSON deserializer from one of the possible serde_jsonrc input /// sources. /// /// Typically it is more convenient to use one of these methods instead: /// /// - Deserializer::from_str /// - Deserializer::from_bytes /// - Deserializer::from_reader pub fn new(read: R) -> Self { #[cfg(not(feature = "unbounded_depth"))] { Deserializer { read: read, scratch: Vec::new(), remaining_depth: 128, } } #[cfg(feature = "unbounded_depth")] { Deserializer { read: read, scratch: Vec::new(), remaining_depth: 128, disable_recursion_limit: false, } } } } #[cfg(feature = "std")] impl<R> Deserializer<read::IoRead<R>> where R: crate::io::Read, { /// Creates a JSON deserializer from an `io::Read`. /// /// Reader-based deserializers do not support deserializing borrowed types /// like `&str`, since the `std::io::Read` trait has no non-copying methods /// -- everything it does involves copying bytes out of the data source. pub fn from_reader(reader: R) -> Self { Deserializer::new(read::IoRead::new(reader)) } } impl<'a> Deserializer<read::SliceRead<'a>> { /// Creates a JSON deserializer from a `&[u8]`. pub fn from_slice(bytes: &'a [u8]) -> Self { Deserializer::new(read::SliceRead::new(bytes)) } } impl<'a> Deserializer<read::StrRead<'a>> { /// Creates a JSON deserializer from a `&str`. pub fn from_str(s: &'a str) -> Self { Deserializer::new(read::StrRead::new(s)) } } macro_rules! overflow { ($a:ident * 10 + $b:ident, $c:expr) => { $a >= $c / 10 && ($a > $c / 10 || $b > $c % 10) }; } pub(crate) enum ParserNumber { F64(f64), U64(u64), I64(i64), #[cfg(feature = "arbitrary_precision")] String(String), } impl ParserNumber { fn visit<'de, V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { match self { ParserNumber::F64(x) => visitor.visit_f64(x), ParserNumber::U64(x) => visitor.visit_u64(x), ParserNumber::I64(x) => visitor.visit_i64(x), #[cfg(feature = "arbitrary_precision")] ParserNumber::String(x) => visitor.visit_map(NumberDeserializer { number: x.into() }), } } fn invalid_type(self, exp: &dyn Expected) -> Error { match self { ParserNumber::F64(x) => de::Error::invalid_type(Unexpected::Float(x), exp), ParserNumber::U64(x) => de::Error::invalid_type(Unexpected::Unsigned(x), exp), ParserNumber::I64(x) => de::Error::invalid_type(Unexpected::Signed(x), exp), #[cfg(feature = "arbitrary_precision")] ParserNumber::String(_) => de::Error::invalid_type(Unexpected::Other("number"), exp), } } } impl<'de, R: Read<'de>> Deserializer<R> { /// The `Deserializer::end` method should be called after a value has been fully deserialized. /// This allows the `Deserializer` to validate that the input stream is at the end or that it /// only has trailing whitespace. pub fn end(&mut self) -> Result<()> { match tri!(self.parse_whitespace()) { Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)), None => Ok(()), } } /// Turn a JSON deserializer into an iterator over values of type T. pub fn into_iter<T>(self) -> StreamDeserializer<'de, R, T> where T: de::Deserialize<'de>, { // This cannot be an implementation of std::iter::IntoIterator because // we need the caller to choose what T is. let offset = self.read.byte_offset(); StreamDeserializer { de: self, offset: offset, output: PhantomData, lifetime: PhantomData, } } /// Parse arbitrarily deep JSON structures without any consideration for /// overflowing the stack. /// /// You will want to provide some other way to protect against stack /// overflows, such as by wrapping your Deserializer in the dynamically /// growing stack adapter provided by the serde_stacker crate. Additionally /// you will need to be careful around other recursive operations on the /// parsed result which may overflow the stack after deserialization has /// completed, including, but not limited to, Display and Debug and Drop /// impls. /// /// *This method is only available if serde_json is built with the /// `"unbounded_depth"` feature.* /// /// # Examples /// /// ``` /// use serde::Deserialize; /// use serde_jsonrc::Value; /// /// fn main() { /// let mut json = String::new(); /// for _ in 0..10000 { /// json = format!("[{}]", json); /// } /// /// let mut deserializer = serde_jsonrc::Deserializer::from_str(&json); /// deserializer.disable_recursion_limit(); /// let deserializer = serde_stacker::Deserializer::new(&mut deserializer); /// let value = Value::deserialize(deserializer).unwrap(); /// /// carefully_drop_nested_arrays(value); /// } /// /// fn carefully_drop_nested_arrays(value: Value) { /// let mut stack = vec![value]; /// while let Some(value) = stack.pop() { /// if let Value::Array(array) = value { /// stack.extend(array); /// } /// } /// } /// ``` #[cfg(feature = "unbounded_depth")] pub fn disable_recursion_limit(&mut self) { self.disable_recursion_limit = true; } fn peek(&mut self) -> Result<Option<u8>> { self.read.peek() } fn peek_or_null(&mut self) -> Result<u8> { Ok(tri!(self.peek()).unwrap_or(b'\x00')) } fn eat_char(&mut self) { self.read.discard(); } fn next_char(&mut self) -> Result<Option<u8>> { self.read.next() } fn next_char_or_null(&mut self) -> Result<u8> { Ok(tri!(self.next_char()).unwrap_or(b'\x00')) } /// Error caused by a byte from next_char(). #[cold] fn error(&self, reason: ErrorCode) -> Error { let position = self.read.position(); Error::syntax(reason, position.line, position.column) } /// Error caused by a byte from peek(). #[cold] fn peek_error(&self, reason: ErrorCode) -> Error { let position = self.read.peek_position(); Error::syntax(reason, position.line, position.column) } /// Returns the first non-whitespace byte without consuming it, or `None` if /// EOF is encountered. fn parse_whitespace(&mut self) -> Result<Option<u8>> { // Consume comments as if they were whitespace. loop { match tri!(self.peek()) { Some(b' ') | Some(b'\n') | Some(b'\t') | Some(b'\r') => { self.eat_char(); } Some(b'/') => { self.eat_char(); match tri!(self.peek()) { Some(b'/') => { // TODO: Read until newline. loop { match tri!(self.peek()) { Some(b'\n') => { self.eat_char(); break; } Some(_) => { self.eat_char(); } None => { return Ok(None); } } } } Some(b'*') => loop { match tri!(self.peek()) { Some(b'*') => { self.eat_char(); match tri!(self.peek()) { Some(b'/') => { self.eat_char(); break; } Some(_) => {}, None => { return Err(self.peek_error( ErrorCode::EofWhileParsingBlockComment, )); } } } Some(_) => { self.eat_char(); } None => { return Err( self.peek_error(ErrorCode::EofWhileParsingBlockComment) ); } } }, _ => { return Err(self.peek_error(ErrorCode::ExpectedCommentSlashOrStar)); } }; } other => { return Ok(other); } } } } #[cold] fn peek_invalid_type(&mut self, exp: &dyn Expected) -> Error { let err = match self.peek_or_null().unwrap_or(b'\x00') { b'n' => { self.eat_char(); if let Err(err) = self.parse_ident(b"ull") { return err; } de::Error::invalid_type(Unexpected::Unit, exp) } b't' => { self.eat_char(); if let Err(err) = self.parse_ident(b"rue") { return err; } de::Error::invalid_type(Unexpected::Bool(true), exp) } b'f' => { self.eat_char(); if let Err(err) = self.parse_ident(b"alse") { return err; } de::Error::invalid_type(Unexpected::Bool(false), exp) } b'-' => { self.eat_char(); match self.parse_any_number(false) { Ok(n) => n.invalid_type(exp), Err(err) => return err, } } b'0'..=b'9' => match self.parse_any_number(true) { Ok(n) => n.invalid_type(exp), Err(err) => return err, }, b'"' => { self.eat_char(); self.scratch.clear(); match self.read.parse_str(&mut self.scratch) { Ok(s) => de::Error::invalid_type(Unexpected::Str(&s), exp), Err(err) => return err, } } b'[' => de::Error::invalid_type(Unexpected::Seq, exp), b'{' => de::Error::invalid_type(Unexpected::Map, exp), _ => self.peek_error(ErrorCode::ExpectedSomeValue), }; self.fix_position(err) } fn deserialize_prim_number<V>(&mut self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { let peek = match tri!(self.parse_whitespace()) { Some(b) => b, None => { return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); } }; let value = match peek { b'-' => { self.eat_char(); tri!(self.parse_integer(false)).visit(visitor) } b'0'..=b'9' => tri!(self.parse_integer(true)).visit(visitor), _ => Err(self.peek_invalid_type(&visitor)), }; match value { Ok(value) => Ok(value), Err(err) => Err(self.fix_position(err)), } } serde_if_integer128! { fn scan_integer128(&mut self, buf: &mut String) -> Result<()> { match tri!(self.next_char_or_null()) { b'0' => { buf.push('0'); // There can be only one leading '0'. match tri!(self.peek_or_null()) { b'0'..=b'9' => { Err(self.peek_error(ErrorCode::InvalidNumber)) } _ => Ok(()), } } c @ b'1'..=b'9' => { buf.push(c as char); while let c @ b'0'..=b'9' = tri!(self.peek_or_null()) { self.eat_char(); buf.push(c as char); } Ok(()) } _ => { Err(self.error(ErrorCode::InvalidNumber)) } } } } #[cold] fn fix_position(&self, err: Error) -> Error { err.fix_position(move |code| self.error(code)) } fn parse_ident(&mut self, ident: &[u8]) -> Result<()> { for expected in ident { match tri!(self.next_char()) { None => { return Err(self.error(ErrorCode::EofWhileParsingValue)); } Some(next) => { if next != *expected { return Err(self.error(ErrorCode::ExpectedSomeIdent)); } } } } Ok(()) } fn parse_integer(&mut self, positive: bool) -> Result<ParserNumber> { let next = match tri!(self.next_char()) { Some(b) => b, None => { return Err(self.error(ErrorCode::EofWhileParsingValue)); } }; match next { b'0' => { // There can be only one leading '0'. match tri!(self.peek_or_null()) { b'0'..=b'9' => Err(self.peek_error(ErrorCode::InvalidNumber)), _ => self.parse_number(positive, 0), } } c @ b'1'..=b'9' => { let mut res = (c - b'0') as u64; loop { match tri!(self.peek_or_null()) { c @ b'0'..=b'9' => { self.eat_char(); let digit = (c - b'0') as u64; // We need to be careful with overflow. If we can, try to keep the // number as a `u64` until we grow too large. At that point, switch to // parsing the value as a `f64`. if overflow!(res * 10 + digit, u64::max_value()) { return Ok(ParserNumber::F64(tri!( self.parse_long_integer( positive, res, 1, // res * 10^1 ) ))); } res = res * 10 + digit; } _ => { return self.parse_number(positive, res); } } } } _ => Err(self.error(ErrorCode::InvalidNumber)), } } fn parse_long_integer( &mut self, positive: bool, significand: u64, mut exponent: i32, ) -> Result<f64> { loop { match tri!(self.peek_or_null()) { b'0'..=b'9' => { self.eat_char(); // This could overflow... if your integer is gigabytes long. // Ignore that possibility. exponent += 1; } b'.' => { return self.parse_decimal(positive, significand, exponent); } b'e' | b'E' => { return self.parse_exponent(positive, significand, exponent); } _ => { return self.f64_from_parts(positive, significand, exponent); } } } } fn parse_number(&mut self, positive: bool, significand: u64) -> Result<ParserNumber> { Ok(match tri!(self.peek_or_null()) { b'.' => ParserNumber::F64(tri!(self.parse_decimal(positive, significand, 0))), b'e' | b'E' => ParserNumber::F64(tri!(self.parse_exponent(positive, significand, 0))), _ => { if positive { ParserNumber::U64(significand) } else { let neg = (significand as i64).wrapping_neg(); // Convert into a float if we underflow. if neg > 0 { ParserNumber::F64(-(significand as f64)) } else { ParserNumber::I64(neg) } } } }) } fn parse_decimal( &mut self, positive: bool, mut significand: u64, mut exponent: i32, ) -> Result<f64> { self.eat_char(); let mut at_least_one_digit = false; while let c @ b'0'..=b'9' = tri!(self.peek_or_null()) { self.eat_char(); let digit = (c - b'0') as u64; at_least_one_digit = true; if overflow!(significand * 10 + digit, u64::max_value()) { // The next multiply/add would overflow, so just ignore all // further digits. while let b'0'..=b'9' = tri!(self.peek_or_null()) { self.eat_char(); } break; } significand = significand * 10 + digit; exponent -= 1; } if !at_least_one_digit { match tri!(self.peek()) { Some(_) => return Err(self.peek_error(ErrorCode::InvalidNumber)), None => return Err(self.peek_error(ErrorCode::EofWhileParsingValue)), } } match tri!(self.peek_or_null()) { b'e' | b'E' => self.parse_exponent(positive, significand, exponent), _ => self.f64_from_parts(positive, significand, exponent), } } fn parse_exponent( &mut self, positive: bool, significand: u64, starting_exp: i32, ) -> Result<f64> { self.eat_char(); let positive_exp = match tri!(self.peek_or_null()) { b'+' => { self.eat_char(); true } b'-' => { self.eat_char(); false } _ => true, }; let next = match tri!(self.next_char()) { Some(b) => b, None => { return Err(self.error(ErrorCode::EofWhileParsingValue)); } }; // Make sure a digit follows the exponent place. let mut exp = match next { c @ b'0'..=b'9' => (c - b'0') as i32, _ => { return Err(self.error(ErrorCode::InvalidNumber)); } }; while let c @ b'0'..=b'9' = tri!(self.peek_or_null()) { self.eat_char(); let digit = (c - b'0') as i32; if overflow!(exp * 10 + digit, i32::max_value()) { return self.parse_exponent_overflow(positive, significand, positive_exp); } exp = exp * 10 + digit; } let final_exp = if positive_exp { starting_exp.saturating_add(exp) } else { starting_exp.saturating_sub(exp) }; self.f64_from_parts(positive, significand, final_exp) } // This cold code should not be inlined into the middle of the hot // exponent-parsing loop above. #[cold] #[inline(never)] fn parse_exponent_overflow( &mut self, positive: bool, significand: u64, positive_exp: bool, ) -> Result<f64> { // Error instead of +/- infinity. if significand != 0 && positive_exp { return Err(self.error(ErrorCode::NumberOutOfRange)); } while let b'0'..=b'9' = tri!(self.peek_or_null()) { self.eat_char(); } Ok(if positive { 0.0 } else { -0.0 }) } fn parse_any_signed_number(&mut self) -> Result<ParserNumber> { let peek = match tri!(self.peek()) { Some(b) => b, None => { return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); } }; let value = match peek { b'-' => { self.eat_char(); self.parse_any_number(false) } b'0'..=b'9' => self.parse_any_number(true), _ => Err(self.peek_error(ErrorCode::InvalidNumber)), }; let value = match tri!(self.peek()) { Some(_) => Err(self.peek_error(ErrorCode::InvalidNumber)), None => value, }; match value { Ok(value) => Ok(value), // The de::Error impl creates errors with unknown line and column. // Fill in the position here by looking at the current index in the // input. There is no way to tell whether this should call `error` // or `peek_error` so pick the one that seems correct more often. // Worst case, the position is off by one character. Err(err) => Err(self.fix_position(err)), } } #[cfg(not(feature = "arbitrary_precision"))] fn parse_any_number(&mut self, positive: bool) -> Result<ParserNumber> { self.parse_integer(positive) } #[cfg(feature = "arbitrary_precision")] fn parse_any_number(&mut self, positive: bool) -> Result<ParserNumber> { let mut buf = String::with_capacity(16); if !positive { buf.push('-'); } self.scan_integer(&mut buf)?; Ok(ParserNumber::String(buf)) } #[cfg(feature = "arbitrary_precision")] fn scan_or_eof(&mut self, buf: &mut String) -> Result<u8> { match tri!(self.next_char()) { Some(b) => { buf.push(b as char); Ok(b) } None => Err(self.error(ErrorCode::EofWhileParsingValue)), } } #[cfg(feature = "arbitrary_precision")] fn scan_integer(&mut self, buf: &mut String) -> Result<()> { match tri!(self.scan_or_eof(buf)) { b'0' => { // There can be only one leading '0'. match tri!(self.peek_or_null()) { b'0'..=b'9' => Err(self.peek_error(ErrorCode::InvalidNumber)), _ => self.scan_number(buf), } } b'1'..=b'9' => loop { match tri!(self.peek_or_null()) { c @ b'0'..=b'9' => { self.eat_char(); buf.push(c as char); } _ => { return self.scan_number(buf); } } }, _ => Err(self.error(ErrorCode::InvalidNumber)), } } #[cfg(feature = "arbitrary_precision")] fn scan_number(&mut self, buf: &mut String) -> Result<()> { match tri!(self.peek_or_null()) { b'.' => self.scan_decimal(buf), b'e' | b'E' => self.scan_exponent(buf), _ => Ok(()), } } #[cfg(feature = "arbitrary_precision")] fn scan_decimal(&mut self, buf: &mut String) -> Result<()> { self.eat_char(); buf.push('.'); let mut at_least_one_digit = false; while let c @ b'0'..=b'9' = tri!(self.peek_or_null()) { self.eat_char(); buf.push(c as char); at_least_one_digit = true; } if !at_least_one_digit { match tri!(self.peek()) { Some(_) => return Err(self.peek_error(ErrorCode::InvalidNumber)), None => return Err(self.peek_error(ErrorCode::EofWhileParsingValue)), } } match tri!(self.peek_or_null()) { b'e' | b'E' => self.scan_exponent(buf), _ => Ok(()), } } #[cfg(feature = "arbitrary_precision")] fn scan_exponent(&mut self, buf: &mut String) -> Result<()> { self.eat_char(); buf.push('e'); match tri!(self.peek_or_null()) { b'+' => { self.eat_char(); } b'-' => { self.eat_char(); buf.push('-'); } _ => {} } // Make sure a digit follows the exponent place. match tri!(self.scan_or_eof(buf)) { b'0'..=b'9' => {} _ => { return Err(self.error(ErrorCode::InvalidNumber)); } } while let c @ b'0'..=b'9' = tri!(self.peek_or_null()) { self.eat_char(); buf.push(c as char); } Ok(()) } fn f64_from_parts( &mut self, positive: bool, significand: u64, mut exponent: i32, ) -> Result<f64> { let mut f = significand as f64; loop { match POW10.get(exponent.wrapping_abs() as usize) { Some(&pow) => { if exponent >= 0 { f *= pow; if f.is_infinite() { return Err(self.error(ErrorCode::NumberOutOfRange)); } } else { f /= pow; } break; } None => { if f == 0.0 { break; } if exponent >= 0 { return Err(self.error(ErrorCode::NumberOutOfRange)); } f /= 1e308; exponent += 308; } } } Ok(if positive { f } else { -f }) } fn parse_object_colon(&mut self) -> Result<()> { match tri!(self.parse_whitespace()) { Some(b':') => { self.eat_char(); Ok(()) } Some(_) => Err(self.peek_error(ErrorCode::ExpectedColon)), None => Err(self.peek_error(ErrorCode::EofWhileParsingObject)), } } fn end_seq(&mut self) -> Result<()> { match tri!(self.parse_whitespace()) { Some(b']') => { self.eat_char(); Ok(()) } Some(b',') => { self.eat_char(); match self.parse_whitespace() { Ok(Some(b']')) => Err(self.peek_error(ErrorCode::TrailingComma)), _ => Err(self.peek_error(ErrorCode::TrailingCharacters)), } } Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)), None => Err(self.peek_error(ErrorCode::EofWhileParsingList)), } } fn end_map(&mut self) -> Result<()> { match tri!(self.parse_whitespace()) { Some(b'}') => { self.eat_char(); Ok(()) } Some(b',') => Err(self.peek_error(ErrorCode::TrailingComma)), Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)), None => Err(self.peek_error(ErrorCode::EofWhileParsingObject)), } } fn ignore_value(&mut self) -> Result<()> { self.scratch.clear(); let mut enclosing = None; loop { let peek = match tri!(self.parse_whitespace()) { Some(b) => b, None => { return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); } }; let frame = match peek { b'n' => { self.eat_char(); tri!(self.parse_ident(b"ull")); None } b't' => { self.eat_char(); tri!(self.parse_ident(b"rue")); None } b'f' => { self.eat_char(); tri!(self.parse_ident(b"alse")); None } b'-' => { self.eat_char(); tri!(self.ignore_integer()); None } b'0'..=b'9' => { tri!(self.ignore_integer()); None } b'"' => { self.eat_char(); tri!(self.read.ignore_str()); None } frame @ b'[' | frame @ b'{' => { self.scratch.extend(enclosing.take()); self.eat_char(); Some(frame) } _ => return Err(self.peek_error(ErrorCode::ExpectedSomeValue)), }; let (mut accept_comma, mut frame) = match frame { Some(frame) => (false, frame), None => match enclosing.take() { Some(frame) => (true, frame), None => match self.scratch.pop() { Some(frame) => (true, frame), None => return Ok(()), }, }, }; loop { match tri!(self.parse_whitespace()) { Some(b',') if accept_comma => { self.eat_char(); break; } Some(b']') if frame == b'[' => {} Some(b'}') if frame == b'{' => {} Some(_) => { if accept_comma { return Err(self.peek_error(match frame { b'[' => ErrorCode::ExpectedListCommaOrEnd, b'{' => ErrorCode::ExpectedObjectCommaOrEnd, _ => unreachable!(), })); } else { break; } } None => { return Err(self.peek_error(match frame { b'[' => ErrorCode::EofWhileParsingList, b'{' => ErrorCode::EofWhileParsingObject, _ => unreachable!(), })); } } self.eat_char(); frame = match self.scratch.pop() { Some(frame) => frame, None => return Ok(()), }; accept_comma = true; } if frame == b'{' { match tri!(self.parse_whitespace()) { Some(b'"') => self.eat_char(), Some(_) => return Err(self.peek_error(ErrorCode::KeyMustBeAString)), None => return Err(self.peek_error(ErrorCode::EofWhileParsingObject)), } tri!(self.read.ignore_str()); match tri!(self.parse_whitespace()) { Some(b':') => self.eat_char(), Some(_) => return Err(self.peek_error(ErrorCode::ExpectedColon)), None => return Err(self.peek_error(ErrorCode::EofWhileParsingObject)), } } enclosing = Some(frame); } } fn ignore_integer(&mut self) -> Result<()> { match tri!(self.next_char_or_null()) { b'0' => { // There can be only one leading '0'. if let b'0'..=b'9' = tri!(self.peek_or_null()) { return Err(self.peek_error(ErrorCode::InvalidNumber)); } } b'1'..=b'9' => { while let b'0'..=b'9' = tri!(self.peek_or_null()) { self.eat_char(); } } _ => { return Err(self.error(ErrorCode::InvalidNumber)); } } match tri!(self.peek_or_null()) { b'.' => self.ignore_decimal(), b'e' | b'E' => self.ignore_exponent(), _ => Ok(()), } } fn ignore_decimal(&mut self) -> Result<()> { self.eat_char(); let mut at_least_one_digit = false; while let b'0'..=b'9' = tri!(self.peek_or_null()) { self.eat_char(); at_least_one_digit = true; } if !at_least_one_digit { return Err(self.peek_error(ErrorCode::InvalidNumber)); } match tri!(self.peek_or_null()) { b'e' | b'E' => self.ignore_exponent(), _ => Ok(()), } } fn ignore_exponent(&mut self) -> Result<()> { self.eat_char(); match tri!(self.peek_or_null()) { b'+' | b'-' => self.eat_char(), _ => {} } // Make sure a digit follows the exponent place. match tri!(self.next_char_or_null()) { b'0'..=b'9' => {} _ => { return Err(self.error(ErrorCode::InvalidNumber)); } } while let b'0'..=b'9' = tri!(self.peek_or_null()) { self.eat_char(); } Ok(()) } #[cfg(feature = "raw_value")] fn deserialize_raw_value<V>(&mut self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { self.parse_whitespace()?; self.read.begin_raw_buffering(); self.ignore_value()?; self.read.end_raw_buffering(visitor) } } impl FromStr for Number { type Err = Error; fn from_str(s: &str) -> result::Result<Self, Self::Err> { Deserializer::from_str(s) .parse_any_signed_number() .map(Into::into) } } static POW10: [f64; 309] = [ 1e000, 1e001, 1e002, 1e003, 1e004, 1e005, 1e006, 1e007, 1e008, 1e009, // 1e010, 1e011, 1e012, 1e013, 1e014, 1e015, 1e016, 1e017, 1e018, 1e019, // 1e020, 1e021, 1e022, 1e023, 1e024, 1e025, 1e026, 1e027, 1e028, 1e029, // 1e030, 1e031, 1e032, 1e033, 1e034, 1e035, 1e036, 1e037, 1e038, 1e039, // 1e040, 1e041, 1e042, 1e043, 1e044, 1e045, 1e046, 1e047, 1e048, 1e049, // 1e050, 1e051, 1e052, 1e053, 1e054, 1e055, 1e056, 1e057, 1e058, 1e059, // 1e060, 1e061, 1e062, 1e063, 1e064, 1e065, 1e066, 1e067, 1e068, 1e069, // 1e070, 1e071, 1e072, 1e073, 1e074, 1e075, 1e076, 1e077, 1e078, 1e079, // 1e080, 1e081, 1e082, 1e083, 1e084, 1e085, 1e086, 1e087, 1e088, 1e089, // 1e090, 1e091, 1e092, 1e093, 1e094, 1e095, 1e096, 1e097, 1e098, 1e099, // 1e100, 1e101, 1e102, 1e103, 1e104, 1e105, 1e106, 1e107, 1e108, 1e109, // 1e110, 1e111, 1e112, 1e113, 1e114, 1e115, 1e116, 1e117, 1e118, 1e119, // 1e120, 1e121, 1e122, 1e123, 1e124, 1e125, 1e126, 1e127, 1e128, 1e129, // 1e130, 1e131, 1e132, 1e133, 1e134, 1e135, 1e136, 1e137, 1e138, 1e139, // 1e140, 1e141, 1e142, 1e143, 1e144, 1e145, 1e146, 1e147, 1e148, 1e149, // 1e150, 1e151, 1e152, 1e153, 1e154, 1e155, 1e156, 1e157, 1e158, 1e159, // 1e160, 1e161, 1e162, 1e163, 1e164, 1e165, 1e166, 1e167, 1e168, 1e169, // 1e170, 1e171, 1e172, 1e173, 1e174, 1e175, 1e176, 1e177, 1e178, 1e179, // 1e180, 1e181, 1e182, 1e183, 1e184, 1e185, 1e186, 1e187, 1e188, 1e189, // 1e190, 1e191, 1e192, 1e193, 1e194, 1e195, 1e196, 1e197, 1e198, 1e199, // 1e200, 1e201, 1e202, 1e203, 1e204, 1e205, 1e206, 1e207, 1e208, 1e209, // 1e210, 1e211, 1e212, 1e213, 1e214, 1e215, 1e216, 1e217, 1e218, 1e219, // 1e220, 1e221, 1e222, 1e223, 1e224, 1e225, 1e226, 1e227, 1e228, 1e229, // 1e230, 1e231, 1e232, 1e233, 1e234, 1e235, 1e236, 1e237, 1e238, 1e239, // 1e240, 1e241, 1e242, 1e243, 1e244, 1e245, 1e246, 1e247, 1e248, 1e249, // 1e250, 1e251, 1e252, 1e253, 1e254, 1e255, 1e256, 1e257, 1e258, 1e259, // 1e260, 1e261, 1e262, 1e263, 1e264, 1e265, 1e266, 1e267, 1e268, 1e269, // 1e270, 1e271, 1e272, 1e273, 1e274, 1e275, 1e276, 1e277, 1e278, 1e279, // 1e280, 1e281, 1e282, 1e283, 1e284, 1e285, 1e286, 1e287, 1e288, 1e289, // 1e290, 1e291, 1e292, 1e293, 1e294, 1e295, 1e296, 1e297, 1e298, 1e299, // 1e300, 1e301, 1e302, 1e303, 1e304, 1e305, 1e306, 1e307, 1e308, ]; macro_rules! deserialize_prim_number { ($method:ident) => { fn $method<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { self.deserialize_prim_number(visitor) } } } #[cfg(not(feature = "unbounded_depth"))] macro_rules! if_checking_recursion_limit { ($($body:tt)*) => { $($body)* }; } #[cfg(feature = "unbounded_depth")] macro_rules! if_checking_recursion_limit { ($this:ident $($body:tt)*) => { if !$this.disable_recursion_limit { $this $($body)* } }; } macro_rules! check_recursion { ($this:ident $($body:tt)*) => { if_checking_recursion_limit! { $this.remaining_depth -= 1; if $this.remaining_depth == 0 { return Err($this.peek_error(ErrorCode::RecursionLimitExceeded)); } } $this $($body)* if_checking_recursion_limit! { $this.remaining_depth += 1; } }; } impl<'de, 'a, R: Read<'de>> de::Deserializer<'de> for &'a mut Deserializer<R> { type Error = Error; #[inline] fn deserialize_any<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { let peek = match tri!(self.parse_whitespace()) { Some(b) => b, None => { return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); } }; let value = match peek { b'n' => { self.eat_char(); tri!(self.parse_ident(b"ull")); visitor.visit_unit() } b't' => { self.eat_char(); tri!(self.parse_ident(b"rue")); visitor.visit_bool(true) } b'f' => { self.eat_char(); tri!(self.parse_ident(b"alse")); visitor.visit_bool(false) } b'-' => { self.eat_char(); tri!(self.parse_any_number(false)).visit(visitor) } b'0'..=b'9' => tri!(self.parse_any_number(true)).visit(visitor), b'"' => { self.eat_char(); self.scratch.clear(); match tri!(self.read.parse_str(&mut self.scratch)) { Reference::Borrowed(s) => visitor.visit_borrowed_str(s), Reference::Copied(s) => visitor.visit_str(s), } } b'[' => { check_recursion! { self.eat_char(); let ret = visitor.visit_seq(SeqAccess::new(self)); } match (ret, self.end_seq()) { (Ok(ret), Ok(())) => Ok(ret), (Err(err), _) | (_, Err(err)) => Err(err), } } b'{' => { check_recursion! { self.eat_char(); let ret = visitor.visit_map(MapAccess::new(self)); } match (ret, self.end_map()) { (Ok(ret), Ok(())) => Ok(ret), (Err(err), _) | (_, Err(err)) => Err(err), } } _ => Err(self.peek_error(ErrorCode::ExpectedSomeValue)), }; match value { Ok(value) => Ok(value), // The de::Error impl creates errors with unknown line and column. // Fill in the position here by looking at the current index in the // input. There is no way to tell whether this should call `error` // or `peek_error` so pick the one that seems correct more often. // Worst case, the position is off by one character. Err(err) => Err(self.fix_position(err)), } } fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { let peek = match tri!(self.parse_whitespace()) { Some(b) => b, None => { return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); } }; let value = match peek { b't' => { self.eat_char(); tri!(self.parse_ident(b"rue")); visitor.visit_bool(true) } b'f' => { self.eat_char(); tri!(self.parse_ident(b"alse")); visitor.visit_bool(false) } _ => Err(self.peek_invalid_type(&visitor)), }; match value { Ok(value) => Ok(value), Err(err) => Err(self.fix_position(err)), } } deserialize_prim_number!(deserialize_i8); deserialize_prim_number!(deserialize_i16); deserialize_prim_number!(deserialize_i32); deserialize_prim_number!(deserialize_i64); deserialize_prim_number!(deserialize_u8); deserialize_prim_number!(deserialize_u16); deserialize_prim_number!(deserialize_u32); deserialize_prim_number!(deserialize_u64); deserialize_prim_number!(deserialize_f32); deserialize_prim_number!(deserialize_f64); serde_if_integer128! { fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { let mut buf = String::new(); match tri!(self.parse_whitespace()) { Some(b'-') => { self.eat_char(); buf.push('-'); } Some(_) => {} None => { return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); } }; tri!(self.scan_integer128(&mut buf)); let value = match buf.parse() { Ok(int) => visitor.visit_i128(int), Err(_) => { return Err(self.error(ErrorCode::NumberOutOfRange)); } }; match value { Ok(value) => Ok(value), Err(err) => Err(self.fix_position(err)), } } fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { match tri!(self.parse_whitespace()) { Some(b'-') => { return Err(self.peek_error(ErrorCode::NumberOutOfRange)); } Some(_) => {} None => { return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); } } let mut buf = String::new(); tri!(self.scan_integer128(&mut buf)); let value = match buf.parse() { Ok(int) => visitor.visit_u128(int), Err(_) => { return Err(self.error(ErrorCode::NumberOutOfRange)); } }; match value { Ok(value) => Ok(value), Err(err) => Err(self.fix_position(err)), } } } fn deserialize_char<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { self.deserialize_str(visitor) } fn deserialize_str<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { let peek = match tri!(self.parse_whitespace()) { Some(b) => b, None => { return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); } }; let value = match peek { b'"' => { self.eat_char(); self.scratch.clear(); match tri!(self.read.parse_str(&mut self.scratch)) { Reference::Borrowed(s) => visitor.visit_borrowed_str(s), Reference::Copied(s) => visitor.visit_str(s), } } _ => Err(self.peek_invalid_type(&visitor)), }; match value { Ok(value) => Ok(value), Err(err) => Err(self.fix_position(err)), } } fn deserialize_string<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { self.deserialize_str(visitor) } /// Parses a JSON string as bytes. Note that this function does not check /// whether the bytes represent a valid UTF-8 string. /// /// The relevant part of the JSON specification is Section 8.2 of [RFC /// 7159]: /// /// > When all the strings represented in a JSON text are composed entirely /// > of Unicode characters (however escaped), then that JSON text is /// > interoperable in the sense that all software implementations that /// > parse it will agree on the contents of names and of string values in /// > objects and arrays. /// > /// > However, the ABNF in this specification allows member names and string /// > values to contain bit sequences that cannot encode Unicode characters; /// > for example, "\uDEAD" (a single unpaired UTF-16 surrogate). Instances /// > of this have been observed, for example, when a library truncates a /// > UTF-16 string without checking whether the truncation split a /// > surrogate pair. The behavior of software that receives JSON texts /// > containing such values is unpredictable; for example, implementations /// > might return different values for the length of a string value or even /// > suffer fatal runtime exceptions. /// /// [RFC 7159]: https://tools.ietf.org/html/rfc7159 /// /// The behavior of serde_jsonrc is specified to fail on non-UTF-8 strings /// when deserializing into Rust UTF-8 string types such as String, and /// succeed with non-UTF-8 bytes when deserializing using this method. /// /// Escape sequences are processed as usual, and for `\uXXXX` escapes it is /// still checked if the hex number represents a valid Unicode code point. /// /// # Examples /// /// You can use this to parse JSON strings containing invalid UTF-8 bytes. /// /// ``` /// use serde_bytes::ByteBuf; /// /// fn look_at_bytes() -> Result<(), serde_jsonrc::Error> { /// let json_data = b"\"some bytes: \xe5\x00\xe5\""; /// let bytes: ByteBuf = serde_jsonrc::from_slice(json_data)?; /// /// assert_eq!(b'\xe5', bytes[12]); /// assert_eq!(b'\0', bytes[13]); /// assert_eq!(b'\xe5', bytes[14]); /// /// Ok(()) /// } /// # /// # look_at_bytes().unwrap(); /// ``` /// /// Backslash escape sequences like `\n` are still interpreted and required /// to be valid, and `\u` escape sequences are required to represent valid /// Unicode code points. /// /// ``` /// use serde_bytes::ByteBuf; /// /// fn look_at_bytes() { /// let json_data = b"\"invalid unicode surrogate: \\uD801\""; /// let parsed: Result<ByteBuf, _> = serde_jsonrc::from_slice(json_data); /// /// assert!(parsed.is_err()); /// /// let expected_msg = "unexpected end of hex escape at line 1 column 35"; /// assert_eq!(expected_msg, parsed.unwrap_err().to_string()); /// } /// # /// # look_at_bytes(); /// ``` fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { let peek = match tri!(self.parse_whitespace()) { Some(b) => b, None => { return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); } }; let value = match peek { b'"' => { self.eat_char(); self.scratch.clear(); match tri!(self.read.parse_str_raw(&mut self.scratch)) { Reference::Borrowed(b) => visitor.visit_borrowed_bytes(b), Reference::Copied(b) => visitor.visit_bytes(b), } } b'[' => self.deserialize_seq(visitor), _ => Err(self.peek_invalid_type(&visitor)), }; match value { Ok(value) => Ok(value), Err(err) => Err(self.fix_position(err)), } } #[inline] fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { self.deserialize_bytes(visitor) } /// Parses a `null` as a None, and any other values as a `Some(...)`. #[inline] fn deserialize_option<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { match tri!(self.parse_whitespace()) { Some(b'n') => { self.eat_char(); tri!(self.parse_ident(b"ull")); visitor.visit_none() } _ => visitor.visit_some(self), } } fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { let peek = match tri!(self.parse_whitespace()) { Some(b) => b, None => { return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); } }; let value = match peek { b'n' => { self.eat_char(); tri!(self.parse_ident(b"ull")); visitor.visit_unit() } _ => Err(self.peek_invalid_type(&visitor)), }; match value { Ok(value) => Ok(value), Err(err) => Err(self.fix_position(err)), } } fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { self.deserialize_unit(visitor) } /// Parses a newtype struct as the underlying value. #[inline] fn deserialize_newtype_struct<V>(self, name: &str, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { #[cfg(feature = "raw_value")] { if name == crate::raw::TOKEN { return self.deserialize_raw_value(visitor); } } let _ = name; visitor.visit_newtype_struct(self) } fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { let peek = match tri!(self.parse_whitespace()) { Some(b) => b, None => { return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); } }; let value = match peek { b'[' => { check_recursion! { self.eat_char(); let ret = visitor.visit_seq(SeqAccess::new(self)); } match (ret, self.end_seq()) { (Ok(ret), Ok(())) => Ok(ret), (Err(err), _) | (_, Err(err)) => Err(err), } } _ => Err(self.peek_invalid_type(&visitor)), }; match value { Ok(value) => Ok(value), Err(err) => Err(self.fix_position(err)), } } fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { self.deserialize_seq(visitor) } fn deserialize_tuple_struct<V>( self, _name: &'static str, _len: usize, visitor: V, ) -> Result<V::Value> where V: de::Visitor<'de>, { self.deserialize_seq(visitor) } fn deserialize_map<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { let peek = match tri!(self.parse_whitespace()) { Some(b) => b, None => { return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); } }; let value = match peek { b'{' => { check_recursion! { self.eat_char(); let ret = visitor.visit_map(MapAccess::new(self)); } match (ret, self.end_map()) { (Ok(ret), Ok(())) => Ok(ret), (Err(err), _) | (_, Err(err)) => Err(err), } } _ => Err(self.peek_invalid_type(&visitor)), }; match value { Ok(value) => Ok(value), Err(err) => Err(self.fix_position(err)), } } fn deserialize_struct<V>( self, _name: &'static str, _fields: &'static [&'static str], visitor: V, ) -> Result<V::Value> where V: de::Visitor<'de>, { let peek = match tri!(self.parse_whitespace()) { Some(b) => b, None => { return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); } }; let value = match peek { b'[' => { check_recursion! { self.eat_char(); let ret = visitor.visit_seq(SeqAccess::new(self)); } match (ret, self.end_seq()) { (Ok(ret), Ok(())) => Ok(ret), (Err(err), _) | (_, Err(err)) => Err(err), } } b'{' => { check_recursion! { self.eat_char(); let ret = visitor.visit_map(MapAccess::new(self)); } match (ret, self.end_map()) { (Ok(ret), Ok(())) => Ok(ret), (Err(err), _) | (_, Err(err)) => Err(err), } } _ => Err(self.peek_invalid_type(&visitor)), }; match value { Ok(value) => Ok(value), Err(err) => Err(self.fix_position(err)), } } /// Parses an enum as an object like `{"$KEY":$VALUE}`, where $VALUE is either a straight /// value, a `[..]`, or a `{..}`. #[inline] fn deserialize_enum<V>( self, _name: &str, _variants: &'static [&'static str], visitor: V, ) -> Result<V::Value> where V: de::Visitor<'de>, { match tri!(self.parse_whitespace()) { Some(b'{') => { check_recursion! { self.eat_char(); let value = tri!(visitor.visit_enum(VariantAccess::new(self))); } match tri!(self.parse_whitespace()) { Some(b'}') => { self.eat_char(); Ok(value) } Some(_) => Err(self.error(ErrorCode::ExpectedSomeValue)), None => Err(self.error(ErrorCode::EofWhileParsingObject)), } } Some(b'"') => visitor.visit_enum(UnitVariantAccess::new(self)), Some(_) => Err(self.peek_error(ErrorCode::ExpectedSomeValue)), None => Err(self.peek_error(ErrorCode::EofWhileParsingValue)), } } fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { self.deserialize_str(visitor) } fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { tri!(self.ignore_value()); visitor.visit_unit() } } struct SeqAccess<'a, R: 'a> { de: &'a mut Deserializer<R>, } impl<'a, R: 'a> SeqAccess<'a, R> { fn new(de: &'a mut Deserializer<R>) -> Self { SeqAccess { de } } } impl<'de, 'a, R: Read<'de> + 'a> de::SeqAccess<'de> for SeqAccess<'a, R> { type Error = Error; fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>> where T: de::DeserializeSeed<'de>, { match tri!(self.de.parse_whitespace()) { Some(b) => { // List most common branch first. if b != b']' { let result = Ok(Some(tri!(seed.deserialize(&mut *self.de)))); if !result.is_ok() { return result; } match tri!(self.de.parse_whitespace()) { Some(b',') => self.de.eat_char(), Some(b']') => { // Ignore. } Some(_) => { return Err(self.de.peek_error(ErrorCode::ExpectedListCommaOrEnd)); } None => { return Err(self.de.peek_error(ErrorCode::EofWhileParsingList)); } } result } else { Ok(None) } } None => Err(self.de.peek_error(ErrorCode::EofWhileParsingList)), } } } struct MapAccess<'a, R: 'a> { de: &'a mut Deserializer<R>, } impl<'a, R: 'a> MapAccess<'a, R> { fn new(de: &'a mut Deserializer<R>) -> Self { MapAccess { de } } } impl<'de, 'a, R: Read<'de> + 'a> de::MapAccess<'de> for MapAccess<'a, R> { type Error = Error; fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>> where K: de::DeserializeSeed<'de>, { match tri!(self.de.parse_whitespace()) { Some(b'"') => seed.deserialize(MapKey { de: &mut *self.de }).map(Some), Some(b'}') => { return Ok(None); } Some(_) => Err(self.de.peek_error(ErrorCode::KeyMustBeAString)), None => Err(self.de.peek_error(ErrorCode::EofWhileParsingObject)), } } fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value> where V: de::DeserializeSeed<'de>, { tri!(self.de.parse_object_colon()); let result = seed.deserialize(&mut *self.de); if result.is_ok() { match tri!(self.de.parse_whitespace()) { Some(b',') => self.de.eat_char(), Some(b'}') => { // Ignore. } Some(_) => { return Err(self.de.peek_error(ErrorCode::ExpectedObjectCommaOrEnd)); } None => { return Err(self.de.peek_error(ErrorCode::EofWhileParsingObject)); } }; }; result } } struct VariantAccess<'a, R: 'a> { de: &'a mut Deserializer<R>, } impl<'a, R: 'a> VariantAccess<'a, R> { fn new(de: &'a mut Deserializer<R>) -> Self { VariantAccess { de: de } } } impl<'de, 'a, R: Read<'de> + 'a> de::EnumAccess<'de> for VariantAccess<'a, R> { type Error = Error; type Variant = Self; fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)> where V: de::DeserializeSeed<'de>, { let val = tri!(seed.deserialize(&mut *self.de)); tri!(self.de.parse_object_colon()); Ok((val, self)) } } impl<'de, 'a, R: Read<'de> + 'a> de::VariantAccess<'de> for VariantAccess<'a, R> { type Error = Error; fn unit_variant(self) -> Result<()> { de::Deserialize::deserialize(self.de) } fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value> where T: de::DeserializeSeed<'de>, { seed.deserialize(self.de) } fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { de::Deserializer::deserialize_seq(self.de, visitor) } fn struct_variant<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { de::Deserializer::deserialize_struct(self.de, "", fields, visitor) } } struct UnitVariantAccess<'a, R: 'a> { de: &'a mut Deserializer<R>, } impl<'a, R: 'a> UnitVariantAccess<'a, R> { fn new(de: &'a mut Deserializer<R>) -> Self { UnitVariantAccess { de: de } } } impl<'de, 'a, R: Read<'de> + 'a> de::EnumAccess<'de> for UnitVariantAccess<'a, R> { type Error = Error; type Variant = Self; fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)> where V: de::DeserializeSeed<'de>, { let variant = tri!(seed.deserialize(&mut *self.de)); Ok((variant, self)) } } impl<'de, 'a, R: Read<'de> + 'a> de::VariantAccess<'de> for UnitVariantAccess<'a, R> { type Error = Error; fn unit_variant(self) -> Result<()> { Ok(()) } fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value> where T: de::DeserializeSeed<'de>, { Err(de::Error::invalid_type( Unexpected::UnitVariant, &"newtype variant", )) } fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { Err(de::Error::invalid_type( Unexpected::UnitVariant, &"tuple variant", )) } fn struct_variant<V>(self, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { Err(de::Error::invalid_type( Unexpected::UnitVariant, &"struct variant", )) } } /// Only deserialize from this after peeking a '"' byte! Otherwise it may /// deserialize invalid JSON successfully. struct MapKey<'a, R: 'a> { de: &'a mut Deserializer<R>, } macro_rules! deserialize_integer_key { ($method:ident => $visit:ident) => { fn $method<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { self.de.eat_char(); self.de.scratch.clear(); let string = tri!(self.de.read.parse_str(&mut self.de.scratch)); match (string.parse(), string) { (Ok(integer), _) => visitor.$visit(integer), (Err(_), Reference::Borrowed(s)) => visitor.visit_borrowed_str(s), (Err(_), Reference::Copied(s)) => visitor.visit_str(s), } } } } impl<'de, 'a, R> de::Deserializer<'de> for MapKey<'a, R> where R: Read<'de>, { type Error = Error; #[inline] fn deserialize_any<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { self.de.eat_char(); self.de.scratch.clear(); match tri!(self.de.read.parse_str(&mut self.de.scratch)) { Reference::Borrowed(s) => visitor.visit_borrowed_str(s), Reference::Copied(s) => visitor.visit_str(s), } } deserialize_integer_key!(deserialize_i8 => visit_i8); deserialize_integer_key!(deserialize_i16 => visit_i16); deserialize_integer_key!(deserialize_i32 => visit_i32); deserialize_integer_key!(deserialize_i64 => visit_i64); deserialize_integer_key!(deserialize_u8 => visit_u8); deserialize_integer_key!(deserialize_u16 => visit_u16); deserialize_integer_key!(deserialize_u32 => visit_u32); deserialize_integer_key!(deserialize_u64 => visit_u64); serde_if_integer128! { deserialize_integer_key!(deserialize_i128 => visit_i128); deserialize_integer_key!(deserialize_u128 => visit_u128); } #[inline] fn deserialize_option<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { // Map keys cannot be null. visitor.visit_some(self) } #[inline] fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { visitor.visit_newtype_struct(self) } #[inline] fn deserialize_enum<V>( self, name: &'static str, variants: &'static [&'static str], visitor: V, ) -> Result<V::Value> where V: de::Visitor<'de>, { self.de.deserialize_enum(name, variants, visitor) } #[inline] fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { self.de.deserialize_bytes(visitor) } #[inline] fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { self.de.deserialize_bytes(visitor) } forward_to_deserialize_any! { bool f32 f64 char str string unit unit_struct seq tuple tuple_struct map struct identifier ignored_any } } ////////////////////////////////////////////////////////////////////////////// /// Iterator that deserializes a stream into multiple JSON values. /// /// A stream deserializer can be created from any JSON deserializer using the /// `Deserializer::into_iter` method. /// /// The data can consist of any JSON value. Values need to be a self-delineating value e.g. /// arrays, objects, or strings, or be followed by whitespace or a self-delineating value. /// /// ``` /// use serde_jsonrc::{Deserializer, Value}; /// /// fn main() { /// let data = "{\"k\": 3}1\"cool\"\"stuff\" 3{} [0, 1, 2]"; /// /// let stream = Deserializer::from_str(data).into_iter::<Value>(); /// /// for value in stream { /// println!("{}", value.unwrap()); /// } /// } /// ``` pub struct StreamDeserializer<'de, R, T> { de: Deserializer<R>, offset: usize, output: PhantomData<T>, lifetime: PhantomData<&'de ()>, } impl<'de, R, T> StreamDeserializer<'de, R, T> where R: read::Read<'de>, T: de::Deserialize<'de>, { /// Create a JSON stream deserializer from one of the possible serde_jsonrc /// input sources. /// /// Typically it is more convenient to use one of these methods instead: /// /// - Deserializer::from_str(...).into_iter() /// - Deserializer::from_bytes(...).into_iter() /// - Deserializer::from_reader(...).into_iter() pub fn new(read: R) -> Self { let offset = read.byte_offset(); StreamDeserializer { de: Deserializer::new(read), offset: offset, output: PhantomData, lifetime: PhantomData, } } /// Returns the number of bytes so far deserialized into a successful `T`. /// /// If a stream deserializer returns an EOF error, new data can be joined to /// `old_data[stream.byte_offset()..]` to try again. /// /// ``` /// let data = b"[0] [1] ["; /// /// let de = serde_jsonrc::Deserializer::from_slice(data); /// let mut stream = de.into_iter::<Vec<i32>>(); /// assert_eq!(0, stream.byte_offset()); /// /// println!("{:?}", stream.next()); // [0] /// assert_eq!(3, stream.byte_offset()); /// /// println!("{:?}", stream.next()); // [1] /// assert_eq!(7, stream.byte_offset()); /// /// println!("{:?}", stream.next()); // error /// assert_eq!(8, stream.byte_offset()); /// /// // If err.is_eof(), can join the remaining data to new data and continue. /// let remaining = &data[stream.byte_offset()..]; /// ``` /// /// *Note:* In the future this method may be changed to return the number of /// bytes so far deserialized into a successful T *or* syntactically valid /// JSON skipped over due to a type error. See [serde-rs/json#70] for an /// example illustrating this. /// /// [serde-rs/json#70]: https://github.com/serde-rs/json/issues/70 pub fn byte_offset(&self) -> usize { self.offset } fn peek_end_of_value(&mut self) -> Result<()> { match tri!(self.de.peek()) { Some(b' ') | Some(b'\n') | Some(b'\t') | Some(b'\r') | Some(b'"') | Some(b'[') | Some(b']') | Some(b'{') | Some(b'}') | Some(b',') | Some(b':') | None => Ok(()), Some(_) => { let position = self.de.read.peek_position(); Err(Error::syntax( ErrorCode::TrailingCharacters, position.line, position.column, )) } } } } impl<'de, R, T> Iterator for StreamDeserializer<'de, R, T> where R: Read<'de>, T: de::Deserialize<'de>, { type Item = Result<T>; fn next(&mut self) -> Option<Result<T>> { // skip whitespaces, if any // this helps with trailing whitespaces, since whitespaces between // values are handled for us. match self.de.parse_whitespace() { Ok(None) => { self.offset = self.de.read.byte_offset(); None } Ok(Some(b)) => { // If the value does not have a clear way to show the end of the value // (like numbers, null, true etc.) we have to look for whitespace or // the beginning of a self-delineated value. let self_delineated_value = match b { b'[' | b'"' | b'{' => true, _ => false, }; self.offset = self.de.read.byte_offset(); let result = de::Deserialize::deserialize(&mut self.de); Some(match result { Ok(value) => { self.offset = self.de.read.byte_offset(); if self_delineated_value { Ok(value) } else { self.peek_end_of_value().map(|_| value) } } Err(e) => Err(e), }) } Err(e) => Some(Err(e)), } } } ////////////////////////////////////////////////////////////////////////////// fn from_trait<'de, R, T>(read: R) -> Result<T> where R: Read<'de>, T: de::Deserialize<'de>, { let mut de = Deserializer::new(read); let value = tri!(de::Deserialize::deserialize(&mut de)); // Make sure the whole stream has been consumed. tri!(de.end()); Ok(value) } /// Deserialize an instance of type `T` from an IO stream of JSON. /// /// The content of the IO stream is deserialized directly from the stream /// without being buffered in memory by serde_jsonrc. /// /// When reading from a source against which short reads are not efficient, such /// as a [`File`], you will want to apply your own buffering because serde_jsonrc /// will not buffer the input. See [`std::io::BufReader`]. /// /// It is expected that the input stream ends after the deserialized object. /// If the stream does not end, such as in the case of a persistent socket connection, /// this function will not return. It is possible instead to deserialize from a prefix of an input /// stream without looking for EOF by managing your own [`Deserializer`]. /// /// Note that counter to intuition, this function is usually slower than /// reading a file completely into memory and then applying [`from_str`] /// or [`from_slice`] on it. See [issue #160]. /// /// [`File`]: https://doc.rust-lang.org/std/fs/struct.File.html /// [`std::io::BufReader`]: https://doc.rust-lang.org/std/io/struct.BufReader.html /// [`from_str`]: ./fn.from_str.html /// [`from_slice`]: ./fn.from_slice.html /// [issue #160]: https://github.com/serde-rs/json/issues/160 /// /// # Example /// /// Reading the contents of a file. /// /// ``` /// use serde::Deserialize; /// /// use std::error::Error; /// use std::fs::File; /// use std::io::BufReader; /// use std::path::Path; /// /// #[derive(Deserialize, Debug)] /// struct User { /// fingerprint: String, /// location: String, /// } /// /// fn read_user_from_file<P: AsRef<Path>>(path: P) -> Result<User, Box<Error>> { /// // Open the file in read-only mode with buffer. /// let file = File::open(path)?; /// let reader = BufReader::new(file); /// /// // Read the JSON contents of the file as an instance of `User`. /// let u = serde_jsonrc::from_reader(reader)?; /// /// // Return the `User`. /// Ok(u) /// } /// /// fn main() { /// # } /// # fn fake_main() { /// let u = read_user_from_file("test.json").unwrap(); /// println!("{:#?}", u); /// } /// ``` /// /// Reading from a persistent socket connection. /// /// ``` /// use serde::Deserialize; /// /// use std::error::Error; /// use std::net::{TcpListener, TcpStream}; /// /// #[derive(Deserialize, Debug)] /// struct User { /// fingerprint: String, /// location: String, /// } /// /// fn read_user_from_stream(tcp_stream: TcpStream) -> Result<User, Box<dyn Error>> { /// let mut de = serde_jsonrc::Deserializer::from_reader(tcp_stream); /// let u = User::deserialize(&mut de)?; /// /// Ok(u) /// } /// /// fn main() { /// # } /// # fn fake_main() { /// let listener = TcpListener::bind("127.0.0.1:4000").unwrap(); /// /// for stream in listener.incoming() { /// println!("{:#?}", read_user_from_stream(stream.unwrap())); /// } /// } /// ``` /// /// # Errors /// /// This conversion can fail if the structure of the input does not match the /// structure expected by `T`, for example if `T` is a struct type but the input /// contains something other than a JSON map. It can also fail if the structure /// is correct but `T`'s implementation of `Deserialize` decides that something /// is wrong with the data, for example required struct fields are missing from /// the JSON map or some number is too big to fit in the expected primitive /// type. #[cfg(feature = "std")] pub fn from_reader<R, T>(rdr: R) -> Result<T> where R: crate::io::Read, T: de::DeserializeOwned, { from_trait(read::IoRead::new(rdr)) } /// Deserialize an instance of type `T` from bytes of JSON text. /// /// # Example /// /// ``` /// use serde::Deserialize; /// /// #[derive(Deserialize, Debug)] /// struct User { /// fingerprint: String, /// location: String, /// } /// /// fn main() { /// // The type of `j` is `&[u8]` /// let j = b" /// { /// \"fingerprint\": \"0xF9BA143B95FF6D82\", /// \"location\": \"Menlo Park, CA\" /// }"; /// /// let u: User = serde_jsonrc::from_slice(j).unwrap(); /// println!("{:#?}", u); /// } /// ``` /// /// # Errors /// /// This conversion can fail if the structure of the input does not match the /// structure expected by `T`, for example if `T` is a struct type but the input /// contains something other than a JSON map. It can also fail if the structure /// is correct but `T`'s implementation of `Deserialize` decides that something /// is wrong with the data, for example required struct fields are missing from /// the JSON map or some number is too big to fit in the expected primitive /// type. pub fn from_slice<'a, T>(v: &'a [u8]) -> Result<T> where T: de::Deserialize<'a>, { from_trait(read::SliceRead::new(v)) } /// Deserialize an instance of type `T` from a string of JSON text. /// /// # Example /// /// ``` /// use serde::Deserialize; /// /// #[derive(Deserialize, Debug)] /// struct User { /// fingerprint: String, /// location: String, /// } /// /// fn main() { /// // The type of `j` is `&str` /// let j = " /// { /// \"fingerprint\": \"0xF9BA143B95FF6D82\", /// \"location\": \"Menlo Park, CA\" /// }"; /// /// let u: User = serde_jsonrc::from_str(j).unwrap(); /// println!("{:#?}", u); /// } /// ``` /// /// # Errors /// /// This conversion can fail if the structure of the input does not match the /// structure expected by `T`, for example if `T` is a struct type but the input /// contains something other than a JSON map. It can also fail if the structure /// is correct but `T`'s implementation of `Deserialize` decides that something /// is wrong with the data, for example required struct fields are missing from /// the JSON map or some number is too big to fit in the expected primitive /// type. pub fn from_str<'a, T>(s: &'a str) -> Result<T> where T: de::Deserialize<'a>, { from_trait(read::StrRead::new(s)) }
32.195625
98
0.482515
62b7f6cb72e3baf51199d72942eb65d069a4fa89
10,835
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Shim which is passed to Cargo as "rustc" when running the bootstrap. //! //! This shim will take care of some various tasks that our build process //! requires that Cargo can't quite do through normal configuration: //! //! 1. When compiling build scripts and build dependencies, we need a guaranteed //! full standard library available. The only compiler which actually has //! this is the snapshot, so we detect this situation and always compile with //! the snapshot compiler. //! 2. We pass a bunch of `--cfg` and other flags based on what we're compiling //! (and this slightly differs based on a whether we're using a snapshot or //! not), so we do that all here. //! //! This may one day be replaced by RUSTFLAGS, but the dynamic nature of //! switching compilers for the bootstrap and for build scripts will probably //! never get replaced. #![deny(warnings)] extern crate bootstrap; use std::env; use std::ffi::OsString; use std::io; use std::io::prelude::*; use std::str::FromStr; use std::path::PathBuf; use std::process::{Command, ExitStatus}; fn main() { let args = env::args_os().skip(1).collect::<Vec<_>>(); // Detect whether or not we're a build script depending on whether --target // is passed (a bit janky...) let target = args.windows(2) .find(|w| &*w[0] == "--target") .and_then(|w| w[1].to_str()); let version = args.iter().find(|w| &**w == "-vV"); let verbose = match env::var("RUSTC_VERBOSE") { Ok(s) => usize::from_str(&s).expect("RUSTC_VERBOSE should be an integer"), Err(_) => 0, }; // Build scripts always use the snapshot compiler which is guaranteed to be // able to produce an executable, whereas intermediate compilers may not // have the standard library built yet and may not be able to produce an // executable. Otherwise we just use the standard compiler we're // bootstrapping with. // // Also note that cargo will detect the version of the compiler to trigger // a rebuild when the compiler changes. If this happens, we want to make // sure to use the actual compiler instead of the snapshot compiler becase // that's the one that's actually changing. let (rustc, libdir) = if target.is_none() && version.is_none() { ("RUSTC_SNAPSHOT", "RUSTC_SNAPSHOT_LIBDIR") } else { ("RUSTC_REAL", "RUSTC_LIBDIR") }; let stage = env::var("RUSTC_STAGE").expect("RUSTC_STAGE was not set"); let sysroot = env::var_os("RUSTC_SYSROOT").expect("RUSTC_SYSROOT was not set"); let mut on_fail = env::var_os("RUSTC_ON_FAIL").map(|of| Command::new(of)); let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{:?} was not set", rustc)); let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{:?} was not set", libdir)); let mut dylib_path = bootstrap::util::dylib_path(); dylib_path.insert(0, PathBuf::from(libdir)); let mut cmd = Command::new(rustc); cmd.args(&args) .arg("--cfg") .arg(format!("stage{}", stage)) .env(bootstrap::util::dylib_path_var(), env::join_paths(&dylib_path).unwrap()); if let Some(target) = target { // The stage0 compiler has a special sysroot distinct from what we // actually downloaded, so we just always pass the `--sysroot` option. cmd.arg("--sysroot").arg(sysroot); // When we build Rust dylibs they're all intended for intermediate // usage, so make sure we pass the -Cprefer-dynamic flag instead of // linking all deps statically into the dylib. if env::var_os("RUSTC_NO_PREFER_DYNAMIC").is_none() { cmd.arg("-Cprefer-dynamic"); } // Pass the `rustbuild` feature flag to crates which rustbuild is // building. See the comment in bootstrap/lib.rs where this env var is // set for more details. if env::var_os("RUSTBUILD_UNSTABLE").is_some() { cmd.arg("--cfg").arg("rustbuild"); } // Help the libc crate compile by assisting it in finding the MUSL // native libraries. if let Some(s) = env::var_os("MUSL_ROOT") { let mut root = OsString::from("native="); root.push(&s); root.push("/lib"); cmd.arg("-L").arg(&root); } // Pass down extra flags, commonly used to configure `-Clinker` when // cross compiling. if let Ok(s) = env::var("RUSTC_FLAGS") { cmd.args(&s.split(" ").filter(|s| !s.is_empty()).collect::<Vec<_>>()); } // Pass down incremental directory, if any. if let Ok(dir) = env::var("RUSTC_INCREMENTAL") { cmd.arg(format!("-Zincremental={}", dir)); if verbose > 0 { cmd.arg("-Zincremental-info"); } } // If we're compiling specifically the `panic_abort` crate then we pass // the `-C panic=abort` option. Note that we do not do this for any // other crate intentionally as this is the only crate for now that we // ship with panic=abort. // // This... is a bit of a hack how we detect this. Ideally this // information should be encoded in the crate I guess? Would likely // require an RFC amendment to RFC 1513, however. let is_panic_abort = args.windows(2) .any(|a| &*a[0] == "--crate-name" && &*a[1] == "panic_abort"); if is_panic_abort { cmd.arg("-C").arg("panic=abort"); } // Set various options from config.toml to configure how we're building // code. if env::var("RUSTC_DEBUGINFO") == Ok("true".to_string()) { cmd.arg("-g"); } else if env::var("RUSTC_DEBUGINFO_LINES") == Ok("true".to_string()) { cmd.arg("-Cdebuginfo=1"); } let debug_assertions = match env::var("RUSTC_DEBUG_ASSERTIONS") { Ok(s) => if s == "true" { "y" } else { "n" }, Err(..) => "n", }; cmd.arg("-C").arg(format!("debug-assertions={}", debug_assertions)); if let Ok(s) = env::var("RUSTC_CODEGEN_UNITS") { cmd.arg("-C").arg(format!("codegen-units={}", s)); } // Emit save-analysis info. if env::var("RUSTC_SAVE_ANALYSIS") == Ok("api".to_string()) { cmd.arg("-Zsave-analysis-api"); } // Dealing with rpath here is a little special, so let's go into some // detail. First off, `-rpath` is a linker option on Unix platforms // which adds to the runtime dynamic loader path when looking for // dynamic libraries. We use this by default on Unix platforms to ensure // that our nightlies behave the same on Windows, that is they work out // of the box. This can be disabled, of course, but basically that's why // we're gated on RUSTC_RPATH here. // // Ok, so the astute might be wondering "why isn't `-C rpath` used // here?" and that is indeed a good question to task. This codegen // option is the compiler's current interface to generating an rpath. // Unfortunately it doesn't quite suffice for us. The flag currently // takes no value as an argument, so the compiler calculates what it // should pass to the linker as `-rpath`. This unfortunately is based on // the **compile time** directory structure which when building with // Cargo will be very different than the runtime directory structure. // // All that's a really long winded way of saying that if we use // `-Crpath` then the executables generated have the wrong rpath of // something like `$ORIGIN/deps` when in fact the way we distribute // rustc requires the rpath to be `$ORIGIN/../lib`. // // So, all in all, to set up the correct rpath we pass the linker // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it // fun to pass a flag to a tool to pass a flag to pass a flag to a tool // to change a flag in a binary? if env::var("RUSTC_RPATH") == Ok("true".to_string()) { let rpath = if target.contains("apple") { // Note that we need to take one extra step on macOS to also pass // `-Wl,-instal_name,@rpath/...` to get things to work right. To // do that we pass a weird flag to the compiler to get it to do // so. Note that this is definitely a hack, and we should likely // flesh out rpath support more fully in the future. if stage != "0" { cmd.arg("-Z").arg("osx-rpath-install-name"); } Some("-Wl,-rpath,@loader_path/../lib") } else if !target.contains("windows") { Some("-Wl,-rpath,$ORIGIN/../lib") } else { None }; if let Some(rpath) = rpath { cmd.arg("-C").arg(format!("link-args={}", rpath)); } if let Ok(s) = env::var("RUSTFLAGS") { for flag in s.split_whitespace() { cmd.arg(flag); } } } if target.contains("pc-windows-msvc") { cmd.arg("-Z").arg("unstable-options"); cmd.arg("-C").arg("target-feature=+crt-static"); } } if verbose > 1 { writeln!(&mut io::stderr(), "rustc command: {:?}", cmd).unwrap(); } // Actually run the compiler! std::process::exit(if let Some(ref mut on_fail) = on_fail { match cmd.status() { Ok(s) if s.success() => 0, _ => { println!("\nDid not run successfully:\n{:?}\n-------------", cmd); exec_cmd(on_fail).expect("could not run the backup command"); 1 } } } else { std::process::exit(match exec_cmd(&mut cmd) { Ok(s) => s.code().unwrap_or(0xfe), Err(e) => panic!("\n\nfailed to run {:?}: {}\n\n", cmd, e), }) }) } #[cfg(unix)] fn exec_cmd(cmd: &mut Command) -> ::std::io::Result<ExitStatus> { use std::os::unix::process::CommandExt; Err(cmd.exec()) } #[cfg(not(unix))] fn exec_cmd(cmd: &mut Command) -> ::std::io::Result<ExitStatus> { cmd.status() }
42.490196
91
0.589109
1ca2788851245259fcaa75fed8a02d2337fb72b5
7,857
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::{iter::Peekable, mem, sync::Arc, vec::IntoIter}; use kvproto::coprocessor::KeyRange; use tipb::schema::ColumnInfo; use super::{Executor, ExecutorMetrics, Row}; use crate::coprocessor::codec::table; use crate::coprocessor::dag::exec_summary::{ExecSummary, ExecSummaryCollector}; use crate::coprocessor::{Error, Result}; use crate::storage::{Key, Store}; // an InnerExecutor is used in ScanExecutor, // hold the different logics between table scan and index scan pub trait InnerExecutor { fn decode_row( &self, key: Vec<u8>, value: Vec<u8>, columns: Arc<Vec<ColumnInfo>>, ) -> Result<Option<Row>>; // checks if the key range represents a point. fn is_point(&self, range: &KeyRange) -> bool; // indicate which scan it will perform, Table or Index, this will pass to Scanner. fn scan_on(&self) -> super::super::scanner::ScanOn; // indicate whether the scan is a key only scan. fn key_only(&self) -> bool; } // Executor for table scan and index scan pub struct ScanExecutor<C: ExecSummaryCollector, S: Store, T: InnerExecutor> { summary_collector: C, store: S, desc: bool, key_ranges: Peekable<IntoIter<KeyRange>>, current_range: Option<KeyRange>, scan_range: KeyRange, scanner: Option<super::super::scanner::Scanner<S>>, columns: Arc<Vec<ColumnInfo>>, inner: T, counts: Option<Vec<i64>>, metrics: ExecutorMetrics, first_collect: bool, } impl<C: ExecSummaryCollector, S: Store, T: InnerExecutor> ScanExecutor<C, S, T> { pub fn new( summary_collector: C, inner: T, desc: bool, columns: Vec<ColumnInfo>, mut key_ranges: Vec<KeyRange>, store: S, collect: bool, ) -> Result<Self> { box_try!(table::check_table_ranges(&key_ranges)); if desc { key_ranges.reverse(); } let counts = if collect { Some(Vec::default()) } else { None }; Ok(Self { summary_collector, inner, store, desc, columns: Arc::new(columns), key_ranges: key_ranges.into_iter().peekable(), current_range: None, scan_range: KeyRange::default(), scanner: None, counts, metrics: Default::default(), first_collect: true, }) } fn get_row_from_range_scanner(&mut self) -> Result<Option<Row>> { if let Some(scanner) = self.scanner.as_mut() { self.metrics.scan_counter.inc_range(); let (key, value) = match scanner.next_row()? { Some((key, value)) => (key, value), None => return Ok(None), }; return self.inner.decode_row(key, value, self.columns.clone()); } Ok(None) } fn get_row_from_point(&mut self, mut range: KeyRange) -> Result<Option<Row>> { self.metrics.scan_counter.inc_point(); let key = range.take_start(); let value = self .store .get(&Key::from_raw(&key), &mut self.metrics.cf_stats)?; if let Some(value) = value { return self.inner.decode_row(key, value, self.columns.clone()); } Ok(None) } #[inline] fn inc_last_count(&mut self) { if let Some(counts) = self.counts.as_mut() { counts.last_mut().map_or((), |val| *val += 1); } } fn new_scanner(&self, range: KeyRange) -> Result<super::super::scanner::Scanner<S>> { super::super::Scanner::new( &self.store, self.inner.scan_on(), self.desc, self.inner.key_only(), range, ) .map_err(Error::from) } fn next_impl(&mut self) -> Result<Option<Row>> { loop { if let Some(row) = self.get_row_from_range_scanner()? { self.inc_last_count(); return Ok(Some(row)); } if let Some(range) = self.key_ranges.next() { if let Some(counts) = self.counts.as_mut() { counts.push(0) }; self.current_range = Some(range.clone()); if self.inner.is_point(&range) { if let Some(row) = self.get_row_from_point(range)? { self.inc_last_count(); return Ok(Some(row)); } continue; } self.scanner = match self.scanner.take() { Some(mut scanner) => { box_try!(scanner.reset_range(range, &self.store)); Some(scanner) } None => Some(self.new_scanner(range)?), }; continue; } return Ok(None); } } } impl<C: ExecSummaryCollector, S: Store, T: InnerExecutor> Executor for ScanExecutor<C, S, T> { fn next(&mut self) -> Result<Option<Row>> { let timer = self.summary_collector.on_start_iterate(); let ret = self.next_impl(); if let Ok(Some(_)) = ret { self.summary_collector.on_finish_iterate(timer, 1); } else { self.summary_collector.on_finish_iterate(timer, 0); } ret } fn collect_output_counts(&mut self, counts: &mut Vec<i64>) { if let Some(cur_counts) = self.counts.as_mut() { counts.append(cur_counts); cur_counts.push(0); } } fn collect_metrics_into(&mut self, metrics: &mut ExecutorMetrics) { metrics.merge(&mut self.metrics); if let Some(scanner) = self.scanner.as_mut() { scanner.collect_statistics_into(&mut metrics.cf_stats); } if self.first_collect { if self.inner.scan_on() == super::super::ScanOn::Table { metrics.executor_count.table_scan += 1; } else { metrics.executor_count.index_scan += 1; } self.first_collect = false; } } fn collect_execution_summaries(&mut self, target: &mut [ExecSummary]) { self.summary_collector.collect_into(target); } fn get_len_of_columns(&self) -> usize { self.columns.len() } fn start_scan(&mut self) { if let Some(range) = self.current_range.as_ref() { if !self.inner.is_point(range) { let scanner = self.scanner.as_ref().unwrap(); return scanner.start_scan(&mut self.scan_range); } } if let Some(range) = self.key_ranges.peek() { if !self.desc { self.scan_range.set_start(range.get_start().to_owned()); } else { self.scan_range.set_end(range.get_end().to_owned()); } } } fn stop_scan(&mut self) -> Option<KeyRange> { let mut ret_range = mem::replace(&mut self.scan_range, KeyRange::default()); match self.current_range.as_ref() { Some(range) => { if !self.inner.is_point(range) { let scanner = self.scanner.as_mut().unwrap(); if scanner.stop_scan(&mut ret_range) { return Some(ret_range); } } if !self.desc { ret_range.set_end(range.get_end().to_owned()); } else { ret_range.set_start(range.get_start().to_owned()); } } // `stop_scan` will be called only if we get some data from // `current_range` so that it's unreachable. None => unreachable!(), } Some(ret_range) } }
33.012605
94
0.540283
0ed48c1b6e4606c7119a7f36a2eb4580d4f36a08
1,080
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Watchdog Control and Status Register"] pub cs: crate::Reg<cs::CS_SPEC>, #[doc = "0x04 - Watchdog Counter Register"] pub cnt: crate::Reg<cnt::CNT_SPEC>, #[doc = "0x08 - Watchdog Timeout Value Register"] pub toval: crate::Reg<toval::TOVAL_SPEC>, #[doc = "0x0c - Watchdog Window Register"] pub win: crate::Reg<win::WIN_SPEC>, } #[doc = "CS register accessor: an alias for `Reg<CS_SPEC>`"] pub type CS = crate::Reg<cs::CS_SPEC>; #[doc = "Watchdog Control and Status Register"] pub mod cs; #[doc = "CNT register accessor: an alias for `Reg<CNT_SPEC>`"] pub type CNT = crate::Reg<cnt::CNT_SPEC>; #[doc = "Watchdog Counter Register"] pub mod cnt; #[doc = "TOVAL register accessor: an alias for `Reg<TOVAL_SPEC>`"] pub type TOVAL = crate::Reg<toval::TOVAL_SPEC>; #[doc = "Watchdog Timeout Value Register"] pub mod toval; #[doc = "WIN register accessor: an alias for `Reg<WIN_SPEC>`"] pub type WIN = crate::Reg<win::WIN_SPEC>; #[doc = "Watchdog Window Register"] pub mod win;
37.241379
66
0.673148
e9ba8616b997ebb0b74d8a34b47e3d2f145b7fa6
2,868
//! Test the serial interface with the DMA engine //! //! This example requires you to short (connect) the TX and RX pins. #![deny(unsafe_code)] // #![deny(warnings)] #![no_main] #![no_std] #[macro_use(singleton)] extern crate cortex_m; #[macro_use(entry, exception)] extern crate cortex_m_rt as rt; #[macro_use(block)] extern crate nb; extern crate panic_semihosting; extern crate stm32l4xx_hal as hal; // #[macro_use(block)] // extern crate nb; use crate::hal::dma::{CircReadDma, Half}; use crate::hal::prelude::*; use crate::hal::serial::{Config, Serial}; use crate::rt::ExceptionFrame; use cortex_m::asm; #[entry] fn main() -> ! { let p = hal::stm32::Peripherals::take().unwrap(); let mut flash = p.FLASH.constrain(); let mut rcc = p.RCC.constrain(); let mut pwr = p.PWR.constrain(&mut rcc.apb1r1); let mut gpioa = p.GPIOA.split(&mut rcc.ahb2); let channels = p.DMA1.split(&mut rcc.ahb1); // let mut gpiob = p.GPIOB.split(&mut rcc.ahb2); // clock configuration using the default settings (all clocks run at 8 MHz) let clocks = rcc.cfgr.freeze(&mut flash.acr, &mut pwr); // TRY this alternate clock configuration (clocks run at nearly the maximum frequency) // let clocks = rcc.cfgr.sysclk(64.mhz()).pclk1(32.mhz()).freeze(&mut flash.acr); // The Serial API is highly generic // TRY the commented out, different pin configurations let tx = gpioa.pa9.into_af7(&mut gpioa.moder, &mut gpioa.afrh); // let tx = gpiob.pb6.into_af7(&mut gpiob.moder, &mut gpiob.afrl); let rx = gpioa.pa10.into_af7(&mut gpioa.moder, &mut gpioa.afrh); // let rx = gpiob.pb7.into_af7(&mut gpiob.moder, &mut gpiob.afrl); // TRY using a different USART peripheral here let serial = Serial::usart1( p.USART1, (tx, rx), Config::default().baudrate(9_600.bps()), clocks, &mut rcc.apb2, ); let (mut tx, rx) = serial.split(); let sent = b'X'; // The `block!` macro makes an operation block until it finishes // NOTE the error type is `!` block!(tx.write(sent)).ok(); let buf = singleton!(: [[u8; 8]; 2] = [[0; 8]; 2]).unwrap(); let mut circ_buffer = rx.with_dma(channels.5).circ_read(buf); for _ in 0..2 { while circ_buffer.readable_half().unwrap() != Half::First {} let _first_half = circ_buffer.peek(|_buf, half| half).unwrap(); // asm::bkpt(); while circ_buffer.readable_half().unwrap() != Half::Second {} // asm::bkpt(); let _second_half = circ_buffer.peek(|_buf, half| half).unwrap(); } // let received = block!(rx.read()).unwrap(); // assert_eq!(received, sent); // if all goes well you should reach this breakpoint asm::bkpt(); loop { continue; } } #[exception] fn HardFault(ef: &ExceptionFrame) -> ! { panic!("{:#?}", ef); }
27.84466
90
0.627964
5d5202e6b6fc7209683851c0f371bc27f364ef4a
1,865
// Copyright 2018, Collabora, Ltd. // SPDX-License-Identifier: BSL-1.0 // Author: Ryan A. Pavlik <ryan.pavlik@collabora.com> // Rough port of the vrpn_print_devices client from the // mainline C++ VRPN repo extern crate futures; extern crate tokio; extern crate vrpn; use std::sync::Arc; use tokio::prelude::*; use vrpn::{ async_io::{connect_tcp, ping, ConnectionIp, ConnectionIpStream, Drain, StreamExtras}, handler::{HandlerCode, TypedHandler}, prelude::*, tracker::PoseReport, Message, Result, StaticSenderName, }; #[derive(Debug)] struct TrackerHandler {} impl TypedHandler for TrackerHandler { type Item = PoseReport; fn handle_typed(&mut self, msg: &Message<PoseReport>) -> Result<HandlerCode> { println!("{:?}\n {:?}", msg.header, msg.body); Ok(HandlerCode::ContinueProcessing) } } type Selected = Drain<stream::Select<ConnectionIpStream, ping::Client<ConnectionIp>>>; fn main() { let addr = "127.0.0.1:3883".parse().unwrap(); let connection_future = connect_tcp(addr) .and_then(|stream| { let connection = ConnectionIp::new_client(None, None, stream)?; let sender = connection .register_sender(StaticSenderName(b"Tracker0")) .expect("should be able to register sender"); let _ = connection.add_typed_handler(Box::new(TrackerHandler {}), Some(sender))?; connection.pack_all_descriptions()?; let ping_client = ping::Client::new(sender, Arc::clone(&connection))?; let selected: Selected = ConnectionIpStream::new(Arc::clone(&connection)) .select(ping_client) .drain(); Ok(selected) }) .flatten() .map_err(|e| { eprintln!("Error: {}", e); () }); tokio::run(connection_future); }
31.610169
93
0.624665
3aaa903bdcc1edb0f78e44aaca489fb10d713578
906
use crate::api::{AddressParam, AddressResult}; use crate::error_handling::Result; use crate::message_handler::encode_message; use coin_filecoin::address::FilecoinAddress; use prost::Message; pub fn get_address(param: &AddressParam) -> Result<Vec<u8>> { let address = FilecoinAddress::get_address(param.path.as_ref(), param.network.as_ref())?; let address_message = AddressResult { path: param.path.to_owned(), chain_type: param.chain_type.to_string(), address, }; encode_message(address_message) } pub fn display_filecoin_address(param: &AddressParam) -> Result<Vec<u8>> { let address = FilecoinAddress::display_address(param.path.as_ref(), param.network.as_ref())?; let address_message = AddressResult { path: param.path.to_owned(), chain_type: param.chain_type.to_string(), address, }; encode_message(address_message) }
32.357143
97
0.707506
23fb4a96ccccefc4cc7ecdc87a44f15bd92d7bb2
12,212
//! Contains the types for read concerns and write concerns. #[cfg(test)] mod test; use std::time::Duration; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_with::skip_serializing_none; use typed_builder::TypedBuilder; use crate::{ bson::{doc, serde_helpers, Timestamp}, bson_util, error::{ErrorKind, Result}, }; /// Specifies the consistency and isolation properties of read operations from replica sets and /// replica set shards. /// /// See the documentation [here](https://docs.mongodb.com/manual/reference/read-concern/) for more /// information about read concerns. #[skip_serializing_none] #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct ReadConcern { /// The level of the read concern. pub level: ReadConcernLevel, } /// An internal-only read concern type that allows the omission of a "level" as well as /// specification of "atClusterTime" and "afterClusterTime". #[skip_serializing_none] #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(rename = "readConcern")] pub(crate) struct ReadConcernInternal { /// The level of the read concern. pub(crate) level: Option<ReadConcernLevel>, /// The snapshot read timestamp. pub(crate) at_cluster_time: Option<Timestamp>, /// The time of most recent operation using this session. /// Used for providing causal consistency. pub(crate) after_cluster_time: Option<Timestamp>, } impl ReadConcern { /// Creates a read concern with level "majority". /// See the specific documentation for this read concern level [here](https://docs.mongodb.com/manual/reference/read-concern-majority/). pub fn majority() -> Self { ReadConcernLevel::Majority.into() } /// Creates a read concern with level "local". /// See the specific documentation for this read concern level [here](https://docs.mongodb.com/manual/reference/read-concern-local/). pub fn local() -> Self { ReadConcernLevel::Local.into() } /// Creates a read concern with level "linearizable". /// See the specific documentation for this read concern level [here](https://docs.mongodb.com/manual/reference/read-concern-linearizable/). pub fn linearizable() -> Self { ReadConcernLevel::Linearizable.into() } /// Creates a read concern with level "available". /// See the specific documentation for this read concern level [here](https://docs.mongodb.com/manual/reference/read-concern-available/). pub fn available() -> Self { ReadConcernLevel::Available.into() } /// Creates a read concern with level "snapshot". /// See the specific documentation for this read concern level [here](https://docs.mongodb.com/manual/reference/read-concern-snapshot/). pub fn snapshot() -> Self { ReadConcernLevel::Snapshot.into() } /// Creates a read concern with a custom read concern level. This is present to provide forwards /// compatibility with any future read concerns which may be added to new versions of /// MongoDB. pub fn custom(level: String) -> Self { ReadConcernLevel::from_str(level.as_str()).into() } #[cfg(test)] pub(crate) fn serialize_for_client_options<S>( read_concern: &Option<ReadConcern>, serializer: S, ) -> std::result::Result<S::Ok, S::Error> where S: Serializer, { #[derive(Serialize)] struct ReadConcernHelper<'a> { readconcernlevel: &'a str, } let state = read_concern.as_ref().map(|concern| ReadConcernHelper { readconcernlevel: concern.level.as_str(), }); state.serialize(serializer) } } impl From<ReadConcern> for ReadConcernInternal { fn from(rc: ReadConcern) -> Self { ReadConcernInternal { level: Some(rc.level), at_cluster_time: None, after_cluster_time: None, } } } impl From<ReadConcernLevel> for ReadConcern { fn from(level: ReadConcernLevel) -> Self { Self { level } } } /// Specifies the level consistency and isolation properties of a given `ReadCocnern`. /// /// See the documentation [here](https://docs.mongodb.com/manual/reference/read-concern/) for more /// information about read concerns. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub enum ReadConcernLevel { /// See the specific documentation for this read concern level [here](https://docs.mongodb.com/manual/reference/read-concern-local/). Local, /// See the specific documentation for this read concern level [here](https://docs.mongodb.com/manual/reference/read-concern-majority/). Majority, /// See the specific documentation for this read concern level [here](https://docs.mongodb.com/manual/reference/read-concern-linearizable/). Linearizable, /// See the specific documentation for this read concern level [here](https://docs.mongodb.com/manual/reference/read-concern-available/). Available, /// See the specific documentation for this read concern level [here](https://docs.mongodb.com/manual/reference/read-concern-snapshot/). Snapshot, /// Specify a custom read concern level. This is present to provide forwards compatibility with /// any future read concerns which may be added to new versions of MongoDB. Custom(String), } impl ReadConcernLevel { pub(crate) fn from_str(s: &str) -> Self { match s { "local" => ReadConcernLevel::Local, "majority" => ReadConcernLevel::Majority, "linearizable" => ReadConcernLevel::Linearizable, "available" => ReadConcernLevel::Available, "snapshot" => ReadConcernLevel::Snapshot, s => ReadConcernLevel::Custom(s.to_string()), } } /// Gets the string representation of the `ReadConcernLevel`. pub(crate) fn as_str(&self) -> &str { match self { ReadConcernLevel::Local => "local", ReadConcernLevel::Majority => "majority", ReadConcernLevel::Linearizable => "linearizable", ReadConcernLevel::Available => "available", ReadConcernLevel::Snapshot => "snapshot", ReadConcernLevel::Custom(ref s) => s, } } } impl<'de> Deserialize<'de> for ReadConcernLevel { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> { let s = String::deserialize(deserializer)?; Ok(ReadConcernLevel::from_str(&s)) } } impl Serialize for ReadConcernLevel { fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: Serializer, { self.as_str().serialize(serializer) } } /// Specifies the level of acknowledgement requested from the server for write operations. /// /// See the documentation [here](https://docs.mongodb.com/manual/reference/write-concern/) for more /// information about write concerns. #[skip_serializing_none] #[derive(Clone, Debug, Default, PartialEq, TypedBuilder, Serialize, Deserialize)] #[builder(field_defaults(default, setter(into)))] #[non_exhaustive] pub struct WriteConcern { /// Requests acknowledgement that the operation has propagated to a specific number or variety /// of servers. pub w: Option<Acknowledgment>, /// Specifies a time limit for the write concern. If an operation has not propagated to the /// requested level within the time limit, an error will return. /// /// Note that an error being returned due to a write concern error does not imply that the /// write would not have finished propagating if allowed more time to finish, and the /// server will not roll back the writes that occurred before the timeout was reached. #[serde(rename = "wtimeout")] #[serde(serialize_with = "bson_util::serialize_duration_option_as_int_millis")] #[serde(deserialize_with = "bson_util::deserialize_duration_option_from_u64_millis")] #[serde(default)] pub w_timeout: Option<Duration>, /// Requests acknowledgement that the operation has propagated to the on-disk journal. #[serde(rename = "j")] pub journal: Option<bool>, } /// The type of the `w` field in a [`WriteConcern`](struct.WriteConcern.html). #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub enum Acknowledgment { /// Requires acknowledgement that the write has reached the specified number of nodes. /// /// Note: specifying 0 here indicates that the write concern is unacknowledged, which is /// currently unsupported and will result in an error during operation execution. Nodes(u32), /// Requires acknowledgement that the write has reached the majority of nodes. Majority, /// Requires acknowledgement according to the given custom write concern. See [here](https://docs.mongodb.com/manual/tutorial/configure-replica-set-tag-sets/#tag-sets-and-custom-write-concern-behavior) /// for more information. Custom(String), } impl Serialize for Acknowledgment { fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: Serializer, { match self { Acknowledgment::Majority => serializer.serialize_str("majority"), Acknowledgment::Nodes(n) => serde_helpers::serialize_u32_as_i32(n, serializer), Acknowledgment::Custom(name) => serializer.serialize_str(name), } } } impl<'de> Deserialize<'de> for Acknowledgment { fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] #[serde(untagged)] enum IntOrString { Int(u32), String(String), } match IntOrString::deserialize(deserializer)? { IntOrString::String(s) => Ok(s.into()), IntOrString::Int(i) => Ok(i.into()), } } } impl From<u32> for Acknowledgment { fn from(i: u32) -> Self { Acknowledgment::Nodes(i) } } impl From<String> for Acknowledgment { fn from(s: String) -> Self { if s == "majority" { Acknowledgment::Majority } else { Acknowledgment::Custom(s) } } } impl WriteConcern { #[allow(dead_code)] pub(crate) fn is_acknowledged(&self) -> bool { self.w != Some(Acknowledgment::Nodes(0)) || self.journal == Some(true) } pub(crate) fn is_empty(&self) -> bool { self.w == None && self.w_timeout == None && self.journal == None } /// Validates that the write concern. A write concern is invalid if both the `w` field is 0 /// and the `j` field is `true`. pub(crate) fn validate(&self) -> Result<()> { if self.w == Some(Acknowledgment::Nodes(0)) && self.journal == Some(true) { return Err(ErrorKind::InvalidArgument { message: "write concern cannot have w=0 and j=true".to_string(), } .into()); } if let Some(w_timeout) = self.w_timeout { if w_timeout < Duration::from_millis(0) { return Err(ErrorKind::InvalidArgument { message: "write concern `w_timeout` field cannot be negative".to_string(), } .into()); } } Ok(()) } #[cfg(test)] pub(crate) fn serialize_for_client_options<S>( write_concern: &Option<WriteConcern>, serializer: S, ) -> std::result::Result<S::Ok, S::Error> where S: Serializer, { #[derive(Serialize)] struct WriteConcernHelper<'a> { w: Option<&'a Acknowledgment>, #[serde(serialize_with = "bson_util::serialize_duration_option_as_int_millis")] wtimeoutms: Option<Duration>, journal: Option<bool>, } let state = write_concern.as_ref().map(|concern| WriteConcernHelper { w: concern.w.as_ref(), wtimeoutms: concern.w_timeout, journal: concern.journal, }); state.serialize(serializer) } }
35.294798
205
0.65321
181089aef6f3d195be8442d86b51afd9eb9044dd
8,586
use std::time::Duration; use hex::encode as hex_encode; use reqwest::header::{HeaderMap, HeaderName, HeaderValue, CONTENT_TYPE, USER_AGENT}; use reqwest::Response; use reqwest::StatusCode; use ring::hmac; use serde::de; use serde::de::DeserializeOwned; use serde_json::from_str; use crate::errors::error_messages; use crate::errors::*; use crate::rest_model::PairQuery; use crate::util::{build_request_p, build_signed_request_p}; #[derive(Clone)] pub struct Client { api_key: String, secret_key: String, inner: reqwest::Client, host: String, } impl Client { /// Returns a client based on the specified host and credentials /// Credentials do not need to be specified when using public endpoints /// Host is mandatory pub fn new(api_key: Option<String>, secret_key: Option<String>, host: String) -> Self { let builder: reqwest::ClientBuilder = reqwest::ClientBuilder::new(); let builder = builder.timeout(Duration::from_secs(2)); Client { api_key: api_key.unwrap_or_else(|| "".into()), secret_key: secret_key.unwrap_or_else(|| "".into()), inner: builder.build().unwrap(), host, } } pub async fn get_signed(&self, endpoint: &str, request: &str) -> Result<String> { let url = self.sign_request(endpoint, request); let response = self .inner .clone() .get(url.as_str()) .headers(self.build_headers(true)?) .send() .await?; self.handler(response).await } pub async fn get_signed_d<T: de::DeserializeOwned>(&self, endpoint: &str, request: &str) -> Result<T> { let r = self.get_signed(endpoint, request).await?; let t = from_str(r.as_str())?; Ok(t) } pub async fn get_signed_p<T: de::DeserializeOwned, P: serde::Serialize>( &self, endpoint: &str, payload: Option<P>, recv_window: u64, ) -> Result<T> { let req = if let Some(p) = payload { build_signed_request_p(p, recv_window)? } else { let option: Option<PairQuery> = None; build_signed_request_p(option, recv_window)? }; let string = self.get_signed(endpoint, &req).await?; let data: &str = string.as_str(); let t = from_str(data)?; Ok(t) } pub async fn post_signed(&self, endpoint: &str, request: &str) -> Result<String> { let url = self.sign_request(endpoint, request); let response = self .inner .clone() .post(url.as_str()) .headers(self.build_headers(true)?) .send() .await?; self.handler(response).await } pub async fn post_signed_d<T: de::DeserializeOwned>(&self, endpoint: &str, request: &str) -> Result<T> { let r = self.post_signed(endpoint, request).await?; let t = from_str(r.as_str())?; Ok(t) } pub async fn post_signed_p<T: de::DeserializeOwned, P: serde::Serialize>( &self, endpoint: &str, payload: P, recv_window: u64, ) -> Result<T> { let request = build_signed_request_p(payload, recv_window)?; let string = self.post_signed(endpoint, &request).await?; let data: &str = string.as_str(); let t = from_str(data)?; Ok(t) } pub async fn delete_signed_p<T: de::DeserializeOwned, P: serde::Serialize>( &self, endpoint: &str, payload: P, recv_window: u64, ) -> Result<T> { let request = build_signed_request_p(payload, recv_window)?; let string = self.delete_signed(endpoint, &request).await?; let data: &str = string.as_str(); let t = from_str(data)?; Ok(t) } pub async fn delete_signed(&self, endpoint: &str, request: &str) -> Result<String> { let url = self.sign_request(endpoint, request); let response = self .inner .clone() .delete(url.as_str()) .headers(self.build_headers(true)?) .send() .await?; self.handler(response).await } pub async fn get(&self, endpoint: &str, request: &str) -> Result<String> { let mut url: String = format!("{}{}", self.host, endpoint); if !request.is_empty() { url.push_str(format!("?{}", request).as_str()); } let response = reqwest::get(url.as_str()).await?; self.handler(response).await } pub async fn get_p<T: DeserializeOwned>(&self, endpoint: &str, request: &str) -> Result<T> { let r = self.get(endpoint, request).await?; let t = from_str(r.as_str())?; Ok(t) } pub async fn get_d<T: DeserializeOwned, S: serde::Serialize>( &self, endpoint: &str, payload: Option<S>, ) -> Result<T> { let req = if let Some(p) = payload { build_request_p(p)? } else { String::new() }; self.get_p(endpoint, req.as_str()).await } pub async fn post(&self, endpoint: &str) -> Result<String> { let url: String = format!("{}{}", self.host, endpoint); let response = self .inner .clone() .post(url.as_str()) .headers(self.build_headers(false)?) .send() .await?; self.handler(response).await } pub async fn put(&self, endpoint: &str, listen_key: &str) -> Result<String> { let url: String = format!("{}{}", self.host, endpoint); let data: String = format!("listenKey={}", listen_key); let response = self .inner .clone() .put(url.as_str()) .headers(self.build_headers(false)?) .body(data) .send() .await?; self.handler(response).await } pub async fn delete(&self, endpoint: &str, listen_key: &str) -> Result<String> { let url: String = format!("{}{}", self.host, endpoint); let data: String = format!("listenKey={}", listen_key); let response = self .inner .clone() .delete(url.as_str()) .headers(self.build_headers(false)?) .body(data) .send() .await?; self.handler(response).await } // Request must be signed fn sign_request(&self, endpoint: &str, request: &str) -> String { let signed_key = hmac::Key::new(hmac::HMAC_SHA256, self.secret_key.as_bytes()); let signature = hex_encode(hmac::sign(&signed_key, request.as_bytes()).as_ref()); let request_body: String = format!("{}&signature={}", request, signature); let url: String = format!("{}{}?{}", self.host, endpoint, request_body); url } fn build_headers(&self, content_type: bool) -> Result<HeaderMap> { let mut custon_headers = HeaderMap::new(); custon_headers.insert(USER_AGENT, HeaderValue::from_static("binance-rs")); if content_type { custon_headers.insert( CONTENT_TYPE, HeaderValue::from_static("application/x-www-form-urlencoded"), ); } custon_headers.insert( HeaderName::from_static("x-mbx-apikey"), HeaderValue::from_str(self.api_key.as_str())?, ); Ok(custon_headers) } async fn handler(&self, response: Response) -> Result<String> { match response.status() { StatusCode::OK => { let body = response.bytes().await?; let result = std::str::from_utf8(&body); Ok(result?.to_string()) } StatusCode::INTERNAL_SERVER_ERROR => Err(Error::InternalServerError), StatusCode::SERVICE_UNAVAILABLE => Err(Error::ServiceUnavailable), StatusCode::UNAUTHORIZED => Err(Error::Unauthorized), StatusCode::BAD_REQUEST => { let error: BinanceContentError = response.json().await?; Err(handle_content_error(error)) } s => Err(Error::Msg(format!("Received response: {:?}", s))), } } } fn handle_content_error(error: BinanceContentError) -> crate::errors::Error { match (error.code, error.msg.as_ref()) { (-1013, error_messages::INVALID_PRICE) => Error::InvalidPrice, (-1125, msg) => Error::InvalidListenKey(msg.to_string()), _ => Error::BinanceError { response: error }, } }
32.278195
108
0.563941
e8970d081be43c36619673cd535b241a0381bdc2
11,695
pub mod error; pub mod output; mod tests; use chrono::{prelude::*, Duration}; use error::Error; use std::process::Stdio; use tokio::io::AsyncWriteExt; use tokio::process::Command; use crate::sealed::{FirstCmd, SecondCmd}; pub type Result<T> = std::result::Result<T, Error>; //OpCLI have expiration_time field what is the token's expiration time. //Intent to implement some method to auto renew the token. //TODO #[derive(Clone)] pub struct OpCLI { expiration_time: DateTime<Utc>, session: String, } impl OpCLI { #[inline] pub async fn new_with_pass(username: &str, password: &str) -> Result<Self> { let mut child = Command::new("op") .arg("signin") .arg(username) .arg("--raw") .stdin(Stdio::piped()) .stderr(Stdio::piped()) .stdout(Stdio::piped()) .spawn()?; let stdin = child.stdin.as_mut().unwrap(); stdin.write_all(password.as_bytes()).await?; let output = child.wait_with_output().await?; handle_op_signin_error(String::from_utf8_lossy(&output.stderr).to_string()).await?; let expiration_time = Utc::now() + Duration::minutes(29); Ok(Self { expiration_time, session: String::from_utf8_lossy(&output.stdout).to_string(), }) } pub fn get(&self) -> GetCmd { GetCmd { cmd: "get".to_string(), session: self.session.to_string(), } } pub fn create(&self) -> CreateCmd { CreateCmd { cmd: "create".to_string(), session: self.session.to_string(), } } #[inline] pub fn list(&self) -> ListCmd { ListCmd { cmd: "list".to_string(), session: self.session.to_string(), } } #[inline] pub fn delete(&self) -> DeleteCmd { DeleteCmd { cmd: "delete".to_string(), session: self.session.to_string(), } } } #[derive(Debug, Clone)] pub struct GetCmd { cmd: String, session: String, } impl sealed::FirstCmd for GetCmd { #[doc(hidden)] fn cmd(&self) -> &str { &self.cmd } #[doc(hidden)] fn session(&self) -> &str { &self.session } } //this macro repeat codes above. to create a first cmd then //implement FirstCmd trait for it. macro_rules! its_first_cmd { ($($FirstCmd:ident),+ $(,)?) => { $( #[derive(Debug, Clone)] pub struct $FirstCmd { cmd: String, session: String, } impl sealed::FirstCmd for $FirstCmd { #[doc(hidden)] fn cmd(&self) -> &str { &self.cmd } #[doc(hidden)] fn session(&self) -> &str { &self.session } } )+ }; } its_first_cmd!(CreateCmd, ListCmd, DeleteCmd); //Maybe I can generic on some of second cmd's method, they seems like do same thing. //TODO impl GetCmd { pub fn account(&self) -> AccountCmd { let flags: Vec<String> = Vec::new(); AccountCmd { first: self.clone(), cmd: "account".to_string(), flags, } } ///this method return items' fields of website,username,password pub fn item_lite(&self, item: &str) -> ItemLiteCmd { let flags: Vec<String> = vec![ item.to_string(), "--fields".to_string(), "website,username,password".to_string(), ]; ItemLiteCmd { first: self.clone(), cmd: "item".to_string(), flags, } } pub fn item(&self, item: &str) -> GetItemCmd { let flags: Vec<String> = vec![item.to_string()]; GetItemCmd { first: self.clone(), cmd: "item".to_string(), flags, } } pub fn document(&self, doc: &str) -> GetDocumentCmd { let flags: Vec<String> = vec![doc.to_string()]; GetDocumentCmd { first: self.clone(), cmd: "document".to_string(), flags, } } pub fn totp(&self, item_name: &str) -> GetTotpCmd { let flags: Vec<String> = vec![item_name.to_string()]; GetTotpCmd { first: self.clone(), cmd: "totp".to_string(), flags, } } pub fn user(&self, uuid: &str) -> GetUserCmd { let flags: Vec<String> = vec![uuid.to_string()]; GetUserCmd { first: self.clone(), cmd: "user".to_string(), flags, } } } impl CreateCmd { pub fn document(&self, path: &str) -> CreateDocumentCmd { let flags: Vec<String> = vec![path.to_string()]; CreateDocumentCmd { first: self.clone(), cmd: "document".to_string(), flags, } } } impl ListCmd { pub fn documents(&self) -> ListDocumentsCmd { let flags: Vec<String> = Vec::new(); ListDocumentsCmd { first: self.clone(), cmd: "documents".to_string(), flags, } } pub fn items(&self) -> ListItemsCmd { let flags: Vec<String> = Vec::new(); ListItemsCmd { first: self.clone(), cmd: "items".to_string(), flags, } } pub fn users(&self) -> ListUsersCmd { let flags: Vec<String> = Vec::new(); ListUsersCmd { first: self.clone(), cmd: "users".to_string(), flags, } } } impl DeleteCmd { pub fn item(&self) -> DeleteItemCmd { let flags: Vec<String> = Vec::new(); DeleteItemCmd { first: self.clone(), cmd: "item".to_string(), flags, } } pub fn document(&self, doc: &str) -> DeleteDocumentCmd { let flags: Vec<String> = vec![doc.to_string()]; DeleteDocumentCmd { first: self.clone(), cmd: "document".to_string(), flags, } } } #[async_trait::async_trait] pub trait SecondCmdExt: SecondCmd { fn add_flag(&mut self, flags: &[&str]) -> &Self { for flag in flags { if !self.flags().contains(&flag.to_string()) { self.flags().push(flag.to_string()) } } self } async fn run(&self) -> Result<Self::Output> { let mut args: Vec<String> = vec![ self.first().cmd().to_string(), self.cmd().to_string(), "--session".to_string(), self.first().session().trim().to_string(), ]; if !self.flags().is_empty() { self.flags() .into_iter() .for_each(|flag| args.push(flag.to_string())) } let out_str: &str = &exec_command(args).await?; if out_str.len() == 0 { return Ok(serde_json::from_str("{\"field\":\"ok\"}")?); } Ok(serde_json::from_str(out_str)?) } } impl<T: SecondCmd> SecondCmdExt for T {} #[derive(Debug)] pub struct AccountCmd { first: GetCmd, cmd: String, flags: Vec<String>, } #[async_trait::async_trait] impl SecondCmd for AccountCmd { type Output = output::Account; type First = GetCmd; #[doc(hidden)] fn first(&self) -> &GetCmd { &self.first } #[doc(hidden)] fn cmd(&self) -> &str { &self.cmd } #[doc(hidden)] fn flags(&self) -> Vec<String> { self.flags.clone() } } //This macro repeat above codes. To create a new second cmd struct //and implement SecondCmd trait for it. macro_rules! its_second_cmd { ($(($FirstCmd:ident,$SecondCmd:ident,$Output:ident)),+ $(,)?) => { $(#[derive(Debug)] pub struct $SecondCmd { first: $FirstCmd, cmd: String, flags: Vec<String>, } #[async_trait::async_trait] impl SecondCmd for $SecondCmd { type Output = output::$Output; type First = $FirstCmd; #[doc(hidden)] fn first(&self) -> &$FirstCmd { &self.first } #[doc(hidden)] fn cmd(&self) -> &str { &self.cmd } #[doc(hidden)] fn flags(&self) -> Vec<String> { self.flags.clone() } })+ }; } its_second_cmd!( (GetCmd, ItemLiteCmd, ItemLite), (GetCmd, GetDocumentCmd, Value), (GetCmd, GetTotpCmd, Value), (GetCmd, GetItemCmd, GetItem), (GetCmd, GetUserCmd, GetUser), (CreateCmd, CreateDocumentCmd, CreateDocument), (ListCmd, ListDocumentsCmd, ListDocuments), (ListCmd, ListItemsCmd, ListItems), (ListCmd, ListUsersCmd, ListUsers), (DeleteCmd, DeleteItemCmd, DeleteItem), (DeleteCmd, DeleteDocumentCmd, DeleteDocument) ); #[inline] async fn exec_command(args: Vec<String>) -> Result<String> { let child = Command::new("op") .args(args) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn()?; let output = child.wait_with_output().await?; handle_op_exec_error(String::from_utf8_lossy(&output.stderr).to_string()).await?; Ok(String::from_utf8_lossy(&output.stdout).to_string()) } #[inline] async fn handle_op_signin_error(std_err: String) -> std::result::Result<(), Error> { match std_err.trim() { err if err.contains("401") => Err(Error::OPSignInError("Wrong password".to_string())), err if err.contains("Account not found") => Err(Error::OPSignInError( "Account does not exist,may be you should firstly setup 1password-cli.".to_string(), )), _ => Ok(()), } } #[inline] async fn handle_op_exec_error(std_err: String) -> std::result::Result<(), Error> { match std_err.trim() { err if err.contains("doesn't seem to be an item") => { Err(Error::ItemQueryError("Item not founded".to_string())) } err if err.contains("Invalid session token") => { Err(Error::ItemQueryError("In valid session token".to_string())) } err if err.contains("More than one item matches") => Err(Error::ItemQueryError( "More than one item matches,Please specify one by uuid".to_string(), )), _ => Ok(()), } } //why I need this: Cause of SecondCmdExt need explicit scope in. //So this will impl a casting method for the struct who //implemented SecondCmdExt. now user do not need `use crate::SecondCmdExt` macro_rules! impl_casting_method { ($($ObjName:ident),+ $(,)?) => { $( impl $ObjName { pub async fn run(&self) -> Result<<Self as SecondCmd>::Output> { <Self as SecondCmdExt>::run(self).await } pub fn add_flag(&mut self, flags: &[&str]) -> &Self { <Self as SecondCmdExt>::add_flag(self, flags) } } )+ }; } impl_casting_method!( ItemLiteCmd, GetDocumentCmd, GetTotpCmd, GetItemCmd, CreateDocumentCmd, ListDocumentsCmd, ListItemsCmd, AccountCmd ); mod sealed { use serde::de::DeserializeOwned; pub trait FirstCmd { #[doc(hidden)] fn cmd(&self) -> &str; #[doc(hidden)] fn session(&self) -> &str; } #[async_trait::async_trait] pub trait SecondCmd { type Output: DeserializeOwned; type First: FirstCmd + Clone; #[doc(hidden)] fn first(&self) -> &Self::First; #[doc(hidden)] fn cmd(&self) -> &str; #[doc(hidden)] fn flags(&self) -> Vec<String>; } }
26.399549
96
0.531937
abbbd1eb56da0aa66db5abe3992de8e1db425a4b
24,819
/* * Copyright (c) 2017 Boucher, Antoni <bouanto@zoho.com> * * 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. */ use std::collections::HashMap; use std::fs::File; use std::io::Read; #[cfg(feature = "unstable")] use std::iter::FromIterator; use std::str::FromStr; use std::sync::Mutex; use proc_macro; use proc_macro2::{TokenTree, TokenStream}; use quote::ToTokens; use syn::{ self, Expr, Ident, LitStr, Pat, Path, Type, parse, parse2, }; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use self::ChildItem::*; use self::EventValue::*; use self::EventValueReturn::*; use self::EitherWidget::*; use self::IdentOrEventValue::*; use self::InitProperties::*; use self::PathOrIdent::*; use self::SaveWidget::*; lazy_static! { static ref NAMES_INDEX: Mutex<HashMap<String, u32>> = Mutex::new(HashMap::new()); } type ChildEvents = HashMap<(Ident, Ident), Event>; type ChildProperties = HashMap<(Ident, Ident), Expr>; #[derive(PartialEq)] enum SaveWidget { DontSave, Save, } #[derive(Debug)] pub enum EventValueReturn { CallReturn(Expr), Return(Expr, Expr), WithoutReturn(Expr), } #[derive(Debug)] pub enum EventValue { CurrentWidget(EventValueReturn), ForeignWidget(Ident, EventValueReturn), NoEventValue, } #[derive(Debug)] pub struct Event { pub params: Vec<Pat>, pub shared_values: Vec<Ident>, pub use_self: bool, pub value: EventValue, } impl Event { fn new() -> Self { Event { params: vec![], shared_values: vec![], use_self: false, value: NoEventValue, } } } #[derive(Debug)] pub struct Widget { pub child_events: ChildEvents, // TODO: does it make sense for a relm widget? pub child_properties: ChildProperties, // TODO: does it make sense for a relm widget? pub children: Vec<Widget>, pub container_type: Option<Option<String>>, // TODO: Why two Options? pub init_parameters: Vec<Expr>, pub is_container: bool, pub name: Ident, pub parent_id: Option<String>, pub properties: HashMap<Ident, Expr>, pub typ: Path, pub widget: EitherWidget, } impl Widget { fn new_gtk(widget: GtkWidget, typ: Path, init_parameters: Vec<Expr>, children: Vec<Widget>, properties: HashMap<Ident, Expr>, child_properties: ChildProperties, child_events: ChildEvents) -> Self { let name = gen_widget_name(&typ); Widget { child_events, child_properties, children, container_type: None, init_parameters, is_container: false, name, parent_id: None, properties, typ, widget: Gtk(widget), } } fn new_relm(widget: RelmWidget, typ: Path, init_parameters: Vec<Expr>, children: Vec<Widget>, properties: HashMap<Ident, Expr>, child_properties: ChildProperties, child_events: ChildEvents) -> Self { let mut name = gen_widget_name(&typ); // Relm widgets are not used in the update() method; they are only saved to avoid dropping // their channel too soon. // So prepend an underscore to hide a warning. name = Ident::new(&format!("_{}", name), name.span()); Widget { child_events, child_properties, children, container_type: None, init_parameters, is_container: false, name, parent_id: None, properties, typ, widget: Relm(widget), } } } #[derive(Debug)] pub enum EitherWidget { Gtk(GtkWidget), Relm(RelmWidget), } #[derive(Debug)] pub struct GtkWidget { pub construct_properties: HashMap<Ident, Expr>, pub events: HashMap<Ident, Event>, pub relm_name: Option<Type>, pub save: bool, } impl GtkWidget { fn new() -> Self { GtkWidget { construct_properties: HashMap::new(), events: HashMap::new(), relm_name: None, save: false, } } } #[derive(Debug)] pub struct RelmWidget { pub events: HashMap<Ident, Vec<Event>>, pub gtk_events: HashMap<Ident, Event>, pub messages: HashMap<Ident, Expr>, } impl RelmWidget { fn new() -> Self { RelmWidget { events: HashMap::new(), gtk_events: HashMap::new(), messages: HashMap::new(), } } } pub fn parse_widget(tokens: TokenStream) -> Widget { if let Ok(literal) = parse2::<LitStr>(tokens.clone()) { // TODO: also support glade file. let mut file = File::open(literal.value()).expect("File::open() in parse()"); let mut file_content = String::new(); file.read_to_string(&mut file_content).expect("read_to_string() in parse()"); let tokens = proc_macro::TokenStream::from_str(&file_content).expect("convert string to TokenStream"); #[cfg(feature = "unstable")] let tokens = respan_with(tokens, literal.span().unstable()); parse(tokens).expect("parse() Widget") } else { parse2(tokens).expect("parse() Widget") } } enum InitProperties { ConstructProperties(HashMap<Ident, Expr>), InitParameters(Vec<Expr>), NoInitProperties, } macro_rules! separated_by0 { ($i:expr, $sep:ident!($($sep_args:tt)*), $submac:ident!( $($args:tt)* )) => {{ let ret; let mut res = ::std::vec::Vec::new(); let mut input = $i; loop { if input.eof() { ret = ::std::result::Result::Ok((res, input)); break; } match $submac!(input, $($args)*) { ::std::result::Result::Err(_) => { ret = ::std::result::Result::Ok((res, input)); break; } ::std::result::Result::Ok((o, i)) => { // loop trip must always consume (otherwise infinite loops) if i == input { ret = ::syn::parse_error(); break; } res.push(o); input = i; } } match $sep!(input, $($sep_args)*) { ::std::result::Result::Err(_) => { ret = ::std::result::Result::Ok((res, input)); break; }, ::std::result::Result::Ok((_, i)) => { // loop trip must always consume (otherwise infinite loops) if i == input { ret = ::syn::parse_error(); break; } input = i; }, } } ret }}; } named! { parse_hash -> InitProperties, map!(braces!(map!(separated_by0!( punct!(,), do_parse!( ident: syn!(Ident) >> punct!(:) >> expr: syn!(Expr) >> (ident, expr) )), |data| ConstructProperties(data.into_iter().collect()))), |(_, hash)| hash) } named! { init_properties -> InitProperties, alt! ( map!(parens!(alt! ( parse_hash | map!(expr_list, InitParameters) ) ), |(_, hash)| hash) | epsilon!() => { |_| NoInitProperties } ) } enum ChildItem { ChildEvent(Ident, Ident, Event), ItemChildProperties(ChildProperties), ItemEvent(Ident, Event), ChildWidget(Widget), Property(Ident, Value), RelmMsg(Ident, Value), RelmMsgEvent(Ident, Event), } impl ChildItem { fn unwrap_widget(self) -> Widget { match self { ChildEvent(_, _, _) => panic!("Expected widget, found child event"), ItemEvent(_, _) => panic!("Expected widget, found event"), ItemChildProperties(_) => panic!("Expected widget, found child properties"), Property(_, _) => panic!("Expected widget, found property"), RelmMsg(_, _) => panic!("Expected widget, found relm msg"), RelmMsgEvent(_, _) => panic!("Expected widget, found relm msg event"), ChildWidget(widget) => widget, } } } named! { attributes -> HashMap<String, Option<LitStr>>, map!(many0!(do_parse!( punct!(#) >> values: map!(brackets!(separated_by0!(punct!(,), do_parse!( name: syn!(Ident) >> value: option!(do_parse!( punct!(=) >> value: syn!(LitStr) >> (value) )) >> (name.to_string(), value) ))), |(_, values)| values ) >> (values))), |maps| { let mut attrs = HashMap::new(); for map in maps { for (key, values) in map { attrs.insert(key, values); } } attrs }) } #[derive(Debug)] enum PathOrIdent { WidgetIdent(Path), WidgetPath(Path), } impl PathOrIdent { fn get_ident(&self) -> &Path { match *self { WidgetIdent(ref ident) => ident, WidgetPath(_) => panic!("Expected ident"), } } fn get_path(&self) -> &Path { match *self { WidgetIdent(_) => panic!("Expected path"), WidgetPath(ref path) => path, } } } named! { path_or_ident -> PathOrIdent, map!(syn!(Path), |path| { if path.segments.len() == 1 { WidgetIdent(path) } else { WidgetPath(path) } }) } named! { child_widget(root: SaveWidget) -> (ChildItem, Option<String>), do_parse!( attributes: map!(option!(attributes), |attributes| attributes.unwrap_or_else(HashMap::new)) >> typ: path_or_ident >> relm_widget: cond!(match typ { WidgetIdent(_) => true, WidgetPath(_) => false, }, call!(relm_widget, typ.get_ident().clone())) >> gtk_widget: cond!(match typ { WidgetIdent(_) => false, WidgetPath(_) => true, }, call!(gtk_widget, typ.get_path().clone(), attributes.contains_key("name") || root == Save)) >> (match typ { WidgetIdent(_) => { let mut widget = relm_widget.expect("relm widget"); adjust_widget_with_attributes(widget, &attributes) }, WidgetPath(_) => { let mut widget = gtk_widget.expect("gtk widget"); adjust_widget_with_attributes(widget, &attributes) }, }) ) } named! { gtk_widget(typ: Path, save: bool) -> ChildItem, map!(do_parse!( init_properties: init_properties >> gtk_widget: braces!(do_parse!( child_items: separated_by0!(punct!(,), call!(child_gtk_item)) >> ({ let mut gtk_widget = GtkWidget::new(); gtk_widget.save = save; let mut init_parameters = vec![]; let mut children = vec![]; let mut properties = HashMap::new(); let mut child_events = HashMap::new(); let mut child_properties = HashMap::new(); for item in child_items.into_iter() { match item { ChildEvent(event_name, child_name, event) => { let _ = child_events.insert((child_name, event_name), event); }, ItemChildProperties(child_props) => { for (key, value) in child_props { child_properties.insert(key, value); } }, ItemEvent(ident, event) => { let _ = gtk_widget.events.insert(ident, event); }, ChildWidget(widget) => children.push(widget), Property(ident, value) => { let _ = properties.insert(ident, value.value); }, RelmMsg(_, _) | RelmMsgEvent(_, _) => panic!("Unexpected relm msg in gtk widget"), } } match init_properties { ConstructProperties(construct_properties) => gtk_widget.construct_properties = construct_properties, InitParameters(init_params) => init_parameters = init_params, NoInitProperties => (), } ChildWidget(Widget::new_gtk(gtk_widget, typ, init_parameters, children, properties, child_properties, child_events)) }) )) >> (gtk_widget) ), |(_, widget)| widget) } named! { child_relm_item -> ChildItem, alt! ( relm_property_or_event | map!(call!(child_widget, DontSave), |(widget, _)| widget) ) } named! { relm_widget(typ: Path) -> ChildItem, do_parse!( init_parameters: option!(map!(parens!(expr_list), |(_, exprs)| exprs)) >> relm_widget: map!(option!(braces!(do_parse!( child_items: separated_by0!(punct!(,), call!(child_relm_item)) >> ({ let init_parameters = init_parameters.clone().unwrap_or_else(Vec::new); let mut relm_widget = RelmWidget::new(); let mut children = vec![]; let mut child_properties = HashMap::new(); let mut child_events = HashMap::new(); let mut properties = HashMap::new(); for item in child_items { match item { ChildEvent(event_name, child_name, event) => { let _ = child_events.insert((child_name, event_name), event); }, ChildWidget(widget) => children.push(widget), ItemEvent(ident, event) => { let _ = relm_widget.gtk_events.insert(ident, event); }, ItemChildProperties(child_props) => { for (key, value) in child_props { child_properties.insert(key, value); } }, Property(ident, value) => { let _ = properties.insert(ident, value.value); }, RelmMsg(ident, value) => { let _ = relm_widget.messages.insert(ident, value.value); }, RelmMsgEvent(ident, event) => { let events = relm_widget.events.entry(ident).or_insert_with(Vec::new); events.push(event); }, } } ChildWidget(Widget::new_relm(relm_widget, typ.clone(), init_parameters, children, properties, child_properties, child_events)) }) ))), |widget| { widget .map(|(_, widget)| widget) .unwrap_or_else(|| { let init_parameters = init_parameters.unwrap_or_else(Vec::new); ChildWidget(Widget::new_relm(RelmWidget::new(), typ, init_parameters, vec![], HashMap::new(), HashMap::new(), HashMap::new())) }) }) >> (relm_widget) ) } named! { relm_property_or_event -> ChildItem, do_parse!( ident: syn!(Ident) >> item: alt! ( do_parse!( punct!(:) >> result: call!(value_or_child_properties, ident.clone()) >> ( if ident.to_string().chars().next().map(|char| char.is_lowercase()) == Some(false) { // Uppercase is a msg to send. match result { Property(ident, value) => RelmMsg(ident, value), _ => panic!("Expecting property"), } } else { // Lowercase is a gtk property. result } ) ) | do_parse!( punct!(.) >> event_name: syn!(Ident) >> event: event >> (ChildEvent(event_name, ident.clone(), event)) ) | map!(event, |mut event| { if ident.to_string().chars().next().map(|char| char.is_lowercase()) == Some(false) { // Uppercase is a msg. RelmMsgEvent(ident, event) } else { // Lowercase is a gtk event. if event.params.is_empty() { event.params.push(wild_pat()); } ItemEvent(ident, event) } }) ) >> (item) )} named! { gtk_child_property_or_event -> ChildItem, do_parse!( ident: syn!(Ident) >> item: alt! ( do_parse!( punct!(:) >> value: call!(value_or_child_properties, ident.clone()) >> (value) ) | do_parse!( punct!(.) >> event_name: syn!(Ident) >> mut event: event >> ({ if event.params.is_empty() { event.params.push(wild_pat()); } ChildEvent(event_name, ident.clone(), event) }) ) | map!(event, |mut event| { if event.params.is_empty() { event.params.push(wild_pat()); } ItemEvent(ident, event) }) ) >> (item) ) } named! { value_or_child_properties(ident: Ident) -> ChildItem, alt! ( map!(braces!(child_properties), |(_, properties)| { let properties = properties.into_iter() .map(|(key, value)| ((ident.clone(), key), value)) .collect(); ItemChildProperties(properties) }) | map!(value, |value| Property(ident, value)) ) } named! { tag(expected_ident: String) -> (), do_parse!( ident: syn!(Ident) >> cond!(ident != expected_ident, map!(reject!(), |()| ())) >> cond!(ident == expected_ident, epsilon!()) >> () )} named! { shared_values -> Option<Vec<Ident>>, option!(do_parse!( call!(tag, "with".to_string()) >> idents: map!(parens!(ident_list), |(_, idents)| idents) >> (idents) )) } enum IdentOrEventValue { MessageIdent(EventValueReturn, bool), MessageEventValue(Ident, EventValueReturn, bool), } fn expr_use_self(expr: &Expr) -> bool { let mut tokens = quote! {}; expr.to_tokens(&mut tokens); tokens.into_iter().any(|token| { if let TokenTree::Ident(ident) = token { return ident == "self"; } false }) } struct Value { value: Expr, use_self: bool, } named! { value -> Value, do_parse!( expr: syn!(Expr) >> ({ let use_self = expr_use_self(&expr); Value { value: expr, use_self, } }) )} named! { event_value -> (EventValueReturn, bool), alt! ( do_parse!( call!(tag, "return".to_string()) >> value: value >> (CallReturn(value.value), value.use_self) ) | map!(parens!(do_parse!( value1: value >> punct!(,) >> value2: value >> (Return(value1.value, value2.value), value1.use_self || value2.use_self) )), |(_, value)| value) | do_parse!( value: value >> (WithoutReturn(value.value), value.use_self) ) ) } named! { message_sent -> IdentOrEventValue, do_parse!( value: alt! ( map!(do_parse!( ident: syn!(Ident) >> punct!(@) >> event_value: event_value >> ((ident, event_value)) ), |(ident, (value, use_self))| MessageEventValue(ident, value, use_self)) | event_value => { |(value, use_self)| MessageIdent(value, use_self) } ) >> (value) ) } named! { expr_list -> Vec<Expr>, map!(call!(Punctuated::parse_terminated), |exprs: Punctuated<Expr, Token![,]>| exprs.into_iter().collect()) } named! { ident_list -> Vec<Ident>, map!(call!(Punctuated::parse_terminated), |idents: Punctuated<Ident, Token![,]>| idents.into_iter().collect()) } named! { event -> Event, do_parse!( params: option!(map!(parens!(separated_by0!(punct!(,), syn!(syn::Pat))), |(_, params)| params)) >> shared_values: shared_values >> punct!(=>) >> message_sent: message_sent >> ({ let mut event = Event::new(); if let Some(params) = params { event.params = params; } if let Some(shared_values) = shared_values { event.shared_values = shared_values; } match message_sent { MessageIdent(event_value, use_self) => { event.use_self = use_self; event.value = CurrentWidget(event_value); }, MessageEventValue(ident, event_value, use_self) => { event.use_self = use_self; event.value = ForeignWidget(ident, event_value); }, } event }) )} named! { child_gtk_item -> ChildItem, alt! ( gtk_child_property_or_event | map!(call!(child_widget, DontSave), |(widget, _)| widget) ) } named! { child_properties -> HashMap<Ident, Expr>, map!( separated_by0!(punct!(,), do_parse!( ident: syn!(Ident) >> punct!(:) >> value: value >> ((ident, value.value)) )), |properties| properties.into_iter().collect()) } fn wild_pat() -> Pat { parse(quote! { _ }.into()) .expect("wildcard pattern") } impl syn::synom::Synom for Widget { named! { parse -> Self, do_parse!( widget: call!(child_widget, Save) >> option!(punct!(,)) >> ({ let (widget, parent_id) = widget; let mut widget = widget.unwrap_widget(); widget.parent_id = parent_id; widget }) ) } } fn gen_widget_name(path: &Path) -> Ident { let name = path_to_string(path); let name = if let Some(index) = name.rfind(':') { name[index + 1 ..].to_lowercase() } else { name.to_lowercase() }; let mut hashmap = NAMES_INDEX.lock().expect("lock() in gen_widget_name()"); let index = hashmap.entry(name.clone()).or_insert(0); *index += 1; Ident::new(&format!("{}{}", name, index), path.span()) } fn path_to_string(path: &Path) -> String { let mut string = String::new(); for segment in &path.segments { string.push_str(&segment.ident.to_string()); } string } fn adjust_widget_with_attributes(mut widget: ChildItem, attributes: &HashMap<String, Option<LitStr>>) -> (ChildItem, Option<String>) { let parent_id; match widget { ChildWidget(ref mut widget) => { let container_type = attributes.get("container") .map(|typ| typ.as_ref().map(|lit| lit.value())); let name = attributes.get("name").and_then(|name| name.clone()); if let Some(name) = name { widget.name = Ident::new(&name.value(), name.span()); } widget.is_container = !widget.children.is_empty(); widget.container_type = container_type; parent_id = attributes.get("parent").and_then(|opt_str| opt_str.as_ref().map(|lit| lit.value())); }, _ => panic!("Expecting widget"), } (widget, parent_id) } #[cfg(feature = "unstable")] pub fn respan_with(tokens: proc_macro::TokenStream, span: proc_macro::Span) -> proc_macro::TokenStream { let mut result = vec![]; for mut token in tokens { match token { proc_macro::TokenTree::Group(group) => { let new_tokens = respan_with(group.stream(), span); let mut res = proc_macro::TokenTree::Group(proc_macro::Group::new(group.delimiter(), new_tokens)); res.set_span(span); result.push(res); }, _ => { token.set_span(span); result.push(token); } } } FromIterator::from_iter(result.into_iter()) }
31.062578
127
0.537693
8feb39343edca73264cc7a483053562a1f0240e5
8,263
//! A very simple, and fast, constant propagation //! //! Each location has the known constant values for all variables before //! execution of that location. //! //! Calling Constants::eval() uses the known constant values to replace scalars, //! and then attempts to evaluate the expression to an `il::Constant`. use crate::analysis::fixed_point; use crate::error::*; use crate::executor::eval; use crate::il; use std::cmp::{Ordering, PartialOrd}; use std::collections::HashMap; /// Compute constants for the given function pub fn constants<'r>( function: &'r il::Function, ) -> Result<HashMap<il::ProgramLocation, Constants>> { let constants = fixed_point::fixed_point_forward(ConstantsAnalysis {}, function)?; // we're now going to remap constants, so each position holds the values of // constants immediately preceeding its execution. let mut result = HashMap::new(); for (location, _) in &constants { let rfl = location.function_location().apply(function).unwrap(); let rpl = il::RefProgramLocation::new(function, rfl); result.insert( location.clone(), rpl.backward()? .into_iter() .fold(Constants::new(), |c, location| { c.join(&constants[&location.into()]) }), ); } Ok(result) } #[allow(dead_code)] // Bottom is never used #[derive(Clone, Debug, PartialEq)] enum Constant { Top, Constant(il::Constant), Bottom, } impl Constant { fn get(&self) -> Option<&il::Constant> { match *self { Constant::Constant(ref constant) => Some(constant), Constant::Top | Constant::Bottom => None, } } } impl PartialOrd for Constant { fn partial_cmp(&self, other: &Constant) -> Option<Ordering> { match *self { Constant::Top => match *other { Constant::Top => Some(Ordering::Equal), Constant::Constant(_) | Constant::Bottom => Some(Ordering::Greater), }, Constant::Constant(ref lc) => match *other { Constant::Top => Some(Ordering::Less), Constant::Constant(ref rc) => { if lc == rc { Some(Ordering::Equal) } else { None } } Constant::Bottom => Some(Ordering::Greater), }, Constant::Bottom => match *other { Constant::Top | Constant::Constant(_) => Some(Ordering::Less), Constant::Bottom => Some(Ordering::Equal), }, } } } /// The value of all constants before the `RefProgramLocation` is evaluated. #[derive(Clone, Debug, PartialEq)] pub struct Constants { constants: HashMap<il::Scalar, Constant>, } impl PartialOrd for Constants { fn partial_cmp(&self, other: &Constants) -> Option<Ordering> { if self.constants.len() < other.constants.len() { for (ls, lc) in self.constants.iter() { if !other.constants.get(ls).map(|rc| lc <= rc).unwrap_or(false) { return None; } } Some(Ordering::Less) } else if self.constants.len() > other.constants.len() { for (ls, lc) in other.constants.iter() { if !self.constants.get(ls).map(|rc| lc <= rc).unwrap_or(false) { return None; } } Some(Ordering::Greater) } else { let mut order = Ordering::Equal; for (ls, lc) in &self.constants { match other.constants.get(ls) { Some(rc) => { if lc < rc { if order <= Ordering::Equal { order = Ordering::Less; } else { return None; } } else if lc > rc { if order >= Ordering::Equal { order = Ordering::Greater; } else { return None; } } } None => { return None; } } } Some(order) } } } impl Constants { fn new() -> Constants { Constants { constants: HashMap::new(), } } /// Get the constant value for a scalar, if it exists. pub fn scalar(&self, scalar: &il::Scalar) -> Option<&il::Constant> { self.constants .get(scalar) .and_then(|constant| constant.get()) } fn set_scalar(&mut self, scalar: il::Scalar, constant: Constant) { self.constants.insert(scalar, constant); } fn top(&mut self) { self.constants .iter_mut() .for_each(|(_, constant)| *constant = Constant::Top); } /// Attempt to reduce an expression down to a constant, using the constants /// found by this analysis. pub fn eval(&self, expression: &il::Expression) -> Option<il::Constant> { let expression_scalars = expression.scalars(); let expression = expression_scalars.into_iter().fold( Some(expression.clone()), |expression, scalar| { self.scalar(scalar).and_then(|constant| { expression.map(|expr| { expr.replace_scalar(scalar, &constant.clone().into()) .unwrap() }) }) }, )?; eval(&expression).ok() } fn join(self, other: &Constants) -> Constants { let mut result = self.clone(); for (scalar, constant) in other.constants.iter() { match self.constants.get(scalar) { Some(c) => { if c != constant { result.set_scalar(scalar.clone(), Constant::Top); } } None => result.set_scalar(scalar.clone(), constant.clone()), } } result } } // We require a struct to implement methods for our analysis over. struct ConstantsAnalysis {} impl<'r> fixed_point::FixedPointAnalysis<'r, Constants> for ConstantsAnalysis { fn trans( &self, location: il::RefProgramLocation<'r>, state: Option<Constants>, ) -> Result<Constants> { let mut state = match state { Some(state) => state, None => Constants::new(), }; let state = match location.instruction() { Some(instruction) => match *instruction.operation() { il::Operation::Assign { ref dst, ref src } => { let constant = state .eval(src) .map(|constant| Constant::Constant(constant)) .unwrap_or(Constant::Top); state.set_scalar(dst.clone(), constant); state } il::Operation::Load { ref dst, .. } => { state.set_scalar(dst.clone(), Constant::Top); state } il::Operation::Store { .. } | il::Operation::Branch { .. } => { state.top(); state } il::Operation::Intrinsic { ref intrinsic } => { if let Some(scalars_written) = intrinsic.scalars_written() { scalars_written .into_iter() .for_each(|scalar| state.set_scalar(scalar.clone(), Constant::Top)); } else { state.top(); } state } il::Operation::Nop => state, }, None => state, }; Ok(state) } fn join(&self, state0: Constants, state1: &Constants) -> Result<Constants> { Ok(state0.join(state1)) } }
32.920319
96
0.481544
09f7ca32437d0dafb6613dfac834d6c18d3e7551
5,584
use super::flo_store::*; use super::animation_core::*; use desync::*; use flo_canvas::*; use flo_animation::*; use futures::*; use std::sync::*; use std::time::Duration; /// /// Canvas cache associated with a point in time /// pub struct LayerCanvasCache<TFile: FloFile+Send> { /// Database core core: Arc<Desync<AnimationDbCore<TFile>>>, /// The time where we're retrieving (or storing) cached items when: Duration, /// The ID of the layer that we're retrieving/storing cached items layer_id: i64 } impl<TFile: FloFile+Send> LayerCanvasCache<TFile> { /// /// Creates a layer cache at the specified time on a particular layer /// pub fn cache_with_time(db: Arc<Desync<AnimationDbCore<TFile>>>, layer_id: i64, when: Duration) -> LayerCanvasCache<TFile> { LayerCanvasCache { core: db, when: when, layer_id: layer_id } } } impl<TFile: 'static+FloFile+Send> CanvasCache for LayerCanvasCache<TFile> { /// /// Invalidates any stored canvas with the specified type /// fn invalidate(&self, cache_type: CacheType) { // Copy the properties from this structure let layer_id = self.layer_id; let when = self.when; // Perform the update in the background self.core.desync(move |core| { // Remove the cached item let result = core.db.update(vec![ DatabaseUpdate::PushLayerId(layer_id), DatabaseUpdate::PopDeleteLayerCache(when, cache_type) ]); // Note any failures if let Err(result) = result { core.failure = Some(result.into()) } }); } /// /// Stores a particular drawing in the cache /// fn store(&self, cache_type: CacheType, items: Arc<Vec<Draw>>) { // Serialize the drawing instructions let mut draw_string = String::new(); items.iter().for_each(|item| { item.encode_canvas(&mut draw_string); }); // Copy the properties from this structure let layer_id = self.layer_id; let when = self.when; // Perform the update in the background self.core.desync(move |core| { // Store the cached item let result = core.db.update(vec![ DatabaseUpdate::PushLayerId(layer_id), DatabaseUpdate::PopStoreLayerCache(when, cache_type, draw_string) ]); // Note any failures if let Err(result) = result { core.failure = Some(result.into()) } }); } /// /// Retrieves the cached item at the specified time, if it exists /// fn retrieve(&self, cache_type: CacheType) -> Option<Arc<Vec<Draw>>> { self.core.sync(|core| core.db.query_layer_cached_drawing(self.layer_id, cache_type, self.when)) .unwrap() .map(|drawing| Arc::new(drawing)) } /// /// Retrieves the cached item, or calls the supplied function to generate it if it's not already in the cache /// fn retrieve_or_generate(&self, cache_type: CacheType, generate: Box<dyn Fn() -> Arc<Vec<Draw>> + Send>) -> CacheProcess<Arc<Vec<Draw>>, Box<dyn Future<Item=Arc<Vec<Draw>>, Error=Canceled>+Send>> { if let Some(result) = self.retrieve(cache_type) { // Cached data is already available CacheProcess::Cached(result) } else { // Process in the background using the cache work queue let core = Arc::clone(&self.core); let work = self.core.sync(|core| Arc::clone(&core.cache_work)); let layer_id = self.layer_id; let when = self.when; // Note that as all caching work is done sequentially, it's not possible to accidentally call the generation function twice let future_result = work.future(move |_| { // Attempt to retrieve an existing entry for this cached item let existing = core.sync(|core| core.db.query_layer_cached_drawing(layer_id, cache_type, when)) .unwrap() .map(|drawing| Arc::new(drawing)); if let Some(existing) = existing { // Re-use the existing cached element if one has been generated in the meantime existing } else { // Call the generation function to create a new cache let new_drawing = generate(); // Encode for storing in the database let mut draw_string = String::new(); new_drawing.iter().for_each(|item| { item.encode_canvas(&mut draw_string); }); core.desync(move |core| { // Store the cached item let result = core.db.update(vec![ DatabaseUpdate::PushLayerId(layer_id), DatabaseUpdate::PopStoreLayerCache(when, cache_type, draw_string) ]); // Note any failures if let Err(result) = result { core.failure = Some(result.into()) } }); // The generated drawing is the cache result new_drawing } }); CacheProcess::Process(Box::new(future_result)) } } }
36.25974
200
0.551576
1cd7a27a70dba7cb79feac5623c6a360170ef7e7
2,976
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![deny(warnings)] use nix::sys::socket::SockAddr; use std::io::{Read, Write}; use std::net::TcpListener; use std::net::{IpAddr, Ipv4Addr}; use std::str; use std::sync::mpsc; use std::thread; use tempfile::NamedTempFile; use vsock::VsockStream; use vsock_proxy::starter::Proxy; fn vsock_connect(port: u32) -> VsockStream { let sockaddr = SockAddr::new_vsock(vsock_proxy::starter::VSOCK_PROXY_CID, port); VsockStream::connect(&sockaddr).expect("Could not connect") } /// Test connection with both client and server sending each other messages #[test] fn test_tcp_connection() { // Proxy will translate from port 8000 vsock to localhost port 9000 TCP let addr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).to_string(); let mut file = NamedTempFile::new().unwrap(); file.write_all( b"allowlist:\n\ - {address: 127.0.0.1, port: 9000}", ) .unwrap(); let proxy = Proxy::new( vsock_proxy::starter::VSOCK_PROXY_PORT, &addr, 9000, 2, file.path().to_str(), false, false, ) .unwrap(); let (tx, rx) = mpsc::channel(); // Create a listening TCP server on port 9000 let server_handle = thread::spawn(move || { let server = TcpListener::bind("127.0.0.1:9000").expect("server bind"); tx.send(true).expect("server send event"); let (mut stream, _) = server.accept().expect("server accept"); // Read request let mut buf = [0; 13]; stream.read_exact(&mut buf).expect("server read"); let msg = str::from_utf8(&buf).expect("from_utf8"); assert_eq!(msg, "client2server"); // Write response stream.write_all(b"server2client").expect("server write"); }); let _ret = rx.recv().expect("main recv event"); let (tx, rx) = mpsc::channel(); // Start proxy in a different thread let ret = proxy.sock_listen(); let listener = ret.expect("proxy listen"); let proxy_handle = thread::spawn(move || { tx.send(true).expect("proxy send event"); let _ret = proxy.sock_accept(&listener).expect("proxy accept"); }); let _ret = rx.recv().expect("main recv event"); // Start client that connects to proxy on port 8000 vsock let client_handle = thread::spawn(move || { let mut stream = vsock_connect(vsock_proxy::starter::VSOCK_PROXY_PORT); // Write request stream.write_all(b"client2server").expect("client write"); // Read response let mut buf = [0; 13]; stream.read_exact(&mut buf).expect("client read"); let msg = str::from_utf8(&buf).expect("from_utf8"); assert_eq!(msg, "server2client"); }); server_handle.join().expect("Server panicked"); proxy_handle.join().expect("Proxy panicked"); client_handle.join().expect("Client panicked"); }
31.659574
84
0.628696
ab33fbcca15a3172513e2124b374632cf604b80a
25,374
// Type substitutions. use crate::mir; use crate::ty::codec::{TyDecoder, TyEncoder}; use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeVisitor}; use crate::ty::sty::{ClosureSubsts, GeneratorSubsts, InlineConstSubsts}; use crate::ty::{self, Lift, List, ParamConst, Ty, TyCtxt}; use rustc_hir::def_id::DefId; use rustc_macros::HashStable; use rustc_serialize::{self, Decodable, Encodable}; use rustc_span::{Span, DUMMY_SP}; use smallvec::SmallVec; use core::intrinsics; use std::cmp::Ordering; use std::fmt; use std::marker::PhantomData; use std::mem; use std::num::NonZeroUsize; use std::ops::ControlFlow; /// An entity in the Rust type system, which can be one of /// several kinds (types, lifetimes, and consts). /// To reduce memory usage, a `GenericArg` is an interned pointer, /// with the lowest 2 bits being reserved for a tag to /// indicate the type (`Ty`, `Region`, or `Const`) it points to. #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct GenericArg<'tcx> { ptr: NonZeroUsize, marker: PhantomData<(Ty<'tcx>, ty::Region<'tcx>, &'tcx ty::Const<'tcx>)>, } const TAG_MASK: usize = 0b11; const TYPE_TAG: usize = 0b00; const REGION_TAG: usize = 0b01; const CONST_TAG: usize = 0b10; #[derive(Debug, TyEncodable, TyDecodable, PartialEq, Eq, PartialOrd, Ord, HashStable)] pub enum GenericArgKind<'tcx> { Lifetime(ty::Region<'tcx>), Type(Ty<'tcx>), Const(&'tcx ty::Const<'tcx>), } impl<'tcx> GenericArgKind<'tcx> { fn pack(self) -> GenericArg<'tcx> { let (tag, ptr) = match self { GenericArgKind::Lifetime(lt) => { // Ensure we can use the tag bits. assert_eq!(mem::align_of_val(lt) & TAG_MASK, 0); (REGION_TAG, lt as *const _ as usize) } GenericArgKind::Type(ty) => { // Ensure we can use the tag bits. assert_eq!(mem::align_of_val(ty) & TAG_MASK, 0); (TYPE_TAG, ty as *const _ as usize) } GenericArgKind::Const(ct) => { // Ensure we can use the tag bits. assert_eq!(mem::align_of_val(ct) & TAG_MASK, 0); (CONST_TAG, ct as *const _ as usize) } }; GenericArg { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData } } } impl<'tcx> fmt::Debug for GenericArg<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.unpack() { GenericArgKind::Lifetime(lt) => lt.fmt(f), GenericArgKind::Type(ty) => ty.fmt(f), GenericArgKind::Const(ct) => ct.fmt(f), } } } impl<'tcx> Ord for GenericArg<'tcx> { fn cmp(&self, other: &GenericArg<'_>) -> Ordering { self.unpack().cmp(&other.unpack()) } } impl<'tcx> PartialOrd for GenericArg<'tcx> { fn partial_cmp(&self, other: &GenericArg<'_>) -> Option<Ordering> { Some(self.cmp(&other)) } } impl<'tcx> From<ty::Region<'tcx>> for GenericArg<'tcx> { fn from(r: ty::Region<'tcx>) -> GenericArg<'tcx> { GenericArgKind::Lifetime(r).pack() } } impl<'tcx> From<Ty<'tcx>> for GenericArg<'tcx> { fn from(ty: Ty<'tcx>) -> GenericArg<'tcx> { GenericArgKind::Type(ty).pack() } } impl<'tcx> From<&'tcx ty::Const<'tcx>> for GenericArg<'tcx> { fn from(c: &'tcx ty::Const<'tcx>) -> GenericArg<'tcx> { GenericArgKind::Const(c).pack() } } impl<'tcx> GenericArg<'tcx> { #[inline] pub fn unpack(self) -> GenericArgKind<'tcx> { let ptr = self.ptr.get(); unsafe { match ptr & TAG_MASK { REGION_TAG => GenericArgKind::Lifetime(&*((ptr & !TAG_MASK) as *const _)), TYPE_TAG => GenericArgKind::Type(&*((ptr & !TAG_MASK) as *const _)), CONST_TAG => GenericArgKind::Const(&*((ptr & !TAG_MASK) as *const _)), _ => intrinsics::unreachable(), } } } /// Unpack the `GenericArg` as a type when it is known certainly to be a type. /// This is true in cases where `Substs` is used in places where the kinds are known /// to be limited (e.g. in tuples, where the only parameters are type parameters). pub fn expect_ty(self) -> Ty<'tcx> { match self.unpack() { GenericArgKind::Type(ty) => ty, _ => bug!("expected a type, but found another kind"), } } /// Unpack the `GenericArg` as a const when it is known certainly to be a const. pub fn expect_const(self) -> &'tcx ty::Const<'tcx> { match self.unpack() { GenericArgKind::Const(c) => c, _ => bug!("expected a const, but found another kind"), } } } impl<'a, 'tcx> Lift<'tcx> for GenericArg<'a> { type Lifted = GenericArg<'tcx>; fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> { match self.unpack() { GenericArgKind::Lifetime(lt) => tcx.lift(lt).map(|lt| lt.into()), GenericArgKind::Type(ty) => tcx.lift(ty).map(|ty| ty.into()), GenericArgKind::Const(ct) => tcx.lift(ct).map(|ct| ct.into()), } } } impl<'tcx> TypeFoldable<'tcx> for GenericArg<'tcx> { fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>( self, folder: &mut F, ) -> Result<Self, F::Error> { match self.unpack() { GenericArgKind::Lifetime(lt) => lt.try_fold_with(folder).map(Into::into), GenericArgKind::Type(ty) => ty.try_fold_with(folder).map(Into::into), GenericArgKind::Const(ct) => ct.try_fold_with(folder).map(Into::into), } } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> { match self.unpack() { GenericArgKind::Lifetime(lt) => lt.visit_with(visitor), GenericArgKind::Type(ty) => ty.visit_with(visitor), GenericArgKind::Const(ct) => ct.visit_with(visitor), } } } impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for GenericArg<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.unpack().encode(e) } } impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for GenericArg<'tcx> { fn decode(d: &mut D) -> Result<GenericArg<'tcx>, D::Error> { Ok(GenericArgKind::decode(d)?.pack()) } } /// A substitution mapping generic parameters to new values. pub type InternalSubsts<'tcx> = List<GenericArg<'tcx>>; pub type SubstsRef<'tcx> = &'tcx InternalSubsts<'tcx>; impl<'a, 'tcx> InternalSubsts<'tcx> { /// Interpret these substitutions as the substitutions of a closure type. /// Closure substitutions have a particular structure controlled by the /// compiler that encodes information like the signature and closure kind; /// see `ty::ClosureSubsts` struct for more comments. pub fn as_closure(&'a self) -> ClosureSubsts<'a> { ClosureSubsts { substs: self } } /// Interpret these substitutions as the substitutions of a generator type. /// Generator substitutions have a particular structure controlled by the /// compiler that encodes information like the signature and generator kind; /// see `ty::GeneratorSubsts` struct for more comments. pub fn as_generator(&'tcx self) -> GeneratorSubsts<'tcx> { GeneratorSubsts { substs: self } } /// Interpret these substitutions as the substitutions of an inline const. /// Inline const substitutions have a particular structure controlled by the /// compiler that encodes information like the inferred type; /// see `ty::InlineConstSubsts` struct for more comments. pub fn as_inline_const(&'tcx self) -> InlineConstSubsts<'tcx> { InlineConstSubsts { substs: self } } /// Creates an `InternalSubsts` that maps each generic parameter to itself. pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> SubstsRef<'tcx> { Self::for_item(tcx, def_id, |param, _| tcx.mk_param_from_def(param)) } /// Creates an `InternalSubsts` for generic parameter definitions, /// by calling closures to obtain each kind. /// The closures get to observe the `InternalSubsts` as they're /// being built, which can be used to correctly /// substitute defaults of generic parameters. pub fn for_item<F>(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx> where F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, { let defs = tcx.generics_of(def_id); let count = defs.count(); let mut substs = SmallVec::with_capacity(count); Self::fill_item(&mut substs, tcx, defs, &mut mk_kind); tcx.intern_substs(&substs) } pub fn extend_to<F>(&self, tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx> where F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, { Self::for_item(tcx, def_id, |param, substs| { self.get(param.index as usize).cloned().unwrap_or_else(|| mk_kind(param, substs)) }) } pub fn fill_item<F>( substs: &mut SmallVec<[GenericArg<'tcx>; 8]>, tcx: TyCtxt<'tcx>, defs: &ty::Generics, mk_kind: &mut F, ) where F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, { if let Some(def_id) = defs.parent { let parent_defs = tcx.generics_of(def_id); Self::fill_item(substs, tcx, parent_defs, mk_kind); } Self::fill_single(substs, defs, mk_kind) } pub fn fill_single<F>( substs: &mut SmallVec<[GenericArg<'tcx>; 8]>, defs: &ty::Generics, mk_kind: &mut F, ) where F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, { substs.reserve(defs.params.len()); for param in &defs.params { let kind = mk_kind(param, substs); assert_eq!(param.index as usize, substs.len()); substs.push(kind); } } pub fn is_noop(&self) -> bool { self.is_empty() } #[inline] pub fn types(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a { self.iter() .filter_map(|k| if let GenericArgKind::Type(ty) = k.unpack() { Some(ty) } else { None }) } #[inline] pub fn regions(&'a self) -> impl DoubleEndedIterator<Item = ty::Region<'tcx>> + 'a { self.iter().filter_map(|k| { if let GenericArgKind::Lifetime(lt) = k.unpack() { Some(lt) } else { None } }) } #[inline] pub fn consts(&'a self) -> impl DoubleEndedIterator<Item = &'tcx ty::Const<'tcx>> + 'a { self.iter().filter_map(|k| { if let GenericArgKind::Const(ct) = k.unpack() { Some(ct) } else { None } }) } #[inline] pub fn non_erasable_generics( &'a self, ) -> impl DoubleEndedIterator<Item = GenericArgKind<'tcx>> + 'a { self.iter().filter_map(|k| match k.unpack() { GenericArgKind::Lifetime(_) => None, generic => Some(generic), }) } #[inline] pub fn type_at(&self, i: usize) -> Ty<'tcx> { if let GenericArgKind::Type(ty) = self[i].unpack() { ty } else { bug!("expected type for param #{} in {:?}", i, self); } } #[inline] pub fn region_at(&self, i: usize) -> ty::Region<'tcx> { if let GenericArgKind::Lifetime(lt) = self[i].unpack() { lt } else { bug!("expected region for param #{} in {:?}", i, self); } } #[inline] pub fn const_at(&self, i: usize) -> &'tcx ty::Const<'tcx> { if let GenericArgKind::Const(ct) = self[i].unpack() { ct } else { bug!("expected const for param #{} in {:?}", i, self); } } #[inline] pub fn type_for_def(&self, def: &ty::GenericParamDef) -> GenericArg<'tcx> { self.type_at(def.index as usize).into() } /// Transform from substitutions for a child of `source_ancestor` /// (e.g., a trait or impl) to substitutions for the same child /// in a different item, with `target_substs` as the base for /// the target impl/trait, with the source child-specific /// parameters (e.g., method parameters) on top of that base. /// /// For example given: /// /// ```no_run /// trait X<S> { fn f<T>(); } /// impl<U> X<U> for U { fn f<V>() {} } /// ``` /// /// * If `self` is `[Self, S, T]`: the identity substs of `f` in the trait. /// * If `source_ancestor` is the def_id of the trait. /// * If `target_substs` is `[U]`, the substs for the impl. /// * Then we will return `[U, T]`, the subst for `f` in the impl that /// are needed for it to match the trait. pub fn rebase_onto( &self, tcx: TyCtxt<'tcx>, source_ancestor: DefId, target_substs: SubstsRef<'tcx>, ) -> SubstsRef<'tcx> { let defs = tcx.generics_of(source_ancestor); tcx.mk_substs(target_substs.iter().chain(self.iter().skip(defs.params.len()))) } pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> SubstsRef<'tcx> { tcx.mk_substs(self.iter().take(generics.count())) } } impl<'tcx> TypeFoldable<'tcx> for SubstsRef<'tcx> { fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>( self, folder: &mut F, ) -> Result<Self, F::Error> { // This code is hot enough that it's worth specializing for the most // common length lists, to avoid the overhead of `SmallVec` creation. // The match arms are in order of frequency. The 1, 2, and 0 cases are // typically hit in 90--99.99% of cases. When folding doesn't change // the substs, it's faster to reuse the existing substs rather than // calling `intern_substs`. match self.len() { 1 => { let param0 = self[0].try_fold_with(folder)?; if param0 == self[0] { Ok(self) } else { Ok(folder.tcx().intern_substs(&[param0])) } } 2 => { let param0 = self[0].try_fold_with(folder)?; let param1 = self[1].try_fold_with(folder)?; if param0 == self[0] && param1 == self[1] { Ok(self) } else { Ok(folder.tcx().intern_substs(&[param0, param1])) } } 0 => Ok(self), _ => { let params: SmallVec<[_; 8]> = self.iter().map(|k| k.try_fold_with(folder)).collect::<Result<_, _>>()?; if params[..] == self[..] { Ok(self) } else { Ok(folder.tcx().intern_substs(&params)) } } } } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> { self.iter().try_for_each(|t| t.visit_with(visitor)) } } /////////////////////////////////////////////////////////////////////////// // Public trait `Subst` // // Just call `foo.subst(tcx, substs)` to perform a substitution across // `foo`. Or use `foo.subst_spanned(tcx, substs, Some(span))` when // there is more information available (for better errors). pub trait Subst<'tcx>: Sized { fn subst(self, tcx: TyCtxt<'tcx>, substs: &[GenericArg<'tcx>]) -> Self { self.subst_spanned(tcx, substs, None) } fn subst_spanned( self, tcx: TyCtxt<'tcx>, substs: &[GenericArg<'tcx>], span: Option<Span>, ) -> Self; } impl<'tcx, T: TypeFoldable<'tcx>> Subst<'tcx> for T { fn subst_spanned( self, tcx: TyCtxt<'tcx>, substs: &[GenericArg<'tcx>], span: Option<Span>, ) -> T { let mut folder = SubstFolder { tcx, substs, span, binders_passed: 0 }; self.fold_with(&mut folder) } } /////////////////////////////////////////////////////////////////////////// // The actual substitution engine itself is a type folder. struct SubstFolder<'a, 'tcx> { tcx: TyCtxt<'tcx>, substs: &'a [GenericArg<'tcx>], /// The location for which the substitution is performed, if available. span: Option<Span>, /// Number of region binders we have passed through while doing the substitution binders_passed: u32, } impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> { fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { self.tcx } fn fold_binder<T: TypeFoldable<'tcx>>( &mut self, t: ty::Binder<'tcx, T>, ) -> ty::Binder<'tcx, T> { self.binders_passed += 1; let t = t.super_fold_with(self); self.binders_passed -= 1; t } fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { // Note: This routine only handles regions that are bound on // type declarations and other outer declarations, not those // bound in *fn types*. Region substitution of the bound // regions that appear in a function signature is done using // the specialized routine `ty::replace_late_regions()`. match *r { ty::ReEarlyBound(data) => { let rk = self.substs.get(data.index as usize).map(|k| k.unpack()); match rk { Some(GenericArgKind::Lifetime(lt)) => self.shift_region_through_binders(lt), _ => { let span = self.span.unwrap_or(DUMMY_SP); let msg = format!( "Region parameter out of range \ when substituting in region {} (index={})", data.name, data.index ); span_bug!(span, "{}", msg); } } } _ => r, } } fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { if !t.needs_subst() { return t; } match *t.kind() { ty::Param(p) => self.ty_for_param(p, t), _ => t.super_fold_with(self), } } fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { if let ty::ConstKind::Param(p) = c.val { self.const_for_param(p, c) } else { c.super_fold_with(self) } } #[inline] fn fold_mir_const(&mut self, c: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx> { c.super_fold_with(self) } } impl<'a, 'tcx> SubstFolder<'a, 'tcx> { fn ty_for_param(&self, p: ty::ParamTy, source_ty: Ty<'tcx>) -> Ty<'tcx> { // Look up the type in the substitutions. It really should be in there. let opt_ty = self.substs.get(p.index as usize).map(|k| k.unpack()); let ty = match opt_ty { Some(GenericArgKind::Type(ty)) => ty, Some(kind) => { let span = self.span.unwrap_or(DUMMY_SP); span_bug!( span, "expected type for `{:?}` ({:?}/{}) but found {:?} \ when substituting, substs={:?}", p, source_ty, p.index, kind, self.substs, ); } None => { let span = self.span.unwrap_or(DUMMY_SP); span_bug!( span, "type parameter `{:?}` ({:?}/{}) out of range \ when substituting, substs={:?}", p, source_ty, p.index, self.substs, ); } }; self.shift_vars_through_binders(ty) } fn const_for_param( &self, p: ParamConst, source_ct: &'tcx ty::Const<'tcx>, ) -> &'tcx ty::Const<'tcx> { // Look up the const in the substitutions. It really should be in there. let opt_ct = self.substs.get(p.index as usize).map(|k| k.unpack()); let ct = match opt_ct { Some(GenericArgKind::Const(ct)) => ct, Some(kind) => { let span = self.span.unwrap_or(DUMMY_SP); span_bug!( span, "expected const for `{:?}` ({:?}/{}) but found {:?} \ when substituting substs={:?}", p, source_ct, p.index, kind, self.substs, ); } None => { let span = self.span.unwrap_or(DUMMY_SP); span_bug!( span, "const parameter `{:?}` ({:?}/{}) out of range \ when substituting substs={:?}", p, source_ct, p.index, self.substs, ); } }; self.shift_vars_through_binders(ct) } /// It is sometimes necessary to adjust the De Bruijn indices during substitution. This occurs /// when we are substituting a type with escaping bound vars into a context where we have /// passed through binders. That's quite a mouthful. Let's see an example: /// /// ``` /// type Func<A> = fn(A); /// type MetaFunc = for<'a> fn(Func<&'a i32>) /// ``` /// /// The type `MetaFunc`, when fully expanded, will be /// /// for<'a> fn(fn(&'a i32)) /// ^~ ^~ ^~~ /// | | | /// | | DebruijnIndex of 2 /// Binders /// /// Here the `'a` lifetime is bound in the outer function, but appears as an argument of the /// inner one. Therefore, that appearance will have a DebruijnIndex of 2, because we must skip /// over the inner binder (remember that we count De Bruijn indices from 1). However, in the /// definition of `MetaFunc`, the binder is not visible, so the type `&'a i32` will have a /// De Bruijn index of 1. It's only during the substitution that we can see we must increase the /// depth by 1 to account for the binder that we passed through. /// /// As a second example, consider this twist: /// /// ``` /// type FuncTuple<A> = (A,fn(A)); /// type MetaFuncTuple = for<'a> fn(FuncTuple<&'a i32>) /// ``` /// /// Here the final type will be: /// /// for<'a> fn((&'a i32, fn(&'a i32))) /// ^~~ ^~~ /// | | /// DebruijnIndex of 1 | /// DebruijnIndex of 2 /// /// As indicated in the diagram, here the same type `&'a i32` is substituted once, but in the /// first case we do not increase the De Bruijn index and in the second case we do. The reason /// is that only in the second case have we passed through a fn binder. fn shift_vars_through_binders<T: TypeFoldable<'tcx>>(&self, val: T) -> T { debug!( "shift_vars(val={:?}, binders_passed={:?}, has_escaping_bound_vars={:?})", val, self.binders_passed, val.has_escaping_bound_vars() ); if self.binders_passed == 0 || !val.has_escaping_bound_vars() { return val; } let result = ty::fold::shift_vars(self.tcx(), val, self.binders_passed); debug!("shift_vars: shifted result = {:?}", result); result } fn shift_region_through_binders(&self, region: ty::Region<'tcx>) -> ty::Region<'tcx> { if self.binders_passed == 0 || !region.has_escaping_bound_vars() { return region; } ty::fold::shift_region(self.tcx, region, self.binders_passed) } } /// Stores the user-given substs to reach some fully qualified path /// (e.g., `<T>::Item` or `<T as Trait>::Item`). #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] #[derive(HashStable, TypeFoldable, Lift)] pub struct UserSubsts<'tcx> { /// The substitutions for the item as given by the user. pub substs: SubstsRef<'tcx>, /// The self type, in the case of a `<T>::Item` path (when applied /// to an inherent impl). See `UserSelfTy` below. pub user_self_ty: Option<UserSelfTy<'tcx>>, } /// Specifies the user-given self type. In the case of a path that /// refers to a member in an inherent impl, this self type is /// sometimes needed to constrain the type parameters on the impl. For /// example, in this code: /// /// ``` /// struct Foo<T> { } /// impl<A> Foo<A> { fn method() { } } /// ``` /// /// when you then have a path like `<Foo<&'static u32>>::method`, /// this struct would carry the `DefId` of the impl along with the /// self type `Foo<u32>`. Then we can instantiate the parameters of /// the impl (with the substs from `UserSubsts`) and apply those to /// the self type, giving `Foo<?A>`. Finally, we unify that with /// the self type here, which contains `?A` to be `&'static u32` #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] #[derive(HashStable, TypeFoldable, Lift)] pub struct UserSelfTy<'tcx> { pub impl_def_id: DefId, pub self_ty: Ty<'tcx>, }
35.738028
100
0.550445
5d0ce43efd380addbdb636379d8808edf282e37b
2,523
use crate::error::*; use crate::*; pub struct Pkg; impl<V, I> Installer<V, Pkg, I> { pub fn cleanup<D: AsRef<Path>>(&self, tmp_destination: D) -> Result<()> { let tmp_destination = tmp_destination.as_ref(); debug!("cleanup {}", &tmp_destination.display()); fs::remove_dir_all(tmp_destination).chain_err(|| "failed to cleanup pkg") } pub fn find_payload<P>(&self, dir: P) -> Result<PathBuf> where P: AsRef<Path>, { let dir = dir.as_ref(); debug!("find paylod in unpacked installer {}", dir.display()); let mut files = fs::read_dir(dir) .and_then(|read_dir| Ok(read_dir.filter_map(io::Result::ok))) .map_err(|_err| { io::Error::new( io::ErrorKind::Other, format!( "can't iterate files in extracted payload {}", &dir.display() ), ) })?; files .find(|entry| { if let Some(file_name) = entry.file_name().to_str() { file_name.ends_with(".pkg.tmp") || file_name == "Payload~" } else { false } }) .ok_or_else(|| { io::Error::new( io::ErrorKind::Other, format!( "can't locate *.pkg.tmp directory or Payload~ in extracted installer at {}", &dir.display() ), ) }) .map(|entry| entry.path()) .and_then(|path| match path.file_name() { Some(name) if name == "Payload~" => Ok(path), _ => { let payload_path = path.join("Payload"); if payload_path.exists() { Ok(payload_path) } else { Err(io::Error::new( io::ErrorKind::Other, format!( "can't locate Payload directory in extracted installer at {}", &dir.display() ), )) } } }) .map(|path| { debug!("Found payload {}", path.display()); path }) .chain_err(|| "failed to find payload in pkg") } }
35.041667
100
0.403884
7286f6abb925d5245df1e4c81eaa3a310cc23a06
3,832
//! Use a floating button to overlay a button over some content //! //! *This API requires the following crate features to be activated: floating_button* use iced_web::{Bus, Button, Css, Element, Widget}; use dodrio::bumpalo; pub use crate::style::button::*; pub mod anchor; pub use anchor::Anchor; pub mod offset; pub use offset::Offset; /// A floating button floating over some content. /// /// TODO: Example #[allow(missing_debug_implementations)] pub struct FloatingButton<'a, Message> { anchor: Anchor, offset: Offset, hidden: bool, on_press: Option<Message>, underlay: Element<'a, Message>, button: Button<'a, Message>, } impl<'a, Message> FloatingButton<'a, Message> where Message: Clone, { /// Creates a new [`FloatingButton`](FloatingButton) over some content, /// showing the given [`Button`](iced_native::button::Button). pub fn new<U, B>(underlay: U, button: B) -> Self where U: Into<Element<'a, Message>>, B: Into<Button<'a, Message>>, { FloatingButton { anchor: Anchor::SouthEast, offset: 5.0.into(), hidden: false, on_press: None, underlay: underlay.into(), button: button.into(), } } /// Sets the [`Anchor`](Anchor) of the [`FloatingButton`](FloatingButton). pub fn anchor(mut self, anchor: Anchor) -> Self { self.anchor = anchor; self } /// Sets the [`Offset`](Offset) of the [`FloatingButton`](FloatingButton). pub fn offset<O>(mut self, offset: O) -> Self where O: Into<Offset>, { self.offset = offset.into(); self } /// Hide or unhide the [`Button`](iced_native::button::Button) on the /// [`FloatingButton`](FloatingButton). pub fn hide(mut self, hide: bool) -> Self { self.hidden = hide; self } /// Sets the `on_press` message for the [`Button`]. /// /// This is currently only a workaround. pub fn on_press(mut self, msg: Message) -> Self { self.on_press = Some(msg.clone()); self.button = self.button.on_press(msg); self } } impl<'a, Message> Widget<Message> for FloatingButton<'a, Message> where Message: 'static + Clone, { fn node<'b>( &self, bump: &'b bumpalo::Bump, bus: &Bus<Message>, style_sheet: &mut Css<'b>, ) -> dodrio::Node<'b> { use dodrio::builder::*; let position = match self.anchor { Anchor::NorthWest => format!("top: {}px; left: {}px;", self.offset.y, self.offset.x), Anchor::NorthEast => format!("top: {}px; right: {}px;", self.offset.y, self.offset.x), Anchor::SouthWest => format!("bottom: {}px; left: {}px;", self.offset.y, self.offset.x), Anchor::SouthEast => format!("bottom: {}px; right: {}px;", self.offset.y, self.offset.x), }; let node = div(bump) .attr("style", "position: relative; width: 100%; height: 100%;") .children(vec![ self.underlay.node(bump, bus, style_sheet), div(bump) .attr( "style", bumpalo::format!( in bump, "position: absolute; {}", position ).into_bump_str(), ) .children(vec![self.button.node(bump, bus, style_sheet)]) .finish(), ]); node.finish() } } impl<'a, Message> From<FloatingButton<'a, Message>> for Element<'a, Message> where Message: 'static + Clone, { fn from(floating_button: FloatingButton<'a, Message>) -> Element<'a, Message> { Element::new(floating_button) } }
29.705426
101
0.548539
67bf2b752d35843c5503e49f1eb617ae523ea8e6
3,342
//! The raw quick read-write cell. use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering as AtomicOrdering; use std::sync::Arc; use std::sync::Weak; use parking_lot::Mutex; use parking_lot::Once; use parking_lot::OnceState; use parking_lot::RwLock; /// Raw quick read-write cell. pub(crate) struct RawQrwCell<T> { inner: [RwLock<Option<Arc<T>>>; 2], selector: AtomicUsize, update_lock: Mutex<()>, init: Once, } impl<T: Default> Default for RawQrwCell<T> { fn default() -> Self { let init = Once::new(); init.call_once(|| ()); Self { inner: [RwLock::new(Some(Arc::new(T::default()))), RwLock::new(None)], selector: AtomicUsize::new(0), update_lock: Mutex::new(()), init, } } } impl<T> RawQrwCell<T> { /// Create a new, empty RawQrwCell. pub(crate) const fn new() -> Self { Self { inner: [ parking_lot::const_rwlock(None), parking_lot::const_rwlock(None), ], selector: AtomicUsize::new(0), update_lock: parking_lot::const_mutex(()), init: Once::new(), } } /// Create a new RawQrwCell with a value. pub(crate) fn with_value(value: T) -> Self { let init = Once::new(); init.call_once(|| ()); Self { inner: [RwLock::new(Some(Arc::new(value))), RwLock::new(None)], selector: AtomicUsize::new(0), update_lock: Mutex::new(()), init, } } /// Get the current value of the cell. pub(crate) fn get(&self) -> Arc<T> { if self.init.state() != OnceState::Done { panic!("Attempted to read from a qrwcell that has not been initialized!"); } loop { let selector = self.get_selector(); let guard = self.inner[selector].read(); if let Some(value) = guard.as_ref() { break Arc::clone(value); } } } /// Get the current value of the cell (as a weak pointer). pub(crate) fn get_weak(&self) -> Weak<T> { if self.init.state() != OnceState::Done { panic!("Attempted to read from a qrwcell that has not been initialized!"); } loop { let selector = self.get_selector(); let guard = self.inner[selector].read(); if let Some(value) = guard.as_ref() { break Arc::downgrade(value); } } } /// Update the cell, returning the old value. pub(crate) fn update(&self, new: T) -> Arc<T> { self.init.call_once(|| ()); let _update_lock = self.update_lock.lock(); let new_arc = Arc::new(new); let selector = self.get_selector() ^ 1; { let mut cell = self.inner[selector].write(); *cell = Some(Arc::clone(&new_arc)); } let selector = self.switch_selector(); { let mut cell = self.inner[selector].write(); cell.take().unwrap_or(new_arc) } } #[inline] fn get_selector(&self) -> usize { self.selector.load(AtomicOrdering::Acquire) } #[inline] fn switch_selector(&self) -> usize { self.selector.fetch_xor(1, AtomicOrdering::Release) } }
29.06087
86
0.534411
710484aca0004a23789b412e7a66a85efcad29e2
892
use std::fmt; use cosmwasm_std::{Binary, Deps, DepsMut, Env, MessageInfo, Response, StdError}; use schemars::JsonSchema; use crate::{test_helpers::EmptyMsg, Contract, ContractWrapper}; fn instantiate( _deps: DepsMut, _env: Env, _info: MessageInfo, _msg: EmptyMsg, ) -> Result<Response, StdError> { Err(StdError::generic_err("Init failed")) } fn execute( _deps: DepsMut, _env: Env, _info: MessageInfo, _msg: EmptyMsg, ) -> Result<Response, StdError> { Err(StdError::generic_err("Handle failed")) } fn query(_deps: Deps, _env: Env, _msg: EmptyMsg) -> Result<Binary, StdError> { Err(StdError::generic_err("Query failed")) } pub fn contract<C>() -> Box<dyn Contract<C>> where C: Clone + fmt::Debug + PartialEq + JsonSchema + 'static, { let contract = ContractWrapper::new_with_empty(execute, instantiate, query); Box::new(contract) }
24.108108
80
0.680493
ffd70def1ca2547e620594097fb5a51344d45d11
1,005
use std::sync::Mutex; lazy_static! { pub static ref DIVES: Mutex<DiveStats> = Mutex::new(DiveStats{total: 0, duplicates: 0}); } pub struct DiveStats { total: usize, duplicates: usize, } impl DiveStats { pub fn record(&mut self, total: usize, duplicates: usize) { let new = DiveStats{total, duplicates}; info!("{:?}", new); self.merge(&new); } fn merge(&mut self, other: &Self) { self.total += other.total; self.duplicates += other.duplicates; } pub fn clear(&mut self) { self.total = 0; self.duplicates = 0; } } use std::fmt; impl fmt::Debug for DiveStats { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "DiveStats {{ total: {}, duplicates={}, dupe_rate={:.2} }}", self.total, self.duplicates, (self.duplicates as f64) / (self.total as f64) ) } } // misfit functions impl DiveStats { // exists for dumb type coercion reasons pub fn format(&self) -> String { format!("{:?}", self) } }
19.326923
90
0.602985
e52d60ecbe0044143786c7f73b45373497caf8dc
1,364
use std::collections::HashMap; use std::env; use std::fs; use std::sync::mpsc::channel; use std::thread; fn parse_file_to_vec(file_path: String) -> HashMap<usize, i64> { let content = fs::read_to_string(file_path).unwrap(); let tokens: Vec<&str> = content.split(',').collect(); let mut ret: HashMap<usize, i64> = HashMap::new(); for elem in tokens.iter().enumerate() { ret.insert(elem.0, elem.1.trim().parse::<i64>().unwrap()); } ret } fn main() { let vec_str: Vec<String> = env::args().collect(); let (file_path, input_val) = match vec_str.len() { 0..=2 => { panic!("Not enough args"); } 3 => ( vec_str.get(1).unwrap(), (*vec_str.get(2).unwrap()).trim().parse::<i64>().unwrap(), ), _ => { panic!("Too many args"); } }; let mut mem_original = parse_file_to_vec(file_path.to_string()); let (tx_from_main, rx_from_main) = channel(); let (tx_from_machine, rx_from_machine) = channel(); tx_from_main.send(input_val).expect("Error at sending"); thread::spawn(move || { let mut machine = intcode::Machine::new(&mut mem_original, rx_from_main, tx_from_machine); machine.run(); }); let val = rx_from_machine.recv().expect("Error from machine"); println!("Value: {:?}", val); }
29.021277
98
0.583578
62c264ca421eeb0661a9403ad7739c0ae9f267b5
7,475
// Copyright © 2015-2017 winapi-rs developers // 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. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms //! this ALWAYS GENERATED file contains the definitions for the interfaces use ctypes::c_float; use shared::basetsd::{UINT32, UINT64}; use shared::guiddef::{LPCGUID, REFIID}; use shared::minwindef::{BYTE, DWORD, LPVOID}; use shared::mmreg::WAVEFORMATEX; use shared::winerror::{FACILITY_AUDCLNT, SEVERITY_ERROR, SEVERITY_SUCCESS}; use shared::wtypesbase::SCODE; use um::audiosessiontypes::AUDCLNT_SHAREMODE; use um::strmif::REFERENCE_TIME; use um::unknwnbase::{IUnknown, IUnknownVtbl}; use um::winnt::{HANDLE, HRESULT}; //1627 pub const AUDCLNT_E_NOT_INITIALIZED: HRESULT = AUDCLNT_ERR!(0x001); pub const AUDCLNT_E_ALREADY_INITIALIZED: HRESULT = AUDCLNT_ERR!(0x002); pub const AUDCLNT_E_WRONG_ENDPOINT_TYPE: HRESULT = AUDCLNT_ERR!(0x003); pub const AUDCLNT_E_DEVICE_INVALIDATED: HRESULT = AUDCLNT_ERR!(0x004); pub const AUDCLNT_E_NOT_STOPPED: HRESULT = AUDCLNT_ERR!(0x005); pub const AUDCLNT_E_BUFFER_TOO_LARGE: HRESULT = AUDCLNT_ERR!(0x006); pub const AUDCLNT_E_OUT_OF_ORDER: HRESULT = AUDCLNT_ERR!(0x007); pub const AUDCLNT_E_UNSUPPORTED_FORMAT: HRESULT = AUDCLNT_ERR!(0x008); pub const AUDCLNT_E_INVALID_SIZE: HRESULT = AUDCLNT_ERR!(0x009); pub const AUDCLNT_E_DEVICE_IN_USE: HRESULT = AUDCLNT_ERR!(0x00a); pub const AUDCLNT_E_BUFFER_OPERATION_PENDING: HRESULT = AUDCLNT_ERR!(0x00b); pub const AUDCLNT_E_THREAD_NOT_REGISTERED: HRESULT = AUDCLNT_ERR!(0x00c); pub const AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: HRESULT = AUDCLNT_ERR!(0x00e); pub const AUDCLNT_E_ENDPOINT_CREATE_FAILED: HRESULT = AUDCLNT_ERR!(0x00f); pub const AUDCLNT_E_SERVICE_NOT_RUNNING: HRESULT = AUDCLNT_ERR!(0x010); pub const AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: HRESULT = AUDCLNT_ERR!(0x011); pub const AUDCLNT_E_EXCLUSIVE_MODE_ONLY: HRESULT = AUDCLNT_ERR!(0x012); pub const AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: HRESULT = AUDCLNT_ERR!(0x013); pub const AUDCLNT_E_EVENTHANDLE_NOT_SET: HRESULT = AUDCLNT_ERR!(0x014); pub const AUDCLNT_E_INCORRECT_BUFFER_SIZE: HRESULT = AUDCLNT_ERR!(0x015); pub const AUDCLNT_E_BUFFER_SIZE_ERROR: HRESULT = AUDCLNT_ERR!(0x016); pub const AUDCLNT_E_CPUUSAGE_EXCEEDED: HRESULT = AUDCLNT_ERR!(0x017); pub const AUDCLNT_E_BUFFER_ERROR: HRESULT = AUDCLNT_ERR!(0x018); pub const AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED: HRESULT = AUDCLNT_ERR!(0x019); pub const AUDCLNT_E_INVALID_DEVICE_PERIOD: HRESULT = AUDCLNT_ERR!(0x020); pub const AUDCLNT_E_INVALID_STREAM_FLAG: HRESULT = AUDCLNT_ERR!(0x021); pub const AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE: HRESULT = AUDCLNT_ERR!(0x022); pub const AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES: HRESULT = AUDCLNT_ERR!(0x023); pub const AUDCLNT_E_OFFLOAD_MODE_ONLY: HRESULT = AUDCLNT_ERR!(0x024); pub const AUDCLNT_E_NONOFFLOAD_MODE_ONLY: HRESULT = AUDCLNT_ERR!(0x025); pub const AUDCLNT_E_RESOURCES_INVALIDATED: HRESULT = AUDCLNT_ERR!(0x026); pub const AUDCLNT_E_RAW_MODE_UNSUPPORTED: HRESULT = AUDCLNT_ERR!(0x027); pub const AUDCLNT_S_BUFFER_EMPTY: SCODE = AUDCLNT_SUCCESS!(0x001); pub const AUDCLNT_S_THREAD_ALREADY_REGISTERED: SCODE = AUDCLNT_SUCCESS!(0x002); pub const AUDCLNT_S_POSITION_STALLED: SCODE = AUDCLNT_SUCCESS!(0x003); ENUM!{enum AUDCLNT_BUFFERFLAGS { AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY = 0x1, AUDCLNT_BUFFERFLAGS_SILENT = 0x2, AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR = 0x4, }} DEFINE_GUID!{IID_IAudioClient, 0x1CB9AD4C, 0xDBFA, 0x4c32, 0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2} DEFINE_GUID!{IID_IAudioRenderClient, 0xF294ACFC, 0x3146, 0x4483, 0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2} DEFINE_GUID!{IID_IAudioCaptureClient, 0xc8adbd64, 0xe71e, 0x48a0, 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17} DEFINE_GUID!{IID_IAudioClock, 0xcd63314f, 0x3fba, 0x4a1b, 0x81, 0x2c, 0xef, 0x96, 0x35, 0x87, 0x28, 0xe7} DEFINE_GUID!{IID_IAudioStreamVolume, 0x93014887, 0x242d, 0x4068, 0x8a, 0x15, 0xcf, 0x5e, 0x93, 0xb9, 0x0f, 0xe3} RIDL!{#[uuid(0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2)] interface IAudioClient(IAudioClientVtbl): IUnknown(IUnknownVtbl) { fn Initialize( ShareMode: AUDCLNT_SHAREMODE, StreamFlags: DWORD, hnsBufferDuration: REFERENCE_TIME, hnsPeriodicity: REFERENCE_TIME, pFormat: *const WAVEFORMATEX, AudioSessionGuid: LPCGUID, ) -> HRESULT, fn GetBufferSize( pNumBufferFrames: *mut UINT32, ) -> HRESULT, fn GetStreamLatency( phnsLatency: *mut REFERENCE_TIME, ) -> HRESULT, fn GetCurrentPadding( pNumPaddingFrames: *mut UINT32, ) -> HRESULT, fn IsFormatSupported( ShareMode: AUDCLNT_SHAREMODE, pFormat: *const WAVEFORMATEX, ppClosestMatch: *mut *mut WAVEFORMATEX, ) -> HRESULT, fn GetMixFormat( ppDeviceFormat: *mut *mut WAVEFORMATEX, ) -> HRESULT, fn GetDevicePeriod( phnsDefaultDevicePeriod: *mut REFERENCE_TIME, phnsMinimumDevicePeriod: *mut REFERENCE_TIME, ) -> HRESULT, fn Start() -> HRESULT, fn Stop() -> HRESULT, fn Reset() -> HRESULT, fn SetEventHandle( eventHandle: HANDLE, ) -> HRESULT, fn GetService( riid: REFIID, ppv: *mut LPVOID, ) -> HRESULT, }} RIDL!{#[uuid(0xf294acfc, 0x3146, 0x4483, 0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2)] interface IAudioRenderClient(IAudioRenderClientVtbl): IUnknown(IUnknownVtbl) { fn GetBuffer( NumFramesRequested: UINT32, ppData: *mut *mut BYTE, ) -> HRESULT, fn ReleaseBuffer( NumFramesWritten: UINT32, dwFlags: DWORD, ) -> HRESULT, }} RIDL!{#[uuid(0xc8adbd64, 0xe71e, 0x48a0, 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17)] interface IAudioCaptureClient(IAudioCaptureClientVtbl): IUnknown(IUnknownVtbl) { fn GetBuffer( ppData: *mut *mut BYTE, pNumFramesToRead: *mut UINT32, pdwFlags: *mut DWORD, pu64DevicePosition: *mut UINT64, pu64QPCPosition: *mut UINT64, ) -> HRESULT, fn ReleaseBuffer( NumFramesRead: UINT32, ) -> HRESULT, fn GetNextPacketSize( pNumFramesInNextPacket: *mut UINT32, ) -> HRESULT, }} RIDL!{#[uuid(0xcd63314f, 0x3fba, 0x4a1b, 0x81, 0x2c, 0xef, 0x96, 0x35, 0x87, 0x28, 0xe7)] interface IAudioClock(IAudioClockVtbl): IUnknown(IUnknownVtbl) { fn GetFrequency( pu64Frequency: *mut UINT64, ) -> HRESULT, fn GetPosition( pu64Position: *mut UINT64, pu64QPCPosition: *mut UINT64, ) -> HRESULT, fn GetCharacteristics( pdwCharacteristics: *mut DWORD, ) -> HRESULT, }} RIDL!{#[uuid(0x93014887, 0x242d, 0x4068, 0x8a, 0x15, 0xcf, 0x5e, 0x93, 0xb9, 0x0f, 0xe3)] interface IAudioStreamVolume(IAudioStreamVolumeVtbl): IUnknown(IUnknownVtbl) { fn GetChannelCount( pdwCount: *mut UINT32, ) -> HRESULT, fn SetChannelVolume( dwIndex: UINT32, fLevel: c_float, ) -> HRESULT, fn GetChannelVolume( dwIndex: UINT32, pfLevel: *mut c_float, ) -> HRESULT, fn SetAllVolumes( dwCount: UINT32, pfVolumes: *const c_float, ) -> HRESULT, fn GetAllVolumes( dwCount: UINT32, pfVolumes: *mut c_float, ) -> HRESULT, }}
42.95977
92
0.729632
8f22649f76e96f2522ef542522543e8fcc370c33
17,249
use self::lca::least_common_ancestor; use crate::{ bundler::{load::TransformedModule, scope::Metadata}, BundleKind, Bundler, Load, ModuleId, Resolve, }; use anyhow::{bail, Error}; use petgraph::{ algo::all_simple_paths, graphmap::DiGraphMap, visit::Bfs, EdgeDirection::{Incoming, Outgoing}, }; use std::{ collections::{hash_map::Entry, HashMap, HashSet}, ops::{Deref, DerefMut}, }; mod lca; #[cfg(test)] mod tests; #[derive(Debug, Default)] struct PlanBuilder { /// A hashmap to check if a module import is circular. /// /// This contains all dependencies, including transitive ones. For example, /// if `a` dependes on `b` and `b` depdends on `c`, all of /// `(a, b)`, `(a, c)`,`(b, c)` will be inserted. all_deps: HashSet<(ModuleId, ModuleId)>, /// Graph to compute direct dependencies (direct means it will be merged /// directly) direct_deps: ModuleGraph, circular: Circulars, kinds: HashMap<ModuleId, BundleKind>, } #[derive(Debug, Default)] struct Circulars(Vec<HashSet<ModuleId>>); impl Circulars { pub fn get(&self, id: ModuleId) -> Option<&HashSet<ModuleId>> { let pos = self.0.iter().position(|set| set.contains(&id))?; Some(&self.0[pos]) } // pub fn remove(&mut self, id: ModuleId) -> Option<HashSet<ModuleId>> { // let pos = self.0.iter().position(|set| set.contains(&id))?; // Some(self.0.remove(pos)) // } } impl Deref for Circulars { type Target = Vec<HashSet<ModuleId>>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for Circulars { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl PlanBuilder { fn mark_as_circular(&mut self, src: ModuleId, imported: ModuleId) { for set in self.circular.iter_mut() { if set.contains(&src) || set.contains(&imported) { set.insert(src); set.insert(imported); return; } } let mut set = HashSet::default(); set.insert(src); set.insert(imported); self.circular.push(set); } fn is_circular(&self, id: ModuleId) -> bool { for set in self.circular.iter() { if set.contains(&id) { return true; } } false } } #[derive(Debug, Default)] pub(super) struct Plan { pub entries: Vec<ModuleId>, /// key is entry pub normal: HashMap<ModuleId, NormalPlan>, /// key is entry pub circular: HashMap<ModuleId, CircularPlan>, pub bundle_kinds: HashMap<ModuleId, BundleKind>, } impl Plan { pub fn entry_as_circular(&self, entry: ModuleId) -> Option<&CircularPlan> { self.circular.get(&entry) } } #[derive(Debug, Default)] pub(super) struct NormalPlan { /// Direct dependencies pub chunks: Vec<ModuleId>, /// Used to handle /// /// - a -> b /// - a -> c /// - b -> d /// - c -> d pub transitive_chunks: Vec<ModuleId>, } #[derive(Debug, Default)] pub(super) struct CircularPlan { /// Members of the circular dependncies. pub chunks: Vec<ModuleId>, } pub(super) type ModuleGraph = DiGraphMap<ModuleId, usize>; impl<L, R> Bundler<'_, L, R> where L: Load, R: Resolve, { pub(super) fn determine_entries( &self, entries: HashMap<String, TransformedModule>, ) -> Result<Plan, Error> { let plan = self.calculate_plan(entries)?; let plan = self.handle_duplicates(plan); Ok(plan) } /// 1. For entry -> a -> b -> a, entry -> a->c, entry -> b -> c, /// we change c as transitive dependancy of entry. fn handle_duplicates(&self, plan: Plan) -> Plan { plan } fn calculate_plan(&self, entries: HashMap<String, TransformedModule>) -> Result<Plan, Error> { let mut builder = PlanBuilder::default(); for (name, module) in entries { match builder.kinds.insert(module.id, BundleKind::Named { name }) { Some(v) => bail!("Multiple entries with same input path detected: {:?}", v), None => {} } self.add_to_graph(&mut builder, module.id, &mut vec![]); } let mut metadata = HashMap::<ModuleId, Metadata>::default(); // Draw dependency graph to calculte for (id, _) in &builder.kinds { let mut bfs = Bfs::new(&builder.direct_deps, *id); while let Some(dep) = bfs.next(&builder.direct_deps) { if dep == *id { // Useless continue; } metadata.entry(dep).or_default().bundle_cnt += 1; } } // Promote modules to entry. for (id, md) in &metadata { if md.bundle_cnt > 1 { // TODO: Dynamic import let module = self.scope.get_module(*id).unwrap(); match builder.kinds.insert( *id, BundleKind::Lib { name: module.fm.name.to_string(), }, ) { Some(v) => { bail!("An entry cannot be imported: {:?}", v); } None => {} } } } Ok(self.build_plan(&metadata, builder)) } fn build_plan(&self, metadata: &HashMap<ModuleId, Metadata>, builder: PlanBuilder) -> Plan { let mut plans = Plan::default(); for (id, kind) in builder.kinds.iter() { plans.entries.push(*id); plans.bundle_kinds.insert(*id, kind.clone()); } // Convert graph to plan for (root_entry, _) in &builder.kinds { let root_entry = *root_entry; let mut bfs = Bfs::new(&builder.direct_deps, root_entry); while let Some(entry) = bfs.next(&builder.direct_deps) { let deps: Vec<_> = builder .direct_deps .neighbors_directed(entry, Outgoing) .collect(); for &dep in &deps { if let Some(circular_members) = builder.circular.get(entry) { if circular_members.contains(&dep) { log::debug!( "Adding a circular dependency {:?} to normal entry {:?}", dep, entry ); if entry != root_entry && dep != root_entry { plans.normal.entry(entry).or_default().chunks.push(dep); } continue; } } let is_es6 = self.scope.get_module(entry).unwrap().is_es6; let dependants = builder .direct_deps .neighbors_directed(dep, Incoming) .collect::<Vec<_>>(); if metadata.get(&dep).map(|md| md.bundle_cnt).unwrap_or(0) == 1 { log::debug!("{:?} depends on {:?}", entry, dep); // Common js support. if !is_es6 { // Dependancy of // // a -> b // b -> c // // results in // // a <- b // b <- c // if dependants.len() <= 1 { plans.normal.entry(entry).or_default().chunks.push(dep); continue; } // We now have a module depended by multiple modules. Let's say // // a -> b // a -> c // b -> c // // results in // // a <- b // a <- c let module = least_common_ancestor(&builder.direct_deps, &dependants); let normal_plan = plans.normal.entry(module).or_default(); for &dep in &deps { if !normal_plan.chunks.contains(&dep) && !normal_plan.transitive_chunks.contains(&dep) { if dependants.contains(&module) { log::trace!("Normal: {:?} => {:?}", module, dep); // `entry` depends on `module` directly normal_plan.chunks.push(dep); } else { log::trace!("Transitive: {:?} => {:?}", module, dep); normal_plan.transitive_chunks.push(dep); } } } continue; } if 2 <= dependants.len() { // Should be merged as a transitive dependency. let higher_module = if plans.entries.contains(&dependants[0]) { dependants[0] } else if dependants.len() == 2 && plans.entries.contains(&dependants[1]) { dependants[1] } else { least_common_ancestor(&builder.direct_deps, &dependants) }; if dependants.len() == 2 && dependants.contains(&higher_module) { let mut entry = *dependants.iter().find(|&&v| v != higher_module).unwrap(); // We choose higher node if import is circular if builder.is_circular(entry) { entry = higher_module; } let normal_plan = plans.normal.entry(entry).or_default(); if !normal_plan.chunks.contains(&dep) { log::trace!("Normal: {:?} => {:?}", entry, dep); normal_plan.chunks.push(dep); } } else { let t = &mut plans .normal .entry(higher_module) .or_default() .transitive_chunks; if !t.contains(&dep) { log::trace!("Transitive: {:?} => {:?}", entry, dep); t.push(dep) } } } else { // Direct dependency. log::trace!("Normal: {:?} => {:?}", entry, dep); plans.normal.entry(entry).or_default().chunks.push(dep); } continue; } } } } // Handle circular imports for (root_entry, _) in builder.kinds.iter() { let mut bfs = Bfs::new(&builder.direct_deps, *root_entry); while let Some(entry) = bfs.next(&builder.direct_deps) { let deps: Vec<_> = builder .direct_deps .neighbors_directed(entry, Outgoing) .collect(); for dep in deps { // Check if it's circular. if let Some(members) = builder.circular.get(dep) { // Exclude circular imnports from normal dependencies for &circular_member in members { if entry == circular_member { continue; } // Remove direct deps if it's circular if builder.direct_deps.contains_edge(dep, circular_member) { log::debug!( "[circular] Removing {:?} => {:?}", dep, circular_member ); { let c = &mut plans.normal.entry(dep).or_default().chunks; if let Some(pos) = c.iter().position(|&v| v == circular_member) { c.remove(pos); } } { let c = &mut plans .normal .entry(circular_member) .or_default() .chunks; if let Some(pos) = c.iter().position(|&v| v == dep) { c.remove(pos); } } } } // Add circular plans match plans.circular.entry(dep) { // Already added Entry::Occupied(_) => { // TODO: assert! } // We need to mark modules as circular. Entry::Vacant(e) => { let circular_plan = e.insert(CircularPlan::default()); if let Some(v) = builder.circular.get(dep) { circular_plan .chunks .extend(v.iter().copied().filter(|&v| v != dep)); } } } // if !builder.is_circular(dep) { // plans.normal.entry(dep).or_default().chunks. // push(entry); } } } } } for &entry in &plans.entries { plans.normal.entry(entry).or_default(); } // dbg!(&plans); plans } fn add_to_graph( &self, builder: &mut PlanBuilder, module_id: ModuleId, path: &mut Vec<ModuleId>, ) { builder.direct_deps.add_node(module_id); let m = self .scope .get_module(module_id) .expect("failed to get module"); for src in m .imports .specifiers .iter() .map(|v| &v.0) .chain(m.exports.reexports.iter().map(|v| &v.0)) { if !builder.direct_deps.contains_edge(module_id, src.module_id) { log::debug!("Dependency: {:?} => {:?}", module_id, src.module_id); } builder.direct_deps.add_edge(module_id, src.module_id, 0); for &id in &*path { builder.all_deps.insert((id, src.module_id)); } builder.all_deps.insert((module_id, src.module_id)); if !builder.all_deps.contains(&(src.module_id, module_id)) { path.push(module_id); self.add_to_graph(builder, src.module_id, path); assert_eq!(path.pop(), Some(module_id)); } } // Prevent dejavu for (src, _) in &m.imports.specifiers { if builder.all_deps.contains(&(src.module_id, module_id)) { log::debug!("Circular dep: {:?} => {:?}", module_id, src.module_id); builder.mark_as_circular(module_id, src.module_id); let circular_paths = all_simple_paths::<Vec<ModuleId>, _>( &builder.direct_deps, src.module_id, module_id, 0, None, ) .collect::<Vec<_>>(); for path in circular_paths { for dep in path { builder.mark_as_circular(module_id, dep) } } } } } }
35.058943
99
0.406806
e80439dc33b7dacf13486278b9b7cc9e1893f985
6,437
use introspection_connector::{ConnectorError, ErrorKind}; use quaint::error::{Error as QuaintError, ErrorKind as QuaintKind}; use thiserror::Error; use user_facing_errors::{quaint::render_quaint_error, query_engine::DatabaseConstraint}; pub type SqlResult<T> = Result<T, SqlError>; #[derive(Debug, Error)] pub enum SqlError { #[error("{0}")] Generic(#[source] anyhow::Error), #[error("Error connecting to the database {cause}")] ConnectionError { #[source] cause: QuaintKind, }, #[error("Error querying the database: {}", _0)] QueryError(#[source] anyhow::Error), #[error("Database '{}' does not exist", db_name)] DatabaseDoesNotExist { db_name: String, #[source] cause: QuaintKind, }, #[error("Access denied to database '{}'", db_name)] DatabaseAccessDenied { db_name: String, #[source] cause: QuaintKind, }, #[error("Database '{}' already exists", db_name)] DatabaseAlreadyExists { db_name: String, #[source] cause: QuaintKind, }, #[error("Authentication failed for user '{}'", user)] AuthenticationFailed { user: String, #[source] cause: QuaintKind, }, #[error("Connect timed out")] ConnectTimeout(#[source] QuaintKind), #[error("Operation timed out ({0})")] Timeout(String), #[error("Error opening a TLS connection. {}", cause)] TlsError { #[source] cause: QuaintKind, }, #[error("Unique constraint violation")] UniqueConstraintViolation { constraint: DatabaseConstraint, #[source] cause: QuaintKind, }, } impl SqlError { pub(crate) fn into_connector_error(self, connection_info: &super::ConnectionInfo) -> ConnectorError { match self { SqlError::DatabaseDoesNotExist { db_name, cause } => ConnectorError { user_facing_error: render_quaint_error(&cause, connection_info), kind: ErrorKind::DatabaseDoesNotExist { db_name }, }, SqlError::DatabaseAccessDenied { db_name, cause } => ConnectorError { user_facing_error: render_quaint_error(&cause, connection_info), kind: ErrorKind::DatabaseAccessDenied { database_name: db_name }, }, SqlError::DatabaseAlreadyExists { db_name, cause } => ConnectorError { user_facing_error: render_quaint_error(&cause, connection_info), kind: ErrorKind::DatabaseAlreadyExists { db_name }, }, SqlError::AuthenticationFailed { user, cause } => ConnectorError { user_facing_error: render_quaint_error(&cause, connection_info), kind: ErrorKind::AuthenticationFailed { user }, }, SqlError::ConnectTimeout(cause) => { let user_facing_error = render_quaint_error(&cause, connection_info); ConnectorError { user_facing_error, kind: ErrorKind::ConnectTimeout, } } SqlError::Timeout(message) => ConnectorError::from_kind(ErrorKind::Timeout(message)), SqlError::TlsError { cause } => { let user_facing_error = render_quaint_error(&cause, connection_info); ConnectorError { user_facing_error, kind: ErrorKind::TlsError { message: format!("{}", cause), }, } } SqlError::ConnectionError { cause } => { let user_facing_error = render_quaint_error(&cause, connection_info); ConnectorError { user_facing_error, kind: ErrorKind::ConnectionError { host: connection_info.host().to_owned(), cause: cause.into(), }, } } SqlError::UniqueConstraintViolation { cause, .. } => { let user_facing_error = render_quaint_error(&cause, connection_info); ConnectorError { user_facing_error, kind: ErrorKind::ConnectionError { host: connection_info.host().to_owned(), cause: cause.into(), }, } } error => ConnectorError::from_kind(ErrorKind::QueryError(error.into())), } } } impl From<QuaintKind> for SqlError { fn from(kind: QuaintKind) -> Self { match kind { QuaintKind::DatabaseDoesNotExist { ref db_name } => Self::DatabaseDoesNotExist { db_name: db_name.clone(), cause: kind, }, QuaintKind::DatabaseAlreadyExists { ref db_name } => Self::DatabaseAlreadyExists { db_name: db_name.clone(), cause: kind, }, QuaintKind::DatabaseAccessDenied { ref db_name } => Self::DatabaseAccessDenied { db_name: db_name.clone(), cause: kind, }, QuaintKind::AuthenticationFailed { ref user } => Self::AuthenticationFailed { user: user.clone(), cause: kind, }, e @ QuaintKind::ConnectTimeout(..) => Self::ConnectTimeout(e), QuaintKind::ConnectionError { .. } => Self::ConnectionError { cause: kind }, QuaintKind::Timeout(message) => Self::Timeout(format!("quaint timeout: {}", message)), QuaintKind::TlsError { .. } => Self::TlsError { cause: kind }, QuaintKind::UniqueConstraintViolation { ref constraint } => Self::UniqueConstraintViolation { constraint: constraint.into(), cause: kind, }, _ => SqlError::QueryError(kind.into()), } } } impl From<QuaintError> for SqlError { fn from(e: QuaintError) -> Self { QuaintKind::from(e).into() } } impl From<sql_schema_describer::SqlSchemaDescriberError> for SqlError { fn from(error: sql_schema_describer::SqlSchemaDescriberError) -> Self { SqlError::QueryError(anyhow::anyhow!("{}", error)) } } impl From<String> for SqlError { fn from(error: String) -> Self { SqlError::Generic(anyhow::anyhow!(error)) } }
35.174863
105
0.560354
1dbf211b269414ea8c8531c5b8b91787150862cf
803
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:issue_3907.rs extern crate issue_3907; type Foo = issue_3907::Foo; //~ NOTE: type defined here struct S { name: isize } impl Foo for S { //~ ERROR: `Foo` is not a trait //~^ NOTE: `type` aliases cannot be used for traits fn bar() { } } fn main() { let s = S { name: 0 }; s.bar(); }
25.903226
69
0.671233
bff99b8c258683f367de59cc3bb10d2b31bbdeb3
698
extern crate day03; extern crate rayon; extern crate util; use std::io; use day03::task01::Step; fn main() -> io::Result<()> { let parser = |x: String| x .split(",") .map(|item: &str| Ok(Step::from(item.to_string())) ).collect::<io::Result<Vec<Step>>>(); let wires = util::get_parsed_input_from_file("day03/src/input", parser)?; let wire1 = wires.get(0).unwrap().to_vec(); let wire2 = wires.get(1).unwrap().to_vec(); let result = day03::task01::run((wire1.clone(), wire2.clone())); println!("Day 03 Task 01: {}", result); let result = day03::task02::run((wire1, wire2)); println!("Day 03 Task 02: {}", result); Ok(()) }
25.851852
77
0.580229
8ace3aa65ff6f933eab4feeb8754c1ebe6ea6515
1,924
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT use crate::miner::{GetControlAddressesReturn, Method}; use address::Address; use ipld_blockstore::BlockStore; use num_traits::Zero; use runtime::Runtime; use std::error::Error as StdError; use vm::{ActorError, Serialized, TokenAmount, METHOD_SEND}; pub(crate) fn request_miner_control_addrs<BS, RT>( rt: &mut RT, miner_addr: Address, ) -> Result<(Address, Address, Vec<Address>), ActorError> where BS: BlockStore, RT: Runtime<BS>, { let ret = rt.send( miner_addr, Method::ControlAddresses as u64, Serialized::default(), TokenAmount::zero(), )?; let addrs: GetControlAddressesReturn = ret.deserialize()?; Ok((addrs.owner, addrs.worker, addrs.control_addresses)) } /// ResolveToIDAddr resolves the given address to it's ID address form. /// If an ID address for the given address dosen't exist yet, it tries to create one by sending /// a zero balance to the given address. pub(crate) fn resolve_to_id_addr<BS, RT>( rt: &mut RT, address: &Address, ) -> Result<Address, Box<dyn StdError>> where BS: BlockStore, RT: Runtime<BS>, { // if we are able to resolve it to an ID address, return the resolved address if let Some(addr) = rt.resolve_address(address)? { return Ok(addr); } // send 0 balance to the account so an ID address for it is created and then try to resolve rt.send( *address, METHOD_SEND, Default::default(), Default::default(), ) .map_err(|e| { e.wrap(&format!( "failed to send zero balance to address {}", address )) })?; rt.resolve_address(address)?.ok_or_else(|| { format!( "failed to resolve address {} to ID address even after sending zero balance", address, ) .into() }) }
27.884058
95
0.637734
dbc8f6be44dc5355fef1cd021e11b39a87203a36
7,349
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use crate::server::metrics::GRPC_MSG_HISTOGRAM_STATIC; use crate::server::service::kv::{batch_commands_response, poll_future_notify}; use crate::storage::{ errors::{extract_key_error, extract_region_error}, kv::Engine, lock_manager::LockManager, Storage, }; use futures03::compat::Compat; use futures03::future::FutureExt; use kvproto::kvrpcpb::*; use tikv_util::mpsc::batch::Sender; use tikv_util::time::{duration_to_sec, Instant}; pub struct ReqBatcher { gets: Vec<GetRequest>, raw_gets: Vec<RawGetRequest>, get_ids: Vec<u64>, raw_get_ids: Vec<u64>, } impl ReqBatcher { pub fn new() -> ReqBatcher { ReqBatcher { gets: vec![], raw_gets: vec![], get_ids: vec![], raw_get_ids: vec![], } } pub fn can_batch_get(&self, req: &GetRequest) -> bool { req.get_context().get_priority() == CommandPri::Normal } pub fn can_batch_raw_get(&self, req: &RawGetRequest) -> bool { req.get_context().get_priority() == CommandPri::Normal } pub fn add_get_request(&mut self, req: GetRequest, id: u64) { self.gets.push(req); self.get_ids.push(id); } pub fn add_raw_get_request(&mut self, req: RawGetRequest, id: u64) { self.raw_gets.push(req); self.raw_get_ids.push(id); } pub fn maybe_commit<E: Engine, L: LockManager>( &mut self, storage: &Storage<E, L>, tx: &Sender<(u64, batch_commands_response::Response)>, ) { if self.gets.len() > 10 { let gets = std::mem::replace(&mut self.gets, vec![]); let ids = std::mem::replace(&mut self.get_ids, vec![]); future_batch_get_command(storage, ids, gets, tx.clone()); } if self.raw_gets.len() > 16 { let gets = std::mem::replace(&mut self.raw_gets, vec![]); let ids = std::mem::replace(&mut self.raw_get_ids, vec![]); future_batch_raw_get_command(storage, ids, gets, tx.clone()); } } pub fn commit<E: Engine, L: LockManager>( &mut self, storage: &Storage<E, L>, tx: &Sender<(u64, batch_commands_response::Response)>, ) { if !self.gets.is_empty() { let gets = std::mem::replace(&mut self.gets, vec![]); let ids = std::mem::replace(&mut self.get_ids, vec![]); future_batch_get_command(storage, ids, gets, tx.clone()); } if !self.raw_gets.is_empty() { let gets = std::mem::replace(&mut self.raw_gets, vec![]); let ids = std::mem::replace(&mut self.raw_get_ids, vec![]); future_batch_raw_get_command(storage, ids, gets, tx.clone()); } } } fn future_batch_get_command<E: Engine, L: LockManager>( storage: &Storage<E, L>, requests: Vec<u64>, gets: Vec<GetRequest>, tx: Sender<(u64, batch_commands_response::Response)>, ) { let begin_instant = Instant::now_coarse(); let ret = storage.batch_get_command(gets); let f = async move { match ret.await { Ok(ret) => { for (v, req) in ret.into_iter().zip(requests) { let mut resp = GetResponse::default(); if let Some(err) = extract_region_error(&v) { resp.set_region_error(err); } else { match v { Ok(Some(val)) => resp.set_value(val), Ok(None) => resp.set_not_found(true), Err(e) => resp.set_error(extract_key_error(&e)), } } let mut res = batch_commands_response::Response::default(); res.cmd = Some(batch_commands_response::response::Cmd::Get(resp)); if tx.send_and_notify((req, res)).is_err() { error!("KvService response batch commands fail"); } } } e => { let mut resp = GetResponse::default(); if let Some(err) = extract_region_error(&e) { resp.set_region_error(err); } else if let Err(e) = e { resp.set_error(extract_key_error(&e)); } let mut res = batch_commands_response::Response::default(); res.cmd = Some(batch_commands_response::response::Cmd::Get(resp)); for req in requests { if tx.send_and_notify((req, res.clone())).is_err() { error!("KvService response batch commands fail"); } } } } GRPC_MSG_HISTOGRAM_STATIC .kv_batch_get_command .observe(begin_instant.elapsed_secs()); }; poll_future_notify(Compat::new(f.unit_error().boxed())); } fn future_batch_raw_get_command<E: Engine, L: LockManager>( storage: &Storage<E, L>, requests: Vec<u64>, gets: Vec<RawGetRequest>, tx: Sender<(u64, batch_commands_response::Response)>, ) { let begin_instant = Instant::now_coarse(); let ret = storage.raw_batch_get_command(gets); let f = async move { match ret.await { Ok(v) => { if requests.len() != v.len() { error!("KvService batch response size mismatch"); } for (req, v) in requests.into_iter().zip(v.into_iter()) { let mut resp = RawGetResponse::default(); if let Some(err) = extract_region_error(&v) { resp.set_region_error(err); } else { match v { Ok(Some(val)) => resp.set_value(val), Ok(None) => resp.set_not_found(true), Err(e) => resp.set_error(format!("{}", e)), } } let mut res = batch_commands_response::Response::default(); res.cmd = Some(batch_commands_response::response::Cmd::RawGet(resp)); if tx.send_and_notify((req, res)).is_err() { error!("KvService response batch commands fail"); } } } e => { let mut resp = RawGetResponse::default(); if let Some(err) = extract_region_error(&e) { resp.set_region_error(err); } else if let Err(e) = e { resp.set_error(format!("{}", e)); } let mut res = batch_commands_response::Response::default(); res.cmd = Some(batch_commands_response::response::Cmd::RawGet(resp)); for req in requests { if tx.send_and_notify((req, res.clone())).is_err() { error!("KvService response batch commands fail"); } } } } GRPC_MSG_HISTOGRAM_STATIC .raw_batch_get_command .observe(duration_to_sec(begin_instant.elapsed())); }; poll_future_notify(Compat::new(f.unit_error().boxed())); }
38.07772
89
0.521704
fb7978fc2b2c4ddd0798949b7987e8cbbb566bcb
18,207
//! The RTR client. //! //! This module implements a generic RTR client through [`Client`]. In order //! to use the client, you will need to provide a type that implements //! [`VrpTarget`] as well as one that implements [`VrpUpdate`]. The former //! represents the place where all the information received via the RTR client //! is stored, while the latter receives a set of updates and applies it to //! the target. //! //! For more information on how to use the client, see the [`Client`] type. //! //! [`Client`]: struct.Client.html //! [`VrpTarget`]: trait VrpTarget.html //! [`VrpUpdate`]: trait.VrpUpdate.html use std::io; use std::future::Future; use std::marker::Unpin; use tokio::time::{timeout, timeout_at, Duration, Instant}; use tokio::io::{AsyncRead, AsyncWrite}; use crate::payload::{Action, Payload, Timing}; use crate::pdu; use crate::state::State; //------------ Configuration Constants --------------------------------------- const IO_TIMEOUT: Duration = Duration::from_secs(1); //------------ VrpTarget ----------------------------------------------------- /// A type that keeps data received via RTR. /// /// The data of the target consisting of a set of items called VRPs for /// Validated RPKI Payload. It is modified by atomic updates that add /// or remove items of the set. /// /// This trait provides a method to start and apply updates which are /// collected into a different type that implements the companion /// [`VrpUpdate`] trait. /// /// [`VrpUpdate`]: trait.VrpUpdate.html pub trait VrpTarget { /// The type of a single update. type Update: VrpUpdate; /// Starts a new update. /// /// If the update is a for a reset query, `reset` will be `true`, meaning /// that when the update is applied, all previous data should be removed. /// This flag is repeated later in `apply`, leaving it to implementations /// whether to store updates differently for reset and serial queries. fn start(&mut self, reset: bool) -> Self::Update; /// Applies an update to the target. /// /// The data to apply is handed over via `update`. If `reset` is `true`, /// the data should replace the current data of the target. Otherwise it /// entries should be added and removed according to the action. The /// `timing` parameter contains the timing information provided by the /// server. fn apply( &mut self, update: Self::Update, reset: bool, timing: Timing ) -> Result<(), VrpError>; } //------------ VrpUpdate ----------------------------------------------------- /// A type that can receive a VRP data update. /// /// The update happens by repeatedly calling the [`push_vrp`] method with a /// single update as received by the client. The data is not filtered. It /// may contain duplicates and it may conflict with the current data set. /// It is the task of the implementor to deal with such situations. /// /// A value of this type is created via `VrpTarget::start` when the client /// starts processing an update. If the update succeeds, the value is applied /// to the target by giving it to `VrpTarget::apply`. If the update fails at /// any point, the valus is simply dropped. /// /// [`push_vrp`]: #method.push_vrp /// [`VrpTarget::start`]: trait.VrpTarget.html#method.start /// [`VrpTarget::apply`]: trait.VrpTarget.html#method.apply pub trait VrpUpdate { /// Updates one single VRP. /// /// The `action` argument describes whether the VRP is to be announced, /// i.e., added to the data set, or withdrawn, i.e., removed. The VRP /// itself is given via `payload`. fn push_vrp( &mut self, action: Action, payload: Payload ) -> Result<(), VrpError>; } impl VrpUpdate for Vec<(Action, Payload)> { fn push_vrp( &mut self, action: Action, payload: Payload ) -> Result<(), VrpError> { self.push((action, payload)); Ok(()) } } //------------ Client -------------------------------------------------------- /// An RTR client. /// /// The client wraps a socket – represented by the type argument `Sock` which /// needs to support Tokio’s asynchronous writing and reading – and runs an /// RTR client over it. All data received will be passed on a [`VrpTarget`] /// of type `Target`. /// /// The client keeps the socket open until either the server closes the /// connection, an error happens, or the client is dropped. It will /// periodically push a new dataset to the target. pub struct Client<Sock, Target> { /// The socket to communicate over. sock: Sock, /// The target for the VRP set. target: Target, /// The current synchronisation state. /// /// The first element is the session ID, the second is the serial. If /// this is `None`, we do a reset query next. state: Option<State>, /// The RRDP version to use. /// /// If this is `None` we haven’t spoken with the server yet. In this /// case, we use 1 and accept any version from the server. Otherwise /// send this version and receving a differing version from the server /// is an error as it is not allowed to change its mind halfway. version: Option<u8>, /// The timing parameters reported by the server. /// /// We use the `refresh` value to determine how long to wait before /// requesting an update. The other values we just report to the target. timing: Timing, /// The next time we should be running. /// /// If this is None, we should be running now. next_update: Option<Instant>, } impl<Sock, Target> Client<Sock, Target> { /// Creates a new client. /// /// The client will use `sock` for communicating with the server and /// `target` to send updates to. /// /// If the last state of a connection with this server is known – it can /// be determined by calling [`state`] on the client – it can be reused /// via the `state` argument. Make sure to also have the matching data in /// your target in this case since the there will not necessarily be a /// reset update. If you don’t have any state or don’t want to reuse an /// earlier session, simply pass `None`. /// /// [`state`]: #method.state pub fn new( sock: Sock, target: Target, state: Option<State> ) -> Self { Client { sock, target, state, version: None, timing: Timing::default(), next_update: None, } } /// Returns a reference to the target. pub fn target(&self) -> &Target { &self.target } /// Returns a mutable reference to the target. pub fn target_mut(&mut self) -> &mut Target { &mut self.target } /// Converts the client into its target. pub fn into_target(self) -> Target { self.target } /// Returns the current state of the session. /// /// The method will return `None` if there hasn’t been initial state and /// there has not been any converstation with the server yet. pub fn state(&self) -> Option<State> { self.state } /// Returns the protocol version to use. fn version(&self) -> u8 { self.version.unwrap_or(1) } } impl<Sock, Target> Client<Sock, Target> where Sock: AsyncRead + AsyncWrite + Unpin, Target: VrpTarget { /// Runs the client. /// /// The method will keep the client asynchronously running, fetching any /// new data that becomes available on the server and pushing it to the /// target until either the server closes the connection – in which case /// the method will return `Ok(())` –, an error happens – which will be /// returned or the future gets dropped. pub async fn run(&mut self) -> Result<(), io::Error> { match self._run().await { Ok(()) => Ok(()), Err(err) => { if err.kind() == io::ErrorKind::UnexpectedEof { Ok(()) } else { Err(err) } } } } /// Internal version of run. /// /// This is only here to make error handling easier. async fn _run(&mut self) -> Result<(), io::Error> { // End of loop via an io::Error. loop { match self.state { Some(state) => { match self.serial(state).await? { Some(update) => { self.apply(update, false).await?; } None => continue, } } None => { let update = self.reset().await?; self.apply(update, true).await?; } } if let Ok(Err(err)) = timeout( Duration::from_secs(u64::from(self.timing.refresh)), pdu::SerialNotify::read(&mut self.sock) ).await { return Err(err) } } } /// Performs a single update of the client data. /// /// The method will wait until the next update is due and the request one /// single update from the server. It will request a new update object /// from the target, apply the update to that object and, if the update /// succeeds, return the object. pub async fn update( &mut self ) -> Result<Target::Update, io::Error> { if let Some(instant) = self.next_update.take() { if let Ok(Err(err)) = timeout_at( instant, pdu::SerialNotify::read(&mut self.sock) ).await { return Err(err) } } if let Some(state) = self.state { if let Some(update) = self.serial(state).await? { self.next_update = Some( Instant::now() + self.timing.refresh_duration() ); return Ok(update) } } let res = self.reset().await; self.next_update = Some( Instant::now() + self.timing.refresh_duration() ); res } /// Perform a serial query. /// /// Returns some update if the query succeeded and the client should now /// wait for a while. Returns `None` if the server reported a restart and /// we need to proceed with a reset query. Returns an error /// in any other case. async fn serial( &mut self, state: State ) -> Result<Option<Target::Update>, io::Error> { pdu::SerialQuery::new( self.version(), state, ).write(&mut self.sock).await?; let start = match self.try_io(FirstReply::read).await? { FirstReply::Response(start) => start, FirstReply::Reset(_) => { self.state = None; return Ok(None) } }; self.check_version(start.version())?; let mut target = self.target.start(false); loop { match pdu::Payload::read(&mut self.sock).await? { Ok(Some(pdu)) => { self.check_version(pdu.version())?; let (action, payload) = pdu.to_payload(); if let Err(err) = target.push_vrp(action, payload) { err.send( self.version(), Some(pdu), &mut self.sock ).await?; return Err(io::Error::new(io::ErrorKind::Other, "")); } } Ok(None) => { // Unsupported but legal payload: ignore. } Err(end) => { self.check_version(end.version())?; self.state = Some(end.state()); if let Some(timing) = end.timing() { self.timing = timing } break; } } } Ok(Some(target)) } /// Performs a reset query. pub async fn reset(&mut self) -> Result<Target::Update, io::Error> { pdu::ResetQuery::new( self.version() ).write(&mut self.sock).await?; let start = self.try_io(|sock| { pdu::CacheResponse::read(sock) }).await?; self.check_version(start.version())?; let mut target = self.target.start(true); loop { match pdu::Payload::read(&mut self.sock).await? { Ok(Some(pdu)) => { self.check_version(pdu.version())?; let (action, payload) = pdu.to_payload(); if let Err(err) = target.push_vrp(action, payload) { err.send( self.version(), Some(pdu), &mut self.sock ).await?; return Err(io::Error::new(io::ErrorKind::Other, "")); } } Ok(None) => { // Unsupported but legal payload: ignore. } Err(end) => { self.check_version(end.version())?; self.state = Some(end.state()); if let Some(timing) = end.timing() { self.timing = timing } break; } } } Ok(target) } /// Tries to apply an update and sends errors if that fails. async fn apply( &mut self, update: Target::Update, reset: bool ) -> Result<(), io::Error> { if let Err(err) = self.target.apply(update, reset, self.timing) { err.send(self.version(), None, &mut self.sock).await?; Err(io::Error::new(io::ErrorKind::Other, "")) } else { Ok(()) } } /// Performs some IO operation on the socket. /// /// The mutable reference to the socket is passed to the closure provided /// which does the actual IO. The closure is given `IO_TIMEOUT` to finsih /// whatever it is doing. Otherwise it is cancelled and a timeout error /// is returned. async fn try_io<'a, F, Fut, T>( &'a mut self, op: F ) -> Result<T, io::Error> where F: FnOnce(&'a mut Sock) -> Fut, Fut: Future<Output = Result<T, io::Error>> + 'a { match timeout(IO_TIMEOUT, op(&mut self.sock)).await { Ok(res) => res, Err(_) => { Err(io::Error::new( io::ErrorKind::TimedOut, "server response timed out" )) } } } /// Checks whether `version` matches the stored version. /// /// Returns an error if it doesn’t. fn check_version(&mut self, version: u8) -> Result<(), io::Error> { if let Some(stored_version) = self.version { if version != stored_version { Err(io::Error::new( io::ErrorKind::InvalidData, "version has changed" )) } else { Ok(()) } } else { self.version = Some(version); Ok(()) } } } //------------ FirstReply ---------------------------------------------------- /// The first reply from a server in response to a serial query. enum FirstReply { /// A cache response. Actual data is to follow. Response(pdu::CacheResponse), /// A reset response. We need to retry with a reset query. Reset(pdu::CacheReset), } impl FirstReply { /// Reads the first reply from a socket. /// /// If any other reply than a cache response or reset response is /// received or anything else goes wrong, returns an error. async fn read<Sock: AsyncRead + Unpin>( sock: &mut Sock ) -> Result<Self, io::Error> { let header = pdu::Header::read(sock).await?; match header.pdu() { pdu::CacheResponse::PDU => { pdu::CacheResponse::read_payload( header, sock ).await.map(FirstReply::Response) } pdu::CacheReset::PDU => { pdu::CacheReset::read_payload( header, sock ).await.map(FirstReply::Reset) } pdu::Error::PDU => { Err(io::Error::new( io::ErrorKind::Other, format!("server reported error {}", header.session()) )) } pdu => { Err(io::Error::new( io::ErrorKind::InvalidData, format!("unexpected PDU {}", pdu) )) } } } } //------------ VrpError ------------------------------------------------------ /// A received VRP was not acceptable. #[derive(Clone, Copy, Debug)] pub enum VrpError { /// A nonexisting record was withdrawn. UnknownWithdraw, /// An existing record was announced again. DuplicateAnnounce, /// The record is corrupt. Corrupt, /// An internal error in the receiver happend. Internal, } impl VrpError { fn error_code(self) -> u16 { match self { VrpError::UnknownWithdraw => 6, VrpError::DuplicateAnnounce => 7, VrpError::Corrupt => 0, VrpError::Internal => 1 } } async fn send( self, version: u8, pdu: Option<pdu::Payload>, sock: &mut (impl AsyncWrite + Unpin) ) -> Result<(), io::Error> { match pdu { Some(pdu::Payload::V4(pdu)) => { pdu::Error::new( version, self.error_code(), pdu, "" ).write(sock).await } Some(pdu::Payload::V6(pdu)) => { pdu::Error::new( version, self.error_code(), pdu, "" ).write(sock).await } None => { pdu::Error::new( version, self.error_code(), "", "" ).write(sock).await } } } }
33.46875
78
0.528313
0335914e0955e769da7eb7b58fd1846a3bf2711f
939
// // Copyright 2020 The Project Oak Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // use oak_utils::{generate_grpc_code, CodegenOptions}; fn main() -> Result<(), Box<dyn std::error::Error>> { generate_grpc_code( "../../../", &["examples/translator/proto/translator.proto"], CodegenOptions { build_client: true, ..Default::default() }, )?; Ok(()) }
31.3
75
0.666667
fb19db590085415117403b34af60ca73f84b3329
1,518
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn movddup_1() { run_test(&Instruction { mnemonic: Mnemonic::MOVDDUP, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 18, 247], OperandSize::Dword) } fn movddup_2() { run_test(&Instruction { mnemonic: Mnemonic::MOVDDUP, operand1: Some(Direct(XMM7)), operand2: Some(Indirect(EAX, Some(OperandSize::Qword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 18, 56], OperandSize::Dword) } fn movddup_3() { run_test(&Instruction { mnemonic: Mnemonic::MOVDDUP, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 18, 254], OperandSize::Qword) } fn movddup_4() { run_test(&Instruction { mnemonic: Mnemonic::MOVDDUP, operand1: Some(Direct(XMM3)), operand2: Some(IndirectDisplaced(RAX, 1764602209, Some(OperandSize::Qword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 18, 152, 97, 177, 45, 105], OperandSize::Qword) }
63.25
356
0.70751
3a805afd9e6abdc274985ddf95bf03e649c57a55
280
//! @ @<Express shock...@>= //! begin print_err("Missing { inserted"); incr(align_state); //! @.Missing \{ inserted@> //! help2("Where was the left brace? You said something like `\def\a}',")@/ //! ("which I'm going to interpret as `\def\a{}'."); error; goto found; //! end //!
35
75
0.592857
23c6e288c20af51bb6447d33a690dd54bcc5d048
4,057
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use fidl_fuchsia_boot::WriteOnlyLogMarker; use fidl_fuchsia_logger::{LogFilterOptions, LogLevelFilter, LogMessage}; use fidl_test_log_stdio::StdioPuppetMarker; use fuchsia_async as fasync; use fuchsia_component::client::{self as fclient, connect_to_service}; use fuchsia_syslog::{self as syslog, fx_log_info}; use fuchsia_syslog_listener::{self as syslog_listener, LogProcessor}; use fuchsia_zircon as zx; use futures::{channel::mpsc, Stream, StreamExt}; use log::warn; struct Listener { send_logs: mpsc::UnboundedSender<LogMessage>, } impl LogProcessor for Listener { fn log(&mut self, message: LogMessage) { self.send_logs.unbounded_send(message).unwrap(); } fn done(&mut self) { panic!("this should not be called"); } } fn run_listener(tag: &str) -> impl Stream<Item = LogMessage> { let mut options = LogFilterOptions { filter_by_pid: false, pid: 0, min_severity: LogLevelFilter::None, verbosity: 0, filter_by_tid: false, tid: 0, tags: vec![tag.to_string()], }; let (send_logs, recv_logs) = mpsc::unbounded(); let l = Listener { send_logs }; fasync::Task::spawn(async move { let fut = syslog_listener::run_log_listener(l, Some(&mut options), false, None); if let Err(e) = fut.await { panic!("test fail {:?}", e); } }) .detach(); recv_logs } #[fasync::run_singlethreaded(test)] async fn listen_for_syslog() { let random = rand::random::<u16>(); let tag = "logger_integration_rust".to_string() + &random.to_string(); syslog::init_with_tags(&[&tag]).expect("should not fail"); let incoming = run_listener(&tag); fx_log_info!("my msg: {}", 10); warn!("log crate: {}", 20); let mut logs: Vec<LogMessage> = incoming.take(2).collect().await; // sort logs to account for out-of-order arrival logs.sort_by(|a, b| a.time.cmp(&b.time)); assert_eq!(2, logs.len()); assert_eq!(logs[0].tags, vec![tag.clone()]); assert_eq!(logs[0].severity, LogLevelFilter::Info as i32); assert_eq!(logs[0].msg, "my msg: 10"); assert_eq!(logs[1].tags[0], tag.clone()); assert_eq!(logs[1].severity, LogLevelFilter::Warn as i32); assert_eq!(logs[1].msg, "log crate: 20"); } #[fuchsia::test] async fn listen_for_klog() { let logs = run_listener("klog"); let msg = format!("logger_integration_rust test_klog {}", rand::random::<u64>()); let resource = zx::Resource::from(zx::Handle::invalid()); let debuglog = zx::DebugLog::create(&resource, zx::DebugLogOpts::empty()).unwrap(); debuglog.write(msg.as_bytes()).unwrap(); logs.filter(|m| futures::future::ready(m.msg == msg)).next().await; } #[fuchsia::test] async fn listen_for_klog_routed_stdio() { let mut logs = run_listener("klog"); let app_builder = fclient::AppBuilder::new( "fuchsia-pkg://fuchsia.com/test-logs-basic-integration#meta/stdio_puppet.cmx", ); let boot_log = connect_to_service::<WriteOnlyLogMarker>().unwrap(); let stdout_debuglog = boot_log.get().await.unwrap(); let stderr_debuglog = boot_log.get().await.unwrap(); let app = app_builder .stdout(stdout_debuglog) .stderr(stderr_debuglog) .spawn(&fclient::launcher().unwrap()) .unwrap(); let puppet = app.connect_to_service::<StdioPuppetMarker>().unwrap(); let msg = format!("logger_integration_rust test_klog stdout {}", rand::random::<u64>()); puppet.writeln_stdout(&msg).unwrap(); logs.by_ref().filter(|m| futures::future::ready(m.msg == msg)).next().await; let msg = format!("logger_integration_rust test_klog stderr {}", rand::random::<u64>()); puppet.writeln_stderr(&msg).unwrap(); logs.filter(|m| futures::future::ready(m.msg == msg)).next().await; // TODO(fxbug.dev/49357): add test for multiline log once behavior is defined. }
34.381356
92
0.661819
0343cb810ab07980c20623a1c5f97661f0b6547b
5,786
use crate::router::RouteResult; // The plugin crate doesn't play well with async //use plugin::{Extensible, Pluggable}; use typemap::{ShareMap, TypeMap}; use hyper::{Body, Request as HyperRequest, StatusCode}; use hyper::body::{self, Bytes}; use hyper::header; use serde::Deserialize; use serde_json; use std::mem; use std::net::SocketAddr; use std::sync::Arc; use crate::urlencoded::{self, Params}; /// A container for all the request data. pub struct Request<D = ()> { ///the original `hyper::server::Request` pub origin: HyperRequest<Body>, body_taken: bool, pub route_result: Option<RouteResult>, map: ShareMap, data: Arc<D>, remote_addr: Option<SocketAddr>, raw_body_cache: Option<Bytes>, } impl<D> Request<D> { pub fn from_internal(req: HyperRequest<Body>, remote_addr: Option<SocketAddr>, data: Arc<D>) -> Request<D> { Request { origin: req, body_taken: false, route_result: None, map: TypeMap::custom(), data: data, remote_addr: remote_addr, raw_body_cache: None } } pub fn param(&self, key: &str) -> Option<&str> { self.route_result.as_ref().unwrap().param(key) } pub fn path_without_query(&self) -> &str { self.origin.uri().path() } pub fn server_data(&self) -> Arc<D> { self.data.clone() } pub fn remote_addr(&self) -> Option<&SocketAddr> { self.remote_addr.as_ref() } // (Hopefully) temporary replacements for the Extensible trait. We can't // support plugins without Extensible, but access to the ShareMap is used by // itself. pub fn extensions(&self) -> &ShareMap { &self.map } pub fn extensions_mut(&mut self) -> &mut ShareMap { &mut self.map } /// Take the body from the hyper request. Once taken the body is not longer /// available. This method will return `None` in that case. /// /// For small non-streaming applications, the body access methods /// `raw_body`, `string_body`, `json_as`, and `form_body` are probably more /// convenient. Small in this case is hardware dependent, but even small /// modern servers can handle multi-megabyte bodies. /// /// `take_body` and the body access method are mutually exclusive. Once one /// is called, the other will fail. pub fn take_body(&mut self) -> Option<Body> { if self.body_taken { None } else { let stub = HyperRequest::new(Body::empty()); let origin = mem::replace(&mut self.origin, stub); let (parts, body) = origin.into_parts(); let _stub = mem::replace(&mut self.origin, HyperRequest::from_parts(parts, Body::empty())); self.body_taken = true; Some(body) } } } // TODO: migration cleanup - Extensible does not support ShareMap, but TypeMap is not Sync+Send // impl<D> Extensible for Request<D> { // fn extensions(&self) -> &ShareMap { // &self.map // } // fn extensions_mut(&mut self) -> &mut ShareMap { // &mut self.map // } // } // impl<D> Pluggable for Request<D> {} // Various body parsers. These used to live in the body_parser module by // implementing a trait on the Request struct. Async and traits are currently // kind of cumbersome. We use async_trait for Middleware, because users of // nickel need to implement Middleware. Since that is not needed for body // parsers, we will stick with something that will keep the interface simpler. impl<D> Request<D> { /// Extract the raw body from the request. The body is cached so multiple /// middleware may access the body. Note that this may consume a lot of /// memory when large objects are uploaded. /// /// To allow access to the body in different ways, `string_body`, `json_as` /// and `form_body` all call this and use the same underlying cache. pub async fn raw_body(&mut self) -> Result<&[u8], (StatusCode, String)> { if let None = self.raw_body_cache { // read and insert into cache let body = self.take_body(). ok_or((StatusCode::INTERNAL_SERVER_ERROR, "body already taken".to_string()))?; let bytes = body::to_bytes::<Body>(body).await. map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; self.raw_body_cache = Some(bytes); } // we've garanteed this unwrap is safe above Ok(self.raw_body_cache.as_ref().unwrap()) } /// Return the body parsed as a `String`. Returns an error if the body is /// not uft8. pub async fn string_body(&mut self) -> Result<String, (StatusCode, String)> { let bytes = self.raw_body().await?; String::from_utf8(bytes.to_vec()).map_err(|e| (StatusCode::BAD_REQUEST, e.to_string())) } /// Uses serde to deserialze thoe body as json into type `T`. pub async fn json_as<'a, T: Deserialize<'a>>(&'a mut self) -> Result<T, (StatusCode, String)> { let bytes = self.raw_body().await?; serde_json::from_slice::<T>(bytes). map_err(|e| (StatusCode::BAD_REQUEST, e.to_string())) } /// Extract the form data from the body. pub async fn form_body(&mut self) -> Result<Params, (StatusCode, String)> { // check content type match self.origin.headers().get(header::CONTENT_TYPE).map(|v| v.to_str()) { Some(Ok("application/x-www-form-urlencoded")) => { let s = self.string_body().await?; Ok(urlencoded::parse(&s)) }, _ => Err((StatusCode::BAD_REQUEST, "Wrong Content Type".to_string())) } } }
35.066667
103
0.613723
87d857f348370049d3e4bc67c07138119e75cfe3
2,530
#![feature(extern_crate_item_prelude, arbitrary_self_types)] extern crate proc_macro; extern crate proc_macro2; #[macro_use] extern crate quote; #[macro_use] extern crate syn; mod builder; mod schema; mod setter; mod getter; mod data; mod attrs; use self::proc_macro::TokenStream; use syn::DeriveInput; #[proc_macro] pub fn builder(input: TokenStream) -> TokenStream { parse_macro_input!(input as builder::Builder) .output().into() } #[proc_macro] pub fn schema(input: TokenStream) -> TokenStream { use schema::Schema; parse_macro_input!(input as Schema) .tokens().into() } #[proc_macro_derive(RefSetter, attributes(tygres))] pub fn setter_derive(input: TokenStream) -> TokenStream { let item = parse_macro_input!(input as DeriveInput); TokenStream::from(setter::trait_impl_ref_setter(item.into())) } #[proc_macro_derive(ValSetter, attributes(tygres))] pub fn setter_owned_derive(input: TokenStream) -> TokenStream { let item = parse_macro_input!(input as DeriveInput); TokenStream::from(setter::trait_impl_val_setter(item.into())) } #[proc_macro_derive(TakesUnit, attributes(tygres))] pub fn takes_unit_derive(input: TokenStream) -> TokenStream { let item = parse_macro_input!(input as DeriveInput); TokenStream::from(setter::trait_impl_takes_unit(item.into())) } #[proc_macro_derive(ColumnsSetter, attributes(tygres))] pub fn takes_columns_setter_derive(input: TokenStream) -> TokenStream { let item = parse_macro_input!(input as DeriveInput); TokenStream::from(setter::trait_impl_columns_setter(item.into())) } #[proc_macro_derive(HasSetter, attributes(tygres))] pub fn has_setter_derive(input: TokenStream) -> TokenStream { let item = parse_macro_input!(input as DeriveInput); TokenStream::from(setter::trait_impl_has_setter(item.into())) } #[proc_macro_derive(HasOwnedSetter, attributes(tygres))] pub fn has_owned_setter_derive(input: TokenStream) -> TokenStream { let item = parse_macro_input!(input as DeriveInput); TokenStream::from(setter::trait_impl_has_owned_setter(item.into())) } #[proc_macro_derive(Makes, attributes(tygres))] pub fn makes_derive(input: TokenStream) -> TokenStream { let item = parse_macro_input!(input as DeriveInput); TokenStream::from(getter::trait_impl(item.into())) } #[proc_macro_derive(Getter, attributes(tygres))] pub fn getter_derive(input: TokenStream) -> TokenStream { let item = parse_macro_input!(input as DeriveInput); TokenStream::from(getter::trait_impl_getter(item.into())) }
31.234568
71
0.75336
69fd1f335138a5771906e6d050e74ca9bb54801f
1,060
use std::io; use std::str::FromStr; fn get_sum_of_all_numbers_from_one_to_n(n: u32) -> u32 { let mut sum : u32 = 0; for i in 1..n+1 { sum += i; } sum } #[test] fn test() { assert_eq!(get_sum_of_all_numbers_from_one_to_n(1), 1); assert_eq!(get_sum_of_all_numbers_from_one_to_n(2), 3); assert_eq!(get_sum_of_all_numbers_from_one_to_n(10), 55); assert_eq!(get_sum_of_all_numbers_from_one_to_n(20), 210); } fn main() -> io::Result<()> { println!("Please input a number. I will write out a sum of all numbers from 1 to n."); let mut number_string = String::new(); io::stdin().read_line(&mut number_string)?; let number = match u32::from_str(&number_string.trim()) { Ok(number) => number, Err(_) => { println!("Please input only integer numbers!"); std::process::exit(1); } }; let sum = get_sum_of_all_numbers_from_one_to_n(number); println!("Final sum of all numbers from 1 to {} (including) is {}", number, sum); Ok(()) }
23.043478
90
0.615094
1a31aaa4ab30f53528c107dd0590fb1de9bd29e7
4,356
use enum_map::{enum_map, Enum, EnumMap}; pub struct Keyboard { key_states: EnumMap<Key, KeyState>, } /// Emulates the C64 keyboard scanning matrix. /// /// TODO: Support multiple key presses. /// TODO: Support the RESTORE key. /// TODO: Emulate ghosting. impl Keyboard { pub fn new() -> Self { Self { key_states: enum_map!(_ => KeyState::Released), } } pub fn set_key_state(&mut self, key: Key, state: KeyState) { self.key_states[key] = state; } /// Simulates probing the keyboard state with given column bit mask. Returns /// row states as bits. The bit layout corresponds to appropriate CIA's port /// registers. pub fn scan(&self, mask: u8) -> u8 { for i in 0..=7 { let column_bit = 1 << i; if mask & column_bit == 0 { for j in 0..=7 { if self.key_states[KEY_MATRIX[i][j]] == KeyState::Pressed { return !(1 << j); } } } } return 0xff; } } #[derive(Enum, Clone, Copy)] pub enum Key { LeftArrow, D1, D2, D3, D4, D5, D6, D7, D8, D9, D0, Plus, Minus, Pound, ClrHome, InstDel, Ctrl, Q, W, E, R, T, Y, U, I, O, P, At, Asterisk, UpArrow, Restore, RunStop, ShiftLock, A, S, D, F, G, H, J, K, L, Colon, Semicolon, Equals, Return, Commodore, LShift, Z, X, C, V, B, N, M, Comma, Period, Slash, RShift, CrsrUpDown, CrsrLeftRight, Space, F1, F3, F5, F7, } #[derive(PartialEq)] pub enum KeyState { Pressed, Released, } const KEY_MATRIX: [[Key; 8]; 8] = [ [ Key::InstDel, Key::Return, Key::CrsrLeftRight, Key::F7, Key::F1, Key::F3, Key::F5, Key::CrsrUpDown, ], [ Key::D3, Key::W, Key::A, Key::D4, Key::Z, Key::S, Key::E, Key::LShift, ], [ Key::D5, Key::R, Key::D, Key::D6, Key::C, Key::F, Key::T, Key::X, ], [ Key::D7, Key::Y, Key::G, Key::D8, Key::B, Key::H, Key::U, Key::V, ], [ Key::D9, Key::I, Key::J, Key::D0, Key::M, Key::K, Key::O, Key::N, ], [ Key::Plus, Key::P, Key::L, Key::Minus, Key::Period, Key::Colon, Key::At, Key::Comma, ], [ Key::Pound, Key::Asterisk, Key::Semicolon, Key::ClrHome, Key::RShift, Key::Equals, Key::UpArrow, Key::Slash, ], [ Key::D1, Key::LeftArrow, Key::Ctrl, Key::D2, Key::Space, Key::Commodore, Key::Q, Key::RunStop, ], ]; #[cfg(test)] mod tests { use super::*; fn scan_all_columns(keyboard: &Keyboard) -> [u8; 8] { let masks = [ 0b0111_1111, 0b1011_1111, 0b1101_1111, 0b1110_1111, 0b1111_0111, 0b1111_1011, 0b1111_1101, 0b1111_1110, ]; let mut result = [0; 8]; for (i, mask) in masks.into_iter().enumerate() { result[i] = keyboard.scan(mask); } return result; } #[test] fn single_key_presses() { let mut k = Keyboard::new(); k.set_key_state(Key::R, KeyState::Pressed); assert_eq!( scan_all_columns(&k), [!0, !0, !0, !0, !0, 0b1111_1101, !0, !0] ); k.set_key_state(Key::R, KeyState::Released); k.set_key_state(Key::U, KeyState::Pressed); assert_eq!( scan_all_columns(&k), [!0, !0, !0, !0, 0b1011_1111, !0, !0, !0] ); k.set_key_state(Key::U, KeyState::Released); k.set_key_state(Key::N, KeyState::Pressed); assert_eq!( scan_all_columns(&k), [!0, !0, !0, 0b0111_1111, !0, !0, !0, !0] ); } }
17.354582
80
0.429752
03337a7c263ebd7ec10316cb1fb896c62eefa6da
832
/* * * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LolCatalogItemCost { #[serde(rename = "cost", skip_serializing_if = "Option::is_none")] pub cost: Option<i64>, #[serde(rename = "currency", skip_serializing_if = "Option::is_none")] pub currency: Option<String>, #[serde(rename = "discount", skip_serializing_if = "Option::is_none")] pub discount: Option<f32>, } impl LolCatalogItemCost { pub fn new() -> LolCatalogItemCost { LolCatalogItemCost { cost: None, currency: None, discount: None, } } }
23.771429
109
0.645433
26d7b986e44c4e4712530d7d10ed1747c13f9aa1
28,714
use std::collections::HashMap; use std::cell::RefCell; use std::default::Default; use std::collections::BTreeMap; use serde_json as json; use std::io; use std::fs; use std::mem; use std::thread::sleep; use crate::client; // ############## // UTILITIES ### // ############ // ######## // HUB ### // ###### /// Central instance to access all AbusiveExperienceReport related resource activities /// /// # Examples /// /// Instantiate a new hub /// /// ```test_harness,no_run /// extern crate hyper; /// extern crate hyper_rustls; /// extern crate google_abusiveexperiencereport1 as abusiveexperiencereport1; /// use abusiveexperiencereport1::{Result, Error}; /// # async fn dox() { /// use std::default::Default; /// use abusiveexperiencereport1::{AbusiveExperienceReport, oauth2, hyper, hyper_rustls}; /// /// // Get an ApplicationSecret instance by some means. It contains the `client_id` and /// // `client_secret`, among other things. /// let secret: oauth2::ApplicationSecret = Default::default(); /// // Instantiate the authenticator. It will choose a suitable authentication flow for you, /// // unless you replace `None` with the desired Flow. /// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about /// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and /// // retrieve them from storage. /// let auth = oauth2::InstalledFlowAuthenticator::builder( /// secret, /// oauth2::InstalledFlowReturnMethod::HTTPRedirect, /// ).build().await.unwrap(); /// let mut hub = AbusiveExperienceReport::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth); /// // You can configure optional parameters by calling the respective setters at will, and /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.sites().get("name") /// .doit().await; /// /// match result { /// Err(e) => match e { /// // The Error enum provides details about what exactly happened. /// // You can also just use its `Debug`, `Display` or `Error` traits /// Error::HttpError(_) /// |Error::Io(_) /// |Error::MissingAPIKey /// |Error::MissingToken(_) /// |Error::Cancelled /// |Error::UploadSizeLimitExceeded(_, _) /// |Error::Failure(_) /// |Error::BadRequest(_) /// |Error::FieldClash(_) /// |Error::JsonDecodeError(_, _) => println!("{}", e), /// }, /// Ok(res) => println!("Success: {:?}", res), /// } /// # } /// ``` #[derive(Clone)] pub struct AbusiveExperienceReport<> { pub client: hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>, pub auth: oauth2::authenticator::Authenticator<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>>, _user_agent: String, _base_url: String, _root_url: String, } impl<'a, > client::Hub for AbusiveExperienceReport<> {} impl<'a, > AbusiveExperienceReport<> { pub fn new(client: hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>, authenticator: oauth2::authenticator::Authenticator<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>>) -> AbusiveExperienceReport<> { AbusiveExperienceReport { client, auth: authenticator, _user_agent: "google-api-rust-client/3.0.0".to_string(), _base_url: "https://abusiveexperiencereport.googleapis.com/".to_string(), _root_url: "https://abusiveexperiencereport.googleapis.com/".to_string(), } } pub fn sites(&'a self) -> SiteMethods<'a> { SiteMethods { hub: &self } } pub fn violating_sites(&'a self) -> ViolatingSiteMethods<'a> { ViolatingSiteMethods { hub: &self } } /// Set the user-agent header field to use in all requests to the server. /// It defaults to `google-api-rust-client/3.0.0`. /// /// Returns the previously set user-agent. pub fn user_agent(&mut self, agent_name: String) -> String { mem::replace(&mut self._user_agent, agent_name) } /// Set the base url to use in all requests to the server. /// It defaults to `https://abusiveexperiencereport.googleapis.com/`. /// /// Returns the previously set base url. pub fn base_url(&mut self, new_base_url: String) -> String { mem::replace(&mut self._base_url, new_base_url) } /// Set the root url to use in all requests to the server. /// It defaults to `https://abusiveexperiencereport.googleapis.com/`. /// /// Returns the previously set root url. pub fn root_url(&mut self, new_root_url: String) -> String { mem::replace(&mut self._root_url, new_root_url) } } // ############ // SCHEMAS ### // ########## /// Response message for GetSiteSummary. /// /// # Activities /// /// This type is used in activities, which are methods you may call on this type or where this type is involved in. /// The list links the activity name, along with information about where it is used (one of *request* and *response*). /// /// * [get sites](SiteGetCall) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct SiteSummaryResponse { /// The site's Abusive Experience Report status. #[serde(rename="abusiveStatus")] pub abusive_status: Option<String>, /// The time at which [enforcement](https://support.google.com/webtools/answer/7538608) against the site began or will begin. Not set when the filter_status is OFF. #[serde(rename="enforcementTime")] pub enforcement_time: Option<String>, /// The site's [enforcement status](https://support.google.com/webtools/answer/7538608). #[serde(rename="filterStatus")] pub filter_status: Option<String>, /// The time at which the site's status last changed. #[serde(rename="lastChangeTime")] pub last_change_time: Option<String>, /// A link to the full Abusive Experience Report for the site. Not set in ViolatingSitesResponse. Note that you must complete the [Search Console verification process](https://support.google.com/webmasters/answer/9008080) for the site before you can access the full report. #[serde(rename="reportUrl")] pub report_url: Option<String>, /// The name of the reviewed site, e.g. `google.com`. #[serde(rename="reviewedSite")] pub reviewed_site: Option<String>, /// Whether the site is currently under review. #[serde(rename="underReview")] pub under_review: Option<bool>, } impl client::ResponseResult for SiteSummaryResponse {} /// Response message for ListViolatingSites. /// /// # Activities /// /// This type is used in activities, which are methods you may call on this type or where this type is involved in. /// The list links the activity name, along with information about where it is used (one of *request* and *response*). /// /// * [list violating sites](ViolatingSiteListCall) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct ViolatingSitesResponse { /// The list of violating sites. #[serde(rename="violatingSites")] pub violating_sites: Option<Vec<SiteSummaryResponse>>, } impl client::ResponseResult for ViolatingSitesResponse {} // ################### // MethodBuilders ### // ################# /// A builder providing access to all methods supported on *site* resources. /// It is not used directly, but through the `AbusiveExperienceReport` hub. /// /// # Example /// /// Instantiate a resource builder /// /// ```test_harness,no_run /// extern crate hyper; /// extern crate hyper_rustls; /// extern crate google_abusiveexperiencereport1 as abusiveexperiencereport1; /// /// # async fn dox() { /// use std::default::Default; /// use abusiveexperiencereport1::{AbusiveExperienceReport, oauth2, hyper, hyper_rustls}; /// /// let secret: oauth2::ApplicationSecret = Default::default(); /// let auth = oauth2::InstalledFlowAuthenticator::builder( /// secret, /// oauth2::InstalledFlowReturnMethod::HTTPRedirect, /// ).build().await.unwrap(); /// let mut hub = AbusiveExperienceReport::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth); /// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* /// // like `get(...)` /// // to build up your call. /// let rb = hub.sites(); /// # } /// ``` pub struct SiteMethods<'a> where { hub: &'a AbusiveExperienceReport<>, } impl<'a> client::MethodsBuilder for SiteMethods<'a> {} impl<'a> SiteMethods<'a> { /// Create a builder to help you perform the following task: /// /// Gets a site's Abusive Experience Report summary. /// /// # Arguments /// /// * `name` - Required. The name of the site whose summary to get, e.g. `sites/http%3A%2F%2Fwww.google.com%2F`. Format: `sites/{site}` pub fn get(&self, name: &str) -> SiteGetCall<'a> { SiteGetCall { hub: self.hub, _name: name.to_string(), _delegate: Default::default(), _additional_params: Default::default(), } } } /// A builder providing access to all methods supported on *violatingSite* resources. /// It is not used directly, but through the `AbusiveExperienceReport` hub. /// /// # Example /// /// Instantiate a resource builder /// /// ```test_harness,no_run /// extern crate hyper; /// extern crate hyper_rustls; /// extern crate google_abusiveexperiencereport1 as abusiveexperiencereport1; /// /// # async fn dox() { /// use std::default::Default; /// use abusiveexperiencereport1::{AbusiveExperienceReport, oauth2, hyper, hyper_rustls}; /// /// let secret: oauth2::ApplicationSecret = Default::default(); /// let auth = oauth2::InstalledFlowAuthenticator::builder( /// secret, /// oauth2::InstalledFlowReturnMethod::HTTPRedirect, /// ).build().await.unwrap(); /// let mut hub = AbusiveExperienceReport::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth); /// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* /// // like `list(...)` /// // to build up your call. /// let rb = hub.violating_sites(); /// # } /// ``` pub struct ViolatingSiteMethods<'a> where { hub: &'a AbusiveExperienceReport<>, } impl<'a> client::MethodsBuilder for ViolatingSiteMethods<'a> {} impl<'a> ViolatingSiteMethods<'a> { /// Create a builder to help you perform the following task: /// /// Lists sites that are failing in the Abusive Experience Report. pub fn list(&self) -> ViolatingSiteListCall<'a> { ViolatingSiteListCall { hub: self.hub, _delegate: Default::default(), _additional_params: Default::default(), } } } // ################### // CallBuilders ### // ################# /// Gets a site's Abusive Experience Report summary. /// /// A builder for the *get* method supported by a *site* resource. /// It is not used directly, but through a `SiteMethods` instance. /// /// # Example /// /// Instantiate a resource method builder /// /// ```test_harness,no_run /// # extern crate hyper; /// # extern crate hyper_rustls; /// # extern crate google_abusiveexperiencereport1 as abusiveexperiencereport1; /// # async fn dox() { /// # use std::default::Default; /// # use abusiveexperiencereport1::{AbusiveExperienceReport, oauth2, hyper, hyper_rustls}; /// /// # let secret: oauth2::ApplicationSecret = Default::default(); /// # let auth = oauth2::InstalledFlowAuthenticator::builder( /// # secret, /// # oauth2::InstalledFlowReturnMethod::HTTPRedirect, /// # ).build().await.unwrap(); /// # let mut hub = AbusiveExperienceReport::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth); /// // You can configure optional parameters by calling the respective setters at will, and /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.sites().get("name") /// .doit().await; /// # } /// ``` pub struct SiteGetCall<'a> where { hub: &'a AbusiveExperienceReport<>, _name: String, _delegate: Option<&'a mut dyn client::Delegate>, _additional_params: HashMap<String, String>, } impl<'a> client::CallBuilder for SiteGetCall<'a> {} impl<'a> SiteGetCall<'a> { /// Perform the operation you have build so far. pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, SiteSummaryResponse)> { use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET}; use std::io::{Read, Seek}; use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION}; use client::ToParts; let mut dd = client::DefaultDelegate; let mut dlg: &mut dyn client::Delegate = match self._delegate { Some(d) => d, None => &mut dd }; dlg.begin(client::MethodInfo { id: "abusiveexperiencereport.sites.get", http_method: hyper::Method::GET }); let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len()); params.push(("name", self._name.to_string())); for &field in ["alt", "name"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(client::Error::FieldClash(field)); } } for (name, value) in self._additional_params.iter() { params.push((&name, value.clone())); } params.push(("alt", "json".to_string())); let mut url = self.hub._base_url.clone() + "v1/{+name}"; let key = dlg.api_key(); match key { Some(value) => params.push(("key", value)), None => { dlg.finished(false); return Err(client::Error::MissingAPIKey) } } for &(find_this, param_name) in [("{+name}", "name")].iter() { let mut replace_with = String::new(); for &(name, ref value) in params.iter() { if name == param_name { replace_with = value.to_string(); break; } } if find_this.as_bytes()[1] == '+' as u8 { replace_with = percent_encode(replace_with.as_bytes(), DEFAULT_ENCODE_SET).to_string(); } url = url.replace(find_this, &replace_with); } { let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1); for param_name in ["name"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } } for &index in indices_for_removal.iter() { params.remove(index); } } let url = url::Url::parse_with_params(&url, params).unwrap(); loop { let mut req_result = { let client = &self.hub.client; dlg.pre_request(); let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string()) .header(USER_AGENT, self.hub._user_agent.clone()); let request = req_builder .body(hyper::body::Body::empty()); client.request(request.unwrap()).await }; match req_result { Err(err) => { if let client::Retry::After(d) = dlg.http_error(&err) { sleep(d); continue; } dlg.finished(false); return Err(client::Error::HttpError(err)) } Ok(mut res) => { if !res.status().is_success() { let res_body_string = client::get_body_as_string(res.body_mut()).await; let (parts, _) = res.into_parts(); let body = hyper::Body::from(res_body_string.clone()); let restored_response = hyper::Response::from_parts(parts, body); let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok(); if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) { sleep(d); continue; } dlg.finished(false); return match server_response { Some(error_value) => Err(client::Error::BadRequest(error_value)), None => Err(client::Error::Failure(restored_response)), } } let result_value = { let res_body_string = client::get_body_as_string(res.body_mut()).await; match json::from_str(&res_body_string) { Ok(decoded) => (res, decoded), Err(err) => { dlg.response_json_decode_error(&res_body_string, &err); return Err(client::Error::JsonDecodeError(res_body_string, err)); } } }; dlg.finished(true); return Ok(result_value) } } } } /// Required. The name of the site whose summary to get, e.g. `sites/http%3A%2F%2Fwww.google.com%2F`. Format: `sites/{site}` /// /// Sets the *name* path property to the given value. /// /// Even though the property as already been set when instantiating this call, /// we provide this method for API completeness. pub fn name(mut self, new_value: &str) -> SiteGetCall<'a> { self._name = new_value.to_string(); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong /// while executing the actual API request. /// /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> SiteGetCall<'a> { self._delegate = Some(new_value); self } /// Set any additional parameter of the query string used in the request. /// It should be used to set parameters which are not yet available through their own /// setters. /// /// Please note that this method must not be used to set any of the known parameters /// which have their own setter method. If done anyway, the request will fail. /// /// # Additional Parameters /// /// * *$.xgafv* (query-string) - V1 error format. /// * *access_token* (query-string) - OAuth access token. /// * *alt* (query-string) - Data format for response. /// * *callback* (query-string) - JSONP /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). pub fn param<T>(mut self, name: T, value: T) -> SiteGetCall<'a> where T: AsRef<str> { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self } } /// Lists sites that are failing in the Abusive Experience Report. /// /// A builder for the *list* method supported by a *violatingSite* resource. /// It is not used directly, but through a `ViolatingSiteMethods` instance. /// /// # Example /// /// Instantiate a resource method builder /// /// ```test_harness,no_run /// # extern crate hyper; /// # extern crate hyper_rustls; /// # extern crate google_abusiveexperiencereport1 as abusiveexperiencereport1; /// # async fn dox() { /// # use std::default::Default; /// # use abusiveexperiencereport1::{AbusiveExperienceReport, oauth2, hyper, hyper_rustls}; /// /// # let secret: oauth2::ApplicationSecret = Default::default(); /// # let auth = oauth2::InstalledFlowAuthenticator::builder( /// # secret, /// # oauth2::InstalledFlowReturnMethod::HTTPRedirect, /// # ).build().await.unwrap(); /// # let mut hub = AbusiveExperienceReport::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth); /// // You can configure optional parameters by calling the respective setters at will, and /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.violating_sites().list() /// .doit().await; /// # } /// ``` pub struct ViolatingSiteListCall<'a> where { hub: &'a AbusiveExperienceReport<>, _delegate: Option<&'a mut dyn client::Delegate>, _additional_params: HashMap<String, String>, } impl<'a> client::CallBuilder for ViolatingSiteListCall<'a> {} impl<'a> ViolatingSiteListCall<'a> { /// Perform the operation you have build so far. pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, ViolatingSitesResponse)> { use std::io::{Read, Seek}; use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION}; use client::ToParts; let mut dd = client::DefaultDelegate; let mut dlg: &mut dyn client::Delegate = match self._delegate { Some(d) => d, None => &mut dd }; dlg.begin(client::MethodInfo { id: "abusiveexperiencereport.violatingSites.list", http_method: hyper::Method::GET }); let mut params: Vec<(&str, String)> = Vec::with_capacity(2 + self._additional_params.len()); for &field in ["alt"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(client::Error::FieldClash(field)); } } for (name, value) in self._additional_params.iter() { params.push((&name, value.clone())); } params.push(("alt", "json".to_string())); let mut url = self.hub._base_url.clone() + "v1/violatingSites"; let key = dlg.api_key(); match key { Some(value) => params.push(("key", value)), None => { dlg.finished(false); return Err(client::Error::MissingAPIKey) } } let url = url::Url::parse_with_params(&url, params).unwrap(); loop { let mut req_result = { let client = &self.hub.client; dlg.pre_request(); let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string()) .header(USER_AGENT, self.hub._user_agent.clone()); let request = req_builder .body(hyper::body::Body::empty()); client.request(request.unwrap()).await }; match req_result { Err(err) => { if let client::Retry::After(d) = dlg.http_error(&err) { sleep(d); continue; } dlg.finished(false); return Err(client::Error::HttpError(err)) } Ok(mut res) => { if !res.status().is_success() { let res_body_string = client::get_body_as_string(res.body_mut()).await; let (parts, _) = res.into_parts(); let body = hyper::Body::from(res_body_string.clone()); let restored_response = hyper::Response::from_parts(parts, body); let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok(); if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) { sleep(d); continue; } dlg.finished(false); return match server_response { Some(error_value) => Err(client::Error::BadRequest(error_value)), None => Err(client::Error::Failure(restored_response)), } } let result_value = { let res_body_string = client::get_body_as_string(res.body_mut()).await; match json::from_str(&res_body_string) { Ok(decoded) => (res, decoded), Err(err) => { dlg.response_json_decode_error(&res_body_string, &err); return Err(client::Error::JsonDecodeError(res_body_string, err)); } } }; dlg.finished(true); return Ok(result_value) } } } } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong /// while executing the actual API request. /// /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> ViolatingSiteListCall<'a> { self._delegate = Some(new_value); self } /// Set any additional parameter of the query string used in the request. /// It should be used to set parameters which are not yet available through their own /// setters. /// /// Please note that this method must not be used to set any of the known parameters /// which have their own setter method. If done anyway, the request will fail. /// /// # Additional Parameters /// /// * *$.xgafv* (query-string) - V1 error format. /// * *access_token* (query-string) - OAuth access token. /// * *alt* (query-string) - Data format for response. /// * *callback* (query-string) - JSONP /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). pub fn param<T>(mut self, name: T, value: T) -> ViolatingSiteListCall<'a> where T: AsRef<str> { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self } }
39.496561
278
0.596329
22cd5472f4d880c662bc6923cbbc3798034121ec
812
use super::Context; use crate::db::models::{Slot, User}; use juniper::{graphql_object, FieldResult, ID}; pub struct QueryRoot; pub fn parse_id(id: ID) -> i32 { let str = id.to_string(); str.parse().unwrap() } #[graphql_object(context = Context)] impl QueryRoot { pub fn apiVersion() -> &'static str { "1.0" } pub fn user(db: &Context, id: ID) -> Option<User> { User::find(&db.dbpool, parse_id(id)).ok() } pub fn users(db: &Context) -> FieldResult<Vec<User>> { let res = User::all(&db.dbpool)?; Ok(res) } pub fn slot(db: &Context, id: ID) -> Option<Slot> { Slot::find(&db.dbpool, parse_id(id)).ok() } pub fn slots(db: &Context) -> FieldResult<Vec<Slot>> { let res = Slot::all(&db.dbpool)?; Ok(res) } }
22.555556
58
0.564039
6aa41f498516733ca9e2dd5c660681a261feb4b0
3,292
use hir::Substs; use crate::completion::{CompletionContext, Completions}; /// Complete fields in fields literals. pub(super) fn complete_struct_literal(acc: &mut Completions, ctx: &CompletionContext) { let (ty, variant) = match ctx.struct_lit_syntax.as_ref().and_then(|it| { Some(( ctx.analyzer.type_of(ctx.db, &it.clone().into())?, ctx.analyzer.resolve_struct_literal(it)?, )) }) { Some(it) => it, _ => return, }; let substs = &ty.substs().unwrap_or_else(Substs::empty); for field in variant.fields(ctx.db) { acc.add_field(ctx, field, substs); } } #[cfg(test)] mod tests { use crate::completion::{do_completion, CompletionItem, CompletionKind}; use insta::assert_debug_snapshot_matches; fn complete(code: &str) -> Vec<CompletionItem> { do_completion(code, CompletionKind::Reference) } #[test] fn test_struct_literal_field() { let completions = complete( r" struct A { the_field: u32 } fn foo() { A { the<|> } } ", ); assert_debug_snapshot_matches!(completions, @r###" ⋮[ ⋮ CompletionItem { ⋮ label: "the_field", ⋮ source_range: [83; 86), ⋮ delete: [83; 86), ⋮ insert: "the_field", ⋮ kind: Field, ⋮ detail: "u32", ⋮ }, ⋮] "###); } #[test] fn test_struct_literal_enum_variant() { let completions = complete( r" enum E { A { a: u32 } } fn foo() { let _ = E::A { <|> } } ", ); assert_debug_snapshot_matches!(completions, @r###" ⋮[ ⋮ CompletionItem { ⋮ label: "a", ⋮ source_range: [119; 119), ⋮ delete: [119; 119), ⋮ insert: "a", ⋮ kind: Field, ⋮ detail: "u32", ⋮ }, ⋮] "###); } #[test] fn test_struct_literal_two_structs() { let completions = complete( r" struct A { a: u32 } struct B { b: u32 } fn foo() { let _: A = B { <|> } } ", ); assert_debug_snapshot_matches!(completions, @r###" ⋮[ ⋮ CompletionItem { ⋮ label: "b", ⋮ source_range: [119; 119), ⋮ delete: [119; 119), ⋮ insert: "b", ⋮ kind: Field, ⋮ detail: "u32", ⋮ }, ⋮] "###); } #[test] fn test_struct_literal_generic_struct() { let completions = complete( r" struct A<T> { a: T } fn foo() { let _: A<u32> = A { <|> } } ", ); assert_debug_snapshot_matches!(completions, @r###" ⋮[ ⋮ CompletionItem { ⋮ label: "a", ⋮ source_range: [93; 93), ⋮ delete: [93; 93), ⋮ insert: "a", ⋮ kind: Field, ⋮ detail: "u32", ⋮ }, ⋮] "###); } }
24.75188
87
0.424058
26c84710363f1c72a7c6751afcac2018f2f6645b
1,761
//! Shared helpers for JSON-RPC Servers. use futures_channel::mpsc; use jsonrpsee_types::v2::error::{INTERNAL_ERROR_CODE, INTERNAL_ERROR_MSG}; use jsonrpsee_types::v2::{JsonRpcError, JsonRpcErrorParams, JsonRpcResponse, RpcParams, TwoPointZero}; use rustc_hash::FxHashMap; use serde::Serialize; use serde_json::value::RawValue; /// Connection ID. pub type ConnectionId = usize; /// Sender. pub type RpcSender<'a> = &'a mpsc::UnboundedSender<String>; /// RPC ID. pub type RpcId<'a> = Option<&'a RawValue>; /// Method registered in the server. pub type Method = Box<dyn Send + Sync + Fn(RpcId, RpcParams, RpcSender, ConnectionId) -> anyhow::Result<()>>; /// Methods registered in the Server. pub type Methods = FxHashMap<&'static str, Method>; /// Helper for sending JSON-RPC responses to the client pub fn send_response(id: RpcId, tx: RpcSender, result: impl Serialize) { let json = match serde_json::to_string(&JsonRpcResponse { jsonrpc: TwoPointZero, id, result }) { Ok(json) => json, Err(err) => { log::error!("Error serializing response: {:?}", err); return send_error(id, tx, INTERNAL_ERROR_CODE, INTERNAL_ERROR_MSG); } }; if let Err(err) = tx.unbounded_send(json) { log::error!("Error sending response to the client: {:?}", err) } } /// Helper for sending JSON-RPC errors to the client pub fn send_error(id: RpcId, tx: RpcSender, code: i32, message: &str) { let json = match serde_json::to_string(&JsonRpcError { jsonrpc: TwoPointZero, error: JsonRpcErrorParams { code, message }, id, }) { Ok(json) => json, Err(err) => { log::error!("Error serializing error message: {:?}", err); return; } }; if let Err(err) = tx.unbounded_send(json) { log::error!("Error sending response to the client: {:?}", err) } }
31.446429
109
0.696195
5b983cacba0c2b52b095ff15ec348d52b2795305
40
fraptor ICON "misc/icons/Factor.ico"
13.333333
37
0.725
ff781bc008449b2fa14d03b025844d7ac0257d94
934
#[macro_use] extern crate yaserde_derive; use yaserde::de::from_str; fn init() { let _ = env_logger::builder().is_test(true).try_init(); } #[test] fn de_no_content() { init(); #[derive(YaDeserialize, PartialEq, Debug)] #[yaserde(root = "book")] pub struct Book { author: String, title: String, } let content = ""; let loaded: Result<Book, String> = from_str(content); assert_eq!( loaded, Err("Unexpected end of stream: no root element found".to_owned()) ); } #[test] fn de_wrong_end_balise() { init(); #[derive(YaDeserialize, PartialEq, Debug)] #[yaserde(root = "book")] pub struct Book { author: String, title: String, } let content = "<book><author>Antoine de Saint-Exupéry<title>Little prince</title></book>"; let loaded: Result<Book, String> = from_str(content); assert_eq!( loaded, Err("Unexpected closing tag: book, expected author".to_owned()) ); }
19.87234
92
0.648822
726a5c1addc08c10883e1fae3650565adc981584
402
// WARNING: THIS CODE IS AUTOGENERATED. // DO NOT EDIT!!! use crate::types::VoiceChatParticipantsInvited; impl VoiceChatParticipantsInvited { /// This function creates an empty struct for the object VoiceChatParticipantsInvited. pub fn new() -> Self { Self { users: None } } } impl Default for VoiceChatParticipantsInvited { fn default() -> Self { Self::new() } }
23.647059
90
0.674129
913f3b1464f505e8706bf63c7726ac0ab59db472
223
#![no_std] #![no_main] mod vga; use core::panic::PanicInfo; #[panic_handler] fn panic(_info: &PanicInfo) -> ! { loop {} } #[no_mangle] pub extern "C" fn _start() { println!("Hello World{}", "!"); loop {} }
11.736842
35
0.565022
612b6ac3f64c7b321ebd7cc1c2421e32fcaaea26
54
pub use self::mm::{MatrixMarketReader}; pub mod mm;
10.8
39
0.703704
619f7c22c4074c1864749110e22bda11d73bad72
12,662
// Any copyright to the test code below this comment is dedicated to the // Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ //use super::super::testing::*; //use super::super::*; use encoding_rs::*; use crate::testing::*; fn decode_iso_2022_jp(bytes: &[u8], expect: &str) { decode(ISO_2022_JP, bytes, expect); } fn encode_iso_2022_jp(string: &str, expect: &[u8]) { encode(ISO_2022_JP, string, expect); } //#[test] pub fn test_iso_2022_jp_decode() { // Empty decode_iso_2022_jp(b"", &""); // ASCII decode_iso_2022_jp(b"\x61\x62", "\u{0061}\u{0062}"); decode_iso_2022_jp(b"\x7F\x0E\x0F", "\u{007F}\u{FFFD}\u{FFFD}"); // Partial escapes decode_iso_2022_jp(b"\x1B", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B$", "\u{FFFD}$"); decode_iso_2022_jp(b"\x1B(", "\u{FFFD}("); decode_iso_2022_jp(b"\x1B.", "\u{FFFD}."); // ISO escapes decode_iso_2022_jp(b"\x1B(B", ""); // ASCII decode_iso_2022_jp(b"\x1B(J", ""); // Roman decode_iso_2022_jp(b"\x1B$@", ""); // 0208 decode_iso_2022_jp(b"\x1B$B", ""); // 0208 decode_iso_2022_jp(b"\x1B$(D", "\u{FFFD}$(D"); // 2012 decode_iso_2022_jp(b"\x1B$A", "\u{FFFD}$A"); // GB2312 decode_iso_2022_jp(b"\x1B$(C", "\u{FFFD}$(C"); // KR decode_iso_2022_jp(b"\x1B.A", "\u{FFFD}.A"); // Latin-1 decode_iso_2022_jp(b"\x1B.F", "\u{FFFD}.F"); // Greek decode_iso_2022_jp(b"\x1B(I", ""); // Half-width Katakana decode_iso_2022_jp(b"\x1B$(O", "\u{FFFD}$(O"); // 2013 decode_iso_2022_jp(b"\x1B$(P", "\u{FFFD}$(P"); // 2013 decode_iso_2022_jp(b"\x1B$(Q", "\u{FFFD}$(Q"); // 2013 decode_iso_2022_jp(b"\x1B$)C", "\u{FFFD}$)C"); // KR decode_iso_2022_jp(b"\x1B$)A", "\u{FFFD}$)A"); // GB2312 decode_iso_2022_jp(b"\x1B$)G", "\u{FFFD}$)G"); // CNS decode_iso_2022_jp(b"\x1B$*H", "\u{FFFD}$*H"); // CNS decode_iso_2022_jp(b"\x1B$)E", "\u{FFFD}$)E"); // IR decode_iso_2022_jp(b"\x1B$+I", "\u{FFFD}$+I"); // CNS decode_iso_2022_jp(b"\x1B$+J", "\u{FFFD}$+J"); // CNS decode_iso_2022_jp(b"\x1B$+K", "\u{FFFD}$+K"); // CNS decode_iso_2022_jp(b"\x1B$+L", "\u{FFFD}$+L"); // CNS decode_iso_2022_jp(b"\x1B$+M", "\u{FFFD}$+M"); // CNS decode_iso_2022_jp(b"\x1B$(@", "\u{FFFD}$(@"); // 0208 decode_iso_2022_jp(b"\x1B$(A", "\u{FFFD}$(A"); // GB2312 decode_iso_2022_jp(b"\x1B$(B", "\u{FFFD}$(B"); // 0208 decode_iso_2022_jp(b"\x1B%G", "\u{FFFD}%G"); // UTF-8 // ASCII decode_iso_2022_jp(b"\x5B", "\u{005B}"); decode_iso_2022_jp(b"\x5C", "\u{005C}"); decode_iso_2022_jp(b"\x7E", "\u{007E}"); decode_iso_2022_jp(b"\x0E", "\u{FFFD}"); decode_iso_2022_jp(b"\x0F", "\u{FFFD}"); decode_iso_2022_jp(b"\x80", "\u{FFFD}"); decode_iso_2022_jp(b"\xFF", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(B\x5B", "\u{005B}"); decode_iso_2022_jp(b"\x1B(B\x5C", "\u{005C}"); decode_iso_2022_jp(b"\x1B(B\x7E", "\u{007E}"); decode_iso_2022_jp(b"\x1B(B\x0E", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(B\x0F", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(B\x80", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(B\xFF", "\u{FFFD}"); // Roman decode_iso_2022_jp(b"\x1B(J\x5B", "\u{005B}"); decode_iso_2022_jp(b"\x1B(J\x5C", "\u{00A5}"); decode_iso_2022_jp(b"\x1B(J\x7E", "\u{203E}"); decode_iso_2022_jp(b"\x1B(J\x0E", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(J\x0F", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(J\x80", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(J\xFF", "\u{FFFD}"); // Katakana decode_iso_2022_jp(b"\x1B(I\x20", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(I\x21", "\u{FF61}"); decode_iso_2022_jp(b"\x1B(I\x5F", "\u{FF9F}"); decode_iso_2022_jp(b"\x1B(I\x60", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(I\x0E", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(I\x0F", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(I\x80", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(I\xFF", "\u{FFFD}"); // 0208 differences from 1978 to 1983 decode_iso_2022_jp(b"\x1B$@\x54\x64", "\u{58FA}"); decode_iso_2022_jp(b"\x1B$@\x44\x5B", "\u{58F7}"); decode_iso_2022_jp(b"\x1B$@\x74\x21", "\u{582F}"); decode_iso_2022_jp(b"\x1B$@\x36\x46", "\u{5C2D}"); decode_iso_2022_jp(b"\x1B$@\x28\x2E", "\u{250F}"); decode_iso_2022_jp(b"\x1B$B\x54\x64", "\u{58FA}"); decode_iso_2022_jp(b"\x1B$B\x44\x5B", "\u{58F7}"); decode_iso_2022_jp(b"\x1B$B\x74\x21", "\u{582F}"); decode_iso_2022_jp(b"\x1B$B\x36\x46", "\u{5C2D}"); decode_iso_2022_jp(b"\x1B$B\x28\x2E", "\u{250F}"); // Broken 0208 decode_iso_2022_jp(b"\x1B$B\x28\x41", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B$@\x80\x54\x64", "\u{FFFD}\u{58FA}"); decode_iso_2022_jp(b"\x1B$B\x28\x80", "\u{FFFD}"); // Transitions decode_iso_2022_jp(b"\x1B(B\x5C\x1B(J\x5C", "\u{005C}\u{00A5}"); decode_iso_2022_jp(b"\x1B(B\x5C\x1B(I\x21", "\u{005C}\u{FF61}"); decode_iso_2022_jp(b"\x1B(B\x5C\x1B$@\x54\x64", "\u{005C}\u{58FA}"); decode_iso_2022_jp(b"\x1B(B\x5C\x1B$B\x54\x64", "\u{005C}\u{58FA}"); decode_iso_2022_jp(b"\x1B(J\x5C\x1B(B\x5C", "\u{00A5}\u{005C}"); decode_iso_2022_jp(b"\x1B(J\x5C\x1B(I\x21", "\u{00A5}\u{FF61}"); decode_iso_2022_jp(b"\x1B(J\x5C\x1B$@\x54\x64", "\u{00A5}\u{58FA}"); decode_iso_2022_jp(b"\x1B(J\x5C\x1B$B\x54\x64", "\u{00A5}\u{58FA}"); decode_iso_2022_jp(b"\x1B(I\x21\x1B(J\x5C", "\u{FF61}\u{00A5}"); decode_iso_2022_jp(b"\x1B(I\x21\x1B(B\x5C", "\u{FF61}\u{005C}"); decode_iso_2022_jp(b"\x1B(I\x21\x1B$@\x54\x64", "\u{FF61}\u{58FA}"); decode_iso_2022_jp(b"\x1B(I\x21\x1B$B\x54\x64", "\u{FF61}\u{58FA}"); decode_iso_2022_jp(b"\x1B$@\x54\x64\x1B(J\x5C", "\u{58FA}\u{00A5}"); decode_iso_2022_jp(b"\x1B$@\x54\x64\x1B(I\x21", "\u{58FA}\u{FF61}"); decode_iso_2022_jp(b"\x1B$@\x54\x64\x1B(B\x5C", "\u{58FA}\u{005C}"); decode_iso_2022_jp(b"\x1B$@\x54\x64\x1B$B\x54\x64", "\u{58FA}\u{58FA}"); decode_iso_2022_jp(b"\x1B$B\x54\x64\x1B(J\x5C", "\u{58FA}\u{00A5}"); decode_iso_2022_jp(b"\x1B$B\x54\x64\x1B(I\x21", "\u{58FA}\u{FF61}"); decode_iso_2022_jp(b"\x1B$B\x54\x64\x1B$@\x54\x64", "\u{58FA}\u{58FA}"); decode_iso_2022_jp(b"\x1B$B\x54\x64\x1B(B\x5C", "\u{58FA}\u{005C}"); // Empty transitions decode_iso_2022_jp(b"\x1B(B\x1B(J", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(B\x1B(I", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(B\x1B$@", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(B\x1B$B", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(J\x1B(B", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(J\x1B(I", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(J\x1B$@", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(J\x1B$B", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(I\x1B(J", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(I\x1B(B", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(I\x1B$@", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B(I\x1B$B", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B$@\x1B(J", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B$@\x1B(I", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B$@\x1B(B", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B$@\x1B$B", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B$B\x1B(J", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B$B\x1B(I", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B$B\x1B$@", "\u{FFFD}"); decode_iso_2022_jp(b"\x1B$B\x1B(B", "\u{FFFD}"); // Transitions to self decode_iso_2022_jp(b"\x1B(B\x5C\x1B(B\x5C", "\u{005C}\u{005C}"); decode_iso_2022_jp(b"\x1B(J\x5C\x1B(J\x5C", "\u{00A5}\u{00A5}"); decode_iso_2022_jp(b"\x1B(I\x21\x1B(I\x21", "\u{FF61}\u{FF61}"); decode_iso_2022_jp(b"\x1B$@\x54\x64\x1B$@\x54\x64", "\u{58FA}\u{58FA}"); decode_iso_2022_jp(b"\x1B$B\x54\x64\x1B$B\x54\x64", "\u{58FA}\u{58FA}"); } //#[test] pub fn test_iso_2022_jp_encode() { // Empty encode_iso_2022_jp("", b""); // ASCII encode_iso_2022_jp("ab", b"ab"); encode_iso_2022_jp("\u{1F4A9}", b"&#128169;"); encode_iso_2022_jp("\x1B", b"&#65533;"); encode_iso_2022_jp("\x0E", b"&#65533;"); encode_iso_2022_jp("\x0F", b"&#65533;"); // Roman encode_iso_2022_jp("a\u{00A5}b", b"a\x1B(J\x5Cb\x1B(B"); encode_iso_2022_jp("a\u{203E}b", b"a\x1B(J\x7Eb\x1B(B"); encode_iso_2022_jp("a\u{00A5}b\x5C", b"a\x1B(J\x5Cb\x1B(B\x5C"); encode_iso_2022_jp("a\u{203E}b\x7E", b"a\x1B(J\x7Eb\x1B(B\x7E"); encode_iso_2022_jp("\u{00A5}\u{1F4A9}", b"\x1B(J\x5C&#128169;\x1B(B"); encode_iso_2022_jp("\u{00A5}\x1B", b"\x1B(J\x5C&#65533;\x1B(B"); encode_iso_2022_jp("\u{00A5}\x0E", b"\x1B(J\x5C&#65533;\x1B(B"); encode_iso_2022_jp("\u{00A5}\x0F", b"\x1B(J\x5C&#65533;\x1B(B"); encode_iso_2022_jp("\u{00A5}\u{58FA}", b"\x1B(J\x5C\x1B$B\x54\x64\x1B(B"); // Half-width Katakana encode_iso_2022_jp("\u{FF61}", b"\x1B$B\x21\x23\x1B(B"); encode_iso_2022_jp("\u{FF65}", b"\x1B$B\x21\x26\x1B(B"); encode_iso_2022_jp("\u{FF66}", b"\x1B$B\x25\x72\x1B(B"); encode_iso_2022_jp("\u{FF70}", b"\x1B$B\x21\x3C\x1B(B"); encode_iso_2022_jp("\u{FF9D}", b"\x1B$B\x25\x73\x1B(B"); encode_iso_2022_jp("\u{FF9E}", b"\x1B$B\x21\x2B\x1B(B"); encode_iso_2022_jp("\u{FF9F}", b"\x1B$B\x21\x2C\x1B(B"); // 0208 encode_iso_2022_jp("\u{58FA}", b"\x1B$B\x54\x64\x1B(B"); encode_iso_2022_jp("\u{58FA}\u{250F}", b"\x1B$B\x54\x64\x28\x2E\x1B(B"); encode_iso_2022_jp("\u{58FA}\u{1F4A9}", b"\x1B$B\x54\x64\x1B(B&#128169;"); encode_iso_2022_jp("\u{58FA}\x1B", b"\x1B$B\x54\x64\x1B(B&#65533;"); encode_iso_2022_jp("\u{58FA}\x0E", b"\x1B$B\x54\x64\x1B(B&#65533;"); encode_iso_2022_jp("\u{58FA}\x0F", b"\x1B$B\x54\x64\x1B(B&#65533;"); encode_iso_2022_jp("\u{58FA}\u{00A5}", b"\x1B$B\x54\x64\x1B(J\x5C\x1B(B"); encode_iso_2022_jp("\u{58FA}a", b"\x1B$B\x54\x64\x1B(Ba"); } //#[test] pub fn test_iso_2022_jp_decode_all() { let input = include_bytes!("test_data/iso_2022_jp_in.txt"); let expectation = include_str!("test_data/iso_2022_jp_in_ref.txt"); let (cow, had_errors) = ISO_2022_JP.decode_without_bom_handling(input); assert!(had_errors, "Should have had errors."); assert_eq!(&cow[..], expectation); } //#[test] pub fn test_iso_2022_jp_encode_all() { let input = include_str!("test_data/iso_2022_jp_out.txt"); let expectation = include_bytes!("test_data/iso_2022_jp_out_ref.txt"); let (cow, encoding, had_errors) = ISO_2022_JP.encode(input); assert!(!had_errors, "Should not have had errors."); assert_eq!(encoding, ISO_2022_JP); assert_eq!(&cow[..], &expectation[..]); } //#[test] pub fn test_iso_2022_jp_half_width_katakana_length() { let mut output = [0u8; 20]; let mut decoder = ISO_2022_JP.new_decoder(); { let (result, read, written) = decoder.decode_to_utf8_without_replacement(b"\x1B\x28\x49", &mut output, false); assert_eq!(result, DecoderResult::InputEmpty); assert_eq!(read, 3); assert_eq!(written, 0); } { let needed = decoder .max_utf8_buffer_length_without_replacement(1) .unwrap(); let (result, read, written) = decoder.decode_to_utf8_without_replacement(b"\x21", &mut output[..needed], true); assert_eq!(result, DecoderResult::InputEmpty); assert_eq!(read, 1); assert_eq!(written, 3); assert_eq!(output[0], 0xEF); assert_eq!(output[1], 0xBD); assert_eq!(output[2], 0xA1); } } //#[test] pub fn test_iso_2022_jp_length_after_escape() { let mut output = [0u16; 20]; let mut decoder = ISO_2022_JP.new_decoder(); { let (result, read, written, had_errors) = decoder.decode_to_utf16(b"\x1B", &mut output, false); assert_eq!(result, CoderResult::InputEmpty); assert_eq!(read, 1); assert_eq!(written, 0); assert!(!had_errors); } { let needed = decoder.max_utf16_buffer_length(1).unwrap(); let (result, read, written, had_errors) = decoder.decode_to_utf16(b"A", &mut output[..needed], true); assert_eq!(result, CoderResult::InputEmpty); assert_eq!(read, 1); assert_eq!(written, 2); assert!(had_errors); assert_eq!(output[0], 0xFFFD); assert_eq!(output[1], 0x0041); } } //#[test] pub fn test_iso_2022_jp_encode_from_two_low_surrogates() { let expectation = b"&#65533;&#65533;"; let mut output = [0u8; 40]; let mut encoder = ISO_2022_JP.new_encoder(); let (result, read, written, had_errors) = encoder.encode_from_utf16(&[0xDC00u16, 0xDEDEu16], &mut output[..], true); assert_eq!(result, CoderResult::InputEmpty); assert_eq!(read, 2); assert_eq!(written, expectation.len()); assert!(had_errors); assert_eq!(&output[..written], expectation); }
42.206667
93
0.613726
8764752372d7216a7dfdacfc2eb4f3e8882b6cef
4,809
use num; use std::io::Read; use std::convert::From; use std::net::{Ipv4Addr, Ipv6Addr}; use byteorder::{NetworkEndian, ReadBytesExt}; macro_rules! get { ($e:expr) => (match $e { Ok(val) => val, Err(_) => return None, }); } #[derive(Clone, Debug)] pub enum NetAddr { V4(Ipv4Addr), V6(Ipv6Addr), Name(String) } #[derive(Clone, Copy, PartialEq, FromPrimitive)] pub enum AuthMethod { Unauthorized = 0x00, GssApi = 0x01, UserPass = 0x02, Other, NoMethod = 0xff, } impl From<u8> for AuthMethod { fn from(x: u8) -> AuthMethod { match num::FromPrimitive::from_u8(x) { Some(method) => method, None => AuthMethod::Other, } } } pub struct AuthRequest { pub version: u8, pub methods: Vec<AuthMethod> } impl AuthRequest { pub fn parse<T: Read>(mut data: T) -> Option<AuthRequest> { let version = get!(data.read_u8()); let n_methods = get!(data.read_u8()); let methods: Vec<Option<AuthMethod>> = (0..n_methods).map(|_| Some(AuthMethod::from(get!(data.read_u8()))) ).collect(); if methods.contains(&None) { return None; } let methods = methods.into_iter().map(|x| x.unwrap()).collect(); Some(AuthRequest{ version, methods }) } } pub struct AuthReply { pub version: u8, pub method: AuthMethod } impl AuthReply { pub fn to_bytes(&self) -> [u8; 2] { if let AuthMethod::Other = self.method { panic!("Can not convert AuthMethod::Other to bytes!") } [self.version, self.method as u8] } } #[derive(Clone, Copy, FromPrimitive)] pub enum SocksCommand { Connect = 0x01, Bind = 0x02, Associate = 0x03 } pub struct SocksRequest { pub version: u8, pub command: SocksCommand, pub address: NetAddr, pub port: u16 } #[derive(Clone, Copy, FromPrimitive)] enum SocksAddrType { Ipv4 = 0x01, Name = 0x03, Ipv6 = 0x04 } impl SocksRequest { pub fn parse<T: Read>(mut data: T) -> Option<SocksRequest> { let version = get!(data.read_u8()); let command = num::FromPrimitive::from_u8(get!(data.read_u8()))?; let _reserved = get!(data.read_u8()); let address = match num::FromPrimitive::from_u8(get!(data.read_u8()))? { SocksAddrType::Ipv4 => NetAddr::V4(Ipv4Addr::from( get!(data.read_u32::<NetworkEndian>()))), SocksAddrType::Ipv6 => { NetAddr::V6(Ipv6Addr::from([ get!(data.read_u16::<NetworkEndian>()), get!(data.read_u16::<NetworkEndian>()), get!(data.read_u16::<NetworkEndian>()), get!(data.read_u16::<NetworkEndian>()), get!(data.read_u16::<NetworkEndian>()), get!(data.read_u16::<NetworkEndian>()), get!(data.read_u16::<NetworkEndian>()), get!(data.read_u16::<NetworkEndian>()), ])) }, SocksAddrType::Name => { let len = get!(data.read_u8()); let bytes_opt: Vec<Option<u8>> = (0..len).map( |_| Some(get!(data.read_u8()))).collect(); if bytes_opt.contains(&None) { return None; } let bytes = bytes_opt.into_iter().map(|x| x.unwrap()).collect(); NetAddr::Name(get!(String::from_utf8(bytes))) }, }; let port = get!(data.read_u16::<NetworkEndian>()); Some(SocksRequest{version, command, address, port}) } } #[derive(Clone, Copy)] pub enum SocksReplyStatus { Success = 0x00, Failure = 0x01 } pub struct SocksReply { pub version: u8, pub status: SocksReplyStatus, pub address: NetAddr, pub port: u16 } impl SocksReply { pub fn to_bytes(&self) -> Vec<u8> { let mut res = vec![self.version, self.status as u8]; match &self.address { &NetAddr::V4(addr) => { res.push(SocksAddrType::Ipv4 as u8); res.extend(addr.octets().iter()); }, &NetAddr::V6(addr) => { res.push(SocksAddrType::Ipv6 as u8); res.extend(addr.octets().iter()); }, &NetAddr::Name(ref name) => { res.push(SocksAddrType::Name as u8); if name.len() > 255 { panic!("Name is too long"); } res.push(name.len() as u8); res.extend(name.as_bytes().iter()); }, } res.push((self.port >> 8) as u8); res.push((self.port & 0xff) as u8); res } }
25.854839
80
0.522146
22f7d8338a8e930f0f9c2a11022381f27962e523
172
enum List { Cons(i32, Box<List>), Nil, } use crate::List::{Cons, Nil}; fn main() { let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil)))))); }
15.636364
76
0.540698
0ad5b41b53ebd5c377fe49ea6b92dd2fee5d1bc7
497
#[macro_use] mod _macros; mod app; mod cli; mod config; mod context; mod edit; mod editor; mod lock; mod log; mod util; use std::panic; use std::process; fn run() { if crate::app::Sheldon::run().is_err() { process::exit(2); } } fn main() { if panic::catch_unwind(run).is_err() { eprintln!( "\nThis is probably a bug, please file an issue at \ https://github.com/rossmacarthur/sheldon/issues." ); process::exit(127); } }
15.53125
64
0.577465
28a1a5249f95a21d6e94fce7e7c5416d831ad58b
1,405
pub trait SrgbColorSpace { fn linear_to_nonlinear_srgb(self) -> Self; fn nonlinear_to_linear_srgb(self) -> Self; } //source: https://entropymine.com/imageworsener/srgbformula/ impl SrgbColorSpace for f32 { fn linear_to_nonlinear_srgb(self) -> f32 { if self <= 0.0 { return self; } if self <= 0.0031308 { self * 12.92 // linear falloff in dark values } else { (1.055 * self.powf(1.0 / 2.4)) - 0.055 //gamma curve in other area } } fn nonlinear_to_linear_srgb(self) -> f32 { if self <= 0.0 { return self; } if self <= 0.04045 { self / 12.92 // linear falloff in dark values } else { ((self + 0.055) / 1.055).powf(2.4) //gamma curve in other area } } } #[test] fn test_srgb_full_roundtrip() { let u8max: f32 = u8::max_value() as f32; for color in 0..u8::max_value() { let color01 = color as f32 / u8max; let color_roundtrip = color01 .linear_to_nonlinear_srgb() .nonlinear_to_linear_srgb(); // roundtrip is not perfect due to numeric precision, even with f64 // so ensure the error is at least ready for u8 (where sRGB is used) assert_eq!( (color01 * u8max).round() as u8, (color_roundtrip * u8max).round() as u8 ); } }
29.270833
78
0.558007
01fcfa5b6b82fed418cf32668b5a4cfb36ca9a96
3,111
//! helpers and type for the HAMT bitmap //! //! The bitmap map a index into the sparse array index //! //! The number of bits set represent the number of elements //! currently present in the array //! //! e.g for the following elements and their indices: //! //! ```text //! [ (0b0010_0000, x) ] //! ``` //! //! will map into this bitmap: //! //! ```text //! 0b0010_0000 (1 bit set) //! ``` //! //! and a vector of 1 element containing x //! //! ```text //! | x | //! ``` //! //! or the following elements and their indices: //! //! ```text //! [ (0b0010_0000, x), (0b1000_0000, y), (0b0000_0010, z) ] //! ``` //! //! will map into this bitmap: //! //! ```text //! 0b1010_0010 (3 bit set) //! ``` //! //! and a vector of 3 elements containing x, y, z in the following order: //! //! ```text //! | z | x | y | //! ``` //! //! use super::hash::LevelIndex; use std::fmt; /// This is a node size bitmap to allow to find element /// in the node's array #[derive(Clone, Copy, PartialEq, Eq)] pub struct SmallBitmap(u32); impl fmt::Debug for SmallBitmap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "SmallBitmap {:032b}", self.0) } } impl SmallBitmap { /// Create a new bitmap with no element pub const fn new() -> Self { SmallBitmap(0u32) } #[inline] pub fn is_empty(self) -> bool { self.0 == 0 } #[inline] pub fn present(self) -> usize { self.0.count_ones() as usize } #[inline] /// Create a new bitmap with 1 element set pub const fn once(b: LevelIndex) -> Self { SmallBitmap(b.mask()) } /// Get the sparse array index from a level index #[inline] pub fn get_index_sparse(self, b: LevelIndex) -> ArrayIndex { let mask = b.mask(); if self.0 & mask == 0 { ArrayIndex::not_found() } else { ArrayIndex::create((self.0 & (mask - 1)).count_ones() as usize) } } /// Get the position of a level index in the sparse array for insertion #[inline] pub fn get_sparse_pos(self, b: LevelIndex) -> ArrayIndex { let mask = b.mask(); ArrayIndex::create((self.0 & (mask - 1)).count_ones() as usize) } /// Check if the element exist pub fn is_set(self, b: LevelIndex) -> bool { (self.0 & b.mask()) != 0 } #[inline] pub fn set_index(self, b: LevelIndex) -> Self { SmallBitmap(self.0 | b.mask()) } #[inline] pub fn clear_index(self, b: LevelIndex) -> Self { SmallBitmap(self.0 & !b.mask()) } } /// Sparse index in the array. /// /// The array elements are allocated on demand, /// and their presence is indicated by the bitmap #[derive(Debug, Clone, Copy)] pub struct ArrayIndex(usize); impl ArrayIndex { pub fn is_not_found(self) -> bool { self.0 == 0xff } pub fn get_found(self) -> usize { assert!(!self.is_not_found()); self.0 } pub fn not_found() -> Self { ArrayIndex(0xff) } pub fn create(s: usize) -> Self { ArrayIndex(s) } }
22.221429
75
0.561234
bba62f2311b8b0e1e743f979f259fdba36020c86
3,901
// The From trait is used for value-to-value conversions. // If From is implemented correctly for a type, the Into trait should work conversely. // You can read more about it at https://doc.rust-lang.org/std/convert/trait.From.html #[derive(Debug)] struct Person { name: String, age: usize, } // We implement the Default trait to use it as a fallback // when the provided string is not convertible into a Person object impl Default for Person { fn default() -> Person { Person { name: String::from("John"), age: 30, } } } // Your task is to complete this implementation // in order for the line `let p = Person::from("Mark,20")` to compile // Please note that you'll need to parse the age component into a `usize` // with something like `"4".parse::<usize>()`. The outcome of this needs to // be handled appropriately. // // Steps: // 1. If the length of the provided string is 0, then return the default of Person // 2. Split the given string on the commas present in it // 3. Extract the first element from the split operation and use it as the name // 4. If the name is empty, then return the default of Person // 5. Extract the other element from the split operation and parse it into a `usize` as the age // If while parsing the age, something goes wrong, then return the default of Person // Otherwise, then return an instantiated Person object with the results impl From<&str> for Person { fn from(s: &str) -> Person { if s.len() == 0 { return Person::default(); } let v: Vec<&str> = s.split(",").collect(); if v.len() != 2 { return Person::default(); } let name = String::from(v[0]); let age = v[1].parse::<usize>().unwrap_or(0); if name.len() == 0 || age <= 0 { return Person::default(); } Person { name, age } } } fn main() { // Use the `from` function let p1 = Person::from("Mark,20"); // Since From is implemented for Person, we should be able to use Into let p2: Person = "Gerald,70".into(); println!("{:?}", p1); println!("{:?}", p2); } #[cfg(test)] mod tests { use super::*; #[test] fn test_default() { // Test that the default person is 30 year old John let dp = Person::default(); assert_eq!(dp.name, "John"); assert_eq!(dp.age, 30); } #[test] fn test_bad_convert() { // Test that John is returned when bad string is provided let p = Person::from(""); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); } #[test] fn test_good_convert() { // Test that "Mark,20" works let p = Person::from("Mark,20"); assert_eq!(p.name, "Mark"); assert_eq!(p.age, 20); } #[test] fn test_bad_age() { // Test that "Mark,twenty" will return the default person due to an error in parsing age let p = Person::from("Mark,twenty"); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); } #[test] fn test_missing_comma_and_age() { let p: Person = Person::from("Mark"); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); } #[test] fn test_missing_age() { let p: Person = Person::from("Mark,"); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); } #[test] fn test_missing_name() { let p: Person = Person::from(",1"); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); } #[test] fn test_missing_name_and_age() { let p: Person = Person::from(","); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); } #[test] fn test_missing_name_and_invalid_age() { let p: Person = Person::from(",one"); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); } }
30.007692
96
0.57857
de58ce009a67b56552855449f0133d9fdb2b0b1d
2,419
use nabi::{Result, Error, HandleRights}; use super::dispatcher::{Dispatch, Dispatcher}; use core::marker::PhantomData; use core::ops::Deref; /// A Handle represents an atomically reference-counted object with specfic rights. /// Handles can be duplicated if they have the `HandleRights::DUPLICATE` right. pub struct Handle<T: Dispatcher + ?Sized> { /// Reference-counted ptr to the stored object. dispatch: Dispatch<T>, /// This handle's access rights to the `Ref<T>`. rights: HandleRights, } impl<T: Dispatcher + ?Sized> Handle<T> { pub fn new(dispatch: Dispatch<T>, rights: HandleRights) -> Handle<T> { Handle { dispatch, rights, } } pub fn duplicate(&self, new_rights: HandleRights) -> Option<Self> { if self.rights.contains(new_rights | HandleRights::DUPLICATE) { Some(Handle { dispatch: self.dispatch.copy_ref(), rights: new_rights, }) } else { None } } pub fn check_rights(&self, rights: HandleRights) -> Result<&Self> { if self.rights.contains(rights) { Ok(self) } else { Err(Error::ACCESS_DENIED) } } pub fn rights(&self) -> HandleRights { self.rights } pub fn dispatcher(&self) -> &Dispatch<T> { &self.dispatch } } impl<T> Handle<T> where T: Dispatcher + Sized { pub fn upcast(self) -> Handle<Dispatcher> { Handle { dispatch: self.dispatch.upcast(), rights: self.rights, } } } impl Handle<Dispatcher> { pub fn cast<T: Dispatcher>(&self) -> Result<Handle<T>> { let dispatch = self.dispatch.cast()?; Ok(Handle { dispatch, rights: self.rights, }) } } impl<T> Deref for Handle<T> where T: Dispatcher + ?Sized { type Target = Dispatch<T>; fn deref(&self) -> &Dispatch<T> { &self.dispatch } } #[repr(transparent)] pub struct UserHandle<T: Dispatcher + ?Sized>(u32, PhantomData<T>); impl<T> UserHandle<T> where T: Dispatcher + ?Sized { #[inline] pub fn new(index: u32) -> UserHandle<T> { UserHandle(index, PhantomData) } #[inline] pub fn inner(&self) -> u32 { self.0 } }
23.715686
84
0.54568
8aa38e2fcf68b01aeef8edfd5640f28ab61a3985
14,266
use std::fmt::{self, Formatter}; use std::io::{USER_DIR}; use std::io::fs::{mkdir_recursive, rmdir_recursive, PathExtensions}; use rustc_serialize::{Encodable, Encoder}; use url::Url; use git2::{self, ObjectType}; use core::GitReference; use util::{CargoResult, ChainError, human, ToUrl, internal}; #[derive(PartialEq, Clone, Show)] #[allow(missing_copy_implementations)] pub struct GitRevision(git2::Oid); impl fmt::String for GitRevision { fn fmt(&self, f: &mut Formatter) -> fmt::Result { fmt::String::fmt(&self.0, f) } } /// GitRemote represents a remote repository. It gets cloned into a local /// GitDatabase. #[derive(PartialEq,Clone,Show)] pub struct GitRemote { url: Url, } #[derive(PartialEq,Clone,RustcEncodable)] struct EncodableGitRemote { url: String, } impl Encodable for GitRemote { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { EncodableGitRemote { url: self.url.to_string() }.encode(s) } } /// GitDatabase is a local clone of a remote repository's database. Multiple /// GitCheckouts can be cloned from this GitDatabase. pub struct GitDatabase { remote: GitRemote, path: Path, repo: git2::Repository, } #[derive(RustcEncodable)] pub struct EncodableGitDatabase { remote: GitRemote, path: String, } impl Encodable for GitDatabase { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { EncodableGitDatabase { remote: self.remote.clone(), path: self.path.display().to_string() }.encode(s) } } /// GitCheckout is a local checkout of a particular revision. Calling /// `clone_into` with a reference will resolve the reference into a revision, /// and return a CargoError if no revision for that reference was found. pub struct GitCheckout<'a> { database: &'a GitDatabase, location: Path, revision: GitRevision, repo: git2::Repository, } #[derive(RustcEncodable)] pub struct EncodableGitCheckout { database: EncodableGitDatabase, location: String, revision: String, } impl<'a> Encodable for GitCheckout<'a> { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { EncodableGitCheckout { location: self.location.display().to_string(), revision: self.revision.to_string(), database: EncodableGitDatabase { remote: self.database.remote.clone(), path: self.database.path.display().to_string(), }, }.encode(s) } } // Implementations impl GitRemote { pub fn new(url: &Url) -> GitRemote { GitRemote { url: url.clone() } } pub fn get_url(&self) -> &Url { &self.url } pub fn rev_for(&self, path: &Path, reference: &GitReference) -> CargoResult<GitRevision> { let db = try!(self.db_at(path)); db.rev_for(reference) } pub fn checkout(&self, into: &Path) -> CargoResult<GitDatabase> { let repo = match git2::Repository::open(into) { Ok(repo) => { try!(self.fetch_into(&repo).chain_error(|| { internal(format!("failed to fetch into {}", into.display())) })); repo } Err(..) => { try!(self.clone_into(into).chain_error(|| { internal(format!("failed to clone into: {}", into.display())) })) } }; Ok(GitDatabase { remote: self.clone(), path: into.clone(), repo: repo }) } pub fn db_at(&self, db_path: &Path) -> CargoResult<GitDatabase> { let repo = try!(git2::Repository::open(db_path)); Ok(GitDatabase { remote: self.clone(), path: db_path.clone(), repo: repo, }) } fn fetch_into(&self, dst: &git2::Repository) -> CargoResult<()> { // Create a local anonymous remote in the repository to fetch the url let url = self.url.to_string(); let refspec = "refs/heads/*:refs/heads/*"; fetch(dst, url.as_slice(), refspec) } fn clone_into(&self, dst: &Path) -> CargoResult<git2::Repository> { let url = self.url.to_string(); if dst.exists() { try!(rmdir_recursive(dst)); } try!(mkdir_recursive(dst, USER_DIR)); let repo = try!(git2::Repository::init_bare(dst)); try!(fetch(&repo, url.as_slice(), "refs/heads/*:refs/heads/*")); Ok(repo) } } impl GitDatabase { fn get_path<'a>(&'a self) -> &'a Path { &self.path } pub fn copy_to(&self, rev: GitRevision, dest: &Path) -> CargoResult<GitCheckout> { let checkout = match git2::Repository::open(dest) { Ok(repo) => { let checkout = GitCheckout::new(dest, self, rev, repo); if !checkout.is_fresh() { try!(checkout.fetch()); try!(checkout.reset()); assert!(checkout.is_fresh()); } checkout } Err(..) => try!(GitCheckout::clone_into(dest, self, rev)), }; try!(checkout.update_submodules().chain_error(|| { internal("failed to update submodules") })); Ok(checkout) } pub fn rev_for(&self, reference: &GitReference) -> CargoResult<GitRevision> { let id = match *reference { GitReference::Tag(ref s) => { try!((|:| { let refname = format!("refs/tags/{}", s); let id = try!(self.repo.refname_to_id(refname.as_slice())); let obj = try!(self.repo.find_object(id, None)); let obj = try!(obj.peel(ObjectType::Commit)); Ok(obj.id()) }).chain_error(|| { human(format!("failed to find tag `{}`", s)) })) } GitReference::Branch(ref s) => { try!((|:| { let b = try!(self.repo.find_branch(s.as_slice(), git2::BranchType::Local)); b.get().target().chain_error(|| { human(format!("branch `{}` did not have a target", s)) }) }).chain_error(|| { human(format!("failed to find branch `{}`", s)) })) } GitReference::Rev(ref s) => { let obj = try!(self.repo.revparse_single(s.as_slice())); obj.id() } }; Ok(GitRevision(id)) } pub fn has_ref<S: Str>(&self, reference: S) -> CargoResult<()> { try!(self.repo.revparse_single(reference.as_slice())); Ok(()) } } impl<'a> GitCheckout<'a> { fn new(path: &Path, database: &'a GitDatabase, revision: GitRevision, repo: git2::Repository) -> GitCheckout<'a> { GitCheckout { location: path.clone(), database: database, revision: revision, repo: repo, } } fn clone_into(into: &Path, database: &'a GitDatabase, revision: GitRevision) -> CargoResult<GitCheckout<'a>> { let repo = try!(GitCheckout::clone_repo(database.get_path(), into)); let checkout = GitCheckout::new(into, database, revision, repo); try!(checkout.reset()); Ok(checkout) } fn clone_repo(source: &Path, into: &Path) -> CargoResult<git2::Repository> { let dirname = into.dir_path(); try!(mkdir_recursive(&dirname, USER_DIR).chain_error(|| { human(format!("Couldn't mkdir {}", dirname.display())) })); if into.exists() { try!(rmdir_recursive(into).chain_error(|| { human(format!("Couldn't rmdir {}", into.display())) })); } let url = try!(source.to_url().map_err(human)); let url = url.to_string(); let repo = try!(git2::Repository::clone(url.as_slice(), into).chain_error(|| { internal(format!("failed to clone {} into {}", source.display(), into.display())) })); Ok(repo) } fn is_fresh(&self) -> bool { match self.repo.revparse_single("HEAD") { Ok(head) => head.id().to_string() == self.revision.to_string(), _ => false, } } fn fetch(&self) -> CargoResult<()> { info!("fetch {}", self.repo.path().display()); let url = try!(self.database.path.to_url().map_err(human)); let url = url.to_string(); let refspec = "refs/heads/*:refs/heads/*"; try!(fetch(&self.repo, url.as_slice(), refspec)); Ok(()) } fn reset(&self) -> CargoResult<()> { info!("reset {} to {}", self.repo.path().display(), self.revision); let object = try!(self.repo.find_object(self.revision.0, None)); try!(self.repo.reset(&object, git2::ResetType::Hard, None, None)); Ok(()) } fn update_submodules(&self) -> CargoResult<()> { return update_submodules(&self.repo); fn update_submodules(repo: &git2::Repository) -> CargoResult<()> { info!("update submodules for: {}", repo.path().display()); for mut child in try!(repo.submodules()).into_iter() { try!(child.init(false)); let url = try!(child.url().chain_error(|| { internal("non-utf8 url for submodule") })); // A submodule which is listed in .gitmodules but not actually // checked out will not have a head id, so we should ignore it. let head = match child.head_id() { Some(head) => head, None => continue, }; // If the submodule hasn't been checked out yet, we need to // clone it. If it has been checked out and the head is the same // as the submodule's head, then we can bail out and go to the // next submodule. let head_and_repo = child.open().and_then(|repo| { Ok((try!(repo.head()).target(), repo)) }); let repo = match head_and_repo { Ok((head, repo)) => { if child.head_id() == head { continue } repo } Err(..) => { let path = repo.path().dir_path().join(child.path()); try!(git2::Repository::clone(url, &path)) } }; // Fetch data from origin and reset to the head commit let refspec = "refs/heads/*:refs/heads/*"; try!(fetch(&repo, url, refspec).chain_error(|| { internal(format!("failed to fetch submodule `{}` from {}", child.name().unwrap_or(""), url)) })); let obj = try!(repo.find_object(head, None)); try!(repo.reset(&obj, git2::ResetType::Hard, None, None)); try!(update_submodules(&repo)); } Ok(()) } } } fn with_authentication<T, F>(url: &str, cfg: &git2::Config, mut f: F) -> CargoResult<T> where F: FnMut(&mut git2::Credentials) -> CargoResult<T> { // Prepare the authentication callbacks. // // We check the `allowed` types of credentials, and we try to do as much as // possible based on that: // // * Prioritize SSH keys from the local ssh agent as they're likely the most // reliable. The username here is prioritized from the credential // callback, then from whatever is configured in git itself, and finally // we fall back to the generic user of `git`. // // * If a username/password is allowed, then we fallback to git2-rs's // implementation of the credential helper. This is what is configured // with `credential.helper` in git, and is the interface for the OSX // keychain, for example. // // * After the above two have failed, we just kinda grapple attempting to // return *something*. let mut cred_helper = git2::CredentialHelper::new(url); cred_helper.config(cfg); let mut cred_error = false; let ret = f(&mut |&mut: url, username, allowed| { let username = if username.is_empty() {None} else {Some(username)}; let creds = if allowed.contains(git2::SSH_KEY) { let user = username.map(|s| s.to_string()) .or_else(|| cred_helper.username.clone()) .unwrap_or("git".to_string()); git2::Cred::ssh_key_from_agent(user.as_slice()) } else if allowed.contains(git2::USER_PASS_PLAINTEXT) { git2::Cred::credential_helper(cfg, url, username) } else if allowed.contains(git2::DEFAULT) { git2::Cred::default() } else { Err(git2::Error::from_str("no authentication available")) }; cred_error = creds.is_err(); creds }); if cred_error { ret.chain_error(|| { human("Failed to authenticate when downloading repository") }) } else { ret } } pub fn fetch(repo: &git2::Repository, url: &str, refspec: &str) -> CargoResult<()> { // Create a local anonymous remote in the repository to fetch the url with_authentication(url, &try!(repo.config()), |f| { let mut cb = git2::RemoteCallbacks::new(); cb.credentials(|a, b, c| f(a, b, c)); let mut remote = try!(repo.remote_anonymous(url.as_slice(), Some(refspec))); try!(remote.add_fetch("refs/tags/*:refs/tags/*")); remote.set_callbacks(&mut cb); try!(remote.fetch(&["refs/tags/*:refs/tags/*", refspec], None, None)); Ok(()) }) }
34.880196
81
0.528179
014772a515b92dadde08b9b5d582ffe553b3011b
33,424
use super::utils::{ depth, report_and_exit, save_state, serialized_type, status_codes, threads, timeout, user_agent, wordlist, OutputLevel, RequesterPolicy, }; use crate::config::determine_output_level; use crate::config::utils::determine_requester_policy; use crate::{ client, parser, scan_manager::resume_scan, traits::FeroxSerialize, utils::fmt_err, DEFAULT_CONFIG_NAME, }; use anyhow::{anyhow, Context, Result}; use clap::{value_t, ArgMatches}; use reqwest::{Client, StatusCode}; use serde::{Deserialize, Serialize}; use std::{ collections::HashMap, env::{current_dir, current_exe}, fs::read_to_string, path::PathBuf, }; /// macro helper to abstract away repetitive configuration updates macro_rules! update_config_if_present { ($c:expr, $m:ident, $v:expr, $t:ty) => { match value_t!($m, $v, $t) { Ok(value) => *$c = value, // Update value Err(clap::Error { kind: clap::ErrorKind::ArgumentNotFound, message: _, info: _, }) => { // Do nothing if argument not found } Err(e) => e.exit(), // Exit with error on parse error } }; } /// macro helper to abstract away repetitive if not default: update checks macro_rules! update_if_not_default { ($old:expr, $new:expr, $default:expr) => { if $new != $default { *$old = $new; } }; } /// Represents the final, global configuration of the program. /// /// This struct is the combination of the following: /// - default configuration values /// - plus overrides read from a configuration file /// - plus command-line options /// /// In that order. /// /// Inspired by and derived from https://github.com/PhilipDaniels/rust-config-example #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Configuration { #[serde(rename = "type", default = "serialized_type")] /// Name of this type of struct, used for serialization, i.e. `{"type":"configuration"}` pub kind: String, /// Path to the wordlist #[serde(default = "wordlist")] pub wordlist: String, /// Path to the config file used #[serde(default)] pub config: String, /// Proxy to use for requests (ex: http(s)://host:port, socks5(h)://host:port) #[serde(default)] pub proxy: String, /// Replay Proxy to use for requests (ex: http(s)://host:port, socks5(h)://host:port) #[serde(default)] pub replay_proxy: String, /// The target URL #[serde(default)] pub target_url: String, /// Status Codes to include (allow list) (default: 200 204 301 302 307 308 401 403 405) #[serde(default = "status_codes")] pub status_codes: Vec<u16>, /// Status Codes to replay to the Replay Proxy (default: whatever is passed to --status-code) #[serde(default = "status_codes")] pub replay_codes: Vec<u16>, /// Status Codes to filter out (deny list) #[serde(default)] pub filter_status: Vec<u16>, /// Instance of [reqwest::Client](https://docs.rs/reqwest/latest/reqwest/struct.Client.html) #[serde(skip)] pub client: Client, /// Instance of [reqwest::Client](https://docs.rs/reqwest/latest/reqwest/struct.Client.html) #[serde(skip)] pub replay_client: Option<Client>, /// Number of concurrent threads (default: 50) #[serde(default = "threads")] pub threads: usize, /// Number of seconds before a request times out (default: 7) #[serde(default = "timeout")] pub timeout: u64, /// Level of verbosity, equates to log level #[serde(default)] pub verbosity: u8, /// Only print URLs (was --quiet in versions < 2.0.0) #[serde(default)] pub silent: bool, /// No header, no status bars #[serde(default)] pub quiet: bool, /// more easily differentiate between the three states of output levels #[serde(skip)] pub output_level: OutputLevel, /// automatically bail at certain error thresholds #[serde(default)] pub auto_bail: bool, /// automatically try to lower request rate in order to reduce errors #[serde(default)] pub auto_tune: bool, /// more easily differentiate between the three requester policies #[serde(skip)] pub requester_policy: RequesterPolicy, /// Store log output as NDJSON #[serde(default)] pub json: bool, /// Output file to write results to (default: stdout) #[serde(default)] pub output: String, /// File in which to store debug output, used in conjunction with verbosity to dictate which /// logs are written #[serde(default)] pub debug_log: String, /// Sets the User-Agent (default: feroxbuster/VERSION) #[serde(default = "user_agent")] pub user_agent: String, /// Follow redirects #[serde(default)] pub redirects: bool, /// Disables TLS certificate validation #[serde(default)] pub insecure: bool, /// File extension(s) to search for #[serde(default)] pub extensions: Vec<String>, /// HTTP headers to be used in each request #[serde(default)] pub headers: HashMap<String, String>, /// URL query parameters #[serde(default)] pub queries: Vec<(String, String)>, /// Do not scan recursively #[serde(default)] pub no_recursion: bool, /// Extract links from html/javscript #[serde(default)] pub extract_links: bool, /// Append / to each request #[serde(default)] pub add_slash: bool, /// Read url(s) from STDIN #[serde(default)] pub stdin: bool, /// Maximum recursion depth, a depth of 0 is infinite recursion #[serde(default = "depth")] pub depth: usize, /// Number of concurrent scans permitted; a limit of 0 means no limit is imposed #[serde(default)] pub scan_limit: usize, /// Number of parallel scans permitted; a limit of 0 means no limit is imposed #[serde(default)] pub parallel: usize, /// Number of requests per second permitted (per directory); a limit of 0 means no limit is imposed #[serde(default)] pub rate_limit: usize, /// Filter out messages of a particular size #[serde(default)] pub filter_size: Vec<u64>, /// Filter out messages of a particular line count #[serde(default)] pub filter_line_count: Vec<usize>, /// Filter out messages of a particular word count #[serde(default)] pub filter_word_count: Vec<usize>, /// Filter out messages by regular expression #[serde(default)] pub filter_regex: Vec<String>, /// Don't auto-filter wildcard responses #[serde(default)] pub dont_filter: bool, /// Scan started from a state file, not from CLI args #[serde(default)] pub resumed: bool, /// Resume scan from this file #[serde(default)] pub resume_from: String, /// Whether or not a scan's current state should be saved when user presses Ctrl+C /// /// Not configurable from CLI; can only be set from a config file #[serde(default = "save_state")] pub save_state: bool, /// The maximum runtime for a scan, expressed as N[smdh] where N can be parsed into a /// non-negative integer and the next character is either s, m, h, or d (case insensitive) #[serde(default)] pub time_limit: String, /// Filter out response bodies that meet a certain threshold of similarity #[serde(default)] pub filter_similar: Vec<String>, /// URLs that should never be scanned/recursed into #[serde(default)] pub url_denylist: Vec<String>, } impl Default for Configuration { /// Builds the default Configuration for feroxbuster fn default() -> Self { let timeout = timeout(); let user_agent = user_agent(); let client = client::initialize(timeout, &user_agent, false, false, &HashMap::new(), None) .expect("Could not build client"); let replay_client = None; let status_codes = status_codes(); let replay_codes = status_codes.clone(); let kind = serialized_type(); let output_level = OutputLevel::Default; let requester_policy = RequesterPolicy::Default; Configuration { kind, client, timeout, user_agent, replay_codes, status_codes, replay_client, requester_policy, dont_filter: false, auto_bail: false, auto_tune: false, silent: false, quiet: false, output_level, resumed: false, stdin: false, json: false, verbosity: 0, scan_limit: 0, parallel: 0, rate_limit: 0, add_slash: false, insecure: false, redirects: false, no_recursion: false, extract_links: false, save_state: true, proxy: String::new(), config: String::new(), output: String::new(), debug_log: String::new(), target_url: String::new(), time_limit: String::new(), resume_from: String::new(), replay_proxy: String::new(), queries: Vec::new(), extensions: Vec::new(), filter_size: Vec::new(), filter_regex: Vec::new(), url_denylist: Vec::new(), filter_line_count: Vec::new(), filter_word_count: Vec::new(), filter_status: Vec::new(), filter_similar: Vec::new(), headers: HashMap::new(), depth: depth(), threads: threads(), wordlist: wordlist(), } } } impl Configuration { /// Creates a [Configuration](struct.Configuration.html) object with the following /// built-in default values /// /// - **timeout**: `5` seconds /// - **redirects**: `false` /// - **extract-links**: `false` /// - **wordlist**: [`DEFAULT_WORDLIST`](constant.DEFAULT_WORDLIST.html) /// - **config**: `None` /// - **threads**: `50` /// - **timeout**: `7` seconds /// - **verbosity**: `0` (no logging enabled) /// - **proxy**: `None` /// - **status_codes**: [`DEFAULT_RESPONSE_CODES`](constant.DEFAULT_RESPONSE_CODES.html) /// - **filter_status**: `None` /// - **output**: `None` (print to stdout) /// - **debug_log**: `None` /// - **quiet**: `false` /// - **silent**: `false` /// - **auto_tune**: `false` /// - **auto_bail**: `false` /// - **save_state**: `true` /// - **user_agent**: `feroxbuster/VERSION` /// - **insecure**: `false` (don't be insecure, i.e. don't allow invalid certs) /// - **extensions**: `None` /// - **url_denylist**: `None` /// - **filter_size**: `None` /// - **filter_similar**: `None` /// - **filter_regex**: `None` /// - **filter_word_count**: `None` /// - **filter_line_count**: `None` /// - **headers**: `None` /// - **queries**: `None` /// - **no_recursion**: `false` (recursively scan enumerated sub-directories) /// - **add_slash**: `false` /// - **stdin**: `false` /// - **json**: `false` /// - **dont_filter**: `false` (auto filter wildcard responses) /// - **depth**: `4` (maximum recursion depth) /// - **scan_limit**: `0` (no limit on concurrent scans imposed) /// - **parallel**: `0` (no limit on parallel scans imposed) /// - **rate_limit**: `0` (no limit on requests per second imposed) /// - **time_limit**: `None` (no limit on length of scan imposed) /// - **replay_proxy**: `None` (no limit on concurrent scans imposed) /// - **replay_codes**: [`DEFAULT_RESPONSE_CODES`](constant.DEFAULT_RESPONSE_CODES.html) /// /// After which, any values defined in a /// [ferox-config.toml](constant.DEFAULT_CONFIG_NAME.html) config file will override the /// built-in defaults. /// /// `ferox-config.toml` can be placed in any of the following locations (in the order shown): /// - `/etc/feroxbuster/` /// - `CONFIG_DIR/ferxobuster/` /// - The same directory as the `feroxbuster` executable /// - The user's current working directory /// /// If more than one valid configuration file is found, each one overwrites the values found previously. /// /// Finally, any options/arguments given on the commandline will override both built-in and /// config-file specified values. /// /// The resulting [Configuration](struct.Configuration.html) is a singleton with a `static` /// lifetime. pub fn new() -> Result<Self> { // when compiling for test, we want to eliminate the runtime dependency of the parser if cfg!(test) { let test_config = Configuration { save_state: false, // don't clutter up junk when testing ..Default::default() }; return Ok(test_config); } let args = parser::initialize().get_matches(); // Get the default configuration, this is what will apply if nothing // else is specified. let mut config = Configuration::default(); // read in all config files Self::parse_config_files(&mut config)?; // read in the user provided options, this produces a separate instance of Configuration // in order to allow for potentially merging into a --resume-from Configuration let cli_config = Self::parse_cli_args(&args); // --resume-from used, need to first read the Configuration from disk, and then // merge the cli_config into the resumed config if let Some(filename) = args.value_of("resume_from") { // when resuming a scan, instead of normal configuration loading, we just // load the config from disk by calling resume_scan let mut previous_config = resume_scan(filename); // if any other arguments were passed on the command line, the theory is that the // user meant to modify the previously cancelled/saved scan in some way that we // should take into account Self::merge_config(&mut previous_config, cli_config); // the resumed flag isn't printed in the banner and really has no business being // serialized or included in much of the usual config logic; simply setting it to true // here and being done with it previous_config.resumed = true; // if the user used --stdin, we already have all the scans started (or complete), we // need to flip stdin to false so that the 'read from stdin' logic doesn't fire (if // not flipped to false, the program hangs waiting for input from stdin again) previous_config.stdin = false; // clients aren't serialized, have to remake them from the previous config Self::try_rebuild_clients(&mut previous_config); return Ok(previous_config); } // if we've gotten to this point in the code, --resume-from was not used, so we need to // merge the cli options into the config file options and return the result Self::merge_config(&mut config, cli_config); // rebuild clients is the last step in either code branch Self::try_rebuild_clients(&mut config); Ok(config) } /// Parse all possible versions of the ferox-config.toml file, adhering to the order of /// precedence outlined above fn parse_config_files(mut config: &mut Self) -> Result<()> { // Next, we parse the ferox-config.toml file, if present and set the values // therein to overwrite our default values. Deserialized defaults are specified // in the Configuration struct so that we don't change anything that isn't // actually specified in the config file // // search for a config using the following order of precedence // - /etc/feroxbuster/ // - CONFIG_DIR/ferxobuster/ // - same directory as feroxbuster executable // - current directory // merge a config found at /etc/feroxbuster/ferox-config.toml let config_file = PathBuf::new() .join("/etc/feroxbuster") .join(DEFAULT_CONFIG_NAME); Self::parse_and_merge_config(config_file, &mut config)?; // merge a config found at ~/.config/feroxbuster/ferox-config.toml // config_dir() resolves to one of the following // - linux: $XDG_CONFIG_HOME or $HOME/.config // - macOS: $HOME/Library/Application Support // - windows: {FOLDERID_RoamingAppData} let config_dir = dirs::config_dir().ok_or_else(|| anyhow!("Couldn't load config"))?; let config_file = config_dir.join("feroxbuster").join(DEFAULT_CONFIG_NAME); Self::parse_and_merge_config(config_file, &mut config)?; // merge a config found in same the directory as feroxbuster executable let exe_path = current_exe()?; let bin_dir = exe_path .parent() .ok_or_else(|| anyhow!("Couldn't load config"))?; let config_file = bin_dir.join(DEFAULT_CONFIG_NAME); Self::parse_and_merge_config(config_file, &mut config)?; // merge a config found in the user's current working directory let cwd = current_dir()?; let config_file = cwd.join(DEFAULT_CONFIG_NAME); Self::parse_and_merge_config(config_file, &mut config)?; Ok(()) } /// Given a set of ArgMatches read from the CLI, update and return the default Configuration /// settings fn parse_cli_args(args: &ArgMatches) -> Self { let mut config = Configuration::default(); update_config_if_present!(&mut config.threads, args, "threads", usize); update_config_if_present!(&mut config.depth, args, "depth", usize); update_config_if_present!(&mut config.scan_limit, args, "scan_limit", usize); update_config_if_present!(&mut config.parallel, args, "parallel", usize); update_config_if_present!(&mut config.rate_limit, args, "rate_limit", usize); update_config_if_present!(&mut config.wordlist, args, "wordlist", String); update_config_if_present!(&mut config.output, args, "output", String); update_config_if_present!(&mut config.debug_log, args, "debug_log", String); update_config_if_present!(&mut config.time_limit, args, "time_limit", String); update_config_if_present!(&mut config.resume_from, args, "resume_from", String); if let Some(arg) = args.values_of("status_codes") { config.status_codes = arg .map(|code| { StatusCode::from_bytes(code.as_bytes()) .unwrap_or_else(|e| report_and_exit(&e.to_string())) .as_u16() }) .collect(); } if let Some(arg) = args.values_of("replay_codes") { // replay codes passed in by the user config.replay_codes = arg .map(|code| { StatusCode::from_bytes(code.as_bytes()) .unwrap_or_else(|e| report_and_exit(&e.to_string())) .as_u16() }) .collect(); } else { // not passed in by the user, use whatever value is held in status_codes config.replay_codes = config.status_codes.clone(); } if let Some(arg) = args.values_of("filter_status") { config.filter_status = arg .map(|code| { StatusCode::from_bytes(code.as_bytes()) .unwrap_or_else(|e| report_and_exit(&e.to_string())) .as_u16() }) .collect(); } if let Some(arg) = args.values_of("extensions") { config.extensions = arg.map(|val| val.to_string()).collect(); } if let Some(arg) = args.values_of("url_denylist") { config.url_denylist = arg.map(|val| val.to_string()).collect(); } if let Some(arg) = args.values_of("filter_regex") { config.filter_regex = arg.map(|val| val.to_string()).collect(); } if let Some(arg) = args.values_of("filter_similar") { config.filter_similar = arg.map(|val| val.to_string()).collect(); } if let Some(arg) = args.values_of("filter_size") { config.filter_size = arg .map(|size| { size.parse::<u64>() .unwrap_or_else(|e| report_and_exit(&e.to_string())) }) .collect(); } if let Some(arg) = args.values_of("filter_words") { config.filter_word_count = arg .map(|size| { size.parse::<usize>() .unwrap_or_else(|e| report_and_exit(&e.to_string())) }) .collect(); } if let Some(arg) = args.values_of("filter_lines") { config.filter_line_count = arg .map(|size| { size.parse::<usize>() .unwrap_or_else(|e| report_and_exit(&e.to_string())) }) .collect(); } if args.is_present("silent") { // the reason this is protected by an if statement: // consider a user specifying silent = true in ferox-config.toml // if the line below is outside of the if, we'd overwrite true with // false if no --silent is used on the command line config.silent = true; config.output_level = OutputLevel::Silent; } if args.is_present("quiet") { config.quiet = true; config.output_level = OutputLevel::Quiet; } if args.is_present("auto_tune") { config.auto_tune = true; config.requester_policy = RequesterPolicy::AutoTune; } if args.is_present("auto_bail") { config.auto_bail = true; config.requester_policy = RequesterPolicy::AutoBail; } if args.is_present("dont_filter") { config.dont_filter = true; } if args.occurrences_of("verbosity") > 0 { // occurrences_of returns 0 if none are found; this is protected in // an if block for the same reason as the quiet option config.verbosity = args.occurrences_of("verbosity") as u8; } if args.is_present("no_recursion") { config.no_recursion = true; } if args.is_present("add_slash") { config.add_slash = true; } if args.is_present("extract_links") { config.extract_links = true; } if args.is_present("json") { config.json = true; } if args.is_present("stdin") { config.stdin = true; } else if let Some(url) = args.value_of("url") { config.target_url = String::from(url); } //// // organizational breakpoint; all options below alter the Client configuration //// update_config_if_present!(&mut config.proxy, args, "proxy", String); update_config_if_present!(&mut config.replay_proxy, args, "replay_proxy", String); update_config_if_present!(&mut config.user_agent, args, "user_agent", String); update_config_if_present!(&mut config.timeout, args, "timeout", u64); if args.is_present("redirects") { config.redirects = true; } if args.is_present("insecure") { config.insecure = true; } if let Some(headers) = args.values_of("headers") { for val in headers { let mut split_val = val.split(':'); // explicitly take first split value as header's name let name = split_val.next().unwrap().trim(); // all other items in the iterator returned by split, when combined with the // original split deliminator (:), make up the header's final value let value = split_val.collect::<Vec<&str>>().join(":"); config.headers.insert(name.to_string(), value.to_string()); } } if let Some(queries) = args.values_of("queries") { for val in queries { // same basic logic used as reading in the headers HashMap above let mut split_val = val.split('='); let name = split_val.next().unwrap().trim(); let value = split_val.collect::<Vec<&str>>().join("="); config.queries.push((name.to_string(), value.to_string())); } } config } /// this function determines if we've gotten a Client configuration change from /// either the config file or command line arguments; if we have, we need to rebuild /// the client and store it in the config struct fn try_rebuild_clients(configuration: &mut Configuration) { if !configuration.proxy.is_empty() || configuration.timeout != timeout() || configuration.user_agent != user_agent() || configuration.redirects || configuration.insecure || !configuration.headers.is_empty() || configuration.resumed { if configuration.proxy.is_empty() { configuration.client = client::initialize( configuration.timeout, &configuration.user_agent, configuration.redirects, configuration.insecure, &configuration.headers, None, ) .expect("Could not rebuild client") } else { configuration.client = client::initialize( configuration.timeout, &configuration.user_agent, configuration.redirects, configuration.insecure, &configuration.headers, Some(&configuration.proxy), ) .expect("Could not rebuild client") } } if !configuration.replay_proxy.is_empty() { // only set replay_client when replay_proxy is set configuration.replay_client = Some( client::initialize( configuration.timeout, &configuration.user_agent, configuration.redirects, configuration.insecure, &configuration.headers, Some(&configuration.replay_proxy), ) .expect("Could not rebuild client"), ); } } /// Given a configuration file's location and an instance of `Configuration`, read in /// the config file if found and update the current settings with the settings found therein fn parse_and_merge_config(config_file: PathBuf, mut config: &mut Self) -> Result<()> { if config_file.exists() { // save off a string version of the path before it goes out of scope let conf_str = config_file.to_str().unwrap_or("").to_string(); let settings = Self::parse_config(config_file)?; // set the config used for viewing in the banner config.config = conf_str; // update the settings Self::merge_config(&mut config, settings); } Ok(()) } /// Given two Configurations, overwrite `settings` with the fields found in `settings_to_merge` fn merge_config(conf: &mut Self, new: Self) { // does not include the following Configuration fields, as they don't make sense here // - kind // - client // - replay_client // - resumed // - config update_if_not_default!(&mut conf.target_url, new.target_url, ""); update_if_not_default!(&mut conf.time_limit, new.time_limit, ""); update_if_not_default!(&mut conf.proxy, new.proxy, ""); update_if_not_default!(&mut conf.verbosity, new.verbosity, 0); update_if_not_default!(&mut conf.silent, new.silent, false); update_if_not_default!(&mut conf.quiet, new.quiet, false); update_if_not_default!(&mut conf.auto_bail, new.auto_bail, false); update_if_not_default!(&mut conf.auto_tune, new.auto_tune, false); // use updated quiet/silent values to determine output level; same for requester policy conf.output_level = determine_output_level(conf.quiet, conf.silent); conf.requester_policy = determine_requester_policy(conf.auto_tune, conf.auto_bail); update_if_not_default!(&mut conf.output, new.output, ""); update_if_not_default!(&mut conf.redirects, new.redirects, false); update_if_not_default!(&mut conf.insecure, new.insecure, false); update_if_not_default!(&mut conf.extract_links, new.extract_links, false); update_if_not_default!(&mut conf.extensions, new.extensions, Vec::<String>::new()); update_if_not_default!( &mut conf.url_denylist, new.url_denylist, Vec::<String>::new() ); update_if_not_default!(&mut conf.headers, new.headers, HashMap::new()); update_if_not_default!(&mut conf.queries, new.queries, Vec::new()); update_if_not_default!(&mut conf.no_recursion, new.no_recursion, false); update_if_not_default!(&mut conf.add_slash, new.add_slash, false); update_if_not_default!(&mut conf.stdin, new.stdin, false); update_if_not_default!(&mut conf.filter_size, new.filter_size, Vec::<u64>::new()); update_if_not_default!( &mut conf.filter_regex, new.filter_regex, Vec::<String>::new() ); update_if_not_default!( &mut conf.filter_similar, new.filter_similar, Vec::<String>::new() ); update_if_not_default!( &mut conf.filter_word_count, new.filter_word_count, Vec::<usize>::new() ); update_if_not_default!( &mut conf.filter_line_count, new.filter_line_count, Vec::<usize>::new() ); update_if_not_default!( &mut conf.filter_status, new.filter_status, Vec::<u16>::new() ); update_if_not_default!(&mut conf.dont_filter, new.dont_filter, false); update_if_not_default!(&mut conf.scan_limit, new.scan_limit, 0); update_if_not_default!(&mut conf.parallel, new.parallel, 0); update_if_not_default!(&mut conf.rate_limit, new.rate_limit, 0); update_if_not_default!(&mut conf.replay_proxy, new.replay_proxy, ""); update_if_not_default!(&mut conf.debug_log, new.debug_log, ""); update_if_not_default!(&mut conf.resume_from, new.resume_from, ""); update_if_not_default!(&mut conf.json, new.json, false); update_if_not_default!(&mut conf.timeout, new.timeout, timeout()); update_if_not_default!(&mut conf.user_agent, new.user_agent, user_agent()); update_if_not_default!(&mut conf.threads, new.threads, threads()); update_if_not_default!(&mut conf.depth, new.depth, depth()); update_if_not_default!(&mut conf.wordlist, new.wordlist, wordlist()); update_if_not_default!(&mut conf.status_codes, new.status_codes, status_codes()); // status_codes() is the default for replay_codes, if they're not provided update_if_not_default!(&mut conf.replay_codes, new.replay_codes, status_codes()); update_if_not_default!(&mut conf.save_state, new.save_state, save_state()); } /// If present, read in `DEFAULT_CONFIG_NAME` and deserialize the specified values /// /// uses serde to deserialize the toml into a `Configuration` struct pub(super) fn parse_config(config_file: PathBuf) -> Result<Self> { let content = read_to_string(config_file)?; let config: Self = toml::from_str(content.as_str())?; Ok(config) } } /// Implementation of FeroxMessage impl FeroxSerialize for Configuration { /// Simple wrapper around create_report_string fn as_str(&self) -> String { format!("{:#?}\n", *self) } /// Create an NDJSON representation of the current scan's Configuration /// /// (expanded for clarity) /// ex: /// { /// "type":"configuration", /// "wordlist":"test", /// "config":"/home/epi/.config/feroxbuster/ferox-config.toml", /// "proxy":"", /// "replay_proxy":"", /// "target_url":"https://localhost.com", /// "status_codes":[ /// 200, /// 204, /// 301, /// 302, /// 307, /// 308, /// 401, /// 403, /// 405 /// ], /// ... /// }\n fn as_json(&self) -> Result<String> { let mut json = serde_json::to_string(&self) .with_context(|| fmt_err("Could not convert Configuration to JSON"))?; json.push('\n'); Ok(json) } }
37.809955
108
0.593137
140c4f91b2640dd7a98f9afc62a31c9940b6f99c
155
mod bellman_ford; mod dijkstra; mod floyd_warshall; pub use bellman_ford::BellmanFord; pub use dijkstra::Dijkstra; pub use floyd_warshall::FloydWarshall;
19.375
38
0.819355
397abd9fde2c2365c4d1ee8d8b71b71505c63c19
1,220
use rand::seq::SliceRandom; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use tui::style::Color; #[derive(Debug, Clone)] pub enum ColorTypes { Base, Hexadecimal, Indexed, } impl<'de> Deserialize<'de> for ColorTypes { fn deserialize<D>(deserializer: D) -> Result<ColorTypes, D::Error> where D: Deserializer<'de>, { let s = String::deserialize(deserializer)?; match &s.as_str().to_lowercase()[..] { "hexadecimal" => Ok(Self::Hexadecimal), "indexed" => Ok(Self::Indexed), _ => Ok(Self::Base), } } } impl Serialize for ColorTypes { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_some(&self) } } pub fn make_random_color() -> Color { use Color::*; let mut random = rand::thread_rng(); let colors = [ Red, Black, Green, Yellow, Blue, Magenta, Cyan, Gray, LightRed, LightGreen, LightYellow, LightBlue, LightMagenta, LightCyan, White, ]; *colors.choose(&mut random).unwrap() }
21.403509
70
0.54918
2ffe1926275088fdac8917deb40d10775e782fb0
11,831
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Service config. /// /// /// Service configuration allows for customization of endpoints, region, credentials providers, /// and retry configuration. Generally, it is constructed automatically for you from a shared /// configuration loaded by the `aws-config` crate. For example: /// /// ```ignore /// // Load a shared config from the environment /// let shared_config = aws_config::from_env().load().await; /// // The client constructor automatically converts the shared config into the service config /// let client = Client::new(&shared_config); /// ``` /// /// The service config can also be constructed manually using its builder. /// pub struct Config { app_name: Option<aws_types::app_name::AppName>, pub(crate) timeout_config: Option<aws_smithy_types::timeout::Config>, pub(crate) sleep_impl: Option<std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>>, pub(crate) retry_config: Option<aws_smithy_types::retry::RetryConfig>, pub(crate) endpoint_resolver: ::std::sync::Arc<dyn aws_endpoint::ResolveAwsEndpoint>, pub(crate) region: Option<aws_types::region::Region>, pub(crate) credentials_provider: aws_types::credentials::SharedCredentialsProvider, } impl std::fmt::Debug for Config { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut config = f.debug_struct("Config"); config.finish() } } impl Config { /// Constructs a config builder. pub fn builder() -> Builder { Builder::default() } /// Returns the name of the app that is using the client, if it was provided. /// /// This _optional_ name is used to identify the application in the user agent that /// gets sent along with requests. pub fn app_name(&self) -> Option<&aws_types::app_name::AppName> { self.app_name.as_ref() } /// Creates a new [service config](crate::Config) from a [shared `config`](aws_types::sdk_config::SdkConfig). pub fn new(config: &aws_types::sdk_config::SdkConfig) -> Self { Builder::from(config).build() } /// The signature version 4 service signing name to use in the credential scope when signing requests. /// /// The signing service may be overridden by the `Endpoint`, or by specifying a custom /// [`SigningService`](aws_types::SigningService) during operation construction pub fn signing_service(&self) -> &'static str { "ioteventsdata" } } /// Builder for creating a `Config`. #[derive(Default)] pub struct Builder { app_name: Option<aws_types::app_name::AppName>, timeout_config: Option<aws_smithy_types::timeout::Config>, sleep_impl: Option<std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>>, retry_config: Option<aws_smithy_types::retry::RetryConfig>, endpoint_resolver: Option<::std::sync::Arc<dyn aws_endpoint::ResolveAwsEndpoint>>, region: Option<aws_types::region::Region>, credentials_provider: Option<aws_types::credentials::SharedCredentialsProvider>, } impl Builder { /// Constructs a config builder. pub fn new() -> Self { Self::default() } /// Sets the name of the app that is using the client. /// /// This _optional_ name is used to identify the application in the user agent that /// gets sent along with requests. pub fn app_name(mut self, app_name: aws_types::app_name::AppName) -> Self { self.set_app_name(Some(app_name)); self } /// Sets the name of the app that is using the client. /// /// This _optional_ name is used to identify the application in the user agent that /// gets sent along with requests. pub fn set_app_name(&mut self, app_name: Option<aws_types::app_name::AppName>) -> &mut Self { self.app_name = app_name; self } /// Set the timeout_config for the builder /// /// # Examples /// /// ```no_run /// # use std::time::Duration; /// use aws_sdk_ioteventsdata::config::Config; /// use aws_smithy_types::{timeout, tristate::TriState}; /// /// let api_timeouts = timeout::Api::new() /// .with_call_attempt_timeout(TriState::Set(Duration::from_secs(1))); /// let timeout_config = timeout::Config::new() /// .with_api_timeouts(api_timeouts); /// let config = Config::builder().timeout_config(timeout_config).build(); /// ``` pub fn timeout_config(mut self, timeout_config: aws_smithy_types::timeout::Config) -> Self { self.set_timeout_config(Some(timeout_config)); self } /// Set the timeout_config for the builder /// /// # Examples /// /// ```no_run /// # use std::time::Duration; /// use aws_sdk_ioteventsdata::config::{Builder, Config}; /// use aws_smithy_types::{timeout, tristate::TriState}; /// /// fn set_request_timeout(builder: &mut Builder) { /// let api_timeouts = timeout::Api::new() /// .with_call_attempt_timeout(TriState::Set(Duration::from_secs(1))); /// let timeout_config = timeout::Config::new() /// .with_api_timeouts(api_timeouts); /// builder.set_timeout_config(Some(timeout_config)); /// } /// /// let mut builder = Config::builder(); /// set_request_timeout(&mut builder); /// let config = builder.build(); /// ``` pub fn set_timeout_config( &mut self, timeout_config: Option<aws_smithy_types::timeout::Config>, ) -> &mut Self { self.timeout_config = timeout_config; self } /// Set the sleep_impl for the builder /// /// # Examples /// /// ```no_run /// use aws_sdk_ioteventsdata::config::Config; /// use aws_smithy_async::rt::sleep::AsyncSleep; /// use aws_smithy_async::rt::sleep::Sleep; /// /// #[derive(Debug)] /// pub struct ForeverSleep; /// /// impl AsyncSleep for ForeverSleep { /// fn sleep(&self, duration: std::time::Duration) -> Sleep { /// Sleep::new(std::future::pending()) /// } /// } /// /// let sleep_impl = std::sync::Arc::new(ForeverSleep); /// let config = Config::builder().sleep_impl(sleep_impl).build(); /// ``` pub fn sleep_impl( mut self, sleep_impl: std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>, ) -> Self { self.set_sleep_impl(Some(sleep_impl)); self } /// Set the sleep_impl for the builder /// /// # Examples /// /// ```no_run /// use aws_sdk_ioteventsdata::config::{Builder, Config}; /// use aws_smithy_async::rt::sleep::AsyncSleep; /// use aws_smithy_async::rt::sleep::Sleep; /// /// #[derive(Debug)] /// pub struct ForeverSleep; /// /// impl AsyncSleep for ForeverSleep { /// fn sleep(&self, duration: std::time::Duration) -> Sleep { /// Sleep::new(std::future::pending()) /// } /// } /// /// fn set_never_ending_sleep_impl(builder: &mut Builder) { /// let sleep_impl = std::sync::Arc::new(ForeverSleep); /// builder.set_sleep_impl(Some(sleep_impl)); /// } /// /// let mut builder = Config::builder(); /// set_never_ending_sleep_impl(&mut builder); /// let config = builder.build(); /// ``` pub fn set_sleep_impl( &mut self, sleep_impl: Option<std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>>, ) -> &mut Self { self.sleep_impl = sleep_impl; self } /// Set the retry_config for the builder /// /// # Examples /// ```no_run /// use aws_sdk_ioteventsdata::config::Config; /// use aws_smithy_types::retry::RetryConfig; /// /// let retry_config = RetryConfig::new().with_max_attempts(5); /// let config = Config::builder().retry_config(retry_config).build(); /// ``` pub fn retry_config(mut self, retry_config: aws_smithy_types::retry::RetryConfig) -> Self { self.set_retry_config(Some(retry_config)); self } /// Set the retry_config for the builder /// /// # Examples /// ```no_run /// use aws_sdk_ioteventsdata::config::{Builder, Config}; /// use aws_smithy_types::retry::RetryConfig; /// /// fn disable_retries(builder: &mut Builder) { /// let retry_config = RetryConfig::new().with_max_attempts(1); /// builder.set_retry_config(Some(retry_config)); /// } /// /// let mut builder = Config::builder(); /// disable_retries(&mut builder); /// let config = builder.build(); /// ``` pub fn set_retry_config( &mut self, retry_config: Option<aws_smithy_types::retry::RetryConfig>, ) -> &mut Self { self.retry_config = retry_config; self } // TODO(docs): include an example of using a static endpoint /// Sets the endpoint resolver to use when making requests. pub fn endpoint_resolver( mut self, endpoint_resolver: impl aws_endpoint::ResolveAwsEndpoint + 'static, ) -> Self { self.endpoint_resolver = Some(::std::sync::Arc::new(endpoint_resolver)); self } /// Sets the AWS region to use when making requests. /// /// # Examples /// ```no_run /// use aws_types::region::Region; /// use aws_sdk_ioteventsdata::config::{Builder, Config}; /// /// let config = aws_sdk_ioteventsdata::Config::builder() /// .region(Region::new("us-east-1")) /// .build(); /// ``` pub fn region(mut self, region: impl Into<Option<aws_types::region::Region>>) -> Self { self.region = region.into(); self } /// Sets the credentials provider for this service pub fn credentials_provider( mut self, credentials_provider: impl aws_types::credentials::ProvideCredentials + 'static, ) -> Self { self.credentials_provider = Some(aws_types::credentials::SharedCredentialsProvider::new( credentials_provider, )); self } /// Sets the credentials provider for this service pub fn set_credentials_provider( &mut self, credentials_provider: Option<aws_types::credentials::SharedCredentialsProvider>, ) -> &mut Self { self.credentials_provider = credentials_provider; self } /// Builds a [`Config`]. pub fn build(self) -> Config { Config { app_name: self.app_name, timeout_config: self.timeout_config, sleep_impl: self.sleep_impl, retry_config: self.retry_config, endpoint_resolver: self .endpoint_resolver .unwrap_or_else(|| ::std::sync::Arc::new(crate::aws_endpoint::endpoint_resolver())), region: self.region, credentials_provider: self.credentials_provider.unwrap_or_else(|| { aws_types::credentials::SharedCredentialsProvider::new( crate::no_credentials::NoCredentials, ) }), } } } impl From<&aws_types::sdk_config::SdkConfig> for Builder { fn from(input: &aws_types::sdk_config::SdkConfig) -> Self { let mut builder = Builder::default(); builder = builder.region(input.region().cloned()); builder.set_retry_config(input.retry_config().cloned()); builder.set_timeout_config(input.timeout_config().cloned()); builder.set_sleep_impl(input.sleep_impl().clone()); builder.set_credentials_provider(input.credentials_provider().cloned()); builder.set_app_name(input.app_name().cloned()); builder } } impl From<&aws_types::sdk_config::SdkConfig> for Config { fn from(sdk_config: &aws_types::sdk_config::SdkConfig) -> Self { Builder::from(sdk_config).build() } }
36.971875
113
0.625983
b908de08a0bddc0b4cdda0f64b07be4ac8c1bec0
9,839
// WARNING: This file was autogenerated by jni-bindgen. Any changes to this file may be lost!!! #[cfg(any(feature = "all", feature = "android-net-rtp-AudioCodec"))] __jni_bindgen! { /// public class [AudioCodec](https://developer.android.com/reference/android/net/rtp/AudioCodec.html) /// /// Required feature: android-net-rtp-AudioCodec public class AudioCodec ("android/net/rtp/AudioCodec") extends crate::java::lang::Object { // // Not emitting: Non-public method // /// [AudioCodec](https://developer.android.com/reference/android/net/rtp/AudioCodec.html#AudioCodec(int,%20java.lang.String,%20java.lang.String)) // /// // /// Required features: "java-lang-String" // #[cfg(any(feature = "all", all(feature = "java-lang-String")))] // fn new<'env>(__jni_env: &'env __jni_bindgen::Env, arg0: i32, arg1: impl __jni_bindgen::std::convert::Into<__jni_bindgen::std::option::Option<&'env crate::java::lang::String>>, arg2: impl __jni_bindgen::std::convert::Into<__jni_bindgen::std::option::Option<&'env crate::java::lang::String>>) -> __jni_bindgen::std::result::Result<__jni_bindgen::Local<'env, crate::android::net::rtp::AudioCodec>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { // // class.path == "android/net/rtp/AudioCodec", java.flags == (empty), .name == "<init>", .descriptor == "(ILjava/lang/String;Ljava/lang/String;)V" // unsafe { // let __jni_args = [__jni_bindgen::AsJValue::as_jvalue(&arg0), __jni_bindgen::AsJValue::as_jvalue(&arg1.into()), __jni_bindgen::AsJValue::as_jvalue(&arg2.into())]; // let (__jni_class, __jni_method) = __jni_env.require_class_method("android/net/rtp/AudioCodec\0", "<init>\0", "(ILjava/lang/String;Ljava/lang/String;)V\0"); // __jni_env.new_object_a(__jni_class, __jni_method, __jni_args.as_ptr()) // } // } /// [getCodecs](https://developer.android.com/reference/android/net/rtp/AudioCodec.html#getCodecs()) /// /// Required features: "android-net-rtp-AudioCodec" #[cfg(any(feature = "all", all(feature = "android-net-rtp-AudioCodec")))] pub fn getCodecs<'env>(__jni_env: &'env __jni_bindgen::Env) -> __jni_bindgen::std::result::Result<__jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, __jni_bindgen::ObjectArray<crate::android::net::rtp::AudioCodec, crate::java::lang::Throwable>>>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { // class.path == "android/net/rtp/AudioCodec", java.flags == PUBLIC | STATIC, .name == "getCodecs", .descriptor == "()[Landroid/net/rtp/AudioCodec;" unsafe { let __jni_args = []; let (__jni_class, __jni_method) = __jni_env.require_class_static_method("android/net/rtp/AudioCodec\0", "getCodecs\0", "()[Landroid/net/rtp/AudioCodec;\0"); __jni_env.call_static_object_method_a(__jni_class, __jni_method, __jni_args.as_ptr()) } } /// [getCodec](https://developer.android.com/reference/android/net/rtp/AudioCodec.html#getCodec(int,%20java.lang.String,%20java.lang.String)) /// /// Required features: "android-net-rtp-AudioCodec", "java-lang-String" #[cfg(any(feature = "all", all(feature = "android-net-rtp-AudioCodec", feature = "java-lang-String")))] pub fn getCodec<'env>(__jni_env: &'env __jni_bindgen::Env, arg0: i32, arg1: impl __jni_bindgen::std::convert::Into<__jni_bindgen::std::option::Option<&'env crate::java::lang::String>>, arg2: impl __jni_bindgen::std::convert::Into<__jni_bindgen::std::option::Option<&'env crate::java::lang::String>>) -> __jni_bindgen::std::result::Result<__jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, crate::android::net::rtp::AudioCodec>>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { // class.path == "android/net/rtp/AudioCodec", java.flags == PUBLIC | STATIC, .name == "getCodec", .descriptor == "(ILjava/lang/String;Ljava/lang/String;)Landroid/net/rtp/AudioCodec;" unsafe { let __jni_args = [__jni_bindgen::AsJValue::as_jvalue(&arg0), __jni_bindgen::AsJValue::as_jvalue(&arg1.into()), __jni_bindgen::AsJValue::as_jvalue(&arg2.into())]; let (__jni_class, __jni_method) = __jni_env.require_class_static_method("android/net/rtp/AudioCodec\0", "getCodec\0", "(ILjava/lang/String;Ljava/lang/String;)Landroid/net/rtp/AudioCodec;\0"); __jni_env.call_static_object_method_a(__jni_class, __jni_method, __jni_args.as_ptr()) } } /// **get** public static final [AMR](https://developer.android.com/reference/android/net/rtp/AudioCodec.html#AMR) /// /// Required feature: android-net-rtp-AudioCodec #[cfg(any(feature = "all", feature = "android-net-rtp-AudioCodec"))] pub fn AMR<'env>(env: &'env __jni_bindgen::Env) -> __jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, crate::android::net::rtp::AudioCodec>> { unsafe { let (class, field) = env.require_class_static_field("android/net/rtp/AudioCodec\0", "AMR\0", "Landroid/net/rtp/AudioCodec;\0"); env.get_static_object_field(class, field) } } /// **get** public static final [GSM](https://developer.android.com/reference/android/net/rtp/AudioCodec.html#GSM) /// /// Required feature: android-net-rtp-AudioCodec #[cfg(any(feature = "all", feature = "android-net-rtp-AudioCodec"))] pub fn GSM<'env>(env: &'env __jni_bindgen::Env) -> __jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, crate::android::net::rtp::AudioCodec>> { unsafe { let (class, field) = env.require_class_static_field("android/net/rtp/AudioCodec\0", "GSM\0", "Landroid/net/rtp/AudioCodec;\0"); env.get_static_object_field(class, field) } } /// **get** public static final [GSM_EFR](https://developer.android.com/reference/android/net/rtp/AudioCodec.html#GSM_EFR) /// /// Required feature: android-net-rtp-AudioCodec #[cfg(any(feature = "all", feature = "android-net-rtp-AudioCodec"))] pub fn GSM_EFR<'env>(env: &'env __jni_bindgen::Env) -> __jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, crate::android::net::rtp::AudioCodec>> { unsafe { let (class, field) = env.require_class_static_field("android/net/rtp/AudioCodec\0", "GSM_EFR\0", "Landroid/net/rtp/AudioCodec;\0"); env.get_static_object_field(class, field) } } /// **get** public static final [PCMA](https://developer.android.com/reference/android/net/rtp/AudioCodec.html#PCMA) /// /// Required feature: android-net-rtp-AudioCodec #[cfg(any(feature = "all", feature = "android-net-rtp-AudioCodec"))] pub fn PCMA<'env>(env: &'env __jni_bindgen::Env) -> __jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, crate::android::net::rtp::AudioCodec>> { unsafe { let (class, field) = env.require_class_static_field("android/net/rtp/AudioCodec\0", "PCMA\0", "Landroid/net/rtp/AudioCodec;\0"); env.get_static_object_field(class, field) } } /// **get** public static final [PCMU](https://developer.android.com/reference/android/net/rtp/AudioCodec.html#PCMU) /// /// Required feature: android-net-rtp-AudioCodec #[cfg(any(feature = "all", feature = "android-net-rtp-AudioCodec"))] pub fn PCMU<'env>(env: &'env __jni_bindgen::Env) -> __jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, crate::android::net::rtp::AudioCodec>> { unsafe { let (class, field) = env.require_class_static_field("android/net/rtp/AudioCodec\0", "PCMU\0", "Landroid/net/rtp/AudioCodec;\0"); env.get_static_object_field(class, field) } } /// **get** public final [fmtp](https://developer.android.com/reference/android/net/rtp/AudioCodec.html#fmtp) /// /// Required feature: java-lang-String #[cfg(any(feature = "all", feature = "java-lang-String"))] pub fn fmtp<'env>(&'env self) -> __jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, crate::java::lang::String>> { unsafe { let env = __jni_bindgen::Env::from_ptr(self.0.env); let (class, field) = env.require_class_field("android/net/rtp/AudioCodec\0", "fmtp\0", "Ljava/lang/String;\0"); env.get_object_field(class, field) } } /// **get** public final [rtpmap](https://developer.android.com/reference/android/net/rtp/AudioCodec.html#rtpmap) /// /// Required feature: java-lang-String #[cfg(any(feature = "all", feature = "java-lang-String"))] pub fn rtpmap<'env>(&'env self) -> __jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, crate::java::lang::String>> { unsafe { let env = __jni_bindgen::Env::from_ptr(self.0.env); let (class, field) = env.require_class_field("android/net/rtp/AudioCodec\0", "rtpmap\0", "Ljava/lang/String;\0"); env.get_object_field(class, field) } } /// **get** public final [type](https://developer.android.com/reference/android/net/rtp/AudioCodec.html#type) pub fn r#type<'env>(&'env self) -> i32 { unsafe { let env = __jni_bindgen::Env::from_ptr(self.0.env); let (class, field) = env.require_class_field("android/net/rtp/AudioCodec\0", "type\0", "I\0"); env.get_int_field(class, field) } } } }
70.278571
507
0.630958
f8394b8a6fc226abec78fbefa1c439af7be63f35
32,158
//! Layout management. /// A procedural macro to generate [Layers](type.Layers.html) /// ## Syntax /// Items inside the macro are converted to Actions as such: /// - [`Action::KeyCode`]: Idents are automatically understood as keycodes: `A`, `RCtrl`, `Space` /// - Punctuation, numbers and other literals that aren't special to the rust parser are converted /// to KeyCodes as well: `,` becomes `KeyCode::Commma`, `2` becomes `KeyCode::Kb2`, `/` becomes `KeyCode::Slash` /// - Characters which require shifted keys are converted to `Action::MultipleKeyCodes(&[LShift, <character>])`: /// `!` becomes `Action::MultipleKeyCodes(&[LShift, Kb1])` etc /// - Characters special to the rust parser (parentheses, brackets, braces, quotes, apostrophes, underscores, backslashes and backticks) /// left alone cause parsing errors and as such have to be enclosed by apostrophes: `'['` becomes `KeyCode::LBracket`, /// `'\''` becomes `KeyCode::Quote`, `'\\'` becomes `KeyCode::BSlash` /// - [`Action::NoOp`]: Lowercase `n` /// - [`Action::Trans`]: Lowercase `t` /// - [`Action::Layer`]: A number in parentheses: `(1)`, `(4 - 2)`, `(0x4u8 as usize)` /// - [`Action::MultipleActions`]: Actions in brackets: `[LCtrl S]`, `[LAlt LCtrl C]`, `[(2) B {Action::NoOp}]` /// - Other `Action`s: anything in braces (`{}`) is copied unchanged to the final layout - `{ Action::Custom(42) }` /// simply becomes `Action::Custom(42)` /// /// **Important note**: comma (`,`) is a keycode on its own, and can't be used to separate keycodes as one would have /// to do when not using a macro. /// /// ## Usage example: /// Example layout for a 4x12 split keyboard: /// ``` /// use keyberon::action::Action; /// static DLAYER: Action = Action::DefaultLayer(5); /// /// pub static LAYERS: keyberon::layout::Layers = keyberon::layout::layout! { /// { /// [ Tab Q W E R T Y U I O P BSpace ] /// [ LCtrl A S D F G H J K L ; Quote ] /// [ LShift Z X C V B N M , . / Escape ] /// [ n n LGui {DLAYER} Space Escape BSpace Enter (1) RAlt n n ] /// } /// { /// [ Tab 1 2 3 4 5 6 7 8 9 0 BSpace ] /// [ LCtrl ! @ # $ % ^ & * '(' ')' - = ] /// [ LShift n n n n n n n n n n [LAlt A]] /// [ n n LGui (2) t t t t t RAlt n n ] /// } /// // ... /// }; /// ``` pub use keyberon_macros::*; use crate::action::{Action, HoldTapConfig, SequenceEvent}; use crate::key_code::KeyCode; use arraydeque::ArrayDeque; use heapless::Vec; use State::*; /// The Layers type. /// /// The first level correspond to the layer, the two others to the /// switch matrix. For example, `layers[1][2][3]` correspond to the /// key i=2, j=3 on the layer 1. pub type Layers<T = core::convert::Infallible> = &'static [&'static [&'static [Action<T>]]]; type Stack = ArrayDeque<[Stacked; 16], arraydeque::behavior::Wrapping>; /// The layout manager. It takes `Event`s and `tick`s as input, and /// generate keyboard reports. pub struct Layout<T = core::convert::Infallible> where T: 'static, { layers: Layers<T>, default_layer: usize, states: Vec<State<T>, 64>, waiting: Option<WaitingState<T>>, stacked: Stack, active_sequences: ArrayDeque<[SequenceState; 4], arraydeque::behavior::Wrapping>, } /// An event on the key matrix. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Event { /// Press event with coordinates (i, j). Press(u8, u8), /// Release event with coordinates (i, j). Release(u8, u8), } impl Event { /// Returns the coordinates (i, j) of the event. pub fn coord(self) -> (u8, u8) { match self { Event::Press(i, j) => (i, j), Event::Release(i, j) => (i, j), } } /// Transforms the coordinates of the event. /// /// # Example /// /// ``` /// # use keyberon::layout::Event; /// assert_eq!( /// Event::Press(3, 10), /// Event::Press(3, 1).transform(|i, j| (i, 11 - j)), /// ); /// ``` pub fn transform(self, f: impl FnOnce(u8, u8) -> (u8, u8)) -> Self { match self { Event::Press(i, j) => { let (i, j) = f(i, j); Event::Press(i, j) } Event::Release(i, j) => { let (i, j) = f(i, j); Event::Release(i, j) } } } /// Returns `true` if the event is a key press. pub fn is_press(self) -> bool { match self { Event::Press(..) => true, Event::Release(..) => false, } } /// Returns `true` if the event is a key release. pub fn is_release(self) -> bool { match self { Event::Release(..) => true, Event::Press(..) => false, } } } /// Event from custom action. #[derive(Debug, PartialEq, Eq)] pub enum CustomEvent<T: 'static> { /// No custom action. NoEvent, /// The given custom action key is pressed. Press(&'static T), /// The given custom action key is released. Release(&'static T), } impl<T> CustomEvent<T> { /// Update an event according to a new event. /// ///The event can only be modified in the order `NoEvent < Press < /// Release` fn update(&mut self, e: Self) { use CustomEvent::*; match (&e, &self) { (Release(_), NoEvent) | (Release(_), Press(_)) => *self = e, (Press(_), NoEvent) => *self = e, _ => (), } } } impl<T> Default for CustomEvent<T> { fn default() -> Self { CustomEvent::NoEvent } } #[derive(Debug, Eq, PartialEq)] enum State<T: 'static> { NormalKey { keycode: KeyCode, coord: (u8, u8) }, LayerModifier { value: usize, coord: (u8, u8) }, Custom { value: &'static T, coord: (u8, u8) }, FakeKey { keycode: KeyCode }, // Fake key event for sequences } impl<T> Copy for State<T> {} impl<T> Clone for State<T> { fn clone(&self) -> Self { *self } } impl<T: 'static> State<T> { fn keycode(&self) -> Option<KeyCode> { match self { NormalKey { keycode, .. } => Some(*keycode), FakeKey { keycode } => Some(*keycode), _ => None, } } fn tick(&self) -> Option<Self> { Some(*self) } fn release(&self, c: (u8, u8), custom: &mut CustomEvent<T>) -> Option<Self> { match *self { NormalKey { coord, .. } | LayerModifier { coord, .. } if coord == c => None, Custom { value, coord } if coord == c => { custom.update(CustomEvent::Release(value)); None } _ => Some(*self), } } fn seq_release(&self, kc: KeyCode) -> Option<Self> { match *self { FakeKey { keycode, .. } if keycode == kc => None, _ => Some(*self), } } fn get_layer(&self) -> Option<usize> { match self { LayerModifier { value, .. } => Some(*value), _ => None, } } } #[derive(Debug, Copy, Clone)] struct WaitingState<T: 'static> { coord: (u8, u8), timeout: u16, delay: u16, hold: &'static Action<T>, tap: &'static Action<T>, config: HoldTapConfig, } enum WaitingAction { Hold, Tap, NoOp, } impl<T> WaitingState<T> { fn tick(&mut self, stacked: &Stack) -> WaitingAction { self.timeout = self.timeout.saturating_sub(1); match self.config { HoldTapConfig::Default => (), HoldTapConfig::HoldOnOtherKeyPress => { if stacked.iter().any(|s| s.event.is_press()) { return WaitingAction::Hold; } } HoldTapConfig::PermissiveHold => { for (x, s) in stacked.iter().enumerate() { if s.event.is_press() { let (i, j) = s.event.coord(); let target = Event::Release(i, j); if stacked.iter().skip(x + 1).any(|s| s.event == target) { return WaitingAction::Hold; } } } } } if let Some(&Stacked { since, .. }) = stacked .iter() .find(|s| self.is_corresponding_release(&s.event)) { if self.timeout >= self.delay - since { WaitingAction::Tap } else { WaitingAction::Hold } } else if self.timeout == 0 { WaitingAction::Hold } else { WaitingAction::NoOp } } fn is_corresponding_release(&self, event: &Event) -> bool { matches!(event, Event::Release(i, j) if (*i, *j) == self.coord) } } #[derive(Debug, Copy, Clone)] struct SequenceState { cur_event: Option<SequenceEvent>, delay: u32, // Keeps track of SequenceEvent::Delay time remaining tapped: Option<KeyCode>, // Keycode of a key that should be released at the next tick remaining_events: &'static [SequenceEvent], } #[derive(Debug)] struct Stacked { event: Event, since: u16, } impl From<Event> for Stacked { fn from(event: Event) -> Self { Stacked { event, since: 0 } } } impl Stacked { fn tick(&mut self) { self.since = self.since.saturating_add(1); } } impl<T: 'static> Layout<T> { /// Creates a new `Layout` object. pub fn new(layers: Layers<T>) -> Self { Self { layers, default_layer: 0, states: Vec::new(), waiting: None, stacked: ArrayDeque::new(), active_sequences: ArrayDeque::new(), } } /// Iterates on the key codes of the current state. pub fn keycodes(&self) -> impl Iterator<Item = KeyCode> + '_ { self.states.iter().filter_map(State::keycode) } fn waiting_into_hold(&mut self) -> CustomEvent<T> { if let Some(w) = &self.waiting { let hold = w.hold; let coord = w.coord; self.waiting = None; self.do_action(hold, coord, 0) } else { CustomEvent::NoEvent } } fn waiting_into_tap(&mut self) -> CustomEvent<T> { if let Some(w) = &self.waiting { let tap = w.tap; let coord = w.coord; self.waiting = None; self.do_action(tap, coord, 0) } else { CustomEvent::NoEvent } } /// A time event. /// /// This method must be called regularly, typically every millisecond. /// /// Returns the corresponding `CustomEvent`, allowing to manage /// custom actions thanks to the `Action::Custom` variant. pub fn tick(&mut self) -> CustomEvent<T> { self.states = self.states.iter().filter_map(State::tick).collect(); self.stacked.iter_mut().for_each(Stacked::tick); self.process_sequences(); match &mut self.waiting { Some(w) => match w.tick(&self.stacked) { WaitingAction::Hold => self.waiting_into_hold(), WaitingAction::Tap => self.waiting_into_tap(), WaitingAction::NoOp => CustomEvent::NoEvent, }, None => match self.stacked.pop_front() { Some(s) => self.unstack(s), None => CustomEvent::NoEvent, }, } } /// Takes care of draining and populating the `active_sequences` ArrayDeque, /// giving us sequences (aka macros) of nearly limitless length! fn process_sequences(&mut self) { // Iterate over all active sequence events for _ in 0..self.active_sequences.len() { if let Some(mut seq) = self.active_sequences.pop_front() { // If we've encountered a SequenceEvent::Delay we must count // that down completely before doing anything else... if seq.delay > 0 { seq.delay = seq.delay.saturating_sub(1); } else if let Some(keycode) = seq.tapped { // Clear out the Press() matching this Tap()'s keycode self.states = self .states .iter() .filter_map(|s| s.seq_release(keycode)) .collect(); seq.tapped = None; } else { // Pull the next SequenceEvent match seq.remaining_events { [e, tail @ ..] => { seq.cur_event = Some(*e); seq.remaining_events = tail; } [] => (), } // Process it (SequenceEvent) match seq.cur_event { Some(SequenceEvent::Complete) => { for fake_key in self.states.clone().iter() { match *fake_key { FakeKey { keycode } => { self.states = self .states .iter() .filter_map(|s| s.seq_release(keycode)) .collect(); } _ => {} } } seq.remaining_events = &[]; } Some(SequenceEvent::Press(keycode)) => { // Start tracking this fake key Press() event let _ = self.states.push(FakeKey { keycode }); } Some(SequenceEvent::Tap(keycode)) => { // Same as Press() except we track it for one tick via seq.tapped: let _ = self.states.push(FakeKey { keycode }); seq.tapped = Some(keycode); } Some(SequenceEvent::Release(keycode)) => { // Clear out the Press() matching this Release's keycode self.states = self .states .iter() .filter_map(|s| s.seq_release(keycode)) .collect() } Some(SequenceEvent::Delay { duration }) => { // Setup a delay that will be decremented once per tick until 0 if duration > 0 { // -1 to start since this tick counts seq.delay = duration - 1; } } _ => {} // We'll never get here } } if seq.remaining_events.len() > 0 { // Put it back self.active_sequences.push_back(seq); } } } } fn unstack(&mut self, stacked: Stacked) -> CustomEvent<T> { use Event::*; match stacked.event { Release(i, j) => { let mut custom = CustomEvent::NoEvent; self.states = self .states .iter() .filter_map(|s| s.release((i, j), &mut custom)) .collect(); custom } Press(i, j) => { let action = self.press_as_action((i, j), self.current_layer()); self.do_action(action, (i, j), stacked.since) } } } /// Register a key event. pub fn event(&mut self, event: Event) { if let Some(stacked) = self.stacked.push_back(event.into()) { self.waiting_into_hold(); self.unstack(stacked); } } fn press_as_action(&self, coord: (u8, u8), layer: usize) -> &'static Action<T> { use crate::action::Action::*; let action = self .layers .get(layer) .and_then(|l| l.get(coord.0 as usize)) .and_then(|l| l.get(coord.1 as usize)); match action { None => &NoOp, Some(Trans) => { if layer != self.default_layer { self.press_as_action(coord, self.default_layer) } else { &NoOp } } Some(action) => action, } } fn do_action( &mut self, action: &'static Action<T>, coord: (u8, u8), delay: u16, ) -> CustomEvent<T> { assert!(self.waiting.is_none()); use Action::*; match action { NoOp | Trans => (), &HoldTap { timeout, hold, tap, config, .. } => { let waiting: WaitingState<T> = WaitingState { coord, timeout, delay, hold, tap, config, }; self.waiting = Some(waiting); } &KeyCode(keycode) => { let _ = self.states.push(NormalKey { coord, keycode }); } &MultipleKeyCodes(v) => { for &keycode in v { let _ = self.states.push(NormalKey { coord, keycode }); } } &MultipleActions(v) => { let mut custom = CustomEvent::NoEvent; for action in v { custom.update(self.do_action(action, coord, delay)); } return custom; } Sequence { events } => { self.active_sequences.push_back(SequenceState { cur_event: None, delay: 0, tapped: None, remaining_events: events, }); } CancelSequences => { // Clear any and all running sequences then clean up any leftover FakeKey events self.active_sequences.clear(); for fake_key in self.states.clone().iter() { match *fake_key { FakeKey { keycode } => { self.states = self .states .iter() .filter_map(|s| s.seq_release(keycode)) .collect(); } _ => {} } } } &Layer(value) => { let _ = self.states.push(LayerModifier { value, coord }); } DefaultLayer(value) => { self.set_default_layer(*value); } Custom(value) => { if self.states.push(State::Custom { value, coord }).is_ok() { return CustomEvent::Press(value); } } } CustomEvent::NoEvent } /// Obtain the index of the current active layer fn current_layer(&self) -> usize { self.states .iter() .rev() .filter_map(State::get_layer) .next() .unwrap_or(self.default_layer) } /// Sets the default layer for the layout pub fn set_default_layer(&mut self, value: usize) { if value < self.layers.len() { self.default_layer = value } } } #[cfg(test)] mod test { extern crate std; use super::{Event::*, Layers, Layout, *}; use crate::action::Action::*; use crate::action::HoldTapConfig; use crate::action::SequenceEvent; use crate::action::{k, l, m}; use crate::key_code::KeyCode; use crate::key_code::KeyCode::*; use std::collections::BTreeSet; #[track_caller] fn assert_keys(expected: &[KeyCode], iter: impl Iterator<Item = KeyCode>) { let expected: BTreeSet<_> = expected.iter().copied().collect(); let tested = iter.collect(); assert_eq!(expected, tested); } #[test] fn basic_hold_tap() { static LAYERS: Layers = &[ &[&[ HoldTap { timeout: 200, hold: &l(1), tap: &k(Space), config: HoldTapConfig::Default, tap_hold_interval: 0, }, HoldTap { timeout: 200, hold: &k(LCtrl), tap: &k(Enter), config: HoldTapConfig::Default, tap_hold_interval: 0, }, ]], &[&[Trans, m(&[LCtrl, Enter])]], ]; let mut layout = Layout::new(LAYERS); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); layout.event(Press(0, 1)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); layout.event(Press(0, 0)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); layout.event(Release(0, 0)); for _ in 0..197 { assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); } assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[LCtrl], layout.keycodes()); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[LCtrl], layout.keycodes()); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[LCtrl, Space], layout.keycodes()); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[LCtrl], layout.keycodes()); layout.event(Release(0, 1)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); } #[test] fn hold_tap_interleaved_timeout() { static LAYERS: Layers = &[&[&[ HoldTap { timeout: 200, hold: &k(LAlt), tap: &k(Space), config: HoldTapConfig::Default, tap_hold_interval: 0, }, HoldTap { timeout: 20, hold: &k(LCtrl), tap: &k(Enter), config: HoldTapConfig::Default, tap_hold_interval: 0, }, ]]]; let mut layout = Layout::new(LAYERS); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); layout.event(Press(0, 0)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); layout.event(Press(0, 1)); for _ in 0..15 { assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); } layout.event(Release(0, 0)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[Space], layout.keycodes()); for _ in 0..10 { assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[Space], layout.keycodes()); } layout.event(Release(0, 1)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[Space, LCtrl], layout.keycodes()); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[LCtrl], layout.keycodes()); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); } #[test] fn hold_on_press() { static LAYERS: Layers = &[&[&[ HoldTap { timeout: 200, hold: &k(LAlt), tap: &k(Space), config: HoldTapConfig::HoldOnOtherKeyPress, tap_hold_interval: 0, }, k(Enter), ]]]; let mut layout = Layout::new(LAYERS); // Press another key before timeout assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); layout.event(Press(0, 0)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); layout.event(Press(0, 1)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[LAlt], layout.keycodes()); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[LAlt, Enter], layout.keycodes()); layout.event(Release(0, 0)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[Enter], layout.keycodes()); layout.event(Release(0, 1)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); // Press another key after timeout assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); layout.event(Press(0, 0)); for _ in 0..200 { assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); } assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[LAlt], layout.keycodes()); layout.event(Press(0, 1)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[LAlt, Enter], layout.keycodes()); layout.event(Release(0, 0)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[Enter], layout.keycodes()); layout.event(Release(0, 1)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); } #[test] fn permissive_hold() { static LAYERS: Layers = &[&[&[ HoldTap { timeout: 200, hold: &k(LAlt), tap: &k(Space), config: HoldTapConfig::PermissiveHold, tap_hold_interval: 0, }, k(Enter), ]]]; let mut layout = Layout::new(LAYERS); // Press and release another key before timeout assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); layout.event(Press(0, 0)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); layout.event(Press(0, 1)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); layout.event(Release(0, 1)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[LAlt], layout.keycodes()); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[LAlt, Enter], layout.keycodes()); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[LAlt], layout.keycodes()); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[LAlt], layout.keycodes()); layout.event(Release(0, 0)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); } #[test] fn multiple_actions() { static LAYERS: Layers = &[ &[&[MultipleActions(&[l(1), k(LShift)]), k(F)]], &[&[Trans, k(E)]], ]; let mut layout = Layout::new(LAYERS); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); layout.event(Press(0, 0)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[LShift], layout.keycodes()); layout.event(Press(0, 1)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[LShift, E], layout.keycodes()); layout.event(Release(0, 1)); layout.event(Release(0, 0)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[LShift], layout.keycodes()); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); } #[test] fn custom() { static LAYERS: Layers<u8> = &[&[&[Action::Custom(42)]]]; let mut layout = Layout::new(LAYERS); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); // Custom event layout.event(Press(0, 0)); assert_eq!(CustomEvent::Press(&42), layout.tick()); assert_keys(&[], layout.keycodes()); // nothing more assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); // release custom layout.event(Release(0, 0)); assert_eq!(CustomEvent::Release(&42), layout.tick()); assert_keys(&[], layout.keycodes()); } #[test] fn multiple_layers() { static LAYERS: Layers = &[ &[&[l(1), l(2)]], &[&[k(A), l(3)]], &[&[l(0), k(B)]], &[&[k(C), k(D)]], ]; let mut layout = Layout::new(LAYERS); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_eq!(0, layout.current_layer()); assert_keys(&[], layout.keycodes()); // press L1 layout.event(Press(0, 0)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_eq!(1, layout.current_layer()); assert_keys(&[], layout.keycodes()); // press L3 on L1 layout.event(Press(0, 1)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_eq!(3, layout.current_layer()); assert_keys(&[], layout.keycodes()); // release L1, still on l3 layout.event(Release(0, 0)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_eq!(3, layout.current_layer()); assert_keys(&[], layout.keycodes()); // press and release C on L3 layout.event(Press(0, 0)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[C], layout.keycodes()); layout.event(Release(0, 0)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_keys(&[], layout.keycodes()); // release L3, back to L0 layout.event(Release(0, 1)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_eq!(0, layout.current_layer()); assert_keys(&[], layout.keycodes()); // back to empty, going to L2 layout.event(Press(0, 1)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_eq!(2, layout.current_layer()); assert_keys(&[], layout.keycodes()); // and press the L0 key on L2 layout.event(Press(0, 0)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_eq!(0, layout.current_layer()); assert_keys(&[], layout.keycodes()); // release the L0, back to L2 layout.event(Release(0, 0)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_eq!(2, layout.current_layer()); assert_keys(&[], layout.keycodes()); // release the L2, back to L0 layout.event(Release(0, 1)); assert_eq!(CustomEvent::NoEvent, layout.tick()); assert_eq!(0, layout.current_layer()); assert_keys(&[], layout.keycodes()); } }
36.011198
140
0.497823
03f29a142eb7372ddee905e45db7fb114990cd7b
7,925
use crate::color::reset_display; use crate::git::{Git, GitStatus, GitStatusItem, GitStatusType}; use crate::Config; use crate::TermBuffer; use crossterm::{ event::{self, Event, KeyCode, KeyEvent, KeyModifiers}, style::{style, Color}, }; use std::iter; #[derive(Debug)] pub struct FilesPrompt<'a> { config: &'a Config, checked: Vec<bool>, focused_index: u16, options: GitStatus, git: &'a Git, } pub enum FilesPromptResult { Files(Vec<String>), Escape, Terminate, } impl<'a> FilesPrompt<'a> { pub fn new(config: &'a Config, git: &'a Git, options: GitStatus) -> Self { FilesPrompt { config, checked: (0..options.len()).map(|_| false).collect(), focused_index: 0, options, git, } } pub fn run(mut self) -> FilesPromptResult { let mut buffer = TermBuffer::new(); let figlet = self .config .get_figlet() .expect("Ensure figlet_file points to a valid file, or remove it."); let mut first_iteration = true; loop { let event = if first_iteration { first_iteration = false; None } else { match event::read() { Ok(Event::Key(KeyEvent { code, modifiers })) => Some(( code, modifiers.contains(KeyModifiers::CONTROL), modifiers.contains(KeyModifiers::SHIFT), modifiers.contains(KeyModifiers::ALT), )), _ => continue, } }; match event { Some((KeyCode::Char('c'), true, false, false)) => { return FilesPromptResult::Terminate; } Some((KeyCode::Char(' '), false, _, false)) => { let index = self.focused_index as usize; if index == 0 { let set_to = !self.checked.iter().all(|&x| x); for item in self.checked.iter_mut() { *item = set_to; } } else { self.checked[index - 1] = !self.checked[index - 1]; } } Some((KeyCode::Char('d'), _, _, _)) => { let index = self.focused_index as usize; if index == 0 { let files: Vec<String> = vec![]; let _r = self.git.diff_less(files); } else { let option = self .options .iter() .nth(index - 1) .expect("diff should match a file"); if option.is_new() { let _r = self.git.less(option.file_name()); } else { let files = vec![option.file_name().to_string()]; let _r = self.git.diff_less(files); } } } Some((KeyCode::Enter, _, _, _)) => { let selected: Vec<String> = self .options .iter() .enumerate() .filter_map(|(i, file)| Some(file).filter(|_| self.checked[i])) .map(Into::into) .collect(); if !selected.is_empty() { return FilesPromptResult::Files(selected); } } Some((KeyCode::Esc, _, _, _)) => { return FilesPromptResult::Escape; } Some((KeyCode::Up, _, _, true)) => { self.focused_index = 0; } Some((KeyCode::Up, _, _, false)) => { self.focused_index = match self.focused_index { 0 => 0, x => x.saturating_sub(1), }; } Some((KeyCode::Down, _, _, true)) => { let total = self.options.len() as u16 + 1; self.focused_index += total.saturating_sub(1); } Some((KeyCode::Down, _, _, false)) => { let total = self.options.len() as u16 + 1; self.focused_index += 1; if self.focused_index >= total { self.focused_index = total.saturating_sub(1); } } None => {} _ => continue, }; let mut header = figlet.create_vec(); figlet.write_to_buf_color("<glint>", header.as_mut_slice(), |s| { style(s).with(Color::Magenta).to_string() }); for line in header { buffer.push_line(line); } let prompt_pre = "Toggle files to commit (with <space>, or tap 'd' for diff):"; let underscores = "-".repeat(prompt_pre.len()); buffer.push_line(""); buffer.push_line(prompt_pre); buffer.push_line(format!("{}{}", underscores, reset_display())); let y_offset = buffer.lines() + self.focused_index; let focused_color = Color::Blue; let default_color = Color::Reset; let status_untracked = style('+').with(Color::Rgb { r: 96, g: 218, b: 177, }); let status_modified = style('•').with(Color::Rgb { r: 96, g: 112, b: 218, }); let status_deleted = style('-').with(Color::Rgb { r: 218, g: 96, b: 118, }); let status_none = style(' '); // Padded limit (never overflows by 1 item) let total = self.options.len(); let max = 15; let take = if total > max { max - 3 } else { total }; for (i, git_status_item) in iter::once(&GitStatusItem::new("<all>".to_owned())) .chain(self.options.iter().map(|item| item)) .enumerate() .take(take + 1) { let line_color = if i as u16 == self.focused_index { focused_color } else { default_color }; let checked = if i == 0 { self.checked.iter().all(|&x| x) } else { self.checked[i - 1] }; let prefix = style(if checked { '☑' } else { '□' }).with(line_color); let file_status = match *git_status_item.status() { GitStatusType::Untracked => &status_untracked, GitStatusType::Modified => &status_modified, GitStatusType::Deleted => &status_deleted, _ => &status_none, }; let file_name = style(git_status_item.file_name()).with(line_color); let line = format!( "{} {} {}{}", prefix, file_status, file_name, reset_display(), ); buffer.push_line(line); } if take < total { let diff = total - take; buffer.push_line(format!("and {} more", diff)); } buffer.set_next_cursor((0, y_offset)); buffer.render_frame(); buffer.flush(); } } }
34.307359
91
0.41224
01e77e5aa411f7398b0c5c2938f9eb51ad92d9ba
918
//! Helper functions to access Horizon headers. use std::str::FromStr; pub use hyper::HeaderMap; /// Returns the remaining requests quota in the current window. pub fn rate_limit_remaining(headers: &HeaderMap) -> Option<u32> { headers .get("X-Ratelimit-Remaining") .map(|value| u32::from_str(value.to_str().unwrap_or("")).ok()) .unwrap_or(None) } /// Returns the requests quota in the time window. pub fn rate_limit_limit(headers: &HeaderMap) -> Option<u32> { headers .get("X-Ratelimit-Limit") .map(|value| u32::from_str(value.to_str().unwrap_or("")).ok()) .unwrap_or(None) } /// Returns the time remaining in the current window, specified in seconds. pub fn rate_limit_reset(headers: &HeaderMap) -> Option<u32> { headers .get("X-Ratelimit-Reset") .map(|value| u32::from_str(value.to_str().unwrap_or("")).ok()) .unwrap_or(None) }
31.655172
75
0.656863
b92a708dae3a0e0d1c37e4208bcd8723a1b7bcc6
8,352
use super::*; use std::cell::RefCell; use std::collections::HashSet; use std::fmt; use std::ops::Deref; use std::rc::Rc; /// A readonly [`Signal`]. /// /// Returned by functions that provide a handle to access state. /// Use [`Signal::handle`] or [`Signal::into_handle`] to retrieve a handle from a [`Signal`]. pub struct StateHandle<T: 'static>(Rc<RefCell<SignalInner<T>>>); impl<T: 'static> StateHandle<T> { /// Get the current value of the state. pub fn get(&self) -> Rc<T> { // If inside an effect, add this signal to dependency list. // If running inside a destructor, do nothing. let _ = CONTEXTS.try_with(|contexts| { if let Some(last_context) = contexts.borrow().last() { let signal = Rc::downgrade(&self.0); last_context .upgrade() .expect("Running should be valid while inside reactive scope") .borrow_mut() .as_mut() .unwrap() .dependencies .insert(Dependency(signal)); } }); self.get_untracked() } /// Get the current value of the state, without tracking this as a dependency if inside a /// reactive context. /// /// # Example /// /// ``` /// use maple_core::prelude::*; /// /// let state = Signal::new(1); /// /// let double = create_memo({ /// let state = state.clone(); /// move || *state.get_untracked() * 2 /// }); /// /// assert_eq!(*double.get(), 2); /// /// state.set(2); /// // double value should still be old value because state was untracked /// assert_eq!(*double.get(), 2); /// ``` pub fn get_untracked(&self) -> Rc<T> { Rc::clone(&self.0.borrow().inner) } } impl<T: 'static> Clone for StateHandle<T> { fn clone(&self) -> Self { Self(Rc::clone(&self.0)) } } impl<T: fmt::Debug> fmt::Debug for StateHandle<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("StateHandle") .field(&self.get_untracked()) .finish() } } #[cfg(feature = "serde")] impl<T: serde::Serialize> serde::Serialize for StateHandle<T> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.get_untracked().as_ref().serialize(serializer) } } #[cfg(feature = "serde")] impl<'de, T: serde::Deserialize<'de>> serde::Deserialize<'de> for StateHandle<T> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { Ok(Signal::new(T::deserialize(deserializer)?).handle()) } } /// State that can be set. /// /// # Example /// ``` /// use maple_core::prelude::*; /// /// let state = Signal::new(0); /// assert_eq!(*state.get(), 0); /// /// state.set(1); /// assert_eq!(*state.get(), 1); /// ``` pub struct Signal<T: 'static> { handle: StateHandle<T>, } impl<T: 'static> Signal<T> { /// Creates a new signal with the given value. /// /// # Example /// ``` /// # use maple_core::prelude::*; /// let state = Signal::new(0); /// # assert_eq!(*state.get(), 0); /// ``` pub fn new(initial: T) -> Self { Self { handle: StateHandle(Rc::new(RefCell::new(SignalInner::new(initial)))), } } /// Set the current value of the state. /// /// This will notify and update any effects and memos that depend on this value. /// /// # Example /// ``` /// # use maple_core::prelude::*; /// /// let state = Signal::new(0); /// assert_eq!(*state.get(), 0); /// /// state.set(1); /// assert_eq!(*state.get(), 1); /// ``` pub fn set(&self, new_value: T) { self.handle.0.borrow_mut().update(new_value); self.trigger_subscribers(); } /// Get the [`StateHandle`] associated with this signal. /// /// This is a shortcut for `(*signal).clone()`. pub fn handle(&self) -> StateHandle<T> { self.handle.clone() } /// Consumes this signal and returns its underlying [`StateHandle`]. pub fn into_handle(self) -> StateHandle<T> { self.handle } /// Calls all the subscribers without modifying the state. /// This can be useful when using patterns such as inner mutability where the state updated will /// not be automatically triggered. In the general case, however, it is preferable to use /// [`Signal::set`] instead. pub fn trigger_subscribers(&self) { // Clone subscribers to prevent modifying list when calling callbacks. let subscribers = self.handle.0.borrow().subscribers.clone(); for subscriber in subscribers { // subscriber might have already been destroyed in the case of nested effects if let Some(callback) = subscriber.try_callback() { callback() } } } } impl<T: 'static> Deref for Signal<T> { type Target = StateHandle<T>; fn deref(&self) -> &Self::Target { &self.handle } } impl<T: 'static> Clone for Signal<T> { fn clone(&self) -> Self { Self { handle: self.handle.clone(), } } } impl<T: PartialEq> PartialEq for Signal<T> { fn eq(&self, other: &Signal<T>) -> bool { self.get_untracked().eq(&other.get_untracked()) } } impl<T: fmt::Debug> fmt::Debug for Signal<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("Signal") .field(&self.get_untracked()) .finish() } } #[cfg(feature = "serde")] impl<T: serde::Serialize> serde::Serialize for Signal<T> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.get_untracked().as_ref().serialize(serializer) } } #[cfg(feature = "serde")] impl<'de, T: serde::Deserialize<'de>> serde::Deserialize<'de> for Signal<T> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { Ok(Signal::new(T::deserialize(deserializer)?)) } } pub(super) struct SignalInner<T> { inner: Rc<T>, subscribers: HashSet<Callback>, } impl<T> SignalInner<T> { fn new(value: T) -> Self { Self { inner: Rc::new(value), subscribers: HashSet::new(), } } /// Adds a handler to the subscriber list. If the handler is already a subscriber, does nothing. fn subscribe(&mut self, handler: Callback) { self.subscribers.insert(handler); } /// Removes a handler from the subscriber list. If the handler is not a subscriber, does /// nothing. fn unsubscribe(&mut self, handler: &Callback) { self.subscribers.remove(handler); } /// Updates the inner value. This does **NOT** call the subscribers. /// You will have to do so manually with `trigger_subscribers`. fn update(&mut self, new_value: T) { self.inner = Rc::new(new_value); } } /// Trait for any [`SignalInner`], regardless of type param `T`. pub(super) trait AnySignalInner { /// Wrapper around [`SignalInner::subscribe`]. fn subscribe(&self, handler: Callback); /// Wrapper around [`SignalInner::unsubscribe`]. fn unsubscribe(&self, handler: &Callback); } impl<T> AnySignalInner for RefCell<SignalInner<T>> { fn subscribe(&self, handler: Callback) { self.borrow_mut().subscribe(handler); } fn unsubscribe(&self, handler: &Callback) { self.borrow_mut().unsubscribe(handler); } } #[cfg(test)] mod tests { use super::*; #[test] fn signals() { let state = Signal::new(0); assert_eq!(*state.get(), 0); state.set(1); assert_eq!(*state.get(), 1); } #[test] fn signal_composition() { let state = Signal::new(0); let double = || *state.get() * 2; assert_eq!(double(), 0); state.set(1); assert_eq!(double(), 2); } #[test] fn state_handle() { let state = Signal::new(0); let readonly = state.handle(); assert_eq!(*readonly.get(), 0); state.set(1); assert_eq!(*readonly.get(), 1); } }
26.769231
100
0.563338
0edb7885d941625bc7d4782b3c809f3bde43cf79
3,929
// AUTOGENERATED FROM index-windows-1252.txt, ORIGINAL COMMENT FOLLOWS: // // Any copyright is dedicated to the Public Domain. // http://creativecommons.org/publicdomain/zero/1.0/ // // For details on index-windows-1252.txt see the Encoding Standard // http://encoding.spec.whatwg.org/ static FORWARD_TABLE: &'static [u16] = &[ 8364, 129, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338, 141, 381, 143, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250, 339, 157, 382, 376, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, ]; #[inline] pub fn forward(code: u8) -> u16 { FORWARD_TABLE[(code - 0x80) as uint] } static BACKWARD_TABLE_LOWER: &'static [u8] = &[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 129, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 141, 0, 143, 144, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 157, 0, 0, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 140, 156, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 138, 154, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 159, 0, 0, 0, 0, 142, 158, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 131, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 136, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 152, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 150, 151, 0, 0, 0, 145, 146, 130, 0, 147, 148, 132, 0, 134, 135, 149, 0, 0, 0, 133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 137, 0, 0, 0, 0, 0, 0, 0, 0, 139, 155, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 153, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; static BACKWARD_TABLE_UPPER: &'static [u16] = &[ 0, 0, 0, 0, 32, 64, 96, 128, 0, 0, 160, 192, 224, 0, 0, 0, 0, 0, 0, 0, 0, 0, 256, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 288, 320, 0, 0, 0, 352, 0, 0, 0, 384, ]; #[inline] pub fn backward(code: u32) -> u8 { let offset = (code >> 5) as uint; let offset = if offset < 266 {BACKWARD_TABLE_UPPER[offset] as uint} else {0}; BACKWARD_TABLE_LOWER[offset + ((code & 31) as uint)] } #[cfg(test)] single_byte_tests!()
53.821918
81
0.482057
50b4b07e2e76f036b36af78ee2152b5df3d00bee
6,815
extern crate gotham; extern crate handlebars_gotham as hbs; extern crate hyper; extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; #[macro_use] extern crate maplit; extern crate mime; use gotham::state::State; use gotham::http::response::create_response; use gotham::handler::{NewHandlerService, NewHandler}; use gotham::middleware::pipeline::new_pipeline; use gotham::router::Router; use gotham::router::route::{Extractors, Route, RouteImpl, Delegation}; use gotham::router::route::dispatch::{new_pipeline_set, finalize_pipeline_set, PipelineSet, PipelineHandleChain, DispatcherImpl}; use gotham::router::route::matcher::MethodOnlyRouteMatcher; use gotham::router::request::path::NoopPathExtractor; use gotham::router::request::query_string::NoopQueryStringExtractor; use gotham::router::response::finalizer::ResponseFinalizerBuilder; use gotham::router::tree::TreeBuilder; use gotham::router::tree::node::{NodeBuilder, SegmentType}; use hbs::{Template, HandlebarsEngine, DirectorySource, MemorySource}; use hbs::handlebars::{Handlebars, RenderContext, RenderError, Helper, to_json}; use hyper::server::Http; use hyper::{Method, Request, Response, StatusCode}; use serde_json::value::{Value, Map}; #[derive(Serialize, Debug)] pub struct Team { name: String, pts: u16, } pub fn make_data() -> Map<String, Value> { let mut data = Map::new(); data.insert("year".to_string(), to_json(&"2017".to_owned())); let teams = vec![ Team { name: "Jiangsu Sainty".to_string(), pts: 43u16, }, Team { name: "Beijing Guoan".to_string(), pts: 27u16, }, Team { name: "Guangzhou Evergrand".to_string(), pts: 22u16, }, Team { name: "Shandong Luneng".to_string(), pts: 12u16, }, ]; data.insert("teams".to_string(), to_json(&teams)); data.insert("engine".to_string(), to_json(&"serde_json".to_owned())); data } /// the handlers fn index(mut state: State, _req: Request) -> (State, Response) { state.put(Template::new("some/path/hello", make_data())); let res = create_response(&state, StatusCode::Ok, None); (state, res) } fn memory(mut state: State, _req: Request) -> (State, Response) { state.put(Template::new("memory", make_data())); let res = create_response(&state, StatusCode::Ok, None); (state, res) } fn temp(mut state: State, _req: Request) -> (State, Response) { state.put(Template::with( include_str!("templates/some/path/hello.hbs"), make_data(), )); let res = create_response(&state, StatusCode::Ok, None); (state, res) } fn plain(state: State, _req: Request) -> (State, Response) { let res = create_response( &state, StatusCode::Ok, Some(("It works".as_bytes().to_owned(), mime::TEXT_PLAIN)), ); (state, res) } fn main() { let mem_templates = btreemap! { "memory".to_owned() => include_str!("templates/some/path/hello.hbs").to_owned() }; let hbse = HandlebarsEngine::new(vec![ Box::new( DirectorySource::new("./examples/templates/", ".hbs") ), Box::new(MemorySource(mem_templates)), ]); // load templates from all registered sources if let Err(r) = hbse.reload() { panic!("{}", r); } hbse.handlebars_mut().register_helper( "some_helper", Box::new(|_: &Helper, _: &Handlebars, _: &mut RenderContext| -> Result<(), RenderError> { Ok(()) }), ); // -________________________- start let mut tree_builder = TreeBuilder::new(); let ps_builder = new_pipeline_set(); let (ps_builder, global) = ps_builder.add(new_pipeline().add(hbse).build()); let ps = finalize_pipeline_set(ps_builder); tree_builder.add_route(static_route( vec![Method::Get], || Ok(index), (global, ()), ps.clone(), )); let mut memory_handler = NodeBuilder::new("memory", SegmentType::Static); memory_handler.add_route(static_route( vec![Method::Get], || Ok(memory), (global, ()), ps.clone(), )); tree_builder.add_child(memory_handler); let mut temp_handler = NodeBuilder::new("temp", SegmentType::Static); temp_handler.add_route(static_route( vec![Method::Get], || Ok(temp), (global, ()), ps.clone(), )); tree_builder.add_child(temp_handler); let mut plain_handler = NodeBuilder::new("plain", SegmentType::Static); plain_handler.add_route(static_route( vec![Method::Get], || Ok(plain), (global, ()), ps.clone(), )); tree_builder.add_child(plain_handler); let tree = tree_builder.finalize(); let response_finalizer_builder = ResponseFinalizerBuilder::new(); let response_finalizer = response_finalizer_builder.finalize(); let router = Router::new(tree, response_finalizer); // -____________________________- end let addr = "127.0.0.1:7878".parse().unwrap(); let server = Http::new() .bind(&addr, NewHandlerService::new(router)) .unwrap(); println!("Listening on http://{}", server.local_addr().unwrap()); server.run().unwrap(); } // router copied from gotham example fn static_route<NH, P, C>( methods: Vec<Method>, new_handler: NH, active_pipelines: C, ps: PipelineSet<P>, ) -> Box<Route + Send + Sync> where NH: NewHandler + 'static, C: PipelineHandleChain<P> + Send + Sync + 'static, P: Send + Sync + 'static, { // Requests must have used the specified method(s) in order for this Route to match. // // You could define your on RouteMatcher of course.. perhaps you'd like to only match on // requests that are made using the GET method and send a User-Agent header for a particular // version of browser you'd like to make fun of.... let matcher = MethodOnlyRouteMatcher::new(methods); // For Requests that match this Route we'll dispatch them to new_handler via the pipelines // defined in active_pipelines. // // n.b. We also specify the set of all known pipelines in the application so the dispatcher can // resolve the pipeline references provided in active_pipelines. For this application that is // only the global pipeline. let dispatcher = DispatcherImpl::new(new_handler, active_pipelines, ps); let extractors: Extractors<NoopPathExtractor, NoopQueryStringExtractor> = Extractors::new(); let route = RouteImpl::new( matcher, Box::new(dispatcher), extractors, Delegation::Internal, ); Box::new(route) } //
29.890351
99
0.634629
64d21a5e0d7f09e1b2fe55ac118f3a4113f16f04
1,194
// ================================================================= // // * WARNING * // // This file is generated! // // Changes made to this file will be overwritten. If changes are // required to the generated code, the service_crategen project // must be updated to generate the changes. // // ================================================================= #![doc(html_logo_url = "https://raw.githubusercontent.com/rusoto/rusoto/master/assets/logo-square.png")] //! <p><fullname>Amazon CloudFront</fullname> <p>This is the <i>Amazon CloudFront API Reference</i>. This guide is for developers who need detailed information about CloudFront API actions, data types, and errors. For detailed information about CloudFront features, see the <i>Amazon CloudFront Developer Guide</i>.</p></p> //! //! If you're using the service, you're probably looking for [CloudFrontClient](struct.CloudFrontClient.html) and [CloudFront](trait.CloudFront.html). extern crate futures; extern crate hyper; extern crate rusoto_core; extern crate tokio_core; extern crate xml; mod generated; mod custom; pub use generated::*; pub use custom::*;
38.516129
323
0.628978
114e66b9285ee20dc31ef99f515ad6b3a7e6985f
6,188
// Copyright 2015 The Ramp Developers // // 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. #![allow(improper_ctypes)] use crate::ll::limb::Limb; use crate::ll::limb_ptr::{Limbs, LimbsMut}; use super::{copy_rest, same_or_separate}; #[allow(dead_code)] unsafe fn add_n_generic(mut wp: LimbsMut, mut xp: Limbs, mut yp: Limbs, mut n: i32) -> Limb { let mut carry = Limb(0); loop { let xl = *xp; let yl = *yp; let (sl, c1) = xl.add_overflow(yl); let (rl, c2) = sl.add_overflow(carry); carry = if c1 || c2 { Limb(1) } else { Limb(0) }; *wp = rl; n -= 1; if n == 0 { break; } wp = wp.offset(1); xp = xp.offset(1); yp = yp.offset(1); } carry } /** * Adds the `n` least signficant limbs of `xp` and `yp`, storing the result in {wp, n}. * If there was a carry, it is returned. */ #[inline] #[cfg(asm)] pub unsafe fn add_n(mut wp: LimbsMut, xp: Limbs, yp: Limbs, n: i32) -> Limb { #[cfg(all(not(feature="fallbacks"),target_arch="x86_64"))] extern "C" { fn ramp_add_n(wp: *mut Limb, xp: *const Limb, yp: *const Limb, n: i32) -> Limb; } debug_assert!(n >= 1); debug_assert!(same_or_separate(wp, n, xp, n)); debug_assert!(same_or_separate(wp, n, yp, n)); return ramp_add_n(&mut *wp, &*xp, &*yp, n); } /** * Adds the `n` least signficant limbs of `xp` and `yp`, storing the result in {wp, n}. * If there was a carry, it is returned. */ #[cfg(any(feature="fallbacks",not(asm)))] #[inline] pub unsafe fn add_n(wp: LimbsMut, xp: Limbs, yp: Limbs, n: i32) -> Limb { debug_assert!(n >= 1); debug_assert!(same_or_separate(wp, n, xp, n)); debug_assert!(same_or_separate(wp, n, yp, n)); add_n_generic(wp, xp, yp, n) } #[allow(dead_code)] unsafe fn sub_n_generic(mut wp: LimbsMut, mut xp: Limbs, mut yp: Limbs, mut n: i32) -> Limb { let mut carry = Limb(0); debug_assert!(n >= 1); debug_assert!(same_or_separate(wp, n, xp, n)); debug_assert!(same_or_separate(wp, n, yp, n)); loop { let xl = *xp; let yl = *yp; let (sl, c1) = xl.sub_overflow(yl); let (rl, c2) = sl.sub_overflow(carry); carry = if c1 || c2 { Limb(1) } else { Limb(0) }; *wp = rl; n -= 1; if n == 0 { break; } wp = wp.offset(1); xp = xp.offset(1); yp = yp.offset(1); } carry } /** * Subtracts the `n` least signficant limbs of `yp` from `xp`, storing the result in {wp, n}. * If there was a borrow from a higher-limb (i.e., the result would be negative), it is returned. */ #[cfg(asm)] #[inline] pub unsafe fn sub_n(mut wp: LimbsMut, xp: Limbs, yp: Limbs, n: i32) -> Limb { extern "C" { fn ramp_sub_n(wp: *mut Limb, xp: *const Limb, yp: *const Limb, n: i32) -> Limb; } ramp_sub_n(&mut *wp, &*xp, &*yp, n) } /** * Subtracts the `n` least signficant limbs of `yp` from `xp`, storing the result in {wp, n}. * If there was a borrow from a higher-limb (i.e., the result would be negative), it is returned. */ #[cfg(not(asm))] #[inline] pub unsafe fn sub_n(wp: LimbsMut, xp: Limbs, yp: Limbs, n: i32) -> Limb { sub_n_generic(wp, xp, yp, n) } macro_rules! aors { ($op:ident, $lop:ident, $f:ident) => { #[inline] pub unsafe fn $op(wp: LimbsMut, xp: Limbs, xs: i32, yp: Limbs, ys: i32) -> Limb { debug_assert!(xs >= ys); debug_assert!(ys >= 0); let mut i = ys; let carry = $f(wp, xp, yp, ys); if carry == 1 { loop { if i >= xs { return Limb(1); } let (x, carry) = Limb::$lop(*xp.offset(i as isize), Limb(1)); *wp.offset(i as isize) = x; i += 1; if !carry { break; } } } if wp.as_const() != xp && i < xs { copy_rest(xp, wp, xs, i); } return Limb(0); } } } aors!(add, add_overflow, add_n); aors!(sub, sub_overflow, sub_n); macro_rules! aors_1 { ($op:ident, $f:ident) => { #[inline] pub unsafe fn $op(mut wp: LimbsMut, xp: Limbs, xs: i32, y: Limb) -> Limb { if xs > 0 { let (v, mut carry) = Limb::$f(*xp, y); *wp = v; let mut i = 1; while carry { if i >= xs { return Limb(1); } let (v, c) = Limb::$f(*xp.offset(i as isize), Limb(1)); carry = c; *wp.offset(i as isize) = v; i += 1; } } return Limb(0); } } } aors_1!(add_1, add_overflow); aors_1!(sub_1, sub_overflow); #[inline(always)] pub unsafe fn incr(mut ptr: LimbsMut, incr: Limb) { let (x, mut carry) = (*ptr).add_overflow(incr); *ptr = x; while carry { ptr = ptr.offset(1); let (x, c) = (*ptr).add_overflow(Limb(1)); *ptr = x; carry = c; } } #[inline(always)] pub unsafe fn decr(mut ptr: LimbsMut, decr: Limb) { let x = *ptr; *ptr = x - decr; if x < decr { loop { ptr = ptr.offset(1); let x = *ptr; *ptr = x - 1; if x != 0 { break; } } } }
26.55794
97
0.497091
0812a4c3a6e40b78e013412c31ba3fad21951250
2,100
use crate::utils::get_test_path; use cargo_tarpaulin::{ config::{Config, Mode}, errors::RunError, }; use cargo_tarpaulin::{launch_tarpaulin, run}; use std::env; #[test] fn error_if_build_script_fails() { let mut config = Config::default(); let test_dir = get_test_path("build_script_fail"); env::set_current_dir(&test_dir).unwrap(); config.manifest = test_dir; config.manifest.push("Cargo.toml"); config.set_clean(false); let result = launch_tarpaulin(&config, &None); assert!(result.is_err()); if let Err(RunError::Cargo(_)) = result { } else { panic!("Expected a Cargo error"); } } #[test] fn error_if_compilation_fails() { let mut config = Config::default(); let test_dir = get_test_path("compile_fail"); env::set_current_dir(&test_dir).unwrap(); config.manifest = test_dir; config.manifest.push("Cargo.toml"); config.set_clean(false); let result = launch_tarpaulin(&config, &None); assert!(result.is_err()); if let Err(RunError::TestCompile(_)) = result { } else { panic!("Expected a TestCompile error"); } } #[test] fn error_if_test_fails() { let mut config = Config::default(); let test_dir = get_test_path("failing_test"); env::set_current_dir(&test_dir).unwrap(); config.manifest = test_dir; config.manifest.push("Cargo.toml"); config.set_clean(false); let result = run(&[config]); assert!(result.is_err()); if let Err(RunError::TestFailed) = result { } else { panic!("Expected a TestCompile error"); } } #[test] fn issue_610() { let mut config = Config::default(); let test_dir = get_test_path("issue_610"); config.test_names.insert("foo".to_string()); env::set_current_dir(&test_dir).unwrap(); config.manifest = test_dir; config.manifest.push("Cargo.toml"); config.set_clean(false); let result = run(&[config.clone()]); assert!(result.is_ok()); config.test_names.clear(); config.command = Mode::Build; let result = run(&[config]); assert!(result.is_err()); }
25
54
0.647619
76a3d0d97d35ad363a1974555d4a19c9b5ec9811
1,000
// c:showBubbleSize use super::super::super::BooleanValue; use quick_xml::events::BytesStart; use quick_xml::Reader; use quick_xml::Writer; use reader::driver::*; use std::io::Cursor; use writer::driver::*; #[derive(Clone, Default, Debug)] pub struct ShowBubbleSize { val: BooleanValue, } impl ShowBubbleSize { pub fn get_val(&self) -> &bool { self.val.get_value() } pub fn set_val(&mut self, value: bool) -> &mut ShowBubbleSize { self.val.set_value(value); self } pub(crate) fn set_attributes<R: std::io::BufRead>( &mut self, _reader: &mut Reader<R>, e: &BytesStart, ) { self.val.set_value_string(get_attribute(e, b"val").unwrap()); } pub(crate) fn write_to(&self, writer: &mut Writer<Cursor<Vec<u8>>>) { // c:showBubbleSize write_start_tag( writer, "c:showBubbleSize", vec![("val", self.val.get_value_string())], true, ); } }
23.809524
73
0.589
5d55d2357c95ad3718c68129545d08354c009b02
123
pub mod deserialization; pub mod serialization; pub use deserialization::Deserializer; pub use serialization::Serializer;
20.5
38
0.829268
26066194aed4d45b05c57e04ebb032aae122605d
7,145
#[doc = "Register `MODE` reader"] pub struct R(crate::R<MODE_SPEC>); impl core::ops::Deref for R { type Target = crate::R<MODE_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<MODE_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<MODE_SPEC>) -> Self { R(reader) } } #[doc = "Register `MODE` writer"] pub struct W(crate::W<MODE_SPEC>); impl core::ops::Deref for W { type Target = crate::W<MODE_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<MODE_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<MODE_SPEC>) -> Self { W(writer) } } #[doc = "Radio data rate and modulation setting. The radio supports frequency-shift keying (FSK) modulation.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum MODE_A { #[doc = "0: 1 Mbps Nordic proprietary radio mode"] NRF_1MBIT = 0, #[doc = "1: 2 Mbps Nordic proprietary radio mode"] NRF_2MBIT = 1, #[doc = "3: 1 Mbps BLE"] BLE_1MBIT = 3, #[doc = "4: 2 Mbps BLE"] BLE_2MBIT = 4, #[doc = "5: Long range 125 kbps TX, 125 kbps and 500 kbps RX"] BLE_LR125KBIT = 5, #[doc = "6: Long range 500 kbps TX, 125 kbps and 500 kbps RX"] BLE_LR500KBIT = 6, #[doc = "15: IEEE 802.15.4-2006 250 kbps"] IEEE802154_250KBIT = 15, } impl From<MODE_A> for u8 { #[inline(always)] fn from(variant: MODE_A) -> Self { variant as _ } } #[doc = "Field `MODE` reader - Radio data rate and modulation setting. The radio supports frequency-shift keying (FSK) modulation."] pub struct MODE_R(crate::FieldReader<u8, MODE_A>); impl MODE_R { pub(crate) fn new(bits: u8) -> Self { MODE_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<MODE_A> { match self.bits { 0 => Some(MODE_A::NRF_1MBIT), 1 => Some(MODE_A::NRF_2MBIT), 3 => Some(MODE_A::BLE_1MBIT), 4 => Some(MODE_A::BLE_2MBIT), 5 => Some(MODE_A::BLE_LR125KBIT), 6 => Some(MODE_A::BLE_LR500KBIT), 15 => Some(MODE_A::IEEE802154_250KBIT), _ => None, } } #[doc = "Checks if the value of the field is `NRF_1MBIT`"] #[inline(always)] pub fn is_nrf_1mbit(&self) -> bool { **self == MODE_A::NRF_1MBIT } #[doc = "Checks if the value of the field is `NRF_2MBIT`"] #[inline(always)] pub fn is_nrf_2mbit(&self) -> bool { **self == MODE_A::NRF_2MBIT } #[doc = "Checks if the value of the field is `BLE_1MBIT`"] #[inline(always)] pub fn is_ble_1mbit(&self) -> bool { **self == MODE_A::BLE_1MBIT } #[doc = "Checks if the value of the field is `BLE_2MBIT`"] #[inline(always)] pub fn is_ble_2mbit(&self) -> bool { **self == MODE_A::BLE_2MBIT } #[doc = "Checks if the value of the field is `BLE_LR125KBIT`"] #[inline(always)] pub fn is_ble_lr125kbit(&self) -> bool { **self == MODE_A::BLE_LR125KBIT } #[doc = "Checks if the value of the field is `BLE_LR500KBIT`"] #[inline(always)] pub fn is_ble_lr500kbit(&self) -> bool { **self == MODE_A::BLE_LR500KBIT } #[doc = "Checks if the value of the field is `IEEE802154_250KBIT`"] #[inline(always)] pub fn is_ieee802154_250kbit(&self) -> bool { **self == MODE_A::IEEE802154_250KBIT } } impl core::ops::Deref for MODE_R { type Target = crate::FieldReader<u8, MODE_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `MODE` writer - Radio data rate and modulation setting. The radio supports frequency-shift keying (FSK) modulation."] pub struct MODE_W<'a> { w: &'a mut W, } impl<'a> MODE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MODE_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "1 Mbps Nordic proprietary radio mode"] #[inline(always)] pub fn nrf_1mbit(self) -> &'a mut W { self.variant(MODE_A::NRF_1MBIT) } #[doc = "2 Mbps Nordic proprietary radio mode"] #[inline(always)] pub fn nrf_2mbit(self) -> &'a mut W { self.variant(MODE_A::NRF_2MBIT) } #[doc = "1 Mbps BLE"] #[inline(always)] pub fn ble_1mbit(self) -> &'a mut W { self.variant(MODE_A::BLE_1MBIT) } #[doc = "2 Mbps BLE"] #[inline(always)] pub fn ble_2mbit(self) -> &'a mut W { self.variant(MODE_A::BLE_2MBIT) } #[doc = "Long range 125 kbps TX, 125 kbps and 500 kbps RX"] #[inline(always)] pub fn ble_lr125kbit(self) -> &'a mut W { self.variant(MODE_A::BLE_LR125KBIT) } #[doc = "Long range 500 kbps TX, 125 kbps and 500 kbps RX"] #[inline(always)] pub fn ble_lr500kbit(self) -> &'a mut W { self.variant(MODE_A::BLE_LR500KBIT) } #[doc = "IEEE 802.15.4-2006 250 kbps"] #[inline(always)] pub fn ieee802154_250kbit(self) -> &'a mut W { self.variant(MODE_A::IEEE802154_250KBIT) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | (value as u32 & 0x0f); self.w } } impl R { #[doc = "Bits 0:3 - Radio data rate and modulation setting. The radio supports frequency-shift keying (FSK) modulation."] #[inline(always)] pub fn mode(&self) -> MODE_R { MODE_R::new((self.bits & 0x0f) as u8) } } impl W { #[doc = "Bits 0:3 - Radio data rate and modulation setting. The radio supports frequency-shift keying (FSK) modulation."] #[inline(always)] pub fn mode(&mut self) -> MODE_W { MODE_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "Data rate and modulation\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mode](index.html) module"] pub struct MODE_SPEC; impl crate::RegisterSpec for MODE_SPEC { type Ux = u32; } #[doc = "`read()` method returns [mode::R](R) reader structure"] impl crate::Readable for MODE_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [mode::W](W) writer structure"] impl crate::Writable for MODE_SPEC { type Writer = W; } #[doc = "`reset()` method sets MODE to value 0"] impl crate::Resettable for MODE_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
32.926267
409
0.594122
87661b98a27b56d39edbd4cef8da6537bdd1128e
8,007
#![allow(unused_imports, non_camel_case_types)] use crate::model::Element::Element; use crate::model::Extension::Extension; use serde_json::json; use serde_json::value::Value; use std::borrow::Cow; /// Describes a required data item for evaluation in terms of the type of data, and /// optional code or date-based filters of the data. #[derive(Debug)] pub struct DataRequirement_Sort<'a> { pub(crate) value: Cow<'a, Value>, } impl DataRequirement_Sort<'_> { pub fn new(value: &Value) -> DataRequirement_Sort { DataRequirement_Sort { value: Cow::Borrowed(value), } } pub fn to_json(&self) -> Value { (*self.value).clone() } /// Extensions for direction pub fn _direction(&self) -> Option<Element> { if let Some(val) = self.value.get("_direction") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for path pub fn _path(&self) -> Option<Element> { if let Some(val) = self.value.get("_path") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// The direction of the sort, ascending or descending. pub fn direction(&self) -> Option<DataRequirement_SortDirection> { if let Some(Value::String(val)) = self.value.get("direction") { return Some(DataRequirement_SortDirection::from_string(&val).unwrap()); } return None; } /// May be used to represent additional information that is not part of the basic /// definition of the element. To make the use of extensions safe and manageable, /// there is a strict set of governance applied to the definition and use of /// extensions. Though any implementer can define an extension, there is a set of /// requirements that SHALL be met as part of the definition of the extension. pub fn extension(&self) -> Option<Vec<Extension>> { if let Some(Value::Array(val)) = self.value.get("extension") { return Some( val.into_iter() .map(|e| Extension { value: Cow::Borrowed(e), }) .collect::<Vec<_>>(), ); } return None; } /// Unique id for the element within a resource (for internal references). This may /// be any string value that does not contain spaces. pub fn id(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("id") { return Some(string); } return None; } /// May be used to represent additional information that is not part of the basic /// definition of the element and that modifies the understanding of the element in /// which it is contained and/or the understanding of the containing element's /// descendants. Usually modifier elements provide negation or qualification. To /// make the use of extensions safe and manageable, there is a strict set of /// governance applied to the definition and use of extensions. Though any /// implementer can define an extension, there is a set of requirements that SHALL /// be met as part of the definition of the extension. Applications processing a /// resource are required to check for modifier extensions. Modifier extensions /// SHALL NOT change the meaning of any elements on Resource or DomainResource /// (including cannot change the meaning of modifierExtension itself). pub fn modifier_extension(&self) -> Option<Vec<Extension>> { if let Some(Value::Array(val)) = self.value.get("modifierExtension") { return Some( val.into_iter() .map(|e| Extension { value: Cow::Borrowed(e), }) .collect::<Vec<_>>(), ); } return None; } /// The attribute of the sort. The specified path must be resolvable from the type /// of the required data. The path is allowed to contain qualifiers (.) to traverse /// sub-elements, as well as indexers ([x]) to traverse multiple-cardinality sub- /// elements. Note that the index must be an integer constant. pub fn path(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("path") { return Some(string); } return None; } pub fn validate(&self) -> bool { if let Some(_val) = self._direction() { if !_val.validate() { return false; } } if let Some(_val) = self._path() { if !_val.validate() { return false; } } if let Some(_val) = self.direction() {} if let Some(_val) = self.extension() { if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) { return false; } } if let Some(_val) = self.id() {} if let Some(_val) = self.modifier_extension() { if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) { return false; } } if let Some(_val) = self.path() {} return true; } } #[derive(Debug)] pub struct DataRequirement_SortBuilder { pub(crate) value: Value, } impl DataRequirement_SortBuilder { pub fn build(&self) -> DataRequirement_Sort { DataRequirement_Sort { value: Cow::Owned(self.value.clone()), } } pub fn with(existing: DataRequirement_Sort) -> DataRequirement_SortBuilder { DataRequirement_SortBuilder { value: (*existing.value).clone(), } } pub fn new() -> DataRequirement_SortBuilder { let mut __value: Value = json!({}); return DataRequirement_SortBuilder { value: __value }; } pub fn _direction<'a>(&'a mut self, val: Element) -> &'a mut DataRequirement_SortBuilder { self.value["_direction"] = json!(val.value); return self; } pub fn _path<'a>(&'a mut self, val: Element) -> &'a mut DataRequirement_SortBuilder { self.value["_path"] = json!(val.value); return self; } pub fn direction<'a>( &'a mut self, val: DataRequirement_SortDirection, ) -> &'a mut DataRequirement_SortBuilder { self.value["direction"] = json!(val.to_string()); return self; } pub fn extension<'a>(&'a mut self, val: Vec<Extension>) -> &'a mut DataRequirement_SortBuilder { self.value["extension"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } pub fn id<'a>(&'a mut self, val: &str) -> &'a mut DataRequirement_SortBuilder { self.value["id"] = json!(val); return self; } pub fn modifier_extension<'a>( &'a mut self, val: Vec<Extension>, ) -> &'a mut DataRequirement_SortBuilder { self.value["modifierExtension"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } pub fn path<'a>(&'a mut self, val: &str) -> &'a mut DataRequirement_SortBuilder { self.value["path"] = json!(val); return self; } } #[derive(Debug)] pub enum DataRequirement_SortDirection { Ascending, Descending, } impl DataRequirement_SortDirection { pub fn from_string(string: &str) -> Option<DataRequirement_SortDirection> { match string { "ascending" => Some(DataRequirement_SortDirection::Ascending), "descending" => Some(DataRequirement_SortDirection::Descending), _ => None, } } pub fn to_string(&self) -> String { match self { DataRequirement_SortDirection::Ascending => "ascending".to_string(), DataRequirement_SortDirection::Descending => "descending".to_string(), } } }
34.217949
100
0.587611